diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVEntityListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVEntityListener.java
index e741358..d5302d2 100644
--- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVEntityListener.java
+++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVEntityListener.java
@@ -1,152 +1,152 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Squid;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import java.util.List;
import java.util.logging.Level;
/**
* Multiverse's Entity {@link Listener}.
*/
public class MVEntityListener implements Listener {
private MultiverseCore plugin;
private MVWorldManager worldManager;
public MVEntityListener(MultiverseCore plugin) {
this.plugin = plugin;
this.worldManager = plugin.getMVWorldManager();
}
/**
* This method is called when an entity's food level goes higher or lower.
* @param event The Event that was fired.
*/
@EventHandler
public void foodLevelChange(FoodLevelChangeEvent event) {
if (event.isCancelled()) {
return;
}
if (event.getEntity() instanceof Player) {
Player p = (Player) event.getEntity();
MultiverseWorld w = this.plugin.getMVWorldManager().getMVWorld(p.getWorld().getName());
if (w != null && !w.getHunger()) {
// If the world has hunger set to false, do not let the level go down
if (event.getFoodLevel() < ((Player) event.getEntity()).getFoodLevel()) {
event.setCancelled(true);
}
}
}
}
/**
* This method is called when an entity's health goes up or down.
* @param event The Event that was fired.
*/
@EventHandler
public void entityRegainHealth(EntityRegainHealthEvent event) {
if (event.isCancelled()) {
return;
}
RegainReason reason = event.getRegainReason();
MultiverseWorld world = this.worldManager.getMVWorld(event.getEntity().getLocation().getWorld());
if (world != null && reason == RegainReason.REGEN && !world.getAutoHeal()) {
event.setCancelled(true);
}
}
/**
* Handle Animal/Monster Spawn settings, seems like a more concrete method than using CraftBukkit.
* @param event The event.
*/
@EventHandler
public void creatureSpawn(CreatureSpawnEvent event) {
// Check to see if the Creature is spawned by a plugin, we don't want to prevent this behaviour.
// TODO: Allow the egg thing to be a config param. Doubt this will be per world; seems silly.
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
return;
}
World world = event.getEntity().getWorld();
if (event.isCancelled())
return;
// Check if it's a world which we are meant to be managing.
if (!(this.worldManager.isMVWorld(world.getName())))
return;
EntityType type = event.getEntityType();
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
/**
* Handle people with non-standard animals: ie a patched craftbukkit.
*/
- if (type == null) {
+ if (type == null || type.getName() == null) {
this.plugin.log(Level.FINER, "Found a null typed creature.");
return;
}
/**
* Animal Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Animals || event.getEntity() instanceof Squid)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getAnimalList(), mvworld.canAnimalsSpawn(), type.getName().toUpperCase()));
}
/**
* Monster Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Monster || event.getEntity() instanceof Ghast || event.getEntity() instanceof Slime)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getMonsterList(), mvworld.canMonstersSpawn(), type.getName().toUpperCase()));
}
}
private static boolean shouldWeKillThisCreature(List<String> creatureList, boolean allowCreatureSpawning, String creature) {
if (creatureList.isEmpty() && allowCreatureSpawning) {
// 1. There are no exceptions and animals are allowed. Save it.
return false;
} else if (creatureList.isEmpty()) {
// 2. There are no exceptions and animals are NOT allowed. Kill it.
return true;
} else if (creatureList.contains(creature.toUpperCase()) && allowCreatureSpawning) {
// 3. There ARE exceptions and animals ARE allowed. Kill it.
return true;
} else if (!creatureList.contains(creature.toUpperCase()) && allowCreatureSpawning) {
// 4. There ARE exceptions and animals ARE NOT allowed. SAVE it.
return false;
} else if (creatureList.contains(creature.toUpperCase()) && !allowCreatureSpawning) {
// 5. No animals are allowed to be spawned, BUT this one can stay...
return false;
} else if (!creatureList.contains(creature.toUpperCase()) && !allowCreatureSpawning) {
// 6. Animals are NOT allowed to spawn, and this creature is not in the save list... KILL IT
return true;
} else {
// This code should NEVER execute. I just left the verbose conditions in right now.
throw new UnsupportedOperationException();
}
}
}
| true | true | public void creatureSpawn(CreatureSpawnEvent event) {
// Check to see if the Creature is spawned by a plugin, we don't want to prevent this behaviour.
// TODO: Allow the egg thing to be a config param. Doubt this will be per world; seems silly.
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
return;
}
World world = event.getEntity().getWorld();
if (event.isCancelled())
return;
// Check if it's a world which we are meant to be managing.
if (!(this.worldManager.isMVWorld(world.getName())))
return;
EntityType type = event.getEntityType();
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
/**
* Handle people with non-standard animals: ie a patched craftbukkit.
*/
if (type == null) {
this.plugin.log(Level.FINER, "Found a null typed creature.");
return;
}
/**
* Animal Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Animals || event.getEntity() instanceof Squid)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getAnimalList(), mvworld.canAnimalsSpawn(), type.getName().toUpperCase()));
}
/**
* Monster Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Monster || event.getEntity() instanceof Ghast || event.getEntity() instanceof Slime)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getMonsterList(), mvworld.canMonstersSpawn(), type.getName().toUpperCase()));
}
}
| public void creatureSpawn(CreatureSpawnEvent event) {
// Check to see if the Creature is spawned by a plugin, we don't want to prevent this behaviour.
// TODO: Allow the egg thing to be a config param. Doubt this will be per world; seems silly.
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
return;
}
World world = event.getEntity().getWorld();
if (event.isCancelled())
return;
// Check if it's a world which we are meant to be managing.
if (!(this.worldManager.isMVWorld(world.getName())))
return;
EntityType type = event.getEntityType();
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
/**
* Handle people with non-standard animals: ie a patched craftbukkit.
*/
if (type == null || type.getName() == null) {
this.plugin.log(Level.FINER, "Found a null typed creature.");
return;
}
/**
* Animal Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Animals || event.getEntity() instanceof Squid)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getAnimalList(), mvworld.canAnimalsSpawn(), type.getName().toUpperCase()));
}
/**
* Monster Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Monster || event.getEntity() instanceof Ghast || event.getEntity() instanceof Slime)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getMonsterList(), mvworld.canMonstersSpawn(), type.getName().toUpperCase()));
}
}
|
diff --git a/src/commons/grails/util/GrailsUtil.java b/src/commons/grails/util/GrailsUtil.java
index db1b5d3e7..b62aa987f 100644
--- a/src/commons/grails/util/GrailsUtil.java
+++ b/src/commons/grails/util/GrailsUtil.java
@@ -1,196 +1,198 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT c;pWARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grails.util;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.ApplicationAttributes;
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.exceptions.GrailsConfigurationException;
import org.codehaus.groovy.grails.support.MockResourceLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.util.Assert;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Manifest;
import java.util.jar.Attributes;
import java.io.IOException;
/**
*
* Grails utility methods for command line and GUI applications
*
* @author Graeme Rocher
* @since 0.2
*
* @version $Revision$
* First Created: 02-Jun-2006
* Last Updated: $Date$
*
*/
public class GrailsUtil {
private static final Log LOG = LogFactory.getLog(GrailsUtil.class);
private static final String GRAILS_IMPLEMENTATION_TITLE = "Grails";
private static final String GRAILS_VERSION;
static {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
Resource[] manifests = resolver.getResources("classpath*:META-INF/GRAILS-MANIFEST.MF");
Manifest grailsManifest = null;
for (int i = 0; i < manifests.length; i++) {
Resource r = manifests[i];
Manifest mf = new Manifest(r.getInputStream());
String implTitle = mf.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_TITLE);
if(!StringUtils.isBlank(implTitle) && implTitle.equals(GRAILS_IMPLEMENTATION_TITLE)) {
grailsManifest = mf;
break;
}
}
String version = null;
if(grailsManifest != null) {
version = grailsManifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
}
if(!StringUtils.isBlank(version)) {
GRAILS_VERSION = version;
}
else {
GRAILS_VERSION = null;
throw new GrailsConfigurationException("Unable to read Grails version from MANIFEST.MF. Are you sure it the grails-core jar is on the classpath? " );
}
} catch (IOException e) {
throw new GrailsConfigurationException("Unable to read Grails version from MANIFEST.MF. Are you sure it the grails-core jar is on the classpath? " + e.getMessage(), e);
}
}
private static final String PRODUCTION_ENV_SHORT_NAME = "prod";
private static final String DEVELOPMENT_ENVIRONMENT_SHORT_NAME = "dev";
private static final String TEST_ENVIRONMENT_SHORT_NAME = "test";
private static Map envNameMappings = new HashMap() {{
put(DEVELOPMENT_ENVIRONMENT_SHORT_NAME, GrailsApplication.ENV_DEVELOPMENT);
put(PRODUCTION_ENV_SHORT_NAME, GrailsApplication.ENV_PRODUCTION);
put(TEST_ENVIRONMENT_SHORT_NAME, GrailsApplication.ENV_TEST);
}};
public static ApplicationContext bootstrapGrailsFromClassPath() {
LOG.info("Loading Grails environment");
ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml");
DefaultGrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class);
GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent);
MockServletContext servletContext = new MockServletContext(new MockResourceLoader());
ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(servletContext);
servletContext.setAttribute( ApplicationAttributes.APPLICATION_CONTEXT, appCtx);
Assert.notNull(appCtx);
return appCtx;
}
/**
* Retrieves the current execution environment
*
* @return The environment Grails is executing under
*/
public static String getEnvironment() {
GrailsApplication app = ApplicationHolder.getApplication();
String envName = null;
if(app!=null) {
- envName = (String)app.getMetadata().get(GrailsApplication.ENVIRONMENT);
+ Map metadata = app.getMetadata();
+ if(metadata!=null)
+ envName = (String)metadata.get(GrailsApplication.ENVIRONMENT);
}
if(StringUtils.isBlank(envName))
envName = System.getProperty(GrailsApplication.ENVIRONMENT);
if(StringUtils.isBlank(envName)) {
// for now if no environment specified default to production
return GrailsApplication.ENV_PRODUCTION;
}
else {
if(envNameMappings.containsKey(envName)) {
return (String)envNameMappings.get(envName);
}
else {
return envName;
}
}
}
/**
* Retrieves whether the current execution environment is the development one
*
* @return True if it is the development environment
*/
public static boolean isDevelopmentEnv() {
return GrailsApplication.ENV_DEVELOPMENT.equals(GrailsUtil.getEnvironment());
}
public static String getGrailsVersion() {
return GRAILS_VERSION;
}
/**
* Logs warning message about deprecation of specified property or method of some class.
*
* @param clazz A class
* @param methodOrPropName Name of deprecated property or method
*/
public static void deprecated(Class clazz, String methodOrPropName ) {
deprecated(clazz, methodOrPropName, getGrailsVersion());
}
/**
* Logs warning message about deprecation of specified property or method of some class.
*
* @param clazz A class
* @param methodOrPropName Name of deprecated property or method
* @param version Version of Grails release in which property or method were deprecated
*/
public static void deprecated(Class clazz, String methodOrPropName, String version ) {
deprecated("Property or method [" + methodOrPropName + "] of class [" + clazz.getName() +
"] is deprecated in [" + getGrailsVersion() +
"] and will be removed in future releases");
}
/**
* Logs warning message about some deprecation and code style related hints.
*
* @param message Message to display
*/
public static void deprecated(String message) {
LOG.warn("[DEPRECATED] " + message);
}
}
| true | true | public static String getEnvironment() {
GrailsApplication app = ApplicationHolder.getApplication();
String envName = null;
if(app!=null) {
envName = (String)app.getMetadata().get(GrailsApplication.ENVIRONMENT);
}
if(StringUtils.isBlank(envName))
envName = System.getProperty(GrailsApplication.ENVIRONMENT);
if(StringUtils.isBlank(envName)) {
// for now if no environment specified default to production
return GrailsApplication.ENV_PRODUCTION;
}
else {
if(envNameMappings.containsKey(envName)) {
return (String)envNameMappings.get(envName);
}
else {
return envName;
}
}
}
| public static String getEnvironment() {
GrailsApplication app = ApplicationHolder.getApplication();
String envName = null;
if(app!=null) {
Map metadata = app.getMetadata();
if(metadata!=null)
envName = (String)metadata.get(GrailsApplication.ENVIRONMENT);
}
if(StringUtils.isBlank(envName))
envName = System.getProperty(GrailsApplication.ENVIRONMENT);
if(StringUtils.isBlank(envName)) {
// for now if no environment specified default to production
return GrailsApplication.ENV_PRODUCTION;
}
else {
if(envNameMappings.containsKey(envName)) {
return (String)envNameMappings.get(envName);
}
else {
return envName;
}
}
}
|
diff --git a/hamster-core/src/main/java/com/pivotal/hamster/appmaster/hnp/DefaultHnpLauncher.java b/hamster-core/src/main/java/com/pivotal/hamster/appmaster/hnp/DefaultHnpLauncher.java
index a8bb4b5..ade8c4f 100644
--- a/hamster-core/src/main/java/com/pivotal/hamster/appmaster/hnp/DefaultHnpLauncher.java
+++ b/hamster-core/src/main/java/com/pivotal/hamster/appmaster/hnp/DefaultHnpLauncher.java
@@ -1,143 +1,142 @@
package com.pivotal.hamster.appmaster.hnp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.event.Dispatcher;
import com.pivotal.hamster.appmaster.event.HamsterFailureEvent;
import com.pivotal.hamster.appmaster.hnp.HnpService.HnpState;
import com.pivotal.hamster.common.HamsterConfig;
import com.pivotal.hamster.common.HamsterException;
public class DefaultHnpLauncher extends HnpLauncher {
private static final Log LOG = LogFactory.getLog(DefaultHnpLauncher.class);
Dispatcher dispatcher;
Thread execThread;
Thread errThread;
Thread outThread;
HnpService service;
String[] args;
int serverPort;
static class StreamGobbler implements Runnable {
BufferedReader reader;
boolean out;
Dispatcher dispatcher;
public StreamGobbler(Dispatcher dispatcher, BufferedReader reader, boolean out) {
this.reader = reader;
this.out = out;
this.dispatcher = dispatcher;
}
public void run() {
try {
String line = null;
while ((line = reader.readLine()) != null) {
if (out)
System.out.println(line);
else
System.err.println(line);
}
} catch (IOException e) {
dispatcher.getEventHandler().handle(new HamsterFailureEvent(e, "failed when fetch output from HNP"));
return;
}
}
}
public DefaultHnpLauncher(Dispatcher dispatcher, HnpService service, String[] args) {
super(DefaultHnpLauncher.class.getName());
this.dispatcher = dispatcher;
this.args = args;
this.service = service;
}
@Override
public void init(Configuration conf) {
super.init(conf);
this.serverPort = service.getServerPort();
}
@Override
public void start() {
execThread = new Thread(new Runnable() {
@Override
public void run() {
// try to launch process
Process proc;
int exitCode = -1;
try {
// exec process
proc = Runtime.getRuntime().exec(args, copyAndSetEnvs());
// get err stream and out stream
BufferedReader bre = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));
BufferedReader bri = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
// use thread fetch output
errThread = new Thread(new StreamGobbler(dispatcher, bre, false));
outThread = new Thread(new StreamGobbler(dispatcher, bri, true));
// start thread fetch output
errThread.start();
outThread.start();
// wait for HNP dead
exitCode = proc.waitFor();
} catch (Exception e) {
- LOG.error("exception when launch HNP process", e);
dispatcher.getEventHandler().handle(new HamsterFailureEvent(e, "exception when launch HNP process"));
return;
}
LOG.info("note HNP exit with exit code = " + exitCode);
if (service.getHnpState() != HnpState.Finished) {
// send a message to hamster terminate handler, this message will be ignored if "finish" is called by hnp
dispatcher.getEventHandler().handle(new HamsterFailureEvent(
new HamsterException("terminate before HNP called finish"), "terminate before HNP called finish"));
}
}
});
execThread.start();
super.start();
}
@Override
public void stop() {
LOG.info("stop hnp launcher");
if (execThread.isAlive()) {
execThread.interrupt();
}
if (errThread.isAlive()) {
errThread.interrupt();
}
if (outThread.isAlive()) {
outThread.interrupt();
}
}
String[] copyAndSetEnvs() {
List<String> envs = new ArrayList<String>();
for (Entry<String, String> entry : System.getenv().entrySet()) {
envs.add(entry.getKey() + "=" + entry.getValue());
}
envs.add(HamsterConfig.AM_UMBILICAL_PORT_ENV_KEY + "=" + serverPort);
return envs.toArray(new String[0]);
}
}
| true | true | public void start() {
execThread = new Thread(new Runnable() {
@Override
public void run() {
// try to launch process
Process proc;
int exitCode = -1;
try {
// exec process
proc = Runtime.getRuntime().exec(args, copyAndSetEnvs());
// get err stream and out stream
BufferedReader bre = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));
BufferedReader bri = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
// use thread fetch output
errThread = new Thread(new StreamGobbler(dispatcher, bre, false));
outThread = new Thread(new StreamGobbler(dispatcher, bri, true));
// start thread fetch output
errThread.start();
outThread.start();
// wait for HNP dead
exitCode = proc.waitFor();
} catch (Exception e) {
LOG.error("exception when launch HNP process", e);
dispatcher.getEventHandler().handle(new HamsterFailureEvent(e, "exception when launch HNP process"));
return;
}
LOG.info("note HNP exit with exit code = " + exitCode);
if (service.getHnpState() != HnpState.Finished) {
// send a message to hamster terminate handler, this message will be ignored if "finish" is called by hnp
dispatcher.getEventHandler().handle(new HamsterFailureEvent(
new HamsterException("terminate before HNP called finish"), "terminate before HNP called finish"));
}
}
});
execThread.start();
super.start();
}
| public void start() {
execThread = new Thread(new Runnable() {
@Override
public void run() {
// try to launch process
Process proc;
int exitCode = -1;
try {
// exec process
proc = Runtime.getRuntime().exec(args, copyAndSetEnvs());
// get err stream and out stream
BufferedReader bre = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));
BufferedReader bri = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
// use thread fetch output
errThread = new Thread(new StreamGobbler(dispatcher, bre, false));
outThread = new Thread(new StreamGobbler(dispatcher, bri, true));
// start thread fetch output
errThread.start();
outThread.start();
// wait for HNP dead
exitCode = proc.waitFor();
} catch (Exception e) {
dispatcher.getEventHandler().handle(new HamsterFailureEvent(e, "exception when launch HNP process"));
return;
}
LOG.info("note HNP exit with exit code = " + exitCode);
if (service.getHnpState() != HnpState.Finished) {
// send a message to hamster terminate handler, this message will be ignored if "finish" is called by hnp
dispatcher.getEventHandler().handle(new HamsterFailureEvent(
new HamsterException("terminate before HNP called finish"), "terminate before HNP called finish"));
}
}
});
execThread.start();
super.start();
}
|
diff --git a/plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/AcceleoProjectUnzipper.java b/plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/AcceleoProjectUnzipper.java
index 6593e45..6a05bf7 100644
--- a/plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/AcceleoProjectUnzipper.java
+++ b/plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/AcceleoProjectUnzipper.java
@@ -1,152 +1,156 @@
/*******************************************************************************
* Copyright (c) 2008, 2012 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.tutorial;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
/**
* Utility class to unzip one or more projects contained in plugins.
*
* @author <a href="mailto:[email protected]">Stephane Begaudeau</a>
* @since 3.2
*/
public class AcceleoProjectUnzipper extends AbstractHandler {
/**
* {@inheritDoc}
*
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
String parameter = event.getParameter("org.eclipse.acceleo.tutorial.projectUnzipperPath");
String path = "invalid";
if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-1/".equals(parameter)) {
path = "step-1";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-2/".equals(parameter)) {
path = "step-2";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-3/".equals(parameter)) {
path = "step-3";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-4/".equals(parameter)) {
path = "step-4";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-5/".equals(parameter)) {
path = "step-5";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-6/".equals(parameter)) {
path = "step-6";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-7/".equals(parameter)) {
path = "step-7";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-8/".equals(parameter)) {
path = "step-8";
}
Bundle bundle = Platform.getBundle("org.eclipse.acceleo.tutorial");
Enumeration<URL> entries = bundle.findEntries(path, "*.zip", false);
while (entries.hasMoreElements()) {
URL nextElement = entries.nextElement();
String projectName = nextElement.toString();
projectName = projectName.substring(projectName.lastIndexOf("/"));
if (projectName.endsWith(".zip")) {
projectName = projectName.substring(0, projectName.length() - ".zip".length());
}
try {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project.exists()) {
- return null;
+ try {
+ project.delete(true, new NullProgressMonitor());
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
}
try {
project.create(new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
final String regexedProjectName = projectName.replaceAll("\\.", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
final ZipInputStream zipFileStream = new ZipInputStream(nextElement.openStream());
ZipEntry zipEntry = zipFileStream.getNextEntry();
while (zipEntry != null) {
// We will construct the new file but we will strip off the project
// directory from the beginning of the path because we have already
// created the destination project for this zip.
final File file = new File(project.getLocation().toString(), zipEntry.getName()
.replaceFirst("^" + regexedProjectName + "/", "")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
if (!zipEntry.isDirectory()) {
/*
* Copy files (and make sure parent directory exist)
*/
final File parentFile = file.getParentFile();
if (null != parentFile && !parentFile.exists()) {
parentFile.mkdirs();
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
final int bufferSize = 102400;
final byte[] buffer = new byte[bufferSize];
while (true) {
final int len = zipFileStream.read(buffer);
if (zipFileStream.available() == 0) {
break;
}
os.write(buffer, 0, len);
}
} finally {
if (null != os) {
os.close();
}
}
} else {
file.mkdir();
}
zipFileStream.closeEntry();
zipEntry = zipFileStream.getNextEntry();
}
try {
project.open(new NullProgressMonitor());
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
| true | true | public Object execute(ExecutionEvent event) throws ExecutionException {
String parameter = event.getParameter("org.eclipse.acceleo.tutorial.projectUnzipperPath");
String path = "invalid";
if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-1/".equals(parameter)) {
path = "step-1";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-2/".equals(parameter)) {
path = "step-2";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-3/".equals(parameter)) {
path = "step-3";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-4/".equals(parameter)) {
path = "step-4";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-5/".equals(parameter)) {
path = "step-5";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-6/".equals(parameter)) {
path = "step-6";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-7/".equals(parameter)) {
path = "step-7";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-8/".equals(parameter)) {
path = "step-8";
}
Bundle bundle = Platform.getBundle("org.eclipse.acceleo.tutorial");
Enumeration<URL> entries = bundle.findEntries(path, "*.zip", false);
while (entries.hasMoreElements()) {
URL nextElement = entries.nextElement();
String projectName = nextElement.toString();
projectName = projectName.substring(projectName.lastIndexOf("/"));
if (projectName.endsWith(".zip")) {
projectName = projectName.substring(0, projectName.length() - ".zip".length());
}
try {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project.exists()) {
return null;
}
try {
project.create(new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
final String regexedProjectName = projectName.replaceAll("\\.", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
final ZipInputStream zipFileStream = new ZipInputStream(nextElement.openStream());
ZipEntry zipEntry = zipFileStream.getNextEntry();
while (zipEntry != null) {
// We will construct the new file but we will strip off the project
// directory from the beginning of the path because we have already
// created the destination project for this zip.
final File file = new File(project.getLocation().toString(), zipEntry.getName()
.replaceFirst("^" + regexedProjectName + "/", "")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
if (!zipEntry.isDirectory()) {
/*
* Copy files (and make sure parent directory exist)
*/
final File parentFile = file.getParentFile();
if (null != parentFile && !parentFile.exists()) {
parentFile.mkdirs();
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
final int bufferSize = 102400;
final byte[] buffer = new byte[bufferSize];
while (true) {
final int len = zipFileStream.read(buffer);
if (zipFileStream.available() == 0) {
break;
}
os.write(buffer, 0, len);
}
} finally {
if (null != os) {
os.close();
}
}
} else {
file.mkdir();
}
zipFileStream.closeEntry();
zipEntry = zipFileStream.getNextEntry();
}
try {
project.open(new NullProgressMonitor());
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
| public Object execute(ExecutionEvent event) throws ExecutionException {
String parameter = event.getParameter("org.eclipse.acceleo.tutorial.projectUnzipperPath");
String path = "invalid";
if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-1/".equals(parameter)) {
path = "step-1";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-2/".equals(parameter)) {
path = "step-2";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-3/".equals(parameter)) {
path = "step-3";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-4/".equals(parameter)) {
path = "step-4";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-5/".equals(parameter)) {
path = "step-5";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-6/".equals(parameter)) {
path = "step-6";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-7/".equals(parameter)) {
path = "step-7";
} else if ("platform:/plugin/org.eclipse.acceleo.tutorial/step-8/".equals(parameter)) {
path = "step-8";
}
Bundle bundle = Platform.getBundle("org.eclipse.acceleo.tutorial");
Enumeration<URL> entries = bundle.findEntries(path, "*.zip", false);
while (entries.hasMoreElements()) {
URL nextElement = entries.nextElement();
String projectName = nextElement.toString();
projectName = projectName.substring(projectName.lastIndexOf("/"));
if (projectName.endsWith(".zip")) {
projectName = projectName.substring(0, projectName.length() - ".zip".length());
}
try {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project.exists()) {
try {
project.delete(true, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
}
try {
project.create(new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
final String regexedProjectName = projectName.replaceAll("\\.", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
final ZipInputStream zipFileStream = new ZipInputStream(nextElement.openStream());
ZipEntry zipEntry = zipFileStream.getNextEntry();
while (zipEntry != null) {
// We will construct the new file but we will strip off the project
// directory from the beginning of the path because we have already
// created the destination project for this zip.
final File file = new File(project.getLocation().toString(), zipEntry.getName()
.replaceFirst("^" + regexedProjectName + "/", "")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
if (!zipEntry.isDirectory()) {
/*
* Copy files (and make sure parent directory exist)
*/
final File parentFile = file.getParentFile();
if (null != parentFile && !parentFile.exists()) {
parentFile.mkdirs();
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
final int bufferSize = 102400;
final byte[] buffer = new byte[bufferSize];
while (true) {
final int len = zipFileStream.read(buffer);
if (zipFileStream.available() == 0) {
break;
}
os.write(buffer, 0, len);
}
} finally {
if (null != os) {
os.close();
}
}
} else {
file.mkdir();
}
zipFileStream.closeEntry();
zipEntry = zipFileStream.getNextEntry();
}
try {
project.open(new NullProgressMonitor());
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
|
diff --git a/src/battlechallenge/Ship.java b/src/battlechallenge/Ship.java
index 6b323dd..384064d 100644
--- a/src/battlechallenge/Ship.java
+++ b/src/battlechallenge/Ship.java
@@ -1,264 +1,264 @@
package battlechallenge;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* The Class Ship. A data holder representing ships from the original game
* battleship.
*/
public class Ship implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 0L;
/**
* The Enum Direction. Which direction the ship will be extended.
*/
public static enum Direction {
/** The NORTH. */
NORTH,
/** The EAST. */
EAST,
/** The SOUTH. */
SOUTH,
/** The WEST. */
WEST
}
/**
* The length. How many spaces the ship extends from the start position in
* the specified direction.
*/
private int length;
/** The health. Number of hits left before the ship is sunk. */
private int health;
/** The start position. */
private Coordinate startPosition;
/**
* The direction. Which direction from the starting position the ship will
* be extended.
*/
private Direction direction;
/** The hits. */
private Set<String> hits;
/** The coordinates */
private Set<String> coords;
/**
* Instantiates a new ship.
*
* @param length
* of the ship
* @param startPosition
* the start position
* @param direction
* the direction
*/
public Ship(int length, Coordinate startPosition, Direction direction) {
this.length = length;
this.health = length;
this.startPosition = startPosition;
this.direction = direction;
this.hits = new HashSet<String>();
this.coords = getCoordinateStrings();
}
/**
* Gets the length.
*
* @return the length
*/
public int getLength() {
return length;
}
/**
* Sets the length.
*
* @param length
* the new length
*/
public void setLength(int length) {
this.length = length;
}
/**
* Gets the starting coordinate of the ship.
*
* @return the start position
*/
public Coordinate getStartPosition() {
return startPosition;
}
/**
* Sets the starting coordinate of the ship.
*
* @param startPosition the new start position
*/
public void setStartPosition(Coordinate startPosition) {
this.startPosition = startPosition;
}
/**
* Gets the direction in which the ship extends outward.
*
* @return the direction
*/
public Direction getDirection() {
return direction;
}
/**
* Sets the direction in which the ship extends outward.
*
* @param direction the new direction
*/
public void setDirection(Direction direction) {
this.direction = direction;
}
/**
* Gets the end position based on the direction the ship extends outward
* from its starting position.
*
* @return the end position
*/
public Coordinate getEndPosition() {
switch (direction) {
case NORTH:
return new Coordinate(startPosition.getRow(),
startPosition.getCol() - length);
case SOUTH:
return new Coordinate(startPosition.getRow(),
startPosition.getCol() + length);
case EAST:
return new Coordinate(startPosition.getRow() + length,
startPosition.getCol());
case WEST:
return new Coordinate(startPosition.getRow() - length,
startPosition.getCol());
}
return null; // Should not reach here, will only be true if the ship
// direction is invalid
}
/**
* Gets the coordinate strings.
*
* @return the coordinate strings
*/
- private Set<String> getCoordinateStrings() {
+ public Set<String> getCoordinateStrings() {
if (coords == null) {
coords = new HashSet<String>();
for (int i = 0; i < length; i++) {
switch (direction) {
case NORTH: {
coords.add((this.startPosition.row + i) + ","
+ this.startPosition.col);
} break;
case SOUTH: {
coords.add((this.startPosition.row - i) + ","
+ this.startPosition.col);
} break;
case EAST: {
coords.add(this.startPosition.row + ","
+ (this.startPosition.col + i));
} break;
case WEST: {
coords.add(this.startPosition.row + ","
+ (this.startPosition.col - i));
} break;
}
}
}
return coords;
}
/**
* In bounds inclusive.
*
* @param rowMin the row min
* @param rowMax the row max
* @param colMin the col min
* @param colMax the col max
* @return true, if successful
*/
public boolean inBoundsInclusive(int rowMin, int rowMax, int colMin, int colMax) {
// TODO: double check "in bound" logic
switch (direction) {
case NORTH:
return this.startPosition.col >= colMin && this.startPosition.col <= colMax && this.startPosition.row <= rowMax && this.startPosition.row >= (rowMin-length);
case SOUTH:
return this.startPosition.col >= colMin && this.startPosition.col <= colMax && this.startPosition.row <= (rowMax+length) && this.startPosition.row >= rowMin;
case EAST:
return this.startPosition.col >= colMin && this.startPosition.col <= (colMax-length) && this.startPosition.row <= rowMax && this.startPosition.row >= rowMin;
case WEST:
return this.startPosition.col >= (colMin+length) && this.startPosition.col <= colMax && this.startPosition.row <= rowMax && this.startPosition.row >= rowMin;
}
return false;
}
/**
* Gets the health. The number of hits left before sinking.
*
* @return the health
*/
public int getHealth() {
return health;
}
/**
* Checks if this ship is sunken.
*
* @return true, if is sunken
*/
public boolean isSunken() {
return health <= 0;
}
/**
* Checks if the supplied coordinate is a hit. Health is automatically
* updated.
*
* @param c the coordinate
* @param damage the damage
* @return true, if is hit
*/
public boolean isHit(Coordinate c, int damage) {
// TODO: handle case where player hits same spot twice (force unique
// shot locations)
if (isSunken()) {
return false;
}
if (coords.contains(c.toString())) {
if (!hits.contains(c.toString())) {
health -= damage; // reduce health on ship by damage
hits.add(c.toString());
}
return true; // Is a hit
}
return false;
}
/**
* Deep copy of the shipObject so that the player can use the ship object as
* necessary while the server has keeps its own copy.
*
* @return the ship
*/
public Ship deepCopy() {
return new Ship(length, startPosition, direction);
}
}
| true | true | private Set<String> getCoordinateStrings() {
if (coords == null) {
coords = new HashSet<String>();
for (int i = 0; i < length; i++) {
switch (direction) {
case NORTH: {
coords.add((this.startPosition.row + i) + ","
+ this.startPosition.col);
} break;
case SOUTH: {
coords.add((this.startPosition.row - i) + ","
+ this.startPosition.col);
} break;
case EAST: {
coords.add(this.startPosition.row + ","
+ (this.startPosition.col + i));
} break;
case WEST: {
coords.add(this.startPosition.row + ","
+ (this.startPosition.col - i));
} break;
}
}
}
return coords;
}
| public Set<String> getCoordinateStrings() {
if (coords == null) {
coords = new HashSet<String>();
for (int i = 0; i < length; i++) {
switch (direction) {
case NORTH: {
coords.add((this.startPosition.row + i) + ","
+ this.startPosition.col);
} break;
case SOUTH: {
coords.add((this.startPosition.row - i) + ","
+ this.startPosition.col);
} break;
case EAST: {
coords.add(this.startPosition.row + ","
+ (this.startPosition.col + i));
} break;
case WEST: {
coords.add(this.startPosition.row + ","
+ (this.startPosition.col - i));
} break;
}
}
}
return coords;
}
|
diff --git a/src/rajawali/materials/TextureManager.java b/src/rajawali/materials/TextureManager.java
index 736bbc4f..4244df20 100644
--- a/src/rajawali/materials/TextureManager.java
+++ b/src/rajawali/materials/TextureManager.java
@@ -1,828 +1,828 @@
package rajawali.materials;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import rajawali.util.RajLog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.opengl.ETC1;
import android.opengl.ETC1Util;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.util.Log;
/**
* @author dennis.ippel
*
*/
public class TextureManager {
private boolean mShouldValidateTextures;
private TextureInfo mCurrentValidatingTexInfo;
private Stack<TextureInfo> mTexturesToUpdate;
private boolean mShouldUpdateTextures;
private static final int GL_TEXTURE_EXTERNAL_OES = 0x8D65;
// Paletted texture constants
// Referenced from OpenGL ES 2.0 extension C header from Khronos Group
// http://www.khronos.org/registry/gles/api/2.0/gl2ext.h
private static final int GL_PALETTE4_RGB8_OES = 0x8B90;
private static final int GL_PALETTE4_RGBA8_OES = 0x8B91;
private static final int GL_PALETTE4_R5_G6_B5_OES = 0x8B92;
private static final int GL_PALETTE4_RGBA4_OES = 0x8B93;
private static final int GL_PALETTE4_RGB5_A1_OES = 0x8B94;
private static final int GL_PALETTE8_RGB8_OES = 0x8B95;
private static final int GL_PALETTE8_RGBA8_OES = 0x8B96;
private static final int GL_PALETTE8_R5_G6_B5_OES = 0x8B97;
private static final int GL_PALETTE8_RGBA4_OES = 0x8B98;
private static final int GL_PALETTE8_RGB5_A1_OES = 0x8B99;
// PowerVR Texture compression constants
private static final int GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00;
private static final int GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01;
private static final int GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02;
private static final int GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03;
// S3 texture compression constants
private static final int GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0;
private static final int GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1;
/**
* List containing texture information objects
*/
private List<TextureInfo> mTextureInfoList;
/**
* Cube map faces
*/
private final int[] CUBE_FACES = new int[] {
GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GLES20.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
GLES20.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
GLES20.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
/**
* Texture types. Can be DIFFUSE, BUMP, FRAME_BUFFER, DEPTH_BUFFER, LOOKUP, CUBE_MAP
*/
public enum TextureType {
DIFFUSE,
BUMP,
SPECULAR,
ALPHA,
FRAME_BUFFER,
DEPTH_BUFFER,
LOOKUP,
CUBE_MAP,
SPHERE_MAP,
VIDEO_TEXTURE
};
public enum CompressionType {
NONE,
ETC1,
PALETTED,
THREEDC,
ATC,
DXT1,
PVRTC
};
public enum WrapType {
CLAMP,
REPEAT
};
public enum FilterType{
NEAREST,
LINEAR
};
public enum PaletteFormat {
PALETTE4_RGB8,
PALETTE4_RGBA8,
PALETTE4_R5_G6_B5,
PALETTE4_RGBA4,
PALETTE4_RGB5_A1,
PALETTE8_RGB8,
PALETTE8_RGBA8,
PALETTE8_R5_G6_B5,
PALETTE8_RGBA4,
PALETTE8_RGB5_A1
};
public enum ThreeDcFormat {
X,
XY
};
public enum AtcFormat {
RGB,
RGBA_EXPLICIT,
RGBA_INTERPOLATED
};
public enum Dxt1Format {
RGB,
RGBA
};
public enum PvrtcFormat {
RGB_2BPP,
RGB_4BPP,
RGBA_2BPP,
RGBA_4BPP
};
public TextureManager() {
mTextureInfoList = Collections.synchronizedList(new CopyOnWriteArrayList<TextureInfo>());
mTexturesToUpdate = new Stack<TextureInfo>();
}
public TextureInfo addTexture(Bitmap texture) {
return addTexture(texture, TextureType.DIFFUSE);
}
public TextureInfo addTexture(Bitmap texture, TextureType textureType) {
return this.addTexture(texture, textureType, true, false, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addTexture(Bitmap texture, TextureType textureType, boolean mipmap) {
return this.addTexture(texture, textureType, mipmap, false, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addTexture(Bitmap texture, boolean mipmap, boolean recycle) {
return this.addTexture(texture, TextureType.DIFFUSE, mipmap, recycle, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addTexture(Bitmap texture, TextureType textureType, WrapType wrapType, FilterType filterType) {
return this.addTexture(texture, textureType, true, false, wrapType, filterType);
}
public TextureInfo addTexture(Bitmap texture, TextureType textureType, boolean mipmap, boolean recycle) {
return this.addTexture(texture, textureType, mipmap, recycle, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addTexture(Bitmap texture, TextureType textureType, boolean mipmap, boolean recycle, WrapType wrapType, FilterType filterType) {
TextureInfo tInfo = addTexture(new ByteBuffer[0], texture, texture.getWidth(), texture.getHeight(), textureType, texture.getConfig(), mipmap, recycle, wrapType, filterType);
if(recycle && tInfo.getTextureId() > 0)
texture.recycle();
else
tInfo.setTexture(texture);
return tInfo;
}
public TextureInfo addTexture(ByteBuffer buffer, int width, int height) {
return addTexture(buffer, width, height, TextureType.DIFFUSE);
}
public TextureInfo addTexture(ByteBuffer buffer, int width, int height, TextureType textureType) {
return addTexture(buffer, null, width, height, textureType, Config.ARGB_8888, false, false, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addTexture(ByteBuffer[] buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, WrapType wrapType, FilterType filterType) {
return addTexture(buffer, texture, width, height, textureType, bitmapConfig, mipmap, recycle, false, wrapType, filterType);
}
public TextureInfo addTexture(ByteBuffer buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, WrapType wrapType, FilterType filterType) {
return addTexture(new ByteBuffer[] { buffer }, texture, width, height, textureType, bitmapConfig, mipmap, recycle, false, wrapType, filterType);
}
public TextureInfo addTexture(TextureInfo textureInfo) {
TextureInfo newInfo;
GLES20.glDeleteTextures(1, new int[] { textureInfo.getTextureId() }, 0);
TextureInfo oldInfo = new TextureInfo(textureInfo);
if (textureInfo.getCompressionType() == CompressionType.NONE) {
if(textureInfo.getTextureType() == TextureType.CUBE_MAP) {
newInfo = addCubemapTextures(textureInfo.getTextures(), textureInfo.isMipmap(), textureInfo.shouldRecycle());
} else if(textureInfo.getTextureType() == TextureType.FRAME_BUFFER) {
newInfo = addTexture(null, textureInfo.getWidth(), textureInfo.getHeight(), TextureType.FRAME_BUFFER);
} else {
if (textureInfo.getTexture() == null) {
newInfo = addTexture(textureInfo.getBuffer(), null, textureInfo.getWidth(), textureInfo.getHeight(), textureInfo.getTextureType(), textureInfo.getBitmapConfig(), false, false, textureInfo.getWrapType(), textureInfo.getFilterType());
} else {
newInfo = addTexture(textureInfo.getTexture(), textureInfo.getTextureType(), textureInfo.isMipmap(), textureInfo.shouldRecycle(), textureInfo.getWrapType(), textureInfo.getFilterType());
}
}
} else {
newInfo = addTexture(textureInfo.getBuffer(), null, textureInfo.getWidth(), textureInfo.getHeight(), textureInfo.getTextureType(), null, false, false, false, textureInfo.getWrapType(), textureInfo.getFilterType(), textureInfo.getCompressionType(), textureInfo.getInternalFormat());
}
// remove newly added texture info because we're sticking with the old one.
mTextureInfoList.remove(newInfo);
textureInfo.setFrom(newInfo);
textureInfo.setTextureName(oldInfo.getTextureName());
return textureInfo;
}
public TextureInfo addTexture(ByteBuffer[] buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addTexture(buffer, texture, width, height, textureType, bitmapConfig, mipmap, recycle, isExistingTexture, wrapType, filterType, CompressionType.NONE, 0);
}
public TextureInfo addTexture(ByteBuffer buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addTexture(new ByteBuffer[] { buffer }, texture, width, height, textureType, bitmapConfig, mipmap, recycle, isExistingTexture, wrapType, filterType, CompressionType.NONE, 0);
}
public TextureInfo addTexture(ByteBuffer[] buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, boolean isExistingTexture, WrapType wrapType, FilterType filterType, CompressionType compressionType, int compressionFormat) {
int bitmapFormat = bitmapConfig == Config.ARGB_8888 ? GLES20.GL_RGBA : GLES20.GL_RGB;
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
int textureId = textures[0];
if(textureId > 0) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
if((mipmap && compressionType == CompressionType.NONE) ||
// Manual mipmapped textures are included
(buffer.length > 1)){
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST_MIPMAP_NEAREST);
}else{
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
}
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
if(wrapType==WrapType.REPEAT){
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
}else{
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
}
if(texture == null) {
if (compressionType == CompressionType.NONE) {
if ((buffer != null && buffer.length == 0) || buffer == null) {
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapFormat, width, height, 0, bitmapFormat, GLES20.GL_UNSIGNED_BYTE, null);
} else {
int w = width, h = height;
for (int i = 0; i < buffer.length; i++) {
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, i, bitmapFormat, w, h, 0, bitmapFormat, GLES20.GL_UNSIGNED_BYTE, buffer[i]);
w = w > 1 ? w / 2 : 1;
- h = h > 1 ? w / 2 : 1;
+ h = h > 1 ? h / 2 : 1;
}
}
} else {
if ((buffer != null && buffer.length == 0) || buffer == null) {
GLES20.glCompressedTexImage2D(GLES20.GL_TEXTURE_2D, 0, compressionFormat, width, height, 0, 0, null);
} else {
int w = width, h = height;
for (int i = 0; i < buffer.length; i++) {
GLES20.glCompressedTexImage2D(GLES20.GL_TEXTURE_2D, i, compressionFormat, w, h, 0, buffer[i].capacity(), buffer[i]);
w = w > 1 ? w / 2 : 1;
- h = h > 1 ? w / 2 : 1;
+ h = h > 1 ? h / 2 : 1;
}
}
}
} else
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapFormat, texture, 0);
if(mipmap && compressionType == CompressionType.NONE)
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
} else {
mShouldValidateTextures = true;
}
TextureInfo textureInfo = mCurrentValidatingTexInfo == null ? new TextureInfo(textureId, textureType) : mCurrentValidatingTexInfo;
if(mCurrentValidatingTexInfo == null) {
textureInfo.setWidth(width);
textureInfo.setHeight(height);
textureInfo.setBitmapConfig(bitmapConfig);
textureInfo.setMipmap(mipmap);
textureInfo.setWrapType(wrapType);
textureInfo.setFilterType(filterType);
textureInfo.shouldRecycle(recycle);
textureInfo.setCompressionType(compressionType);
textureInfo.setBuffer(buffer);
if(compressionType != CompressionType.NONE){
textureInfo.setInternalFormat(compressionFormat);
}
if(!recycle && compressionType == CompressionType.NONE)
textureInfo.setTexture(texture);
} else {
textureInfo.setTextureId(textureId);
}
for (int i = 0; i < buffer.length; i++) {
if(buffer[i] != null) {
buffer[i].limit(0);
}
}
buffer = null;
if(!isExistingTexture && mCurrentValidatingTexInfo == null)
mTextureInfoList.add(textureInfo);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
return textureInfo;
}
/**
* Dynamically generates an ETC1 texture on-the-fly from given bitmap
* and automatically binds the newly generated texture.
*/
public TextureInfo addEtc1Texture(Bitmap bitmap, TextureType textureType) {
int imageSize = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer uncompressedBuffer = ByteBuffer.allocateDirect(imageSize);
bitmap.copyPixelsToBuffer(uncompressedBuffer);
uncompressedBuffer.position(0);
ByteBuffer compressedBuffer = ByteBuffer.allocateDirect(ETC1.getEncodedDataSize(bitmap.getWidth(), bitmap.getHeight())).order(ByteOrder.nativeOrder());
ETC1.encodeImage(uncompressedBuffer, bitmap.getWidth(), bitmap.getHeight(), 2, 2 * bitmap.getWidth(), compressedBuffer);
return addEtc1Texture(compressedBuffer, bitmap.getWidth(), bitmap.getHeight(), textureType);
}
/**
* Attempts to add ETC1 compressed texture and fall back to uncompressed bitmap upon failure.
* @param compressedTex InputStream of the PKM texture resource
* @param fallbackTex Uncompressed Bitmap resource to fallback on if adding ETC1 texture fails
* @return TextureInfo
*/
public TextureInfo addEtc1Texture(InputStream compressedTex, Bitmap fallbackTex) {
return addEtc1Texture(compressedTex, fallbackTex, TextureType.DIFFUSE);
}
public TextureInfo addEtc1Texture(InputStream compressedTex, Bitmap fallbackTex, TextureType textureType) {
ETC1Util.ETC1Texture texture = null;
TextureInfo textureInfo = null;
try {
texture = ETC1Util.createTexture(compressedTex);
} catch (IOException e) {
Log.e("addEtc1Texture", e.getMessage());
} finally {
if (texture == null) {
textureInfo = addTexture(fallbackTex);
Log.d("ETC1", "Falling back to uncompressed texture");
} else {
textureInfo = addEtc1Texture(texture.getData(), texture.getWidth(), texture.getHeight(), textureType);
Log.d("ETC1", "ETC1 texture load successful");
}
}
return textureInfo;
}
/**
* Add mipmap-chained ETC1 texture.
* @param context
* @param resourceIds
* @return
*/
public TextureInfo addEtc1Texture(Context context, int[] resourceIds, TextureType textureType, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
if (resourceIds == null) return null;
ByteBuffer[] mipmapChain = new ByteBuffer[resourceIds.length];
int mip_0_width = 1, mip_0_height = 1;
try {
for (int i = 0, length = resourceIds.length; i < length; i++) {
ETC1Util.ETC1Texture texture = ETC1Util.createTexture(context.getResources().openRawResource(resourceIds[i]));
mipmapChain[i] = texture.getData();
if (i == 0) {
mip_0_width = texture.getWidth();
mip_0_height = texture.getHeight();
}
}
} catch (IOException e) {
RajLog.e(e.getMessage());
e.printStackTrace();
}
return addTexture(mipmapChain, null, mip_0_width, mip_0_height, textureType, null, true, false, isExistingTexture, wrapType, filterType, CompressionType.ETC1, ETC1.ETC1_RGB8_OES);
}
/**
* Add mipmap-chained ETC1 texture.
* @param context
* @param resourceIds
* @return
*/
public TextureInfo addEtc1Texture(Context context, int[] resourceIds, TextureType textureType) {
return addEtc1Texture(context, resourceIds, textureType, false, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addEtc1Texture(ByteBuffer buffer, int width, int height) {
return addEtc1Texture(buffer, width, height, TextureType.DIFFUSE);
}
/**
* Adds and binds ETC1 compressed texture. Due to limitations with compressed textures,
* automatic mipmap generation is disabled.
*
* All devices with OpenGL ES 2.0 API should be able to handle this type of compression.
*/
public TextureInfo addEtc1Texture(ByteBuffer buffer, int width, int height, TextureType textureType) {
return addEtc1Texture(buffer, width, height, textureType, false, WrapType.REPEAT, FilterType.LINEAR);
}
public TextureInfo addEtc1Texture(ByteBuffer buffer, int width, int height, TextureType textureType, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addTexture(new ByteBuffer[] { buffer }, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.ETC1, ETC1.ETC1_RGB8_OES);
}
public TextureInfo addEtc1Texture(ByteBuffer[] buffer, int width, int height, TextureType textureType, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.ETC1, ETC1.ETC1_RGB8_OES);
}
public TextureInfo addPalettedTexture(ByteBuffer buffer, int width, int height, TextureType textureType, PaletteFormat format) {
return addPalettedTexture(buffer, width, height, textureType, format, false, WrapType.REPEAT, FilterType.LINEAR);
}
/**
* Adds and binds paletted texture. Pass in multiple buffer corresponding to different mipmap levels.
*/
public TextureInfo addPalettedTexture(ByteBuffer[] buffer, int width, int height, TextureType textureType, PaletteFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
int internalformat;
switch (format) {
case PALETTE4_RGB8:
internalformat = GL_PALETTE4_RGB8_OES;
break;
case PALETTE4_RGBA8:
internalformat = GL_PALETTE4_RGBA8_OES;
break;
case PALETTE4_R5_G6_B5:
internalformat = GL_PALETTE4_R5_G6_B5_OES;
break;
case PALETTE4_RGBA4:
internalformat = GL_PALETTE4_RGBA4_OES;
break;
case PALETTE4_RGB5_A1:
internalformat = GL_PALETTE4_RGB5_A1_OES;
break;
case PALETTE8_RGB8:
internalformat = GL_PALETTE8_RGB8_OES;
break;
case PALETTE8_RGBA8:
default:
internalformat = GL_PALETTE8_RGBA8_OES;
break;
case PALETTE8_R5_G6_B5:
internalformat = GL_PALETTE8_R5_G6_B5_OES;
break;
case PALETTE8_RGBA4:
internalformat = GL_PALETTE8_RGBA4_OES;
break;
case PALETTE8_RGB5_A1:
internalformat = GL_PALETTE8_RGB5_A1_OES;
break;
}
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.PALETTED, internalformat);
}
public TextureInfo addPalettedTexture(ByteBuffer buffer, int width, int height, TextureType textureType, PaletteFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addPalettedTexture(new ByteBuffer[] { buffer }, width, height, textureType, format, isExistingTexture, wrapType, filterType);
}
public TextureInfo add3dcTexture(ByteBuffer buffer, int width, int height, TextureType textureType, ThreeDcFormat format) {
return add3dcTexture(buffer, width, height, textureType, format, false, WrapType.REPEAT, FilterType.LINEAR);
}
/**
* Adds and binds ATI 3Dc compressed texture. This compression type is most used for
* compressing normal map textures.
*/
public TextureInfo add3dcTexture(ByteBuffer[] buffer, int width, int height, TextureType textureType, ThreeDcFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
if (format == ThreeDcFormat.X)
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.THREEDC, GLES11Ext.GL_3DC_X_AMD);
else
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.THREEDC, GLES11Ext.GL_3DC_XY_AMD);
}
public TextureInfo add3dcTexture(ByteBuffer buffer, int width, int height, TextureType textureType, ThreeDcFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return add3dcTexture(new ByteBuffer[] { buffer }, width, height, textureType, format, isExistingTexture, wrapType, filterType);
}
public TextureInfo addAtcTexture(ByteBuffer buffer, int width, int height, TextureType textureType, AtcFormat format) {
return addAtcTexture(buffer, width, height, textureType, format, false, WrapType.REPEAT, FilterType.LINEAR);
}
/**
* Adds and binds AMD compressed texture. To use mipmaps, pass in more than one items in the buffer,
* starting with mipmap level 0.
*
* This method will only work on devices that support AMD texture compression. Most Adreno GPU
* based devices such as Nexus One and HTC Desire support AMD texture compression.
*/
public TextureInfo addAtcTexture(ByteBuffer[] buffer, int width, int height, TextureType textureType, AtcFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
int internalformat;
switch(format) {
case RGB:
internalformat = GLES11Ext.GL_ATC_RGB_AMD;
break;
case RGBA_EXPLICIT:
default:
internalformat = GLES11Ext.GL_ATC_RGBA_EXPLICIT_ALPHA_AMD;
break;
case RGBA_INTERPOLATED:
internalformat = GLES11Ext.GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD;
break;
}
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.ATC, internalformat);
}
public TextureInfo addAtcTexture(ByteBuffer buffer, int width, int height, TextureType textureType, AtcFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addAtcTexture(new ByteBuffer[] { buffer }, width, height, textureType, format, isExistingTexture, wrapType, filterType);
}
public TextureInfo addDxt1Texture(ByteBuffer buffer, int width, int height, TextureType textureType, Dxt1Format format) {
return addDxt1Texture(buffer, width, height, textureType, format, false, WrapType.REPEAT, FilterType.LINEAR);
}
/**
* Adds and binds DXT1 variant of S3 compressed texture.
*
* This method will only work in devices that support S3 texture compression. Most Nvidia Tegra2 GPU
* based devices such as Motorola Xoom, and Atrix support S3 texture comrpession.
*/
public TextureInfo addDxt1Texture(ByteBuffer[] buffer, int width, int height, TextureType textureType, Dxt1Format format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
int internalformat;
switch (format) {
case RGB:
internalformat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
break;
case RGBA:
default:
internalformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
}
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.DXT1, internalformat);
}
public TextureInfo addDxt1Texture(ByteBuffer buffer, int width, int height, TextureType textureType, Dxt1Format format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addDxt1Texture(new ByteBuffer[] { buffer }, width, height, textureType, format, isExistingTexture, wrapType, filterType);
}
public TextureInfo addPvrtcTexture(ByteBuffer buffer, int width, int height, TextureType textureType, PvrtcFormat format) {
return addPvrtcTexture(buffer, width, height, textureType, format, false, WrapType.REPEAT, FilterType.LINEAR);
}
/**
* Adds and binds PowerVR compressed texture. Due to limitations with compressed textures,
* automatic mipmap generation is disabled.
*
* This method will only work on devices that support PowerVR texture compression. Most PowerVR GPU
* based devices such as Nexus S and Galaxy S3 support AMD texture compression.
*/
public TextureInfo addPvrtcTexture(ByteBuffer[] buffer, int width, int height, TextureType textureType, PvrtcFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
int internalformat;
switch (format) {
case RGB_2BPP:
internalformat = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
break;
case RGB_4BPP:
internalformat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
break;
case RGBA_2BPP:
internalformat = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
break;
case RGBA_4BPP:
default:
internalformat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
break;
}
return addTexture(buffer, null, width, height, textureType, null, false, false, isExistingTexture, wrapType, filterType, CompressionType.PVRTC, internalformat);
}
public TextureInfo addPvrtcTexture(ByteBuffer buffer, int width, int height, TextureType textureType, PvrtcFormat format, boolean isExistingTexture, WrapType wrapType, FilterType filterType) {
return addPvrtcTexture(new ByteBuffer[] { buffer }, width, height, textureType, format, isExistingTexture, wrapType, filterType);
}
/**
* This only works for API Level 15 and higher.
* Thanks to Lubomir Panak (@drakh)
* <p>
* How to use:
* <pre><code>
* protected void initScene() {
* super.initScene();
* mLight = new DirectionalLight(0, 0, 1);
* mCamera.setPosition(0, 0, -17);
*
* VideoMaterial material = new VideoMaterial();
* TextureInfo tInfo = mTextureManager.addVideoTexture();
*
* mTexture = new SurfaceTexture(tInfo.getTextureId());
*
* mMediaPlayer = MediaPlayer.create(getContext(), R.raw.nemo);
* mMediaPlayer.setSurface(new Surface(mTexture));
* mMediaPlayer.start();
*
* BaseObject3D cube = new Plane(2, 2, 1, 1);
* cube.setMaterial(material);
* cube.addTexture(tInfo);
* cube.addLight(mLight);
* addChild(cube);
* }
*
* public void onDrawFrame(GL10 glUnused) {
* mTexture.updateTexImage();
* super.onDrawFrame(glUnused);
* }
* </code></pre>
* @return
*/
public TextureInfo addVideoTexture() {
TextureType textureType = TextureType.VIDEO_TEXTURE;
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
int textureId = textures[0];
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureId);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
TextureInfo textureInfo = new TextureInfo(textureId, textureType);
return textureInfo;
}
public TextureInfo addCubemapTextures(Bitmap[] textures) {
return addCubemapTextures(textures, false);
}
public TextureInfo addCubemapTextures(Bitmap[] textures, boolean mipmap) {
return addCubemapTextures(textures, false, false);
}
public TextureInfo addCubemapTextures(Bitmap[] textures, boolean mipmap, boolean recycle) {
return addCubemapTextures(textures, mipmap, recycle, false);
}
public TextureInfo addCubemapTextures(Bitmap[] textures, boolean mipmap, boolean recycle, boolean isExistingTexture) {
int[] textureIds = new int[1];
GLES20.glGenTextures(1, textureIds, 0);
int textureId = textureIds[0];
TextureInfo textureInfo = mCurrentValidatingTexInfo == null ? new TextureInfo(textureId) : mCurrentValidatingTexInfo;
if(!isExistingTexture && mCurrentValidatingTexInfo == null) mTextureInfoList.add(textureInfo);
if(mCurrentValidatingTexInfo == null) {
textureInfo.setWidth(textures[0].getWidth());
textureInfo.setHeight(textures[0].getHeight());
textureInfo.setTextureType(TextureType.CUBE_MAP);
textureInfo.setBitmapConfig(textures[0].getConfig());
textureInfo.setMipmap(mipmap);
textureInfo.shouldRecycle(recycle);
textureInfo.setIsCubeMap(true);
} else {
textureInfo.setTextureId(textureId);
}
if(textureId > 0) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, textureId);
if(mipmap)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_CUBE_MAP, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_CUBE_MAP, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_CUBE_MAP, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_CUBE_MAP, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_CUBE_MAP, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
for(int i=0; i<6; i++) {
GLES20.glHint(GLES20.GL_GENERATE_MIPMAP_HINT, GLES20.GL_NICEST);
GLUtils.texImage2D(CUBE_FACES[i], 0, textures[i], 0);
if(recycle && textureId > 0) textures[i].recycle();
}
if(mipmap) GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_CUBE_MAP);
} else {
mShouldValidateTextures = true;
}
if(!recycle)
textureInfo.setTextures(textures);
GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, textureId);
return textureInfo;
}
public int getNumTextures() {
return mTextureInfoList.size();
}
/**
* Please use updateTexture(TextureInfo textureInfo, Bitmap texture)
* @deprecated
* @param textureId
* @param texture
*/
@Deprecated
public void updateTexture(Integer textureId, Bitmap texture) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId.intValue());
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, texture);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
}
public void updateTexture(TextureInfo textureInfo, Bitmap texture) {
textureInfo.setTexture(texture);
mShouldUpdateTextures = true;
mTexturesToUpdate.add(textureInfo);
}
public void updateTexture(TextureInfo textureInfo) {
Bitmap texture = textureInfo.getTexture();
int bitmapFormat = texture.getConfig() == Config.ARGB_8888 ? GLES20.GL_RGBA : GLES20.GL_RGB;
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureInfo.getTextureId());
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, texture, bitmapFormat, GLES20.GL_UNSIGNED_BYTE);
if(textureInfo.isMipmap())
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
}
public void reload() {
TextureInfo tInfo = null;
int len = getNumTextures();
for(int i=0; i<len; i++) {
tInfo = mTextureInfoList.get(i);
tInfo.setFrom(addTexture(tInfo));
}
}
public void reset() {
int count = mTextureInfoList.size();
int[] textures = new int[count];
for(int i=0; i<count; i++)
{
TextureInfo ti = mTextureInfoList.get(i);
if(ti.getTexture() != null) ti.getTexture().recycle();
textures[i] = ti.getTextureId();
}
GLES20.glDeleteTextures(count, textures, 0);
mTextureInfoList.clear();
}
public void removeTexture(TextureInfo textureInfo) {
mTextureInfoList.remove(textureInfo);
GLES20.glDeleteTextures(1, new int[] { textureInfo.getTextureId() }, 0);
}
public void removeTextures(ArrayList<TextureInfo> textureInfoList) {
int count = textureInfoList.size();
int[] textures = new int[count];
int i;
for(i=0; i<count; ++i) {
Integer textureId = textureInfoList.get(i).getTextureId();
textures[i] = textureId.intValue();
mTextureInfoList.remove(textureInfoList.get(i));
}
textureInfoList.clear();
GLES20.glDeleteTextures(count, textures, 0);
}
public List<TextureInfo> getTextureInfoList() {
return mTextureInfoList;
}
public void validateTextures() {
if(mShouldValidateTextures) {
// Iterating a temporary list is better for the memory
// consumption than using iterators.
List<TextureInfo> tempList = new ArrayList<TextureInfo>();
tempList.addAll(mTextureInfoList);
for (int i = 0; i < tempList.size(); ++i) {
TextureInfo inf = tempList.get(i);
if(inf.getTextureId() == 0) {
mCurrentValidatingTexInfo = inf;
addTexture(inf);
mCurrentValidatingTexInfo = null;
}
}
mShouldValidateTextures = false;
}
if(mShouldUpdateTextures) {
while(!mTexturesToUpdate.isEmpty())
updateTexture(mTexturesToUpdate.pop());
mShouldUpdateTextures = false;
}
}
}
| false | true | public TextureInfo addTexture(ByteBuffer[] buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, boolean isExistingTexture, WrapType wrapType, FilterType filterType, CompressionType compressionType, int compressionFormat) {
int bitmapFormat = bitmapConfig == Config.ARGB_8888 ? GLES20.GL_RGBA : GLES20.GL_RGB;
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
int textureId = textures[0];
if(textureId > 0) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
if((mipmap && compressionType == CompressionType.NONE) ||
// Manual mipmapped textures are included
(buffer.length > 1)){
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST_MIPMAP_NEAREST);
}else{
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
}
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
if(wrapType==WrapType.REPEAT){
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
}else{
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
}
if(texture == null) {
if (compressionType == CompressionType.NONE) {
if ((buffer != null && buffer.length == 0) || buffer == null) {
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapFormat, width, height, 0, bitmapFormat, GLES20.GL_UNSIGNED_BYTE, null);
} else {
int w = width, h = height;
for (int i = 0; i < buffer.length; i++) {
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, i, bitmapFormat, w, h, 0, bitmapFormat, GLES20.GL_UNSIGNED_BYTE, buffer[i]);
w = w > 1 ? w / 2 : 1;
h = h > 1 ? w / 2 : 1;
}
}
} else {
if ((buffer != null && buffer.length == 0) || buffer == null) {
GLES20.glCompressedTexImage2D(GLES20.GL_TEXTURE_2D, 0, compressionFormat, width, height, 0, 0, null);
} else {
int w = width, h = height;
for (int i = 0; i < buffer.length; i++) {
GLES20.glCompressedTexImage2D(GLES20.GL_TEXTURE_2D, i, compressionFormat, w, h, 0, buffer[i].capacity(), buffer[i]);
w = w > 1 ? w / 2 : 1;
h = h > 1 ? w / 2 : 1;
}
}
}
} else
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapFormat, texture, 0);
if(mipmap && compressionType == CompressionType.NONE)
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
} else {
mShouldValidateTextures = true;
}
TextureInfo textureInfo = mCurrentValidatingTexInfo == null ? new TextureInfo(textureId, textureType) : mCurrentValidatingTexInfo;
if(mCurrentValidatingTexInfo == null) {
textureInfo.setWidth(width);
textureInfo.setHeight(height);
textureInfo.setBitmapConfig(bitmapConfig);
textureInfo.setMipmap(mipmap);
textureInfo.setWrapType(wrapType);
textureInfo.setFilterType(filterType);
textureInfo.shouldRecycle(recycle);
textureInfo.setCompressionType(compressionType);
textureInfo.setBuffer(buffer);
if(compressionType != CompressionType.NONE){
textureInfo.setInternalFormat(compressionFormat);
}
if(!recycle && compressionType == CompressionType.NONE)
textureInfo.setTexture(texture);
} else {
textureInfo.setTextureId(textureId);
}
for (int i = 0; i < buffer.length; i++) {
if(buffer[i] != null) {
buffer[i].limit(0);
}
}
buffer = null;
if(!isExistingTexture && mCurrentValidatingTexInfo == null)
mTextureInfoList.add(textureInfo);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
return textureInfo;
}
| public TextureInfo addTexture(ByteBuffer[] buffer, Bitmap texture, int width, int height, TextureType textureType, Config bitmapConfig, boolean mipmap, boolean recycle, boolean isExistingTexture, WrapType wrapType, FilterType filterType, CompressionType compressionType, int compressionFormat) {
int bitmapFormat = bitmapConfig == Config.ARGB_8888 ? GLES20.GL_RGBA : GLES20.GL_RGB;
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
int textureId = textures[0];
if(textureId > 0) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
if((mipmap && compressionType == CompressionType.NONE) ||
// Manual mipmapped textures are included
(buffer.length > 1)){
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST_MIPMAP_NEAREST);
}else{
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
}
if(filterType==FilterType.LINEAR)
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
else
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
if(wrapType==WrapType.REPEAT){
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
}else{
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
}
if(texture == null) {
if (compressionType == CompressionType.NONE) {
if ((buffer != null && buffer.length == 0) || buffer == null) {
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapFormat, width, height, 0, bitmapFormat, GLES20.GL_UNSIGNED_BYTE, null);
} else {
int w = width, h = height;
for (int i = 0; i < buffer.length; i++) {
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, i, bitmapFormat, w, h, 0, bitmapFormat, GLES20.GL_UNSIGNED_BYTE, buffer[i]);
w = w > 1 ? w / 2 : 1;
h = h > 1 ? h / 2 : 1;
}
}
} else {
if ((buffer != null && buffer.length == 0) || buffer == null) {
GLES20.glCompressedTexImage2D(GLES20.GL_TEXTURE_2D, 0, compressionFormat, width, height, 0, 0, null);
} else {
int w = width, h = height;
for (int i = 0; i < buffer.length; i++) {
GLES20.glCompressedTexImage2D(GLES20.GL_TEXTURE_2D, i, compressionFormat, w, h, 0, buffer[i].capacity(), buffer[i]);
w = w > 1 ? w / 2 : 1;
h = h > 1 ? h / 2 : 1;
}
}
}
} else
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapFormat, texture, 0);
if(mipmap && compressionType == CompressionType.NONE)
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
} else {
mShouldValidateTextures = true;
}
TextureInfo textureInfo = mCurrentValidatingTexInfo == null ? new TextureInfo(textureId, textureType) : mCurrentValidatingTexInfo;
if(mCurrentValidatingTexInfo == null) {
textureInfo.setWidth(width);
textureInfo.setHeight(height);
textureInfo.setBitmapConfig(bitmapConfig);
textureInfo.setMipmap(mipmap);
textureInfo.setWrapType(wrapType);
textureInfo.setFilterType(filterType);
textureInfo.shouldRecycle(recycle);
textureInfo.setCompressionType(compressionType);
textureInfo.setBuffer(buffer);
if(compressionType != CompressionType.NONE){
textureInfo.setInternalFormat(compressionFormat);
}
if(!recycle && compressionType == CompressionType.NONE)
textureInfo.setTexture(texture);
} else {
textureInfo.setTextureId(textureId);
}
for (int i = 0; i < buffer.length; i++) {
if(buffer[i] != null) {
buffer[i].limit(0);
}
}
buffer = null;
if(!isExistingTexture && mCurrentValidatingTexInfo == null)
mTextureInfoList.add(textureInfo);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
return textureInfo;
}
|
diff --git a/src/com/android/contacts/ViewContactActivity.java b/src/com/android/contacts/ViewContactActivity.java
index 1bf67d0..18aa873 100644
--- a/src/com/android/contacts/ViewContactActivity.java
+++ b/src/com/android/contacts/ViewContactActivity.java
@@ -1,1438 +1,1433 @@
/*
* Copyright (C) 2007 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.contacts;
import com.android.contacts.Collapser.Collapsible;
import com.android.contacts.model.ContactsSource;
import com.android.contacts.model.Sources;
import com.android.contacts.model.ContactsSource.DataKind;
import com.android.contacts.ui.EditContactActivity;
import com.android.contacts.util.Constants;
import com.android.contacts.util.DataStatus;
import com.android.contacts.util.NotifyingAsyncQueryHandler;
import com.android.internal.telephony.ITelephony;
import com.android.internal.widget.ContactHeaderWidget;
import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Entity;
import android.content.EntityIterator;
import android.content.Intent;
import android.content.Entity.NamedContentValues;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.net.Uri;
import android.net.WebAddress;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.AggregationExceptions;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.DisplayNameSources;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContactsEntity;
import android.provider.ContactsContract.StatusUpdates;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.CommonDataKinds.Website;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//Wysie
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.List;
/**
* Displays the details of a specific contact.
*/
public class ViewContactActivity extends Activity
implements View.OnCreateContextMenuListener, DialogInterface.OnClickListener,
AdapterView.OnItemClickListener, NotifyingAsyncQueryHandler.AsyncQueryListener {
private static final String TAG = "ViewContact";
private static final boolean SHOW_SEPARATORS = false;
private static final int DIALOG_CONFIRM_DELETE = 1;
private static final int DIALOG_CONFIRM_READONLY_DELETE = 2;
private static final int DIALOG_CONFIRM_MULTIPLE_DELETE = 3;
private static final int DIALOG_CONFIRM_READONLY_HIDE = 4;
private static final int REQUEST_JOIN_CONTACT = 1;
private static final int REQUEST_EDIT_CONTACT = 2;
public static final int MENU_ITEM_MAKE_DEFAULT = 3;
protected Uri mLookupUri;
private ContentResolver mResolver;
private ViewAdapter mAdapter;
private int mNumPhoneNumbers = 0;
/**
* A list of distinct contact IDs included in the current contact.
*/
private ArrayList<Long> mRawContactIds = new ArrayList<Long>();
/* package */ ArrayList<ViewEntry> mPhoneEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mSmsEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mEmailEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mPostalEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mImEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mNicknameEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mOrganizationEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mGroupEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mOtherEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ArrayList<ViewEntry>> mSections = new ArrayList<ArrayList<ViewEntry>>();
private Cursor mCursor;
protected ContactHeaderWidget mContactHeaderWidget;
private NotifyingAsyncQueryHandler mHandler;
protected LayoutInflater mInflater;
protected int mReadOnlySourcesCnt;
protected int mWritableSourcesCnt;
protected boolean mAllRestricted;
protected Uri mPrimaryPhoneUri = null;
protected ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>();
private static final int TOKEN_ENTITIES = 0;
private static final int TOKEN_STATUSES = 1;
private boolean mHasEntities = false;
private boolean mHasStatuses = false;
private long mNameRawContactId = -1;
private int mDisplayNameSource = DisplayNameSources.UNDEFINED;
private ArrayList<Entity> mEntities = Lists.newArrayList();
private HashMap<Long, DataStatus> mStatuses = Maps.newHashMap();
/**
* The view shown if the detail list is empty.
* We set this to the list view when first bind the adapter, so that it won't be shown while
* we're loading data.
*/
private View mEmptyView;
private ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
if (mCursor != null && !mCursor.isClosed()) {
startEntityQuery();
}
}
};
public void onClick(DialogInterface dialog, int which) {
closeCursor();
getContentResolver().delete(mLookupUri, null, null);
finish();
}
private ListView mListView;
private boolean mShowSmsLinksForAllPhones;
//Wysie
private SharedPreferences ePrefs;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
ePrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
final Intent intent = getIntent();
Uri data = intent.getData();
String authority = data.getAuthority();
if (ContactsContract.AUTHORITY.equals(authority)) {
mLookupUri = data;
} else if (android.provider.Contacts.AUTHORITY.equals(authority)) {
final long rawContactId = ContentUris.parseId(data);
mLookupUri = RawContacts.getContactLookupUri(getContentResolver(),
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
}
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.contact_card_layout);
mContactHeaderWidget = (ContactHeaderWidget) findViewById(R.id.contact_header_widget);
mContactHeaderWidget.showStar(true);
mContactHeaderWidget.setExcludeMimes(new String[] {
Contacts.CONTENT_ITEM_TYPE
});
mHandler = new NotifyingAsyncQueryHandler(this, this);
mListView = (ListView) findViewById(R.id.contact_data);
mListView.setOnCreateContextMenuListener(this);
mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY);
mListView.setOnItemClickListener(this);
// Don't set it to mListView yet. We do so later when we bind the adapter.
mEmptyView = findViewById(android.R.id.empty);
mResolver = getContentResolver();
// Build the list of sections. The order they're added to mSections dictates the
// order they are displayed in the list.
mSections.add(mPhoneEntries);
mSections.add(mSmsEntries);
mSections.add(mEmailEntries);
mSections.add(mImEntries);
mSections.add(mPostalEntries);
mSections.add(mNicknameEntries);
mSections.add(mOrganizationEntries);
mSections.add(mGroupEntries);
mSections.add(mOtherEntries);
//TODO Read this value from a preference
//mShowSmsLinksForAllPhones = true;
}
@Override
protected void onResume() {
super.onResume();
//Wysie: Read from preference
mShowSmsLinksForAllPhones = !ePrefs.getBoolean("contacts_show_text_mobile_only", false);
startEntityQuery();
}
@Override
protected void onPause() {
super.onPause();
closeCursor();
}
@Override
protected void onDestroy() {
super.onDestroy();
closeCursor();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CONFIRM_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.deleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_READONLY_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.readOnlyContactDeleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_MULTIPLE_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.multipleContactDeleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_READONLY_HIDE: {
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.readOnlyContactWarning)
.setPositiveButton(android.R.string.ok, this)
.create();
}
}
return null;
}
/** {@inheritDoc} */
public void onQueryComplete(int token, Object cookie, final Cursor cursor) {
if (token == TOKEN_STATUSES) {
try {
// Read available social rows and consider binding
readStatuses(cursor);
} finally {
if (cursor != null) {
cursor.close();
}
}
considerBindData();
return;
}
// One would think we could just iterate over the Cursor
// directly here, as the result set should be small, and we've
// already run the query in an AsyncTask, but a lot of ANRs
// were being reported in this code nonetheless. See bug
// 2539603 for details. The real bug which makes this result
// set huge and CPU-heavy may be elsewhere.
// TODO: if we keep this async, perhaps the entity iteration
// should also be original AsyncTask, rather than ping-ponging
// between threads like this.
final ArrayList<Entity> oldEntities = mEntities;
(new AsyncTask<Void, Void, ArrayList<Entity>>() {
@Override
protected ArrayList<Entity> doInBackground(Void... params) {
ArrayList<Entity> newEntities = new ArrayList<Entity>(cursor.getCount());
EntityIterator iterator = RawContacts.newEntityIterator(cursor);
try {
while (iterator.hasNext()) {
Entity entity = iterator.next();
newEntities.add(entity);
}
} finally {
iterator.close();
}
return newEntities;
}
@Override
protected void onPostExecute(ArrayList<Entity> newEntities) {
if (newEntities == null) {
// There was an error loading.
return;
}
synchronized (ViewContactActivity.this) {
if (mEntities != oldEntities) {
// Multiple async tasks were in flight and we
// lost the race.
return;
}
mEntities = newEntities;
mHasEntities = true;
}
considerBindData();
}
}).execute();
}
private long getRefreshedContactId() {
Uri freshContactUri = Contacts.lookupContact(getContentResolver(), mLookupUri);
if (freshContactUri != null) {
return ContentUris.parseId(freshContactUri);
}
return -1;
}
/**
* Read from the given {@link Cursor} and build a set of {@link DataStatus}
* objects to match any valid statuses found.
*/
private synchronized void readStatuses(Cursor cursor) {
mStatuses.clear();
// Walk found statuses, creating internal row for each
while (cursor.moveToNext()) {
final DataStatus status = new DataStatus(cursor);
final long dataId = cursor.getLong(StatusQuery._ID);
mStatuses.put(dataId, status);
}
mHasStatuses = true;
}
private static Cursor setupContactCursor(ContentResolver resolver, Uri lookupUri) {
if (lookupUri == null) {
return null;
}
final List<String> segments = lookupUri.getPathSegments();
if (segments.size() != 4) {
return null;
}
// Contains an Id.
final long uriContactId = Long.parseLong(segments.get(3));
final String uriLookupKey = Uri.encode(segments.get(2));
final Uri dataUri = Uri.withAppendedPath(
ContentUris.withAppendedId(Contacts.CONTENT_URI, uriContactId),
Contacts.Data.CONTENT_DIRECTORY);
// This cursor has several purposes:
// - Fetch NAME_RAW_CONTACT_ID and DISPLAY_NAME_SOURCE
// - Fetch the lookup-key to ensure we are looking at the right record
// - Watcher for change events
Cursor cursor = resolver.query(dataUri,
new String[] {
Contacts.NAME_RAW_CONTACT_ID,
Contacts.DISPLAY_NAME_SOURCE,
Contacts.LOOKUP_KEY
}, null, null, null);
if (cursor.moveToFirst()) {
String lookupKey =
cursor.getString(cursor.getColumnIndex(Contacts.LOOKUP_KEY));
if (!lookupKey.equals(uriLookupKey)) {
// ID and lookup key do not match
cursor.close();
return null;
}
return cursor;
} else {
cursor.close();
return null;
}
}
private synchronized void startEntityQuery() {
closeCursor();
// Interprete mLookupUri
mCursor = setupContactCursor(mResolver, mLookupUri);
// If mCursor is null now we did not succeed in using the Uri's Id (or it didn't contain
// a Uri). Instead we now have to use the lookup key to find the record
if (mCursor == null) {
mLookupUri = Contacts.getLookupUri(getContentResolver(), mLookupUri);
mCursor = setupContactCursor(mResolver, mLookupUri);
}
// If mCursor is still null, we were unsuccessful in finding the record
if (mCursor == null) {
mNameRawContactId = -1;
mDisplayNameSource = DisplayNameSources.UNDEFINED;
// TODO either figure out a way to prevent a flash of black background or
// use some other UI than a toast
Toast.makeText(this, R.string.invalidContactMessage, Toast.LENGTH_SHORT).show();
Log.e(TAG, "invalid contact uri: " + mLookupUri);
finish();
return;
}
final long contactId = ContentUris.parseId(mLookupUri);
mNameRawContactId =
mCursor.getLong(mCursor.getColumnIndex(Contacts.NAME_RAW_CONTACT_ID));
mDisplayNameSource =
mCursor.getInt(mCursor.getColumnIndex(Contacts.DISPLAY_NAME_SOURCE));
mCursor.registerContentObserver(mObserver);
// Clear flags and start queries to data and status
mHasEntities = false;
mHasStatuses = false;
mHandler.startQuery(TOKEN_ENTITIES, null, RawContactsEntity.CONTENT_URI, null,
RawContacts.CONTACT_ID + "=?", new String[] {
String.valueOf(contactId)
}, null);
final Uri dataUri = Uri.withAppendedPath(
ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId),
Contacts.Data.CONTENT_DIRECTORY);
mHandler.startQuery(TOKEN_STATUSES, null, dataUri, StatusQuery.PROJECTION,
StatusUpdates.PRESENCE + " IS NOT NULL OR " + StatusUpdates.STATUS
+ " IS NOT NULL", null, null);
mContactHeaderWidget.bindFromContactLookupUri(mLookupUri);
}
private void closeCursor() {
if (mCursor != null) {
mCursor.unregisterContentObserver(mObserver);
mCursor.close();
mCursor = null;
}
}
/**
* Consider binding views after any of several background queries has
* completed. We check internal flags and only bind when all data has
* arrived.
*/
private void considerBindData() {
if (mHasEntities && mHasStatuses) {
bindData();
}
}
private void bindData() {
// Build up the contact entries
buildEntries();
// Collapse similar data items in select sections.
Collapser.collapseList(mPhoneEntries);
Collapser.collapseList(mSmsEntries);
Collapser.collapseList(mEmailEntries);
Collapser.collapseList(mPostalEntries);
Collapser.collapseList(mImEntries);
if (mAdapter == null) {
mAdapter = new ViewAdapter(this, mSections);
mListView.setAdapter(mAdapter);
} else {
mAdapter.setSections(mSections, SHOW_SEPARATORS);
}
mListView.setEmptyView(mEmptyView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// Only allow edit when we have at least one raw_contact id
final boolean hasRawContact = (mRawContactIds.size() > 0);
menu.findItem(R.id.menu_edit).setEnabled(hasRawContact);
// Only allow share when unrestricted contacts available
menu.findItem(R.id.menu_share).setEnabled(!mAllRestricted);
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return;
}
// This can be null sometimes, don't crash...
if (info == null) {
Log.e(TAG, "bad menuInfo");
return;
}
ViewEntry entry = ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS);
menu.setHeaderTitle(R.string.contactOptionsTitle);
if (entry.mimetype.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_call).setIntent(entry.intent);
menu.add(0, 0, 0, R.string.menu_sendSMS).setIntent(entry.secondaryIntent);
if (!entry.isPrimary) {
menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultNumber);
}
} else if (entry.mimetype.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_sendEmail).setIntent(entry.intent);
if (!entry.isPrimary) {
menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultEmail);
}
} else if (entry.mimetype.equals(CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_viewAddress).setIntent(entry.intent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit: {
Long rawContactIdToEdit = null;
if (mRawContactIds.size() > 0) {
rawContactIdToEdit = mRawContactIds.get(0);
} else {
// There is no rawContact to edit.
break;
}
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactIdToEdit);
startActivityForResult(new Intent(Intent.ACTION_EDIT, rawContactUri),
REQUEST_EDIT_CONTACT);
break;
}
case R.id.menu_delete: {
// Get confirmation
if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) {
showDialog(DIALOG_CONFIRM_READONLY_DELETE);
} else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) {
showDialog(DIALOG_CONFIRM_READONLY_HIDE);
} else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) {
showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE);
} else {
showDialog(DIALOG_CONFIRM_DELETE);
}
return true;
}
case R.id.menu_join: {
showJoinAggregateActivity();
return true;
}
case R.id.menu_options: {
showOptionsActivity();
return true;
}
case R.id.menu_share: {
if (mAllRestricted) return false;
// TODO: Keep around actual LOOKUP_KEY, or formalize method of extracting
final String lookupKey = Uri.encode(mLookupUri.getPathSegments().get(2));
final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(Contacts.CONTENT_VCARD_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, shareUri);
// Launch chooser to share contact via
final CharSequence chooseTitle = getText(R.string.share_via);
final Intent chooseIntent = Intent.createChooser(intent, chooseTitle);
try {
startActivity(chooseIntent);
} catch (ActivityNotFoundException ex) {
Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_MAKE_DEFAULT: {
if (makeItemDefault(item)) {
return true;
}
break;
}
}
return super.onContextItemSelected(item);
}
private boolean makeItemDefault(MenuItem item) {
ViewEntry entry = getViewEntryForMenuItem(item);
if (entry == null) {
return false;
}
// Update the primary values in the data record.
ContentValues values = new ContentValues(1);
values.put(Data.IS_SUPER_PRIMARY, 1);
getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, entry.id),
values, null, null);
startEntityQuery();
return true;
}
/**
* Shows a list of aggregates that can be joined into the currently viewed aggregate.
*/
public void showJoinAggregateActivity() {
long freshId = getRefreshedContactId();
if (freshId > 0) {
String displayName = null;
if (mCursor.moveToFirst()) {
displayName = mCursor.getString(0);
}
Intent intent = new Intent(ContactsListActivity.JOIN_AGGREGATE);
intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_ID, freshId);
if (displayName != null) {
intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_NAME, displayName);
}
startActivityForResult(intent, REQUEST_JOIN_CONTACT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_JOIN_CONTACT) {
if (resultCode == RESULT_OK && intent != null) {
final long contactId = ContentUris.parseId(intent.getData());
joinAggregate(contactId);
}
} else if (requestCode == REQUEST_EDIT_CONTACT) {
if (resultCode == EditContactActivity.RESULT_CLOSE_VIEW_ACTIVITY) {
finish();
} else if (resultCode == Activity.RESULT_OK) {
mLookupUri = intent.getData();
if (mLookupUri == null) {
finish();
}
}
}
}
private void joinAggregate(final long contactId) {
Cursor c = mResolver.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + "=" + contactId, null, null);
try {
while(c.moveToNext()) {
long rawContactId = c.getLong(0);
setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_TOGETHER);
}
} finally {
c.close();
}
Toast.makeText(this, R.string.contactsJoinedMessage, Toast.LENGTH_LONG).show();
startEntityQuery();
}
/**
* Given a contact ID sets an aggregation exception to either join the contact with the
* current aggregate or split off.
*/
protected void setAggregationException(long rawContactId, int exceptionType) {
ContentValues values = new ContentValues(3);
for (long aRawContactId : mRawContactIds) {
if (aRawContactId != rawContactId) {
values.put(AggregationExceptions.RAW_CONTACT_ID1, aRawContactId);
values.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId);
values.put(AggregationExceptions.TYPE, exceptionType);
mResolver.update(AggregationExceptions.CONTENT_URI, values, null, null);
}
}
}
private void showOptionsActivity() {
final Intent intent = new Intent(this, ContactOptionsActivity.class);
intent.setData(mLookupUri);
startActivity(intent);
}
private ViewEntry getViewEntryForMenuItem(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return null;
}
return ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_CALL: {
try {
ITelephony phone = ITelephony.Stub.asInterface(
ServiceManager.checkService("phone"));
if (phone != null && !phone.isIdle()) {
// Skip out and let the key be handled at a higher level
break;
}
} catch (RemoteException re) {
// Fall through and try to call the contact
}
int index = mListView.getSelectedItemPosition();
if (index != -1) {
ViewEntry entry = ViewAdapter.getEntry(mSections, index, SHOW_SEPARATORS);
if (entry != null &&
entry.intent.getAction() == Intent.ACTION_CALL_PRIVILEGED) {
startActivity(entry.intent);
return true;
}
//FIXME: I think this do same has mNumPhoneNumbers != 0 from Wysie need
} else if (mPrimaryPhoneUri != null) {
// There isn't anything selected, call the default number
final Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
mPrimaryPhoneUri);
startActivity(intent);
return true;
} else if (mNumPhoneNumbers != 0) {
// There isn't anything selected; pick the correct number to dial.
long freshContactId = getRefreshedContactId();
if(!ContactsUtils.callOrSmsContact(freshContactId, this, false)) {
signalError();
return false;
}
}
return false;
}
case KeyEvent.KEYCODE_DEL: {
if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) {
showDialog(DIALOG_CONFIRM_READONLY_DELETE);
} else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) {
showDialog(DIALOG_CONFIRM_READONLY_HIDE);
} else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) {
showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE);
} else {
showDialog(DIALOG_CONFIRM_DELETE);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
ViewEntry entry = ViewAdapter.getEntry(mSections, position, SHOW_SEPARATORS);
if (entry != null) {
Intent intent = entry.intent;
if (intent != null) {
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity found for intent: " + intent);
signalError();
}
} else {
signalError();
}
} else {
signalError();
}
}
/**
* Signal an error to the user via a beep, or some other method.
*/
private void signalError() {
//TODO: implement this when we have the sonification APIs
}
/**
* Build up the entries to display on the screen.
*
* @param personCursor the URI for the contact being displayed
*/
private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mAllRestricted = true;
mPrimaryPhoneUri = null;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
// Mark when this contact has any unrestricted components
final boolean isRestricted = entValues.getAsInteger(RawContacts.IS_RESTRICTED) != 0;
if (!isRestricted) mAllRestricted = false;
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
// Remember super-primary phone
if (isSuperPrimary) mPrimaryPhoneUri = entry.uri;
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
//Wysie: Workaround for the entry.type bug, since entry.type always returns -1
- Integer type;
- try {
- type = entryValues.getAsInteger(Phone.TYPE);
- } catch (NullPointerException e) {
- type = CommonDataKinds.Phone.TYPE_HOME;
- }
+ Integer type = entryValues.getAsInteger(Phone.TYPE);
//Wysie: Bug here, entry.type always returns -1.
- if (/*entry.type*/type == CommonDataKinds.Phone.TYPE_MOBILE || mShowSmsLinksForAllPhones) {
+ if (/*entry.type*/type.intValue() == (CommonDataKinds.Phone.TYPE_MOBILE) || mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
Intent i = startNavigation(entry.data);
if (i != null) {
entry.secondaryIntent = i;
// Add a navigation entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if (Organization.CONTENT_ITEM_TYPE.equals(mimeType) &&
(hasData || !TextUtils.isEmpty(entry.label))) {
// Build organization entries
final boolean isNameRawContact = (mNameRawContactId == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mDisplayNameSource == DisplayNameSources.ORGANIZATION
&& (!hasData || TextUtils.isEmpty(entry.label));
if (!duplicatesTitle) {
entry.uri = null;
if (TextUtils.isEmpty(entry.label)) {
entry.label = entry.data;
entry.data = "";
}
mOrganizationEntries.add(entry);
}
} else if (Nickname.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build nickname entries
final boolean isNameRawContact = (mNameRawContactId == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mDisplayNameSource == DisplayNameSources.NICKNAME;
if (!duplicatesTitle) {
entry.uri = null;
mNicknameEntries.add(entry);
}
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 100;
mOtherEntries.add(entry);
} else if (Website.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
try {
WebAddress webAddress = new WebAddress(entry.data);
entry.intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(webAddress.toString()));
} catch (ParseException e) {
Log.e(TAG, "Couldn't parse website: " + entry.data);
}
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
static String buildActionString(DataKind kind, ContentValues values, boolean lowerCase,
Context context) {
if (kind.actionHeader == null) {
return null;
}
CharSequence actionHeader = kind.actionHeader.inflateUsing(context, values);
if (actionHeader == null) {
return null;
}
return lowerCase ? actionHeader.toString().toLowerCase() : actionHeader.toString();
}
static String buildDataString(DataKind kind, ContentValues values, Context context) {
if (kind.actionBody == null) {
return null;
}
CharSequence actionBody = kind.actionBody.inflateUsing(context, values);
return actionBody == null ? null : actionBody.toString();
}
/**
* A basic structure with the data for a contact entry in the list.
*/
static class ViewEntry extends ContactEntryAdapter.Entry implements Collapsible<ViewEntry> {
public Context context = null;
public String resPackageName = null;
public int actionIcon = -1;
public boolean isPrimary = false;
public int secondaryActionIcon = -1;
public Intent intent;
public Intent secondaryIntent = null;
public int maxLabelLines = 1;
public ArrayList<Long> ids = new ArrayList<Long>();
public int collapseCount = 0;
public int presence = -1;
public CharSequence footerLine = null;
private ViewEntry() {
}
/**
* Build new {@link ViewEntry} and populate from the given values.
*/
public static ViewEntry fromValues(Context context, String mimeType, DataKind kind,
long rawContactId, long dataId, ContentValues values) {
final ViewEntry entry = new ViewEntry();
entry.context = context;
entry.contactId = rawContactId;
entry.id = dataId;
entry.uri = ContentUris.withAppendedId(Data.CONTENT_URI, entry.id);
entry.mimetype = mimeType;
entry.label = buildActionString(kind, values, false, context);
entry.data = buildDataString(kind, values, context);
if (kind.typeColumn != null && values.containsKey(kind.typeColumn)) {
entry.type = values.getAsInteger(kind.typeColumn);
}
if (kind.iconRes > 0) {
entry.resPackageName = kind.resPackageName;
entry.actionIcon = kind.iconRes;
}
return entry;
}
/**
* Apply given {@link DataStatus} values over this {@link ViewEntry}
*
* @param fillData When true, the given status replaces {@link #data}
* and {@link #footerLine}. Otherwise only {@link #presence}
* is updated.
*/
public ViewEntry applyStatus(DataStatus status, boolean fillData) {
presence = status.getPresence();
if (fillData && status.isValid()) {
this.data = status.getStatus().toString();
this.footerLine = status.getTimestampLabel(context);
}
return this;
}
public boolean collapseWith(ViewEntry entry) {
// assert equal collapse keys
if (!shouldCollapseWith(entry)) {
return false;
}
// Choose the label associated with the highest type precedence.
if (TypePrecedence.getTypePrecedence(mimetype, type)
> TypePrecedence.getTypePrecedence(entry.mimetype, entry.type)) {
type = entry.type;
label = entry.label;
}
// Choose the max of the maxLines and maxLabelLines values.
maxLines = Math.max(maxLines, entry.maxLines);
maxLabelLines = Math.max(maxLabelLines, entry.maxLabelLines);
// Choose the presence with the highest precedence.
if (StatusUpdates.getPresencePrecedence(presence)
< StatusUpdates.getPresencePrecedence(entry.presence)) {
presence = entry.presence;
}
// If any of the collapsed entries are primary make the whole thing primary.
isPrimary = entry.isPrimary ? true : isPrimary;
// uri, and contactdId, shouldn't make a difference. Just keep the original.
// Keep track of all the ids that have been collapsed with this one.
ids.add(entry.id);
collapseCount++;
return true;
}
public boolean shouldCollapseWith(ViewEntry entry) {
if (entry == null) {
return false;
}
if (!ContactsUtils.shouldCollapse(context, mimetype, data, entry.mimetype,
entry.data)) {
return false;
}
if (!TextUtils.equals(mimetype, entry.mimetype)
|| !ContactsUtils.areIntentActionEqual(intent, entry.intent)
|| !ContactsUtils.areIntentActionEqual(secondaryIntent, entry.secondaryIntent)
|| actionIcon != entry.actionIcon) {
return false;
}
return true;
}
}
/** Cache of the children views of a row */
static class ViewCache {
public TextView label;
public TextView data;
public TextView footer;
public ImageView actionIcon;
public ImageView presenceIcon;
public ImageView primaryIcon;
public ImageView secondaryActionButton;
public View secondaryActionDivider;
// Need to keep track of this too
ViewEntry entry;
}
private final class ViewAdapter extends ContactEntryAdapter<ViewEntry>
implements View.OnClickListener {
ViewAdapter(Context context, ArrayList<ArrayList<ViewEntry>> sections) {
super(context, sections, SHOW_SEPARATORS);
}
public void onClick(View v) {
Intent intent = (Intent) v.getTag();
startActivity(intent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewEntry entry = getEntry(mSections, position, false);
View v;
ViewCache views;
// Check to see if we can reuse convertView
if (convertView != null) {
v = convertView;
views = (ViewCache) v.getTag();
} else {
// Create a new view if needed
v = mInflater.inflate(R.layout.list_item_text_icons, parent, false);
// Cache the children
views = new ViewCache();
views.label = (TextView) v.findViewById(android.R.id.text1);
views.data = (TextView) v.findViewById(android.R.id.text2);
views.footer = (TextView) v.findViewById(R.id.footer);
views.actionIcon = (ImageView) v.findViewById(R.id.action_icon);
views.primaryIcon = (ImageView) v.findViewById(R.id.primary_icon);
views.presenceIcon = (ImageView) v.findViewById(R.id.presence_icon);
views.secondaryActionButton = (ImageView) v.findViewById(
R.id.secondary_action_button);
views.secondaryActionButton.setOnClickListener(this);
views.secondaryActionDivider = v.findViewById(R.id.divider);
v.setTag(views);
}
// Update the entry in the view cache
views.entry = entry;
// Bind the data to the view
bindView(v, entry);
return v;
}
@Override
protected View newView(int position, ViewGroup parent) {
// getView() handles this
throw new UnsupportedOperationException();
}
@Override
protected void bindView(View view, ViewEntry entry) {
final Resources resources = mContext.getResources();
ViewCache views = (ViewCache) view.getTag();
// Set the label
TextView label = views.label;
setMaxLines(label, entry.maxLabelLines);
label.setText(entry.label);
// Set the data
TextView data = views.data;
if (data != null) {
if (entry.mimetype.equals(Phone.CONTENT_ITEM_TYPE)
|| entry.mimetype.equals(Constants.MIME_SMS_ADDRESS)) {
data.setText(PhoneNumberUtils.formatNumber(entry.data));
} else {
data.setText(entry.data);
}
setMaxLines(data, entry.maxLines);
}
// Set the footer
if (!TextUtils.isEmpty(entry.footerLine)) {
views.footer.setText(entry.footerLine);
views.footer.setVisibility(View.VISIBLE);
} else {
views.footer.setVisibility(View.GONE);
}
// Set the primary icon
views.primaryIcon.setVisibility(entry.isPrimary ? View.VISIBLE : View.GONE);
// Set the action icon
ImageView action = views.actionIcon;
if (entry.actionIcon != -1) {
Drawable actionIcon;
if (entry.resPackageName != null) {
// Load external resources through PackageManager
actionIcon = mContext.getPackageManager().getDrawable(entry.resPackageName,
entry.actionIcon, null);
} else {
actionIcon = resources.getDrawable(entry.actionIcon);
}
action.setImageDrawable(actionIcon);
action.setVisibility(View.VISIBLE);
} else {
// Things should still line up as if there was an icon, so make it invisible
action.setVisibility(View.INVISIBLE);
}
// Set the presence icon
Drawable presenceIcon = ContactPresenceIconUtil.getPresenceIcon(
mContext, entry.presence);
ImageView presenceIconView = views.presenceIcon;
if (presenceIcon != null) {
presenceIconView.setImageDrawable(presenceIcon);
presenceIconView.setVisibility(View.VISIBLE);
} else {
presenceIconView.setVisibility(View.GONE);
}
// Set the secondary action button
ImageView secondaryActionView = views.secondaryActionButton;
Drawable secondaryActionIcon = null;
if (entry.secondaryActionIcon != -1) {
secondaryActionIcon = resources.getDrawable(entry.secondaryActionIcon);
}
if (entry.secondaryIntent != null && secondaryActionIcon != null) {
secondaryActionView.setImageDrawable(secondaryActionIcon);
secondaryActionView.setTag(entry.secondaryIntent);
secondaryActionView.setVisibility(View.VISIBLE);
views.secondaryActionDivider.setVisibility(View.VISIBLE);
} else {
secondaryActionView.setVisibility(View.GONE);
views.secondaryActionDivider.setVisibility(View.GONE);
}
}
private void setMaxLines(TextView textView, int maxLines) {
if (maxLines == 1) {
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
} else {
textView.setSingleLine(false);
textView.setMaxLines(maxLines);
textView.setEllipsize(null);
}
}
}
private interface StatusQuery {
final String[] PROJECTION = new String[] {
Data._ID,
Data.STATUS,
Data.STATUS_RES_PACKAGE,
Data.STATUS_ICON,
Data.STATUS_LABEL,
Data.STATUS_TIMESTAMP,
Data.PRESENCE,
};
final int _ID = 0;
}
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData,
boolean globalSearch) {
if (globalSearch) {
super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
} else {
ContactsSearchManager.startSearch(this, initialQuery);
}
}
//Wysie
public boolean isIntentAvailable(Intent intent) {
final PackageManager packageManager = this.getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
//Wysie: Navigation code. Adapted from rac2030's NavStarter.
//http://code.google.com/p/andrac/source/browse/trunk/NavWidget/src/ch/racic/android/gnav/NavSearch.java
public Intent startNavigation(String address) {
address = address.replace('#', ' ');
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://maps.google.com/maps?myl=saddr&daddr=" + address + "&dirflg=d&nav=1"));
i.addFlags(0x10800000);
i.setClassName("com.google.android.apps.m4ps", "com.google.android.maps.driveabout.app.NavigationActivity");
if (isIntentAvailable(i)) {
return i;
}
else {
i.setClassName("com.google.android.apps.maps", "com.google.android.maps.driveabout.app.NavigationActivity");
if (isIntentAvailable(i)) {
return i;
}
else {
return null;
}
}
}
}
| false | true | private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mAllRestricted = true;
mPrimaryPhoneUri = null;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
// Mark when this contact has any unrestricted components
final boolean isRestricted = entValues.getAsInteger(RawContacts.IS_RESTRICTED) != 0;
if (!isRestricted) mAllRestricted = false;
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
// Remember super-primary phone
if (isSuperPrimary) mPrimaryPhoneUri = entry.uri;
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
//Wysie: Workaround for the entry.type bug, since entry.type always returns -1
Integer type;
try {
type = entryValues.getAsInteger(Phone.TYPE);
} catch (NullPointerException e) {
type = CommonDataKinds.Phone.TYPE_HOME;
}
//Wysie: Bug here, entry.type always returns -1.
if (/*entry.type*/type == CommonDataKinds.Phone.TYPE_MOBILE || mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
Intent i = startNavigation(entry.data);
if (i != null) {
entry.secondaryIntent = i;
// Add a navigation entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if (Organization.CONTENT_ITEM_TYPE.equals(mimeType) &&
(hasData || !TextUtils.isEmpty(entry.label))) {
// Build organization entries
final boolean isNameRawContact = (mNameRawContactId == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mDisplayNameSource == DisplayNameSources.ORGANIZATION
&& (!hasData || TextUtils.isEmpty(entry.label));
if (!duplicatesTitle) {
entry.uri = null;
if (TextUtils.isEmpty(entry.label)) {
entry.label = entry.data;
entry.data = "";
}
mOrganizationEntries.add(entry);
}
} else if (Nickname.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build nickname entries
final boolean isNameRawContact = (mNameRawContactId == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mDisplayNameSource == DisplayNameSources.NICKNAME;
if (!duplicatesTitle) {
entry.uri = null;
mNicknameEntries.add(entry);
}
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 100;
mOtherEntries.add(entry);
} else if (Website.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
try {
WebAddress webAddress = new WebAddress(entry.data);
entry.intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(webAddress.toString()));
} catch (ParseException e) {
Log.e(TAG, "Couldn't parse website: " + entry.data);
}
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
| private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mAllRestricted = true;
mPrimaryPhoneUri = null;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
// Mark when this contact has any unrestricted components
final boolean isRestricted = entValues.getAsInteger(RawContacts.IS_RESTRICTED) != 0;
if (!isRestricted) mAllRestricted = false;
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
// Remember super-primary phone
if (isSuperPrimary) mPrimaryPhoneUri = entry.uri;
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
//Wysie: Workaround for the entry.type bug, since entry.type always returns -1
Integer type = entryValues.getAsInteger(Phone.TYPE);
//Wysie: Bug here, entry.type always returns -1.
if (/*entry.type*/type.intValue() == (CommonDataKinds.Phone.TYPE_MOBILE) || mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
Intent i = startNavigation(entry.data);
if (i != null) {
entry.secondaryIntent = i;
// Add a navigation entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if (Organization.CONTENT_ITEM_TYPE.equals(mimeType) &&
(hasData || !TextUtils.isEmpty(entry.label))) {
// Build organization entries
final boolean isNameRawContact = (mNameRawContactId == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mDisplayNameSource == DisplayNameSources.ORGANIZATION
&& (!hasData || TextUtils.isEmpty(entry.label));
if (!duplicatesTitle) {
entry.uri = null;
if (TextUtils.isEmpty(entry.label)) {
entry.label = entry.data;
entry.data = "";
}
mOrganizationEntries.add(entry);
}
} else if (Nickname.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build nickname entries
final boolean isNameRawContact = (mNameRawContactId == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mDisplayNameSource == DisplayNameSources.NICKNAME;
if (!duplicatesTitle) {
entry.uri = null;
mNicknameEntries.add(entry);
}
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 100;
mOtherEntries.add(entry);
} else if (Website.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
try {
WebAddress webAddress = new WebAddress(entry.data);
entry.intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(webAddress.toString()));
} catch (ParseException e) {
Log.e(TAG, "Couldn't parse website: " + entry.data);
}
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
|
diff --git a/fabric/fabric-agent/src/test/java/org/fusesource/fabric/agent/resolver/ResolverTest.java b/fabric/fabric-agent/src/test/java/org/fusesource/fabric/agent/resolver/ResolverTest.java
index 4f8e571c2..4ae8c28a4 100644
--- a/fabric/fabric-agent/src/test/java/org/fusesource/fabric/agent/resolver/ResolverTest.java
+++ b/fabric/fabric-agent/src/test/java/org/fusesource/fabric/agent/resolver/ResolverTest.java
@@ -1,130 +1,131 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.agent.resolver;
import aQute.lib.osgi.Macro;
import aQute.lib.osgi.Processor;
import org.apache.felix.framework.Felix;
import org.apache.felix.resolver.ResolverImpl;
import org.apache.karaf.features.BundleInfo;
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.Repository;
import org.fusesource.common.util.Manifests;
import org.fusesource.fabric.agent.DeploymentBuilder;
import org.fusesource.fabric.agent.download.DownloadManager;
import org.fusesource.fabric.agent.mvn.MavenConfigurationImpl;
import org.fusesource.fabric.agent.mvn.MavenSettingsImpl;
import org.fusesource.fabric.agent.mvn.PropertiesPropertyResolver;
import org.fusesource.fabric.agent.utils.AgentUtils;
import org.fusesource.fabric.fab.osgi.FabBundleInfo;
import org.junit.Test;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleRevisions;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.resource.Wire;
import org.osgi.service.resolver.ResolveContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.fusesource.fabric.agent.resolver.UriNamespace.getUri;
import static org.fusesource.fabric.agent.utils.AgentUtils.downloadBundles;
import static org.junit.Assert.assertEquals;
/**
*/
public class ResolverTest {
@Test
public void testResolve() throws Exception {
System.setProperty("karaf.data", new File("target/karaf/data").getAbsolutePath());
System.setProperty("karaf.home", new File("target/karaf").getAbsolutePath());
Properties properties = new Properties();
properties.setProperty("mvn.localRepository", "/Users/gnodet/.m2/repository/@snapshots");
properties.setProperty("mvn.repositories", "http://repo1.maven.org/maven2/,http://repo.fusesource.com/nexus/content/repositories/ea");
PropertiesPropertyResolver propertyResolver = new PropertiesPropertyResolver(properties);
MavenConfigurationImpl mavenConfiguration = new MavenConfigurationImpl(propertyResolver, "mvn");
mavenConfiguration.setSettings(new MavenSettingsImpl(new URL("file:/Users/gnodet/.m2/settings.xml")));
DownloadManager manager = new DownloadManager(mavenConfiguration, Executors.newFixedThreadPool(2));
Map<URI, Repository> repositories = new HashMap<URI, Repository>();
AgentUtils.addRepository(manager, repositories, URI.create("mvn:org.apache.karaf.assemblies.features/standard/" + System.getProperty("karaf-version") + "/xml/features"));
DeploymentBuilder builder = new DeploymentBuilder(manager, null, repositories.values());
builder.download(new HashSet<String>(Arrays.asList("karaf-framework", "ssh")),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
+ Collections.<String>emptySet(),
Collections.<String>emptySet());
properties = new Properties();
properties.setProperty("org.osgi.framework.system.packages.extra", "org.apache.karaf.jaas.boot;version=\"2.3.0.redhat-610-SNAPSHOT\",org.apache.karaf.jaas.boot.principal;version=\"2.3.0.redhat-610-SNAPSHOT\"");
properties.setProperty("org.osgi.framework.system.capabilities.extra",
"service-reference;effective:=active;objectClass=org.osgi.service.packageadmin.PackageAdmin," +
"service-reference;effective:=active;objectClass=org.osgi.service.startlevel.StartLevel," +
"service-reference;effective:=active;objectClass=org.osgi.service.url.URLHandlers");
Framework felix = new Felix(properties);
Collection<Resource> resources = builder.resolve(felix.adapt(BundleRevision.class), false);
for (Resource resource : resources) {
System.out.println("Resource: " + getUri(resource));
}
}
@Test
public void testRange() throws Exception {
Processor processor = new Processor();
processor.setProperty("@", "1.2.3.redhat-61-SNAPSHOT");
Macro macro = new Macro(processor);
assertEquals("[1.2,1.3)", macro.process("${range;[==,=+)}"));
assertEquals("[1.2.3.redhat-61-SNAPSHOT,2)", macro.process("${range;[====,+)}"));
}
}
| true | true | public void testResolve() throws Exception {
System.setProperty("karaf.data", new File("target/karaf/data").getAbsolutePath());
System.setProperty("karaf.home", new File("target/karaf").getAbsolutePath());
Properties properties = new Properties();
properties.setProperty("mvn.localRepository", "/Users/gnodet/.m2/repository/@snapshots");
properties.setProperty("mvn.repositories", "http://repo1.maven.org/maven2/,http://repo.fusesource.com/nexus/content/repositories/ea");
PropertiesPropertyResolver propertyResolver = new PropertiesPropertyResolver(properties);
MavenConfigurationImpl mavenConfiguration = new MavenConfigurationImpl(propertyResolver, "mvn");
mavenConfiguration.setSettings(new MavenSettingsImpl(new URL("file:/Users/gnodet/.m2/settings.xml")));
DownloadManager manager = new DownloadManager(mavenConfiguration, Executors.newFixedThreadPool(2));
Map<URI, Repository> repositories = new HashMap<URI, Repository>();
AgentUtils.addRepository(manager, repositories, URI.create("mvn:org.apache.karaf.assemblies.features/standard/" + System.getProperty("karaf-version") + "/xml/features"));
DeploymentBuilder builder = new DeploymentBuilder(manager, null, repositories.values());
builder.download(new HashSet<String>(Arrays.asList("karaf-framework", "ssh")),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
Collections.<String>emptySet());
properties = new Properties();
properties.setProperty("org.osgi.framework.system.packages.extra", "org.apache.karaf.jaas.boot;version=\"2.3.0.redhat-610-SNAPSHOT\",org.apache.karaf.jaas.boot.principal;version=\"2.3.0.redhat-610-SNAPSHOT\"");
properties.setProperty("org.osgi.framework.system.capabilities.extra",
"service-reference;effective:=active;objectClass=org.osgi.service.packageadmin.PackageAdmin," +
"service-reference;effective:=active;objectClass=org.osgi.service.startlevel.StartLevel," +
"service-reference;effective:=active;objectClass=org.osgi.service.url.URLHandlers");
Framework felix = new Felix(properties);
Collection<Resource> resources = builder.resolve(felix.adapt(BundleRevision.class), false);
for (Resource resource : resources) {
System.out.println("Resource: " + getUri(resource));
}
}
| public void testResolve() throws Exception {
System.setProperty("karaf.data", new File("target/karaf/data").getAbsolutePath());
System.setProperty("karaf.home", new File("target/karaf").getAbsolutePath());
Properties properties = new Properties();
properties.setProperty("mvn.localRepository", "/Users/gnodet/.m2/repository/@snapshots");
properties.setProperty("mvn.repositories", "http://repo1.maven.org/maven2/,http://repo.fusesource.com/nexus/content/repositories/ea");
PropertiesPropertyResolver propertyResolver = new PropertiesPropertyResolver(properties);
MavenConfigurationImpl mavenConfiguration = new MavenConfigurationImpl(propertyResolver, "mvn");
mavenConfiguration.setSettings(new MavenSettingsImpl(new URL("file:/Users/gnodet/.m2/settings.xml")));
DownloadManager manager = new DownloadManager(mavenConfiguration, Executors.newFixedThreadPool(2));
Map<URI, Repository> repositories = new HashMap<URI, Repository>();
AgentUtils.addRepository(manager, repositories, URI.create("mvn:org.apache.karaf.assemblies.features/standard/" + System.getProperty("karaf-version") + "/xml/features"));
DeploymentBuilder builder = new DeploymentBuilder(manager, null, repositories.values());
builder.download(new HashSet<String>(Arrays.asList("karaf-framework", "ssh")),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
Collections.<String>emptySet(),
Collections.<String>emptySet());
properties = new Properties();
properties.setProperty("org.osgi.framework.system.packages.extra", "org.apache.karaf.jaas.boot;version=\"2.3.0.redhat-610-SNAPSHOT\",org.apache.karaf.jaas.boot.principal;version=\"2.3.0.redhat-610-SNAPSHOT\"");
properties.setProperty("org.osgi.framework.system.capabilities.extra",
"service-reference;effective:=active;objectClass=org.osgi.service.packageadmin.PackageAdmin," +
"service-reference;effective:=active;objectClass=org.osgi.service.startlevel.StartLevel," +
"service-reference;effective:=active;objectClass=org.osgi.service.url.URLHandlers");
Framework felix = new Felix(properties);
Collection<Resource> resources = builder.resolve(felix.adapt(BundleRevision.class), false);
for (Resource resource : resources) {
System.out.println("Resource: " + getUri(resource));
}
}
|
diff --git a/src/com/herocraftonline/dev/heroes/skill/skills/SkillPort.java b/src/com/herocraftonline/dev/heroes/skill/skills/SkillPort.java
index a418b1cf..92655fbc 100644
--- a/src/com/herocraftonline/dev/heroes/skill/skills/SkillPort.java
+++ b/src/com/herocraftonline/dev/heroes/skill/skills/SkillPort.java
@@ -1,38 +1,34 @@
package com.herocraftonline.dev.heroes.skill.skills;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.persistence.Hero;
import com.herocraftonline.dev.heroes.skill.ActiveSkill;
public class SkillPort extends ActiveSkill {
public SkillPort(Heroes plugin) {
super(plugin);
name = "Port";
description = "Teleports you to the set location!";
usage = "/skill port <location>";
minArgs = 1;
maxArgs = 1;
identifiers.add("skill port");
}
@Override
public boolean use(Hero hero, String[] args) {
Player player = hero.getPlayer();
if (getSetting(hero.getHeroClass(), args[0].toLowerCase(), null) != null) {
- try {
String[] splitArg = getSetting(hero.getHeroClass(), args[0].toLowerCase(), null).split(":");
player.teleport(new Location(hero.getPlayer().getWorld(), Double.parseDouble(splitArg[0]), Double.parseDouble(splitArg[1]), Double.parseDouble(splitArg[2])));
notifyNearbyPlayers(player.getLocation(), useText, player.getName(), name);
return true;
- }catch(NullPointerException NPE) {
- return false;
- }
} else {
return false;
}
}
}
| false | true | public boolean use(Hero hero, String[] args) {
Player player = hero.getPlayer();
if (getSetting(hero.getHeroClass(), args[0].toLowerCase(), null) != null) {
try {
String[] splitArg = getSetting(hero.getHeroClass(), args[0].toLowerCase(), null).split(":");
player.teleport(new Location(hero.getPlayer().getWorld(), Double.parseDouble(splitArg[0]), Double.parseDouble(splitArg[1]), Double.parseDouble(splitArg[2])));
notifyNearbyPlayers(player.getLocation(), useText, player.getName(), name);
return true;
}catch(NullPointerException NPE) {
return false;
}
} else {
return false;
}
}
| public boolean use(Hero hero, String[] args) {
Player player = hero.getPlayer();
if (getSetting(hero.getHeroClass(), args[0].toLowerCase(), null) != null) {
String[] splitArg = getSetting(hero.getHeroClass(), args[0].toLowerCase(), null).split(":");
player.teleport(new Location(hero.getPlayer().getWorld(), Double.parseDouble(splitArg[0]), Double.parseDouble(splitArg[1]), Double.parseDouble(splitArg[2])));
notifyNearbyPlayers(player.getLocation(), useText, player.getName(), name);
return true;
} else {
return false;
}
}
|
diff --git a/SimulationCore/src/simulation/core/view/ForegroundManager.java b/SimulationCore/src/simulation/core/view/ForegroundManager.java
index 9749c43..3e5d73e 100644
--- a/SimulationCore/src/simulation/core/view/ForegroundManager.java
+++ b/SimulationCore/src/simulation/core/view/ForegroundManager.java
@@ -1,52 +1,52 @@
package simulation.core.view;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import simulation.extensionpoint.simulationplugin.definition.AbstractPluginPageWrapper;
import simulation.extensionpoint.simulationplugin.resources.IForegroundManager;
/**
* Manages which pluginPage Composite is shown on the application in foreground.
* @author S-lenovo
*/
public class ForegroundManager implements IForegroundManager{
private Composite currentlyInBackgroundsParent;
private Composite pluginPane;
private AbstractPluginPageWrapper currentlyInForegroundPage;
private TreeViewer viewer;
public ForegroundManager(Composite foregroundParent) {
pluginPane = foregroundParent;
currentlyInBackgroundsParent = new Composite(new Shell(), SWT.NONE);
}
@Override
public void setToForeground(AbstractPluginPageWrapper pageFactory) {
if(currentlyInForegroundPage != pageFactory){
if(currentlyInForegroundPage != null)
currentlyInForegroundPage.setParent(currentlyInBackgroundsParent);
pageFactory.setParent(pluginPane);
currentlyInForegroundPage = pageFactory;
- pluginPane.pack();
- pluginPane.setFocus();
IStructuredSelection selection = new StructuredSelection(pageFactory);
viewer.setSelection(selection, true);
}
+ pluginPane.pack();
+ pluginPane.setFocus();
}
@Override
public Shell getShell() {
return pluginPane.getShell();
}
public void setTreeViewer(TreeViewer viewer) {
this.viewer = viewer;
}
}
| false | true | public void setToForeground(AbstractPluginPageWrapper pageFactory) {
if(currentlyInForegroundPage != pageFactory){
if(currentlyInForegroundPage != null)
currentlyInForegroundPage.setParent(currentlyInBackgroundsParent);
pageFactory.setParent(pluginPane);
currentlyInForegroundPage = pageFactory;
pluginPane.pack();
pluginPane.setFocus();
IStructuredSelection selection = new StructuredSelection(pageFactory);
viewer.setSelection(selection, true);
}
}
| public void setToForeground(AbstractPluginPageWrapper pageFactory) {
if(currentlyInForegroundPage != pageFactory){
if(currentlyInForegroundPage != null)
currentlyInForegroundPage.setParent(currentlyInBackgroundsParent);
pageFactory.setParent(pluginPane);
currentlyInForegroundPage = pageFactory;
IStructuredSelection selection = new StructuredSelection(pageFactory);
viewer.setSelection(selection, true);
}
pluginPane.pack();
pluginPane.setFocus();
}
|
diff --git a/mmstudio/src/org/micromanager/acquisition/ChannelControlPanel.java b/mmstudio/src/org/micromanager/acquisition/ChannelControlPanel.java
index 34ab32dd7..579f4fc45 100644
--- a/mmstudio/src/org/micromanager/acquisition/ChannelControlPanel.java
+++ b/mmstudio/src/org/micromanager/acquisition/ChannelControlPanel.java
@@ -1,373 +1,374 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* ChannelControlsPanel.java
*
* Created on Sep 27, 2010, 1:27:24 PM
*/
package org.micromanager.acquisition;
import ij.ImagePlus;
import java.awt.Color;
import javax.swing.JColorChooser;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.HistogramPanel;
import org.micromanager.graph.HistogramPanel.CursorListener;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.MathFunctions;
import org.micromanager.utils.ReportingUtils;
/**
*
* @author arthur
*/
public class ChannelControlPanel extends javax.swing.JPanel {
private final int channelIndex_;
private final MMVirtualAcquisitionDisplay acq_;
private final HistogramPanel hp_;
private double binSize_;
/** Creates new form ChannelControlsPanel */
public ChannelControlPanel(MMVirtualAcquisitionDisplay acq, int channelIndex) {
initComponents();
channelIndex_ = channelIndex;
acq_ = acq;
hp_ = addHistogramPanel();
updateChannelSettings();
drawDisplaySettings();
}
/** 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() {
fullButton = new javax.swing.JButton();
autoButton = new javax.swing.JButton();
colorPickerLabel = new javax.swing.JLabel();
channelNameCheckbox = new javax.swing.JCheckBox();
histogramPanelHolder = new javax.swing.JPanel();
zoomInButton = new javax.swing.JButton();
zoomOutButton = new javax.swing.JButton();
setOpaque(false);
setPreferredSize(new java.awt.Dimension(250, 100));
fullButton.setFont(fullButton.getFont().deriveFont((float)9));
fullButton.setText("Full");
fullButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
fullButton.setPreferredSize(new java.awt.Dimension(75, 30));
fullButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fullButtonActionPerformed(evt);
}
});
autoButton.setFont(autoButton.getFont().deriveFont((float)9));
autoButton.setText("Auto");
autoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
autoButton.setIconTextGap(0);
autoButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
autoButton.setMaximumSize(new java.awt.Dimension(75, 30));
autoButton.setMinimumSize(new java.awt.Dimension(75, 30));
autoButton.setPreferredSize(new java.awt.Dimension(75, 30));
autoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoButtonActionPerformed(evt);
}
});
colorPickerLabel.setBackground(new java.awt.Color(255, 102, 51));
colorPickerLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
colorPickerLabel.setOpaque(true);
colorPickerLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
colorPickerLabelMouseClicked(evt);
}
});
channelNameCheckbox.setSelected(true);
channelNameCheckbox.setText("Channel");
channelNameCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
channelNameCheckboxActionPerformed(evt);
}
});
histogramPanelHolder.setAlignmentX(0.3F);
histogramPanelHolder.setPreferredSize(new java.awt.Dimension(0, 100));
histogramPanelHolder.setLayout(new java.awt.GridLayout(1, 1));
zoomInButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/micromanager/icons/plus.png"))); // NOI18N
zoomInButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomInButtonActionPerformed(evt);
}
});
zoomOutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/micromanager/icons/minus.png"))); // NOI18N
zoomOutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomOutButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(channelNameCheckbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(4, 4, 4))
.add(layout.createSequentialGroup()
.add(colorPickerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(fullButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
+ .add(0, 0, 0)
.add(zoomOutButton, 0, 0, Short.MAX_VALUE))
.add(autoButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)))
.add(histogramPanelHolder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(channelNameCheckbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fullButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(autoButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(colorPickerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
- .add(zoomOutButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
+ .add(zoomOutButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap())
.add(histogramPanelHolder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
);
}// </editor-fold>//GEN-END:initComponents
private void fullButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fullButtonActionPerformed
setFullRange();
}//GEN-LAST:event_fullButtonActionPerformed
private void colorPickerLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_colorPickerLabelMouseClicked
editColor();
}//GEN-LAST:event_colorPickerLabelMouseClicked
private void channelNameCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_channelNameCheckboxActionPerformed
updateChannelVisibility();
}//GEN-LAST:event_channelNameCheckboxActionPerformed
private void autoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoButtonActionPerformed
setAutoRange();
}//GEN-LAST:event_autoButtonActionPerformed
private void zoomInButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomInButtonActionPerformed
binSize_ = Math.max(binSize_ / 2, 1./8);
updateChannelSettings();
}//GEN-LAST:event_zoomInButtonActionPerformed
private void zoomOutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomOutButtonActionPerformed
binSize_ = Math.min(binSize_ * 2, 256);
updateChannelSettings();
}//GEN-LAST:event_zoomOutButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton autoButton;
private javax.swing.JCheckBox channelNameCheckbox;
private javax.swing.JLabel colorPickerLabel;
private javax.swing.JButton fullButton;
private javax.swing.JPanel histogramPanelHolder;
private javax.swing.JButton zoomInButton;
private javax.swing.JButton zoomOutButton;
// End of variables declaration//GEN-END:variables
private void editColor() {
String name = "selected";
if (acq_.getChannelNames() != null) {
name = acq_.getChannelNames()[channelIndex_];
}
Color newColor = JColorChooser.showDialog(this, "Choose a color for the "
+ name
+ " channel", acq_.getChannelColor(channelIndex_));
if (newColor != null && acq_ != null) {
try {
acq_.setChannelColor(channelIndex_, newColor.getRGB());
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}
updateChannelSettings();
}
public ChannelDisplaySettings getSettings() {
return acq_.getChannelDisplaySettings(channelIndex_);
}
private void updateChannelVisibility() {
acq_.setChannelVisibility(channelIndex_, channelNameCheckbox.isSelected());
}
public final HistogramPanel addHistogramPanel() {
HistogramPanel hp = new HistogramPanel();
hp.setMargins(8, 8);
hp.setTextVisible(false);
hp.setGridVisible(false);
//hp.setCursors(0,255,1.0);
histogramPanelHolder.add(hp);
updateBinSize();
hp.addCursorListener(new CursorListener() {
public void onLeftCursor(double pos) {
int max = acq_.getChannelMax(channelIndex_);
int min = (int) (pos * binSize_);
if (min > max) {
max = min;
}
setDisplayRange(min, max);
}
public void onRightCursor(double pos) {
int min = acq_.getChannelMin(channelIndex_);
int max = (int) (pos * binSize_);
if (max < min) {
min = max;
}
setDisplayRange(min, max);
}
public void onGammaCurve(double gamma) {
if (gamma == 0)
return;
if (gamma < 1.15 && gamma > 0.85)
gamma = 1.0;
else
gamma = MathFunctions.clip(0.05, gamma, 20);
acq_.setChannelGamma(channelIndex_, gamma);
drawDisplaySettings();
}
});
return hp;
}
public final void updateChannelSettings() {
if (acq_ != null) {
Color color = acq_.getChannelColor(channelIndex_);
colorPickerLabel.setBackground(color);
String [] names = acq_.getChannelNames();
if (names != null && channelIndex_ < names.length) {
channelNameCheckbox.setText(names[channelIndex_]);
}
int [] histogram = acq_.getChannelHistogram(channelIndex_);
hp_.setData(makeGraphData(histogram));
hp_.setAutoBounds();
hp_.setTraceStyle(true, color);
drawDisplaySettings();
}
}
private int getMaxValue() {
int type = acq_.getImagePlus().getType();
int maxValue = 0;
if (type == ImagePlus.GRAY8)
maxValue = 1 << 8;
if (type == ImagePlus.GRAY16)
maxValue = 1 << 16;
return maxValue;
}
private void updateBinSize() {
if (binSize_ == 0) {
binSize_ = getMaxValue() / 256;
}
}
public void setDisplayRange(int min, int max) {
acq_.setChannelDisplayRange(channelIndex_,
min, max);
drawDisplaySettings();
}
public final void drawDisplaySettings() {
ChannelDisplaySettings settings = getSettings();
hp_.setCursors(settings.min/binSize_,
settings.max/binSize_,
settings.gamma);
hp_.repaint();
}
private GraphData makeGraphData(int [] rawHistogram) {
GraphData graphData = new GraphData();
if (rawHistogram == null) {
return graphData;
}
updateBinSize();
int[] histogram = new int[256]; // 256 bins
int limit = Math.min((int) (rawHistogram.length / binSize_), 256);
for (int i = 0; i < limit; i++) {
histogram[i] = 0;
for (int j = 0; j < binSize_; j++) {
histogram[i] += rawHistogram[(int) (i * binSize_) + j];
}
}
graphData.setData(histogram);
return graphData;
}
private void setFullRange() {
int maxValue = getMaxValue();
setDisplayRange(0, maxValue);
}
private void setAutoRange() {
int [] histogram = acq_.getChannelHistogram(channelIndex_);
int min = 0;
int max = 0;
for (int i=0;i<histogram.length;++i) {
if (histogram[i] != 0 && min == 0) {
min = i;
max = min;
}
if (histogram[i] != 0) {
max = i;
}
}
setDisplayRange(min, max);
}
}
| false | true | private void initComponents() {
fullButton = new javax.swing.JButton();
autoButton = new javax.swing.JButton();
colorPickerLabel = new javax.swing.JLabel();
channelNameCheckbox = new javax.swing.JCheckBox();
histogramPanelHolder = new javax.swing.JPanel();
zoomInButton = new javax.swing.JButton();
zoomOutButton = new javax.swing.JButton();
setOpaque(false);
setPreferredSize(new java.awt.Dimension(250, 100));
fullButton.setFont(fullButton.getFont().deriveFont((float)9));
fullButton.setText("Full");
fullButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
fullButton.setPreferredSize(new java.awt.Dimension(75, 30));
fullButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fullButtonActionPerformed(evt);
}
});
autoButton.setFont(autoButton.getFont().deriveFont((float)9));
autoButton.setText("Auto");
autoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
autoButton.setIconTextGap(0);
autoButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
autoButton.setMaximumSize(new java.awt.Dimension(75, 30));
autoButton.setMinimumSize(new java.awt.Dimension(75, 30));
autoButton.setPreferredSize(new java.awt.Dimension(75, 30));
autoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoButtonActionPerformed(evt);
}
});
colorPickerLabel.setBackground(new java.awt.Color(255, 102, 51));
colorPickerLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
colorPickerLabel.setOpaque(true);
colorPickerLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
colorPickerLabelMouseClicked(evt);
}
});
channelNameCheckbox.setSelected(true);
channelNameCheckbox.setText("Channel");
channelNameCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
channelNameCheckboxActionPerformed(evt);
}
});
histogramPanelHolder.setAlignmentX(0.3F);
histogramPanelHolder.setPreferredSize(new java.awt.Dimension(0, 100));
histogramPanelHolder.setLayout(new java.awt.GridLayout(1, 1));
zoomInButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/micromanager/icons/plus.png"))); // NOI18N
zoomInButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomInButtonActionPerformed(evt);
}
});
zoomOutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/micromanager/icons/minus.png"))); // NOI18N
zoomOutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomOutButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(channelNameCheckbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(4, 4, 4))
.add(layout.createSequentialGroup()
.add(colorPickerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(fullButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(zoomOutButton, 0, 0, Short.MAX_VALUE))
.add(autoButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)))
.add(histogramPanelHolder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(channelNameCheckbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fullButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(autoButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(colorPickerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(zoomOutButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(histogramPanelHolder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
fullButton = new javax.swing.JButton();
autoButton = new javax.swing.JButton();
colorPickerLabel = new javax.swing.JLabel();
channelNameCheckbox = new javax.swing.JCheckBox();
histogramPanelHolder = new javax.swing.JPanel();
zoomInButton = new javax.swing.JButton();
zoomOutButton = new javax.swing.JButton();
setOpaque(false);
setPreferredSize(new java.awt.Dimension(250, 100));
fullButton.setFont(fullButton.getFont().deriveFont((float)9));
fullButton.setText("Full");
fullButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
fullButton.setPreferredSize(new java.awt.Dimension(75, 30));
fullButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fullButtonActionPerformed(evt);
}
});
autoButton.setFont(autoButton.getFont().deriveFont((float)9));
autoButton.setText("Auto");
autoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
autoButton.setIconTextGap(0);
autoButton.setMargin(new java.awt.Insets(2, 4, 2, 4));
autoButton.setMaximumSize(new java.awt.Dimension(75, 30));
autoButton.setMinimumSize(new java.awt.Dimension(75, 30));
autoButton.setPreferredSize(new java.awt.Dimension(75, 30));
autoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoButtonActionPerformed(evt);
}
});
colorPickerLabel.setBackground(new java.awt.Color(255, 102, 51));
colorPickerLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
colorPickerLabel.setOpaque(true);
colorPickerLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
colorPickerLabelMouseClicked(evt);
}
});
channelNameCheckbox.setSelected(true);
channelNameCheckbox.setText("Channel");
channelNameCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
channelNameCheckboxActionPerformed(evt);
}
});
histogramPanelHolder.setAlignmentX(0.3F);
histogramPanelHolder.setPreferredSize(new java.awt.Dimension(0, 100));
histogramPanelHolder.setLayout(new java.awt.GridLayout(1, 1));
zoomInButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/micromanager/icons/plus.png"))); // NOI18N
zoomInButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomInButtonActionPerformed(evt);
}
});
zoomOutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/micromanager/icons/minus.png"))); // NOI18N
zoomOutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomOutButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(channelNameCheckbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(4, 4, 4))
.add(layout.createSequentialGroup()
.add(colorPickerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(fullButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(0, 0, 0)
.add(zoomOutButton, 0, 0, Short.MAX_VALUE))
.add(autoButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)))
.add(histogramPanelHolder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(channelNameCheckbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fullButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(autoButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(colorPickerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(zoomOutButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(zoomInButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.add(histogramPanelHolder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java b/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java
index 88f92b2..cc03cfc 100644
--- a/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java
+++ b/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java
@@ -1,1733 +1,1733 @@
package net.sacredlabyrinth.Phaed.PreciousStones.managers;
import net.sacredlabyrinth.Phaed.PreciousStones.*;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.BlockTypeEntry;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.PlayerEntry;
import net.sacredlabyrinth.Phaed.PreciousStones.vectors.Field;
import net.sacredlabyrinth.Phaed.PreciousStones.vectors.Unbreakable;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author phaed
*/
public final class CommandManager implements CommandExecutor
{
private PreciousStones plugin;
/**
*
*/
public CommandManager()
{
plugin = PreciousStones.getInstance();
}
/**
* @param sender
* @param command
* @param label
* @param args
* @return
*/
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
try
{
if (command.getName().equals("ps"))
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
boolean hasplayer = player != null;
if (hasplayer)
{
if (plugin.getSettingsManager().isBlacklistedWorld(player.getWorld()))
{
ChatBlock.send(player, "psDisabled");
return true;
}
}
if (args.length > 0)
{
String cmd = args[0];
args = Helper.removeFirst(args);
Block block = hasplayer ? player.getWorld().getBlockAt(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) : null;
if (cmd.equals(ChatBlock.format("commandDraw")))
{
plugin.getForceFieldManager().drawSourceFields();
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebug")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebug(!plugin.getSettingsManager().isDebug());
if (plugin.getSettingsManager().isDebug())
{
ChatBlock.send(sender, "debugEnabled");
}
else
{
ChatBlock.send(sender, "debugDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebugdb")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebugdb(!plugin.getSettingsManager().isDebugdb());
if (plugin.getSettingsManager().isDebugdb())
{
ChatBlock.send(sender, "debugDbEnabled");
}
else
{
ChatBlock.send(sender, "debugDbDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebugsql")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebugsql(!plugin.getSettingsManager().isDebugsql());
if (plugin.getSettingsManager().isDebugsql())
{
ChatBlock.send(sender, "debugSqlEnabled");
}
else
{
ChatBlock.send(sender, "debugSqlDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOn")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(false);
ChatBlock.send(sender, "placingEnabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyEnabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOff")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (!isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(true);
ChatBlock.send(sender, "placingDisabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandAllow")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allow") && hasplayer)
{
if (args.length >= 1)
{
- Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
+ Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
Player allowed = Helper.matchSinglePlayer(playerName);
// only those with permission can be allowed
if (field.getSettings().getRequiredPermissionAllow() != null)
{
if (!plugin.getPermissionsManager().has(allowed, field.getSettings().getRequiredPermissionAllow()))
{
ChatBlock.send(sender, "noPermsForAllow", playerName);
continue;
}
}
boolean done = plugin.getForceFieldManager().addAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "hasBeenAllowed", playerName);
}
else
{
ChatBlock.send(sender, "alreadyAllowed", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().allowAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "hasBeenAllowedIn", playerName, count);
}
else
{
ChatBlock.send(sender, "isAlreadyAllowedOnAll", playerName);
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.remove") && hasplayer)
{
if (args.length >= 1)
{
- Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
+ Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
if (field.containsPlayer(playerName))
{
ChatBlock.send(sender, "cannotRemovePlayerInField");
return true;
}
if (plugin.getForceFieldManager().conflictOfInterestExists(field, playerName))
{
ChatBlock.send(sender, "cannotDisallowWhenOverlap", playerName);
return true;
}
boolean done = plugin.getForceFieldManager().removeAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "removedFromField", playerName);
}
else
{
ChatBlock.send(sender, "playerNotFound", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemoveall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.removeall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().removeAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "removedFromFields", playerName, count);
}
else
{
ChatBlock.send(sender, "nothingToBeDone");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowed")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowed") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
List<String> allowed = field.getAllAllowed();
if (allowed.size() > 0)
{
ChatBlock.send(sender, "allowedList", Helper.toMessage(new ArrayList<String>(allowed), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersAllowedOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandCuboid")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.create.forcefield") && hasplayer)
{
if (args.length >= 1)
{
if ((args[0]).equals("commandCuboidOpen"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.CUBOID);
if (field != null)
{
plugin.getCuboidManager().openCuboid(player, field);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else if ((args[0]).equals("commandCuboidClose"))
{
plugin.getCuboidManager().closeCuboid(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandWho")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.who") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
HashSet<String> inhabitants = plugin.getForceFieldManager().getWho(field);
if (inhabitants.size() > 0)
{
ChatBlock.send(sender, "inhabitantsList", Helper.toMessage(new ArrayList<String>(inhabitants), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersFoundOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetname")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setname") && hasplayer)
{
String fieldName = null;
if (args.length >= 1)
{
fieldName = Helper.toMessage(args);
}
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
// if switching from an existing translocation
// end the previous one correctly by making sure
// to wipe out all applied blocks from the database
if (field.isNamed())
{
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
}
// check if one exists with that name already
if (plugin.getStorageManager().existsFieldWithName(fieldName, player.getName()))
{
ChatBlock.send(sender, "translocationExists");
return true;
}
// if this is a new translocation name, create its head record
// this will cement the size of the cuboid
if (!plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
plugin.getStorageManager().insertTranslocationHead(field, fieldName);
}
// updates the size of the field
plugin.getStorageManager().changeSizeTranslocatiorField(field, fieldName);
// always start off in applied (recording) mode
if (plugin.getStorageManager().existsTranslocationDataWithName(fieldName, field.getOwner()))
{
field.setDisabled(true);
}
else
{
field.setDisabled(false);
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (fieldName == null)
{
boolean done = plugin.getForceFieldManager().setNameField(field, "");
if (done)
{
ChatBlock.send(sender, "fieldNameCleared");
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
else
{
boolean done = plugin.getForceFieldManager().setNameField(field, fieldName);
if (done)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
int count = plugin.getStorageManager().unappliedTranslocationCount(field);
if (count > 0)
{
ChatBlock.send(sender, "translocationHasBlocks", fieldName, count);
}
else
{
ChatBlock.send(sender, "translocationCreated", fieldName);
}
}
else
{
ChatBlock.send(sender, "translocationRenamed", fieldName);
}
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetradius")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setradius") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
FieldSettings fs = field.getSettings();
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
ChatBlock.send(player, "translocationCannotReshape");
return true;
}
}
}
if (!field.hasFlag(FieldFlag.CUBOID))
{
if (radius >= 0 && (radius <= fs.getRadius() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.setradius")))
{
plugin.getForceFieldManager().removeSourceField(field);
field.setRadius(radius);
plugin.getStorageManager().offerField(field);
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "radiusSet", radius);
}
else
{
ChatBlock.send(sender, "radiusMustBeLessThan", fs.getRadius());
}
}
else
{
ChatBlock.send(sender, "cuboidCannotChangeRadius");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetvelocity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setvelocity") && hasplayer)
{
if (args.length == 1 && Helper.isFloat(args[0]))
{
float velocity = Float.parseFloat(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
FieldSettings fs = field.getSettings();
if (fs.hasVeocityFlag())
{
if (velocity < 0 || velocity > 5)
{
ChatBlock.send(sender, "velocityMustBe");
return true;
}
field.setVelocity(velocity);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "velocitySetTo", velocity);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandDisable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.disable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.isDisabled())
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().clearTranslocation(field);
}
}
field.setDisabled(true);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "fieldDisabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyDisabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.enable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isDisabled())
{
// update translocation
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().applyTranslocation(field);
}
}
field.setDisabled(false);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "fieldEnabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyEnabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDensity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.density") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int density = Integer.parseInt(args[0]);
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
data.setDensity(density);
plugin.getStorageManager().offerPlayer(player.getName());
ChatBlock.send(sender, "visualizationChanged", density);
return true;
}
else if (args.length == 0)
{
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
ChatBlock.send(sender, "visualizationSet", data.getDensity());
}
}
else if (cmd.equals(ChatBlock.format("commandToggle")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled"))
{
if (field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "flagsToggledWhileDisabled");
return true;
}
}
}
if (field.hasFlag(flagStr) || field.hasDisabledFlag(flagStr))
{
boolean unToggable = false;
if (field.hasFlag(FieldFlag.DYNMAP_NO_TOGGLE))
{
if (flagStr.equalsIgnoreCase("dynmap-area"))
{
unToggable = true;
}
if (flagStr.equalsIgnoreCase("dynmap-marker"))
{
unToggable = true;
}
}
if (plugin.getSettingsManager().isUnToggable(flagStr))
{
unToggable = true;
}
if (unToggable)
{
ChatBlock.send(sender, "flagCannottoggle");
return true;
}
boolean enabled = field.toggleFieldFlag(flagStr);
if (enabled)
{
ChatBlock.send(sender, "flagEnabled", flagStr);
}
else
{
ChatBlock.send(sender, "flagDisabled", flagStr);
}
field.dirtyFlags();
}
else
{
ChatBlock.send(sender, "flagNotFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if ((cmd.equals(ChatBlock.format("commandVisualize")) || cmd.equals("visualise")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize"))
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Math.min(Integer.parseInt(args[0]), plugin.getServer().getViewDistance());
Set<Field> fieldsInArea;
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize"))
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL);
}
else
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL, player);
}
if (fieldsInArea != null && fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "visualizing");
int count = 0;
for (Field f : fieldsInArea)
{
if (count++ >= plugin.getSettingsManager().getVisualizeMaxFields())
{
continue;
}
plugin.getVisualizationManager().addVisualizationField(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, true);
return true;
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
ChatBlock.send(sender, "visualizing");
plugin.getVisualizationManager().addVisualizationField(player, field);
plugin.getVisualizationManager().displayVisualization(player, true);
}
else
{
ChatBlock.send(sender, "notInsideField");
}
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "visualizationNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandMark")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.mark") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.mark"))
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "markingFields", fieldsInArea.size());
for (Field f : fieldsInArea)
{
plugin.getVisualizationManager().addFieldMark(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
int count = 0;
for (Field f : fieldsInArea)
{
if (plugin.getForceFieldManager().isAllowed(f, player.getName()))
{
count++;
plugin.getVisualizationManager().addFieldMark(player, f);
}
}
if (count > 0)
{
ChatBlock.send(sender, "markingFields", count);
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "markingNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandInsert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.insert") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.hasFlag(flagStr) && !field.hasDisabledFlag(flagStr))
{
if (field.insertFieldFlag(flagStr))
{
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "flagInserted");
plugin.getStorageManager().offerField(field);
}
else
{
ChatBlock.send(sender, "flagNotExists");
}
}
else
{
ChatBlock.send(sender, "flagExists");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandReset")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reset") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
field.RevertFlags();
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "flagsReverted");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetinterval")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setinterval") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int interval = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.GRIEF_REVERT);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (interval >= plugin.getSettingsManager().getGriefRevertMinInterval() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.interval"))
{
field.setRevertSecs(interval);
plugin.getGriefUndoManager().register(field);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "griefRevertIntervalSet", interval);
}
else
{
ChatBlock.send(sender, "minInterval", plugin.getSettingsManager().getGriefRevertMinInterval());
}
}
else
{
ChatBlock.send(sender, "notPointingAtGriefRevert");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSnitch")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.snitch") && hasplayer)
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
plugin.getCommunicationManager().showSnitchList(player, field);
}
else
{
ChatBlock.send(sender, "notPointingAtSnitch");
}
return true;
}
else if (args.length == 1)
{
if (args[0].equals("commandSnitchClear"))
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
boolean cleaned = plugin.getForceFieldManager().cleanSnitchList(field);
if (cleaned)
{
ChatBlock.send(sender, "clearedSnitch");
}
else
{
ChatBlock.send(sender, "snitchEmpty");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandTranslocation")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.use") && hasplayer)
{
if (args.length == 0)
{
ChatBlock.send(sender, "translocationMenu1");
ChatBlock.send(sender, "translocationMenu2");
ChatBlock.send(sender, "translocationMenu3");
ChatBlock.send(sender, "translocationMenu4");
ChatBlock.send(sender, "translocationMenu5");
ChatBlock.send(sender, "translocationMenu6");
ChatBlock.send(sender, "translocationMenu7");
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationList")))
{
plugin.getCommunicationManager().notifyStoredTranslocations(player);
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.delete"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (args.length == 0)
{
plugin.getStorageManager().deleteTranslocation(args[1], player.getName());
ChatBlock.send(sender, "translocationDeleted", args[0]);
}
else
{
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
int count = plugin.getStorageManager().deleteBlockTypeFromTranslocation(field.getName(), player.getName(), entry);
if (count > 0)
{
ChatBlock.send(sender, "translocationDeletedBlocks", count, Helper.friendlyBlockType(Material.getMaterial(entry.getTypeId()).toString()), field.getName());
}
else
{
ChatBlock.send(sender, "noBlocksMatched", arg);
}
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.remove"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledFirst");
return true;
}
if (args.length > 0)
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().removeBlocks(field, player, entries);
}
}
else
{
ChatBlock.send(sender, "usageTranslocationRemove");
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationUnlink")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.unlink"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToUnlink");
return true;
}
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
else
{
ChatBlock.send(sender, "translocationNothingToUnlink");
return true;
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationImport")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.import"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToImport");
return true;
}
if (args.length == 0)
{
plugin.getTranslocationManager().importBlocks(field, player, null);
}
else
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
if (!field.getSettings().canTranslocate(entry))
{
ChatBlock.send(sender, "blockIsBlacklisted", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().importBlocks(field, player, entries);
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandMore")) && hasplayer)
{
ChatBlock cb = plugin.getCommunicationManager().getChatBlock(player);
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
cb.sendBlock(player, plugin.getSettingsManager().getLinesPerPage());
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
ChatBlock.send(sender, "moreNextPage");
}
ChatBlock.sendBlank(player);
return true;
}
ChatBlock.send(sender, "moreNothingMore");
return true;
}
else if (cmd.equals(ChatBlock.format("commandCounts")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.counts") && hasplayer)
{
if (!plugin.getCommunicationManager().showFieldCounts(player, player.getName()))
{
ChatBlock.send(sender, "playerHasNoFields");
}
return true;
}
if (args.length == 1 && plugin.getPermissionsManager().has(player, "preciousstones.admin.counts"))
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
if (!plugin.getCommunicationManager().showCounts(sender, type))
{
ChatBlock.send(sender, "notValidFieldType");
}
}
}
else if (Helper.isString(args[0]) && hasplayer)
{
String target = args[0];
if (!plugin.getCommunicationManager().showFieldCounts(player, target))
{
ChatBlock.send(sender, "playerHasNoFields");
}
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandLocations")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.locations") && hasplayer)
{
plugin.getCommunicationManager().showFieldLocations(sender, -1, sender.getName());
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.locations"))
{
if (args.length == 1 && Helper.isString(args[0]))
{
String targetName = args[0];
plugin.getCommunicationManager().showFieldLocations(sender, -1, targetName);
}
if (args.length == 2 && Helper.isString(args[0]) && Helper.isInteger(args[1]))
{
String targetName = args[0];
int type = Integer.parseInt(args[1]);
plugin.getCommunicationManager().showFieldLocations(sender, type, targetName);
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandInfo")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.info") && hasplayer)
{
Field pointing = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
List<Field> fields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (pointing != null && !fields.contains(pointing))
{
fields.add(pointing);
}
if (fields.size() == 1)
{
plugin.getCommunicationManager().showFieldDetails(player, fields.get(0));
}
else
{
plugin.getCommunicationManager().showFieldDetails(player, fields);
}
if (fields.isEmpty())
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.delete"))
{
if (args.length == 0 && hasplayer)
{
List<Field> sourceFields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (sourceFields.size() > 0)
{
int count = plugin.getForceFieldManager().deleteFields(sourceFields);
if (count > 0)
{
ChatBlock.send(sender, "protectionRemoved");
if (plugin.getSettingsManager().isLogBypassDelete())
{
PreciousStones.log("protectionRemovedFrom", count);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (args.length == 1)
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deleteFieldsOfType(type);
int ubs = plugin.getUnbreakableManager().deleteUnbreakablesOfType(type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedUnbreakables", ubs, Material.getMaterial(type.getTypeId()));
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
int fields = plugin.getForceFieldManager().deleteBelonging(args[0]);
int ubs = plugin.getUnbreakableManager().deleteBelonging(args[0]);
if (fields > 0)
{
ChatBlock.send(sender, "deletedCountFields", args[0], fields);
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedCountUnbreakables", args[0], ubs);
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "playerHasNoPstones");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetowner")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.setowner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
// transfer the count over to the new owner
PlayerEntry oldData = plugin.getPlayerManager().getPlayerEntry(field.getOwner());
oldData.decrementFieldCount(field.getSettings().getTypeEntry());
PlayerEntry newData = plugin.getPlayerManager().getPlayerEntry(owner);
newData.incrementFieldCount(field.getSettings().getTypeEntry());
plugin.getStorageManager().changeTranslocationOwner(field, owner);
plugin.getStorageManager().offerPlayer(field.getOwner());
plugin.getStorageManager().offerPlayer(owner);
// change the owner
field.setOwner(owner);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "ownerSetTo", owner);
return true;
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandChangeowner")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.change-owner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
if (field.isOwner(player.getName()))
{
if (field.hasFlag(FieldFlag.CAN_CHANGE_OWNER))
{
field.setNewOwner(owner);
ChatBlock.send(sender, "fieldCanBeTaken", owner);
return true;
}
else
{
ChatBlock.send(sender, "fieldCannotChangeOwner");
}
}
else
{
ChatBlock.send(sender, "ownerCanOnlyChangeOwner");
}
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandList")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.list") && hasplayer)
{
if (args.length == 1)
{
if (Helper.isInteger(args[0]))
{
int chunk_radius = Integer.parseInt(args[0]);
List<Unbreakable> unbreakables = plugin.getUnbreakableManager().getUnbreakablesInArea(player, chunk_radius);
Set<Field> fields = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), chunk_radius, FieldFlag.ALL);
for (Unbreakable u : unbreakables)
{
ChatBlock.send(sender, "{aqua}{unbreakable}", u.toString());
}
for (Field f : fields)
{
ChatBlock.send(sender, "{aqua}{field}", f.toString());
}
if (unbreakables.isEmpty() && fields.isEmpty())
{
ChatBlock.send(sender, "noPstonesFound");
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandReload")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reload"))
{
plugin.getSettingsManager().load();
ChatBlock.send(sender, "configReloaded");
return true;
}
else if (cmd.equals(ChatBlock.format("commandFields")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.fields"))
{
plugin.getCommunicationManager().showConfiguredFields(sender);
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.enableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().enableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagEnabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDisableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.disableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().disableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagDisabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandClean")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.clean"))
{
List<World> worlds = plugin.getServer().getWorlds();
int cleandFF = 0;
int cleandU = 0;
for (World world : worlds)
{
cleandFF += plugin.getForceFieldManager().cleanOrphans(world);
cleandU += plugin.getUnbreakableManager().cleanOrphans(world);
}
if (cleandFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleandFF);
}
if (cleandU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleandU);
}
if (cleandFF == 0 && cleandU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandRevert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.revert"))
{
List<World> worlds = plugin.getServer().getWorlds();
int cleandFF = 0;
int cleandU = 0;
for (World world : worlds)
{
cleandFF += plugin.getForceFieldManager().revertOrphans(world);
cleandU += plugin.getUnbreakableManager().revertOrphans(world);
}
if (cleandFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleandFF);
}
if (cleandU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleandU);
}
if (cleandFF == 0 && cleandU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
return true;
}
ChatBlock.send(sender, "notValidCommand");
return true;
}
// show the player menu
plugin.getCommunicationManager().showMenu(player);
return true;
}
}
catch (Exception ex)
{
System.out.print("Error: " + ex.getMessage());
for (StackTraceElement el : ex.getStackTrace())
{
System.out.print(el.toString());
}
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
try
{
if (command.getName().equals("ps"))
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
boolean hasplayer = player != null;
if (hasplayer)
{
if (plugin.getSettingsManager().isBlacklistedWorld(player.getWorld()))
{
ChatBlock.send(player, "psDisabled");
return true;
}
}
if (args.length > 0)
{
String cmd = args[0];
args = Helper.removeFirst(args);
Block block = hasplayer ? player.getWorld().getBlockAt(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) : null;
if (cmd.equals(ChatBlock.format("commandDraw")))
{
plugin.getForceFieldManager().drawSourceFields();
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebug")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebug(!plugin.getSettingsManager().isDebug());
if (plugin.getSettingsManager().isDebug())
{
ChatBlock.send(sender, "debugEnabled");
}
else
{
ChatBlock.send(sender, "debugDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebugdb")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebugdb(!plugin.getSettingsManager().isDebugdb());
if (plugin.getSettingsManager().isDebugdb())
{
ChatBlock.send(sender, "debugDbEnabled");
}
else
{
ChatBlock.send(sender, "debugDbDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebugsql")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebugsql(!plugin.getSettingsManager().isDebugsql());
if (plugin.getSettingsManager().isDebugsql())
{
ChatBlock.send(sender, "debugSqlEnabled");
}
else
{
ChatBlock.send(sender, "debugSqlDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOn")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(false);
ChatBlock.send(sender, "placingEnabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyEnabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOff")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (!isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(true);
ChatBlock.send(sender, "placingDisabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandAllow")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allow") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
Player allowed = Helper.matchSinglePlayer(playerName);
// only those with permission can be allowed
if (field.getSettings().getRequiredPermissionAllow() != null)
{
if (!plugin.getPermissionsManager().has(allowed, field.getSettings().getRequiredPermissionAllow()))
{
ChatBlock.send(sender, "noPermsForAllow", playerName);
continue;
}
}
boolean done = plugin.getForceFieldManager().addAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "hasBeenAllowed", playerName);
}
else
{
ChatBlock.send(sender, "alreadyAllowed", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().allowAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "hasBeenAllowedIn", playerName, count);
}
else
{
ChatBlock.send(sender, "isAlreadyAllowedOnAll", playerName);
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.remove") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
if (field.containsPlayer(playerName))
{
ChatBlock.send(sender, "cannotRemovePlayerInField");
return true;
}
if (plugin.getForceFieldManager().conflictOfInterestExists(field, playerName))
{
ChatBlock.send(sender, "cannotDisallowWhenOverlap", playerName);
return true;
}
boolean done = plugin.getForceFieldManager().removeAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "removedFromField", playerName);
}
else
{
ChatBlock.send(sender, "playerNotFound", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemoveall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.removeall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().removeAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "removedFromFields", playerName, count);
}
else
{
ChatBlock.send(sender, "nothingToBeDone");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowed")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowed") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
List<String> allowed = field.getAllAllowed();
if (allowed.size() > 0)
{
ChatBlock.send(sender, "allowedList", Helper.toMessage(new ArrayList<String>(allowed), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersAllowedOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandCuboid")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.create.forcefield") && hasplayer)
{
if (args.length >= 1)
{
if ((args[0]).equals("commandCuboidOpen"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.CUBOID);
if (field != null)
{
plugin.getCuboidManager().openCuboid(player, field);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else if ((args[0]).equals("commandCuboidClose"))
{
plugin.getCuboidManager().closeCuboid(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandWho")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.who") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
HashSet<String> inhabitants = plugin.getForceFieldManager().getWho(field);
if (inhabitants.size() > 0)
{
ChatBlock.send(sender, "inhabitantsList", Helper.toMessage(new ArrayList<String>(inhabitants), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersFoundOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetname")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setname") && hasplayer)
{
String fieldName = null;
if (args.length >= 1)
{
fieldName = Helper.toMessage(args);
}
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
// if switching from an existing translocation
// end the previous one correctly by making sure
// to wipe out all applied blocks from the database
if (field.isNamed())
{
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
}
// check if one exists with that name already
if (plugin.getStorageManager().existsFieldWithName(fieldName, player.getName()))
{
ChatBlock.send(sender, "translocationExists");
return true;
}
// if this is a new translocation name, create its head record
// this will cement the size of the cuboid
if (!plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
plugin.getStorageManager().insertTranslocationHead(field, fieldName);
}
// updates the size of the field
plugin.getStorageManager().changeSizeTranslocatiorField(field, fieldName);
// always start off in applied (recording) mode
if (plugin.getStorageManager().existsTranslocationDataWithName(fieldName, field.getOwner()))
{
field.setDisabled(true);
}
else
{
field.setDisabled(false);
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (fieldName == null)
{
boolean done = plugin.getForceFieldManager().setNameField(field, "");
if (done)
{
ChatBlock.send(sender, "fieldNameCleared");
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
else
{
boolean done = plugin.getForceFieldManager().setNameField(field, fieldName);
if (done)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
int count = plugin.getStorageManager().unappliedTranslocationCount(field);
if (count > 0)
{
ChatBlock.send(sender, "translocationHasBlocks", fieldName, count);
}
else
{
ChatBlock.send(sender, "translocationCreated", fieldName);
}
}
else
{
ChatBlock.send(sender, "translocationRenamed", fieldName);
}
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetradius")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setradius") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
FieldSettings fs = field.getSettings();
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
ChatBlock.send(player, "translocationCannotReshape");
return true;
}
}
}
if (!field.hasFlag(FieldFlag.CUBOID))
{
if (radius >= 0 && (radius <= fs.getRadius() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.setradius")))
{
plugin.getForceFieldManager().removeSourceField(field);
field.setRadius(radius);
plugin.getStorageManager().offerField(field);
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "radiusSet", radius);
}
else
{
ChatBlock.send(sender, "radiusMustBeLessThan", fs.getRadius());
}
}
else
{
ChatBlock.send(sender, "cuboidCannotChangeRadius");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetvelocity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setvelocity") && hasplayer)
{
if (args.length == 1 && Helper.isFloat(args[0]))
{
float velocity = Float.parseFloat(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
FieldSettings fs = field.getSettings();
if (fs.hasVeocityFlag())
{
if (velocity < 0 || velocity > 5)
{
ChatBlock.send(sender, "velocityMustBe");
return true;
}
field.setVelocity(velocity);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "velocitySetTo", velocity);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandDisable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.disable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.isDisabled())
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().clearTranslocation(field);
}
}
field.setDisabled(true);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "fieldDisabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyDisabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.enable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isDisabled())
{
// update translocation
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().applyTranslocation(field);
}
}
field.setDisabled(false);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "fieldEnabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyEnabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDensity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.density") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int density = Integer.parseInt(args[0]);
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
data.setDensity(density);
plugin.getStorageManager().offerPlayer(player.getName());
ChatBlock.send(sender, "visualizationChanged", density);
return true;
}
else if (args.length == 0)
{
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
ChatBlock.send(sender, "visualizationSet", data.getDensity());
}
}
else if (cmd.equals(ChatBlock.format("commandToggle")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled"))
{
if (field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "flagsToggledWhileDisabled");
return true;
}
}
}
if (field.hasFlag(flagStr) || field.hasDisabledFlag(flagStr))
{
boolean unToggable = false;
if (field.hasFlag(FieldFlag.DYNMAP_NO_TOGGLE))
{
if (flagStr.equalsIgnoreCase("dynmap-area"))
{
unToggable = true;
}
if (flagStr.equalsIgnoreCase("dynmap-marker"))
{
unToggable = true;
}
}
if (plugin.getSettingsManager().isUnToggable(flagStr))
{
unToggable = true;
}
if (unToggable)
{
ChatBlock.send(sender, "flagCannottoggle");
return true;
}
boolean enabled = field.toggleFieldFlag(flagStr);
if (enabled)
{
ChatBlock.send(sender, "flagEnabled", flagStr);
}
else
{
ChatBlock.send(sender, "flagDisabled", flagStr);
}
field.dirtyFlags();
}
else
{
ChatBlock.send(sender, "flagNotFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if ((cmd.equals(ChatBlock.format("commandVisualize")) || cmd.equals("visualise")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize"))
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Math.min(Integer.parseInt(args[0]), plugin.getServer().getViewDistance());
Set<Field> fieldsInArea;
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize"))
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL);
}
else
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL, player);
}
if (fieldsInArea != null && fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "visualizing");
int count = 0;
for (Field f : fieldsInArea)
{
if (count++ >= plugin.getSettingsManager().getVisualizeMaxFields())
{
continue;
}
plugin.getVisualizationManager().addVisualizationField(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, true);
return true;
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
ChatBlock.send(sender, "visualizing");
plugin.getVisualizationManager().addVisualizationField(player, field);
plugin.getVisualizationManager().displayVisualization(player, true);
}
else
{
ChatBlock.send(sender, "notInsideField");
}
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "visualizationNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandMark")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.mark") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.mark"))
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "markingFields", fieldsInArea.size());
for (Field f : fieldsInArea)
{
plugin.getVisualizationManager().addFieldMark(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
int count = 0;
for (Field f : fieldsInArea)
{
if (plugin.getForceFieldManager().isAllowed(f, player.getName()))
{
count++;
plugin.getVisualizationManager().addFieldMark(player, f);
}
}
if (count > 0)
{
ChatBlock.send(sender, "markingFields", count);
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "markingNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandInsert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.insert") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.hasFlag(flagStr) && !field.hasDisabledFlag(flagStr))
{
if (field.insertFieldFlag(flagStr))
{
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "flagInserted");
plugin.getStorageManager().offerField(field);
}
else
{
ChatBlock.send(sender, "flagNotExists");
}
}
else
{
ChatBlock.send(sender, "flagExists");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandReset")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reset") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
field.RevertFlags();
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "flagsReverted");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetinterval")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setinterval") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int interval = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.GRIEF_REVERT);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (interval >= plugin.getSettingsManager().getGriefRevertMinInterval() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.interval"))
{
field.setRevertSecs(interval);
plugin.getGriefUndoManager().register(field);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "griefRevertIntervalSet", interval);
}
else
{
ChatBlock.send(sender, "minInterval", plugin.getSettingsManager().getGriefRevertMinInterval());
}
}
else
{
ChatBlock.send(sender, "notPointingAtGriefRevert");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSnitch")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.snitch") && hasplayer)
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
plugin.getCommunicationManager().showSnitchList(player, field);
}
else
{
ChatBlock.send(sender, "notPointingAtSnitch");
}
return true;
}
else if (args.length == 1)
{
if (args[0].equals("commandSnitchClear"))
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
boolean cleaned = plugin.getForceFieldManager().cleanSnitchList(field);
if (cleaned)
{
ChatBlock.send(sender, "clearedSnitch");
}
else
{
ChatBlock.send(sender, "snitchEmpty");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandTranslocation")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.use") && hasplayer)
{
if (args.length == 0)
{
ChatBlock.send(sender, "translocationMenu1");
ChatBlock.send(sender, "translocationMenu2");
ChatBlock.send(sender, "translocationMenu3");
ChatBlock.send(sender, "translocationMenu4");
ChatBlock.send(sender, "translocationMenu5");
ChatBlock.send(sender, "translocationMenu6");
ChatBlock.send(sender, "translocationMenu7");
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationList")))
{
plugin.getCommunicationManager().notifyStoredTranslocations(player);
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.delete"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (args.length == 0)
{
plugin.getStorageManager().deleteTranslocation(args[1], player.getName());
ChatBlock.send(sender, "translocationDeleted", args[0]);
}
else
{
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
int count = plugin.getStorageManager().deleteBlockTypeFromTranslocation(field.getName(), player.getName(), entry);
if (count > 0)
{
ChatBlock.send(sender, "translocationDeletedBlocks", count, Helper.friendlyBlockType(Material.getMaterial(entry.getTypeId()).toString()), field.getName());
}
else
{
ChatBlock.send(sender, "noBlocksMatched", arg);
}
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.remove"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledFirst");
return true;
}
if (args.length > 0)
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().removeBlocks(field, player, entries);
}
}
else
{
ChatBlock.send(sender, "usageTranslocationRemove");
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationUnlink")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.unlink"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToUnlink");
return true;
}
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
else
{
ChatBlock.send(sender, "translocationNothingToUnlink");
return true;
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationImport")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.import"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToImport");
return true;
}
if (args.length == 0)
{
plugin.getTranslocationManager().importBlocks(field, player, null);
}
else
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
if (!field.getSettings().canTranslocate(entry))
{
ChatBlock.send(sender, "blockIsBlacklisted", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().importBlocks(field, player, entries);
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandMore")) && hasplayer)
{
ChatBlock cb = plugin.getCommunicationManager().getChatBlock(player);
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
cb.sendBlock(player, plugin.getSettingsManager().getLinesPerPage());
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
ChatBlock.send(sender, "moreNextPage");
}
ChatBlock.sendBlank(player);
return true;
}
ChatBlock.send(sender, "moreNothingMore");
return true;
}
else if (cmd.equals(ChatBlock.format("commandCounts")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.counts") && hasplayer)
{
if (!plugin.getCommunicationManager().showFieldCounts(player, player.getName()))
{
ChatBlock.send(sender, "playerHasNoFields");
}
return true;
}
if (args.length == 1 && plugin.getPermissionsManager().has(player, "preciousstones.admin.counts"))
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
if (!plugin.getCommunicationManager().showCounts(sender, type))
{
ChatBlock.send(sender, "notValidFieldType");
}
}
}
else if (Helper.isString(args[0]) && hasplayer)
{
String target = args[0];
if (!plugin.getCommunicationManager().showFieldCounts(player, target))
{
ChatBlock.send(sender, "playerHasNoFields");
}
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandLocations")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.locations") && hasplayer)
{
plugin.getCommunicationManager().showFieldLocations(sender, -1, sender.getName());
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.locations"))
{
if (args.length == 1 && Helper.isString(args[0]))
{
String targetName = args[0];
plugin.getCommunicationManager().showFieldLocations(sender, -1, targetName);
}
if (args.length == 2 && Helper.isString(args[0]) && Helper.isInteger(args[1]))
{
String targetName = args[0];
int type = Integer.parseInt(args[1]);
plugin.getCommunicationManager().showFieldLocations(sender, type, targetName);
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandInfo")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.info") && hasplayer)
{
Field pointing = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
List<Field> fields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (pointing != null && !fields.contains(pointing))
{
fields.add(pointing);
}
if (fields.size() == 1)
{
plugin.getCommunicationManager().showFieldDetails(player, fields.get(0));
}
else
{
plugin.getCommunicationManager().showFieldDetails(player, fields);
}
if (fields.isEmpty())
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.delete"))
{
if (args.length == 0 && hasplayer)
{
List<Field> sourceFields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (sourceFields.size() > 0)
{
int count = plugin.getForceFieldManager().deleteFields(sourceFields);
if (count > 0)
{
ChatBlock.send(sender, "protectionRemoved");
if (plugin.getSettingsManager().isLogBypassDelete())
{
PreciousStones.log("protectionRemovedFrom", count);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (args.length == 1)
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deleteFieldsOfType(type);
int ubs = plugin.getUnbreakableManager().deleteUnbreakablesOfType(type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedUnbreakables", ubs, Material.getMaterial(type.getTypeId()));
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
int fields = plugin.getForceFieldManager().deleteBelonging(args[0]);
int ubs = plugin.getUnbreakableManager().deleteBelonging(args[0]);
if (fields > 0)
{
ChatBlock.send(sender, "deletedCountFields", args[0], fields);
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedCountUnbreakables", args[0], ubs);
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "playerHasNoPstones");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetowner")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.setowner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
// transfer the count over to the new owner
PlayerEntry oldData = plugin.getPlayerManager().getPlayerEntry(field.getOwner());
oldData.decrementFieldCount(field.getSettings().getTypeEntry());
PlayerEntry newData = plugin.getPlayerManager().getPlayerEntry(owner);
newData.incrementFieldCount(field.getSettings().getTypeEntry());
plugin.getStorageManager().changeTranslocationOwner(field, owner);
plugin.getStorageManager().offerPlayer(field.getOwner());
plugin.getStorageManager().offerPlayer(owner);
// change the owner
field.setOwner(owner);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "ownerSetTo", owner);
return true;
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandChangeowner")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.change-owner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
if (field.isOwner(player.getName()))
{
if (field.hasFlag(FieldFlag.CAN_CHANGE_OWNER))
{
field.setNewOwner(owner);
ChatBlock.send(sender, "fieldCanBeTaken", owner);
return true;
}
else
{
ChatBlock.send(sender, "fieldCannotChangeOwner");
}
}
else
{
ChatBlock.send(sender, "ownerCanOnlyChangeOwner");
}
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandList")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.list") && hasplayer)
{
if (args.length == 1)
{
if (Helper.isInteger(args[0]))
{
int chunk_radius = Integer.parseInt(args[0]);
List<Unbreakable> unbreakables = plugin.getUnbreakableManager().getUnbreakablesInArea(player, chunk_radius);
Set<Field> fields = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), chunk_radius, FieldFlag.ALL);
for (Unbreakable u : unbreakables)
{
ChatBlock.send(sender, "{aqua}{unbreakable}", u.toString());
}
for (Field f : fields)
{
ChatBlock.send(sender, "{aqua}{field}", f.toString());
}
if (unbreakables.isEmpty() && fields.isEmpty())
{
ChatBlock.send(sender, "noPstonesFound");
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandReload")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reload"))
{
plugin.getSettingsManager().load();
ChatBlock.send(sender, "configReloaded");
return true;
}
else if (cmd.equals(ChatBlock.format("commandFields")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.fields"))
{
plugin.getCommunicationManager().showConfiguredFields(sender);
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.enableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().enableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagEnabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDisableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.disableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().disableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagDisabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandClean")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.clean"))
{
List<World> worlds = plugin.getServer().getWorlds();
int cleandFF = 0;
int cleandU = 0;
for (World world : worlds)
{
cleandFF += plugin.getForceFieldManager().cleanOrphans(world);
cleandU += plugin.getUnbreakableManager().cleanOrphans(world);
}
if (cleandFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleandFF);
}
if (cleandU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleandU);
}
if (cleandFF == 0 && cleandU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandRevert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.revert"))
{
List<World> worlds = plugin.getServer().getWorlds();
int cleandFF = 0;
int cleandU = 0;
for (World world : worlds)
{
cleandFF += plugin.getForceFieldManager().revertOrphans(world);
cleandU += plugin.getUnbreakableManager().revertOrphans(world);
}
if (cleandFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleandFF);
}
if (cleandU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleandU);
}
if (cleandFF == 0 && cleandU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
return true;
}
ChatBlock.send(sender, "notValidCommand");
return true;
}
// show the player menu
plugin.getCommunicationManager().showMenu(player);
return true;
}
}
catch (Exception ex)
{
System.out.print("Error: " + ex.getMessage());
for (StackTraceElement el : ex.getStackTrace())
{
System.out.print(el.toString());
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
try
{
if (command.getName().equals("ps"))
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
boolean hasplayer = player != null;
if (hasplayer)
{
if (plugin.getSettingsManager().isBlacklistedWorld(player.getWorld()))
{
ChatBlock.send(player, "psDisabled");
return true;
}
}
if (args.length > 0)
{
String cmd = args[0];
args = Helper.removeFirst(args);
Block block = hasplayer ? player.getWorld().getBlockAt(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) : null;
if (cmd.equals(ChatBlock.format("commandDraw")))
{
plugin.getForceFieldManager().drawSourceFields();
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebug")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebug(!plugin.getSettingsManager().isDebug());
if (plugin.getSettingsManager().isDebug())
{
ChatBlock.send(sender, "debugEnabled");
}
else
{
ChatBlock.send(sender, "debugDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebugdb")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebugdb(!plugin.getSettingsManager().isDebugdb());
if (plugin.getSettingsManager().isDebugdb())
{
ChatBlock.send(sender, "debugDbEnabled");
}
else
{
ChatBlock.send(sender, "debugDbDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDebugsql")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebugsql(!plugin.getSettingsManager().isDebugsql());
if (plugin.getSettingsManager().isDebugsql())
{
ChatBlock.send(sender, "debugSqlEnabled");
}
else
{
ChatBlock.send(sender, "debugSqlDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOn")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(false);
ChatBlock.send(sender, "placingEnabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyEnabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOff")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (!isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(true);
ChatBlock.send(sender, "placingDisabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandAllow")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allow") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
Player allowed = Helper.matchSinglePlayer(playerName);
// only those with permission can be allowed
if (field.getSettings().getRequiredPermissionAllow() != null)
{
if (!plugin.getPermissionsManager().has(allowed, field.getSettings().getRequiredPermissionAllow()))
{
ChatBlock.send(sender, "noPermsForAllow", playerName);
continue;
}
}
boolean done = plugin.getForceFieldManager().addAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "hasBeenAllowed", playerName);
}
else
{
ChatBlock.send(sender, "alreadyAllowed", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().allowAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "hasBeenAllowedIn", playerName, count);
}
else
{
ChatBlock.send(sender, "isAlreadyAllowedOnAll", playerName);
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.remove") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
if (field.containsPlayer(playerName))
{
ChatBlock.send(sender, "cannotRemovePlayerInField");
return true;
}
if (plugin.getForceFieldManager().conflictOfInterestExists(field, playerName))
{
ChatBlock.send(sender, "cannotDisallowWhenOverlap", playerName);
return true;
}
boolean done = plugin.getForceFieldManager().removeAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "removedFromField", playerName);
}
else
{
ChatBlock.send(sender, "playerNotFound", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemoveall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.removeall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().removeAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "removedFromFields", playerName, count);
}
else
{
ChatBlock.send(sender, "nothingToBeDone");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowed")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowed") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
List<String> allowed = field.getAllAllowed();
if (allowed.size() > 0)
{
ChatBlock.send(sender, "allowedList", Helper.toMessage(new ArrayList<String>(allowed), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersAllowedOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandCuboid")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.create.forcefield") && hasplayer)
{
if (args.length >= 1)
{
if ((args[0]).equals("commandCuboidOpen"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.CUBOID);
if (field != null)
{
plugin.getCuboidManager().openCuboid(player, field);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else if ((args[0]).equals("commandCuboidClose"))
{
plugin.getCuboidManager().closeCuboid(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandWho")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.who") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
HashSet<String> inhabitants = plugin.getForceFieldManager().getWho(field);
if (inhabitants.size() > 0)
{
ChatBlock.send(sender, "inhabitantsList", Helper.toMessage(new ArrayList<String>(inhabitants), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersFoundOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetname")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setname") && hasplayer)
{
String fieldName = null;
if (args.length >= 1)
{
fieldName = Helper.toMessage(args);
}
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
// if switching from an existing translocation
// end the previous one correctly by making sure
// to wipe out all applied blocks from the database
if (field.isNamed())
{
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
}
// check if one exists with that name already
if (plugin.getStorageManager().existsFieldWithName(fieldName, player.getName()))
{
ChatBlock.send(sender, "translocationExists");
return true;
}
// if this is a new translocation name, create its head record
// this will cement the size of the cuboid
if (!plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
plugin.getStorageManager().insertTranslocationHead(field, fieldName);
}
// updates the size of the field
plugin.getStorageManager().changeSizeTranslocatiorField(field, fieldName);
// always start off in applied (recording) mode
if (plugin.getStorageManager().existsTranslocationDataWithName(fieldName, field.getOwner()))
{
field.setDisabled(true);
}
else
{
field.setDisabled(false);
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (fieldName == null)
{
boolean done = plugin.getForceFieldManager().setNameField(field, "");
if (done)
{
ChatBlock.send(sender, "fieldNameCleared");
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
else
{
boolean done = plugin.getForceFieldManager().setNameField(field, fieldName);
if (done)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
int count = plugin.getStorageManager().unappliedTranslocationCount(field);
if (count > 0)
{
ChatBlock.send(sender, "translocationHasBlocks", fieldName, count);
}
else
{
ChatBlock.send(sender, "translocationCreated", fieldName);
}
}
else
{
ChatBlock.send(sender, "translocationRenamed", fieldName);
}
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetradius")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setradius") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
FieldSettings fs = field.getSettings();
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
ChatBlock.send(player, "translocationCannotReshape");
return true;
}
}
}
if (!field.hasFlag(FieldFlag.CUBOID))
{
if (radius >= 0 && (radius <= fs.getRadius() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.setradius")))
{
plugin.getForceFieldManager().removeSourceField(field);
field.setRadius(radius);
plugin.getStorageManager().offerField(field);
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "radiusSet", radius);
}
else
{
ChatBlock.send(sender, "radiusMustBeLessThan", fs.getRadius());
}
}
else
{
ChatBlock.send(sender, "cuboidCannotChangeRadius");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetvelocity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setvelocity") && hasplayer)
{
if (args.length == 1 && Helper.isFloat(args[0]))
{
float velocity = Float.parseFloat(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
FieldSettings fs = field.getSettings();
if (fs.hasVeocityFlag())
{
if (velocity < 0 || velocity > 5)
{
ChatBlock.send(sender, "velocityMustBe");
return true;
}
field.setVelocity(velocity);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "velocitySetTo", velocity);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandDisable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.disable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.isDisabled())
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().clearTranslocation(field);
}
}
field.setDisabled(true);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "fieldDisabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyDisabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.enable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isDisabled())
{
// update translocation
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().applyTranslocation(field);
}
}
field.setDisabled(false);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "fieldEnabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyEnabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDensity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.density") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int density = Integer.parseInt(args[0]);
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
data.setDensity(density);
plugin.getStorageManager().offerPlayer(player.getName());
ChatBlock.send(sender, "visualizationChanged", density);
return true;
}
else if (args.length == 0)
{
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
ChatBlock.send(sender, "visualizationSet", data.getDensity());
}
}
else if (cmd.equals(ChatBlock.format("commandToggle")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled"))
{
if (field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "flagsToggledWhileDisabled");
return true;
}
}
}
if (field.hasFlag(flagStr) || field.hasDisabledFlag(flagStr))
{
boolean unToggable = false;
if (field.hasFlag(FieldFlag.DYNMAP_NO_TOGGLE))
{
if (flagStr.equalsIgnoreCase("dynmap-area"))
{
unToggable = true;
}
if (flagStr.equalsIgnoreCase("dynmap-marker"))
{
unToggable = true;
}
}
if (plugin.getSettingsManager().isUnToggable(flagStr))
{
unToggable = true;
}
if (unToggable)
{
ChatBlock.send(sender, "flagCannottoggle");
return true;
}
boolean enabled = field.toggleFieldFlag(flagStr);
if (enabled)
{
ChatBlock.send(sender, "flagEnabled", flagStr);
}
else
{
ChatBlock.send(sender, "flagDisabled", flagStr);
}
field.dirtyFlags();
}
else
{
ChatBlock.send(sender, "flagNotFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if ((cmd.equals(ChatBlock.format("commandVisualize")) || cmd.equals("visualise")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize"))
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Math.min(Integer.parseInt(args[0]), plugin.getServer().getViewDistance());
Set<Field> fieldsInArea;
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize"))
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL);
}
else
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL, player);
}
if (fieldsInArea != null && fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "visualizing");
int count = 0;
for (Field f : fieldsInArea)
{
if (count++ >= plugin.getSettingsManager().getVisualizeMaxFields())
{
continue;
}
plugin.getVisualizationManager().addVisualizationField(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, true);
return true;
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
ChatBlock.send(sender, "visualizing");
plugin.getVisualizationManager().addVisualizationField(player, field);
plugin.getVisualizationManager().displayVisualization(player, true);
}
else
{
ChatBlock.send(sender, "notInsideField");
}
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "visualizationNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandMark")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.mark") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.mark"))
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "markingFields", fieldsInArea.size());
for (Field f : fieldsInArea)
{
plugin.getVisualizationManager().addFieldMark(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
int count = 0;
for (Field f : fieldsInArea)
{
if (plugin.getForceFieldManager().isAllowed(f, player.getName()))
{
count++;
plugin.getVisualizationManager().addFieldMark(player, f);
}
}
if (count > 0)
{
ChatBlock.send(sender, "markingFields", count);
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "markingNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandInsert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.insert") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.hasFlag(flagStr) && !field.hasDisabledFlag(flagStr))
{
if (field.insertFieldFlag(flagStr))
{
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "flagInserted");
plugin.getStorageManager().offerField(field);
}
else
{
ChatBlock.send(sender, "flagNotExists");
}
}
else
{
ChatBlock.send(sender, "flagExists");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandReset")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reset") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
field.RevertFlags();
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "flagsReverted");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetinterval")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setinterval") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int interval = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.GRIEF_REVERT);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (interval >= plugin.getSettingsManager().getGriefRevertMinInterval() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.interval"))
{
field.setRevertSecs(interval);
plugin.getGriefUndoManager().register(field);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "griefRevertIntervalSet", interval);
}
else
{
ChatBlock.send(sender, "minInterval", plugin.getSettingsManager().getGriefRevertMinInterval());
}
}
else
{
ChatBlock.send(sender, "notPointingAtGriefRevert");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSnitch")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.snitch") && hasplayer)
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
plugin.getCommunicationManager().showSnitchList(player, field);
}
else
{
ChatBlock.send(sender, "notPointingAtSnitch");
}
return true;
}
else if (args.length == 1)
{
if (args[0].equals("commandSnitchClear"))
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
boolean cleaned = plugin.getForceFieldManager().cleanSnitchList(field);
if (cleaned)
{
ChatBlock.send(sender, "clearedSnitch");
}
else
{
ChatBlock.send(sender, "snitchEmpty");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandTranslocation")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.use") && hasplayer)
{
if (args.length == 0)
{
ChatBlock.send(sender, "translocationMenu1");
ChatBlock.send(sender, "translocationMenu2");
ChatBlock.send(sender, "translocationMenu3");
ChatBlock.send(sender, "translocationMenu4");
ChatBlock.send(sender, "translocationMenu5");
ChatBlock.send(sender, "translocationMenu6");
ChatBlock.send(sender, "translocationMenu7");
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationList")))
{
plugin.getCommunicationManager().notifyStoredTranslocations(player);
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.delete"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (args.length == 0)
{
plugin.getStorageManager().deleteTranslocation(args[1], player.getName());
ChatBlock.send(sender, "translocationDeleted", args[0]);
}
else
{
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
int count = plugin.getStorageManager().deleteBlockTypeFromTranslocation(field.getName(), player.getName(), entry);
if (count > 0)
{
ChatBlock.send(sender, "translocationDeletedBlocks", count, Helper.friendlyBlockType(Material.getMaterial(entry.getTypeId()).toString()), field.getName());
}
else
{
ChatBlock.send(sender, "noBlocksMatched", arg);
}
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.remove"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledFirst");
return true;
}
if (args.length > 0)
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().removeBlocks(field, player, entries);
}
}
else
{
ChatBlock.send(sender, "usageTranslocationRemove");
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationUnlink")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.unlink"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToUnlink");
return true;
}
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
else
{
ChatBlock.send(sender, "translocationNothingToUnlink");
return true;
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationImport")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.import"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToImport");
return true;
}
if (args.length == 0)
{
plugin.getTranslocationManager().importBlocks(field, player, null);
}
else
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
if (!field.getSettings().canTranslocate(entry))
{
ChatBlock.send(sender, "blockIsBlacklisted", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().importBlocks(field, player, entries);
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandMore")) && hasplayer)
{
ChatBlock cb = plugin.getCommunicationManager().getChatBlock(player);
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
cb.sendBlock(player, plugin.getSettingsManager().getLinesPerPage());
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
ChatBlock.send(sender, "moreNextPage");
}
ChatBlock.sendBlank(player);
return true;
}
ChatBlock.send(sender, "moreNothingMore");
return true;
}
else if (cmd.equals(ChatBlock.format("commandCounts")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.counts") && hasplayer)
{
if (!plugin.getCommunicationManager().showFieldCounts(player, player.getName()))
{
ChatBlock.send(sender, "playerHasNoFields");
}
return true;
}
if (args.length == 1 && plugin.getPermissionsManager().has(player, "preciousstones.admin.counts"))
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
if (!plugin.getCommunicationManager().showCounts(sender, type))
{
ChatBlock.send(sender, "notValidFieldType");
}
}
}
else if (Helper.isString(args[0]) && hasplayer)
{
String target = args[0];
if (!plugin.getCommunicationManager().showFieldCounts(player, target))
{
ChatBlock.send(sender, "playerHasNoFields");
}
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandLocations")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.locations") && hasplayer)
{
plugin.getCommunicationManager().showFieldLocations(sender, -1, sender.getName());
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.locations"))
{
if (args.length == 1 && Helper.isString(args[0]))
{
String targetName = args[0];
plugin.getCommunicationManager().showFieldLocations(sender, -1, targetName);
}
if (args.length == 2 && Helper.isString(args[0]) && Helper.isInteger(args[1]))
{
String targetName = args[0];
int type = Integer.parseInt(args[1]);
plugin.getCommunicationManager().showFieldLocations(sender, type, targetName);
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandInfo")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.info") && hasplayer)
{
Field pointing = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
List<Field> fields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (pointing != null && !fields.contains(pointing))
{
fields.add(pointing);
}
if (fields.size() == 1)
{
plugin.getCommunicationManager().showFieldDetails(player, fields.get(0));
}
else
{
plugin.getCommunicationManager().showFieldDetails(player, fields);
}
if (fields.isEmpty())
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.delete"))
{
if (args.length == 0 && hasplayer)
{
List<Field> sourceFields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (sourceFields.size() > 0)
{
int count = plugin.getForceFieldManager().deleteFields(sourceFields);
if (count > 0)
{
ChatBlock.send(sender, "protectionRemoved");
if (plugin.getSettingsManager().isLogBypassDelete())
{
PreciousStones.log("protectionRemovedFrom", count);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (args.length == 1)
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deleteFieldsOfType(type);
int ubs = plugin.getUnbreakableManager().deleteUnbreakablesOfType(type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedUnbreakables", ubs, Material.getMaterial(type.getTypeId()));
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
int fields = plugin.getForceFieldManager().deleteBelonging(args[0]);
int ubs = plugin.getUnbreakableManager().deleteBelonging(args[0]);
if (fields > 0)
{
ChatBlock.send(sender, "deletedCountFields", args[0], fields);
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedCountUnbreakables", args[0], ubs);
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "playerHasNoPstones");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetowner")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.setowner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
// transfer the count over to the new owner
PlayerEntry oldData = plugin.getPlayerManager().getPlayerEntry(field.getOwner());
oldData.decrementFieldCount(field.getSettings().getTypeEntry());
PlayerEntry newData = plugin.getPlayerManager().getPlayerEntry(owner);
newData.incrementFieldCount(field.getSettings().getTypeEntry());
plugin.getStorageManager().changeTranslocationOwner(field, owner);
plugin.getStorageManager().offerPlayer(field.getOwner());
plugin.getStorageManager().offerPlayer(owner);
// change the owner
field.setOwner(owner);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "ownerSetTo", owner);
return true;
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandChangeowner")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.change-owner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
if (field.isOwner(player.getName()))
{
if (field.hasFlag(FieldFlag.CAN_CHANGE_OWNER))
{
field.setNewOwner(owner);
ChatBlock.send(sender, "fieldCanBeTaken", owner);
return true;
}
else
{
ChatBlock.send(sender, "fieldCannotChangeOwner");
}
}
else
{
ChatBlock.send(sender, "ownerCanOnlyChangeOwner");
}
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandList")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.list") && hasplayer)
{
if (args.length == 1)
{
if (Helper.isInteger(args[0]))
{
int chunk_radius = Integer.parseInt(args[0]);
List<Unbreakable> unbreakables = plugin.getUnbreakableManager().getUnbreakablesInArea(player, chunk_radius);
Set<Field> fields = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), chunk_radius, FieldFlag.ALL);
for (Unbreakable u : unbreakables)
{
ChatBlock.send(sender, "{aqua}{unbreakable}", u.toString());
}
for (Field f : fields)
{
ChatBlock.send(sender, "{aqua}{field}", f.toString());
}
if (unbreakables.isEmpty() && fields.isEmpty())
{
ChatBlock.send(sender, "noPstonesFound");
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandReload")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reload"))
{
plugin.getSettingsManager().load();
ChatBlock.send(sender, "configReloaded");
return true;
}
else if (cmd.equals(ChatBlock.format("commandFields")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.fields"))
{
plugin.getCommunicationManager().showConfiguredFields(sender);
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.enableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().enableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagEnabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDisableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.disableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().disableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagDisabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandClean")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.clean"))
{
List<World> worlds = plugin.getServer().getWorlds();
int cleandFF = 0;
int cleandU = 0;
for (World world : worlds)
{
cleandFF += plugin.getForceFieldManager().cleanOrphans(world);
cleandU += plugin.getUnbreakableManager().cleanOrphans(world);
}
if (cleandFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleandFF);
}
if (cleandU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleandU);
}
if (cleandFF == 0 && cleandU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandRevert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.revert"))
{
List<World> worlds = plugin.getServer().getWorlds();
int cleandFF = 0;
int cleandU = 0;
for (World world : worlds)
{
cleandFF += plugin.getForceFieldManager().revertOrphans(world);
cleandU += plugin.getUnbreakableManager().revertOrphans(world);
}
if (cleandFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleandFF);
}
if (cleandU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleandU);
}
if (cleandFF == 0 && cleandU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
return true;
}
ChatBlock.send(sender, "notValidCommand");
return true;
}
// show the player menu
plugin.getCommunicationManager().showMenu(player);
return true;
}
}
catch (Exception ex)
{
System.out.print("Error: " + ex.getMessage());
for (StackTraceElement el : ex.getStackTrace())
{
System.out.print(el.toString());
}
}
return false;
}
|
diff --git a/src/com/google/caja/plugin/stages/DebuggingSymbolsStage.java b/src/com/google/caja/plugin/stages/DebuggingSymbolsStage.java
index d259d909..2a2f72ca 100644
--- a/src/com/google/caja/plugin/stages/DebuggingSymbolsStage.java
+++ b/src/com/google/caja/plugin/stages/DebuggingSymbolsStage.java
@@ -1,134 +1,138 @@
// Copyright (C) 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.plugin.stages;
import com.google.caja.lexer.FilePosition;
import com.google.caja.parser.AncestorChain;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.js.Block;
import com.google.caja.parser.quasiliteral.QuasiBuilder;
import com.google.caja.plugin.Job;
import com.google.caja.plugin.Jobs;
import com.google.caja.plugin.PluginMessageType;
import com.google.caja.reporting.MessageQueue;
import com.google.caja.util.Pipeline;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import java.util.Map;
/**
* Adds debugging symbols to cajoled code. This looks for calls into the TCB
* object, {@code ___}, and adds an optional parameter to each call which is an
* index into a table of file positions.
* <p>
* This stage first walks over cajoled code looking for patterns like
* {@code ___.readPub(obj, 'key')}, and rewrites them to include an index into a
* table of debugging symbols: {@code ___.readPub(obj, 'key', 123)}.
* <p>
* It then rewrites the module envelope to make a symbol table to checks that
* may fail at runtime:
* <pre>
* ___.loadModule(
* function (___, IMPORTS___) {
* <b>___.useDebugSymbols('foo.js:1+12-15',7,'2+4-18');</b>
* ...
* })
* </pre>
* The debugSymbols are a list of the form
* <code>'[' <{@link FilePosition}> (',' <prefixLength> ','
* <Δ{@link FilePosition}>)* ']'</code>
* where the Δ{@code FilePosition}s are turned into {@code FilePosition}s
* by prepending them with the first prefixLength characters of the preceding
* {@code FilePosition}.
* <p>
* See also <tt>cajita-debugmode.js</tt> for javascript which supports this
* stage.
*
* @author [email protected]
*/
public final class DebuggingSymbolsStage implements Pipeline.Stage<Jobs> {
private static final boolean DEBUG = false;
public boolean apply(Jobs jobs) {
if (jobs.getPluginMeta().isDebugMode()) {
MessageQueue mq = jobs.getMessageQueue();
for (ListIterator<Job> it = jobs.getJobs().listIterator();
it.hasNext();) {
Job job = it.next();
- if (job.getType() != Job.JobType.JAVASCRIPT) { continue; }
+ if (job.getType() != Job.JobType.JAVASCRIPT
+ // May occur if the cajita rewriter does not run due to errors.
+ || !(job.getRoot().node instanceof Block)) {
+ continue;
+ }
if (DEBUG) {
System.err.println(
"\n\nPre\n===\n"
+ (job.getRoot().cast(Block.class).node.toStringDeep(1))
+ "\n\n");
}
DebuggingSymbols symbols = new DebuggingSymbols();
Block js = addSymbols(job.getRoot().cast(Block.class), symbols, mq);
if (!symbols.isEmpty()) {
if (DEBUG) {
System.err.println("\n\nPost\n===\n" + js.toStringDeep() + "\n\n");
}
it.set(
new Job(AncestorChain.instance(attachSymbols(symbols, js, mq))));
}
}
}
return jobs.hasNoFatalErrors();
}
/**
* Rewrites cajoled code to add position indices to caja operations.
* @param js cajoled javascript.
* @param symbols added to.
* @param mq receives rewriting messages.
* @return js rewritten.
*/
private Block addSymbols(
AncestorChain<Block> js, DebuggingSymbols symbols, MessageQueue mq) {
return (Block) new CajaRuntimeDebuggingRewriter(symbols)
.expand(js.node, mq);
}
/**
* Adds a call to ___.useDebugSymbols to a ___.loadModule call.
*/
private Block attachSymbols(
DebuggingSymbols symbols, Block js, MessageQueue mq) {
Map<String, ParseTreeNode> bindings
= new LinkedHashMap<String, ParseTreeNode>();
if (!QuasiBuilder.match(
"{ ___.loadModule(function (___, IMPORTS___) { @body* }); }",
js, bindings)) {
mq.addMessage(PluginMessageType.MALFORMED_ENVELOPE, js.getFilePosition());
return js;
}
return (Block) QuasiBuilder.substV(
"{"
+ "___.loadModule("
+ " function (___, IMPORTS___) {"
// Pass in varargs to avoid referencing the Array or Object symbol
// before those are pulled from IMPORTS___ in @body.
+ " ___.useDebugSymbols(@symbols*);"
+ " @body*"
+ " });"
+ "}",
"symbols", symbols.toJavascriptSideTable(),
"body", bindings.get("body"));
}
}
| true | true | public boolean apply(Jobs jobs) {
if (jobs.getPluginMeta().isDebugMode()) {
MessageQueue mq = jobs.getMessageQueue();
for (ListIterator<Job> it = jobs.getJobs().listIterator();
it.hasNext();) {
Job job = it.next();
if (job.getType() != Job.JobType.JAVASCRIPT) { continue; }
if (DEBUG) {
System.err.println(
"\n\nPre\n===\n"
+ (job.getRoot().cast(Block.class).node.toStringDeep(1))
+ "\n\n");
}
DebuggingSymbols symbols = new DebuggingSymbols();
Block js = addSymbols(job.getRoot().cast(Block.class), symbols, mq);
if (!symbols.isEmpty()) {
if (DEBUG) {
System.err.println("\n\nPost\n===\n" + js.toStringDeep() + "\n\n");
}
it.set(
new Job(AncestorChain.instance(attachSymbols(symbols, js, mq))));
}
}
}
return jobs.hasNoFatalErrors();
}
| public boolean apply(Jobs jobs) {
if (jobs.getPluginMeta().isDebugMode()) {
MessageQueue mq = jobs.getMessageQueue();
for (ListIterator<Job> it = jobs.getJobs().listIterator();
it.hasNext();) {
Job job = it.next();
if (job.getType() != Job.JobType.JAVASCRIPT
// May occur if the cajita rewriter does not run due to errors.
|| !(job.getRoot().node instanceof Block)) {
continue;
}
if (DEBUG) {
System.err.println(
"\n\nPre\n===\n"
+ (job.getRoot().cast(Block.class).node.toStringDeep(1))
+ "\n\n");
}
DebuggingSymbols symbols = new DebuggingSymbols();
Block js = addSymbols(job.getRoot().cast(Block.class), symbols, mq);
if (!symbols.isEmpty()) {
if (DEBUG) {
System.err.println("\n\nPost\n===\n" + js.toStringDeep() + "\n\n");
}
it.set(
new Job(AncestorChain.instance(attachSymbols(symbols, js, mq))));
}
}
}
return jobs.hasNoFatalErrors();
}
|
diff --git a/src/main/java/org/jukito/JukitoModule.java b/src/main/java/org/jukito/JukitoModule.java
index 209b8d2..fd7b24b 100644
--- a/src/main/java/org/jukito/JukitoModule.java
+++ b/src/main/java/org/jukito/JukitoModule.java
@@ -1,427 +1,429 @@
/**
* Copyright 2011 ArcBees 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.jukito;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.jukito.BindingsCollector.BindingInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.ConfigurationException;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.MembersInjector;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.Stage;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.internal.Errors;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.HasDependencies;
import com.google.inject.spi.InjectionPoint;
/**
* A guice {@link com.google.inject.Module Module} with a bit of syntactic sugar
* to bind within typical test scopes. Depends on mockito. This module
* automatically mocks any interface or abstract class dependency for which a
* binding is not explicitly provided. Any concrete class for which a binding is
* not explicitly provided is bound as a {@link TestScope#SINGLETON}.
* <p />
* Depends on Mockito.
*
* @author Philippe Beaudoin
*/
public abstract class JukitoModule extends TestModule {
protected List<BindingInfo> bindingsObserved = Collections.emptyList();
private final Set<Class<?>> forceMock = new HashSet<Class<?>>();
private final Set<Class<?>> dontForceMock = new HashSet<Class<?>>();
private final List<Key<?>> keysNeedingTransitiveDependencies = new ArrayList<Key<?>>();
private final Map<Class<?>, Object> primitiveTypes = new HashMap<Class<?>, Object>();
public JukitoModule() {
primitiveTypes.put(String.class, "");
primitiveTypes.put(Integer.class, 0);
primitiveTypes.put(Long.class, 0L);
primitiveTypes.put(Boolean.class, false);
primitiveTypes.put(Double.class, 0.0);
primitiveTypes.put(Float.class, 0.0f);
primitiveTypes.put(Short.class, (short) 0);
primitiveTypes.put(Character.class, '\0');
primitiveTypes.put(Byte.class, (byte) 0);
primitiveTypes.put(Class.class, Object.class);
}
/**
* Attach this {@link JukitoModule} to a list of the bindings that were
* observed by a preliminary run of {@link BindingsCollector}.
*
* @param bindingsObserved The observed bindings.
*/
public void setBindingsObserved(List<BindingInfo> bindingsObserved) {
this.bindingsObserved = bindingsObserved;
}
/**
* By default, only abstract classes, interfaces and classes annotated with
* {@link TestMockSingleton} are automatically mocked. Use {@link #forceMock}
* to indicate that all concrete classes derived from the a specific type
* will be mocked in {@link org.jukito.TestMockSingleton} scope.
*
* @param klass The {@link Class} or interface for which all subclasses will
* be mocked.
*/
protected void forceMock(Class<?> klass) {
forceMock.add(klass);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public final void configure() {
bindScopes();
configureTest();
Set<Key<?>> keysObserved = new HashSet<Key<?>>(bindingsObserved.size());
Set<Key<?>> keysNeeded = new HashSet<Key<?>>(bindingsObserved.size());
for (BindingInfo bindingInfo : bindingsObserved) {
if (bindingInfo.key != null) {
keysObserved.add(bindingInfo.key);
}
if (bindingInfo.boundKey != null) {
keysNeeded.add(bindingInfo.boundKey);
}
if (bindingInfo.boundInstance != null &&
bindingInfo.boundInstance instanceof HasDependencies) {
HasDependencies hasDependencies = (HasDependencies) bindingInfo.boundInstance;
for (Dependency<?> dependency : hasDependencies.getDependencies()) {
keysNeeded.add(dependency.getKey());
}
}
}
// Make sure needed keys from Guice bindings are bound as mock or to instances
// (but not as test singletons)
for (Key<?> keyNeeded : keysNeeded) {
addNeededKey(keysObserved, keysNeeded, keyNeeded, false);
keysNeedingTransitiveDependencies.add(keyNeeded);
}
// Preempt JIT binding by looking through the test class and any parent class
// looking for methods annotated with @Test, @Before, or @After.
// Concrete classes bound in this way are bound in @TestSingleton.
Class<?> currentClass = testClass;
while (currentClass != null) {
for (Method method : currentClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(Test.class)
|| method.isAnnotationPresent(Before.class)
|| method.isAnnotationPresent(After.class)) {
Errors errors = new Errors(method);
List<Key<?>> keys = GuiceUtils.getMethodKeys(method, errors);
for (Key<?> key : keys) {
// Skip keys annotated with @All
if (!All.class.equals(key.getAnnotationType())) {
Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(key, errors);
addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
}
}
errors.throwConfigurationExceptionIfErrorsExist();
}
}
currentClass = currentClass.getSuperclass();
}
// Preempt JIT binding by looking through the test class looking for
// fields and methods annotated with @Inject.
// Concrete classes bound in this way are bound in @TestSingleton.
- Set<InjectionPoint> injectionPoints = InjectionPoint.forInstanceMethodsAndFields(testClass);
- for (InjectionPoint injectionPoint : injectionPoints) {
- Errors errors = new Errors(injectionPoint);
- List<Dependency<?>> dependencies = injectionPoint.getDependencies();
- for (Dependency<?> dependency : dependencies) {
- Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(dependency.getKey(),
- errors);
- addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
+ if (testClass != null) {
+ Set<InjectionPoint> injectionPoints = InjectionPoint.forInstanceMethodsAndFields(testClass);
+ for (InjectionPoint injectionPoint : injectionPoints) {
+ Errors errors = new Errors(injectionPoint);
+ List<Dependency<?>> dependencies = injectionPoint.getDependencies();
+ for (Dependency<?> dependency : dependencies) {
+ Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(dependency.getKey(),
+ errors);
+ addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
+ }
+ errors.throwConfigurationExceptionIfErrorsExist();
}
- errors.throwConfigurationExceptionIfErrorsExist();
}
// Recursively add the dependencies of all the bindings observed
for (int i = 0; i < keysNeedingTransitiveDependencies.size(); ++i) {
addDependencies(keysNeedingTransitiveDependencies.get(i), keysObserved, keysNeeded);
}
// Bind all keys needed but not observed as mocks
for (Key<?> key : keysNeeded) {
Class<?> rawType = key.getTypeLiteral().getRawType();
if (!keysObserved.contains(key) && !isCoreGuiceType(rawType)
&& !isAssistedInjection(key)) {
Object primitiveInstance = getDummyInstanceOfPrimitiveType(rawType);
if (primitiveInstance == null) {
bind(key).toProvider(new MockProvider(rawType)).in(TestScope.SINGLETON);
} else {
bindKeyToInstance(key, primitiveInstance);
}
}
}
}
@SuppressWarnings("unchecked")
private <T> void bindKeyToInstance(Key<T> key, Object primitiveInstance) {
bind(key).toInstance((T) primitiveInstance);
}
private void addNeededKey(Set<Key<?>> keysObserved, Set<Key<?>> keysNeeded,
Key<?> keyNeeded, boolean asTestSingleton) {
keysNeeded.add(keyNeeded);
bindIfConcrete(keysObserved, keyNeeded, asTestSingleton);
}
private <T> void bindIfConcrete(Set<Key<?>> keysObserved,
Key<T> key, boolean asTestSingleton) {
TypeLiteral<?> typeToBind = key.getTypeLiteral();
Class<?> rawType = typeToBind.getRawType();
if (!keysObserved.contains(key) && canBeInjected(typeToBind)
&& !shouldForceMock(rawType) && !isAssistedInjection(key)) {
// If an @Singleton annotation is present, force the bind as TestSingleton
if (asTestSingleton ||
rawType.getAnnotation(Singleton.class) != null) {
bind(key).in(TestScope.SINGLETON);
} else {
bind(key);
}
keysObserved.add(key);
keysNeedingTransitiveDependencies.add(key);
}
}
private boolean canBeInjected(TypeLiteral<?> type) {
Class<?> rawType = type.getRawType();
if (isPrimitive(rawType) || isCoreGuiceType(rawType) || !isInstantiable(rawType)) {
return false;
}
try {
InjectionPoint.forConstructorOf(type);
return true;
} catch (ConfigurationException e) {
return false;
}
}
private boolean isAssistedInjection(Key<?> key) {
return key.getAnnotationType() != null
&& Assisted.class.isAssignableFrom(key.getAnnotationType());
}
private boolean shouldForceMock(Class<?> klass) {
if (dontForceMock.contains(klass)) {
return false;
}
if (forceMock.contains(klass)) {
return true;
}
// The forceMock set contains all the base classes the user wants
// to force mock, check id the specified klass is a subclass of one of
// these.
// Update forceMock or dontForceMock based on the result to speed-up
// future look-ups.
boolean result = false;
for (Class<?> classToMock : forceMock) {
if (classToMock.isAssignableFrom(klass)) {
result = true;
break;
}
}
if (result) {
forceMock.add(klass);
} else {
dontForceMock.add(klass);
}
return result;
}
private boolean isInstantiable(Class<?> klass) {
return !klass.isInterface() && !Modifier.isAbstract(klass.getModifiers());
}
private boolean isPrimitive(Class<?> klass) {
return getDummyInstanceOfPrimitiveType(klass) != null;
}
private Object getDummyInstanceOfPrimitiveType(Class<?> klass) {
Object instance = primitiveTypes.get(klass);
if (instance == null && Enum.class.isAssignableFrom(klass)) {
// Safe to ignore exception, Guice will fail with a reasonable error
// if the Enum is empty.
try {
instance = ((Object[]) klass.getMethod("values").invoke(null))[0];
} catch (Exception e) {
}
}
return instance;
}
private boolean isCoreGuiceType(Class<?> klass) {
return TypeLiteral.class.isAssignableFrom(klass)
|| Injector.class.isAssignableFrom(klass)
|| Logger.class.isAssignableFrom(klass)
|| Stage.class.isAssignableFrom(klass)
|| MembersInjector.class.isAssignableFrom(klass);
}
private <T> void addDependencies(Key<T> key, Set<Key<?>> keysObserved,
Set<Key<?>> keysNeeded) {
TypeLiteral<T> type = key.getTypeLiteral();
if (!canBeInjected(type)) {
return;
}
addInjectionPointDependencies(InjectionPoint.forConstructorOf(type),
keysObserved, keysNeeded);
Set<InjectionPoint> methodsAndFieldsInjectionPoints =
InjectionPoint.forInstanceMethodsAndFields(type);
for (InjectionPoint injectionPoint : methodsAndFieldsInjectionPoints) {
addInjectionPointDependencies(injectionPoint, keysObserved, keysNeeded);
}
}
private void addInjectionPointDependencies(InjectionPoint injectionPoint,
Set<Key<?>> keysObserved, Set<Key<?>> keysNeeded) {
// Do not consider dependencies coming from optional injections
if (injectionPoint.isOptional()) {
return;
}
for (Dependency<?> dependency : injectionPoint.getDependencies()) {
Key<?> key = dependency.getKey();
addKeyDependency(key, keysObserved, keysNeeded);
}
}
private void addKeyDependency(Key<?> key, Set<Key<?>> keysObserved,
Set<Key<?>> keysNeeded) {
Key<?> newKey = key;
if (Provider.class.isAssignableFrom(key.getTypeLiteral().getRawType())) {
Type providedType = (
(ParameterizedType) key.getTypeLiteral().getType()).getActualTypeArguments()[0];
if (key.getAnnotation() != null) {
newKey = Key.get(providedType, key.getAnnotation());
} else if (key.getAnnotationType() != null) {
newKey = Key.get(providedType, key.getAnnotationType());
} else {
newKey = Key.get(providedType);
}
}
addNeededKey(keysObserved, keysNeeded, newKey, true);
}
/**
* Override and return the {@link Writer} you want to use to report the tree of test objects,and whether they
* were mocked, spied, automatically instantiated, or explicitly bound. Mostly useful for
* debugging.
*
* @return The {@link Writer}, if {@code null} no report will be output.
*/
public Writer getReportWriter() {
return null;
}
/**
* Outputs the report, see {@link #setReportWriter(Writer)}. Will not output anything if the
* {@code reportWriter} is {@code null}. Do not call directly, it will be called by
* {@link JukitoRunner}. To obtain a report, override {@link #getReportWriter()}.
*/
public void printReport(List<BindingInfo> allBindings) {
Writer reportWriter = getReportWriter();
if (reportWriter == null) {
return;
}
try {
reportWriter.append("*** EXPLICIT BINDINGS ***\n");
Set<Key<?>> reportedKeys = outputBindings(reportWriter, bindingsObserved,
Collections.<Key<?>>emptySet());
reportWriter.append('\n');
reportWriter.append("*** AUTOMATIC BINDINGS ***\n");
outputBindings(reportWriter, allBindings, reportedKeys);
reportWriter.append('\n');
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param reportWriter The {@link Writer} to use to output the report.
* @param bindings The bindings to report.
* @param keysToSkip The keys that should not be reported.
* @return All the keys that were reported.
* @throws IOException If something goes wrong when writing.
*/
private Set<Key<?>> outputBindings(Writer reportWriter, List<BindingInfo> bindings,
Set<Key<?>> keysToSkip) throws IOException {
Set<Key<?>> reportedKeys = new HashSet<Key<?>>(bindings.size());
for (BindingInfo bindingInfo : bindings) {
if (keysToSkip.contains(bindingInfo.key)) {
continue;
}
reportedKeys.add(bindingInfo.key);
reportWriter.append(" ");
reportWriter.append(bindingInfo.key.toString());
reportWriter.append(" --> ");
if (bindingInfo.boundKey != null) {
if (bindingInfo.key == bindingInfo.boundKey) {
reportWriter.append("Bound directly");
} else {
reportWriter.append(bindingInfo.boundKey.toString());
}
} else if (bindingInfo.boundInstance != null) {
reportWriter.append("Instance of " + bindingInfo.boundInstance.getClass().getCanonicalName());
} else {
reportWriter.append("NOTHING!?");
}
reportWriter.append(" ### ");
if (bindingInfo.scope == null) {
reportWriter.append("No scope");
} else {
reportWriter.append("In scope ");
reportWriter.append(bindingInfo.scope);
}
reportWriter.append('\n');
}
return reportedKeys;
}
}
| false | true | public final void configure() {
bindScopes();
configureTest();
Set<Key<?>> keysObserved = new HashSet<Key<?>>(bindingsObserved.size());
Set<Key<?>> keysNeeded = new HashSet<Key<?>>(bindingsObserved.size());
for (BindingInfo bindingInfo : bindingsObserved) {
if (bindingInfo.key != null) {
keysObserved.add(bindingInfo.key);
}
if (bindingInfo.boundKey != null) {
keysNeeded.add(bindingInfo.boundKey);
}
if (bindingInfo.boundInstance != null &&
bindingInfo.boundInstance instanceof HasDependencies) {
HasDependencies hasDependencies = (HasDependencies) bindingInfo.boundInstance;
for (Dependency<?> dependency : hasDependencies.getDependencies()) {
keysNeeded.add(dependency.getKey());
}
}
}
// Make sure needed keys from Guice bindings are bound as mock or to instances
// (but not as test singletons)
for (Key<?> keyNeeded : keysNeeded) {
addNeededKey(keysObserved, keysNeeded, keyNeeded, false);
keysNeedingTransitiveDependencies.add(keyNeeded);
}
// Preempt JIT binding by looking through the test class and any parent class
// looking for methods annotated with @Test, @Before, or @After.
// Concrete classes bound in this way are bound in @TestSingleton.
Class<?> currentClass = testClass;
while (currentClass != null) {
for (Method method : currentClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(Test.class)
|| method.isAnnotationPresent(Before.class)
|| method.isAnnotationPresent(After.class)) {
Errors errors = new Errors(method);
List<Key<?>> keys = GuiceUtils.getMethodKeys(method, errors);
for (Key<?> key : keys) {
// Skip keys annotated with @All
if (!All.class.equals(key.getAnnotationType())) {
Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(key, errors);
addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
}
}
errors.throwConfigurationExceptionIfErrorsExist();
}
}
currentClass = currentClass.getSuperclass();
}
// Preempt JIT binding by looking through the test class looking for
// fields and methods annotated with @Inject.
// Concrete classes bound in this way are bound in @TestSingleton.
Set<InjectionPoint> injectionPoints = InjectionPoint.forInstanceMethodsAndFields(testClass);
for (InjectionPoint injectionPoint : injectionPoints) {
Errors errors = new Errors(injectionPoint);
List<Dependency<?>> dependencies = injectionPoint.getDependencies();
for (Dependency<?> dependency : dependencies) {
Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(dependency.getKey(),
errors);
addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
}
errors.throwConfigurationExceptionIfErrorsExist();
}
// Recursively add the dependencies of all the bindings observed
for (int i = 0; i < keysNeedingTransitiveDependencies.size(); ++i) {
addDependencies(keysNeedingTransitiveDependencies.get(i), keysObserved, keysNeeded);
}
// Bind all keys needed but not observed as mocks
for (Key<?> key : keysNeeded) {
Class<?> rawType = key.getTypeLiteral().getRawType();
if (!keysObserved.contains(key) && !isCoreGuiceType(rawType)
&& !isAssistedInjection(key)) {
Object primitiveInstance = getDummyInstanceOfPrimitiveType(rawType);
if (primitiveInstance == null) {
bind(key).toProvider(new MockProvider(rawType)).in(TestScope.SINGLETON);
} else {
bindKeyToInstance(key, primitiveInstance);
}
}
}
}
| public final void configure() {
bindScopes();
configureTest();
Set<Key<?>> keysObserved = new HashSet<Key<?>>(bindingsObserved.size());
Set<Key<?>> keysNeeded = new HashSet<Key<?>>(bindingsObserved.size());
for (BindingInfo bindingInfo : bindingsObserved) {
if (bindingInfo.key != null) {
keysObserved.add(bindingInfo.key);
}
if (bindingInfo.boundKey != null) {
keysNeeded.add(bindingInfo.boundKey);
}
if (bindingInfo.boundInstance != null &&
bindingInfo.boundInstance instanceof HasDependencies) {
HasDependencies hasDependencies = (HasDependencies) bindingInfo.boundInstance;
for (Dependency<?> dependency : hasDependencies.getDependencies()) {
keysNeeded.add(dependency.getKey());
}
}
}
// Make sure needed keys from Guice bindings are bound as mock or to instances
// (but not as test singletons)
for (Key<?> keyNeeded : keysNeeded) {
addNeededKey(keysObserved, keysNeeded, keyNeeded, false);
keysNeedingTransitiveDependencies.add(keyNeeded);
}
// Preempt JIT binding by looking through the test class and any parent class
// looking for methods annotated with @Test, @Before, or @After.
// Concrete classes bound in this way are bound in @TestSingleton.
Class<?> currentClass = testClass;
while (currentClass != null) {
for (Method method : currentClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(Test.class)
|| method.isAnnotationPresent(Before.class)
|| method.isAnnotationPresent(After.class)) {
Errors errors = new Errors(method);
List<Key<?>> keys = GuiceUtils.getMethodKeys(method, errors);
for (Key<?> key : keys) {
// Skip keys annotated with @All
if (!All.class.equals(key.getAnnotationType())) {
Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(key, errors);
addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
}
}
errors.throwConfigurationExceptionIfErrorsExist();
}
}
currentClass = currentClass.getSuperclass();
}
// Preempt JIT binding by looking through the test class looking for
// fields and methods annotated with @Inject.
// Concrete classes bound in this way are bound in @TestSingleton.
if (testClass != null) {
Set<InjectionPoint> injectionPoints = InjectionPoint.forInstanceMethodsAndFields(testClass);
for (InjectionPoint injectionPoint : injectionPoints) {
Errors errors = new Errors(injectionPoint);
List<Dependency<?>> dependencies = injectionPoint.getDependencies();
for (Dependency<?> dependency : dependencies) {
Key<?> keyNeeded = GuiceUtils.ensureProvidedKey(dependency.getKey(),
errors);
addNeededKey(keysObserved, keysNeeded, keyNeeded, true);
}
errors.throwConfigurationExceptionIfErrorsExist();
}
}
// Recursively add the dependencies of all the bindings observed
for (int i = 0; i < keysNeedingTransitiveDependencies.size(); ++i) {
addDependencies(keysNeedingTransitiveDependencies.get(i), keysObserved, keysNeeded);
}
// Bind all keys needed but not observed as mocks
for (Key<?> key : keysNeeded) {
Class<?> rawType = key.getTypeLiteral().getRawType();
if (!keysObserved.contains(key) && !isCoreGuiceType(rawType)
&& !isAssistedInjection(key)) {
Object primitiveInstance = getDummyInstanceOfPrimitiveType(rawType);
if (primitiveInstance == null) {
bind(key).toProvider(new MockProvider(rawType)).in(TestScope.SINGLETON);
} else {
bindKeyToInstance(key, primitiveInstance);
}
}
}
}
|
diff --git a/src/com/android/contacts/ViewContactActivity.java b/src/com/android/contacts/ViewContactActivity.java
index 3d5ac859c..e6dd623e9 100644
--- a/src/com/android/contacts/ViewContactActivity.java
+++ b/src/com/android/contacts/ViewContactActivity.java
@@ -1,1248 +1,1247 @@
/*
* Copyright (C) 2007 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.contacts;
import com.android.contacts.Collapser.Collapsible;
import com.android.contacts.model.ContactsSource;
import com.android.contacts.model.Sources;
import com.android.contacts.model.ContactsSource.DataKind;
import com.android.contacts.ui.EditContactActivity;
import com.android.contacts.util.Constants;
import com.android.contacts.util.DataStatus;
import com.android.contacts.util.NotifyingAsyncQueryHandler;
import com.android.internal.telephony.ITelephony;
import com.android.internal.widget.ContactHeaderWidget;
import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Entity;
import android.content.EntityIterator;
import android.content.Intent;
import android.content.Entity.NamedContentValues;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.AggregationExceptions;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.StatusUpdates;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Displays the details of a specific contact.
*/
public class ViewContactActivity extends Activity
implements View.OnCreateContextMenuListener, DialogInterface.OnClickListener,
AdapterView.OnItemClickListener, NotifyingAsyncQueryHandler.AsyncQueryListener {
private static final String TAG = "ViewContact";
private static final boolean SHOW_SEPARATORS = false;
private static final int DIALOG_CONFIRM_DELETE = 1;
private static final int DIALOG_CONFIRM_READONLY_DELETE = 2;
private static final int DIALOG_CONFIRM_MULTIPLE_DELETE = 3;
private static final int DIALOG_CONFIRM_READONLY_HIDE = 4;
private static final int REQUEST_JOIN_CONTACT = 1;
private static final int REQUEST_EDIT_CONTACT = 2;
public static final int MENU_ITEM_MAKE_DEFAULT = 3;
protected Uri mLookupUri;
private ContentResolver mResolver;
private ViewAdapter mAdapter;
private int mNumPhoneNumbers = 0;
/**
* A list of distinct contact IDs included in the current contact.
*/
private ArrayList<Long> mRawContactIds = new ArrayList<Long>();
/* package */ ArrayList<ViewEntry> mPhoneEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mSmsEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mEmailEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mPostalEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mImEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mOrganizationEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mGroupEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mOtherEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ArrayList<ViewEntry>> mSections = new ArrayList<ArrayList<ViewEntry>>();
private Cursor mCursor;
protected ContactHeaderWidget mContactHeaderWidget;
private NotifyingAsyncQueryHandler mHandler;
protected LayoutInflater mInflater;
protected int mReadOnlySourcesCnt;
protected int mWritableSourcesCnt;
protected ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>();
private static final int TOKEN_ENTITIES = 0;
private static final int TOKEN_STATUSES = 1;
private boolean mHasEntities = false;
private boolean mHasStatuses = false;
private ArrayList<Entity> mEntities = Lists.newArrayList();
private HashMap<Long, DataStatus> mStatuses = Maps.newHashMap();
private ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
if (mCursor != null && !mCursor.isClosed()) {
startEntityQuery();
}
}
};
public void onClick(DialogInterface dialog, int which) {
closeCursor();
getContentResolver().delete(mLookupUri, null, null);
finish();
}
private FrameLayout mTabContentLayout;
private ListView mListView;
private boolean mShowSmsLinksForAllPhones;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
final Intent intent = getIntent();
Uri data = intent.getData();
String authority = data.getAuthority();
if (ContactsContract.AUTHORITY.equals(authority)) {
mLookupUri = data;
} else if (android.provider.Contacts.AUTHORITY.equals(authority)) {
final long rawContactId = ContentUris.parseId(data);
mLookupUri = RawContacts.getContactLookupUri(getContentResolver(),
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
}
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.contact_card_layout);
mContactHeaderWidget = (ContactHeaderWidget) findViewById(R.id.contact_header_widget);
mContactHeaderWidget.showStar(true);
mContactHeaderWidget.setExcludeMimes(new String[] {
Contacts.CONTENT_ITEM_TYPE
});
mHandler = new NotifyingAsyncQueryHandler(this, this);
mListView = new ListView(this);
mListView.setOnCreateContextMenuListener(this);
mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY);
mListView.setOnItemClickListener(this);
mTabContentLayout = (FrameLayout) findViewById(android.R.id.tabcontent);
mTabContentLayout.addView(mListView);
mResolver = getContentResolver();
// Build the list of sections. The order they're added to mSections dictates the
// order they are displayed in the list.
mSections.add(mPhoneEntries);
mSections.add(mSmsEntries);
mSections.add(mEmailEntries);
mSections.add(mImEntries);
mSections.add(mPostalEntries);
mSections.add(mOrganizationEntries);
mSections.add(mGroupEntries);
mSections.add(mOtherEntries);
//TODO Read this value from a preference
mShowSmsLinksForAllPhones = true;
}
@Override
protected void onResume() {
super.onResume();
startEntityQuery();
}
@Override
protected void onPause() {
super.onPause();
closeCursor();
}
@Override
protected void onDestroy() {
super.onDestroy();
closeCursor();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CONFIRM_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.deleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_READONLY_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.readOnlyContactDeleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_MULTIPLE_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.multipleContactDeleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_READONLY_HIDE: {
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.readOnlyContactWarning)
.setPositiveButton(android.R.string.ok, this)
.create();
}
}
return null;
}
// QUERY CODE //
/** {@inheritDoc} */
public void onQueryEntitiesComplete(int token, Object cookie, EntityIterator iterator) {
try {
// Read incoming entities and consider binding
readEntities(iterator);
considerBindData();
} finally {
if (iterator != null) {
iterator.close();
}
}
}
/** {@inheritDoc} */
public void onQueryComplete(int token, Object cookie, Cursor cursor) {
try {
// Read available social rows and consider binding
readStatuses(cursor);
considerBindData();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private long getRefreshedContactId() {
Uri freshContactUri = Contacts.lookupContact(getContentResolver(), mLookupUri);
if (freshContactUri != null) {
return ContentUris.parseId(freshContactUri);
}
return -1;
}
/**
* Read from the given {@link EntityIterator} to build internal set of
* {@link #mEntities} for data display.
*/
private synchronized void readEntities(EntityIterator iterator) {
mEntities.clear();
try {
while (iterator.hasNext()) {
mEntities.add(iterator.next());
}
mHasEntities = true;
} catch (RemoteException e) {
Log.w(TAG, "Problem reading contact data: " + e.toString());
}
}
/**
* Read from the given {@link Cursor} and build a set of {@link DataStatus}
* objects to match any valid statuses found.
*/
private synchronized void readStatuses(Cursor cursor) {
mStatuses.clear();
// Walk found statuses, creating internal row for each
while (cursor.moveToNext()) {
final DataStatus status = new DataStatus(cursor);
final long dataId = cursor.getLong(StatusQuery._ID);
mStatuses.put(dataId, status);
}
mHasStatuses = true;
}
private synchronized void startEntityQuery() {
closeCursor();
Uri uri = null;
if (mLookupUri != null) {
mLookupUri = Contacts.getLookupUri(getContentResolver(), mLookupUri);
if (mLookupUri != null) {
uri = Contacts.lookupContact(getContentResolver(), mLookupUri);
}
}
if (uri == null) {
// TODO either figure out a way to prevent a flash of black background or
// use some other UI than a toast
Toast.makeText(this, R.string.invalidContactMessage, Toast.LENGTH_SHORT).show();
Log.e(TAG, "invalid contact uri: " + mLookupUri);
finish();
return;
}
final Uri dataUri = Uri.withAppendedPath(uri, Contacts.Data.CONTENT_DIRECTORY);
// Keep stub cursor open on side to watch for change events
mCursor = mResolver.query(dataUri,
new String[] {Contacts.DISPLAY_NAME}, null, null, null);
mCursor.registerContentObserver(mObserver);
final long contactId = ContentUris.parseId(uri);
// Clear flags and start queries to data and status
mHasEntities = false;
mHasStatuses = false;
mHandler.startQueryEntities(TOKEN_ENTITIES, null, RawContacts.CONTENT_URI,
RawContacts.CONTACT_ID + "=" + contactId, null, null);
mHandler.startQuery(TOKEN_STATUSES, null, dataUri, StatusQuery.PROJECTION,
StatusUpdates.PRESENCE + " IS NOT NULL OR " + StatusUpdates.STATUS
+ " IS NOT NULL", null, null);
mContactHeaderWidget.bindFromContactLookupUri(mLookupUri);
}
private void closeCursor() {
if (mCursor != null) {
mCursor.unregisterContentObserver(mObserver);
mCursor.close();
mCursor = null;
}
}
/**
* Consider binding views after any of several background queries has
* completed. We check internal flags and only bind when all data has
* arrived.
*/
private void considerBindData() {
if (mHasEntities && mHasStatuses) {
bindData();
}
}
private void bindData() {
// Build up the contact entries
buildEntries();
// Collapse similar data items in select sections.
Collapser.collapseList(mPhoneEntries);
Collapser.collapseList(mSmsEntries);
Collapser.collapseList(mEmailEntries);
Collapser.collapseList(mPostalEntries);
Collapser.collapseList(mImEntries);
if (mAdapter == null) {
mAdapter = new ViewAdapter(this, mSections);
mListView.setAdapter(mAdapter);
} else {
mAdapter.setSections(mSections, SHOW_SEPARATORS);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// Only allow edit when we have at least one raw_contact id
final boolean hasRawContact = (mRawContactIds.size() > 0);
menu.findItem(R.id.menu_edit).setEnabled(hasRawContact);
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return;
}
// This can be null sometimes, don't crash...
if (info == null) {
Log.e(TAG, "bad menuInfo");
return;
}
ViewEntry entry = ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS);
menu.setHeaderTitle(R.string.contactOptionsTitle);
if (entry.mimetype.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_call).setIntent(entry.intent);
menu.add(0, 0, 0, R.string.menu_sendSMS).setIntent(entry.secondaryIntent);
if (!entry.isPrimary) {
menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultNumber);
}
} else if (entry.mimetype.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_sendEmail).setIntent(entry.intent);
if (!entry.isPrimary) {
menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultEmail);
}
} else if (entry.mimetype.equals(CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_viewAddress).setIntent(entry.intent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit: {
Long rawContactIdToEdit = null;
if (mRawContactIds.size() > 0) {
rawContactIdToEdit = mRawContactIds.get(0);
} else {
// There is no rawContact to edit.
break;
}
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactIdToEdit);
startActivityForResult(new Intent(Intent.ACTION_EDIT, rawContactUri),
REQUEST_EDIT_CONTACT);
break;
}
case R.id.menu_delete: {
// Get confirmation
if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) {
showDialog(DIALOG_CONFIRM_READONLY_DELETE);
} else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) {
showDialog(DIALOG_CONFIRM_READONLY_HIDE);
} else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) {
showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE);
} else {
showDialog(DIALOG_CONFIRM_DELETE);
}
return true;
}
case R.id.menu_join: {
showJoinAggregateActivity();
return true;
}
case R.id.menu_options: {
showOptionsActivity();
return true;
}
case R.id.menu_share: {
// TODO: Keep around actual LOOKUP_KEY, or formalize method of extracting
final String lookupKey = mLookupUri.getPathSegments().get(2);
final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(Contacts.CONTENT_VCARD_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, shareUri);
// Launch chooser to share contact via
final CharSequence chooseTitle = getText(R.string.share_via);
final Intent chooseIntent = Intent.createChooser(intent, chooseTitle);
try {
startActivity(chooseIntent);
} catch (ActivityNotFoundException ex) {
Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_MAKE_DEFAULT: {
if (makeItemDefault(item)) {
return true;
}
break;
}
}
return super.onContextItemSelected(item);
}
private boolean makeItemDefault(MenuItem item) {
ViewEntry entry = getViewEntryForMenuItem(item);
if (entry == null) {
return false;
}
// Update the primary values in the data record.
ContentValues values = new ContentValues(1);
values.put(Data.IS_SUPER_PRIMARY, 1);
getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, entry.id),
values, null, null);
startEntityQuery();
return true;
}
/**
* Shows a list of aggregates that can be joined into the currently viewed aggregate.
*/
public void showJoinAggregateActivity() {
long freshId = getRefreshedContactId();
if (freshId > 0) {
String displayName = null;
if (mCursor.moveToFirst()) {
displayName = mCursor.getString(0);
}
Intent intent = new Intent(ContactsListActivity.JOIN_AGGREGATE);
intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_ID, freshId);
if (displayName != null) {
intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_NAME, displayName);
}
startActivityForResult(intent, REQUEST_JOIN_CONTACT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_JOIN_CONTACT) {
if (resultCode == RESULT_OK && intent != null) {
final long contactId = ContentUris.parseId(intent.getData());
joinAggregate(contactId);
}
} else if (requestCode == REQUEST_EDIT_CONTACT) {
if (resultCode == EditContactActivity.RESULT_CLOSE_VIEW_ACTIVITY) {
finish();
} else if (resultCode == Activity.RESULT_OK) {
mLookupUri = intent.getData();
if (mLookupUri == null) {
finish();
}
}
}
}
private void splitContact(long rawContactId) {
setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_SEPARATE);
// The split operation may have removed the original aggregate contact, so we need
// to requery everything
Toast.makeText(this, R.string.contactsSplitMessage, Toast.LENGTH_LONG).show();
startEntityQuery();
}
private void joinAggregate(final long contactId) {
Cursor c = mResolver.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + "=" + contactId, null, null);
try {
while(c.moveToNext()) {
long rawContactId = c.getLong(0);
setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_TOGETHER);
}
} finally {
c.close();
}
Toast.makeText(this, R.string.contactsJoinedMessage, Toast.LENGTH_LONG).show();
startEntityQuery();
}
/**
* Given a contact ID sets an aggregation exception to either join the contact with the
* current aggregate or split off.
*/
protected void setAggregationException(long rawContactId, int exceptionType) {
ContentValues values = new ContentValues(3);
for (long aRawContactId : mRawContactIds) {
if (aRawContactId != rawContactId) {
values.put(AggregationExceptions.RAW_CONTACT_ID1, aRawContactId);
values.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId);
values.put(AggregationExceptions.TYPE, exceptionType);
mResolver.update(AggregationExceptions.CONTENT_URI, values, null, null);
}
}
}
private void showOptionsActivity() {
final Intent intent = new Intent(this, ContactOptionsActivity.class);
intent.setData(mLookupUri);
startActivity(intent);
}
private ViewEntry getViewEntryForMenuItem(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return null;
}
return ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_CALL: {
try {
ITelephony phone = ITelephony.Stub.asInterface(
ServiceManager.checkService("phone"));
if (phone != null && !phone.isIdle()) {
// Skip out and let the key be handled at a higher level
break;
}
} catch (RemoteException re) {
// Fall through and try to call the contact
}
int index = mListView.getSelectedItemPosition();
if (index != -1) {
ViewEntry entry = ViewAdapter.getEntry(mSections, index, SHOW_SEPARATORS);
if (entry.intent.getAction() == Intent.ACTION_CALL_PRIVILEGED) {
startActivity(entry.intent);
}
} else if (mNumPhoneNumbers != 0) {
// There isn't anything selected, call the default number
long freshContactId = getRefreshedContactId();
if (freshContactId > 0) {
Uri hardContacUri = ContentUris.withAppendedId(
Contacts.CONTENT_URI, freshContactId);
Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, hardContacUri);
startActivity(intent);
}
}
return true;
}
case KeyEvent.KEYCODE_DEL: {
if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) {
showDialog(DIALOG_CONFIRM_READONLY_DELETE);
} else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) {
showDialog(DIALOG_CONFIRM_READONLY_HIDE);
} else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) {
showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE);
} else {
showDialog(DIALOG_CONFIRM_DELETE);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
ViewEntry entry = ViewAdapter.getEntry(mSections, position, SHOW_SEPARATORS);
if (entry != null) {
Intent intent = entry.intent;
if (intent != null) {
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity found for intent: " + intent);
signalError();
}
} else {
signalError();
}
} else {
signalError();
}
}
/**
* Signal an error to the user via a beep, or some other method.
*/
private void signalError() {
//TODO: implement this when we have the sonification APIs
}
/**
* Build up the entries to display on the screen.
*
* @param personCursor the URI for the contact being displayed
*/
private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
- entry.data = PhoneNumberUtils.stripSeparators(entry.data);
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE
|| mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType)
|| Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) {
// Build organization and note entries
entry.uri = null;
mOrganizationEntries.add(entry);
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
static String buildActionString(DataKind kind, ContentValues values, boolean lowerCase,
Context context) {
if (kind.actionHeader == null) {
return null;
}
CharSequence actionHeader = kind.actionHeader.inflateUsing(context, values);
if (actionHeader == null) {
return null;
}
return lowerCase ? actionHeader.toString().toLowerCase() : actionHeader.toString();
}
static String buildDataString(DataKind kind, ContentValues values, Context context) {
if (kind.actionBody == null) {
return null;
}
CharSequence actionBody = kind.actionBody.inflateUsing(context, values);
return actionBody == null ? null : actionBody.toString();
}
/**
* A basic structure with the data for a contact entry in the list.
*/
static class ViewEntry extends ContactEntryAdapter.Entry implements Collapsible<ViewEntry> {
public Context context = null;
public String resPackageName = null;
public int actionIcon = -1;
public boolean isPrimary = false;
public int secondaryActionIcon = -1;
public Intent intent;
public Intent secondaryIntent = null;
public int maxLabelLines = 1;
public ArrayList<Long> ids = new ArrayList<Long>();
public int collapseCount = 0;
public int presence = -1;
public int presenceIcon = -1;
public CharSequence footerLine = null;
private ViewEntry() {
}
/**
* Build new {@link ViewEntry} and populate from the given values.
*/
public static ViewEntry fromValues(Context context, String mimeType, DataKind kind,
long rawContactId, long dataId, ContentValues values) {
final ViewEntry entry = new ViewEntry();
entry.context = context;
entry.contactId = rawContactId;
entry.id = dataId;
entry.uri = ContentUris.withAppendedId(Data.CONTENT_URI, entry.id);
entry.mimetype = mimeType;
entry.label = buildActionString(kind, values, false, context);
entry.data = buildDataString(kind, values, context);
if (kind.typeColumn != null && values.containsKey(kind.typeColumn)) {
entry.type = values.getAsInteger(kind.typeColumn);
}
if (kind.iconRes > 0) {
entry.resPackageName = kind.resPackageName;
entry.actionIcon = kind.iconRes;
}
return entry;
}
/**
* Apply given {@link DataStatus} values over this {@link ViewEntry}
*
* @param fillData When true, the given status replaces {@link #data}
* and {@link #footerLine}. Otherwise only {@link #presence}
* is updated.
*/
public ViewEntry applyStatus(DataStatus status, boolean fillData) {
presence = status.getPresence();
presenceIcon = (presence == -1) ? -1 :
StatusUpdates.getPresenceIconResourceId(this.presence);
if (fillData && status.isValid()) {
this.data = status.getStatus().toString();
this.footerLine = status.getTimestampLabel(context);
}
return this;
}
public boolean collapseWith(ViewEntry entry) {
// assert equal collapse keys
if (!shouldCollapseWith(entry)) {
return false;
}
// Choose the label associated with the highest type precedence.
if (TypePrecedence.getTypePrecedence(mimetype, type)
> TypePrecedence.getTypePrecedence(entry.mimetype, entry.type)) {
type = entry.type;
label = entry.label;
}
// Choose the max of the maxLines and maxLabelLines values.
maxLines = Math.max(maxLines, entry.maxLines);
maxLabelLines = Math.max(maxLabelLines, entry.maxLabelLines);
// Choose the presence with the highest precedence.
if (StatusUpdates.getPresencePrecedence(presence)
< StatusUpdates.getPresencePrecedence(entry.presence)) {
presence = entry.presence;
}
// If any of the collapsed entries are primary make the whole thing primary.
isPrimary = entry.isPrimary ? true : isPrimary;
// uri, and contactdId, shouldn't make a difference. Just keep the original.
// Keep track of all the ids that have been collapsed with this one.
ids.add(entry.id);
collapseCount++;
return true;
}
public boolean shouldCollapseWith(ViewEntry entry) {
if (entry == null) {
return false;
}
if (Phone.CONTENT_ITEM_TYPE.equals(mimetype)
&& Phone.CONTENT_ITEM_TYPE.equals(entry.mimetype)) {
if (!PhoneNumberUtils.compare(this.context, data, entry.data)) {
return false;
}
} else {
if (!equals(data, entry.data)) {
return false;
}
}
if (!equals(mimetype, entry.mimetype)
|| !intentCollapsible(intent, entry.intent)
|| !intentCollapsible(secondaryIntent, entry.secondaryIntent)
|| actionIcon != entry.actionIcon) {
return false;
}
return true;
}
private boolean equals(Object a, Object b) {
return a==b || (a != null && a.equals(b));
}
private boolean intentCollapsible(Intent a, Intent b) {
if (a == b) {
return true;
} else if ((a != null && b != null) && equals(a.getAction(), b.getAction())) {
return true;
}
return false;
}
}
/** Cache of the children views of a row */
static class ViewCache {
public TextView label;
public TextView data;
public TextView footer;
public ImageView actionIcon;
public ImageView presenceIcon;
public ImageView primaryIcon;
public ImageView secondaryActionButton;
public View secondaryActionDivider;
// Need to keep track of this too
ViewEntry entry;
}
private final class ViewAdapter extends ContactEntryAdapter<ViewEntry>
implements View.OnClickListener {
ViewAdapter(Context context, ArrayList<ArrayList<ViewEntry>> sections) {
super(context, sections, SHOW_SEPARATORS);
}
public void onClick(View v) {
Intent intent = (Intent) v.getTag();
startActivity(intent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewEntry entry = getEntry(mSections, position, false);
View v;
ViewCache views;
// Check to see if we can reuse convertView
if (convertView != null) {
v = convertView;
views = (ViewCache) v.getTag();
} else {
// Create a new view if needed
v = mInflater.inflate(R.layout.list_item_text_icons, parent, false);
// Cache the children
views = new ViewCache();
views.label = (TextView) v.findViewById(android.R.id.text1);
views.data = (TextView) v.findViewById(android.R.id.text2);
views.footer = (TextView) v.findViewById(R.id.footer);
views.actionIcon = (ImageView) v.findViewById(R.id.action_icon);
views.primaryIcon = (ImageView) v.findViewById(R.id.primary_icon);
views.presenceIcon = (ImageView) v.findViewById(R.id.presence_icon);
views.secondaryActionButton = (ImageView) v.findViewById(
R.id.secondary_action_button);
views.secondaryActionButton.setOnClickListener(this);
views.secondaryActionDivider = v.findViewById(R.id.divider);
v.setTag(views);
}
// Update the entry in the view cache
views.entry = entry;
// Bind the data to the view
bindView(v, entry);
return v;
}
@Override
protected View newView(int position, ViewGroup parent) {
// getView() handles this
throw new UnsupportedOperationException();
}
@Override
protected void bindView(View view, ViewEntry entry) {
final Resources resources = mContext.getResources();
ViewCache views = (ViewCache) view.getTag();
// Set the label
TextView label = views.label;
setMaxLines(label, entry.maxLabelLines);
label.setText(entry.label);
// Set the data
TextView data = views.data;
if (data != null) {
if (entry.mimetype.equals(Phone.CONTENT_ITEM_TYPE)
|| entry.mimetype.equals(Constants.MIME_SMS_ADDRESS)) {
data.setText(PhoneNumberUtils.formatNumber(entry.data));
} else {
data.setText(entry.data);
}
setMaxLines(data, entry.maxLines);
}
// Set the footer
if (!TextUtils.isEmpty(entry.footerLine)) {
views.footer.setText(entry.footerLine);
views.footer.setVisibility(View.VISIBLE);
} else {
views.footer.setVisibility(View.GONE);
}
// Set the primary icon
views.primaryIcon.setVisibility(entry.isPrimary ? View.VISIBLE : View.GONE);
// Set the action icon
ImageView action = views.actionIcon;
if (entry.actionIcon != -1) {
Drawable actionIcon;
if (entry.resPackageName != null) {
// Load external resources through PackageManager
actionIcon = mContext.getPackageManager().getDrawable(entry.resPackageName,
entry.actionIcon, null);
} else {
actionIcon = resources.getDrawable(entry.actionIcon);
}
action.setImageDrawable(actionIcon);
action.setVisibility(View.VISIBLE);
} else {
// Things should still line up as if there was an icon, so make it invisible
action.setVisibility(View.INVISIBLE);
}
// Set the presence icon
Drawable presenceIcon = null;
if (entry.presenceIcon != -1) {
presenceIcon = resources.getDrawable(entry.presenceIcon);
} else if (entry.presence != -1) {
presenceIcon = resources.getDrawable(
StatusUpdates.getPresenceIconResourceId(entry.presence));
}
ImageView presenceIconView = views.presenceIcon;
if (presenceIcon != null) {
presenceIconView.setImageDrawable(presenceIcon);
presenceIconView.setVisibility(View.VISIBLE);
} else {
presenceIconView.setVisibility(View.GONE);
}
// Set the secondary action button
ImageView secondaryActionView = views.secondaryActionButton;
Drawable secondaryActionIcon = null;
if (entry.secondaryActionIcon != -1) {
secondaryActionIcon = resources.getDrawable(entry.secondaryActionIcon);
}
if (entry.secondaryIntent != null && secondaryActionIcon != null) {
secondaryActionView.setImageDrawable(secondaryActionIcon);
secondaryActionView.setTag(entry.secondaryIntent);
secondaryActionView.setVisibility(View.VISIBLE);
views.secondaryActionDivider.setVisibility(View.VISIBLE);
} else {
secondaryActionView.setVisibility(View.GONE);
views.secondaryActionDivider.setVisibility(View.GONE);
}
}
private void setMaxLines(TextView textView, int maxLines) {
if (maxLines == 1) {
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
} else {
textView.setSingleLine(false);
textView.setMaxLines(maxLines);
textView.setEllipsize(null);
}
}
}
private interface StatusQuery {
final String[] PROJECTION = new String[] {
Data._ID,
Data.STATUS,
Data.STATUS_RES_PACKAGE,
Data.STATUS_ICON,
Data.STATUS_LABEL,
Data.STATUS_TIMESTAMP,
Data.PRESENCE,
};
final int _ID = 0;
}
}
| true | true | private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
entry.data = PhoneNumberUtils.stripSeparators(entry.data);
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE
|| mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType)
|| Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) {
// Build organization and note entries
entry.uri = null;
mOrganizationEntries.add(entry);
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
| private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE
|| mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType)
|| Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) {
// Build organization and note entries
entry.uri = null;
mOrganizationEntries.add(entry);
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
|
diff --git a/basket/src/uag/basket/MainActivity.java b/basket/src/uag/basket/MainActivity.java
index 5effd8c..5c0bd9c 100644
--- a/basket/src/uag/basket/MainActivity.java
+++ b/basket/src/uag/basket/MainActivity.java
@@ -1,19 +1,17 @@
package uag.basket;
import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends DroidGap
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
- //super.loadUrl("file:///android_asset/www/barcodescanner-demo.html");//TMP
super.loadUrl("file:///android_asset/www/uag-basket-view.html");
- //super.loadUrl("file:///android_asset/www/test.html");//TMP
}
}
| false | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//super.loadUrl("file:///android_asset/www/barcodescanner-demo.html");//TMP
super.loadUrl("file:///android_asset/www/uag-basket-view.html");
//super.loadUrl("file:///android_asset/www/test.html");//TMP
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/uag-basket-view.html");
}
|
diff --git a/src/java/com/idega/presentation/ui/TextInput.java b/src/java/com/idega/presentation/ui/TextInput.java
index 8a33ac5e8..3c22df8d0 100755
--- a/src/java/com/idega/presentation/ui/TextInput.java
+++ b/src/java/com/idega/presentation/ui/TextInput.java
@@ -1,283 +1,283 @@
//idega 2000 - Tryggvi Larusson
/*
*Copyright 2000 idega.is All Rights Reserved.
*/
package com.idega.presentation.ui;
import java.io.*;
import java.util.*;
import com.idega.presentation.*;
/**
*@author <a href="mailto:[email protected]">Tryggvi Larusson</a>
*@version 1.2
*/
public class TextInput extends InterfaceObject{
private String inputType = "text";
private Script script;
private boolean isSetAsIntegers;
private boolean isSetAsFloat;
private boolean isSetAsAlphabetical;
private boolean isSetAsEmail;
private boolean isSetAsNotEmpty;
private boolean isSetAsIcelandicSSNumber;
private boolean isSetAsCreditCardNumber;
private String integersErrorMessage;
private String floatErrorMessage;
private String alphabetErrorMessage;
private String emailErrorMessage;
private String notEmptyErrorMessage;
private String icelandicSSNumberErrorMessage;
private String notCreditCardErrorMessage;
private static final String untitled="untitled";
public TextInput(){
this(untitled);
}
public TextInput(String name){
super();
setName(name);
}
public TextInput(String name,String content){
super();
setName(name);
setContent(content);
isSetAsIntegers=false;
isSetAsFloat=false;
isSetAsAlphabetical=false;
isSetAsEmail=false;
isSetAsNotEmpty=false;
isSetAsIcelandicSSNumber=false;
}
public void setAsPasswordInput(boolean asPasswordInput) {
if ( asPasswordInput )
inputType = "password";
else
inputType = "text";
}
public void setLength(int length){
setSize(length);
}
public void setSize(int size){
setAttribute("size",Integer.toString(size));
}
public void setMaxlength(int maxlength){
setAttribute("maxlength",Integer.toString(maxlength));
}
private void setScript(Script script){
this.script = script;
setAssociatedScript(script);
}
private Script getScript(){
if (getParentForm().getAssociatedFormScript() == null){
getParentForm().setAssociatedFormScript(new Script());
}
script = getParentForm().getAssociatedFormScript();
return script;
}
private void setCheckSubmit(){
if ( getScript().getFunction("checkSubmit") == null){
getScript().addFunction("checkSubmit","function checkSubmit(inputs){\n\n}");
}
}
public void setAsNotEmpty(){
this.setAsNotEmpty("Please fill in the box "+this.getName());
}
public void setAsNotEmpty(String errorMessage){
isSetAsNotEmpty=true;
notEmptyErrorMessage=errorMessage;
}
public void setAsCredidCardNumber(){
this.setAsCredidCardNumber("Please enter a valid creditcard number in "+this.getName());
}
public void setAsCredidCardNumber(String errorMessage){
isSetAsCreditCardNumber=true;
notCreditCardErrorMessage=errorMessage;
}
public void setAsEmail(String errorMessage){
isSetAsEmail=true;
emailErrorMessage=errorMessage;
}
public void setAsEmail(){
this.setAsEmail("This is not an email");
}
public void setAsIntegers(){
this.setAsIntegers("Please use only numbers in "+this.getName());
}
public void setAsIntegers(String errorMessage){
isSetAsIntegers=true;
integersErrorMessage=errorMessage;
}
public void setAsFloat(){
this.setAsFloat("Please use only numbers in "+this.getName());
}
public void setAsFloat(String errorMessage){
isSetAsFloat=true;
floatErrorMessage=errorMessage;
}
public void setAsIcelandicSSNumber(){
this.setAsFloat("Please only a Icelandic social security number in "+this.getName());
}
//Checks if it is a valid "kennitala" (social security number)
public void setAsIcelandicSSNumber(String errorMessage){
isSetAsIcelandicSSNumber=true;
icelandicSSNumberErrorMessage=errorMessage;
}
public void setAsAlphabetictext(){
this.setAsAlphabeticText("Please use only alpabetical characters in "+this.getName());
}
public void setAsAlphabeticText(String errorMessage){
isSetAsAlphabetical=true;
alphabetErrorMessage=errorMessage;
}
public void setStyle(String style) {
setAttribute("class",style);
}
public String getValue(){
if (super.getValue() == null){
return "";
}
else{
return super.getValue();
}
}
public void _main(IWContext iwc)throws Exception{
if (getParentForm() != null){
if (isSetAsNotEmpty){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfEmpty (findObj('"+getName()+"'),'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfEmpty","function warnIfEmpty (inputbox,warnMsg) {\n\n if ( inputbox.value == '' ) { \n alert ( warnMsg );\n return false;\n }\n else{\n return true;\n}\n\n}");
}
if (isSetAsIntegers){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if(isSetAsIcelandicSSNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIcelandicSSNumber","function warnIfNotIcelandicSSNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 10){ \n sum = inputbox.value.charAt(0)*3 + inputbox.value.charAt(1)*2 + inputbox.value.charAt(2)*7 + inputbox.value.charAt(3)*6 + inputbox.value.charAt(4)*5 + inputbox.value.charAt(5)*4 + inputbox.value.charAt(6)*3 + inputbox.value.charAt(7)*2; \n var rule1 = inputbox.value.charAt(8) == 11 - (sum % 11); \n var rule2 = inputbox.value.charAt(9) == 0; \n var rule3 = inputbox.value.charAt(9) == 8; \n var rule4 = inputbox.value.charAt(9) == 9; \n var subRule = false; \n if ( rule2 || rule3 || rule4 ) { subRule = true; } \n if ( rule1 && subRule ){ \n return true; \n }\n } \n alert ( warnMsg );\n return false;\n \n }");
- getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if (isSetAsCreditCardNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (findObj('"+getName()+"'),'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotCreditCardNumber","function warnIfNotCreditCardNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 16){ \n return true; \n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
//not fully implemented such as maybe a checksum check could be added??
}
else if(isSetAsFloat){
getParentForm().setOnSubmit("return checkSubmit(this)");
//Not implemented yet
}
else if(isSetAsAlphabetical){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (findObj('"+getName()+"'),'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotAlphabetical","function warnIfNotAlphabetical (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if ((inputbox.value.charAt(i) > '0') && (inputbox.value.charAt(i) < '9')){ \n alert ( warnMsg );\n return false; \n } \n } \n return true;\n\n}");
}
else if(isSetAsEmail){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotEmail (findObj('"+getName()+"')) == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotEmail","function warnIfNotEmail (inputbox) { \n\n var emailVal = inputbox.value; \n\n var atI = emailVal.indexOf (\"@\"); \n\n var dotI = emailVal.indexOf (\".\"); \n\n var warnMsg = \""+emailErrorMessage+"\\n\";\n\n if ( atI && dotI ){\n return true;\n }\n else{\n alert(warnMsg);\n return false;\n }\n}");
//Not finished yet
}
}
}
public void print(IWContext iwc)throws IOException{
//if ( doPrint(iwc) ){
if (getLanguage().equals("HTML")){
if (keepStatus){
if(this.getRequest().getParameter(this.getName()) != null){
setContent(getRequest().getParameter(getName()));
}
}
//if (getInterfaceStyle().equals("default"))
println("<input type=\""+inputType+"\" name=\""+getName()+"\" "+getAttributeString()+" >");
//println("</input>");
// }
}
else if (getLanguage().equals("WML")){
println("<input type=\""+inputType+"\" name=\""+getName()+"\" "+getAttributeString()+" />");
}
//}
}
public synchronized Object clone() {
TextInput obj = null;
try {
obj = (TextInput)super.clone();
if(this.script != null){
obj.script = (Script)this.script.clone();
}
obj.isSetAsIntegers = this.isSetAsIntegers;
obj.isSetAsFloat = this.isSetAsFloat;
obj.isSetAsAlphabetical = this.isSetAsAlphabetical;
obj.isSetAsEmail = this.isSetAsEmail;
obj.isSetAsNotEmpty = this.isSetAsNotEmpty;
obj.integersErrorMessage = this.integersErrorMessage;
obj.floatErrorMessage = this.floatErrorMessage;
obj.alphabetErrorMessage = this.alphabetErrorMessage;
obj.emailErrorMessage = this.emailErrorMessage;
obj.notEmptyErrorMessage = this.notEmptyErrorMessage;
}
catch(Exception ex) {
ex.printStackTrace(System.err);
}
return obj;
}
}
| true | true | public void _main(IWContext iwc)throws Exception{
if (getParentForm() != null){
if (isSetAsNotEmpty){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfEmpty (findObj('"+getName()+"'),'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfEmpty","function warnIfEmpty (inputbox,warnMsg) {\n\n if ( inputbox.value == '' ) { \n alert ( warnMsg );\n return false;\n }\n else{\n return true;\n}\n\n}");
}
if (isSetAsIntegers){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if(isSetAsIcelandicSSNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIcelandicSSNumber","function warnIfNotIcelandicSSNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 10){ \n sum = inputbox.value.charAt(0)*3 + inputbox.value.charAt(1)*2 + inputbox.value.charAt(2)*7 + inputbox.value.charAt(3)*6 + inputbox.value.charAt(4)*5 + inputbox.value.charAt(5)*4 + inputbox.value.charAt(6)*3 + inputbox.value.charAt(7)*2; \n var rule1 = inputbox.value.charAt(8) == 11 - (sum % 11); \n var rule2 = inputbox.value.charAt(9) == 0; \n var rule3 = inputbox.value.charAt(9) == 8; \n var rule4 = inputbox.value.charAt(9) == 9; \n var subRule = false; \n if ( rule2 || rule3 || rule4 ) { subRule = true; } \n if ( rule1 && subRule ){ \n return true; \n }\n } \n alert ( warnMsg );\n return false;\n \n }");
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if (isSetAsCreditCardNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (findObj('"+getName()+"'),'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotCreditCardNumber","function warnIfNotCreditCardNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 16){ \n return true; \n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
//not fully implemented such as maybe a checksum check could be added??
}
else if(isSetAsFloat){
getParentForm().setOnSubmit("return checkSubmit(this)");
//Not implemented yet
}
else if(isSetAsAlphabetical){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (findObj('"+getName()+"'),'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotAlphabetical","function warnIfNotAlphabetical (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if ((inputbox.value.charAt(i) > '0') && (inputbox.value.charAt(i) < '9')){ \n alert ( warnMsg );\n return false; \n } \n } \n return true;\n\n}");
}
else if(isSetAsEmail){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotEmail (findObj('"+getName()+"')) == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotEmail","function warnIfNotEmail (inputbox) { \n\n var emailVal = inputbox.value; \n\n var atI = emailVal.indexOf (\"@\"); \n\n var dotI = emailVal.indexOf (\".\"); \n\n var warnMsg = \""+emailErrorMessage+"\\n\";\n\n if ( atI && dotI ){\n return true;\n }\n else{\n alert(warnMsg);\n return false;\n }\n}");
//Not finished yet
}
}
}
| public void _main(IWContext iwc)throws Exception{
if (getParentForm() != null){
if (isSetAsNotEmpty){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfEmpty (findObj('"+getName()+"'),'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfEmpty","function warnIfEmpty (inputbox,warnMsg) {\n\n if ( inputbox.value == '' ) { \n alert ( warnMsg );\n return false;\n }\n else{\n return true;\n}\n\n}");
}
if (isSetAsIntegers){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if(isSetAsIcelandicSSNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIcelandicSSNumber","function warnIfNotIcelandicSSNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 10){ \n sum = inputbox.value.charAt(0)*3 + inputbox.value.charAt(1)*2 + inputbox.value.charAt(2)*7 + inputbox.value.charAt(3)*6 + inputbox.value.charAt(4)*5 + inputbox.value.charAt(5)*4 + inputbox.value.charAt(6)*3 + inputbox.value.charAt(7)*2; \n var rule1 = inputbox.value.charAt(8) == 11 - (sum % 11); \n var rule2 = inputbox.value.charAt(9) == 0; \n var rule3 = inputbox.value.charAt(9) == 8; \n var rule4 = inputbox.value.charAt(9) == 9; \n var subRule = false; \n if ( rule2 || rule3 || rule4 ) { subRule = true; } \n if ( rule1 && subRule ){ \n return true; \n }\n } \n alert ( warnMsg );\n return false;\n \n }");
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if (isSetAsCreditCardNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (findObj('"+getName()+"'),'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotCreditCardNumber","function warnIfNotCreditCardNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 16){ \n return true; \n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
//not fully implemented such as maybe a checksum check could be added??
}
else if(isSetAsFloat){
getParentForm().setOnSubmit("return checkSubmit(this)");
//Not implemented yet
}
else if(isSetAsAlphabetical){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (findObj('"+getName()+"'),'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotAlphabetical","function warnIfNotAlphabetical (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if ((inputbox.value.charAt(i) > '0') && (inputbox.value.charAt(i) < '9')){ \n alert ( warnMsg );\n return false; \n } \n } \n return true;\n\n}");
}
else if(isSetAsEmail){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotEmail (findObj('"+getName()+"')) == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotEmail","function warnIfNotEmail (inputbox) { \n\n var emailVal = inputbox.value; \n\n var atI = emailVal.indexOf (\"@\"); \n\n var dotI = emailVal.indexOf (\".\"); \n\n var warnMsg = \""+emailErrorMessage+"\\n\";\n\n if ( atI && dotI ){\n return true;\n }\n else{\n alert(warnMsg);\n return false;\n }\n}");
//Not finished yet
}
}
}
|
diff --git a/Sample2Client1/src/main/java/thoiyk/HumanInterfaceComponent/ProdutionRecordItem/PRitemBrowserClass.java b/Sample2Client1/src/main/java/thoiyk/HumanInterfaceComponent/ProdutionRecordItem/PRitemBrowserClass.java
index bd3b53d..fe04fbf 100644
--- a/Sample2Client1/src/main/java/thoiyk/HumanInterfaceComponent/ProdutionRecordItem/PRitemBrowserClass.java
+++ b/Sample2Client1/src/main/java/thoiyk/HumanInterfaceComponent/ProdutionRecordItem/PRitemBrowserClass.java
@@ -1,417 +1,423 @@
/*
This source code is part of the Thoyik
Copyright (C) 2013 Yoserizal
Feedback / Bug Reports [email protected]
This project used:
KFRAMEWORK (http://k-framework.sourceforge.net/)
*/
package thoiyk.HumanInterfaceComponent.ProdutionRecordItem;
/**
*
* @author yoserizy
*/
//rtl
import javax.swing.*;
import java.awt.*;
// utilities
import KFramework30.Widgets.*;
import KFramework30.Base.*;
import KFramework30.Communication.dbTransactionClientClass;
import KFramework30.Communication.persistentObjectManagerClass;
import KFramework30.Widgets.DataBrowser.KBrowserDataWriterInterface;
import KFramework30.Widgets.DataBrowser.TableCellRenderers.CalendarCellEditorClass;
import KFramework30.Widgets.DataBrowser.TableCellRenderers.CalendarCellRendererClass;
import KFramework30.Widgets.DataBrowser.TableCellRenderers.CheckBoxCellEditorClass;
import KFramework30.Widgets.DataBrowser.TableCellRenderers.CheckBoxCellRendererClass;
import KFramework30.Widgets.DataBrowser.TableCellRenderers.ComboCellEditorClass;
import KFramework30.Widgets.DataBrowser.TableCellRenderers.ComboCellRendererClass;
import KFramework30.Widgets.DataBrowser.cellRenderingHookInterface;
import KFramework30.Widgets.DataBrowser.recordClass;
import static KFramework30.Widgets.KDataBrowserBaseClass.BROWSER_COLUMN_TYPE_CURRENCY;
import static KFramework30.Widgets.KDataBrowserBaseClass.BROWSER_COLUMN_TYPE_DATE;
import static KFramework30.Widgets.KDataBrowserBaseClass.BROWSER_COLUMN_TYPE_NUMERICNOFORMAT;
import ProblemDomainComponent.sample_facturaClass;
// system
//import ProblemDomainComponent.pr_newitemClass;
import ProblemDomainComponent.productionrecorditemClass;
import thoiyk.HumanInterfaceComponent.ProductionRecord.PRBrowserClass;
import static thoiyk.HumanInterfaceComponent.ProdutionRecordItem.PRitemBrowserClass.ALL_SAMPLERECORD;
import static thoiyk.HumanInterfaceComponent.ProdutionRecordItem.PRitemBrowserClass.SRITEM_BY_SR;
import thoiyk.HumanInterfaceComponent.ProdutionRecordItem.PRitemEditDialogClass;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
import thoiyk.HumanInterfaceComponent.outstandingorder.outstandingorderEditDialogClass;
public class PRitemBrowserClass
extends KDataBrowserBaseClass
implements
cellRenderingHookInterface, // to customize the data at runtime OPTIONAL
KBrowserDataWriterInterface // to make it RW OPTIONAL
{
// modes
static public final int ALL_SAMPLERECORD = 0;
static public final int SRITEM_BY_SR = 1;
// uses
private int mode;
private long parentID;
private long productID;
// has - defaulted
/** Creates new viajeBrowserClass */
public PRitemBrowserClass(
KConfigurationClass configurationParam,
KLogClass logParam,
JTable tableParam,
int modeParam, long parentIDparam,
java.awt.Window parentWindow ) throws KExceptionClass
{
// inherits
super(
configurationParam, logParam,
true, tableParam, parentWindow,
productionrecorditemClass.class,
PRitemEditDialogClass.class
);
// uses
mode = modeParam;
parentID = parentIDparam;
// has
// set
setCellDisplayHook( this );
}
public void initializeTable()
throws KExceptionClass
{
if( mode == SRITEM_BY_SR ){
// this is a read write browsers
setBrowserSaveListener(this);
if( configuration.getField("databaseType").equals( "oracle" ) ){
super.initializeSQLQuery(
// 1 fields
- " sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qtyneed ",
+ " sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qty, sri.comp, sri.tolerance, sri.qtyneed ",
// 2 tables and joins
" productionrecorditem sri " +
" left join v_sr_item vsri on sri.itemid=vsri.id" ,
// 3 key of primary PDC object
"ID"
);
}else{
throw new KExceptionClass( "Data base type not recognized " + configuration.getField("databaseType"), null );
}
setColumnNames( "sri", "ID", "ID" );
setColumnNames( "sri", "ITEMID", "ItemID" );
setColumnNames( "vsri", "CATEGORY", "Category" );
setColumnNames( "vsri", "ITEMNAME", "ItemName" );
+ setColumnNames( "sri", "QTY", "Qty" );
+ setColumnNames( "sri", "COMP", "Comp" );
+ setColumnNames( "sri", "TOLERANCE", "Tolerance" );
setColumnNames( "sri", "QTYNEED", "QtyNeed" );
// replace criteria
setDefaultCriteria( " samplerecordid = ? " );
bindDefaultParameter1( ":samperecordid", parentID );
}else{ // mode = ALL_INVOICES
// this is NOT a read write browsers
//setBrowserSaveListener(this);
if( configuration.getField("databaseType").equals( "oracle" ) ){
super.initializeSQLQuery(
// 1 fields
- " sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qtyneed ",
+ " sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qty, sri.comp, sri.tolerance, sri.qtyneed ",
// 2 tables and joins
" productionrecorditem sri " +
" left join v_sr_item vsri on sri.itemid=vsri.id" ,
// 3 key of primary PDC object
"ID"
);
}else{
throw new KExceptionClass( "Data base type not recognized " + configuration.getField("databaseType"), null );
}
// FOR ALL INVOICES
setColumnNames( "sri", "ID", "ID" );
setColumnNames( "sri", "ITEMID", "ItemID" );
setColumnNames( "vsri", "CATEGORY", "Category" );
setColumnNames( "vsri", "ITEMNAME", "ItemName" );
+ setColumnNames( "sri", "QTY", "Qty" );
+ setColumnNames( "sri", "COMP", "Comp" );
+ setColumnNames( "sri", "TOLERANCE", "Tolerance" );
setColumnNames( "sri", "QTYNEED", "QtyNeed" );
}
setDefaultOrder( "itemid" );
super.initializeTable();
/* adjustColumnWidth( "id", 60 );
adjustColumnWidth( "Name", 200 );
adjustColumnWidth( "Date", 130 );
adjustColumnWidth( "STATUS", 100 );
adjustColumnWidth( "TOTAL", 100 );
adjustColumnType( "Date", BROWSER_COLUMN_TYPE_DATE ); // so that autofilter will use date format
*/
if( mode == SRITEM_BY_SR ){
//DATE -->>
// setColumnRenderer("Date", new CalendarCellRendererClass(tableModel, log)); //<-- no necessary and looks awful
// setColumnEditor("Date", new CalendarCellEditorClass(tableModel, log));
//DATE -->>
// OK box
// setColumnRenderer("OK", new CheckBoxCellRendererClass(tableModel, log) );
// setColumnEditor("OK", new CheckBoxCellEditorClass(tableModel, log) );
// adjustColumnWidth( "OK", 30 );
// STATUS COMBO
// dbTransactionClientClass query = new dbTransactionClientClass(configuration, log);
// query.prepare( " select FACSTATUS_STATUS from SAMPLE_FACTURA_STATUS " );
// query.executeQuery( 0 , 999 );
// Vector< String > options = new Vector< String >();
// while( query.fetch() ) options.add( (String )query.getField( "FACSTATUS_STATUS" ) );
// setColumnEditor("STATUS", new ComboCellEditorClass( options, tableModel, log, true ) );
// setColumnRenderer("STATUS", new ComboCellRendererClass( options, tableModel, log) );
// TOTAL
// for the total, leave the default text editor assigned when set to editable
}
// adjustColumnType( "TOTAL", BROWSER_COLUMN_TYPE_CURRENCY );
// adjustColumnFont( "id", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "Name", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "Date", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "STATUS", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "TOTAL", new Font( "arial", Font.BOLD, 10 ) );
}
//----------------------------------------------------
// Fired on browser save action, either by button called or user browser.save ...
// Required because it is RW, and implements KBrowserDataWriterInterface
// OPTIONAL , if no RW remove this and the implements KBrowserDataWriterInterface
// For a bare minimums example better see the productBrowserClass
@Override
public void save( java.util.List< String > fieldNames, java.util.List< recordClass > data ){
try {
// load status
Properties invoiceStatusProp = new Properties();
dbTransactionClientClass query = new dbTransactionClientClass(configuration, log);
query.prepare( " select FACSTATUS_ID, FACSTATUS_STATUS from SAMPLE_FACTURA_STATUS " );
query.executeQuery(0, 999);
while( query.fetch() ){
invoiceStatusProp.put( query.getField("FACSTATUS_STATUS"), query.getField("FACSTATUS_ID") );
}
// for you to see
Iterator dataRowChanged = data.iterator();
while( dataRowChanged.hasNext() ){
recordClass currentRow = (recordClass) dataRowChanged.next();
// materialize object
sample_facturaClass factura = new sample_facturaClass();
persistentObjectManagerClass pom = new persistentObjectManagerClass(configuration, log) ;
factura = (sample_facturaClass) pom.copy4( KMetaUtilsClass.getIntegralNumericValueFromString( (String) currentRow.getValueAt(6) ), factura.getClass() );
// update it
// OK box
String OKbox = (String) currentRow.getValueAt(0);
// will return ture or false for the checkbox
// not used in this example. This is a sample on how to read it
// DATE
factura.setFacDate(
KMetaUtilsClass.stringToDate(
KMetaUtilsClass.KDEFAULT_LONG_DATE_TIME_FORMAT, (String) currentRow.getValueAt(3) ) );
// STATUS
factura.setFacstatusId( KMetaUtilsClass.getIntegralNumericValueFromString( invoiceStatusProp.getProperty( (String) currentRow.getValueAt(4) ) ) );
// TOTAL
factura.setFacTotal( KMetaUtilsClass.getCurrencyNumericValueFromString( (String)currentRow.getValueAt(5) ) );
// save it
factura = (sample_facturaClass) pom.update4( KMetaUtilsClass.getIntegralNumericValueFromString( (String)currentRow.getValueAt(6) ), factura);
}
} catch (KExceptionClass error) {
// log error
log.log( this, KMetaUtilsClass.getStackTrace( error ) );
// show error message
KMetaUtilsClass.showErrorMessageFromException( getParentWindow(), error );
}
}
// ---------------------------------------------------------------------------
// These two are OPTIONAL to show how to customize the rendering
// Used because it immplements cellRenderingHookInterface
// Remove immplements and functions if not required
// For a bare minimums example better see the productBrowser.class
public void cellEditHook(int row, int col, boolean isSelected, Component editor, String ColumnName, String value, recordClass record, KLogClass log) throws KExceptionClass {
// not customizing the editor
}
public void cellRenderingHook(
int row, int col, // what cell are we executing for
boolean isSelected, // is it currently highlited ?
Component renderer, // here is the renderer, change it, or replaze it altogether
String ColumnName, String value, // data
recordClass record, // the whole row data
KLogClass log ) // the log used
throws KExceptionClass
{
boolean updateRenderer = false;
// -----------------------------------------------------------------------
if( ColumnName.equals( "TOTAL" ) ) {
if( KMetaUtilsClass.getCurrencyNumericValueFromString( value ) < 0 ){
renderer.setForeground( Color.red );
if( isSelected )renderer.setBackground( Color.yellow );
updateRenderer = true;
}
}
// -----------------------------------------------------------------------
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Event handling
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
@Override
public void newButtonActionPerformed() // need override default to set foreing keys to parent
{
try{
// ------------------------------------------------
// when not inside a client edit dialog
if( mode == ALL_SAMPLERECORD ){
// build a client browser
PRBrowserClass pr_new = new PRBrowserClass(
configuration, log, new javax.swing.JTable(), getParentWindow() );
pr_new.initializeTable();
selectDialogClass selector = new selectDialogClass(
configuration, log, getParentWindow(), pr_new, "Select Production Record Item" );
// dont want to allow this, for example
selector.getNewButton().setEnabled(false);
selector.getDeleteButton().setEnabled(false);
productID = selector.showDialog();
log.log( this,"---------------------------------------\nparentID:"+parentID);
if( parentID == -1 ) throw new KExceptionClass( "You must select a production record for the pr_newitem!", null);
}
// when not inside a client edit dialog
// ------------------------------------------------
HashMap foreingKeys = new HashMap();
foreingKeys.put( "itemid", productID );
foreingKeys.put( "samplerecordid", parentID );
super.newButtonActionPerformed( foreingKeys );
}
catch( Exception error ){
log.log( this, KMetaUtilsClass.getStackTrace( error ) );
KMetaUtilsClass.showErrorMessageFromException( getParentWindow(), error );
}
}
}
| false | true | public void initializeTable()
throws KExceptionClass
{
if( mode == SRITEM_BY_SR ){
// this is a read write browsers
setBrowserSaveListener(this);
if( configuration.getField("databaseType").equals( "oracle" ) ){
super.initializeSQLQuery(
// 1 fields
" sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qtyneed ",
// 2 tables and joins
" productionrecorditem sri " +
" left join v_sr_item vsri on sri.itemid=vsri.id" ,
// 3 key of primary PDC object
"ID"
);
}else{
throw new KExceptionClass( "Data base type not recognized " + configuration.getField("databaseType"), null );
}
setColumnNames( "sri", "ID", "ID" );
setColumnNames( "sri", "ITEMID", "ItemID" );
setColumnNames( "vsri", "CATEGORY", "Category" );
setColumnNames( "vsri", "ITEMNAME", "ItemName" );
setColumnNames( "sri", "QTYNEED", "QtyNeed" );
// replace criteria
setDefaultCriteria( " samplerecordid = ? " );
bindDefaultParameter1( ":samperecordid", parentID );
}else{ // mode = ALL_INVOICES
// this is NOT a read write browsers
//setBrowserSaveListener(this);
if( configuration.getField("databaseType").equals( "oracle" ) ){
super.initializeSQLQuery(
// 1 fields
" sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qtyneed ",
// 2 tables and joins
" productionrecorditem sri " +
" left join v_sr_item vsri on sri.itemid=vsri.id" ,
// 3 key of primary PDC object
"ID"
);
}else{
throw new KExceptionClass( "Data base type not recognized " + configuration.getField("databaseType"), null );
}
// FOR ALL INVOICES
setColumnNames( "sri", "ID", "ID" );
setColumnNames( "sri", "ITEMID", "ItemID" );
setColumnNames( "vsri", "CATEGORY", "Category" );
setColumnNames( "vsri", "ITEMNAME", "ItemName" );
setColumnNames( "sri", "QTYNEED", "QtyNeed" );
}
setDefaultOrder( "itemid" );
super.initializeTable();
/* adjustColumnWidth( "id", 60 );
adjustColumnWidth( "Name", 200 );
adjustColumnWidth( "Date", 130 );
adjustColumnWidth( "STATUS", 100 );
adjustColumnWidth( "TOTAL", 100 );
adjustColumnType( "Date", BROWSER_COLUMN_TYPE_DATE ); // so that autofilter will use date format
*/
if( mode == SRITEM_BY_SR ){
//DATE -->>
// setColumnRenderer("Date", new CalendarCellRendererClass(tableModel, log)); //<-- no necessary and looks awful
// setColumnEditor("Date", new CalendarCellEditorClass(tableModel, log));
//DATE -->>
// OK box
// setColumnRenderer("OK", new CheckBoxCellRendererClass(tableModel, log) );
// setColumnEditor("OK", new CheckBoxCellEditorClass(tableModel, log) );
// adjustColumnWidth( "OK", 30 );
// STATUS COMBO
// dbTransactionClientClass query = new dbTransactionClientClass(configuration, log);
// query.prepare( " select FACSTATUS_STATUS from SAMPLE_FACTURA_STATUS " );
// query.executeQuery( 0 , 999 );
// Vector< String > options = new Vector< String >();
// while( query.fetch() ) options.add( (String )query.getField( "FACSTATUS_STATUS" ) );
// setColumnEditor("STATUS", new ComboCellEditorClass( options, tableModel, log, true ) );
// setColumnRenderer("STATUS", new ComboCellRendererClass( options, tableModel, log) );
// TOTAL
// for the total, leave the default text editor assigned when set to editable
}
// adjustColumnType( "TOTAL", BROWSER_COLUMN_TYPE_CURRENCY );
// adjustColumnFont( "id", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "Name", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "Date", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "STATUS", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "TOTAL", new Font( "arial", Font.BOLD, 10 ) );
}
| public void initializeTable()
throws KExceptionClass
{
if( mode == SRITEM_BY_SR ){
// this is a read write browsers
setBrowserSaveListener(this);
if( configuration.getField("databaseType").equals( "oracle" ) ){
super.initializeSQLQuery(
// 1 fields
" sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qty, sri.comp, sri.tolerance, sri.qtyneed ",
// 2 tables and joins
" productionrecorditem sri " +
" left join v_sr_item vsri on sri.itemid=vsri.id" ,
// 3 key of primary PDC object
"ID"
);
}else{
throw new KExceptionClass( "Data base type not recognized " + configuration.getField("databaseType"), null );
}
setColumnNames( "sri", "ID", "ID" );
setColumnNames( "sri", "ITEMID", "ItemID" );
setColumnNames( "vsri", "CATEGORY", "Category" );
setColumnNames( "vsri", "ITEMNAME", "ItemName" );
setColumnNames( "sri", "QTY", "Qty" );
setColumnNames( "sri", "COMP", "Comp" );
setColumnNames( "sri", "TOLERANCE", "Tolerance" );
setColumnNames( "sri", "QTYNEED", "QtyNeed" );
// replace criteria
setDefaultCriteria( " samplerecordid = ? " );
bindDefaultParameter1( ":samperecordid", parentID );
}else{ // mode = ALL_INVOICES
// this is NOT a read write browsers
//setBrowserSaveListener(this);
if( configuration.getField("databaseType").equals( "oracle" ) ){
super.initializeSQLQuery(
// 1 fields
" sri.id , sri.itemid, vsri.category,vsri.nama itemname, sri.qty, sri.comp, sri.tolerance, sri.qtyneed ",
// 2 tables and joins
" productionrecorditem sri " +
" left join v_sr_item vsri on sri.itemid=vsri.id" ,
// 3 key of primary PDC object
"ID"
);
}else{
throw new KExceptionClass( "Data base type not recognized " + configuration.getField("databaseType"), null );
}
// FOR ALL INVOICES
setColumnNames( "sri", "ID", "ID" );
setColumnNames( "sri", "ITEMID", "ItemID" );
setColumnNames( "vsri", "CATEGORY", "Category" );
setColumnNames( "vsri", "ITEMNAME", "ItemName" );
setColumnNames( "sri", "QTY", "Qty" );
setColumnNames( "sri", "COMP", "Comp" );
setColumnNames( "sri", "TOLERANCE", "Tolerance" );
setColumnNames( "sri", "QTYNEED", "QtyNeed" );
}
setDefaultOrder( "itemid" );
super.initializeTable();
/* adjustColumnWidth( "id", 60 );
adjustColumnWidth( "Name", 200 );
adjustColumnWidth( "Date", 130 );
adjustColumnWidth( "STATUS", 100 );
adjustColumnWidth( "TOTAL", 100 );
adjustColumnType( "Date", BROWSER_COLUMN_TYPE_DATE ); // so that autofilter will use date format
*/
if( mode == SRITEM_BY_SR ){
//DATE -->>
// setColumnRenderer("Date", new CalendarCellRendererClass(tableModel, log)); //<-- no necessary and looks awful
// setColumnEditor("Date", new CalendarCellEditorClass(tableModel, log));
//DATE -->>
// OK box
// setColumnRenderer("OK", new CheckBoxCellRendererClass(tableModel, log) );
// setColumnEditor("OK", new CheckBoxCellEditorClass(tableModel, log) );
// adjustColumnWidth( "OK", 30 );
// STATUS COMBO
// dbTransactionClientClass query = new dbTransactionClientClass(configuration, log);
// query.prepare( " select FACSTATUS_STATUS from SAMPLE_FACTURA_STATUS " );
// query.executeQuery( 0 , 999 );
// Vector< String > options = new Vector< String >();
// while( query.fetch() ) options.add( (String )query.getField( "FACSTATUS_STATUS" ) );
// setColumnEditor("STATUS", new ComboCellEditorClass( options, tableModel, log, true ) );
// setColumnRenderer("STATUS", new ComboCellRendererClass( options, tableModel, log) );
// TOTAL
// for the total, leave the default text editor assigned when set to editable
}
// adjustColumnType( "TOTAL", BROWSER_COLUMN_TYPE_CURRENCY );
// adjustColumnFont( "id", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "Name", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "Date", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "STATUS", new Font( "arial", Font.PLAIN, 10 ) );
// adjustColumnFont( "TOTAL", new Font( "arial", Font.BOLD, 10 ) );
}
|
diff --git a/src/org/servalproject/audio/AudioRecorder.java b/src/org/servalproject/audio/AudioRecorder.java
index 6c93c144..9f1fb40d 100644
--- a/src/org/servalproject/audio/AudioRecorder.java
+++ b/src/org/servalproject/audio/AudioRecorder.java
@@ -1,181 +1,181 @@
package org.servalproject.audio;
import java.io.IOException;
import java.io.InputStream;
import org.servalproject.batphone.VoMP;
import org.servalproject.servald.ServalDMonitor;
import uk.co.mmscomputing.sound.CompressInputStream;
import android.media.AudioFormat;
import android.media.MediaRecorder;
import android.os.Process;
import android.util.Log;
public class AudioRecorder implements Runnable {
private static final String TAG = "AudioRecorder";
private boolean stopMe = false;
private final String call_session_token;
private Thread audioThread;
private ServalDMonitor monitor;
private InputStream audioInput;
private Oslec echoCanceler;
private InputStream codecInput;
private VoMP.Codec codec = null;
private boolean discard = false;
public AudioRecorder(Oslec echoCanceler, String token,
ServalDMonitor monitor) {
call_session_token = token;
this.monitor = monitor;
this.echoCanceler = echoCanceler;
}
public synchronized void startRecording(VoMP.Codec codec)
throws IOException {
Log.v(TAG, "Start recording " + codec);
if (this.codec != null)
throw new IOException("Recording already started");
if (audioThread == null)
throw new IOException("Audio recording has not been prepared");
switch (codec) {
case Signed16:
codecInput = audioInput;
break;
case Alaw8:
codecInput = new CompressInputStream(audioInput, true);
break;
case Ulaw8:
codecInput = new CompressInputStream(audioInput, false);
break;
default:
throw new IOException(codec + " is not yet supported");
}
this.codec = codec;
this.discard = false;
}
public synchronized void stopRecording() {
if (audioThread != null) {
stopMe = true;
audioThread.interrupt();
}
}
public void prepareAudio() throws IOException {
this.discard = true;
if (audioThread == null) {
audioThread = new Thread(this, "Recording");
audioThread.start();
}
}
private void prepare() throws IOException {
if (audioInput != null)
return;
// ensure 60ms minimum record buffer
audioInput = new AudioInputStream(echoCanceler,
MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
8 * 60 * 2);
codecInput = audioInput;
}
private void cleanup() {
if (audioInput == null)
return;
try {
codecInput.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
audioInput = null;
codecInput = null;
}
@Override
public void run() {
try {
prepare();
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
return;
}
// get one block of audio at a time.
// get in byte[], even though samples are natively short[],
// as it ends up being more efficient when we hand them to
// a codec or just send them as raw PCM
int bytesRead = 0;
byte[] block = null;
Log.d(TAG, "Starting loop");
// We need to be careful that we don't buffer more audio than we can
// process, send and play.
// The rest of the audio and network processing seems to be well enough
// behaved. So we can probably afford to boost this thread so that we
// don't miss anything
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
while (!stopMe) {
try {
if (discard || codec == null) {
// skip 20ms of audio at a time until we know the codec
// we are going to use
audioInput.skip(20 * 8 * 2);
continue;
}
if (block == null) {
switch (codec) {
case Signed16:
block = new byte[20 * 8 * 2];
break;
case Ulaw8:
case Alaw8:
block = new byte[20 * 8];
break;
}
Log.v(TAG, "Starting to read audio in " + block.length
+ " byte blocks");
}
if (bytesRead < block.length) {
int bytes = codecInput.read(block, bytesRead,
block.length - bytesRead);
if (bytes > 0)
// process audio block
bytesRead += bytes;
}
if (bytesRead >= block.length) {
- monitor.sendMessageAndData(block, block.length, "AUDIO ",
+ monitor.sendMessageAndData(block, block.length, "audio ",
call_session_token, " ",
codec.codeString);
bytesRead = 0;
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
Log.d(TAG, "Releasing recorder and terminating");
cleanup();
audioThread = null;
}
}
| true | true | public void run() {
try {
prepare();
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
return;
}
// get one block of audio at a time.
// get in byte[], even though samples are natively short[],
// as it ends up being more efficient when we hand them to
// a codec or just send them as raw PCM
int bytesRead = 0;
byte[] block = null;
Log.d(TAG, "Starting loop");
// We need to be careful that we don't buffer more audio than we can
// process, send and play.
// The rest of the audio and network processing seems to be well enough
// behaved. So we can probably afford to boost this thread so that we
// don't miss anything
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
while (!stopMe) {
try {
if (discard || codec == null) {
// skip 20ms of audio at a time until we know the codec
// we are going to use
audioInput.skip(20 * 8 * 2);
continue;
}
if (block == null) {
switch (codec) {
case Signed16:
block = new byte[20 * 8 * 2];
break;
case Ulaw8:
case Alaw8:
block = new byte[20 * 8];
break;
}
Log.v(TAG, "Starting to read audio in " + block.length
+ " byte blocks");
}
if (bytesRead < block.length) {
int bytes = codecInput.read(block, bytesRead,
block.length - bytesRead);
if (bytes > 0)
// process audio block
bytesRead += bytes;
}
if (bytesRead >= block.length) {
monitor.sendMessageAndData(block, block.length, "AUDIO ",
call_session_token, " ",
codec.codeString);
bytesRead = 0;
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
Log.d(TAG, "Releasing recorder and terminating");
cleanup();
audioThread = null;
}
| public void run() {
try {
prepare();
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
return;
}
// get one block of audio at a time.
// get in byte[], even though samples are natively short[],
// as it ends up being more efficient when we hand them to
// a codec or just send them as raw PCM
int bytesRead = 0;
byte[] block = null;
Log.d(TAG, "Starting loop");
// We need to be careful that we don't buffer more audio than we can
// process, send and play.
// The rest of the audio and network processing seems to be well enough
// behaved. So we can probably afford to boost this thread so that we
// don't miss anything
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
while (!stopMe) {
try {
if (discard || codec == null) {
// skip 20ms of audio at a time until we know the codec
// we are going to use
audioInput.skip(20 * 8 * 2);
continue;
}
if (block == null) {
switch (codec) {
case Signed16:
block = new byte[20 * 8 * 2];
break;
case Ulaw8:
case Alaw8:
block = new byte[20 * 8];
break;
}
Log.v(TAG, "Starting to read audio in " + block.length
+ " byte blocks");
}
if (bytesRead < block.length) {
int bytes = codecInput.read(block, bytesRead,
block.length - bytesRead);
if (bytes > 0)
// process audio block
bytesRead += bytes;
}
if (bytesRead >= block.length) {
monitor.sendMessageAndData(block, block.length, "audio ",
call_session_token, " ",
codec.codeString);
bytesRead = 0;
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
Log.d(TAG, "Releasing recorder and terminating");
cleanup();
audioThread = null;
}
|
diff --git a/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/disassembly/TCFDisassemblyBackend.java b/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/disassembly/TCFDisassemblyBackend.java
index 0d4b19e25..cfb211383 100644
--- a/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/disassembly/TCFDisassemblyBackend.java
+++ b/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/disassembly/TCFDisassemblyBackend.java
@@ -1,972 +1,972 @@
/*******************************************************************************
* Copyright (c) 2010, 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.internal.cdt.ui.disassembly;
import static org.eclipse.cdt.debug.internal.ui.disassembly.dsf.DisassemblyUtils.DEBUG;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AbstractDisassemblyBackend;
import org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AddressRangePosition;
import org.eclipse.cdt.debug.internal.ui.disassembly.dsf.DisassemblyUtils;
import org.eclipse.cdt.debug.internal.ui.disassembly.dsf.ErrorPosition;
import org.eclipse.cdt.debug.internal.ui.disassembly.dsf.IDisassemblyPartCallback;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchesListener;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocumentExtension4;
import org.eclipse.jface.text.Position;
import org.eclipse.tcf.internal.cdt.ui.Activator;
import org.eclipse.tcf.internal.debug.launch.TCFSourceLookupDirector;
import org.eclipse.tcf.internal.debug.launch.TCFSourceLookupParticipant;
import org.eclipse.tcf.internal.debug.model.TCFContextState;
import org.eclipse.tcf.internal.debug.model.TCFSourceRef;
import org.eclipse.tcf.internal.debug.ui.model.TCFChildrenStackTrace;
import org.eclipse.tcf.internal.debug.ui.model.TCFModel;
import org.eclipse.tcf.internal.debug.ui.model.TCFNode;
import org.eclipse.tcf.internal.debug.ui.model.TCFNodeExecContext;
import org.eclipse.tcf.internal.debug.ui.model.TCFNodeStackFrame;
import org.eclipse.tcf.internal.debug.ui.model.TCFNumberFormat;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IChannel.IChannelListener;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IDisassembly;
import org.eclipse.tcf.services.IDisassembly.DoneDisassemble;
import org.eclipse.tcf.services.IDisassembly.IDisassemblyLine;
import org.eclipse.tcf.services.IExpressions;
import org.eclipse.tcf.services.IExpressions.DoneCreate;
import org.eclipse.tcf.services.IExpressions.DoneDispose;
import org.eclipse.tcf.services.IExpressions.DoneEvaluate;
import org.eclipse.tcf.services.IExpressions.Expression;
import org.eclipse.tcf.services.IExpressions.Value;
import org.eclipse.tcf.services.ILineNumbers;
import org.eclipse.tcf.services.ILineNumbers.CodeArea;
import org.eclipse.tcf.services.ILineNumbers.DoneMapToSource;
import org.eclipse.tcf.services.IMemory.MemoryError;
import org.eclipse.tcf.services.IMemory;
import org.eclipse.tcf.services.IRunControl;
import org.eclipse.tcf.services.IRunControl.RunControlContext;
import org.eclipse.tcf.services.IRunControl.RunControlListener;
import org.eclipse.tcf.services.ISymbols;
import org.eclipse.tcf.util.TCFDataCache;
import org.eclipse.tcf.util.TCFTask;
import org.eclipse.ui.PlatformUI;
@SuppressWarnings("restriction")
public class TCFDisassemblyBackend extends AbstractDisassemblyBackend {
private static class AddressRange {
BigInteger start;
BigInteger end;
}
private static class FunctionOffset {
static final FunctionOffset NONE = new FunctionOffset(null, null);
String name;
BigInteger offset;
FunctionOffset(String name, BigInteger offset) {
this.name = name;
this.offset = offset;
}
@Override
public String toString() {
if (name == null || name.length() == 0) return "";
if (isZeroOffset()) return name;
return name + '+' + offset.toString();
}
boolean isZeroOffset() {
return offset == null || offset.compareTo(BigInteger.ZERO) == 0;
}
}
private class TCFLaunchListener implements ILaunchesListener {
public void launchesRemoved(ILaunch[] launches) {
}
public void launchesAdded(ILaunch[] launches) {
}
public void launchesChanged(ILaunch[] launches) {
if (fExecContext == null) return;
for (ILaunch launch : launches) {
if (launch == fExecContext.getModel().getLaunch()) {
if (launch.isTerminated()) {
handleSessionEnded();
}
break;
}
}
}
}
private class TCFChannelListener implements IChannelListener {
public void onChannelOpened() {
}
public void onChannelClosed(Throwable error) {
handleSessionEnded();
}
public void congestionLevel(int level) {
}
}
private class TCFRunControlListener implements RunControlListener {
public void contextAdded(RunControlContext[] contexts) {
}
public void contextChanged(RunControlContext[] contexts) {
}
public void contextRemoved(String[] context_ids) {
String id = fExecContext.getID();
for (String contextId : context_ids) {
if (id.equals(contextId)) {
fCallback.handleTargetEnded();
return;
}
}
}
public void contextSuspended(String context, String pc, String reason,
Map<String, Object> params) {
if (fExecContext.getID().equals(context)) {
handleContextSuspended(pc != null ? new BigInteger(pc) : null);
}
}
public void contextResumed(String context) {
if (fExecContext.getID().equals(context)) {
fCallback.handleTargetResumed();
}
}
public void containerSuspended(String context, String pc,
String reason, Map<String, Object> params,
String[] suspended_ids) {
String id = fExecContext.getID();
if (id.equals(context)) {
handleContextSuspended(pc != null ? new BigInteger(pc) : null);
return;
}
for (String contextId : suspended_ids) {
if (id.equals(contextId)) {
handleContextSuspended(null);
return;
}
}
}
public void containerResumed(String[] context_ids) {
String id = fExecContext.getID();
for (String contextId : context_ids) {
if (id.equals(contextId)) {
fCallback.handleTargetResumed();
return;
}
}
}
public void contextException(String context, String msg) {
}
}
private IDisassemblyPartCallback fCallback;
private volatile TCFNodeExecContext fExecContext;
private volatile TCFNodeExecContext fMemoryContext;
private volatile TCFNodeStackFrame fActiveFrame;
private volatile BigInteger fSuspendAddress;
private volatile int fSuspendCount;
private final IRunControl.RunControlListener fRunControlListener = new TCFRunControlListener();
private final IChannelListener fChannelListener = new TCFChannelListener();
private final ILaunchesListener fLaunchesListener = new TCFLaunchListener();
@Override
public void init(IDisassemblyPartCallback callback) {
fCallback = callback;
}
public boolean supportsDebugContext(IAdaptable context) {
return (context instanceof TCFNodeExecContext || context instanceof TCFNodeStackFrame)
&& hasDisassemblyService((TCFNode) context);
}
private boolean hasDisassemblyService(final TCFNode context) {
Boolean hasService = new TCFTask<Boolean>() {
public void run() {
IDisassembly disass = null;
IChannel channel = context.getChannel();
if (channel != null && channel.getState() != IChannel.STATE_CLOSED) {
disass = channel.getRemoteService(IDisassembly.class);
}
done(disass != null);
}
}.getE();
return hasService != null && hasService.booleanValue();
}
public boolean hasDebugContext() {
return fExecContext != null;
}
public SetDebugContextResult setDebugContext(IAdaptable context) {
TCFNodeStackFrame frame = null;
TCFNodeExecContext thread = null;
SetDebugContextResult result = new SetDebugContextResult();
if (context instanceof TCFNodeExecContext) {
thread = (TCFNodeExecContext)context;
IChannel channel = thread.getChannel();
try {
final TCFNodeExecContext ctx = thread;
frame = new TCFTask<TCFNodeStackFrame>(channel) {
public void run() {
TCFChildrenStackTrace stack = ctx.getStackTrace();
if (!stack.validate(this)) return;
done(stack.getTopFrame());
}
}.getE();
}
catch (Error x) {
if (channel.getState() == IChannel.STATE_OPEN) throw x;
frame = null;
}
if (frame == null) thread = null;
}
else if (context instanceof TCFNodeStackFrame) {
frame = (TCFNodeStackFrame)context;
thread = (TCFNodeExecContext)frame.getParent();
}
if (fExecContext != thread) {
result.contextChanged = true;
fSuspendCount++;
if (fExecContext != null) removeListeners(fExecContext);
fExecContext = thread;
if (thread != null) addListeners(thread);
}
if (fExecContext != null) {
fMemoryContext = new TCFTask<TCFNodeExecContext>(fExecContext.getChannel()) {
public void run() {
TCFDataCache<TCFNodeExecContext> cache = fExecContext.getMemoryNode();
if (!cache.validate(this)) return;
done(cache.getData());
}
}.getE();
}
else {
fMemoryContext = null;
}
fActiveFrame = frame;
result.sessionId = thread != null ? thread.getID() : null;
if (!result.contextChanged && fActiveFrame != null) {
fCallback.asyncExec(new Runnable() {
public void run() {
fCallback.gotoFrameIfActive(getFrameLevel());
}
});
}
return result;
}
private void addListeners(final TCFNodeExecContext context) {
assert context != null;
Protocol.invokeAndWait(new Runnable() {
public void run() {
IChannel channel = context.getChannel();
IRunControl rctl = channel.getRemoteService(IRunControl.class);
if (rctl != null) rctl.addListener(fRunControlListener);
channel.addChannelListener(fChannelListener);
}
});
DebugPlugin.getDefault().getLaunchManager().addLaunchListener(fLaunchesListener );
}
private void removeListeners(final TCFNodeExecContext context) {
assert context != null;
DebugPlugin.getDefault().getLaunchManager().removeLaunchListener(fLaunchesListener);
Protocol.invokeAndWait(new Runnable() {
public void run() {
IChannel channel = context.getChannel();
IRunControl rctl = channel.getRemoteService(IRunControl.class);
if (rctl != null) rctl.removeListener(fRunControlListener);
channel.removeChannelListener(fChannelListener);
}
});
}
private void handleContextSuspended(BigInteger pc) {
fSuspendCount++;
fSuspendAddress = pc;
fCallback.handleTargetSuspended();
}
private void handleSessionEnded() {
clearDebugContext();
fCallback.handleTargetEnded();
}
public void clearDebugContext() {
if (fExecContext != null) {
removeListeners(fExecContext);
}
fExecContext = null;
fMemoryContext = null;
fActiveFrame = null;
}
public void retrieveFrameAddress(final int targetFrame) {
final TCFNodeExecContext execContext = fExecContext;
if (execContext == null) {
fCallback.setUpdatePending(false);
return;
}
BigInteger address;
if (targetFrame == 0 && fSuspendAddress != null) {
// shortcut for goto frame on suspend
address = fSuspendAddress;
fSuspendAddress = null;
}
else {
final int suspendCount = fSuspendCount;
final TCFChildrenStackTrace stack = execContext.getStackTrace();
address = new TCFTask<BigInteger>(execContext.getChannel()) {
public void run() {
if (suspendCount != fSuspendCount || execContext != fExecContext) {
done(null);
return;
}
if (!stack.validate(this)) return;
TCFNodeStackFrame frame = null;
if (targetFrame == 0) {
frame = stack.getTopFrame();
}
else {
Map<String,TCFNode> frameData = stack.getData();
for (TCFNode node : frameData.values()) {
if (node instanceof TCFNodeStackFrame) {
TCFNodeStackFrame cand = (TCFNodeStackFrame) node;
if (cand.getFrameNo() == targetFrame) {
frame = cand;
break;
}
}
}
}
if (frame != null) {
TCFDataCache<BigInteger> addressCache = frame.getAddress();
if (!addressCache.validate(this)) return;
done(addressCache.getData());
return;
}
done(null);
}
}.getE();
}
if (execContext == fExecContext) {
fCallback.setUpdatePending(false);
if (address == null) address = BigInteger.valueOf(-2);
if (targetFrame == 0) {
fCallback.updatePC(address);
}
else {
fCallback.gotoFrame(targetFrame, address);
}
}
}
public int getFrameLevel() {
if (fActiveFrame == null) return -1;
Integer level = new TCFTask<Integer>() {
public void run() {
done(fActiveFrame != null ? fActiveFrame.getFrameNo() : -1);
}
}.getE();
return level != null ? level.intValue() : -1;
}
public boolean isSuspended() {
if (fExecContext == null) return false;
Boolean suspended = new TCFTask<Boolean>(fExecContext.getChannel()) {
public void run() {
if (fExecContext == null) {
done(null);
return;
}
TCFDataCache<TCFContextState> stateCache = fExecContext.getState();
if (!stateCache.validate(this)) return;
TCFContextState state = stateCache.getData();
if (state != null) {
done(state.is_suspended);
return;
}
done(null);
}
}.getE();
return suspended != null ? suspended.booleanValue() : false;
}
public boolean hasFrameContext() {
return fActiveFrame != null;
}
public String getFrameFile() {
final TCFNodeStackFrame frame = fActiveFrame;
if (frame == null) return null;
String file = new TCFTask<String>(frame.getChannel()) {
public void run() {
if (frame != fActiveFrame) {
done(null);
return;
}
TCFDataCache<TCFSourceRef> sourceRefCache = frame.getLineInfo();
if (!sourceRefCache.validate(this)) return;
TCFSourceRef sourceRef = sourceRefCache.getData();
if (sourceRef != null && sourceRef.area != null) {
done(TCFSourceLookupParticipant.toFileName(sourceRef.area));
return;
}
done(null);
}
}.getE();
return file;
}
public int getFrameLine() {
final TCFNodeStackFrame frame = fActiveFrame;
if (frame == null) return -1;
Integer line = new TCFTask<Integer>(frame.getChannel()) {
public void run() {
if (frame != fActiveFrame) {
done(null);
return;
}
TCFDataCache<TCFSourceRef> sourceRefCache = frame.getLineInfo();
if (!sourceRefCache.validate(this)) return;
TCFSourceRef sourceRef = sourceRefCache.getData();
if (sourceRef != null && sourceRef.area != null) {
done(sourceRef.area.start_line);
return;
}
done(null);
}
}.getE();
return line != null ? line.intValue() : -1;
}
public void retrieveDisassembly(final BigInteger startAddress,
BigInteger endAddress, String file, int lineNumber, int lines,
final boolean mixed, final boolean showSymbols, boolean showDisassembly,
final int linesHint) {
final TCFNodeExecContext execContext = fExecContext;
if (execContext == null || execContext.isDisposed()) {
fCallback.setUpdatePending(false);
return;
}
final int suspendCount = fSuspendCount;
final long modCount = getModCount();
Protocol.invokeLater(new Runnable() {
IMemory.MemoryContext mem;
boolean big_endian;
int addr_bits;
IDisassemblyLine[] disassembly;
AddressRange range;
boolean done_disassembly;
ISymbols.Symbol[] functionSymbols;
boolean done_symbols;
CodeArea[] code_areas;
boolean done_line_numbers;
byte[] code;
boolean done_code;
public void run() {
if (execContext != fExecContext) return;
if (suspendCount != fSuspendCount || fMemoryContext == null) {
fCallback.setUpdatePending(false);
return;
}
final IChannel channel = execContext.getChannel();
IDisassembly disass = channel.getRemoteService(IDisassembly.class);
if (disass == null) {
fCallback.setUpdatePending(false);
return;
}
TCFDataCache<IMemory.MemoryContext> cache = fMemoryContext.getMemoryContext();
if (!cache.validate(this)) return;
mem = cache.getData();
if (mem == null) {
fCallback.setUpdatePending(false);
return;
}
big_endian = mem.isBigEndian();
addr_bits = mem.getAddressSize() * 8;
if (!done_disassembly) {
Map<String, Object> params = new HashMap<String, Object>();
disass.disassemble(mem.getID(), startAddress, linesHint * 4, params, new DoneDisassemble() {
@Override
public void doneDisassemble(IToken token, final Throwable error, IDisassemblyLine[] res) {
if (execContext != fExecContext) return;
if (error != null) {
fCallback.asyncExec(new Runnable() {
public void run() {
if (execContext != fExecContext) return;
if (modCount == getModCount()) {
fCallback.insertError(startAddress, TCFModel.getErrorMessage(error, false));
fCallback.setUpdatePending(false);
if (fCallback.getAddressSize() < addr_bits) fCallback.addressSizeChanged(addr_bits);
}
}
});
return;
}
if (res != null && res.length > 0) {
disassembly = res;
range = new AddressRange();
range.start = JSON.toBigInteger(res[0].getAddress());
IDisassemblyLine last = res[res.length - 1];
range.end = JSON.toBigInteger(last.getAddress()).add(BigInteger.valueOf(last.getSize()));
}
done_disassembly = true;
run();
}
});
return;
}
if (!done_symbols && (range == null || !showSymbols)) {
done_symbols = true;
}
if (!done_symbols) {
final ISymbols symbols = channel.getRemoteService(ISymbols.class);
if (symbols == null) {
done_symbols = true;
}
else {
final ArrayList<ISymbols.Symbol> symbolList = new ArrayList<ISymbols.Symbol>();
IDisassemblyLine line = disassembly[0];
symbols.findByAddr(mem.getID(), line.getAddress(), new ISymbols.DoneFind() {
int idx = 0;
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error == null && symbol_id != null) {
symbols.getContext(symbol_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol context) {
BigInteger nextAddress = null;
if (error == null && context != null) {
if (context.getTypeClass().equals(ISymbols.TypeClass.function)) {
symbolList.add(context);
nextAddress = JSON.toBigInteger(context.getAddress()).add(BigInteger.valueOf(context.getSize()));
}
}
findNextSymbol(nextAddress);
}
});
return;
}
findNextSymbol(null);
}
private void findNextSymbol(BigInteger nextAddress) {
while (++idx < disassembly.length) {
BigInteger instrAddress = JSON.toBigInteger(disassembly[idx].getAddress());
if (nextAddress != null && instrAddress.compareTo(nextAddress) < 0) continue;
symbols.findByAddr(mem.getID(), instrAddress, this);
return;
}
functionSymbols = symbolList.toArray(new ISymbols.Symbol[symbolList.size()]);
done_symbols = true;
run();
}
});
return;
}
}
if (!done_line_numbers && (range == null || !mixed)) {
done_line_numbers = true;
}
if (!done_line_numbers) {
ILineNumbers lineNumbers = channel.getRemoteService(ILineNumbers.class);
if (lineNumbers == null) {
done_line_numbers = true;
}
else {
lineNumbers.mapToSource(mem.getID(), range.start, range.end, new DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, final CodeArea[] areas) {
if (error != null) {
Activator.log(error);
}
else {
code_areas = areas;
}
done_line_numbers = true;
run();
}
});
return;
}
}
if (!done_code && range == null) {
done_code = true;
}
if (!done_code) {
code = new byte[range.end.subtract(range.start).intValue()];
- mem.get(startAddress, 1, code, 0, code.length, 0, new IMemory.DoneMemory() {
+ mem.get(range.start, 1, code, 0, code.length, 0, new IMemory.DoneMemory() {
@Override
public void doneMemory(IToken token, MemoryError error) {
done_code = true;
run();
}
});
return;
}
fCallback.asyncExec(new Runnable() {
public void run() {
insertDisassembly(modCount, startAddress, code, range, big_endian,
disassembly, functionSymbols, code_areas);
if (fCallback.getAddressSize() < addr_bits) fCallback.addressSizeChanged(addr_bits);
}
});
}
});
}
private long getModCount() {
return ((IDocumentExtension4) fCallback.getDocument()).getModificationStamp();
}
protected final void insertDisassembly(long modCount, BigInteger startAddress, byte[] code, AddressRange range, boolean big_endian,
IDisassemblyLine[] instructions, ISymbols.Symbol[] symbols, CodeArea[] codeAreas) {
if (!fCallback.hasViewer() || fExecContext == null) return;
if (modCount != getModCount()) return;
if (DEBUG) System.out.println("insertDisassembly "+ DisassemblyUtils.getAddressText(startAddress)); //$NON-NLS-1$
boolean updatePending = fCallback.getUpdatePending();
assert updatePending;
if (!updatePending) {
// safe-guard in case something weird is going on
return;
}
boolean insertedAnyAddress = false;
try {
fCallback.lockScroller();
AddressRangePosition p = null;
if (instructions != null) for (IDisassemblyLine instruction : instructions) {
BigInteger address = JSON.toBigInteger(instruction.getAddress());
if (startAddress == null) {
startAddress = address;
fCallback.setGotoAddressPending(address);
}
if (p == null || !p.containsAddress(address)) {
p = fCallback.getPositionOfAddress(address);
}
if (p instanceof ErrorPosition && p.fValid) {
p.fValid = false;
fCallback.getDocument().addInvalidAddressRange(p);
}
else if (p == null /* || address.compareTo(endAddress) > 0 */) {
if (DEBUG) System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$
return;
}
else if (p.fValid) {
if (DEBUG) System.out.println("Excess disassembly lines at " + DisassemblyUtils.getAddressText(address)); //$NON-NLS-1$
// if (!p.fAddressOffset.equals(address)) {
// // override probably unaligned disassembly
// p.fValid = false;
// fCallback.getDocument().addInvalidAddressRange(p);
// }
// else {
continue;
// }
}
// insert source
String sourceFile = null;
int firstLine = -1;
int lastLine = -1;
CodeArea area = findCodeArea(address, codeAreas);
if (area != null && area.file != null) {
IPath filePath = new Path(area.file);
if (!filePath.isAbsolute() && area.directory != null) {
filePath = new Path(area.directory).append(filePath);
}
sourceFile = filePath.toString();
firstLine = area.start_line - 1;
lastLine = area.end_line - 2;
}
if (sourceFile != null && firstLine >= 0) {
try {
p = fCallback.insertSource(p, address, sourceFile, firstLine, lastLine);
}
catch (NoSuchMethodError nsme) {
// use fallback
p = fCallback.insertSource(p, address, sourceFile, firstLine);
}
}
// insert symbol label
FunctionOffset functionOffset = getFunctionOffset(address, symbols);
if (functionOffset.name != null && functionOffset.isZeroOffset()) {
p = fCallback.getDocument().insertLabel(p, address, functionOffset.name, true);
}
// insert instruction
int instrLength = instruction.getSize();
Map<String,Object>[] instrAttrs = instruction.getInstruction();
String instr = formatInstruction(instrAttrs);
int offs = address.subtract(range.start).intValue();
if (code != null && offs >= 0 && offs + instrLength <= code.length) {
BigInteger opcode = BigInteger.ZERO;
for (int i = 0; i < instrLength; i++) {
int j = big_endian ? i : instrLength - i - 1;
opcode = opcode.shiftLeft(8).add(BigInteger.valueOf(code[offs + j] & 0xff));
}
p = fCallback.getDocument().insertDisassemblyLine(p,
address, instrLength, functionOffset.toString(),
opcode, instr, sourceFile, firstLine);
}
else {
p = fCallback.getDocument().insertDisassemblyLine(p,
address, instrLength, functionOffset.toString(),
instr, sourceFile, firstLine);
}
if (p == null) break;
insertedAnyAddress = true;
}
}
catch (BadLocationException e) {
// should not happen
DisassemblyUtils.internalError(e);
}
finally {
fCallback.setUpdatePending(false);
if (insertedAnyAddress) {
fCallback.updateInvalidSource();
fCallback.unlockScroller();
fCallback.doPending();
fCallback.updateVisibleArea();
}
else {
fCallback.unlockScroller();
}
}
}
private FunctionOffset getFunctionOffset(BigInteger address, ISymbols.Symbol[] symbols) {
if (symbols != null) {
for (ISymbols.Symbol symbol : symbols) {
BigInteger symbolAddress = JSON.toBigInteger(symbol.getAddress());
BigInteger offset = address.subtract(symbolAddress);
switch (offset.compareTo(BigInteger.ZERO)) {
case 0:
return new FunctionOffset(symbol.getName(), BigInteger.ZERO);
case 1:
if (offset.compareTo(BigInteger.valueOf(symbol.getSize())) < 0) {
return new FunctionOffset(symbol.getName(), offset);
}
break;
default:
break;
}
}
}
return FunctionOffset.NONE;
}
private CodeArea findCodeArea(BigInteger address, CodeArea[] codeAreas) {
if (codeAreas != null) {
for (CodeArea codeArea : codeAreas) {
if (address.equals(JSON.toBigInteger(codeArea.start_address))) {
return codeArea;
}
}
}
return null;
}
/**
* Format an instruction.
*
* @param instrAttrs
* @return string representation
*/
private String formatInstruction(Map<String, Object>[] instrAttrs) {
StringBuilder buf = new StringBuilder(20);
for (Map<String, Object> attrs : instrAttrs) {
if (buf.length() > 0) buf.append(' ');
Object type = attrs.get(IDisassembly.FIELD_TYPE);
if (IDisassembly.FTYPE_STRING.equals(type) || IDisassembly.FTYPE_Register.equals(type)) {
Object text = attrs.get(IDisassembly.FIELD_TEXT);
buf.append(text);
}
else {
Object value = attrs.get(IDisassembly.FIELD_VALUE);
BigInteger bigValue = new BigInteger(value.toString());
// TODO number format
buf.append("0x").append(bigValue.toString(16));
}
}
return buf.toString();
}
public void gotoSymbol(final String symbol) {
final TCFNodeStackFrame activeFrame = fActiveFrame;
if (activeFrame == null) return;
Protocol.invokeLater(new Runnable() {
public void run() {
if (activeFrame != fActiveFrame) return;
IChannel channel = activeFrame.getChannel();
final IExpressions exprSvc = channel.getRemoteService(IExpressions.class);
if (exprSvc != null) {
TCFNode evalContext = activeFrame.isEmulated() ? activeFrame.getParent() : activeFrame;
exprSvc.create(evalContext.getID(), null, symbol, new DoneCreate() {
public void doneCreate(IToken token, Exception error, final Expression context) {
if (error == null) {
exprSvc.evaluate(context.getID(), new DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, Value value) {
if (error == null && value.getValue() != null) {
final BigInteger address = TCFNumberFormat.toBigInteger(
value.getValue(), value.isBigEndian(), false);
fCallback.asyncExec(new Runnable() {
public void run() {
fCallback.gotoAddress(address);
}
});
}
else {
handleError(error);
}
exprSvc.dispose(context.getID(), new DoneDispose() {
public void doneDispose(IToken token, Exception error) {
// no-op
}
});
}
});
}
else {
handleError(error);
}
}
});
}
}
protected void handleError(final Exception error) {
fCallback.asyncExec(new Runnable() {
public void run() {
Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, error.getLocalizedMessage(), error);
ErrorDialog.openError(fCallback.getSite().getShell(), "Error", null, status); //$NON-NLS-1$
}
});
}
});
}
public void retrieveDisassembly(String file, int lines,
BigInteger endAddress, boolean mixed, boolean showSymbols,
boolean showDisassembly) {
// TODO disassembly for source file
fCallback.setUpdatePending(false);
}
public String evaluateExpression(final String expression) {
final TCFNodeStackFrame activeFrame = fActiveFrame;
if (activeFrame == null) return null;
String value = new TCFTask<String>(activeFrame.getChannel()) {
public void run() {
if (activeFrame != fActiveFrame) {
done(null);
return;
}
IChannel channel = activeFrame.getChannel();
final IExpressions exprSvc = channel.getRemoteService(IExpressions.class);
if (exprSvc != null) {
TCFNode evalContext = activeFrame.isEmulated() ? activeFrame.getParent() : activeFrame;
exprSvc.create(evalContext.getID(), null, expression, new DoneCreate() {
public void doneCreate(IToken token, Exception error, final Expression context) {
if (error == null) {
exprSvc.evaluate(context.getID(), new DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, Value value) {
if (error == null && value.getValue() != null) {
BigInteger address = TCFNumberFormat.toBigInteger(
value.getValue(), value.isBigEndian(), false);
done("0x" + address.toString(16));
}
else {
done(null);
}
exprSvc.dispose(context.getID(), new DoneDispose() {
public void doneDispose(IToken token, Exception error) {
// no-op
}
});
}
});
}
else {
done(null);
}
}
});
}
else {
done(null);
}
}
}.getE();
return value;
}
public void dispose() {
}
public Object insertSource(Position pos, BigInteger address, String file, int lineNumber) {
TCFNodeExecContext ctx = fMemoryContext;
if (ctx == null) return null;
return TCFSourceLookupDirector.lookup(ctx.getModel().getLaunch(), ctx.getID(), file);
}
/*
* @see org.eclipse.cdt.debug.internal.ui.disassembly.dsf.AbstractDisassemblyBackend#evaluateAddressExpression(java.lang.String, boolean)
*/
@Override
public BigInteger evaluateAddressExpression(String expression, boolean suppressError) {
String value = evaluateExpression(expression);
if (value != null) {
try {
return DisassemblyUtils.decodeAddress(value);
}
catch (NumberFormatException e) {
if (!suppressError) {
MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Expression does not evaluate to an address");
}
}
}
return null;
}
}
| true | true | public void retrieveDisassembly(final BigInteger startAddress,
BigInteger endAddress, String file, int lineNumber, int lines,
final boolean mixed, final boolean showSymbols, boolean showDisassembly,
final int linesHint) {
final TCFNodeExecContext execContext = fExecContext;
if (execContext == null || execContext.isDisposed()) {
fCallback.setUpdatePending(false);
return;
}
final int suspendCount = fSuspendCount;
final long modCount = getModCount();
Protocol.invokeLater(new Runnable() {
IMemory.MemoryContext mem;
boolean big_endian;
int addr_bits;
IDisassemblyLine[] disassembly;
AddressRange range;
boolean done_disassembly;
ISymbols.Symbol[] functionSymbols;
boolean done_symbols;
CodeArea[] code_areas;
boolean done_line_numbers;
byte[] code;
boolean done_code;
public void run() {
if (execContext != fExecContext) return;
if (suspendCount != fSuspendCount || fMemoryContext == null) {
fCallback.setUpdatePending(false);
return;
}
final IChannel channel = execContext.getChannel();
IDisassembly disass = channel.getRemoteService(IDisassembly.class);
if (disass == null) {
fCallback.setUpdatePending(false);
return;
}
TCFDataCache<IMemory.MemoryContext> cache = fMemoryContext.getMemoryContext();
if (!cache.validate(this)) return;
mem = cache.getData();
if (mem == null) {
fCallback.setUpdatePending(false);
return;
}
big_endian = mem.isBigEndian();
addr_bits = mem.getAddressSize() * 8;
if (!done_disassembly) {
Map<String, Object> params = new HashMap<String, Object>();
disass.disassemble(mem.getID(), startAddress, linesHint * 4, params, new DoneDisassemble() {
@Override
public void doneDisassemble(IToken token, final Throwable error, IDisassemblyLine[] res) {
if (execContext != fExecContext) return;
if (error != null) {
fCallback.asyncExec(new Runnable() {
public void run() {
if (execContext != fExecContext) return;
if (modCount == getModCount()) {
fCallback.insertError(startAddress, TCFModel.getErrorMessage(error, false));
fCallback.setUpdatePending(false);
if (fCallback.getAddressSize() < addr_bits) fCallback.addressSizeChanged(addr_bits);
}
}
});
return;
}
if (res != null && res.length > 0) {
disassembly = res;
range = new AddressRange();
range.start = JSON.toBigInteger(res[0].getAddress());
IDisassemblyLine last = res[res.length - 1];
range.end = JSON.toBigInteger(last.getAddress()).add(BigInteger.valueOf(last.getSize()));
}
done_disassembly = true;
run();
}
});
return;
}
if (!done_symbols && (range == null || !showSymbols)) {
done_symbols = true;
}
if (!done_symbols) {
final ISymbols symbols = channel.getRemoteService(ISymbols.class);
if (symbols == null) {
done_symbols = true;
}
else {
final ArrayList<ISymbols.Symbol> symbolList = new ArrayList<ISymbols.Symbol>();
IDisassemblyLine line = disassembly[0];
symbols.findByAddr(mem.getID(), line.getAddress(), new ISymbols.DoneFind() {
int idx = 0;
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error == null && symbol_id != null) {
symbols.getContext(symbol_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol context) {
BigInteger nextAddress = null;
if (error == null && context != null) {
if (context.getTypeClass().equals(ISymbols.TypeClass.function)) {
symbolList.add(context);
nextAddress = JSON.toBigInteger(context.getAddress()).add(BigInteger.valueOf(context.getSize()));
}
}
findNextSymbol(nextAddress);
}
});
return;
}
findNextSymbol(null);
}
private void findNextSymbol(BigInteger nextAddress) {
while (++idx < disassembly.length) {
BigInteger instrAddress = JSON.toBigInteger(disassembly[idx].getAddress());
if (nextAddress != null && instrAddress.compareTo(nextAddress) < 0) continue;
symbols.findByAddr(mem.getID(), instrAddress, this);
return;
}
functionSymbols = symbolList.toArray(new ISymbols.Symbol[symbolList.size()]);
done_symbols = true;
run();
}
});
return;
}
}
if (!done_line_numbers && (range == null || !mixed)) {
done_line_numbers = true;
}
if (!done_line_numbers) {
ILineNumbers lineNumbers = channel.getRemoteService(ILineNumbers.class);
if (lineNumbers == null) {
done_line_numbers = true;
}
else {
lineNumbers.mapToSource(mem.getID(), range.start, range.end, new DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, final CodeArea[] areas) {
if (error != null) {
Activator.log(error);
}
else {
code_areas = areas;
}
done_line_numbers = true;
run();
}
});
return;
}
}
if (!done_code && range == null) {
done_code = true;
}
if (!done_code) {
code = new byte[range.end.subtract(range.start).intValue()];
mem.get(startAddress, 1, code, 0, code.length, 0, new IMemory.DoneMemory() {
@Override
public void doneMemory(IToken token, MemoryError error) {
done_code = true;
run();
}
});
return;
}
fCallback.asyncExec(new Runnable() {
public void run() {
insertDisassembly(modCount, startAddress, code, range, big_endian,
disassembly, functionSymbols, code_areas);
if (fCallback.getAddressSize() < addr_bits) fCallback.addressSizeChanged(addr_bits);
}
});
}
});
}
| public void retrieveDisassembly(final BigInteger startAddress,
BigInteger endAddress, String file, int lineNumber, int lines,
final boolean mixed, final boolean showSymbols, boolean showDisassembly,
final int linesHint) {
final TCFNodeExecContext execContext = fExecContext;
if (execContext == null || execContext.isDisposed()) {
fCallback.setUpdatePending(false);
return;
}
final int suspendCount = fSuspendCount;
final long modCount = getModCount();
Protocol.invokeLater(new Runnable() {
IMemory.MemoryContext mem;
boolean big_endian;
int addr_bits;
IDisassemblyLine[] disassembly;
AddressRange range;
boolean done_disassembly;
ISymbols.Symbol[] functionSymbols;
boolean done_symbols;
CodeArea[] code_areas;
boolean done_line_numbers;
byte[] code;
boolean done_code;
public void run() {
if (execContext != fExecContext) return;
if (suspendCount != fSuspendCount || fMemoryContext == null) {
fCallback.setUpdatePending(false);
return;
}
final IChannel channel = execContext.getChannel();
IDisassembly disass = channel.getRemoteService(IDisassembly.class);
if (disass == null) {
fCallback.setUpdatePending(false);
return;
}
TCFDataCache<IMemory.MemoryContext> cache = fMemoryContext.getMemoryContext();
if (!cache.validate(this)) return;
mem = cache.getData();
if (mem == null) {
fCallback.setUpdatePending(false);
return;
}
big_endian = mem.isBigEndian();
addr_bits = mem.getAddressSize() * 8;
if (!done_disassembly) {
Map<String, Object> params = new HashMap<String, Object>();
disass.disassemble(mem.getID(), startAddress, linesHint * 4, params, new DoneDisassemble() {
@Override
public void doneDisassemble(IToken token, final Throwable error, IDisassemblyLine[] res) {
if (execContext != fExecContext) return;
if (error != null) {
fCallback.asyncExec(new Runnable() {
public void run() {
if (execContext != fExecContext) return;
if (modCount == getModCount()) {
fCallback.insertError(startAddress, TCFModel.getErrorMessage(error, false));
fCallback.setUpdatePending(false);
if (fCallback.getAddressSize() < addr_bits) fCallback.addressSizeChanged(addr_bits);
}
}
});
return;
}
if (res != null && res.length > 0) {
disassembly = res;
range = new AddressRange();
range.start = JSON.toBigInteger(res[0].getAddress());
IDisassemblyLine last = res[res.length - 1];
range.end = JSON.toBigInteger(last.getAddress()).add(BigInteger.valueOf(last.getSize()));
}
done_disassembly = true;
run();
}
});
return;
}
if (!done_symbols && (range == null || !showSymbols)) {
done_symbols = true;
}
if (!done_symbols) {
final ISymbols symbols = channel.getRemoteService(ISymbols.class);
if (symbols == null) {
done_symbols = true;
}
else {
final ArrayList<ISymbols.Symbol> symbolList = new ArrayList<ISymbols.Symbol>();
IDisassemblyLine line = disassembly[0];
symbols.findByAddr(mem.getID(), line.getAddress(), new ISymbols.DoneFind() {
int idx = 0;
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error == null && symbol_id != null) {
symbols.getContext(symbol_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol context) {
BigInteger nextAddress = null;
if (error == null && context != null) {
if (context.getTypeClass().equals(ISymbols.TypeClass.function)) {
symbolList.add(context);
nextAddress = JSON.toBigInteger(context.getAddress()).add(BigInteger.valueOf(context.getSize()));
}
}
findNextSymbol(nextAddress);
}
});
return;
}
findNextSymbol(null);
}
private void findNextSymbol(BigInteger nextAddress) {
while (++idx < disassembly.length) {
BigInteger instrAddress = JSON.toBigInteger(disassembly[idx].getAddress());
if (nextAddress != null && instrAddress.compareTo(nextAddress) < 0) continue;
symbols.findByAddr(mem.getID(), instrAddress, this);
return;
}
functionSymbols = symbolList.toArray(new ISymbols.Symbol[symbolList.size()]);
done_symbols = true;
run();
}
});
return;
}
}
if (!done_line_numbers && (range == null || !mixed)) {
done_line_numbers = true;
}
if (!done_line_numbers) {
ILineNumbers lineNumbers = channel.getRemoteService(ILineNumbers.class);
if (lineNumbers == null) {
done_line_numbers = true;
}
else {
lineNumbers.mapToSource(mem.getID(), range.start, range.end, new DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, final CodeArea[] areas) {
if (error != null) {
Activator.log(error);
}
else {
code_areas = areas;
}
done_line_numbers = true;
run();
}
});
return;
}
}
if (!done_code && range == null) {
done_code = true;
}
if (!done_code) {
code = new byte[range.end.subtract(range.start).intValue()];
mem.get(range.start, 1, code, 0, code.length, 0, new IMemory.DoneMemory() {
@Override
public void doneMemory(IToken token, MemoryError error) {
done_code = true;
run();
}
});
return;
}
fCallback.asyncExec(new Runnable() {
public void run() {
insertDisassembly(modCount, startAddress, code, range, big_endian,
disassembly, functionSymbols, code_areas);
if (fCallback.getAddressSize() < addr_bits) fCallback.addressSizeChanged(addr_bits);
}
});
}
});
}
|
diff --git a/hale/eu.esdihumboldt.hale.gmlwriter.test/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/PatternTest.java b/hale/eu.esdihumboldt.hale.gmlwriter.test/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/PatternTest.java
index 4f417206c..1465a726a 100644
--- a/hale/eu.esdihumboldt.hale.gmlwriter.test/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/PatternTest.java
+++ b/hale/eu.esdihumboldt.hale.gmlwriter.test/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/PatternTest.java
@@ -1,115 +1,116 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.writers;
import java.util.List;
import org.geotools.feature.NameImpl;
import org.junit.Test;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.DefinitionPath;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.PathElement;
import eu.esdihumboldt.hale.schemaprovider.model.SchemaElement;
import eu.esdihumboldt.hale.schemaprovider.model.TypeDefinition;
import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.CustomDefaultAttribute;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
/**
* Tests for {@link Pattern}
*
* @author Simon Templer
* @partner 01 / Fraunhofer Institute for Computer Graphics Research
* @version $Id$
*/
public class PatternTest {
private static final String GML_NS = "http://www.opengis.net/gml";
/**
* The curve element name
*/
private static final NameImpl CURVE_ELEMENT = new NameImpl(GML_NS, "Curve");
/**
* Test a direct match
*/
@Test
public void testDirect() {
Pattern pattern = Pattern.parse("Curve");
TypeDefinition start = createCurveType();
DefinitionPath path = pattern.match(start, new DefinitionPath(start, CURVE_ELEMENT), GML_NS);
assertNotNull("A match should have been found", path);
assertTrue("Path should be empty", path.isEmpty());
assertEquals(start, path.getLastType());
}
/**
* Test a direct match that should fails
*/
@Test
public void testDirectFail() {
Pattern pattern = Pattern.parse("CurveType");
TypeDefinition start = createCurveType();
DefinitionPath path = pattern.match(start, new DefinitionPath(start, CURVE_ELEMENT), GML_NS);
assertNull("A match should not have been found", path);
}
/**
* Test a descending match
*/
@Test
public void testDescent() {
Pattern pattern = Pattern.parse("**/LineStringSegment");
TypeDefinition start = createCurveType();
DefinitionPath path = pattern.match(start, new DefinitionPath(start, CURVE_ELEMENT), GML_NS);
assertNotNull("A match should have been found", path);
assertFalse("Path should not be empty", path.isEmpty());
List<PathElement> steps = path.getSteps();
assertEquals(2, steps.size());
String[] names = new String[]{"segments", "LineStringSegment"};
// check path elements
for (int i = 0; i < steps.size(); i++) {
assertEquals(names[i], steps.get(i).getName().getLocalPart());
}
}
private TypeDefinition createCurveType() {
// create the curve type
TypeDefinition curve = new TypeDefinition(new NameImpl(GML_NS, "CurveType"), null, null);
curve.addDeclaringElement(new SchemaElement(CURVE_ELEMENT, curve.getName(), curve, null));
// create the segments property for curve
TypeDefinition segArray = new TypeDefinition(new NameImpl(GML_NS, "CurveSegmentArrayPropertyType"), null, null);
curve.addDeclaredAttribute(new CustomDefaultAttribute("segments", segArray.getName(), segArray, GML_NS, null));
// create the AbstractCurveSegement property for segArray
TypeDefinition absSeg = new TypeDefinition(new NameImpl(GML_NS, "AbstractCurveSegementType"), null, null);
absSeg.setAbstract(true);
segArray.addDeclaredAttribute(new CustomDefaultAttribute("AbstractCurveSegment", absSeg.getName(), absSeg, GML_NS, null));
// add dummy sub-type
new TypeDefinition(new NameImpl("somespace", "SomeSegmentType"), null, absSeg);
// create the LineStringSegmentType sub-type
TypeDefinition lineSeg = new TypeDefinition(new NameImpl(GML_NS, "LineStringSegmentType"), null, absSeg);
- lineSeg.addDeclaringElement(new SchemaElement(new NameImpl(GML_NS, "LineStringSegment"), lineSeg.getName(), lineSeg, null));
+ lineSeg.addDeclaringElement(new SchemaElement(new NameImpl(GML_NS, "LineStringSegment"),
+ lineSeg.getName(), lineSeg, new NameImpl(GML_NS, "AbstractCurveSegment")));
return curve;
}
}
| true | true | private TypeDefinition createCurveType() {
// create the curve type
TypeDefinition curve = new TypeDefinition(new NameImpl(GML_NS, "CurveType"), null, null);
curve.addDeclaringElement(new SchemaElement(CURVE_ELEMENT, curve.getName(), curve, null));
// create the segments property for curve
TypeDefinition segArray = new TypeDefinition(new NameImpl(GML_NS, "CurveSegmentArrayPropertyType"), null, null);
curve.addDeclaredAttribute(new CustomDefaultAttribute("segments", segArray.getName(), segArray, GML_NS, null));
// create the AbstractCurveSegement property for segArray
TypeDefinition absSeg = new TypeDefinition(new NameImpl(GML_NS, "AbstractCurveSegementType"), null, null);
absSeg.setAbstract(true);
segArray.addDeclaredAttribute(new CustomDefaultAttribute("AbstractCurveSegment", absSeg.getName(), absSeg, GML_NS, null));
// add dummy sub-type
new TypeDefinition(new NameImpl("somespace", "SomeSegmentType"), null, absSeg);
// create the LineStringSegmentType sub-type
TypeDefinition lineSeg = new TypeDefinition(new NameImpl(GML_NS, "LineStringSegmentType"), null, absSeg);
lineSeg.addDeclaringElement(new SchemaElement(new NameImpl(GML_NS, "LineStringSegment"), lineSeg.getName(), lineSeg, null));
return curve;
}
| private TypeDefinition createCurveType() {
// create the curve type
TypeDefinition curve = new TypeDefinition(new NameImpl(GML_NS, "CurveType"), null, null);
curve.addDeclaringElement(new SchemaElement(CURVE_ELEMENT, curve.getName(), curve, null));
// create the segments property for curve
TypeDefinition segArray = new TypeDefinition(new NameImpl(GML_NS, "CurveSegmentArrayPropertyType"), null, null);
curve.addDeclaredAttribute(new CustomDefaultAttribute("segments", segArray.getName(), segArray, GML_NS, null));
// create the AbstractCurveSegement property for segArray
TypeDefinition absSeg = new TypeDefinition(new NameImpl(GML_NS, "AbstractCurveSegementType"), null, null);
absSeg.setAbstract(true);
segArray.addDeclaredAttribute(new CustomDefaultAttribute("AbstractCurveSegment", absSeg.getName(), absSeg, GML_NS, null));
// add dummy sub-type
new TypeDefinition(new NameImpl("somespace", "SomeSegmentType"), null, absSeg);
// create the LineStringSegmentType sub-type
TypeDefinition lineSeg = new TypeDefinition(new NameImpl(GML_NS, "LineStringSegmentType"), null, absSeg);
lineSeg.addDeclaringElement(new SchemaElement(new NameImpl(GML_NS, "LineStringSegment"),
lineSeg.getName(), lineSeg, new NameImpl(GML_NS, "AbstractCurveSegment")));
return curve;
}
|
diff --git a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java
index 49f97e02..56eed6c7 100644
--- a/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java
+++ b/wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/AbstractEmbeddedScpWagonWithKeyTest.java
@@ -1,168 +1,168 @@
package org.apache.maven.wagon.providers.ssh;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.wagon.StreamingWagonTestCase;
import org.apache.maven.wagon.Wagon;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.repository.Repository;
import org.apache.maven.wagon.resource.Resource;
import org.codehaus.plexus.util.FileUtils;
import java.io.File;
import java.util.Arrays;
import java.util.List;
/**
* @author <a href="[email protected]">Michal Maczka</a>
* @version $Id$
*/
public abstract class AbstractEmbeddedScpWagonWithKeyTest
extends StreamingWagonTestCase
{
SshServerEmbedded sshServerEmbedded;
@Override
protected void setUp()
throws Exception
{
super.setUp();
String sshKeyResource = "ssh-keys/id_rsa.pub";
sshServerEmbedded = new SshServerEmbedded( getProtocol(), Arrays.asList( sshKeyResource ), true );
sshServerEmbedded.start();
System.out.println( "sshd on port " + sshServerEmbedded.getPort() );
}
@Override
protected void tearDownWagonTestingFixtures()
throws Exception
{
sshServerEmbedded.stop();
}
protected abstract String getProtocol();
@Override
protected int getTestRepositoryPort()
{
return sshServerEmbedded.getPort();
}
public String getTestRepositoryUrl()
{
return TestData.getTestRepositoryUrl( sshServerEmbedded.getPort() );
}
protected AuthenticationInfo getAuthInfo()
{
AuthenticationInfo authInfo = super.getAuthInfo();
// user : guest/guest123 - passphrase : toto01
authInfo.setUserName( "guest" );
//authInfo.setPassword( TestData.getUserPassword() );
authInfo.setPrivateKey( new File( "src/test/ssh-keys/id_rsa" ).getPath() );
return authInfo;
}
protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource )
{
return new File( repository.getBasedir(), resource.getName() ).lastModified();
}
public void testConnect()
throws Exception
{
getWagon().connect( new Repository( "foo", getTestRepositoryUrl() ), getAuthInfo() );
assertTrue( true );
}
@Override
protected boolean supportsGetIfNewer()
{
return false;
}
public void testWithSpaces()
throws Exception
{
String dir = "foo test";
File spaceDirectory = new File( TestData.getRepoPath(), dir );
if ( spaceDirectory.exists() )
{
FileUtils.deleteDirectory( spaceDirectory );
}
spaceDirectory.mkdirs();
String subDir = "foo bar";
File sub = new File( spaceDirectory, subDir );
if ( sub.exists() )
{
FileUtils.deleteDirectory( sub );
}
sub.mkdirs();
File dummy = new File( "src/test/resources/dummy.txt" );
FileUtils.copyFileToDirectory( dummy, sub );
String url = getTestRepositoryUrl() + "/" + dir;
Repository repo = new Repository( "foo", url );
Wagon wagon = getWagon();
- wagon.connect( repo );
+ wagon.connect( repo, getAuthInfo() );
List<String> files = wagon.getFileList( subDir );
assertNotNull( files );
assertEquals( 1, files.size() );
assertTrue( files.contains( "dummy.txt" ) );
wagon.put( new File( "src/test/resources/dummy.txt" ), subDir + "/newdummy.txt" );
files = wagon.getFileList( subDir );
assertNotNull( files );
assertEquals( 2, files.size() );
assertTrue( files.contains( "dummy.txt" ) );
assertTrue( files.contains( "newdummy.txt" ) );
File sourceWithSpace = new File( "target/directory with spaces" );
if ( sourceWithSpace.exists() )
{
FileUtils.deleteDirectory( sourceWithSpace );
}
File resources = new File( "src/test/resources" );
FileUtils.copyDirectory( resources, sourceWithSpace );
wagon.putDirectory( sourceWithSpace, "target with spaces" );
files = wagon.getFileList( "target with spaces" );
assertNotNull( files );
assertTrue( files.contains( "dummy.txt" ) );
assertFalse( files.contains( "newdummy.txt" ) );
assertTrue( files.contains( "log4j.xml" ) );
}
}
| true | true | public void testWithSpaces()
throws Exception
{
String dir = "foo test";
File spaceDirectory = new File( TestData.getRepoPath(), dir );
if ( spaceDirectory.exists() )
{
FileUtils.deleteDirectory( spaceDirectory );
}
spaceDirectory.mkdirs();
String subDir = "foo bar";
File sub = new File( spaceDirectory, subDir );
if ( sub.exists() )
{
FileUtils.deleteDirectory( sub );
}
sub.mkdirs();
File dummy = new File( "src/test/resources/dummy.txt" );
FileUtils.copyFileToDirectory( dummy, sub );
String url = getTestRepositoryUrl() + "/" + dir;
Repository repo = new Repository( "foo", url );
Wagon wagon = getWagon();
wagon.connect( repo );
List<String> files = wagon.getFileList( subDir );
assertNotNull( files );
assertEquals( 1, files.size() );
assertTrue( files.contains( "dummy.txt" ) );
wagon.put( new File( "src/test/resources/dummy.txt" ), subDir + "/newdummy.txt" );
files = wagon.getFileList( subDir );
assertNotNull( files );
assertEquals( 2, files.size() );
assertTrue( files.contains( "dummy.txt" ) );
assertTrue( files.contains( "newdummy.txt" ) );
File sourceWithSpace = new File( "target/directory with spaces" );
if ( sourceWithSpace.exists() )
{
FileUtils.deleteDirectory( sourceWithSpace );
}
File resources = new File( "src/test/resources" );
FileUtils.copyDirectory( resources, sourceWithSpace );
wagon.putDirectory( sourceWithSpace, "target with spaces" );
files = wagon.getFileList( "target with spaces" );
assertNotNull( files );
assertTrue( files.contains( "dummy.txt" ) );
assertFalse( files.contains( "newdummy.txt" ) );
assertTrue( files.contains( "log4j.xml" ) );
}
| public void testWithSpaces()
throws Exception
{
String dir = "foo test";
File spaceDirectory = new File( TestData.getRepoPath(), dir );
if ( spaceDirectory.exists() )
{
FileUtils.deleteDirectory( spaceDirectory );
}
spaceDirectory.mkdirs();
String subDir = "foo bar";
File sub = new File( spaceDirectory, subDir );
if ( sub.exists() )
{
FileUtils.deleteDirectory( sub );
}
sub.mkdirs();
File dummy = new File( "src/test/resources/dummy.txt" );
FileUtils.copyFileToDirectory( dummy, sub );
String url = getTestRepositoryUrl() + "/" + dir;
Repository repo = new Repository( "foo", url );
Wagon wagon = getWagon();
wagon.connect( repo, getAuthInfo() );
List<String> files = wagon.getFileList( subDir );
assertNotNull( files );
assertEquals( 1, files.size() );
assertTrue( files.contains( "dummy.txt" ) );
wagon.put( new File( "src/test/resources/dummy.txt" ), subDir + "/newdummy.txt" );
files = wagon.getFileList( subDir );
assertNotNull( files );
assertEquals( 2, files.size() );
assertTrue( files.contains( "dummy.txt" ) );
assertTrue( files.contains( "newdummy.txt" ) );
File sourceWithSpace = new File( "target/directory with spaces" );
if ( sourceWithSpace.exists() )
{
FileUtils.deleteDirectory( sourceWithSpace );
}
File resources = new File( "src/test/resources" );
FileUtils.copyDirectory( resources, sourceWithSpace );
wagon.putDirectory( sourceWithSpace, "target with spaces" );
files = wagon.getFileList( "target with spaces" );
assertNotNull( files );
assertTrue( files.contains( "dummy.txt" ) );
assertFalse( files.contains( "newdummy.txt" ) );
assertTrue( files.contains( "log4j.xml" ) );
}
|
diff --git a/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java b/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java
index 907cfcaa..b9397621 100755
--- a/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java
+++ b/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java
@@ -1,5782 +1,5783 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cismap.commons.gui;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
import edu.umd.cs.piccolo.*;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.event.PInputEventListener;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.util.PPaintContext;
import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.DataConversionException;
import org.jdom.Element;
import pswing.PSwingCanvas;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import javax.swing.*;
import javax.swing.Timer;
import de.cismet.cismap.commons.*;
import de.cismet.cismap.commons.features.*;
import de.cismet.cismap.commons.featureservice.DocumentFeatureService;
import de.cismet.cismap.commons.featureservice.WebFeatureService;
import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel;
import de.cismet.cismap.commons.gui.piccolo.*;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.*;
import de.cismet.cismap.commons.gui.printing.PrintingSettingsWidget;
import de.cismet.cismap.commons.gui.printing.PrintingWidget;
import de.cismet.cismap.commons.gui.printing.Scale;
import de.cismet.cismap.commons.gui.progresswidgets.DocumentProgressWidget;
import de.cismet.cismap.commons.gui.simplelayerwidget.LayerControl;
import de.cismet.cismap.commons.gui.simplelayerwidget.NewSimpleInternalLayerWidget;
import de.cismet.cismap.commons.interaction.CismapBroker;
import de.cismet.cismap.commons.interaction.CrsChangeListener;
import de.cismet.cismap.commons.interaction.events.CrsChangedEvent;
import de.cismet.cismap.commons.interaction.events.MapDnDEvent;
import de.cismet.cismap.commons.interaction.events.StatusEvent;
import de.cismet.cismap.commons.interaction.memento.Memento;
import de.cismet.cismap.commons.interaction.memento.MementoInterface;
import de.cismet.cismap.commons.preferences.CismapPreferences;
import de.cismet.cismap.commons.preferences.GlobalPreferences;
import de.cismet.cismap.commons.preferences.LayersPreferences;
import de.cismet.cismap.commons.rasterservice.FeatureAwareRasterService;
import de.cismet.cismap.commons.rasterservice.MapService;
import de.cismet.cismap.commons.rasterservice.RasterMapService;
import de.cismet.cismap.commons.retrieval.AbstractRetrievalService;
import de.cismet.cismap.commons.retrieval.RetrievalEvent;
import de.cismet.cismap.commons.retrieval.RetrievalListener;
import de.cismet.tools.CismetThreadPool;
import de.cismet.tools.CurrentStackTrace;
import de.cismet.tools.StaticDebuggingTools;
import de.cismet.tools.configuration.Configurable;
import de.cismet.tools.gui.historybutton.DefaultHistoryModel;
import de.cismet.tools.gui.historybutton.HistoryModel;
/**
* DOCUMENT ME!
*
* @author [email protected]
* @version $Revision$, $Date$
*/
public final class MappingComponent extends PSwingCanvas implements MappingModelListener,
FeatureCollectionListener,
HistoryModel,
Configurable,
DropTargetListener,
CrsChangeListener {
//~ Static fields/initializers ---------------------------------------------
/** Wenn false, werden alle debug statements vom compiler wegoptimiert. */
private static final boolean DEBUG = Debug.DEBUG;
public static final String PROPERTY_MAP_INTERACTION_MODE = "INTERACTION_MODE"; // NOI18N
public static final String MOTION = "MOTION"; // NOI18N
public static final String SELECT = "SELECT"; // NOI18N
public static final String ZOOM = "ZOOM"; // NOI18N
public static final String PAN = "PAN"; // NOI18N
public static final String ALKIS_PRINT = "ALKIS_PRINT"; // NOI18N
public static final String FEATURE_INFO = "FEATURE_INFO"; // NOI18N
public static final String CREATE_SEARCH_POLYGON = "SEARCH_POLYGON"; // NOI18N
public static final String CREATE_SIMPLE_GEOMETRY = "CREATE_SIMPLE_GEOMETRY"; // NOI18N
public static final String MOVE_POLYGON = "MOVE_POLYGON"; // NOI18N
public static final String REMOVE_POLYGON = "REMOVE_POLYGON"; // NOI18N
public static final String NEW_POLYGON = "NEW_POLYGON"; // NOI18N
public static final String SPLIT_POLYGON = "SPLIT_POLYGON"; // NOI18N
public static final String JOIN_POLYGONS = "JOIN_POLYGONS"; // NOI18N
public static final String RAISE_POLYGON = "RAISE_POLYGON"; // NOI18N
public static final String ROTATE_POLYGON = "ROTATE_POLYGON"; // NOI18N
public static final String ATTACH_POLYGON_TO_ALPHADATA = "ATTACH_POLYGON_TO_ALPHADATA"; // NOI18N
public static final String MOVE_HANDLE = "MOVE_HANDLE"; // NOI18N
public static final String REMOVE_HANDLE = "REMOVE_HANDLE"; // NOI18N
public static final String ADD_HANDLE = "ADD_HANDLE"; // NOI18N
public static final String MEASUREMENT = "MEASUREMENT"; // NOI18N
public static final String LINEAR_REFERENCING = "LINEMEASUREMENT"; // NOI18N
public static final String PRINTING_AREA_SELECTION = "PRINTING_AREA_SELECTION"; // NOI18N
public static final String CUSTOM_FEATUREACTION = "CUSTOM_FEATUREACTION"; // NOI18N
public static final String CUSTOM_FEATUREINFO = "CUSTOM_FEATUREINFO"; // NOI18N
public static final String OVERVIEW = "OVERVIEW"; // NOI18N
private static MappingComponent THIS;
/** Name of the internal Simple Layer Widget. */
public static final String LAYERWIDGET = "SimpleInternalLayerWidget"; // NOI18N
/** Name of the internal Document Progress Widget. */
public static final String PROGRESSWIDGET = "DocumentProgressWidget"; // NOI18N
/** Internat Widget at position north west. */
public static final int POSITION_NORTHWEST = 1;
/** Internat Widget at position south west. */
public static final int POSITION_SOUTHWEST = 2;
/** Internat Widget at position north east. */
public static final int POSITION_NORTHEAST = 4;
/** Internat Widget at position south east. */
public static final int POSITION_SOUTHEAST = 8;
/** Delay after a compoent resize event triggers a service reload request. */
private static final int RESIZE_DELAY = 500;
/** If a document exceeds the criticalDocumentSize, the document progress widget is displayed. */
private static final long criticalDocumentSize = 10000000; // 10MB
private static final transient Logger LOG = Logger.getLogger(MappingComponent.class);
//~ Instance fields --------------------------------------------------------
private boolean featureServiceLayerVisible = true;
private final List<LayerControl> layerControls = new ArrayList<LayerControl>();
private boolean gridEnabled = true;
private MappingModel mappingModel;
private ConcurrentHashMap<Feature, PFeature> pFeatureHM = new ConcurrentHashMap<Feature, PFeature>();
private WorldToScreenTransform wtst = null;
private double clip_offset_x;
private double clip_offset_y;
private double printingResolution = 0d;
private boolean backgroundEnabled = true;
private PLayer featureLayer = new PLayer();
private PLayer tmpFeatureLayer = new PLayer();
private PLayer mapServicelayer = new PLayer();
private PLayer featureServiceLayer = new PLayer();
private PLayer handleLayer = new PLayer();
private PLayer snapHandleLayer = new PLayer();
private PLayer rubberBandLayer = new PLayer();
private PLayer highlightingLayer = new PLayer();
private PLayer crosshairLayer = new PLayer();
private PLayer stickyLayer = new PLayer();
private PLayer printingFrameLayer = new PLayer();
private PLayer dragPerformanceImproverLayer = new PLayer();
private boolean readOnly = true;
private boolean snappingEnabled = true;
private boolean visualizeSnappingEnabled = true;
private boolean visualizeSnappingRectEnabled = false;
private int snappingRectSize = 20;
private final Map<String, Cursor> cursors = new HashMap<String, Cursor>();
private final Map<String, PBasicInputEventHandler> inputEventListener =
new HashMap<String, PBasicInputEventHandler>();
private final Action zoomAction;
private int acceptableActions = DnDConstants.ACTION_COPY_OR_MOVE;
private FeatureCollection featureCollection;
private boolean infoNodesVisible = false;
private boolean fixedMapExtent = false;
private boolean fixedMapScale = false;
private boolean inGlueIdenticalPointsMode = true;
/** Holds value of property interactionMode. */
private String interactionMode;
/** Holds value of property handleInteractionMode. */
private String handleInteractionMode;
// "Phantom PCanvas" der nie selbst dargestellt wird
// wird nur dazu benutzt das Graphics Objekt up to date
// zu halten und dann als Hintergrund von z.B. einem
// Panel zu fungieren
// coooooooool, was ? ;-)
private final PCanvas selectedObjectPresenter = new PCanvas();
private BoundingBox currentBoundingBox = null;
private Rectangle2D newViewBounds;
private int animationDuration = 500;
private int taskCounter = 0;
private CismapPreferences cismapPrefs;
private DefaultHistoryModel historyModel = new DefaultHistoryModel();
// Scales
private final List<Scale> scales = new ArrayList<Scale>();
// Printing
private PrintingSettingsWidget printingSettingsDialog;
private PrintingWidget printingDialog;
// Scalebar
private double screenResolution = 100.0;
private volatile boolean locked = true;
private final List<PNode> stickyPNodes = new ArrayList<PNode>();
// Undo- & Redo-Stacks
private final MementoInterface memUndo = new Memento();
private final MementoInterface memRedo = new Memento();
private boolean featureDebugging = false;
private BoundingBox fixedBoundingBox = null;
// Object handleFeatureServiceBlocker = new Object();
private final List<MapListener> mapListeners = new ArrayList<MapListener>();
/** Contains the internal widgets. */
private final Map<String, JInternalFrame> internalWidgets = new HashMap<String, JInternalFrame>();
/** Contains the positions of the internal widgets. */
private final Map<String, Integer> internalWidgetPositions = new HashMap<String, Integer>();
/** The timer that delays the reload requests. */
private Timer delayedResizeEventTimer = null;
private DocumentProgressListener documentProgressListener = null;
private List<Crs> crsList = new ArrayList<Crs>();
private CrsTransformer transformer;
private boolean resetCrs = false;
private final Timer showHandleDelay;
private final Map<MapService, Future<?>> serviceFuturesMap = new HashMap<MapService, Future<?>>();
/** Utility field used by bound properties. */
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
private ButtonGroup interactionButtonGroup;
private boolean mainMappingComponent = false;
/**
* Creates new PFeatures for all features in the given array and adds them to the PFeatureHashmap. Then adds the
* PFeature to the featurelayer.
*
* <p>DANGER: there's a bug risk here because the method runs in an own thread! It is possible that a PFeature of a
* feature is demanded but not yet added to the hashmap which causes in most cases a NullPointerException!</p>
*
* @param features array with features to add
*/
private final HashMap<String, PLayer> featureGrpLayerMap = new HashMap<String, PLayer>();
//~ Constructors -----------------------------------------------------------
/**
* Creates a new instance of MappingComponent.
*/
public MappingComponent() {
this(false);
}
/**
* Creates a new MappingComponent object.
*
* @param mainMappingComponent DOCUMENT ME!
*/
public MappingComponent(final boolean mainMappingComponent) {
super();
this.mainMappingComponent = mainMappingComponent;
locked = true;
THIS = this;
// wird in der Regel wieder ueberschrieben
setSnappingRectSize(20);
setSnappingEnabled(false);
setVisualizeSnappingEnabled(false);
setAnimationDuration(500);
setInteractionMode(ZOOM);
showHandleDelay = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
showHandles(false);
}
});
showHandleDelay.setRepeats(false);
featureDebugging = StaticDebuggingTools.checkHomeForFile("cismetTurnOnFeatureDebugging"); // NOI18N
setFeatureCollection(new DefaultFeatureCollection());
addMapListener((DefaultFeatureCollection)getFeatureCollection());
final DropTarget dt = new DropTarget(this, acceptableActions, this);
setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING);
setAnimatingRenderQuality(PPaintContext.LOW_QUALITY_RENDERING);
removeInputEventListener(getPanEventHandler());
removeInputEventListener(getZoomEventHandler());
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent evt) {
if (MappingComponent.this.delayedResizeEventTimer == null) {
delayedResizeEventTimer = new Timer(RESIZE_DELAY, new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
delayedResizeEventTimer.stop();
delayedResizeEventTimer = null;
// perform delayed resize:
// rescape map + move widgets + reload services
componentResizedDelayed();
}
});
delayedResizeEventTimer.start();
} else {
// perform intermediate resize:
// rescape map + move widgets
componentResizedIntermediate();
delayedResizeEventTimer.restart();
}
}
});
final PRoot root = getRoot();
final PCamera otherCamera = new PCamera();
otherCamera.addLayer(featureLayer);
selectedObjectPresenter.setCamera(otherCamera);
root.addChild(otherCamera);
getLayer().addChild(mapServicelayer);
getLayer().addChild(featureServiceLayer);
getLayer().addChild(featureLayer);
getLayer().addChild(tmpFeatureLayer);
getLayer().addChild(rubberBandLayer);
getLayer().addChild(highlightingLayer);
getLayer().addChild(crosshairLayer);
getLayer().addChild(dragPerformanceImproverLayer);
getLayer().addChild(printingFrameLayer);
getCamera().addLayer(mapServicelayer);
getCamera().addLayer(featureLayer);
getCamera().addLayer(tmpFeatureLayer);
getCamera().addLayer(rubberBandLayer);
getCamera().addLayer(highlightingLayer);
getCamera().addLayer(crosshairLayer);
getCamera().addLayer(dragPerformanceImproverLayer);
getCamera().addLayer(printingFrameLayer);
getCamera().addChild(snapHandleLayer);
getCamera().addChild(handleLayer);
getCamera().addChild(stickyLayer);
handleLayer.moveToFront();
otherCamera.setTransparency(0.05f);
initInputListener();
initCursors();
addInputEventListener(getInputListener(MOTION));
addInputEventListener(getInputListener(CUSTOM_FEATUREACTION));
final KeyboardListener k = new KeyboardListener(this);
addInputEventListener(k);
getRoot().getDefaultInputManager().setKeyboardFocus(k);
setInteractionMode(ZOOM);
setHandleInteractionMode(MOVE_HANDLE);
dragPerformanceImproverLayer.setVisible(false);
historyModel.setMaximumPossibilities(30);
zoomAction = new AbstractAction() {
{
putValue(
Action.NAME,
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.zoomAction.NAME")); // NOI18N
putValue(
Action.SMALL_ICON,
new ImageIcon(getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/layers.png"))); // NOI18N
putValue(
Action.SHORT_DESCRIPTION,
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.zoomAction.SHORT_DESCRIPTION")); // NOI18N
putValue(
Action.LONG_DESCRIPTION,
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.zoomAction.LONG_DESCRIPTION")); // NOI18N
putValue(Action.MNEMONIC_KEY, Integer.valueOf('Z')); // NOI18N
putValue(Action.ACTION_COMMAND_KEY, "zoom.action"); // NOI18N
}
@Override
public void actionPerformed(final ActionEvent event) {
zoomAction.putValue(
Action.SMALL_ICON,
new ImageIcon(getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N
setInteractionMode(MappingComponent.ZOOM);
}
};
this.getCamera().addPropertyChangeListener(PCamera.PROPERTY_VIEW_TRANSFORM, new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
checkAndFixErroneousTransformation();
handleLayer.removeAllChildren();
showHandleDelay.restart();
rescaleStickyNodes();
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.SCALE, interactionMode));
}
});
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ButtonGroup getInteractionButtonGroup() {
return interactionButtonGroup;
}
/**
* DOCUMENT ME!
*
* @param interactionButtonGroup DOCUMENT ME!
*/
public void setInteractionButtonGroup(final ButtonGroup interactionButtonGroup) {
this.interactionButtonGroup = interactionButtonGroup;
}
/**
* DOCUMENT ME!
*
* @param mapListener DOCUMENT ME!
*/
public void addMapListener(final MapListener mapListener) {
if (mapListener != null) {
mapListeners.add(mapListener);
}
}
/**
* DOCUMENT ME!
*
* @param mapListener DOCUMENT ME!
*/
public void removeMapListener(final MapListener mapListener) {
if (mapListener != null) {
mapListeners.remove(mapListener);
}
}
/**
* DOCUMENT ME!
*/
public void dispose() {
CismapBroker.getInstance().removeCrsChangeListener(this);
getFeatureCollection().removeAllFeatures();
}
/**
* DOCUMENT ME!
*
* @return true, if debug-messages are logged.
*/
public boolean isFeatureDebugging() {
return featureDebugging;
}
/**
* Creates printingDialog and printingSettingsDialog.
*/
public void initPrintingDialogs() {
printingSettingsDialog = new PrintingSettingsWidget(true, this);
printingDialog = new PrintingWidget(true, this);
}
/**
* Returns the momentary image of the PCamera of this MappingComponent.
*
* @return Image
*/
public Image getImage() {
// this.getCamera().print();
return this.getCamera().toImage(this.getWidth(), this.getHeight(), Color.white);
}
/**
* Creates an image with given width and height from all features in the given featurecollection. The image will be
* used for printing.
*
* @param fc FeatureCollection
* @param width desired width of the resulting image
* @param height desired height of the resulting image
*
* @return Image of the featurecollection
*/
public Image getImageOfFeatures(final Collection<Feature> fc, final int width, final int height) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getImageOffFeatures (" + width + "x" + height + ")"); // NOI18N
}
}
final PrintingFrameListener pfl = ((PrintingFrameListener)getInputListener(PRINTING_AREA_SELECTION));
final PCanvas pc = new PCanvas();
pc.setSize(width, height);
final List<PFeature> list = new ArrayList<PFeature>();
final Iterator it = fc.iterator();
while (it.hasNext()) {
final Feature f = (Feature)it.next();
final PFeature p = new PFeature(f, wtst, clip_offset_x, clip_offset_y, MappingComponent.this);
if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) {
list.add(p);
}
}
pc.getCamera().animateViewToCenterBounds(pfl.getPrintingRectangle().getBounds(), true, 0);
final double scale = 1 / pc.getCamera().getViewScale();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("subPCscale:" + scale); // NOI18N
}
}
// TODO Sorge dafür dass die PSwingKomponente richtig gedruckt wird und dass die Karte nicht mehr "zittert"
int printingLineWidth = -1;
for (final PNode p : list) {
if (p instanceof PFeature) {
final PFeature original = ((PFeature)p);
original.setInfoNodeExpanded(false);
if (printingLineWidth > 0) {
((StyledFeature)original.getFeature()).setLineWidth(printingLineWidth);
} else if (StyledFeature.class.isAssignableFrom(original.getFeature().getClass())) {
final int orginalLineWidth = ((StyledFeature)original.getFeature()).getLineWidth();
printingLineWidth = (int)Math.round(orginalLineWidth * (getPrintingResolution() * 2));
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getImageOfFeatures: changed printingLineWidth from " + orginalLineWidth
+ " to " + printingLineWidth + " (resolution=" + getPrintingResolution()
+ ")"); // NOI18N
}
}
((StyledFeature)original.getFeature()).setLineWidth(printingLineWidth);
}
final PFeature copy = new PFeature(original.getFeature(),
getWtst(),
0,
0,
MappingComponent.this,
true);
pc.getLayer().addChild(copy);
copy.setTransparency(original.getTransparency());
copy.setStrokePaint(original.getStrokePaint());
final boolean expanded = original.isInfoNodeExpanded();
copy.addInfoNode();
copy.setInfoNodeExpanded(false);
copy.refreshInfoNode();
original.refreshInfoNode();
removeStickyNode(copy.getStickyChild());
final PNode stickyChild = copy.getStickyChild();
if (stickyChild != null) {
stickyChild.setScale(scale * getPrintingResolution());
if (copy.hasSecondStickyChild()) {
copy.getSecondStickyChild().setScale(scale * getPrintingResolution());
}
}
}
}
final Image ret = pc.getCamera().toImage(width, height, new Color(255, 255, 255, 0));
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug(ret);
}
}
return ret;
} catch (final Exception exception) {
LOG.error("Error during the creation of an image from features", exception); // NOI18N
return null;
}
}
/**
* Creates an image with given width and height from all features that intersects the printingframe.
*
* @param width desired width of the resulting image
* @param height desired height of the resulting image
*
* @return Image of intersecting features
*/
public Image getFeatureImage(final int width, final int height) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getFeatureImage " + width + "x" + height); // NOI18N
}
}
final PrintingFrameListener pfl = ((PrintingFrameListener)getInputListener(PRINTING_AREA_SELECTION));
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("printing rectangle bounds: " + pfl.getPrintingRectangle().getBounds()); // NOI18N
}
}
final PCanvas pc = new PCanvas();
pc.setSize(width, height);
final List<PNode> list = new ArrayList<PNode>();
final Iterator it = featureLayer.getChildrenIterator();
while (it.hasNext()) {
final PNode p = (PNode)it.next();
if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) {
list.add(p);
}
}
/* Prüfe alle Features der Gruppen Layer (welche auch Kinder des Feature-Layers sind)
* und füge sie der Liste für alle zum malen anstehenden Features hinzu, wenn - der Gruppen-Layer sichtbar ist
* und - das Feature im Druckbereich liegt
*/
final Collection<PLayer> groupLayers = this.featureGrpLayerMap.values();
List<PNode> grpMembers;
for (final PLayer layer : groupLayers) {
if (layer.getVisible()) {
grpMembers = layer.getChildrenReference();
for (final PNode p : grpMembers) {
if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) {
list.add(p);
}
}
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("intersecting feature count: " + list.size()); // NOI18N
}
}
pc.getCamera().animateViewToCenterBounds(pfl.getPrintingRectangle().getBounds(), true, 0);
final double scale = 1 / pc.getCamera().getViewScale();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("subPCscale:" + scale); // NOI18N
}
}
// TODO Sorge dafür dass die PSwingKomponente richtig gedruckt wird und dass die Karte nicht mehr "zittert"
for (final PNode p : list) {
if (p instanceof PFeature) {
final PFeature original = ((PFeature)p);
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
original.setInfoNodeExpanded(false);
final PFeature copy = new PFeature(
original.getFeature(),
getWtst(),
0,
0,
MappingComponent.this,
true);
pc.getLayer().addChild(copy);
copy.setTransparency(original.getTransparency());
copy.setStrokePaint(original.getStrokePaint());
copy.addInfoNode();
copy.setInfoNodeExpanded(false);
// Wenn mal irgendwas wegen Querformat kommt :
if (copy.getStickyChild() != null) {
copy.getStickyChild().setScale(scale * getPrintingResolution());
}
} catch (final Exception t) {
LOG.error("Fehler beim erstellen des Featureabbildes", t); // NOI18N
}
}
});
} catch (final Exception t) {
LOG.error("Fehler beim erstellen des Featureabbildes", t); // NOI18N
return null;
}
}
}
return pc.getCamera().toImage(width, height, new Color(255, 255, 255, 0));
}
/**
* Adds the given PCamera to the PRoot of this MappingComponent.
*
* @param cam PCamera-object
*/
public void addToPRoot(final PCamera cam) {
getRoot().addChild(cam);
}
/**
* Adds a PNode to the StickyNode-vector.
*
* @param pn PNode-object
*/
public void addStickyNode(final PNode pn) {
// if(DEBUG)log.debug("addStickyNode:" + pn);
stickyPNodes.add(pn);
}
/**
* Removes a specific PNode from the StickyNode-vector.
*
* @param pn PNode that should be removed
*/
public void removeStickyNode(final PNode pn) {
stickyPNodes.remove(pn);
}
/**
* DOCUMENT ME!
*
* @return Vector<PNode> with all sticky PNodes
*/
public List<PNode> getStickyNodes() {
return stickyPNodes;
}
/**
* Calls private method rescaleStickyNodeWork(node) to rescale the sticky PNode. Forces the execution to the EDT.
*
* @param n PNode to rescale
*/
public void rescaleStickyNode(final PNode n) {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
rescaleStickyNodeWork(n);
}
});
} else {
rescaleStickyNodeWork(n);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private double getPrintingResolution() {
return this.printingResolution;
}
/**
* DOCUMENT ME!
*
* @param printingResolution DOCUMENT ME!
*/
public void setPrintingResolution(final double printingResolution) {
this.printingResolution = printingResolution;
}
/**
* Sets the scale of the given PNode to the value of the camera scale.
*
* @param n PNode to rescale
*/
private void rescaleStickyNodeWork(final PNode n) {
final double s = MappingComponent.this.getCamera().getViewScale();
n.setScale(1 / s);
}
/**
* Rescales all nodes inside the StickyNode-vector.
*/
public void rescaleStickyNodes() {
final List<PNode> stickyNodeCopy = new ArrayList<PNode>(getStickyNodes());
for (final PNode each : stickyNodeCopy) {
if ((each instanceof PSticky) && each.getVisible()) {
rescaleStickyNode(each);
} else {
if ((each instanceof PSticky) && (each.getParent() == null)) {
removeStickyNode(each);
}
}
}
}
/**
* Returns the custom created Action zoomAction.
*
* @return Action-object
*/
public Action getZoomAction() {
return zoomAction;
}
/**
* Pans to the given bounds without creating a historyaction to undo the action.
*
* @param bounds new bounds of the camera
*/
public void gotoBoundsWithoutHistory(PBounds bounds) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("gotoBoundsWithoutHistory(PBounds: " + bounds, new CurrentStackTrace()); // NOI18N
}
}
try {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("error during removeAllCHildren", e); // NOI18N
}
if (bounds.getWidth() < 0) {
bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight());
}
if (bounds.getHeight() < 0) {
bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1));
}
if (bounds instanceof PBoundsWithCleverToString) {
final PBoundsWithCleverToString boundWCTS = (PBoundsWithCleverToString)bounds;
if (!boundWCTS.getCrsCode().equals(mappingModel.getSrs().getCode())) {
try {
final Rectangle2D pos = new Rectangle2D.Double();
XBoundingBox bbox = boundWCTS.getWorldCoordinates();
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
bbox = trans.transformBoundingBox(bbox);
bounds = bbox.getPBounds(getWtst());
} catch (final Exception e) {
LOG.error("Cannot transform the bounding box from " + boundWCTS.getCrsCode() + " to "
+ mappingModel.getSrs().getCode());
}
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("before animateView"); // NOI18N
}
}
getCamera().animateViewToCenterBounds((bounds), true, animationDuration);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("after animateView"); // NOI18N
}
}
queryServicesWithoutHistory();
showHandles(true);
} catch (NullPointerException npe) {
LOG.warn("NPE in gotoBoundsWithoutHistory(" + bounds + ")", npe); // NOI18N
}
}
/**
* Checks out the y-camerascales for negative value and fixes it by negating both x- and y-scales.
*/
private void checkAndFixErroneousTransformation() {
if (getCamera().getViewTransform().getScaleY() < 0) {
final double y = getCamera().getViewTransform().getScaleY();
final double x = getCamera().getViewTransform().getScaleX();
LOG.warn("Erroneous ViewTransform: getViewTransform (scaleY=" + y + " scaleX=" + x + "). Try to fix it."); // NOI18N
getCamera().getViewTransformReference()
.setToScale(getCamera().getViewTransform().getScaleX() * (-1), y * (-1));
}
}
/**
* Re-adds the default layers in a given order.
*/
private void adjustLayers() {
int counter = 0;
getCamera().addLayer(counter++, mapServicelayer);
for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) {
getCamera().addLayer(counter++, (PLayer)featureServiceLayer.getChild(i));
}
getCamera().addLayer(counter++, featureLayer);
getCamera().addLayer(counter++, tmpFeatureLayer);
getCamera().addLayer(counter++, rubberBandLayer);
getCamera().addLayer(counter++, dragPerformanceImproverLayer);
getCamera().addLayer(counter++, printingFrameLayer);
}
/**
* Assigns the listeners to the according interactionmodes.
*/
public void initInputListener() {
inputEventListener.put(MOTION, new SimpleMoveListener(this));
inputEventListener.put(CUSTOM_FEATUREACTION, new CustomFeatureActionListener(this));
inputEventListener.put(ZOOM, new RubberBandZoomListener());
inputEventListener.put(PAN, new PanAndMousewheelZoomListener());
inputEventListener.put(SELECT, new SelectionListener());
inputEventListener.put(FEATURE_INFO, new GetFeatureInfoClickDetectionListener());
inputEventListener.put(CREATE_SEARCH_POLYGON, new MetaSearchCreateSearchGeometryListener(this));
inputEventListener.put(CREATE_SIMPLE_GEOMETRY, new CreateSimpleGeometryListener(this));
inputEventListener.put(MOVE_POLYGON, new FeatureMoveListener(this));
inputEventListener.put(NEW_POLYGON, new CreateNewGeometryListener(this));
inputEventListener.put(RAISE_POLYGON, new RaisePolygonListener(this));
inputEventListener.put(REMOVE_POLYGON, new DeleteFeatureListener());
inputEventListener.put(ATTACH_POLYGON_TO_ALPHADATA, new AttachFeatureListener());
inputEventListener.put(JOIN_POLYGONS, new JoinPolygonsListener());
inputEventListener.put(SPLIT_POLYGON, new SplitPolygonListener(this));
inputEventListener.put(LINEAR_REFERENCING, new CreateLinearReferencedMarksListener(this));
inputEventListener.put(MEASUREMENT, new MeasurementListener(this));
inputEventListener.put(PRINTING_AREA_SELECTION, new PrintingFrameListener(this));
inputEventListener.put(CUSTOM_FEATUREINFO, new CustomFeatureInfoListener());
inputEventListener.put(OVERVIEW, new OverviewModeListener());
}
/**
* Assigns a custom interactionmode with an own PBasicInputEventHandler.
*
* @param key interactionmode as String
* @param listener new PBasicInputEventHandler
*/
public void addCustomInputListener(final String key, final PBasicInputEventHandler listener) {
inputEventListener.put(key, listener);
}
/**
* Assigns the cursors to the according interactionmodes.
*/
public void initCursors() {
putCursor(SELECT, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(ZOOM, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(PAN, new Cursor(Cursor.HAND_CURSOR));
putCursor(FEATURE_INFO, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(CREATE_SEARCH_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(MOVE_POLYGON, new Cursor(Cursor.HAND_CURSOR));
putCursor(ROTATE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(NEW_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(RAISE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(REMOVE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(ATTACH_POLYGON_TO_ALPHADATA, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(JOIN_POLYGONS, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(SPLIT_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(MEASUREMENT, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(LINEAR_REFERENCING, new Cursor(Cursor.DEFAULT_CURSOR));
putCursor(CREATE_SIMPLE_GEOMETRY, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(MOVE_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(REMOVE_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR));
putCursor(ADD_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR));
}
/**
* Shows the printingsetting-dialog that resets the interactionmode after printing.
*
* @param oldInteractionMode String-object
*/
public void showPrintingSettingsDialog(final String oldInteractionMode) {
if (!(printingSettingsDialog.getParent() instanceof JFrame)) {
printingSettingsDialog = printingSettingsDialog.cloneWithNewParent(true, this);
}
printingSettingsDialog.setInteractionModeAfterPrinting(oldInteractionMode);
printingSettingsDialog.setLocationRelativeTo(this);
printingSettingsDialog.setVisible(true);
}
/**
* Shows the printing-dialog that resets the interactionmode after printing.
*
* @param oldInteractionMode String-object
*/
public void showPrintingDialog(final String oldInteractionMode) {
setPointerAnnotationVisibility(false);
if (!(printingDialog.getParent() instanceof JFrame)) {
printingDialog = printingDialog.cloneWithNewParent(true, this);
}
try {
printingDialog.setInteractionModeAfterPrinting(oldInteractionMode);
printingDialog.startLoading();
printingDialog.setLocationRelativeTo(this);
printingDialog.setVisible(true);
} catch (final Exception e) {
LOG.error("Fehler beim Anzeigen des Printing Dialogs", e); // NOI18N
}
}
/**
* Getter for property interactionMode.
*
* @return Value of property interactionMode.
*/
public String getInteractionMode() {
return this.interactionMode;
}
/**
* Changes the interactionmode.
*
* @param interactionMode new interactionmode as String
*/
public void setInteractionMode(final String interactionMode) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:"
+ this.interactionMode + "",
new Exception()); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
setPointerAnnotationVisibility(false);
if (getPrintingFrameLayer().getChildrenCount() > 1) {
getPrintingFrameLayer().removeAllChildren();
}
if (this.interactionMode != null) {
if (interactionMode.equals(FEATURE_INFO)) {
((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo()
.setVisible(true);
} else {
((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo()
.setVisible(false);
}
if (isReadOnly()) {
((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class);
}
final PInputEventListener pivl = this.getInputListener(this.interactionMode);
if (pivl != null) {
removeInputEventListener(pivl);
} else {
LOG.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N
}
if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) {
featureCollection.unselectAll();
}
if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEAR_REFERENCING)
|| interactionMode.equals(SPLIT_POLYGON))
&& (this.readOnly == false)) {
featureSelectionChanged(null);
}
if (interactionMode.equals(JOIN_POLYGONS)) {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
}
final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent(
this,
PROPERTY_MAP_INTERACTION_MODE,
this.interactionMode,
interactionMode);
this.interactionMode = interactionMode;
final PInputEventListener pivl = getInputListener(interactionMode);
if (pivl != null) {
addInputEventListener(pivl);
propertyChangeSupport.firePropertyChange(interactionModeChangedEvent);
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode));
} else {
LOG.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N
}
} catch (final Exception e) {
LOG.error("Fehler beim Ändern des InteractionModes", e); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
@Deprecated
public void formComponentResized(final ComponentEvent evt) {
this.componentResizedDelayed();
}
/**
* Resizes the map and does not reload all services.
*
* @see #componentResizedDelayed()
*/
public void componentResizedIntermediate() {
if (!this.isLocked()) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N
}
}
if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) {
if (mappingModel != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N
}
}
if (MappingComponent.this.currentBoundingBox == null) {
LOG.error("currentBoundingBox is null"); // NOI18N
currentBoundingBox = getCurrentBoundingBox();
}
// rescale map
if (historyModel.getCurrentElement() != null) {
final PBounds bounds = (PBounds)historyModel.getCurrentElement();
if (bounds.getWidth() < 0) {
bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight());
}
if (bounds.getHeight() < 0) {
bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1));
}
getCamera().animateViewToCenterBounds(bounds, true, animationDuration);
}
}
}
// move internal widgets
for (final String internalWidget : this.internalWidgets.keySet()) {
if (this.getInternalWidget(internalWidget).isVisible()) {
showInternalWidget(internalWidget, true, 0);
}
}
}
}
/**
* Resizes the map and reloads all services.
*
* @see #componentResizedIntermediate()
*/
public void componentResizedDelayed() {
if (!this.isLocked()) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N
}
}
if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) {
if (mappingModel != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N
}
}
if (MappingComponent.this.currentBoundingBox == null) {
LOG.error("currentBoundingBox is null"); // NOI18N
currentBoundingBox = getCurrentBoundingBox();
}
gotoBoundsWithoutHistory((PBounds)historyModel.getCurrentElement());
// move internal widgets
for (final String internalWidget : this.internalWidgets.keySet()) {
if (this.getInternalWidget(internalWidget).isVisible()) {
showInternalWidget(internalWidget, true, 0);
}
}
}
}
} catch (final Exception t) {
LOG.error("Fehler in formComponentResized()", t); // NOI18N
}
}
}
/**
* syncSelectedObjectPresenter(int i).
*
* @param i DOCUMENT ME!
*/
public void syncSelectedObjectPresenter(final int i) {
selectedObjectPresenter.setVisible(true);
if (featureCollection.getSelectedFeatures().size() > 0) {
if (featureCollection.getSelectedFeatures().size() == 1) {
final PFeature selectedFeature = (PFeature)pFeatureHM.get(
featureCollection.getSelectedFeatures().toArray()[0]);
if (selectedFeature != null) {
selectedObjectPresenter.getCamera()
.animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2);
}
} else {
// todo
}
} else {
LOG.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N
}
}
/**
* Returns the current featureCollection.
*
* @return DOCUMENT ME!
*/
public FeatureCollection getFeatureCollection() {
return featureCollection;
}
/**
* Replaces the old featureCollection with a new one.
*
* @param featureCollection the new featureCollection
*/
public void setFeatureCollection(final FeatureCollection featureCollection) {
this.featureCollection = featureCollection;
featureCollection.addFeatureCollectionListener(this);
}
/**
* DOCUMENT ME!
*
* @param visibility DOCUMENT ME!
*/
public void setFeatureCollectionVisibility(final boolean visibility) {
featureLayer.setVisible(visibility);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFeatureCollectionVisible() {
return featureLayer.getVisible();
}
/**
* Adds a new mapservice at a specific place of the layercontrols.
*
* @param mapService the new mapservice
* @param position the index where to position the mapservice
*/
public void addMapService(final MapService mapService, final int position) {
try {
PNode p = new PNode();
if (mapService instanceof RasterMapService) {
LOG.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N
if (mapService.getPNode() instanceof XPImage) {
p = (XPImage)mapService.getPNode();
} else {
p = new XPImage();
mapService.setPNode(p);
}
mapService.addRetrievalListener(new MappingComponentRasterServiceListener(
position,
p,
(ServiceLayer)mapService));
} else {
LOG.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName()
+ ")"); // NOI18N
p = new PLayer();
mapService.setPNode(p);
if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService
+ "): isDocumentFeatureService, checking document size"); // NOI18N
}
}
final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService;
if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) {
LOG.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '"
+ documentFeatureService.getName() + "' size of "
+ (documentFeatureService.getDocumentSize() / 1000000)
+ "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000)
+ "MB)"); // NOI18N
if (this.documentProgressListener == null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService
+ "): lazy instantiation of documentProgressListener"); // NOI18N
}
}
this.documentProgressListener = new DocumentProgressListener();
}
if (this.documentProgressListener.getRequestId() != -1) {
LOG.error("FeatureMapService(" + mapService
+ "): The documentProgressListener is already in use by request '"
+ this.documentProgressListener.getRequestId()
+ ", document progress cannot be tracked"); // NOI18N
} else {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N
}
}
documentFeatureService.addRetrievalListener(this.documentProgressListener);
}
}
}
mapService.addRetrievalListener(new MappingComponentFeatureServiceListener(
(ServiceLayer)mapService,
(PLayer)mapService.getPNode()));
}
p.setTransparency(mapService.getTranslucency());
p.setVisible(mapService.isVisible());
mapServicelayer.addChild(p);
} catch (final Exception e) {
LOG.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + e.getMessage(), e); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param mm DOCUMENT ME!
*/
public void preparationSetMappingModel(final MappingModel mm) {
mappingModel = mm;
}
/**
* Sets a new mappingmodel in this MappingComponent.
*
* @param mm the new mappingmodel
*/
public void setMappingModel(final MappingModel mm) {
LOG.info("setMappingModel"); // NOI18N
// FIXME: why is the default uncaught exception handler set in such a random place?
if (Thread.getDefaultUncaughtExceptionHandler() == null) {
LOG.info("setDefaultUncaughtExceptionHandler"); // NOI18N
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
LOG.error("Error", e);
}
});
}
mappingModel = mm;
currentBoundingBox = mm.getInitialBoundingBox();
final Runnable r = new Runnable() {
@Override
public void run() {
mappingModel.addMappingModelListener(MappingComponent.this);
final TreeMap rs = mappingModel.getRasterServices();
// Rückwärts wegen der Reihenfolge der Layer im Layer Widget
final Iterator it = rs.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if (o instanceof MapService) {
addMapService(((MapService)o), rsi);
}
}
adjustLayers();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Set Mapping Modell done"); // NOI18N
}
}
}
};
CismetThreadPool.execute(r);
}
/**
* Returns the current mappingmodel.
*
* @return current mappingmodel
*/
public MappingModel getMappingModel() {
return mappingModel;
}
/**
* Animates a component to a given x/y-coordinate in a given time.
*
* @param c the component to animate
* @param toX final x-position
* @param toY final y-position
* @param animationDuration duration of the animation
* @param hideAfterAnimation should the component be hidden after animation?
*/
private void animateComponent(final JComponent c,
final int toX,
final int toY,
final int animationDuration,
final boolean hideAfterAnimation) {
if (animationDuration > 0) {
final int x = (int)c.getBounds().getX() - toX;
final int y = (int)c.getBounds().getY() - toY;
int sx;
int sy;
if (x > 0) {
sx = -1;
} else {
sx = 1;
}
if (y > 0) {
sy = -1;
} else {
sy = 1;
}
int big;
if (Math.abs(x) > Math.abs(y)) {
big = Math.abs(x);
} else {
big = Math.abs(y);
}
final int sleepy;
if ((animationDuration / big) < 1) {
sleepy = 1;
} else {
sleepy = animationDuration / big;
}
final int directionY = sy;
final int directionX = sx;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY
+ ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX="
+ toX + ", toY=" + toY); // NOI18N
}
}
final Thread timer = new Thread() {
@Override
public void run() {
while (!isInterrupted()) {
try {
sleep(sleepy);
} catch (final Exception iex) {
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
int currentY = (int)c.getBounds().getY();
int currentX = (int)c.getBounds().getX();
if (currentY != toY) {
currentY = currentY + directionY;
}
if (currentX != toX) {
currentX = currentX + directionX;
}
c.setBounds(currentX, currentY, c.getWidth(), c.getHeight());
}
});
if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) {
if (hideAfterAnimation) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
c.setVisible(false);
c.hide();
}
});
}
break;
}
}
}
};
timer.setPriority(Thread.NORM_PRIORITY);
timer.start();
} else {
c.setBounds(toX, toY, c.getWidth(), c.getHeight());
if (hideAfterAnimation) {
c.setVisible(false);
}
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
@Deprecated
public NewSimpleInternalLayerWidget getInternalLayerWidget() {
return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET);
}
/**
* Adds a new internal widget to the map.<br/>
* If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget
* will be added. If a widget with a different name already exisit at the same {@code position} the new widget will
* not be added and the operation returns {@code false}.
*
* @param name unique name of the widget
* @param position position of the widget
* @param widget the widget
*
* @return {@code true} if the widget could be added, {@code false} otherwise
*
* @see #POSITION_NORTHEAST
* @see #POSITION_NORTHWEST
* @see #POSITION_SOUTHEAST
* @see #POSITION_SOUTHWEST
*/
public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) {
if (LOG.isDebugEnabled()) {
LOG.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N
}
if (this.internalWidgets.containsKey(name)) {
LOG.warn("widget '" + name + "' already added, removing old widget"); // NOI18N
this.remove(this.getInternalWidget(name));
} else if (this.internalWidgetPositions.containsValue(position)) {
LOG.warn("widget position '" + position + "' already taken"); // NOI18N
return false;
}
this.internalWidgets.put(name, widget);
this.internalWidgetPositions.put(name, position);
widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N
this.add(widget);
widget.pack();
return true;
}
/**
* Removes an existing internal widget from the map.
*
* @param name name of the widget to be removed
*
* @return {@code true} id the widget was found and removed, {@code false} otherwise
*/
public boolean removeInternalWidget(final String name) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing internal widget '" + name + "'"); // NOI18N
}
if (!this.internalWidgets.containsKey(name)) {
LOG.warn("widget '" + name + "' not found"); // NOI18N
return false;
}
this.remove(this.getInternalWidget(name));
this.internalWidgets.remove(name);
this.internalWidgetPositions.remove(name);
return true;
}
/**
* Shows an InternalWidget by sliding it into the mappingcomponent.
*
* @param name name of the internl component to show
* @param visible should the widget be visible after the animation?
* @param animationDuration duration of the animation
*
* @return {@code true} if the operation was successful, {@code false} otherwise
*/
public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) {
final JInternalFrame internalWidget = this.getInternalWidget(name);
if (internalWidget == null) {
return false;
}
final int positionX;
final int positionY;
final int widgetPosition = this.getInternalWidgetPosition(name);
final boolean isHigher = (getHeight() < (internalWidget.getHeight() + 2)) && (getHeight() > 0);
final boolean isWider = (getWidth() < (internalWidget.getWidth() + 2)) && (getWidth() > 0);
switch (widgetPosition) {
case POSITION_NORTHWEST: {
positionX = 1;
positionY = 1;
break;
}
case POSITION_SOUTHWEST: {
positionX = 1;
positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1);
break;
}
case POSITION_NORTHEAST: {
positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1);
positionY = 1;
break;
}
case POSITION_SOUTHEAST: {
positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1);
positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1);
break;
}
default: {
LOG.warn("unkown widget position?!"); // NOI18N
return false;
}
}
if (visible) {
final int toY;
if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) {
if (isHigher) {
toY = getHeight() - 1;
} else {
toY = positionY - internalWidget.getHeight() - 1;
}
} else {
if (isHigher) {
toY = getHeight() + 1;
} else {
toY = positionY + internalWidget.getHeight() + 1;
}
}
internalWidget.setBounds(
positionX,
toY,
isWider ? (getWidth() - 2) : internalWidget.getWidth(),
isHigher ? (getHeight() - 2) : internalWidget.getHeight());
internalWidget.setVisible(true);
internalWidget.show();
animateComponent(internalWidget, positionX, positionY, animationDuration, false);
} else {
internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight());
int toY = positionY + internalWidget.getHeight() + 1;
if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) {
toY = positionY - internalWidget.getHeight() - 1;
}
animateComponent(internalWidget, positionX, toY, animationDuration, true);
}
return true;
}
/**
* DOCUMENT ME!
*
* @param visible DOCUMENT ME!
* @param animationDuration DOCUMENT ME!
*/
@Deprecated
public void showInternalLayerWidget(final boolean visible, final int animationDuration) {
this.showInternalWidget(LAYERWIDGET, visible, animationDuration);
}
/**
* Returns a boolean, if the InternalLayerWidget is visible.
*
* @return true, if visible, else false
*/
@Deprecated
public boolean isInternalLayerWidgetVisible() {
return this.getInternalLayerWidget().isVisible();
}
/**
* Returns a boolean, if the InternalWidget is visible.
*
* @param name name of the widget
*
* @return true, if visible, else false
*/
public boolean isInternalWidgetVisible(final String name) {
final JInternalFrame widget = this.getInternalWidget(name);
if (widget != null) {
return widget.isVisible();
}
return false;
}
/**
* Moves the camera to the initial bounding box (e.g. if the home-button is pressed).
*/
public void gotoInitialBoundingBox() {
final double x1;
final double y1;
final double x2;
final double y2;
final double w;
final double h;
x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1());
y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1());
x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2());
y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2());
final Rectangle2D home = new Rectangle2D.Double();
home.setRect(x1, y2, x2 - x1, y1 - y2);
getCamera().animateViewToCenterBounds(home, true, animationDuration);
if (getCamera().getViewTransform().getScaleY() < 0) {
LOG.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N
}
setNewViewBounds(home);
queryServices();
}
/**
* Refreshs all registered services.
*/
public void queryServices() {
if (newViewBounds != null) {
addToHistory(new PBoundsWithCleverToString(
new PBounds(newViewBounds),
wtst,
mappingModel.getSrs().getCode()));
queryServicesWithoutHistory();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServices()"); // NOI18N
}
}
rescaleStickyNodes();
}
}
/**
* Forces all services to refresh themselves.
*/
public void refresh() {
forceQueryServicesWithoutHistory();
}
/**
* Forces all services to refresh themselves.
*/
private void forceQueryServicesWithoutHistory() {
queryServicesWithoutHistory(true);
}
/**
* Refreshs all services, but not forced.
*/
private void queryServicesWithoutHistory() {
queryServicesWithoutHistory(false);
}
/**
* Waits until all animations are done, then iterates through all registered services and calls handleMapService()
* for each.
*
* @param forced forces the refresh
*/
private void queryServicesWithoutHistory(final boolean forced) {
if (forced && mainMappingComponent) {
CismapBroker.getInstance().fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_RESET, this));
}
if (!locked) {
final Runnable r = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception doNothing) {
}
}
CismapBroker.getInstance().fireMapBoundsChanged();
if (MappingComponent.this.isBackgroundEnabled()) {
final TreeMap rs = mappingModel.getRasterServices();
final TreeMap fs = mappingModel.getFeatureServices();
for (final Iterator it = rs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if (o instanceof MapService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N
}
}
handleMapService(rsi, (MapService)o, forced);
} else {
LOG.warn("service is not of type MapService:" + o); // NOI18N
}
}
for (final Iterator it = fs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int fsi = ((Integer)key).intValue();
final Object o = fs.get(key);
if (o instanceof MapService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N
}
}
handleMapService(fsi, (MapService)o, forced);
} else {
LOG.warn("service is not of type MapService:" + o); // NOI18N
}
}
}
}
};
CismetThreadPool.execute(r);
}
}
/**
* queryServicesIndependentFromMap.
*
* @param width DOCUMENT ME!
* @param height DOCUMENT ME!
* @param bb DOCUMENT ME!
* @param rl DOCUMENT ME!
*/
public void queryServicesIndependentFromMap(final int width,
final int height,
final BoundingBox bb,
final RetrievalListener rl) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N
}
}
final Runnable r = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception doNothing) {
}
}
if (MappingComponent.this.isBackgroundEnabled()) {
final TreeMap rs = mappingModel.getRasterServices();
final TreeMap fs = mappingModel.getFeatureServices();
for (final Iterator it = rs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer)
&& ((ServiceLayer)o).isEnabled()
&& (o instanceof RetrievalServiceLayer)
&& ((RetrievalServiceLayer)o).getPNode().getVisible()) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap: cloning '"
+ o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N
}
}
AbstractRetrievalService r;
if (o instanceof WebFeatureService) {
final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o)
.clone();
wfsClone.removeAllListeners();
r = wfsClone;
} else {
r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners();
}
r.addRetrievalListener(rl);
((ServiceLayer)r).setLayerPosition(rsi);
handleMapService(rsi, (MapService)r, width, height, bb, true);
} catch (final Exception t) {
LOG.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N
}
} else {
LOG.warn("ignoring service '" + o + "' for printing"); // NOI18N
}
}
for (final Iterator it = fs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int fsi = ((Integer)key).intValue();
final Object o = fs.get(key);
if (o instanceof AbstractRetrievalService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap: cloning '"
+ o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N
}
}
AbstractRetrievalService r;
if (o instanceof WebFeatureService) {
final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o)
.clone();
wfsClone.removeAllListeners();
r = (AbstractRetrievalService)o;
} else {
r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners();
}
r.addRetrievalListener(rl);
((ServiceLayer)r).setLayerPosition(fsi);
handleMapService(fsi, (MapService)r, 0, 0, bb, true);
}
}
}
}
};
CismetThreadPool.execute(r);
}
/**
* former synchronized method.
*
* @param position DOCUMENT ME!
* @param service rs
* @param forced DOCUMENT ME!
*/
public void handleMapService(final int position, final MapService service, final boolean forced) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("in handleRasterService: " + service + "("
+ Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N
}
}
final PBounds bounds = getCamera().getViewBounds();
final BoundingBox bb = new BoundingBox();
final double x1 = getWtst().getWorldX(bounds.getMinX());
final double y1 = getWtst().getWorldY(bounds.getMaxY());
final double x2 = getWtst().getWorldX(bounds.getMaxX());
final double y2 = getWtst().getWorldY(bounds.getMinY());
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Bounds=" + bounds); // NOI18N
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N
}
}
if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N
bb.setX1(x1 - (x2 - x1));
bb.setY1(y1 - (y2 - y1));
bb.setX2(x2 + (x2 - x1));
bb.setY2(y2 + (y2 - y1));
} else {
bb.setX1(x1);
bb.setY1(y1);
bb.setX2(x2);
bb.setY2(y2);
}
handleMapService(position, service, getWidth(), getHeight(), bb, forced);
}
/**
* former synchronized method.
*
* @param position DOCUMENT ME!
* @param rs DOCUMENT ME!
* @param width DOCUMENT ME!
* @param height DOCUMENT ME!
* @param bb DOCUMENT ME!
* @param forced DOCUMENT ME!
*/
private void handleMapService(final int position,
final MapService rs,
final int width,
final int height,
final BoundingBox bb,
final boolean forced) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("handleMapService: " + rs); // NOI18N
}
}
rs.setSize(height, width);
if (((ServiceLayer)rs).isEnabled()) {
synchronized (serviceFuturesMap) {
final Future<?> sf = serviceFuturesMap.get(rs);
if ((sf == null) || sf.isDone()) {
final Runnable serviceCall = new Runnable() {
@Override
public void run() {
try {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception e) {
}
}
rs.setBoundingBox(bb);
if (rs instanceof FeatureAwareRasterService) {
((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection);
}
rs.retrieve(forced);
} finally {
serviceFuturesMap.remove(rs);
}
}
};
synchronized (serviceFuturesMap) {
serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall));
}
}
}
}
}
/**
* Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it.
*
* @return new WorldToScreenTransform or null
*/
public WorldToScreenTransform getWtst() {
try {
if (wtst == null) {
final double y_real = mappingModel.getInitialBoundingBox().getY2()
- mappingModel.getInitialBoundingBox().getY1();
final double x_real = mappingModel.getInitialBoundingBox().getX2()
- mappingModel.getInitialBoundingBox().getX1();
double clip_height;
double clip_width;
double x_screen = getWidth();
double y_screen = getHeight();
if (x_screen == 0) {
x_screen = 100;
}
if (y_screen == 0) {
y_screen = 100;
}
if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert
clip_height = x_screen * y_real / x_real;
clip_width = x_screen;
clip_offset_y = 0; // (y_screen-clip_height)/2;
clip_offset_x = 0;
} else { // Y ist Bestimmer
clip_height = y_screen;
clip_width = y_screen * x_real / y_real;
clip_offset_y = 0;
clip_offset_x = 0; // (x_screen-clip_width)/2;
}
wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),
mappingModel.getInitialBoundingBox().getY2());
}
return wtst;
} catch (final Exception t) {
LOG.error("Fehler in getWtst()", t); // NOI18N
return null;
}
}
/**
* Resets the current WorldToScreenTransformation.
*/
public void resetWtst() {
wtst = null;
}
/**
* Returns 0.
*
* @return DOCUMENT ME!
*/
public double getClip_offset_x() {
return 0; // clip_offset_x;
}
/**
* Assigns a new value to the x-clip-offset.
*
* @param clip_offset_x new clipoffset
*/
public void setClip_offset_x(final double clip_offset_x) {
this.clip_offset_x = clip_offset_x;
}
/**
* Returns 0.
*
* @return DOCUMENT ME!
*/
public double getClip_offset_y() {
return 0; // clip_offset_y;
}
/**
* Assigns a new value to the y-clip-offset.
*
* @param clip_offset_y new clipoffset
*/
public void setClip_offset_y(final double clip_offset_y) {
this.clip_offset_y = clip_offset_y;
}
/**
* Returns the rubberband-PLayer.
*
* @return DOCUMENT ME!
*/
public PLayer getRubberBandLayer() {
return rubberBandLayer;
}
/**
* Assigns a given PLayer to the variable rubberBandLayer.
*
* @param rubberBandLayer a PLayer
*/
public void setRubberBandLayer(final PLayer rubberBandLayer) {
this.rubberBandLayer = rubberBandLayer;
}
/**
* Sets new viewbounds.
*
* @param r2d Rectangle2D
*/
public void setNewViewBounds(final Rectangle2D r2d) {
newViewBounds = r2d;
}
/**
* Will be called if the selection of features changes. It selects the PFeatures connected to the selected features
* of the featurecollectionevent and moves them to the front. Also repaints handles at the end.
*
* @param fce featurecollectionevent with selected features
*/
@Override
public void featureSelectionChanged(final FeatureCollectionEvent fce) {
final Collection allChildren = featureLayer.getChildrenReference();
final ArrayList<PFeature> all = new ArrayList<PFeature>();
for (final Object o : allChildren) {
if (o instanceof PFeature) {
all.add((PFeature)o);
} else if (o instanceof PLayer) {
// Handling von Feature-Gruppen-Layer, welche als Kinder dem Feature Layer hinzugefügt wurden
all.addAll(((PLayer)o).getChildrenReference());
}
}
// final Collection<PFeature> all = featureLayer.getChildrenReference();
for (final PFeature f : all) {
f.setSelected(false);
}
Collection<Feature> c;
if (fce != null) {
c = fce.getFeatureCollection().getSelectedFeatures();
} else {
c = featureCollection.getSelectedFeatures();
}
////handle featuregroup select-delegation////
final Set<Feature> selectionResult = new HashSet<Feature>();
for (final Feature current : c) {
if (current instanceof FeatureGroup) {
selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current));
} else {
selectionResult.add(current);
}
}
c = selectionResult;
for (final Feature f : c) {
if (f != null) {
final PFeature feature = getPFeatureHM().get(f);
if (feature != null) {
if (feature.getParent() != null) {
feature.getParent().moveToFront();
}
feature.setSelected(true);
feature.moveToFront();
// Fuer den selectedObjectPresenter (Eigener PCanvas)
syncSelectedObjectPresenter(1000);
} else {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
}
}
showHandles(false);
}
/**
* Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on
* each feature of the given featurecollectionevent. Repaints handles at the end.
*
* @param fce featurecollectionevent with changed features
*/
@Override
public void featuresChanged(final FeatureCollectionEvent fce) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("featuresChanged"); // NOI18N
}
}
final List<Feature> list = new ArrayList<Feature>();
list.addAll(fce.getEventFeatures());
for (final Feature elem : list) {
reconsiderFeature(elem);
}
showHandles(false);
}
/**
* Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls
* following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode()
*
* @param fce featurecollectionevent with features to reconsile
*/
@Override
public void featureReconsiderationRequested(final FeatureCollectionEvent fce) {
for (final Feature f : fce.getEventFeatures()) {
if (f != null) {
final PFeature node = pFeatureHM.get(f);
if (node != null) {
node.syncGeometry();
node.visualize();
node.resetInfoNodePosition();
node.refreshInfoNode();
repaint();
}
}
}
}
/**
* Method is deprecated and deactivated. Does nothing!!
*
* @param fce FeatureCollectionEvent with features to add
*/
@Override
@Deprecated
public void featuresAdded(final FeatureCollectionEvent fce) {
}
/**
* Method is deprecated and deactivated. Does nothing!!
*
* @deprecated DOCUMENT ME!
*/
@Override
@Deprecated
public void featureCollectionChanged() {
}
/**
* Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a
* checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent.
*
* @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice
*/
@Override
public void allFeaturesRemoved(final FeatureCollectionEvent fce) {
for (final PFeature feature : pFeatureHM.values()) {
feature.cleanup();
}
stickyPNodes.clear();
pFeatureHM.clear();
featureLayer.removeAllChildren();
// Lösche alle Features in den Gruppen-Layer, aber füge den Gruppen-Layer wieder dem FeatureLayer hinzu
for (final PLayer layer : featureGrpLayerMap.values()) {
layer.removeAllChildren();
featureLayer.addChild(layer);
}
checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce);
}
/**
* Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining
* supporting rasterservices and paints handles at the end.
*
* @param fce FeatureCollectionEvent with features to remove
*/
@Override
public void featuresRemoved(final FeatureCollectionEvent fce) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("featuresRemoved"); // NOI18N
}
}
removeFeatures(fce.getEventFeatures());
checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce);
showHandles(false);
}
/**
* Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and
* which need a refresh.
*
* @param fce FeatureCollectionEvent with removed features
*/
private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) {
final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved =
new HashSet<FeatureAwareRasterService>();
final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed =
new HashSet<FeatureAwareRasterService>();
final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>();
for (final Feature f : getFeatureCollection().getAllFeatures()) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N
}
}
rasterServices.add(rs); // DANGER
}
}
for (final Feature f : fce.getEventFeatures()) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N
}
}
if (rasterServices.contains(rs)) {
for (final Object o : getMappingModel().getRasterServices().values()) {
final MapService r = (MapService)o;
if (r.equals(rs)) {
rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r);
}
}
} else {
for (final Object o : getMappingModel().getRasterServices().values()) {
final MapService r = (MapService)o;
if (r.equals(rs)) {
rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r);
}
}
}
}
}
for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) {
getMappingModel().removeLayer(frs);
}
for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) {
handleMapService(0, frs, true);
}
}
/**
* public void showFeatureCollection(Feature[] features) { com.vividsolutions.jts.geom.Envelope
* env=computeFeatureEnvelope(features); showFeatureCollection(features,env); } public void
* showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { selectedFeature=null;
* handleLayer.removeAllChildren(); //setRasterServiceLayerImagesVisibility(false); Envelope eSquare=null; HashSet<Feature>
* featureSet=new HashSet<Feature>(); featureSet.addAll(holdFeatures);
* featureSet.addAll(java.util.Arrays.asList(f)); Feature[] features=featureSet.toArray(new Feature[0]);
* pFeatureHM.clear(); addFeaturesToMap(features); zoomToFullFeatureCollectionBounds(); }.
*
* @param groupId DOCUMENT ME!
* @param visible DOCUMENT ME!
*/
public void setGroupLayerVisibility(final String groupId, final boolean visible) {
final PLayer layer = this.featureGrpLayerMap.get(groupId);
if (layer != null) {
layer.setVisible(visible);
}
}
/**
* is called when new feature is added to FeatureCollection.
*
* @param features DOCUMENT ME!
*/
public void addFeaturesToMap(final Feature[] features) {
final double local_clip_offset_y = clip_offset_y;
final double local_clip_offset_x = clip_offset_x;
/// Hier muss der layer bestimmt werdenn
for (int i = 0; i < features.length; ++i) {
final Feature feature = features[i];
final PFeature p = new PFeature(
feature,
getWtst(),
local_clip_offset_x,
local_clip_offset_y,
MappingComponent.this);
try {
if (feature instanceof StyledFeature) {
p.setTransparency(((StyledFeature)(feature)).getTransparency());
} else {
p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency());
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (feature instanceof FeatureGroupMember) {
final FeatureGroupMember fgm = (FeatureGroupMember)feature;
final String groupId = fgm.getGroupId();
PLayer groupLayer = featureGrpLayerMap.get(groupId);
if (groupLayer == null) {
groupLayer = new PLayer();
featureLayer.addChild(groupLayer);
featureGrpLayerMap.put(groupId, groupLayer);
if (LOG.isDebugEnabled()) {
LOG.debug("created layer for group " + groupId);
}
}
groupLayer.addChild(p);
if (fgm.getGeometry() != null) {
pFeatureHM.put(fgm.getFeature(), p);
+ pFeatureHM.put(fgm, p);
}
if (LOG.isDebugEnabled()) {
LOG.debug("added feature to group " + groupId);
}
}
}
});
} catch (final Exception e) {
p.setTransparency(0.8f);
LOG.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N
}
// So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt)
if (!(feature instanceof FeatureGroupMember)) {
if (feature.getGeometry() != null) {
pFeatureHM.put(p.getFeature(), p);
final int ii = i;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
featureLayer.addChild(p);
if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) {
p.moveToFront();
}
}
});
}
}
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
rescaleStickyNodes();
repaint();
fireFeaturesAddedToMap(Arrays.asList(features));
// SuchFeatures in den Vordergrund stellen
for (final Feature feature : featureCollection.getAllFeatures()) {
if (feature instanceof SearchFeature) {
final PFeature pFeature = pFeatureHM.get(feature);
pFeature.moveToFront();
}
}
}
});
// check whether the feature has a rasterSupportLayer or not
for (final Feature f : features) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (!getMappingModel().getRasterServices().containsValue(rs)) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureAwareRasterServiceAdded"); // NOI18N
}
}
rs.setFeatureCollection(getFeatureCollection());
getMappingModel().addLayer(rs);
}
}
}
showHandles(false);
}
/**
* DOCUMENT ME!
*
* @param cf DOCUMENT ME!
*/
private void fireFeaturesAddedToMap(final Collection<Feature> cf) {
for (final MapListener curMapListener : mapListeners) {
curMapListener.featuresAddedToMap(cf);
}
}
/**
* Creates an envelope around all features from the given array.
*
* @param features features to create the envelope around
*
* @return Envelope com.vividsolutions.jts.geom.Envelope
*/
private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) {
final PNode root = new PNode();
for (int i = 0; i < features.length; ++i) {
final PNode p = PNodeFactory.createPFeature(features[i], this);
if (p != null) {
root.addChild(p);
}
}
final PBounds ext = root.getFullBounds();
final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope(
ext.x,
ext.x
+ ext.width,
ext.y,
ext.y
+ ext.height);
return env;
}
/**
* Zooms in / out to match the bounds of the featurecollection.
*/
public void zoomToFullFeatureCollectionBounds() {
zoomToFeatureCollection();
}
/**
* Adds a new cursor to the cursor-hashmap.
*
* @param mode interactionmode as string
* @param cursor cursor-object
*/
public void putCursor(final String mode, final Cursor cursor) {
cursors.put(mode, cursor);
}
/**
* Returns the cursor assigned to the given mode.
*
* @param mode mode as String
*
* @return Cursor-object or null
*/
public Cursor getCursor(final String mode) {
return cursors.get(mode);
}
/**
* Adds a new PBasicInputEventHandler for a specific interactionmode.
*
* @param mode interactionmode as string
* @param listener new PBasicInputEventHandler
*/
public void addInputListener(final String mode, final PBasicInputEventHandler listener) {
inputEventListener.put(mode, listener);
}
/**
* Returns the PBasicInputEventHandler assigned to the committed interactionmode.
*
* @param mode interactionmode as string
*
* @return PBasicInputEventHandler-object or null
*/
public PInputEventListener getInputListener(final String mode) {
final Object o = inputEventListener.get(mode);
if (o instanceof PInputEventListener) {
return (PInputEventListener)o;
} else {
return null;
}
}
/**
* Returns whether the features are editable or not.
*
* @return DOCUMENT ME!
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Sets all Features ReadOnly use Feature.setEditable(boolean) instead.
*
* @param readOnly DOCUMENT ME!
*/
public void setReadOnly(final boolean readOnly) {
for (final Object f : featureCollection.getAllFeatures()) {
((Feature)f).setEditable(!readOnly);
}
this.readOnly = readOnly;
handleLayer.repaint();
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
snapHandleLayer.removeAllChildren();
}
/**
* Returns the current HandleInteractionMode.
*
* @return DOCUMENT ME!
*/
public String getHandleInteractionMode() {
return handleInteractionMode;
}
/**
* Changes the HandleInteractionMode. Repaints handles.
*
* @param handleInteractionMode the new HandleInteractionMode
*/
public void setHandleInteractionMode(final String handleInteractionMode) {
this.handleInteractionMode = handleInteractionMode;
showHandles(false);
}
/**
* Returns whether the background is enabled or not.
*
* @return DOCUMENT ME!
*/
public boolean isBackgroundEnabled() {
return backgroundEnabled;
}
/**
* TODO.
*
* @param backgroundEnabled DOCUMENT ME!
*/
public void setBackgroundEnabled(final boolean backgroundEnabled) {
if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) {
featureServiceLayerVisible = featureServiceLayer.getVisible();
}
this.mapServicelayer.setVisible(backgroundEnabled);
this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible);
for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) {
featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible);
}
if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) {
this.queryServices();
}
this.backgroundEnabled = backgroundEnabled;
}
/**
* Returns the featurelayer.
*
* @return DOCUMENT ME!
*/
public PLayer getFeatureLayer() {
return featureLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map<String, PLayer> getFeatureGroupLayers() {
return this.featureGrpLayerMap;
}
/**
* Adds a PFeature to the PFeatureHashmap.
*
* @param p PFeature to add
*/
public void refreshHM(final PFeature p) {
pFeatureHM.put(p.getFeature(), p);
}
/**
* Returns the selectedObjectPresenter (PCanvas).
*
* @return DOCUMENT ME!
*/
public PCanvas getSelectedObjectPresenter() {
return selectedObjectPresenter;
}
/**
* If f != null it calls the reconsiderFeature()-method of the featurecollection.
*
* @param f feature to reconcile
*/
public void reconsiderFeature(final Feature f) {
if (f != null) {
featureCollection.reconsiderFeature(f);
}
}
/**
* Removes all features of the collection from the hashmap.
*
* @param fc collection of features to remove
*/
public void removeFeatures(final Collection<Feature> fc) {
featureLayer.setVisible(false);
for (final Feature elem : fc) {
removeFromHM(elem);
}
featureLayer.setVisible(true);
}
/**
* Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key.
*
* @param f feature of the Pfeature that should be deleted
*/
public void removeFromHM(final Feature f) {
final PFeature pf = pFeatureHM.get(f);
if (pf != null) {
pf.cleanup();
pFeatureHM.remove(f);
stickyPNodes.remove(pf);
try {
LOG.info("Entferne Feature " + f); // NOI18N
featureLayer.removeChild(pf);
for (final PLayer grpLayer : this.featureGrpLayerMap.values()) {
if (grpLayer.removeChild(pf) != null) {
break;
}
}
} catch (Exception ex) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N
}
}
}
} else {
LOG.warn("Feature war nicht in pFeatureHM"); // NOI18N
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("pFeatureHM" + pFeatureHM); // NOI18N
}
}
}
/**
* Zooms to the current selected node.
*
* @deprecated DOCUMENT ME!
*/
public void zoomToSelectedNode() {
zoomToSelection();
}
/**
* Zooms to the current selected features.
*/
public void zoomToSelection() {
final Collection<Feature> selection = featureCollection.getSelectedFeatures();
zoomToAFeatureCollection(selection, true, false);
}
/**
* Zooms to a specific featurecollection.
*
* @param collection the featurecolltion
* @param withHistory should the zoomaction be undoable
* @param fixedScale fixedScale
*/
public void zoomToAFeatureCollection(final Collection<Feature> collection,
final boolean withHistory,
final boolean fixedScale) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("zoomToAFeatureCollection"); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
boolean first = true;
Geometry g = null;
for (final Feature f : collection) {
if (first) {
if (f.getGeometry() != null) {
g = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode())
.getEnvelope();
if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) {
g = g.buffer(((Bufferable)f).getBuffer() + 0.001);
}
first = false;
}
} else {
if (f.getGeometry() != null) {
Geometry geometry = CrsTransformer.transformToGivenCrs(f.getGeometry(),
mappingModel.getSrs().getCode())
.getEnvelope();
if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) {
geometry = geometry.buffer(((Bufferable)f).getBuffer() + 0.001);
}
g = g.getEnvelope().union(geometry);
}
}
}
if (g != null) {
// FIXME: we shouldn't only complain but do sth
if ((getHeight() == 0) || (getWidth() == 0)) {
LOG.warn("DIVISION BY ZERO"); // NOI18N
}
// dreisatz.de
final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10;
final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10;
double buff = 0;
if (hBuff > vBuff) {
buff = hBuff;
} else {
buff = vBuff;
}
if (buff == 0.0) {
if (mappingModel.getSrs().isMetric()) {
buff = 1.0;
} else {
buff = 0.01;
}
}
g = g.buffer(buff);
final BoundingBox bb = new BoundingBox(g);
final boolean onlyOnePoint = (collection.size() == 1)
&& (((Feature)(collection.toArray()[0])).getGeometry()
instanceof com.vividsolutions.jts.geom.Point);
gotoBoundingBox(bb, withHistory, !(fixedScale || (onlyOnePoint && (g.getArea() < 10))), animationDuration);
}
}
/**
* Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create
* their handles and to add them to the handlelayer.
*
* @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles
*/
public void showHandles(final boolean waitTillAllAnimationsAreComplete) {
// are there features selected?
if (featureCollection.getSelectedFeatures().size() > 0) {
// DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf
final Runnable handle = new Runnable() {
@Override
public void run() {
// alle bisherigen Handles entfernen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
});
while (getAnimating() && waitTillAllAnimationsAreComplete) {
try {
Thread.currentThread().sleep(10);
} catch (final Exception e) {
LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N
}
}
if (featureCollection.areFeaturesEditable()
&& (getInteractionMode().equals(SELECT)
|| getInteractionMode().equals(LINEAR_REFERENCING)
|| getInteractionMode().equals(PAN)
|| getInteractionMode().equals(ZOOM)
|| getInteractionMode().equals(ALKIS_PRINT)
|| getInteractionMode().equals(SPLIT_POLYGON))) {
// Handles für alle selektierten Features der Collection hinzufügen
if (getHandleInteractionMode().equals(ROTATE_POLYGON)) {
final LinkedHashSet<Feature> copy = new LinkedHashSet(
featureCollection.getSelectedFeatures());
for (final Feature selectedFeature : copy) {
if ((selectedFeature instanceof Feature) && selectedFeature.isEditable()) {
if (pFeatureHM.get(selectedFeature) != null) {
// manipulates gui -> edt
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
pFeatureHM.get(selectedFeature).addRotationHandles(handleLayer);
}
});
} else {
LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N
}
}
}
} else {
final LinkedHashSet<Feature> copy = new LinkedHashSet(
featureCollection.getSelectedFeatures());
for (final Feature selectedFeature : copy) {
if ((selectedFeature != null) && selectedFeature.isEditable()) {
if (pFeatureHM.get(selectedFeature) != null) {
// manipulates gui -> edt
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
pFeatureHM.get(selectedFeature).addHandles(handleLayer);
} catch (final Exception e) {
LOG.error("Error bei addHandles: ", e); // NOI18N
}
}
});
} else {
LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N
}
// DANGER mit break werden nur die Handles EINES slektierten Features angezeigt
// wird break auskommentiert werden jedoch zu viele Handles angezeigt break;
}
}
}
}
}
};
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("showHandles", new CurrentStackTrace()); // NOI18N
}
}
CismetThreadPool.execute(handle);
} else {
// alle bisherigen Handles entfernen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
});
}
}
/**
* Will return a PureNewFeature if there is only one in the featurecollection else null.
*
* @return DOCUMENT ME!
*/
public PFeature getSolePureNewFeature() {
int counter = 0;
PFeature sole = null;
for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) {
final Object o = it.next();
if (o instanceof PFeature) {
if (((PFeature)o).getFeature() instanceof PureNewFeature) {
++counter;
sole = ((PFeature)o);
}
}
}
if (counter == 1) {
return sole;
} else {
return null;
}
}
/**
* Returns the temporary featurelayer.
*
* @return DOCUMENT ME!
*/
public PLayer getTmpFeatureLayer() {
return tmpFeatureLayer;
}
/**
* Assigns a new temporary featurelayer.
*
* @param tmpFeatureLayer PLayer
*/
public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) {
this.tmpFeatureLayer = tmpFeatureLayer;
}
/**
* Returns whether the grid is enabled or not.
*
* @return DOCUMENT ME!
*/
public boolean isGridEnabled() {
return gridEnabled;
}
/**
* Enables or disables the grid.
*
* @param gridEnabled true, to enable the grid
*/
public void setGridEnabled(final boolean gridEnabled) {
this.gridEnabled = gridEnabled;
}
/**
* Returns a String from two double-values. Serves the visualization.
*
* @param x X-coordinate
* @param y Y-coordinate
*
* @return a String-object like "(X,Y)"
*/
public static String getCoordinateString(final double x, final double y) {
final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N
final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public com.vividsolutions.jts.geom.Point getPointGeometryFromPInputEvent(final PInputEvent event) {
final double xCoord = getWtst().getSourceX(event.getPosition().getX() - getClip_offset_x());
final double yCoord = getWtst().getSourceY(event.getPosition().getY() - getClip_offset_y());
final GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),
CrsTransformer.extractSridFromCrs(getMappingModel().getSrs().getCode()));
return gf.createPoint(new Coordinate(xCoord, yCoord));
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getHandleLayer() {
return handleLayer;
}
/**
* DOCUMENT ME!
*
* @param handleLayer DOCUMENT ME!
*/
public void setHandleLayer(final PLayer handleLayer) {
this.handleLayer = handleLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisualizeSnappingEnabled() {
return visualizeSnappingEnabled;
}
/**
* DOCUMENT ME!
*
* @param visualizeSnappingEnabled DOCUMENT ME!
*/
public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) {
this.visualizeSnappingEnabled = visualizeSnappingEnabled;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisualizeSnappingRectEnabled() {
return visualizeSnappingRectEnabled;
}
/**
* DOCUMENT ME!
*
* @param visualizeSnappingRectEnabled DOCUMENT ME!
*/
public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) {
this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getSnappingRectSize() {
return snappingRectSize;
}
/**
* DOCUMENT ME!
*
* @param snappingRectSize DOCUMENT ME!
*/
public void setSnappingRectSize(final int snappingRectSize) {
this.snappingRectSize = snappingRectSize;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getSnapHandleLayer() {
return snapHandleLayer;
}
/**
* DOCUMENT ME!
*
* @param snapHandleLayer DOCUMENT ME!
*/
public void setSnapHandleLayer(final PLayer snapHandleLayer) {
this.snapHandleLayer = snapHandleLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isSnappingEnabled() {
return snappingEnabled;
}
/**
* DOCUMENT ME!
*
* @param snappingEnabled DOCUMENT ME!
*/
public void setSnappingEnabled(final boolean snappingEnabled) {
this.snappingEnabled = snappingEnabled;
setVisualizeSnappingEnabled(snappingEnabled);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getFeatureServiceLayer() {
return featureServiceLayer;
}
/**
* DOCUMENT ME!
*
* @param featureServiceLayer DOCUMENT ME!
*/
public void setFeatureServiceLayer(final PLayer featureServiceLayer) {
this.featureServiceLayer = featureServiceLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getAnimationDuration() {
return animationDuration;
}
/**
* DOCUMENT ME!
*
* @param animationDuration DOCUMENT ME!
*/
public void setAnimationDuration(final int animationDuration) {
this.animationDuration = animationDuration;
}
/**
* DOCUMENT ME!
*
* @param prefs DOCUMENT ME!
*/
@Deprecated
public void setPreferences(final CismapPreferences prefs) {
LOG.warn("involing deprecated operation setPreferences()"); // NOI18N
cismapPrefs = prefs;
final ActiveLayerModel mm = new ActiveLayerModel();
final LayersPreferences layersPrefs = prefs.getLayersPrefs();
final GlobalPreferences globalPrefs = prefs.getGlobalPrefs();
setSnappingRectSize(globalPrefs.getSnappingRectSize());
setSnappingEnabled(globalPrefs.isSnappingEnabled());
setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled());
setAnimationDuration(globalPrefs.getAnimationDuration());
setInteractionMode(globalPrefs.getStartMode());
mm.addHome(globalPrefs.getInitialBoundingBox());
final Crs crs = new Crs();
crs.setCode(globalPrefs.getInitialBoundingBox().getSrs());
crs.setName(globalPrefs.getInitialBoundingBox().getSrs());
crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs());
mm.setSrs(crs);
final TreeMap raster = layersPrefs.getRasterServices();
if (raster != null) {
final Iterator it = raster.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final Object o = raster.get(key);
if (o instanceof MapService) {
mm.addLayer((RetrievalServiceLayer)o);
}
}
}
final TreeMap features = layersPrefs.getFeatureServices();
if (features != null) {
final Iterator it = features.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final Object o = features.get(key);
if (o instanceof MapService) {
// TODO
mm.addLayer((RetrievalServiceLayer)o);
}
}
}
setMappingModel(mm);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public CismapPreferences getCismapPrefs() {
return cismapPrefs;
}
/**
* DOCUMENT ME!
*
* @param duration DOCUMENT ME!
* @param animationDuration DOCUMENT ME!
* @param what DOCUMENT ME!
* @param number DOCUMENT ME!
*/
public void flash(final int duration, final int animationDuration, final int what, final int number) {
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getDragPerformanceImproverLayer() {
return dragPerformanceImproverLayer;
}
/**
* DOCUMENT ME!
*
* @param dragPerformanceImproverLayer DOCUMENT ME!
*/
public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) {
this.dragPerformanceImproverLayer = dragPerformanceImproverLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Deprecated
public PLayer getRasterServiceLayer() {
return mapServicelayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getMapServiceLayer() {
return mapServicelayer;
}
/**
* DOCUMENT ME!
*
* @param rasterServiceLayer DOCUMENT ME!
*/
public void setRasterServiceLayer(final PLayer rasterServiceLayer) {
this.mapServicelayer = rasterServiceLayer;
}
/**
* DOCUMENT ME!
*
* @param f DOCUMENT ME!
*/
public void showGeometryInfoPanel(final Feature f) {
}
/**
* Adds a PropertyChangeListener to the listener list.
*
* @param l The listener to add.
*/
@Override
public void addPropertyChangeListener(final PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
/**
* Removes a PropertyChangeListener from the listener list.
*
* @param l The listener to remove.
*/
@Override
public void removePropertyChangeListener(final PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
/**
* Setter for property taskCounter. former synchronized method
*/
public void fireActivityChanged() {
propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N
}
/**
* Returns true, if there's still one layercontrol running. Else false; former synchronized method
*
* @return DOCUMENT ME!
*/
public boolean isRunning() {
for (final LayerControl lc : layerControls) {
if (lc.isRunning()) {
return true;
}
}
return false;
}
/**
* Sets the visibility of all infonodes.
*
* @param visible true, if infonodes should be visible
*/
public void setInfoNodesVisible(final boolean visible) {
infoNodesVisible = visible;
for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) {
final Object elem = it.next();
if (elem instanceof PFeature) {
((PFeature)elem).setInfoNodeVisible(visible);
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("setInfoNodesVisible()"); // NOI18N
}
}
rescaleStickyNodes();
}
/**
* Adds an object to the historymodel.
*
* @param o Object to add
*/
@Override
public void addToHistory(final Object o) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("addToHistory:" + o.toString()); // NOI18N
}
}
historyModel.addToHistory(o);
}
/**
* Removes a specific HistoryModelListener from the historymodel.
*
* @param hml HistoryModelListener
*/
@Override
public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) {
historyModel.removeHistoryModelListener(hml);
}
/**
* Adds aHistoryModelListener to the historymodel.
*
* @param hml HistoryModelListener
*/
@Override
public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) {
historyModel.addHistoryModelListener(hml);
}
/**
* Sets the maximum value of saved historyactions.
*
* @param max new integer value
*/
@Override
public void setMaximumPossibilities(final int max) {
historyModel.setMaximumPossibilities(max);
}
/**
* Redos the last undone historyaction.
*
* @param external true, if fireHistoryChanged-action should be fired
*
* @return PBounds of the forward-action
*/
@Override
public Object forward(final boolean external) {
final PBounds fwd = (PBounds)historyModel.forward(external);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("HistoryModel.forward():" + fwd); // NOI18N
}
}
if (external) {
this.gotoBoundsWithoutHistory(fwd);
}
return fwd;
}
/**
* Undos the last action.
*
* @param external true, if fireHistoryChanged-action should be fired
*
* @return PBounds of the back-action
*/
@Override
public Object back(final boolean external) {
final PBounds back = (PBounds)historyModel.back(external);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("HistoryModel.back():" + back); // NOI18N
}
}
if (external) {
this.gotoBoundsWithoutHistory(back);
}
return back;
}
/**
* Returns true, if it's possible to redo an action.
*
* @return DOCUMENT ME!
*/
@Override
public boolean isForwardPossible() {
return historyModel.isForwardPossible();
}
/**
* Returns true, if it's possible to undo an action.
*
* @return DOCUMENT ME!
*/
@Override
public boolean isBackPossible() {
return historyModel.isBackPossible();
}
/**
* Returns a vector with all redo-possibilities.
*
* @return DOCUMENT ME!
*/
@Override
public Vector getForwardPossibilities() {
return historyModel.getForwardPossibilities();
}
/**
* Returns the current element of the historymodel.
*
* @return DOCUMENT ME!
*/
@Override
public Object getCurrentElement() {
return historyModel.getCurrentElement();
}
/**
* Returns a vector with all undo-possibilities.
*
* @return DOCUMENT ME!
*/
@Override
public Vector getBackPossibilities() {
return historyModel.getBackPossibilities();
}
/**
* Returns whether an internallayerwidget is available.
*
* @return DOCUMENT ME!
*/
@Deprecated
public boolean isInternalLayerWidgetAvailable() {
return this.getInternalWidget(LAYERWIDGET) != null;
}
/**
* Sets the variable, if an internallayerwidget is available or not.
*
* @param internalLayerWidgetAvailable true, if available
*/
@Deprecated
public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) {
if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) {
this.removeInternalWidget(LAYERWIDGET);
} else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) {
final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget(
MappingComponent.this);
MappingComponent.this.addInternalWidget(
LAYERWIDGET,
MappingComponent.POSITION_SOUTHEAST,
simpleInternalLayerWidget);
}
}
/**
* DOCUMENT ME!
*
* @param mme DOCUMENT ME!
*/
@Override
public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) {
}
/**
* Removes the mapservice from the rasterservicelayer.
*
* @param rasterService the removing mapservice
*/
@Override
public void mapServiceRemoved(final MapService rasterService) {
try {
mapServicelayer.removeChild(rasterService.getPNode());
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_REMOVED, rasterService));
}
System.gc();
} catch (final Exception e) {
LOG.warn("Fehler bei mapServiceRemoved", e); // NOI18N
}
}
/**
* Adds the commited mapservice on the last position to the rasterservicelayer.
*
* @param mapService the new mapservice
*/
@Override
public void mapServiceAdded(final MapService mapService) {
addMapService(mapService, mapServicelayer.getChildrenCount());
if (mapService instanceof FeatureAwareRasterService) {
((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection());
}
if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) {
handleMapService(0, mapService, false);
}
}
/**
* Returns the current OGC scale.
*
* @return DOCUMENT ME!
*/
public double getCurrentOGCScale() {
// funktioniert nur bei metrischen SRS's
final double h = getCamera().getViewBounds().getHeight() / getHeight();
final double w = getCamera().getViewBounds().getWidth() / getWidth();
return Math.sqrt((h * h) + (w * w));
}
/**
* Returns the current BoundingBox.
*
* @return DOCUMENT ME!
*/
public BoundingBox getCurrentBoundingBox() {
if (fixedBoundingBox != null) {
return fixedBoundingBox;
} else {
try {
final PBounds bounds = getCamera().getViewBounds();
final double x1 = wtst.getWorldX(bounds.getX());
final double y1 = wtst.getWorldY(bounds.getY());
final double x2 = x1 + bounds.width;
final double y2 = y1 - bounds.height;
final Crs currentCrs = CismapBroker.getInstance().getSrs();
final boolean metric;
// FIXME: this is a hack to overcome the "metric" issue for 4326 default srs
if (CrsTransformer.getCurrentSrid() == 4326) {
metric = false;
} else {
metric = currentCrs.isMetric();
}
currentBoundingBox = new XBoundingBox(x1, y1, x2, y2, currentCrs.getCode(), metric);
return currentBoundingBox;
} catch (final Exception e) {
LOG.error("cannot create bounding box from current view, return null", e); // NOI18N
return null;
}
}
}
/**
* Returns a BoundingBox with a fixed size.
*
* @return DOCUMENT ME!
*/
public BoundingBox getFixedBoundingBox() {
return fixedBoundingBox;
}
/**
* Assigns fixedBoundingBox a new value.
*
* @param fixedBoundingBox new boundingbox
*/
public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) {
this.fixedBoundingBox = fixedBoundingBox;
}
/**
* Paints the outline of the forwarded BoundingBox.
*
* @param bb BoundingBox
*/
public void outlineArea(final BoundingBox bb) {
outlineArea(bb, null);
}
/**
* Paints the outline of the forwarded PBounds.
*
* @param b PBounds
*/
public void outlineArea(final PBounds b) {
outlineArea(b, null);
}
/**
* Paints a filled rectangle of the area of the forwarded BoundingBox.
*
* @param bb BoundingBox
* @param fillingPaint Color to fill the rectangle
*/
public void outlineArea(final BoundingBox bb, final Paint fillingPaint) {
PBounds pb = null;
if (bb != null) {
pb = new PBounds(wtst.getScreenX(bb.getX1()),
wtst.getScreenY(bb.getY2()),
bb.getX2()
- bb.getX1(),
bb.getY2()
- bb.getY1());
}
outlineArea(pb, fillingPaint);
}
/**
* Paints a filled rectangle of the area of the forwarded PBounds.
*
* @param b PBounds to paint
* @param fillingColor Color to fill the rectangle
*/
public void outlineArea(final PBounds b, final Paint fillingColor) {
if (b == null) {
if (highlightingLayer.getChildrenCount() > 0) {
highlightingLayer.removeAllChildren();
}
} else {
highlightingLayer.removeAllChildren();
highlightingLayer.setTransparency(1);
final PPath rectangle = new PPath();
rectangle.setPaint(fillingColor);
rectangle.setStroke(new FixedWidthStroke());
rectangle.setStrokePaint(new Color(100, 100, 100, 255));
rectangle.setPathTo(b);
highlightingLayer.addChild(rectangle);
}
}
/**
* Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally.
*
* @param bb BoundingBox to highlight
*/
public void highlightArea(final BoundingBox bb) {
PBounds pb = null;
if (bb != null) {
pb = new PBounds(wtst.getScreenX(bb.getX1()),
wtst.getScreenY(bb.getY2()),
bb.getX2()
- bb.getX1(),
bb.getY2()
- bb.getY1());
}
highlightArea(pb);
}
/**
* Highlights the delivered PBounds by painting over with a transparent white.
*
* @param b PBounds to hightlight
*/
private void highlightArea(final PBounds b) {
if (b == null) {
if (highlightingLayer.getChildrenCount() > 0) {
}
highlightingLayer.animateToTransparency(0, animationDuration);
highlightingLayer.removeAllChildren();
} else {
highlightingLayer.removeAllChildren();
highlightingLayer.setTransparency(1);
final PPath rectangle = new PPath();
rectangle.setPaint(new Color(255, 255, 255, 100));
rectangle.setStroke(null);
rectangle.setPathTo(this.getCamera().getViewBounds());
highlightingLayer.addChild(rectangle);
rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration);
}
}
/**
* Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls
* crossHairPoint(Point p) internally.
*
* @param c coordinate of the crosshair's venue
*/
public void crossHairPoint(final Coordinate c) {
Point p = null;
if (c != null) {
p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y));
}
crossHairPoint(p);
}
/**
* Paints a crosshair at the delivered point.
*
* @param p point of the crosshair's venue
*/
public void crossHairPoint(final Point p) {
if (p == null) {
if (crosshairLayer.getChildrenCount() > 0) {
crosshairLayer.removeAllChildren();
}
} else {
crosshairLayer.removeAllChildren();
crosshairLayer.setTransparency(1);
final PPath lineX = new PPath();
final PPath lineY = new PPath();
lineX.setStroke(new FixedWidthStroke());
lineX.setStrokePaint(new Color(100, 100, 100, 255));
lineY.setStroke(new FixedWidthStroke());
lineY.setStrokePaint(new Color(100, 100, 100, 255));
final PBounds current = getCamera().getViewBounds();
final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1);
final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2);
lineX.setPathTo(x);
crosshairLayer.addChild(lineX);
lineY.setPathTo(y);
crosshairLayer.addChild(lineY);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Element getConfiguration() {
if (LOG.isDebugEnabled()) {
LOG.debug("writing configuration <cismapMappingPreferences>"); // NOI18N
}
final Element ret = new Element("cismapMappingPreferences"); // NOI18N
ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N
ret.setAttribute(
"creationMode",
((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N
ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N
ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N
final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON);
if (inputListener instanceof CreateSearchGeometryListener) {
final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener;
ret.setAttribute("createSearchMode", listener.getMode());
}
// Position
final Element currentPosition = new Element("Position"); // NOI18N
currentPosition.addContent(currentBoundingBox.getJDOMElement());
currentPosition.setAttribute("CRS", mappingModel.getSrs().getCode());
ret.addContent(currentPosition);
// Crs
final Element crsListElement = new Element("crsList");
for (final Crs tmp : crsList) {
crsListElement.addContent(tmp.getJDOMElement());
}
ret.addContent(crsListElement);
if (printingSettingsDialog != null) {
ret.addContent(printingSettingsDialog.getConfiguration());
}
// save internal widgets status
final Element widgets = new Element("InternalWidgets"); // NOI18N
for (final String name : this.internalWidgets.keySet()) {
final Element widget = new Element("Widget"); // NOI18N
widget.setAttribute("name", name); // NOI18N
widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N
widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N
widgets.addContent(widget);
}
ret.addContent(widgets);
return ret;
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void masterConfigure(final Element e) {
final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N
// CRS List
try {
final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N
boolean defaultCrsFound = false;
crsList.clear();
for (final Object elem : crsElements) {
if (elem instanceof Element) {
final Crs s = new Crs((Element)elem);
crsList.add(s);
if (s.isSelected() && s.isMetric()) {
try {
if (defaultCrsFound) {
LOG.warn("More than one default CRS is set. "
+ "Please check your master configuration file."); // NOI18N
}
CismapBroker.getInstance().setDefaultCrs(s.getCode());
defaultCrsFound = true;
transformer = new CrsTransformer(s.getCode());
} catch (final Exception ex) {
LOG.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex);
}
}
}
}
} catch (final Exception skip) {
LOG.error("Error while reading the crs list", skip); // NOI18N
}
if (CismapBroker.getInstance().getDefaultCrs() == null) {
LOG.fatal("The default CRS is not set. This can lead to almost irreparable data errors. "
+ "Keep in mind: The default CRS must be metric"); // NOI18N
}
if (transformer == null) {
LOG.error("No metric default crs found. Use EPSG:31466 as default crs"); // NOI18N
try {
transformer = new CrsTransformer("EPSG:31466"); // NOI18N
CismapBroker.getInstance().setDefaultCrs("EPSG:31466"); // NOI18N
} catch (final Exception ex) {
LOG.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); // NOI18N
}
}
// HOME
try {
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N
}
}
while (it.hasNext()) {
final Element elem = it.next();
final String srs = elem.getAttribute("srs").getValue(); // NOI18N
boolean metric = false;
try {
metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N
} catch (DataConversionException dce) {
LOG.warn("Metric hat falschen Syntax", dce); // NOI18N
}
boolean defaultVal = false;
try {
defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N
} catch (DataConversionException dce) {
LOG.warn("default hat falschen Syntax", dce); // NOI18N
}
final XBoundingBox xbox = new XBoundingBox(elem, srs, metric);
alm.addHome(xbox);
if (defaultVal) {
Crs crsObject = null;
for (final Crs tmp : crsList) {
if (tmp.getCode().equals(srs)) {
crsObject = tmp;
break;
}
}
if (crsObject == null) {
LOG.error("CRS " + srs + " from the default home is not found in the crs list");
crsObject = new Crs(srs, srs, srs, true, false);
crsList.add(crsObject);
}
alm.setSrs(crsObject);
alm.setDefaultHomeSrs(crsObject);
CismapBroker.getInstance().setSrs(crsObject);
wtst = null;
getWtst();
}
}
}
} catch (final Exception ex) {
LOG.error("Fehler beim MasterConfigure der MappingComponent", ex); // NOI18N
}
try {
final Element defaultCrs = prefs.getChild("defaultCrs");
final int defaultCrsInt = Integer.parseInt(defaultCrs.getAttributeValue("geometrySridAlias"));
CismapBroker.getInstance().setDefaultCrsAlias(defaultCrsInt);
} catch (final Exception ex) {
LOG.error("Error while reading the default crs alias from the master configuration file.", ex);
}
try {
final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N
scales.clear();
for (final Object elem : scalesList) {
if (elem instanceof Element) {
final Scale s = new Scale((Element)elem);
scales.add(s);
}
}
} catch (final Exception skip) {
LOG.error("Fehler beim Lesen von Scale", skip); // NOI18N
}
// Und jetzt noch die PriningEinstellungen
initPrintingDialogs();
printingSettingsDialog.masterConfigure(prefs);
}
/**
* Configurates this MappingComponent.
*
* @param e JDOM-Element with configuration
*/
@Override
public void configure(final Element e) {
final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N
try {
final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N
for (final Object elem : crsElements) {
if (elem instanceof Element) {
final Crs s = new Crs((Element)elem);
// the crs is equals to an other crs, if the code is equal. If a crs has in the
// local configuration file an other name than in the master configuration file,
// the old crs will be removed and the local one should be added to use the
// local name and short name of the crs.
if (crsList.contains(s)) {
crsList.remove(s);
}
crsList.add(s);
}
}
} catch (final Exception skip) {
LOG.warn("Error while reading the crs list", skip); // NOI18N
}
// InteractionMode
try {
final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N
setInteractionMode(interactMode);
if (interactMode.equals(MappingComponent.NEW_POLYGON)) {
try {
final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N
((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode);
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des CreationInteractionMode", ex); // NOI18N
}
}
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des InteractionMode", ex); // NOI18N
}
try {
final String createSearchMode = prefs.getAttribute("createSearchMode").getValue();
final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON);
if ((inputListener instanceof CreateSearchGeometryListener) && (createSearchMode != null)) {
final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener;
listener.setMode(createSearchMode);
}
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des CreateSearchMode", ex); // NOI18N
}
try {
final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N
setHandleInteractionMode(handleInterMode);
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des HandleInteractionMode", ex); // NOI18N
}
try {
final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N
LOG.info("snapping=" + snapping); // NOI18N
setSnappingEnabled(snapping);
setVisualizeSnappingEnabled(snapping);
setInGlueIdenticalPointsMode(snapping);
} catch (final Exception ex) {
LOG.warn("Fehler beim setzen von snapping und Konsorten", ex); // NOI18N
}
// aktuelle Position
try {
final Element pos = prefs.getChild("Position"); // NOI18N
final BoundingBox b = new BoundingBox(pos);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Position:" + b); // NOI18N
}
}
final PBounds pb = b.getPBounds(getWtst());
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("PositionPb:" + pb); // NOI18N
}
}
if (Double.isNaN(b.getX1())
|| Double.isNaN(b.getX2())
|| Double.isNaN(b.getY1())
|| Double.isNaN(b.getY2())) {
LOG.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N
this.currentBoundingBox = getMappingModel().getInitialBoundingBox();
final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null);
addToHistory(new PBoundsWithCleverToString(
new PBounds(currentBoundingBox.getPBounds(wtst)),
wtst,
crsCode));
} else {
// set the current crs
final Attribute crsAtt = pos.getAttribute("CRS");
if (crsAtt != null) {
final String currentCrs = crsAtt.getValue();
Crs crsObject = null;
for (final Crs tmp : crsList) {
if (tmp.getCode().equals(currentCrs)) {
crsObject = tmp;
break;
}
}
if (crsObject == null) {
LOG.error("CRS " + currentCrs + " from the position element is not found in the crs list");
}
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
if (alm instanceof ActiveLayerModel) {
alm.setSrs(crsObject);
}
CismapBroker.getInstance().setSrs(crsObject);
wtst = null;
getWtst();
}
this.currentBoundingBox = b;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("added to History" + b); // NOI18N
}
}
}
} catch (final Exception ex) {
LOG.warn("Fehler beim lesen der aktuellen Position", ex); // NOI18N
this.currentBoundingBox = getMappingModel().getInitialBoundingBox();
}
if (printingSettingsDialog != null) {
printingSettingsDialog.configure(prefs);
}
try {
final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N
if (widgets != null) {
for (final Object widget : widgets.getChildren()) {
final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N
final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N
this.showInternalWidget(name, visible, 0);
}
}
} catch (final Exception ex) {
LOG.warn("could not enable internal widgets: " + ex, ex); // NOI18N
}
}
/**
* Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent
* will only pan to the featurecollection and not zoom.
*
* @param fixedScale true, if zoom is not allowed
*/
public void zoomToFeatureCollection(final boolean fixedScale) {
zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale);
}
/**
* Zooms to all features of the mappingcomponents featurecollection.
*/
public void zoomToFeatureCollection() {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("zoomToFeatureCollection"); // NOI18N
}
}
zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false);
}
/**
* Moves the view to the target Boundingbox.
*
* @param bb target BoundingBox
* @param history true, if the action sould be saved in the history
* @param scaleToFit true, to zoom
* @param animationDuration duration of the animation
*/
public void gotoBoundingBox(final BoundingBox bb,
final boolean history,
final boolean scaleToFit,
final int animationDuration) {
gotoBoundingBox(bb, history, scaleToFit, animationDuration, true);
}
/**
* Moves the view to the target Boundingbox.
*
* @param bb target BoundingBox
* @param history true, if the action sould be saved in the history
* @param scaleToFit true, to zoom
* @param animationDuration duration of the animation
* @param queryServices true, if the services should be refreshed after animation
*/
public void gotoBoundingBox(BoundingBox bb,
final boolean history,
final boolean scaleToFit,
final int animationDuration,
final boolean queryServices) {
if (bb != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
if (bb instanceof XBoundingBox) {
if (!((XBoundingBox)bb).getSrs().equals(mappingModel.getSrs().getCode())) {
try {
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
bb = trans.transformBoundingBox((XBoundingBox)bb);
} catch (final Exception e) {
LOG.warn("Cannot transform the bounding box", e);
}
}
}
final double x1 = getWtst().getScreenX(bb.getX1());
final double y1 = getWtst().getScreenY(bb.getY1());
final double x2 = getWtst().getScreenX(bb.getX2());
final double y2 = getWtst().getScreenY(bb.getY2());
final double w;
final double h;
final Rectangle2D pos = new Rectangle2D.Double();
pos.setRect(x1, y2, x2 - x1, y1 - y2);
getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration);
if (getCamera().getViewTransform().getScaleY() < 0) {
LOG.warn("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N
}
showHandles(true);
final Runnable handle = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(10);
} catch (final Exception e) {
LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N
}
}
if (history) {
if ((x1 == x2) || (y1 == y2) || !scaleToFit) {
setNewViewBounds(getCamera().getViewBounds());
} else {
setNewViewBounds(pos);
}
if (queryServices) {
queryServices();
}
} else {
if (queryServices) {
queryServicesWithoutHistory();
}
}
}
};
CismetThreadPool.execute(handle);
} else {
LOG.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N
}
}
/**
* Moves the view to the target Boundingbox without saving the action in the history.
*
* @param bb target BoundingBox
*/
public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) {
gotoBoundingBoxWithoutHistory(bb, animationDuration);
}
/**
* Moves the view to the target Boundingbox without saving the action in the history.
*
* @param bb target BoundingBox
* @param animationDuration the animation duration
*/
public void gotoBoundingBoxWithoutHistory(final BoundingBox bb, final int animationDuration) {
gotoBoundingBox(bb, false, true, animationDuration);
}
/**
* Moves the view to the target Boundingbox and saves the action in the history.
*
* @param bb target BoundingBox
*/
public void gotoBoundingBoxWithHistory(final BoundingBox bb) {
gotoBoundingBox(bb, true, true, animationDuration);
}
/**
* Returns a BoundingBox of the current view in another scale.
*
* @param scaleDenominator specific target scale
*
* @return DOCUMENT ME!
*/
public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) {
return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBox());
}
/**
* Returns the BoundingBox of the delivered BoundingBox in another scale.
*
* @param scaleDenominator specific target scale
* @param bb source BoundingBox
*
* @return DOCUMENT ME!
*/
public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) {
final double screenWidthInInch = getWidth() / screenResolution;
final double screenWidthInMeter = screenWidthInInch * 0.0254;
final double screenHeightInInch = getHeight() / screenResolution;
final double screenHeightInMeter = screenHeightInInch * 0.0254;
final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator;
final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator;
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
// transform the given bounding box to a metric coordinate system
bb = transformer.transformBoundingBox(bb, mappingModel.getSrs().getCode());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2);
final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2);
BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2),
midY
- (realWorldHeightInMeter / 2),
midX
+ (realWorldWidthInMeter / 2),
midY
+ (realWorldHeightInMeter / 2));
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
// transform the scaled bounding box to the current coordinate system
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
return scaledBox;
}
/**
* Calculate the current scaledenominator.
*
* @return DOCUMENT ME!
*/
public double getScaleDenominator() {
BoundingBox boundingBox = getCurrentBoundingBox();
final double screenWidthInInch = getWidth() / screenResolution;
final double screenWidthInMeter = screenWidthInInch * 0.0254;
final double screenHeightInInch = getHeight() / screenResolution;
final double screenHeightInMeter = screenHeightInInch * 0.0254;
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
boundingBox = transformer.transformBoundingBox(
boundingBox,
mappingModel.getSrs().getCode());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
final double realWorldWidthInMeter = boundingBox.getWidth();
return realWorldWidthInMeter / screenWidthInMeter;
}
/**
* Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code>
* DropTarget</code> registered with this listener.
*
* <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code>
* DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data
* object(s) to be transfered.</p>
*
* <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int
* dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P>
*
* <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be
* invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData()
* method.</P>
*
* <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the
* drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method.</P>
*
* <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code>
* Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only
* if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code>
* true</code>. Otherwise, the behavior of the call is implementation-dependent.</P>
*
* @param dtde the <code>DropTargetDropEvent</code>
*/
@Override
public void drop(final DropTargetDropEvent dtde) {
if (isDropEnabled(dtde)) {
try {
final MapDnDEvent mde = new MapDnDEvent();
mde.setDte(dtde);
final Point p = dtde.getLocation();
getCamera().getViewTransform().inverseTransform(p, p);
mde.setXPos(getWtst().getWorldX(p.getX()));
mde.setYPos(getWtst().getWorldY(p.getY()));
CismapBroker.getInstance().fireDropOnMap(mde);
} catch (final Exception ex) {
LOG.error("Error in drop", ex); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param dtde DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private boolean isDropEnabled(final DropTargetDropEvent dtde) {
if (ALKIS_PRINT.equals(getInteractionMode())) {
for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) {
// necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here
if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) {
return false;
}
}
}
return true;
}
/**
* Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site
* for the <code>DropTarget</code> registered with this listener.
*
* @param dte the <code>DropTargetEvent</code>
*/
@Override
public void dragExit(final DropTargetEvent dte) {
}
/**
* Called if the user has modified the current drop gesture.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dropActionChanged(final DropTargetDragEvent dtde) {
}
/**
* Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p
* site for the <code>DropTarget</code> registered with this listener.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dragOver(final DropTargetDragEvent dtde) {
try {
final MapDnDEvent mde = new MapDnDEvent();
mde.setDte(dtde);
// TODO: this seems to be buggy!
final Point p = dtde.getLocation();
getCamera().getViewTransform().inverseTransform(p, p);
mde.setXPos(getWtst().getWorldX(p.getX()));
mde.setYPos(getWtst().getWorldY(p.getY()));
CismapBroker.getInstance().fireDragOverMap(mde);
} catch (final Exception ex) {
LOG.error("Error in dragOver", ex); // NOI18N
}
}
/**
* Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for
* the <code>DropTarget</code> registered with this listener.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dragEnter(final DropTargetDragEvent dtde) {
}
/**
* Returns the PfeatureHashmap which assigns a Feature to a PFeature.
*
* @return DOCUMENT ME!
*/
public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() {
return pFeatureHM;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFixedMapExtent() {
return fixedMapExtent;
}
/**
* DOCUMENT ME!
*
* @param fixedMapExtent DOCUMENT ME!
*/
public void setFixedMapExtent(final boolean fixedMapExtent) {
this.fixedMapExtent = fixedMapExtent;
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(
StatusEvent.MAP_EXTEND_FIXED,
this.fixedMapExtent));
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFixedMapScale() {
return fixedMapScale;
}
/**
* DOCUMENT ME!
*
* @param fixedMapScale DOCUMENT ME!
*/
public void setFixedMapScale(final boolean fixedMapScale) {
this.fixedMapScale = fixedMapScale;
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(
StatusEvent.MAP_SCALE_FIXED,
this.fixedMapScale));
}
}
/**
* DOCUMENT ME!
*
* @param one DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
public void selectPFeatureManually(final PFeature one) {
if (one != null) {
featureCollection.select(one.getFeature());
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
public PFeature getSelectedNode() {
// gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist
// deshalb gebe ich mal nur das erste zur�ck
if (featureCollection.getSelectedFeatures().size() > 0) {
final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0];
if (selF == null) {
return null;
}
return pFeatureHM.get(selF);
} else {
return null;
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isInfoNodesVisible() {
return infoNodesVisible;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getPrintingFrameLayer() {
return printingFrameLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PrintingSettingsWidget getPrintingSettingsDialog() {
return printingSettingsDialog;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isInGlueIdenticalPointsMode() {
return inGlueIdenticalPointsMode;
}
/**
* DOCUMENT ME!
*
* @param inGlueIdenticalPointsMode DOCUMENT ME!
*/
public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) {
this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getHighlightingLayer() {
return highlightingLayer;
}
/**
* DOCUMENT ME!
*
* @param anno DOCUMENT ME!
*/
public void setPointerAnnotation(final PNode anno) {
((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno);
}
/**
* DOCUMENT ME!
*
* @param visib DOCUMENT ME!
*/
public void setPointerAnnotationVisibility(final boolean visib) {
if (getInputListener(MOTION) != null) {
((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib);
}
}
/**
* Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't
* equal MOTION.
*
* @return DOCUMENT ME!
*/
public boolean isPointerAnnotationVisible() {
if (getInputListener(MOTION) != null) {
return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible();
} else {
return false;
}
}
/**
* Returns a vector with different scales.
*
* @return DOCUMENT ME!
*/
public List<Scale> getScales() {
return scales;
}
/**
* Returns a list with different crs.
*
* @return DOCUMENT ME!
*/
public List<Crs> getCrsList() {
return crsList;
}
/**
* DOCUMENT ME!
*
* @return a transformer with the default crs as destination crs. The default crs is the first crs in the
* configuration file that has set the selected attribut on true). This crs must be metric.
*/
public CrsTransformer getMetricTransformer() {
return transformer;
}
/**
* Locks the MappingComponent.
*/
public void lock() {
locked = true;
}
/**
* Unlocks the MappingComponent.
*/
public void unlock() {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("unlock"); // NOI18N
}
}
locked = false;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N
}
}
gotoBoundingBoxWithHistory(currentBoundingBox);
}
/**
* Returns whether the MappingComponent is locked or not.
*
* @return DOCUMENT ME!
*/
public boolean isLocked() {
return locked;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isMainMappingComponent() {
return mainMappingComponent;
}
/**
* Returns the MementoInterface for redo-actions.
*
* @return DOCUMENT ME!
*/
public MementoInterface getMemRedo() {
return memRedo;
}
/**
* Returns the MementoInterface for undo-actions.
*
* @return DOCUMENT ME!
*/
public MementoInterface getMemUndo() {
return memUndo;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map<String, PBasicInputEventHandler> getInputEventListener() {
return inputEventListener;
}
/**
* DOCUMENT ME!
*
* @param inputEventListener DOCUMENT ME!
*/
public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) {
this.inputEventListener.clear();
this.inputEventListener.putAll(inputEventListener);
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
@Override
public synchronized void crsChanged(final CrsChangedEvent event) {
if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) {
if (locked) {
return;
}
try {
// the wtst object should not be null, so the getWtst method will be invoked
final WorldToScreenTransform oldWtst = getWtst();
final BoundingBox bbox = getCurrentBoundingBox(); // getCurrentBoundingBox();
final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode());
final BoundingBox newBbox = crsTransformer.transformBoundingBox(bbox, event.getFormerCrs().getCode());
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.setSrs(event.getCurrentCrs());
}
wtst = null;
getWtst();
gotoBoundingBoxWithoutHistory(newBbox, 0);
final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures());
featureCollection.removeAllFeatures();
featureCollection.addFeatures(list);
if (LOG.isDebugEnabled()) {
LOG.debug("debug features added: " + list.size());
}
// refresh all wfs layer
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.refreshWebFeatureServices();
alm.refreshShapeFileLayer();
}
// transform the highlighting layer
for (int i = 0; i < highlightingLayer.getChildrenCount(); ++i) {
final PNode node = highlightingLayer.getChild(i);
CrsTransformer.transformPNodeToGivenCrs(
node,
event.getFormerCrs().getCode(),
event.getCurrentCrs().getCode(),
oldWtst,
getWtst());
rescaleStickyNode(node);
}
} catch (final Exception e) {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"),
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"),
JOptionPane.ERROR_MESSAGE);
LOG.error("Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e);
resetCrs = true;
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.setSrs(event.getCurrentCrs());
CismapBroker.getInstance().setSrs(event.getFormerCrs());
}
} else {
resetCrs = false;
}
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public JInternalFrame getInternalWidget(final String name) {
if (this.internalWidgets.containsKey(name)) {
return this.internalWidgets.get(name);
} else {
LOG.warn("unknown internal widget '" + name + "'"); // NOI18N
return null;
}
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getInternalWidgetPosition(final String name) {
if (this.internalWidgetPositions.containsKey(name)) {
return this.internalWidgetPositions.get(name);
} else {
LOG.warn("unknown position for '" + name + "'"); // NOI18N
return -1;
}
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class MappingComponentRasterServiceListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
private final transient ServiceLayer rasterService;
private final XPImage pi;
private int position = -1;
//~ Constructors -------------------------------------------------------
/**
* Creates a new MappingComponentRasterServiceListener object.
*
* @param position DOCUMENT ME!
* @param pn DOCUMENT ME!
* @param rasterService DOCUMENT ME!
*/
public MappingComponentRasterServiceListener(final int position,
final PNode pn,
final ServiceLayer rasterService) {
this.position = position;
this.rasterService = rasterService;
if (pn instanceof XPImage) {
this.pi = (XPImage)pn;
} else {
this.pi = null;
}
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
fireActivityChanged();
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
this.log.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() // NOI18N
+ " Errors: " // NOI18N
+ e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N
fireActivityChanged();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
final Point2D localOrigin = getCamera().getViewBounds().getOrigin();
final double localScale = getCamera().getViewScale();
final PBounds localBounds = getCamera().getViewBounds();
final Object o = e.getRetrievedObject();
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
final Runnable paintImageOnMap = new Runnable() {
@Override
public void run() {
fireActivityChanged();
if ((o instanceof Image) && (e.isHasErrors() == false)) {
// TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden
if (isBackgroundEnabled()) {
final Image i = (Image)o;
if (rasterService.getName().startsWith("prefetching")) { // NOI18N
final double x = localOrigin.getX() - localBounds.getWidth();
final double y = localOrigin.getY() - localBounds.getHeight();
pi.setImage(i, 0);
pi.setScale(3 / localScale);
pi.setOffset(x, y);
} else {
pi.setImage(i, animationDuration * 2);
pi.setScale(1 / localScale);
pi.setOffset(localOrigin);
MappingComponent.this.repaint();
}
}
}
}
};
if (EventQueue.isDispatchThread()) {
paintImageOnMap.run();
} else {
EventQueue.invokeLater(paintImageOnMap);
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
this.log.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getPosition() {
return position;
}
/**
* DOCUMENT ME!
*
* @param position DOCUMENT ME!
*/
public void setPosition(final int position) {
this.position = position;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class DocumentProgressListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
/** Displays the loading progress of Documents, e.g. SHP Files */
private final transient DocumentProgressWidget documentProgressWidget;
private transient long requestId = -1;
//~ Constructors -------------------------------------------------------
/**
* Creates a new DocumentProgressListener object.
*/
public DocumentProgressListener() {
documentProgressWidget = new DocumentProgressWidget();
documentProgressWidget.setVisible(false);
if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) {
MappingComponent.this.addInternalWidget(
MappingComponent.PROGRESSWIDGET,
MappingComponent.POSITION_SOUTHWEST,
documentProgressWidget);
}
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalStarted aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != -1) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = e.getRequestIdentifier();
this.documentProgressWidget.setServiceName(e.getRetrievalService().toString());
this.documentProgressWidget.setProgress(-1);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalProgress, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: initialisation progress: " + e.getPercentageDone()); // NOI18N
}
}
this.documentProgressWidget.setProgress(e.getPercentageDone());
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalComplete, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N
}
e.getRetrievalService().removeRetrievalListener(this);
this.requestId = -1;
this.documentProgressWidget.setProgress(100);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalAborted aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = -1;
this.documentProgressWidget.setProgress(0);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalError aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = -1;
e.getRetrievalService().removeRetrievalListener(this);
this.documentProgressWidget.setProgress(0);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public long getRequestId() {
return this.requestId;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class MappingComponentFeatureServiceListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
private final transient ServiceLayer featureService;
private final transient PLayer parent;
private long requestIdentifier;
private Thread completionThread;
private final List deletionCandidates;
private final List twins;
//~ Constructors -------------------------------------------------------
/**
* Creates a new MappingComponentFeatureServiceListener.
*
* @param featureService the featureretrievalservice
* @param parent the featurelayer (PNode) connected with the servicelayer
*/
public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) {
this.featureService = featureService;
this.parent = parent;
this.deletionCandidates = new ArrayList();
this.twins = new ArrayList();
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
requestIdentifier = e.getRequestIdentifier();
}
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N
}
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: "
+ e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress()
+ ")"); // NOI18N
}
}
fireActivityChanged();
// TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das
// flüssiger ist
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
this.log.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: "
+ (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N
}
}
if (e.isInitialisationEvent()) {
this.log.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: initialisation complete"); // NOI18N
fireActivityChanged();
return;
}
if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N
completionThread.interrupt();
}
if (e.getRequestIdentifier() < requestIdentifier) {
if (DEBUG) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N
}
((RetrievalServiceLayer)featureService).setProgress(-1);
fireActivityChanged();
return;
}
final List newFeatures = new ArrayList();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
((RetrievalServiceLayer)featureService).setProgress(-1);
parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible());
}
});
// clear all old data to delete twins
deletionCandidates.clear();
twins.clear();
// if it's a refresh, add all old features which should be deleted in the
// newly acquired featurecollection
if (!e.isRefreshExisting()) {
deletionCandidates.addAll(parent.getChildrenReference());
}
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N
}
}
// only start parsing the features if there are no errors and a correct collection
if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) {
completionThread = new Thread() {
@Override
public void run() {
// this is the collection with the retrieved features
final List features = new ArrayList((Collection)e.getRetrievedObject());
final int size = features.size();
int counter = 0;
final Iterator it = features.iterator();
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(featureService + "[" + e.getRequestIdentifier() + " ("
+ requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N
}
}
while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()
&& it.hasNext()) {
counter++;
final Object o = it.next();
if (o instanceof Feature) {
final PFeature p = new PFeature(((Feature)o),
wtst,
clip_offset_x,
clip_offset_y,
MappingComponent.this);
PFeature twin = null;
for (final Object tester : deletionCandidates) {
// if tester and PFeature are FeatureWithId-objects
if ((((PFeature)tester).getFeature() instanceof FeatureWithId)
&& (p.getFeature() instanceof FeatureWithId)) {
final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId();
final int id2 = ((FeatureWithId)(p.getFeature())).getId();
if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id
if (id1 == id2) {
twin = ((PFeature)tester);
break;
}
} else { // else test the geometry for equality
if (((PFeature)tester).getFeature().getGeometry().equals(
p.getFeature().getGeometry())) {
twin = ((PFeature)tester);
break;
}
}
} else { // no FeatureWithId, test geometries for
// equality
if (((PFeature)tester).getFeature().getGeometry().equals(
p.getFeature().getGeometry())) {
twin = ((PFeature)tester);
break;
}
}
}
// if a twin is found remove him from the deletion candidates
// and add him to the twins
if (twin != null) {
deletionCandidates.remove(twin);
twins.add(twin);
} else { // else add the PFeature to the new features
newFeatures.add(p);
}
// calculate the advance of the progressbar
// fire event only wheen needed
final int currentProgress = (int)((double)counter / (double)size * 100d);
if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) {
((RetrievalServiceLayer)featureService).setProgress(currentProgress);
fireActivityChanged();
}
}
}
if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) {
// after all features are computed do stuff on the EDT
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N
}
}
// if it's a refresh, delete all previous features
if (e.isRefreshExisting()) {
parent.removeAllChildren();
}
final List deleteFeatures = new ArrayList();
for (final Object o : newFeatures) {
parent.addChild((PNode)o);
}
// set the prograssbar to full
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: set progress to 100"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(100);
fireActivityChanged();
// repaint the featurelayer
parent.repaint();
// remove stickyNode from all deletionCandidates and add
// each to the new deletefeature-collection
for (final Object o : deletionCandidates) {
if (o instanceof PFeature) {
final PNode p = ((PFeature)o).getPrimaryAnnotationNode();
if (p != null) {
removeStickyNode(p);
}
deleteFeatures.add(o);
}
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: parentCount before:"
+ parent.getChildrenCount()); // NOI18N
}
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: deleteFeatures="
+ deleteFeatures.size()); // + " :" +
// deleteFeatures);//NOI18N
}
}
parent.removeChildren(deleteFeatures);
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: parentCount after:"
+ parent.getChildrenCount()); // NOI18N
}
}
if (LOG.isInfoEnabled()) {
LOG.info(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: "
+ parent.getChildrenCount()
+ " features retrieved or updated"); // NOI18N
}
rescaleStickyNodes();
} catch (final Exception exception) {
log.warn(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: Fehler beim Aufr\u00E4umen",
exception); // NOI18N
}
}
});
} else {
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(featureService + "[" + e.getRequestIdentifier() + " ("
+ requestIdentifier
+ ")]: completion thread Interrupted or synchronisation lost"); // NOI18N
}
}
}
}
};
completionThread.setPriority(Thread.NORM_PRIORITY);
if (requestIdentifier == e.getRequestIdentifier()) {
completionThread.start();
} else {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: completion thread Interrupted or synchronisation lost"); // NOI18N
}
}
}
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: aborted, TaskCounter:" + taskCounter); // NOI18N
if (completionThread != null) {
completionThread.interrupt();
}
if (e.getRequestIdentifier() < requestIdentifier) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(-1);
} else {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(0);
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, featureService));
}
}
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
class ImageSelection implements Transferable {
//~ Instance fields --------------------------------------------------------
private Image image;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ImageSelection object.
*
* @param image DOCUMENT ME!
*/
public ImageSelection(final Image image) {
this.image = image;
}
//~ Methods ----------------------------------------------------------------
/**
* Returns supported flavors.
*
* @return DOCUMENT ME!
*/
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
/**
* Returns true if flavor is supported.
*
* @param flavor DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
/**
* Returns image.
*
* @param flavor DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws UnsupportedFlavorException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!DataFlavor.imageFlavor.equals(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}
}
| true | true | public void setInteractionMode(final String interactionMode) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:"
+ this.interactionMode + "",
new Exception()); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
setPointerAnnotationVisibility(false);
if (getPrintingFrameLayer().getChildrenCount() > 1) {
getPrintingFrameLayer().removeAllChildren();
}
if (this.interactionMode != null) {
if (interactionMode.equals(FEATURE_INFO)) {
((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo()
.setVisible(true);
} else {
((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo()
.setVisible(false);
}
if (isReadOnly()) {
((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class);
}
final PInputEventListener pivl = this.getInputListener(this.interactionMode);
if (pivl != null) {
removeInputEventListener(pivl);
} else {
LOG.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N
}
if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) {
featureCollection.unselectAll();
}
if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEAR_REFERENCING)
|| interactionMode.equals(SPLIT_POLYGON))
&& (this.readOnly == false)) {
featureSelectionChanged(null);
}
if (interactionMode.equals(JOIN_POLYGONS)) {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
}
final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent(
this,
PROPERTY_MAP_INTERACTION_MODE,
this.interactionMode,
interactionMode);
this.interactionMode = interactionMode;
final PInputEventListener pivl = getInputListener(interactionMode);
if (pivl != null) {
addInputEventListener(pivl);
propertyChangeSupport.firePropertyChange(interactionModeChangedEvent);
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode));
} else {
LOG.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N
}
} catch (final Exception e) {
LOG.error("Fehler beim Ändern des InteractionModes", e); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
@Deprecated
public void formComponentResized(final ComponentEvent evt) {
this.componentResizedDelayed();
}
/**
* Resizes the map and does not reload all services.
*
* @see #componentResizedDelayed()
*/
public void componentResizedIntermediate() {
if (!this.isLocked()) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N
}
}
if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) {
if (mappingModel != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N
}
}
if (MappingComponent.this.currentBoundingBox == null) {
LOG.error("currentBoundingBox is null"); // NOI18N
currentBoundingBox = getCurrentBoundingBox();
}
// rescale map
if (historyModel.getCurrentElement() != null) {
final PBounds bounds = (PBounds)historyModel.getCurrentElement();
if (bounds.getWidth() < 0) {
bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight());
}
if (bounds.getHeight() < 0) {
bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1));
}
getCamera().animateViewToCenterBounds(bounds, true, animationDuration);
}
}
}
// move internal widgets
for (final String internalWidget : this.internalWidgets.keySet()) {
if (this.getInternalWidget(internalWidget).isVisible()) {
showInternalWidget(internalWidget, true, 0);
}
}
}
}
/**
* Resizes the map and reloads all services.
*
* @see #componentResizedIntermediate()
*/
public void componentResizedDelayed() {
if (!this.isLocked()) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N
}
}
if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) {
if (mappingModel != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N
}
}
if (MappingComponent.this.currentBoundingBox == null) {
LOG.error("currentBoundingBox is null"); // NOI18N
currentBoundingBox = getCurrentBoundingBox();
}
gotoBoundsWithoutHistory((PBounds)historyModel.getCurrentElement());
// move internal widgets
for (final String internalWidget : this.internalWidgets.keySet()) {
if (this.getInternalWidget(internalWidget).isVisible()) {
showInternalWidget(internalWidget, true, 0);
}
}
}
}
} catch (final Exception t) {
LOG.error("Fehler in formComponentResized()", t); // NOI18N
}
}
}
/**
* syncSelectedObjectPresenter(int i).
*
* @param i DOCUMENT ME!
*/
public void syncSelectedObjectPresenter(final int i) {
selectedObjectPresenter.setVisible(true);
if (featureCollection.getSelectedFeatures().size() > 0) {
if (featureCollection.getSelectedFeatures().size() == 1) {
final PFeature selectedFeature = (PFeature)pFeatureHM.get(
featureCollection.getSelectedFeatures().toArray()[0]);
if (selectedFeature != null) {
selectedObjectPresenter.getCamera()
.animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2);
}
} else {
// todo
}
} else {
LOG.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N
}
}
/**
* Returns the current featureCollection.
*
* @return DOCUMENT ME!
*/
public FeatureCollection getFeatureCollection() {
return featureCollection;
}
/**
* Replaces the old featureCollection with a new one.
*
* @param featureCollection the new featureCollection
*/
public void setFeatureCollection(final FeatureCollection featureCollection) {
this.featureCollection = featureCollection;
featureCollection.addFeatureCollectionListener(this);
}
/**
* DOCUMENT ME!
*
* @param visibility DOCUMENT ME!
*/
public void setFeatureCollectionVisibility(final boolean visibility) {
featureLayer.setVisible(visibility);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFeatureCollectionVisible() {
return featureLayer.getVisible();
}
/**
* Adds a new mapservice at a specific place of the layercontrols.
*
* @param mapService the new mapservice
* @param position the index where to position the mapservice
*/
public void addMapService(final MapService mapService, final int position) {
try {
PNode p = new PNode();
if (mapService instanceof RasterMapService) {
LOG.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N
if (mapService.getPNode() instanceof XPImage) {
p = (XPImage)mapService.getPNode();
} else {
p = new XPImage();
mapService.setPNode(p);
}
mapService.addRetrievalListener(new MappingComponentRasterServiceListener(
position,
p,
(ServiceLayer)mapService));
} else {
LOG.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName()
+ ")"); // NOI18N
p = new PLayer();
mapService.setPNode(p);
if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService
+ "): isDocumentFeatureService, checking document size"); // NOI18N
}
}
final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService;
if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) {
LOG.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '"
+ documentFeatureService.getName() + "' size of "
+ (documentFeatureService.getDocumentSize() / 1000000)
+ "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000)
+ "MB)"); // NOI18N
if (this.documentProgressListener == null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService
+ "): lazy instantiation of documentProgressListener"); // NOI18N
}
}
this.documentProgressListener = new DocumentProgressListener();
}
if (this.documentProgressListener.getRequestId() != -1) {
LOG.error("FeatureMapService(" + mapService
+ "): The documentProgressListener is already in use by request '"
+ this.documentProgressListener.getRequestId()
+ ", document progress cannot be tracked"); // NOI18N
} else {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N
}
}
documentFeatureService.addRetrievalListener(this.documentProgressListener);
}
}
}
mapService.addRetrievalListener(new MappingComponentFeatureServiceListener(
(ServiceLayer)mapService,
(PLayer)mapService.getPNode()));
}
p.setTransparency(mapService.getTranslucency());
p.setVisible(mapService.isVisible());
mapServicelayer.addChild(p);
} catch (final Exception e) {
LOG.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + e.getMessage(), e); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param mm DOCUMENT ME!
*/
public void preparationSetMappingModel(final MappingModel mm) {
mappingModel = mm;
}
/**
* Sets a new mappingmodel in this MappingComponent.
*
* @param mm the new mappingmodel
*/
public void setMappingModel(final MappingModel mm) {
LOG.info("setMappingModel"); // NOI18N
// FIXME: why is the default uncaught exception handler set in such a random place?
if (Thread.getDefaultUncaughtExceptionHandler() == null) {
LOG.info("setDefaultUncaughtExceptionHandler"); // NOI18N
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
LOG.error("Error", e);
}
});
}
mappingModel = mm;
currentBoundingBox = mm.getInitialBoundingBox();
final Runnable r = new Runnable() {
@Override
public void run() {
mappingModel.addMappingModelListener(MappingComponent.this);
final TreeMap rs = mappingModel.getRasterServices();
// Rückwärts wegen der Reihenfolge der Layer im Layer Widget
final Iterator it = rs.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if (o instanceof MapService) {
addMapService(((MapService)o), rsi);
}
}
adjustLayers();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Set Mapping Modell done"); // NOI18N
}
}
}
};
CismetThreadPool.execute(r);
}
/**
* Returns the current mappingmodel.
*
* @return current mappingmodel
*/
public MappingModel getMappingModel() {
return mappingModel;
}
/**
* Animates a component to a given x/y-coordinate in a given time.
*
* @param c the component to animate
* @param toX final x-position
* @param toY final y-position
* @param animationDuration duration of the animation
* @param hideAfterAnimation should the component be hidden after animation?
*/
private void animateComponent(final JComponent c,
final int toX,
final int toY,
final int animationDuration,
final boolean hideAfterAnimation) {
if (animationDuration > 0) {
final int x = (int)c.getBounds().getX() - toX;
final int y = (int)c.getBounds().getY() - toY;
int sx;
int sy;
if (x > 0) {
sx = -1;
} else {
sx = 1;
}
if (y > 0) {
sy = -1;
} else {
sy = 1;
}
int big;
if (Math.abs(x) > Math.abs(y)) {
big = Math.abs(x);
} else {
big = Math.abs(y);
}
final int sleepy;
if ((animationDuration / big) < 1) {
sleepy = 1;
} else {
sleepy = animationDuration / big;
}
final int directionY = sy;
final int directionX = sx;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY
+ ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX="
+ toX + ", toY=" + toY); // NOI18N
}
}
final Thread timer = new Thread() {
@Override
public void run() {
while (!isInterrupted()) {
try {
sleep(sleepy);
} catch (final Exception iex) {
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
int currentY = (int)c.getBounds().getY();
int currentX = (int)c.getBounds().getX();
if (currentY != toY) {
currentY = currentY + directionY;
}
if (currentX != toX) {
currentX = currentX + directionX;
}
c.setBounds(currentX, currentY, c.getWidth(), c.getHeight());
}
});
if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) {
if (hideAfterAnimation) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
c.setVisible(false);
c.hide();
}
});
}
break;
}
}
}
};
timer.setPriority(Thread.NORM_PRIORITY);
timer.start();
} else {
c.setBounds(toX, toY, c.getWidth(), c.getHeight());
if (hideAfterAnimation) {
c.setVisible(false);
}
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
@Deprecated
public NewSimpleInternalLayerWidget getInternalLayerWidget() {
return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET);
}
/**
* Adds a new internal widget to the map.<br/>
* If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget
* will be added. If a widget with a different name already exisit at the same {@code position} the new widget will
* not be added and the operation returns {@code false}.
*
* @param name unique name of the widget
* @param position position of the widget
* @param widget the widget
*
* @return {@code true} if the widget could be added, {@code false} otherwise
*
* @see #POSITION_NORTHEAST
* @see #POSITION_NORTHWEST
* @see #POSITION_SOUTHEAST
* @see #POSITION_SOUTHWEST
*/
public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) {
if (LOG.isDebugEnabled()) {
LOG.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N
}
if (this.internalWidgets.containsKey(name)) {
LOG.warn("widget '" + name + "' already added, removing old widget"); // NOI18N
this.remove(this.getInternalWidget(name));
} else if (this.internalWidgetPositions.containsValue(position)) {
LOG.warn("widget position '" + position + "' already taken"); // NOI18N
return false;
}
this.internalWidgets.put(name, widget);
this.internalWidgetPositions.put(name, position);
widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N
this.add(widget);
widget.pack();
return true;
}
/**
* Removes an existing internal widget from the map.
*
* @param name name of the widget to be removed
*
* @return {@code true} id the widget was found and removed, {@code false} otherwise
*/
public boolean removeInternalWidget(final String name) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing internal widget '" + name + "'"); // NOI18N
}
if (!this.internalWidgets.containsKey(name)) {
LOG.warn("widget '" + name + "' not found"); // NOI18N
return false;
}
this.remove(this.getInternalWidget(name));
this.internalWidgets.remove(name);
this.internalWidgetPositions.remove(name);
return true;
}
/**
* Shows an InternalWidget by sliding it into the mappingcomponent.
*
* @param name name of the internl component to show
* @param visible should the widget be visible after the animation?
* @param animationDuration duration of the animation
*
* @return {@code true} if the operation was successful, {@code false} otherwise
*/
public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) {
final JInternalFrame internalWidget = this.getInternalWidget(name);
if (internalWidget == null) {
return false;
}
final int positionX;
final int positionY;
final int widgetPosition = this.getInternalWidgetPosition(name);
final boolean isHigher = (getHeight() < (internalWidget.getHeight() + 2)) && (getHeight() > 0);
final boolean isWider = (getWidth() < (internalWidget.getWidth() + 2)) && (getWidth() > 0);
switch (widgetPosition) {
case POSITION_NORTHWEST: {
positionX = 1;
positionY = 1;
break;
}
case POSITION_SOUTHWEST: {
positionX = 1;
positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1);
break;
}
case POSITION_NORTHEAST: {
positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1);
positionY = 1;
break;
}
case POSITION_SOUTHEAST: {
positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1);
positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1);
break;
}
default: {
LOG.warn("unkown widget position?!"); // NOI18N
return false;
}
}
if (visible) {
final int toY;
if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) {
if (isHigher) {
toY = getHeight() - 1;
} else {
toY = positionY - internalWidget.getHeight() - 1;
}
} else {
if (isHigher) {
toY = getHeight() + 1;
} else {
toY = positionY + internalWidget.getHeight() + 1;
}
}
internalWidget.setBounds(
positionX,
toY,
isWider ? (getWidth() - 2) : internalWidget.getWidth(),
isHigher ? (getHeight() - 2) : internalWidget.getHeight());
internalWidget.setVisible(true);
internalWidget.show();
animateComponent(internalWidget, positionX, positionY, animationDuration, false);
} else {
internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight());
int toY = positionY + internalWidget.getHeight() + 1;
if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) {
toY = positionY - internalWidget.getHeight() - 1;
}
animateComponent(internalWidget, positionX, toY, animationDuration, true);
}
return true;
}
/**
* DOCUMENT ME!
*
* @param visible DOCUMENT ME!
* @param animationDuration DOCUMENT ME!
*/
@Deprecated
public void showInternalLayerWidget(final boolean visible, final int animationDuration) {
this.showInternalWidget(LAYERWIDGET, visible, animationDuration);
}
/**
* Returns a boolean, if the InternalLayerWidget is visible.
*
* @return true, if visible, else false
*/
@Deprecated
public boolean isInternalLayerWidgetVisible() {
return this.getInternalLayerWidget().isVisible();
}
/**
* Returns a boolean, if the InternalWidget is visible.
*
* @param name name of the widget
*
* @return true, if visible, else false
*/
public boolean isInternalWidgetVisible(final String name) {
final JInternalFrame widget = this.getInternalWidget(name);
if (widget != null) {
return widget.isVisible();
}
return false;
}
/**
* Moves the camera to the initial bounding box (e.g. if the home-button is pressed).
*/
public void gotoInitialBoundingBox() {
final double x1;
final double y1;
final double x2;
final double y2;
final double w;
final double h;
x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1());
y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1());
x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2());
y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2());
final Rectangle2D home = new Rectangle2D.Double();
home.setRect(x1, y2, x2 - x1, y1 - y2);
getCamera().animateViewToCenterBounds(home, true, animationDuration);
if (getCamera().getViewTransform().getScaleY() < 0) {
LOG.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N
}
setNewViewBounds(home);
queryServices();
}
/**
* Refreshs all registered services.
*/
public void queryServices() {
if (newViewBounds != null) {
addToHistory(new PBoundsWithCleverToString(
new PBounds(newViewBounds),
wtst,
mappingModel.getSrs().getCode()));
queryServicesWithoutHistory();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServices()"); // NOI18N
}
}
rescaleStickyNodes();
}
}
/**
* Forces all services to refresh themselves.
*/
public void refresh() {
forceQueryServicesWithoutHistory();
}
/**
* Forces all services to refresh themselves.
*/
private void forceQueryServicesWithoutHistory() {
queryServicesWithoutHistory(true);
}
/**
* Refreshs all services, but not forced.
*/
private void queryServicesWithoutHistory() {
queryServicesWithoutHistory(false);
}
/**
* Waits until all animations are done, then iterates through all registered services and calls handleMapService()
* for each.
*
* @param forced forces the refresh
*/
private void queryServicesWithoutHistory(final boolean forced) {
if (forced && mainMappingComponent) {
CismapBroker.getInstance().fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_RESET, this));
}
if (!locked) {
final Runnable r = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception doNothing) {
}
}
CismapBroker.getInstance().fireMapBoundsChanged();
if (MappingComponent.this.isBackgroundEnabled()) {
final TreeMap rs = mappingModel.getRasterServices();
final TreeMap fs = mappingModel.getFeatureServices();
for (final Iterator it = rs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if (o instanceof MapService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N
}
}
handleMapService(rsi, (MapService)o, forced);
} else {
LOG.warn("service is not of type MapService:" + o); // NOI18N
}
}
for (final Iterator it = fs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int fsi = ((Integer)key).intValue();
final Object o = fs.get(key);
if (o instanceof MapService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N
}
}
handleMapService(fsi, (MapService)o, forced);
} else {
LOG.warn("service is not of type MapService:" + o); // NOI18N
}
}
}
}
};
CismetThreadPool.execute(r);
}
}
/**
* queryServicesIndependentFromMap.
*
* @param width DOCUMENT ME!
* @param height DOCUMENT ME!
* @param bb DOCUMENT ME!
* @param rl DOCUMENT ME!
*/
public void queryServicesIndependentFromMap(final int width,
final int height,
final BoundingBox bb,
final RetrievalListener rl) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N
}
}
final Runnable r = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception doNothing) {
}
}
if (MappingComponent.this.isBackgroundEnabled()) {
final TreeMap rs = mappingModel.getRasterServices();
final TreeMap fs = mappingModel.getFeatureServices();
for (final Iterator it = rs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer)
&& ((ServiceLayer)o).isEnabled()
&& (o instanceof RetrievalServiceLayer)
&& ((RetrievalServiceLayer)o).getPNode().getVisible()) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap: cloning '"
+ o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N
}
}
AbstractRetrievalService r;
if (o instanceof WebFeatureService) {
final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o)
.clone();
wfsClone.removeAllListeners();
r = wfsClone;
} else {
r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners();
}
r.addRetrievalListener(rl);
((ServiceLayer)r).setLayerPosition(rsi);
handleMapService(rsi, (MapService)r, width, height, bb, true);
} catch (final Exception t) {
LOG.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N
}
} else {
LOG.warn("ignoring service '" + o + "' for printing"); // NOI18N
}
}
for (final Iterator it = fs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int fsi = ((Integer)key).intValue();
final Object o = fs.get(key);
if (o instanceof AbstractRetrievalService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap: cloning '"
+ o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N
}
}
AbstractRetrievalService r;
if (o instanceof WebFeatureService) {
final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o)
.clone();
wfsClone.removeAllListeners();
r = (AbstractRetrievalService)o;
} else {
r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners();
}
r.addRetrievalListener(rl);
((ServiceLayer)r).setLayerPosition(fsi);
handleMapService(fsi, (MapService)r, 0, 0, bb, true);
}
}
}
}
};
CismetThreadPool.execute(r);
}
/**
* former synchronized method.
*
* @param position DOCUMENT ME!
* @param service rs
* @param forced DOCUMENT ME!
*/
public void handleMapService(final int position, final MapService service, final boolean forced) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("in handleRasterService: " + service + "("
+ Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N
}
}
final PBounds bounds = getCamera().getViewBounds();
final BoundingBox bb = new BoundingBox();
final double x1 = getWtst().getWorldX(bounds.getMinX());
final double y1 = getWtst().getWorldY(bounds.getMaxY());
final double x2 = getWtst().getWorldX(bounds.getMaxX());
final double y2 = getWtst().getWorldY(bounds.getMinY());
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Bounds=" + bounds); // NOI18N
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N
}
}
if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N
bb.setX1(x1 - (x2 - x1));
bb.setY1(y1 - (y2 - y1));
bb.setX2(x2 + (x2 - x1));
bb.setY2(y2 + (y2 - y1));
} else {
bb.setX1(x1);
bb.setY1(y1);
bb.setX2(x2);
bb.setY2(y2);
}
handleMapService(position, service, getWidth(), getHeight(), bb, forced);
}
/**
* former synchronized method.
*
* @param position DOCUMENT ME!
* @param rs DOCUMENT ME!
* @param width DOCUMENT ME!
* @param height DOCUMENT ME!
* @param bb DOCUMENT ME!
* @param forced DOCUMENT ME!
*/
private void handleMapService(final int position,
final MapService rs,
final int width,
final int height,
final BoundingBox bb,
final boolean forced) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("handleMapService: " + rs); // NOI18N
}
}
rs.setSize(height, width);
if (((ServiceLayer)rs).isEnabled()) {
synchronized (serviceFuturesMap) {
final Future<?> sf = serviceFuturesMap.get(rs);
if ((sf == null) || sf.isDone()) {
final Runnable serviceCall = new Runnable() {
@Override
public void run() {
try {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception e) {
}
}
rs.setBoundingBox(bb);
if (rs instanceof FeatureAwareRasterService) {
((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection);
}
rs.retrieve(forced);
} finally {
serviceFuturesMap.remove(rs);
}
}
};
synchronized (serviceFuturesMap) {
serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall));
}
}
}
}
}
/**
* Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it.
*
* @return new WorldToScreenTransform or null
*/
public WorldToScreenTransform getWtst() {
try {
if (wtst == null) {
final double y_real = mappingModel.getInitialBoundingBox().getY2()
- mappingModel.getInitialBoundingBox().getY1();
final double x_real = mappingModel.getInitialBoundingBox().getX2()
- mappingModel.getInitialBoundingBox().getX1();
double clip_height;
double clip_width;
double x_screen = getWidth();
double y_screen = getHeight();
if (x_screen == 0) {
x_screen = 100;
}
if (y_screen == 0) {
y_screen = 100;
}
if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert
clip_height = x_screen * y_real / x_real;
clip_width = x_screen;
clip_offset_y = 0; // (y_screen-clip_height)/2;
clip_offset_x = 0;
} else { // Y ist Bestimmer
clip_height = y_screen;
clip_width = y_screen * x_real / y_real;
clip_offset_y = 0;
clip_offset_x = 0; // (x_screen-clip_width)/2;
}
wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),
mappingModel.getInitialBoundingBox().getY2());
}
return wtst;
} catch (final Exception t) {
LOG.error("Fehler in getWtst()", t); // NOI18N
return null;
}
}
/**
* Resets the current WorldToScreenTransformation.
*/
public void resetWtst() {
wtst = null;
}
/**
* Returns 0.
*
* @return DOCUMENT ME!
*/
public double getClip_offset_x() {
return 0; // clip_offset_x;
}
/**
* Assigns a new value to the x-clip-offset.
*
* @param clip_offset_x new clipoffset
*/
public void setClip_offset_x(final double clip_offset_x) {
this.clip_offset_x = clip_offset_x;
}
/**
* Returns 0.
*
* @return DOCUMENT ME!
*/
public double getClip_offset_y() {
return 0; // clip_offset_y;
}
/**
* Assigns a new value to the y-clip-offset.
*
* @param clip_offset_y new clipoffset
*/
public void setClip_offset_y(final double clip_offset_y) {
this.clip_offset_y = clip_offset_y;
}
/**
* Returns the rubberband-PLayer.
*
* @return DOCUMENT ME!
*/
public PLayer getRubberBandLayer() {
return rubberBandLayer;
}
/**
* Assigns a given PLayer to the variable rubberBandLayer.
*
* @param rubberBandLayer a PLayer
*/
public void setRubberBandLayer(final PLayer rubberBandLayer) {
this.rubberBandLayer = rubberBandLayer;
}
/**
* Sets new viewbounds.
*
* @param r2d Rectangle2D
*/
public void setNewViewBounds(final Rectangle2D r2d) {
newViewBounds = r2d;
}
/**
* Will be called if the selection of features changes. It selects the PFeatures connected to the selected features
* of the featurecollectionevent and moves them to the front. Also repaints handles at the end.
*
* @param fce featurecollectionevent with selected features
*/
@Override
public void featureSelectionChanged(final FeatureCollectionEvent fce) {
final Collection allChildren = featureLayer.getChildrenReference();
final ArrayList<PFeature> all = new ArrayList<PFeature>();
for (final Object o : allChildren) {
if (o instanceof PFeature) {
all.add((PFeature)o);
} else if (o instanceof PLayer) {
// Handling von Feature-Gruppen-Layer, welche als Kinder dem Feature Layer hinzugefügt wurden
all.addAll(((PLayer)o).getChildrenReference());
}
}
// final Collection<PFeature> all = featureLayer.getChildrenReference();
for (final PFeature f : all) {
f.setSelected(false);
}
Collection<Feature> c;
if (fce != null) {
c = fce.getFeatureCollection().getSelectedFeatures();
} else {
c = featureCollection.getSelectedFeatures();
}
////handle featuregroup select-delegation////
final Set<Feature> selectionResult = new HashSet<Feature>();
for (final Feature current : c) {
if (current instanceof FeatureGroup) {
selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current));
} else {
selectionResult.add(current);
}
}
c = selectionResult;
for (final Feature f : c) {
if (f != null) {
final PFeature feature = getPFeatureHM().get(f);
if (feature != null) {
if (feature.getParent() != null) {
feature.getParent().moveToFront();
}
feature.setSelected(true);
feature.moveToFront();
// Fuer den selectedObjectPresenter (Eigener PCanvas)
syncSelectedObjectPresenter(1000);
} else {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
}
}
showHandles(false);
}
/**
* Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on
* each feature of the given featurecollectionevent. Repaints handles at the end.
*
* @param fce featurecollectionevent with changed features
*/
@Override
public void featuresChanged(final FeatureCollectionEvent fce) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("featuresChanged"); // NOI18N
}
}
final List<Feature> list = new ArrayList<Feature>();
list.addAll(fce.getEventFeatures());
for (final Feature elem : list) {
reconsiderFeature(elem);
}
showHandles(false);
}
/**
* Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls
* following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode()
*
* @param fce featurecollectionevent with features to reconsile
*/
@Override
public void featureReconsiderationRequested(final FeatureCollectionEvent fce) {
for (final Feature f : fce.getEventFeatures()) {
if (f != null) {
final PFeature node = pFeatureHM.get(f);
if (node != null) {
node.syncGeometry();
node.visualize();
node.resetInfoNodePosition();
node.refreshInfoNode();
repaint();
}
}
}
}
/**
* Method is deprecated and deactivated. Does nothing!!
*
* @param fce FeatureCollectionEvent with features to add
*/
@Override
@Deprecated
public void featuresAdded(final FeatureCollectionEvent fce) {
}
/**
* Method is deprecated and deactivated. Does nothing!!
*
* @deprecated DOCUMENT ME!
*/
@Override
@Deprecated
public void featureCollectionChanged() {
}
/**
* Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a
* checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent.
*
* @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice
*/
@Override
public void allFeaturesRemoved(final FeatureCollectionEvent fce) {
for (final PFeature feature : pFeatureHM.values()) {
feature.cleanup();
}
stickyPNodes.clear();
pFeatureHM.clear();
featureLayer.removeAllChildren();
// Lösche alle Features in den Gruppen-Layer, aber füge den Gruppen-Layer wieder dem FeatureLayer hinzu
for (final PLayer layer : featureGrpLayerMap.values()) {
layer.removeAllChildren();
featureLayer.addChild(layer);
}
checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce);
}
/**
* Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining
* supporting rasterservices and paints handles at the end.
*
* @param fce FeatureCollectionEvent with features to remove
*/
@Override
public void featuresRemoved(final FeatureCollectionEvent fce) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("featuresRemoved"); // NOI18N
}
}
removeFeatures(fce.getEventFeatures());
checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce);
showHandles(false);
}
/**
* Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and
* which need a refresh.
*
* @param fce FeatureCollectionEvent with removed features
*/
private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) {
final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved =
new HashSet<FeatureAwareRasterService>();
final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed =
new HashSet<FeatureAwareRasterService>();
final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>();
for (final Feature f : getFeatureCollection().getAllFeatures()) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N
}
}
rasterServices.add(rs); // DANGER
}
}
for (final Feature f : fce.getEventFeatures()) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N
}
}
if (rasterServices.contains(rs)) {
for (final Object o : getMappingModel().getRasterServices().values()) {
final MapService r = (MapService)o;
if (r.equals(rs)) {
rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r);
}
}
} else {
for (final Object o : getMappingModel().getRasterServices().values()) {
final MapService r = (MapService)o;
if (r.equals(rs)) {
rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r);
}
}
}
}
}
for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) {
getMappingModel().removeLayer(frs);
}
for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) {
handleMapService(0, frs, true);
}
}
/**
* public void showFeatureCollection(Feature[] features) { com.vividsolutions.jts.geom.Envelope
* env=computeFeatureEnvelope(features); showFeatureCollection(features,env); } public void
* showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { selectedFeature=null;
* handleLayer.removeAllChildren(); //setRasterServiceLayerImagesVisibility(false); Envelope eSquare=null; HashSet<Feature>
* featureSet=new HashSet<Feature>(); featureSet.addAll(holdFeatures);
* featureSet.addAll(java.util.Arrays.asList(f)); Feature[] features=featureSet.toArray(new Feature[0]);
* pFeatureHM.clear(); addFeaturesToMap(features); zoomToFullFeatureCollectionBounds(); }.
*
* @param groupId DOCUMENT ME!
* @param visible DOCUMENT ME!
*/
public void setGroupLayerVisibility(final String groupId, final boolean visible) {
final PLayer layer = this.featureGrpLayerMap.get(groupId);
if (layer != null) {
layer.setVisible(visible);
}
}
/**
* is called when new feature is added to FeatureCollection.
*
* @param features DOCUMENT ME!
*/
public void addFeaturesToMap(final Feature[] features) {
final double local_clip_offset_y = clip_offset_y;
final double local_clip_offset_x = clip_offset_x;
/// Hier muss der layer bestimmt werdenn
for (int i = 0; i < features.length; ++i) {
final Feature feature = features[i];
final PFeature p = new PFeature(
feature,
getWtst(),
local_clip_offset_x,
local_clip_offset_y,
MappingComponent.this);
try {
if (feature instanceof StyledFeature) {
p.setTransparency(((StyledFeature)(feature)).getTransparency());
} else {
p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency());
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (feature instanceof FeatureGroupMember) {
final FeatureGroupMember fgm = (FeatureGroupMember)feature;
final String groupId = fgm.getGroupId();
PLayer groupLayer = featureGrpLayerMap.get(groupId);
if (groupLayer == null) {
groupLayer = new PLayer();
featureLayer.addChild(groupLayer);
featureGrpLayerMap.put(groupId, groupLayer);
if (LOG.isDebugEnabled()) {
LOG.debug("created layer for group " + groupId);
}
}
groupLayer.addChild(p);
if (fgm.getGeometry() != null) {
pFeatureHM.put(fgm.getFeature(), p);
}
if (LOG.isDebugEnabled()) {
LOG.debug("added feature to group " + groupId);
}
}
}
});
} catch (final Exception e) {
p.setTransparency(0.8f);
LOG.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N
}
// So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt)
if (!(feature instanceof FeatureGroupMember)) {
if (feature.getGeometry() != null) {
pFeatureHM.put(p.getFeature(), p);
final int ii = i;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
featureLayer.addChild(p);
if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) {
p.moveToFront();
}
}
});
}
}
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
rescaleStickyNodes();
repaint();
fireFeaturesAddedToMap(Arrays.asList(features));
// SuchFeatures in den Vordergrund stellen
for (final Feature feature : featureCollection.getAllFeatures()) {
if (feature instanceof SearchFeature) {
final PFeature pFeature = pFeatureHM.get(feature);
pFeature.moveToFront();
}
}
}
});
// check whether the feature has a rasterSupportLayer or not
for (final Feature f : features) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (!getMappingModel().getRasterServices().containsValue(rs)) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureAwareRasterServiceAdded"); // NOI18N
}
}
rs.setFeatureCollection(getFeatureCollection());
getMappingModel().addLayer(rs);
}
}
}
showHandles(false);
}
/**
* DOCUMENT ME!
*
* @param cf DOCUMENT ME!
*/
private void fireFeaturesAddedToMap(final Collection<Feature> cf) {
for (final MapListener curMapListener : mapListeners) {
curMapListener.featuresAddedToMap(cf);
}
}
/**
* Creates an envelope around all features from the given array.
*
* @param features features to create the envelope around
*
* @return Envelope com.vividsolutions.jts.geom.Envelope
*/
private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) {
final PNode root = new PNode();
for (int i = 0; i < features.length; ++i) {
final PNode p = PNodeFactory.createPFeature(features[i], this);
if (p != null) {
root.addChild(p);
}
}
final PBounds ext = root.getFullBounds();
final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope(
ext.x,
ext.x
+ ext.width,
ext.y,
ext.y
+ ext.height);
return env;
}
/**
* Zooms in / out to match the bounds of the featurecollection.
*/
public void zoomToFullFeatureCollectionBounds() {
zoomToFeatureCollection();
}
/**
* Adds a new cursor to the cursor-hashmap.
*
* @param mode interactionmode as string
* @param cursor cursor-object
*/
public void putCursor(final String mode, final Cursor cursor) {
cursors.put(mode, cursor);
}
/**
* Returns the cursor assigned to the given mode.
*
* @param mode mode as String
*
* @return Cursor-object or null
*/
public Cursor getCursor(final String mode) {
return cursors.get(mode);
}
/**
* Adds a new PBasicInputEventHandler for a specific interactionmode.
*
* @param mode interactionmode as string
* @param listener new PBasicInputEventHandler
*/
public void addInputListener(final String mode, final PBasicInputEventHandler listener) {
inputEventListener.put(mode, listener);
}
/**
* Returns the PBasicInputEventHandler assigned to the committed interactionmode.
*
* @param mode interactionmode as string
*
* @return PBasicInputEventHandler-object or null
*/
public PInputEventListener getInputListener(final String mode) {
final Object o = inputEventListener.get(mode);
if (o instanceof PInputEventListener) {
return (PInputEventListener)o;
} else {
return null;
}
}
/**
* Returns whether the features are editable or not.
*
* @return DOCUMENT ME!
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Sets all Features ReadOnly use Feature.setEditable(boolean) instead.
*
* @param readOnly DOCUMENT ME!
*/
public void setReadOnly(final boolean readOnly) {
for (final Object f : featureCollection.getAllFeatures()) {
((Feature)f).setEditable(!readOnly);
}
this.readOnly = readOnly;
handleLayer.repaint();
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
snapHandleLayer.removeAllChildren();
}
/**
* Returns the current HandleInteractionMode.
*
* @return DOCUMENT ME!
*/
public String getHandleInteractionMode() {
return handleInteractionMode;
}
/**
* Changes the HandleInteractionMode. Repaints handles.
*
* @param handleInteractionMode the new HandleInteractionMode
*/
public void setHandleInteractionMode(final String handleInteractionMode) {
this.handleInteractionMode = handleInteractionMode;
showHandles(false);
}
/**
* Returns whether the background is enabled or not.
*
* @return DOCUMENT ME!
*/
public boolean isBackgroundEnabled() {
return backgroundEnabled;
}
/**
* TODO.
*
* @param backgroundEnabled DOCUMENT ME!
*/
public void setBackgroundEnabled(final boolean backgroundEnabled) {
if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) {
featureServiceLayerVisible = featureServiceLayer.getVisible();
}
this.mapServicelayer.setVisible(backgroundEnabled);
this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible);
for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) {
featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible);
}
if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) {
this.queryServices();
}
this.backgroundEnabled = backgroundEnabled;
}
/**
* Returns the featurelayer.
*
* @return DOCUMENT ME!
*/
public PLayer getFeatureLayer() {
return featureLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map<String, PLayer> getFeatureGroupLayers() {
return this.featureGrpLayerMap;
}
/**
* Adds a PFeature to the PFeatureHashmap.
*
* @param p PFeature to add
*/
public void refreshHM(final PFeature p) {
pFeatureHM.put(p.getFeature(), p);
}
/**
* Returns the selectedObjectPresenter (PCanvas).
*
* @return DOCUMENT ME!
*/
public PCanvas getSelectedObjectPresenter() {
return selectedObjectPresenter;
}
/**
* If f != null it calls the reconsiderFeature()-method of the featurecollection.
*
* @param f feature to reconcile
*/
public void reconsiderFeature(final Feature f) {
if (f != null) {
featureCollection.reconsiderFeature(f);
}
}
/**
* Removes all features of the collection from the hashmap.
*
* @param fc collection of features to remove
*/
public void removeFeatures(final Collection<Feature> fc) {
featureLayer.setVisible(false);
for (final Feature elem : fc) {
removeFromHM(elem);
}
featureLayer.setVisible(true);
}
/**
* Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key.
*
* @param f feature of the Pfeature that should be deleted
*/
public void removeFromHM(final Feature f) {
final PFeature pf = pFeatureHM.get(f);
if (pf != null) {
pf.cleanup();
pFeatureHM.remove(f);
stickyPNodes.remove(pf);
try {
LOG.info("Entferne Feature " + f); // NOI18N
featureLayer.removeChild(pf);
for (final PLayer grpLayer : this.featureGrpLayerMap.values()) {
if (grpLayer.removeChild(pf) != null) {
break;
}
}
} catch (Exception ex) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N
}
}
}
} else {
LOG.warn("Feature war nicht in pFeatureHM"); // NOI18N
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("pFeatureHM" + pFeatureHM); // NOI18N
}
}
}
/**
* Zooms to the current selected node.
*
* @deprecated DOCUMENT ME!
*/
public void zoomToSelectedNode() {
zoomToSelection();
}
/**
* Zooms to the current selected features.
*/
public void zoomToSelection() {
final Collection<Feature> selection = featureCollection.getSelectedFeatures();
zoomToAFeatureCollection(selection, true, false);
}
/**
* Zooms to a specific featurecollection.
*
* @param collection the featurecolltion
* @param withHistory should the zoomaction be undoable
* @param fixedScale fixedScale
*/
public void zoomToAFeatureCollection(final Collection<Feature> collection,
final boolean withHistory,
final boolean fixedScale) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("zoomToAFeatureCollection"); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
boolean first = true;
Geometry g = null;
for (final Feature f : collection) {
if (first) {
if (f.getGeometry() != null) {
g = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode())
.getEnvelope();
if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) {
g = g.buffer(((Bufferable)f).getBuffer() + 0.001);
}
first = false;
}
} else {
if (f.getGeometry() != null) {
Geometry geometry = CrsTransformer.transformToGivenCrs(f.getGeometry(),
mappingModel.getSrs().getCode())
.getEnvelope();
if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) {
geometry = geometry.buffer(((Bufferable)f).getBuffer() + 0.001);
}
g = g.getEnvelope().union(geometry);
}
}
}
if (g != null) {
// FIXME: we shouldn't only complain but do sth
if ((getHeight() == 0) || (getWidth() == 0)) {
LOG.warn("DIVISION BY ZERO"); // NOI18N
}
// dreisatz.de
final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10;
final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10;
double buff = 0;
if (hBuff > vBuff) {
buff = hBuff;
} else {
buff = vBuff;
}
if (buff == 0.0) {
if (mappingModel.getSrs().isMetric()) {
buff = 1.0;
} else {
buff = 0.01;
}
}
g = g.buffer(buff);
final BoundingBox bb = new BoundingBox(g);
final boolean onlyOnePoint = (collection.size() == 1)
&& (((Feature)(collection.toArray()[0])).getGeometry()
instanceof com.vividsolutions.jts.geom.Point);
gotoBoundingBox(bb, withHistory, !(fixedScale || (onlyOnePoint && (g.getArea() < 10))), animationDuration);
}
}
/**
* Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create
* their handles and to add them to the handlelayer.
*
* @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles
*/
public void showHandles(final boolean waitTillAllAnimationsAreComplete) {
// are there features selected?
if (featureCollection.getSelectedFeatures().size() > 0) {
// DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf
final Runnable handle = new Runnable() {
@Override
public void run() {
// alle bisherigen Handles entfernen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
});
while (getAnimating() && waitTillAllAnimationsAreComplete) {
try {
Thread.currentThread().sleep(10);
} catch (final Exception e) {
LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N
}
}
if (featureCollection.areFeaturesEditable()
&& (getInteractionMode().equals(SELECT)
|| getInteractionMode().equals(LINEAR_REFERENCING)
|| getInteractionMode().equals(PAN)
|| getInteractionMode().equals(ZOOM)
|| getInteractionMode().equals(ALKIS_PRINT)
|| getInteractionMode().equals(SPLIT_POLYGON))) {
// Handles für alle selektierten Features der Collection hinzufügen
if (getHandleInteractionMode().equals(ROTATE_POLYGON)) {
final LinkedHashSet<Feature> copy = new LinkedHashSet(
featureCollection.getSelectedFeatures());
for (final Feature selectedFeature : copy) {
if ((selectedFeature instanceof Feature) && selectedFeature.isEditable()) {
if (pFeatureHM.get(selectedFeature) != null) {
// manipulates gui -> edt
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
pFeatureHM.get(selectedFeature).addRotationHandles(handleLayer);
}
});
} else {
LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N
}
}
}
} else {
final LinkedHashSet<Feature> copy = new LinkedHashSet(
featureCollection.getSelectedFeatures());
for (final Feature selectedFeature : copy) {
if ((selectedFeature != null) && selectedFeature.isEditable()) {
if (pFeatureHM.get(selectedFeature) != null) {
// manipulates gui -> edt
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
pFeatureHM.get(selectedFeature).addHandles(handleLayer);
} catch (final Exception e) {
LOG.error("Error bei addHandles: ", e); // NOI18N
}
}
});
} else {
LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N
}
// DANGER mit break werden nur die Handles EINES slektierten Features angezeigt
// wird break auskommentiert werden jedoch zu viele Handles angezeigt break;
}
}
}
}
}
};
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("showHandles", new CurrentStackTrace()); // NOI18N
}
}
CismetThreadPool.execute(handle);
} else {
// alle bisherigen Handles entfernen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
});
}
}
/**
* Will return a PureNewFeature if there is only one in the featurecollection else null.
*
* @return DOCUMENT ME!
*/
public PFeature getSolePureNewFeature() {
int counter = 0;
PFeature sole = null;
for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) {
final Object o = it.next();
if (o instanceof PFeature) {
if (((PFeature)o).getFeature() instanceof PureNewFeature) {
++counter;
sole = ((PFeature)o);
}
}
}
if (counter == 1) {
return sole;
} else {
return null;
}
}
/**
* Returns the temporary featurelayer.
*
* @return DOCUMENT ME!
*/
public PLayer getTmpFeatureLayer() {
return tmpFeatureLayer;
}
/**
* Assigns a new temporary featurelayer.
*
* @param tmpFeatureLayer PLayer
*/
public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) {
this.tmpFeatureLayer = tmpFeatureLayer;
}
/**
* Returns whether the grid is enabled or not.
*
* @return DOCUMENT ME!
*/
public boolean isGridEnabled() {
return gridEnabled;
}
/**
* Enables or disables the grid.
*
* @param gridEnabled true, to enable the grid
*/
public void setGridEnabled(final boolean gridEnabled) {
this.gridEnabled = gridEnabled;
}
/**
* Returns a String from two double-values. Serves the visualization.
*
* @param x X-coordinate
* @param y Y-coordinate
*
* @return a String-object like "(X,Y)"
*/
public static String getCoordinateString(final double x, final double y) {
final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N
final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public com.vividsolutions.jts.geom.Point getPointGeometryFromPInputEvent(final PInputEvent event) {
final double xCoord = getWtst().getSourceX(event.getPosition().getX() - getClip_offset_x());
final double yCoord = getWtst().getSourceY(event.getPosition().getY() - getClip_offset_y());
final GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),
CrsTransformer.extractSridFromCrs(getMappingModel().getSrs().getCode()));
return gf.createPoint(new Coordinate(xCoord, yCoord));
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getHandleLayer() {
return handleLayer;
}
/**
* DOCUMENT ME!
*
* @param handleLayer DOCUMENT ME!
*/
public void setHandleLayer(final PLayer handleLayer) {
this.handleLayer = handleLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisualizeSnappingEnabled() {
return visualizeSnappingEnabled;
}
/**
* DOCUMENT ME!
*
* @param visualizeSnappingEnabled DOCUMENT ME!
*/
public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) {
this.visualizeSnappingEnabled = visualizeSnappingEnabled;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisualizeSnappingRectEnabled() {
return visualizeSnappingRectEnabled;
}
/**
* DOCUMENT ME!
*
* @param visualizeSnappingRectEnabled DOCUMENT ME!
*/
public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) {
this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getSnappingRectSize() {
return snappingRectSize;
}
/**
* DOCUMENT ME!
*
* @param snappingRectSize DOCUMENT ME!
*/
public void setSnappingRectSize(final int snappingRectSize) {
this.snappingRectSize = snappingRectSize;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getSnapHandleLayer() {
return snapHandleLayer;
}
/**
* DOCUMENT ME!
*
* @param snapHandleLayer DOCUMENT ME!
*/
public void setSnapHandleLayer(final PLayer snapHandleLayer) {
this.snapHandleLayer = snapHandleLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isSnappingEnabled() {
return snappingEnabled;
}
/**
* DOCUMENT ME!
*
* @param snappingEnabled DOCUMENT ME!
*/
public void setSnappingEnabled(final boolean snappingEnabled) {
this.snappingEnabled = snappingEnabled;
setVisualizeSnappingEnabled(snappingEnabled);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getFeatureServiceLayer() {
return featureServiceLayer;
}
/**
* DOCUMENT ME!
*
* @param featureServiceLayer DOCUMENT ME!
*/
public void setFeatureServiceLayer(final PLayer featureServiceLayer) {
this.featureServiceLayer = featureServiceLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getAnimationDuration() {
return animationDuration;
}
/**
* DOCUMENT ME!
*
* @param animationDuration DOCUMENT ME!
*/
public void setAnimationDuration(final int animationDuration) {
this.animationDuration = animationDuration;
}
/**
* DOCUMENT ME!
*
* @param prefs DOCUMENT ME!
*/
@Deprecated
public void setPreferences(final CismapPreferences prefs) {
LOG.warn("involing deprecated operation setPreferences()"); // NOI18N
cismapPrefs = prefs;
final ActiveLayerModel mm = new ActiveLayerModel();
final LayersPreferences layersPrefs = prefs.getLayersPrefs();
final GlobalPreferences globalPrefs = prefs.getGlobalPrefs();
setSnappingRectSize(globalPrefs.getSnappingRectSize());
setSnappingEnabled(globalPrefs.isSnappingEnabled());
setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled());
setAnimationDuration(globalPrefs.getAnimationDuration());
setInteractionMode(globalPrefs.getStartMode());
mm.addHome(globalPrefs.getInitialBoundingBox());
final Crs crs = new Crs();
crs.setCode(globalPrefs.getInitialBoundingBox().getSrs());
crs.setName(globalPrefs.getInitialBoundingBox().getSrs());
crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs());
mm.setSrs(crs);
final TreeMap raster = layersPrefs.getRasterServices();
if (raster != null) {
final Iterator it = raster.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final Object o = raster.get(key);
if (o instanceof MapService) {
mm.addLayer((RetrievalServiceLayer)o);
}
}
}
final TreeMap features = layersPrefs.getFeatureServices();
if (features != null) {
final Iterator it = features.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final Object o = features.get(key);
if (o instanceof MapService) {
// TODO
mm.addLayer((RetrievalServiceLayer)o);
}
}
}
setMappingModel(mm);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public CismapPreferences getCismapPrefs() {
return cismapPrefs;
}
/**
* DOCUMENT ME!
*
* @param duration DOCUMENT ME!
* @param animationDuration DOCUMENT ME!
* @param what DOCUMENT ME!
* @param number DOCUMENT ME!
*/
public void flash(final int duration, final int animationDuration, final int what, final int number) {
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getDragPerformanceImproverLayer() {
return dragPerformanceImproverLayer;
}
/**
* DOCUMENT ME!
*
* @param dragPerformanceImproverLayer DOCUMENT ME!
*/
public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) {
this.dragPerformanceImproverLayer = dragPerformanceImproverLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Deprecated
public PLayer getRasterServiceLayer() {
return mapServicelayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getMapServiceLayer() {
return mapServicelayer;
}
/**
* DOCUMENT ME!
*
* @param rasterServiceLayer DOCUMENT ME!
*/
public void setRasterServiceLayer(final PLayer rasterServiceLayer) {
this.mapServicelayer = rasterServiceLayer;
}
/**
* DOCUMENT ME!
*
* @param f DOCUMENT ME!
*/
public void showGeometryInfoPanel(final Feature f) {
}
/**
* Adds a PropertyChangeListener to the listener list.
*
* @param l The listener to add.
*/
@Override
public void addPropertyChangeListener(final PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
/**
* Removes a PropertyChangeListener from the listener list.
*
* @param l The listener to remove.
*/
@Override
public void removePropertyChangeListener(final PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
/**
* Setter for property taskCounter. former synchronized method
*/
public void fireActivityChanged() {
propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N
}
/**
* Returns true, if there's still one layercontrol running. Else false; former synchronized method
*
* @return DOCUMENT ME!
*/
public boolean isRunning() {
for (final LayerControl lc : layerControls) {
if (lc.isRunning()) {
return true;
}
}
return false;
}
/**
* Sets the visibility of all infonodes.
*
* @param visible true, if infonodes should be visible
*/
public void setInfoNodesVisible(final boolean visible) {
infoNodesVisible = visible;
for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) {
final Object elem = it.next();
if (elem instanceof PFeature) {
((PFeature)elem).setInfoNodeVisible(visible);
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("setInfoNodesVisible()"); // NOI18N
}
}
rescaleStickyNodes();
}
/**
* Adds an object to the historymodel.
*
* @param o Object to add
*/
@Override
public void addToHistory(final Object o) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("addToHistory:" + o.toString()); // NOI18N
}
}
historyModel.addToHistory(o);
}
/**
* Removes a specific HistoryModelListener from the historymodel.
*
* @param hml HistoryModelListener
*/
@Override
public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) {
historyModel.removeHistoryModelListener(hml);
}
/**
* Adds aHistoryModelListener to the historymodel.
*
* @param hml HistoryModelListener
*/
@Override
public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) {
historyModel.addHistoryModelListener(hml);
}
/**
* Sets the maximum value of saved historyactions.
*
* @param max new integer value
*/
@Override
public void setMaximumPossibilities(final int max) {
historyModel.setMaximumPossibilities(max);
}
/**
* Redos the last undone historyaction.
*
* @param external true, if fireHistoryChanged-action should be fired
*
* @return PBounds of the forward-action
*/
@Override
public Object forward(final boolean external) {
final PBounds fwd = (PBounds)historyModel.forward(external);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("HistoryModel.forward():" + fwd); // NOI18N
}
}
if (external) {
this.gotoBoundsWithoutHistory(fwd);
}
return fwd;
}
/**
* Undos the last action.
*
* @param external true, if fireHistoryChanged-action should be fired
*
* @return PBounds of the back-action
*/
@Override
public Object back(final boolean external) {
final PBounds back = (PBounds)historyModel.back(external);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("HistoryModel.back():" + back); // NOI18N
}
}
if (external) {
this.gotoBoundsWithoutHistory(back);
}
return back;
}
/**
* Returns true, if it's possible to redo an action.
*
* @return DOCUMENT ME!
*/
@Override
public boolean isForwardPossible() {
return historyModel.isForwardPossible();
}
/**
* Returns true, if it's possible to undo an action.
*
* @return DOCUMENT ME!
*/
@Override
public boolean isBackPossible() {
return historyModel.isBackPossible();
}
/**
* Returns a vector with all redo-possibilities.
*
* @return DOCUMENT ME!
*/
@Override
public Vector getForwardPossibilities() {
return historyModel.getForwardPossibilities();
}
/**
* Returns the current element of the historymodel.
*
* @return DOCUMENT ME!
*/
@Override
public Object getCurrentElement() {
return historyModel.getCurrentElement();
}
/**
* Returns a vector with all undo-possibilities.
*
* @return DOCUMENT ME!
*/
@Override
public Vector getBackPossibilities() {
return historyModel.getBackPossibilities();
}
/**
* Returns whether an internallayerwidget is available.
*
* @return DOCUMENT ME!
*/
@Deprecated
public boolean isInternalLayerWidgetAvailable() {
return this.getInternalWidget(LAYERWIDGET) != null;
}
/**
* Sets the variable, if an internallayerwidget is available or not.
*
* @param internalLayerWidgetAvailable true, if available
*/
@Deprecated
public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) {
if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) {
this.removeInternalWidget(LAYERWIDGET);
} else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) {
final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget(
MappingComponent.this);
MappingComponent.this.addInternalWidget(
LAYERWIDGET,
MappingComponent.POSITION_SOUTHEAST,
simpleInternalLayerWidget);
}
}
/**
* DOCUMENT ME!
*
* @param mme DOCUMENT ME!
*/
@Override
public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) {
}
/**
* Removes the mapservice from the rasterservicelayer.
*
* @param rasterService the removing mapservice
*/
@Override
public void mapServiceRemoved(final MapService rasterService) {
try {
mapServicelayer.removeChild(rasterService.getPNode());
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_REMOVED, rasterService));
}
System.gc();
} catch (final Exception e) {
LOG.warn("Fehler bei mapServiceRemoved", e); // NOI18N
}
}
/**
* Adds the commited mapservice on the last position to the rasterservicelayer.
*
* @param mapService the new mapservice
*/
@Override
public void mapServiceAdded(final MapService mapService) {
addMapService(mapService, mapServicelayer.getChildrenCount());
if (mapService instanceof FeatureAwareRasterService) {
((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection());
}
if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) {
handleMapService(0, mapService, false);
}
}
/**
* Returns the current OGC scale.
*
* @return DOCUMENT ME!
*/
public double getCurrentOGCScale() {
// funktioniert nur bei metrischen SRS's
final double h = getCamera().getViewBounds().getHeight() / getHeight();
final double w = getCamera().getViewBounds().getWidth() / getWidth();
return Math.sqrt((h * h) + (w * w));
}
/**
* Returns the current BoundingBox.
*
* @return DOCUMENT ME!
*/
public BoundingBox getCurrentBoundingBox() {
if (fixedBoundingBox != null) {
return fixedBoundingBox;
} else {
try {
final PBounds bounds = getCamera().getViewBounds();
final double x1 = wtst.getWorldX(bounds.getX());
final double y1 = wtst.getWorldY(bounds.getY());
final double x2 = x1 + bounds.width;
final double y2 = y1 - bounds.height;
final Crs currentCrs = CismapBroker.getInstance().getSrs();
final boolean metric;
// FIXME: this is a hack to overcome the "metric" issue for 4326 default srs
if (CrsTransformer.getCurrentSrid() == 4326) {
metric = false;
} else {
metric = currentCrs.isMetric();
}
currentBoundingBox = new XBoundingBox(x1, y1, x2, y2, currentCrs.getCode(), metric);
return currentBoundingBox;
} catch (final Exception e) {
LOG.error("cannot create bounding box from current view, return null", e); // NOI18N
return null;
}
}
}
/**
* Returns a BoundingBox with a fixed size.
*
* @return DOCUMENT ME!
*/
public BoundingBox getFixedBoundingBox() {
return fixedBoundingBox;
}
/**
* Assigns fixedBoundingBox a new value.
*
* @param fixedBoundingBox new boundingbox
*/
public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) {
this.fixedBoundingBox = fixedBoundingBox;
}
/**
* Paints the outline of the forwarded BoundingBox.
*
* @param bb BoundingBox
*/
public void outlineArea(final BoundingBox bb) {
outlineArea(bb, null);
}
/**
* Paints the outline of the forwarded PBounds.
*
* @param b PBounds
*/
public void outlineArea(final PBounds b) {
outlineArea(b, null);
}
/**
* Paints a filled rectangle of the area of the forwarded BoundingBox.
*
* @param bb BoundingBox
* @param fillingPaint Color to fill the rectangle
*/
public void outlineArea(final BoundingBox bb, final Paint fillingPaint) {
PBounds pb = null;
if (bb != null) {
pb = new PBounds(wtst.getScreenX(bb.getX1()),
wtst.getScreenY(bb.getY2()),
bb.getX2()
- bb.getX1(),
bb.getY2()
- bb.getY1());
}
outlineArea(pb, fillingPaint);
}
/**
* Paints a filled rectangle of the area of the forwarded PBounds.
*
* @param b PBounds to paint
* @param fillingColor Color to fill the rectangle
*/
public void outlineArea(final PBounds b, final Paint fillingColor) {
if (b == null) {
if (highlightingLayer.getChildrenCount() > 0) {
highlightingLayer.removeAllChildren();
}
} else {
highlightingLayer.removeAllChildren();
highlightingLayer.setTransparency(1);
final PPath rectangle = new PPath();
rectangle.setPaint(fillingColor);
rectangle.setStroke(new FixedWidthStroke());
rectangle.setStrokePaint(new Color(100, 100, 100, 255));
rectangle.setPathTo(b);
highlightingLayer.addChild(rectangle);
}
}
/**
* Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally.
*
* @param bb BoundingBox to highlight
*/
public void highlightArea(final BoundingBox bb) {
PBounds pb = null;
if (bb != null) {
pb = new PBounds(wtst.getScreenX(bb.getX1()),
wtst.getScreenY(bb.getY2()),
bb.getX2()
- bb.getX1(),
bb.getY2()
- bb.getY1());
}
highlightArea(pb);
}
/**
* Highlights the delivered PBounds by painting over with a transparent white.
*
* @param b PBounds to hightlight
*/
private void highlightArea(final PBounds b) {
if (b == null) {
if (highlightingLayer.getChildrenCount() > 0) {
}
highlightingLayer.animateToTransparency(0, animationDuration);
highlightingLayer.removeAllChildren();
} else {
highlightingLayer.removeAllChildren();
highlightingLayer.setTransparency(1);
final PPath rectangle = new PPath();
rectangle.setPaint(new Color(255, 255, 255, 100));
rectangle.setStroke(null);
rectangle.setPathTo(this.getCamera().getViewBounds());
highlightingLayer.addChild(rectangle);
rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration);
}
}
/**
* Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls
* crossHairPoint(Point p) internally.
*
* @param c coordinate of the crosshair's venue
*/
public void crossHairPoint(final Coordinate c) {
Point p = null;
if (c != null) {
p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y));
}
crossHairPoint(p);
}
/**
* Paints a crosshair at the delivered point.
*
* @param p point of the crosshair's venue
*/
public void crossHairPoint(final Point p) {
if (p == null) {
if (crosshairLayer.getChildrenCount() > 0) {
crosshairLayer.removeAllChildren();
}
} else {
crosshairLayer.removeAllChildren();
crosshairLayer.setTransparency(1);
final PPath lineX = new PPath();
final PPath lineY = new PPath();
lineX.setStroke(new FixedWidthStroke());
lineX.setStrokePaint(new Color(100, 100, 100, 255));
lineY.setStroke(new FixedWidthStroke());
lineY.setStrokePaint(new Color(100, 100, 100, 255));
final PBounds current = getCamera().getViewBounds();
final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1);
final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2);
lineX.setPathTo(x);
crosshairLayer.addChild(lineX);
lineY.setPathTo(y);
crosshairLayer.addChild(lineY);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Element getConfiguration() {
if (LOG.isDebugEnabled()) {
LOG.debug("writing configuration <cismapMappingPreferences>"); // NOI18N
}
final Element ret = new Element("cismapMappingPreferences"); // NOI18N
ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N
ret.setAttribute(
"creationMode",
((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N
ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N
ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N
final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON);
if (inputListener instanceof CreateSearchGeometryListener) {
final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener;
ret.setAttribute("createSearchMode", listener.getMode());
}
// Position
final Element currentPosition = new Element("Position"); // NOI18N
currentPosition.addContent(currentBoundingBox.getJDOMElement());
currentPosition.setAttribute("CRS", mappingModel.getSrs().getCode());
ret.addContent(currentPosition);
// Crs
final Element crsListElement = new Element("crsList");
for (final Crs tmp : crsList) {
crsListElement.addContent(tmp.getJDOMElement());
}
ret.addContent(crsListElement);
if (printingSettingsDialog != null) {
ret.addContent(printingSettingsDialog.getConfiguration());
}
// save internal widgets status
final Element widgets = new Element("InternalWidgets"); // NOI18N
for (final String name : this.internalWidgets.keySet()) {
final Element widget = new Element("Widget"); // NOI18N
widget.setAttribute("name", name); // NOI18N
widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N
widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N
widgets.addContent(widget);
}
ret.addContent(widgets);
return ret;
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void masterConfigure(final Element e) {
final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N
// CRS List
try {
final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N
boolean defaultCrsFound = false;
crsList.clear();
for (final Object elem : crsElements) {
if (elem instanceof Element) {
final Crs s = new Crs((Element)elem);
crsList.add(s);
if (s.isSelected() && s.isMetric()) {
try {
if (defaultCrsFound) {
LOG.warn("More than one default CRS is set. "
+ "Please check your master configuration file."); // NOI18N
}
CismapBroker.getInstance().setDefaultCrs(s.getCode());
defaultCrsFound = true;
transformer = new CrsTransformer(s.getCode());
} catch (final Exception ex) {
LOG.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex);
}
}
}
}
} catch (final Exception skip) {
LOG.error("Error while reading the crs list", skip); // NOI18N
}
if (CismapBroker.getInstance().getDefaultCrs() == null) {
LOG.fatal("The default CRS is not set. This can lead to almost irreparable data errors. "
+ "Keep in mind: The default CRS must be metric"); // NOI18N
}
if (transformer == null) {
LOG.error("No metric default crs found. Use EPSG:31466 as default crs"); // NOI18N
try {
transformer = new CrsTransformer("EPSG:31466"); // NOI18N
CismapBroker.getInstance().setDefaultCrs("EPSG:31466"); // NOI18N
} catch (final Exception ex) {
LOG.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); // NOI18N
}
}
// HOME
try {
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N
}
}
while (it.hasNext()) {
final Element elem = it.next();
final String srs = elem.getAttribute("srs").getValue(); // NOI18N
boolean metric = false;
try {
metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N
} catch (DataConversionException dce) {
LOG.warn("Metric hat falschen Syntax", dce); // NOI18N
}
boolean defaultVal = false;
try {
defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N
} catch (DataConversionException dce) {
LOG.warn("default hat falschen Syntax", dce); // NOI18N
}
final XBoundingBox xbox = new XBoundingBox(elem, srs, metric);
alm.addHome(xbox);
if (defaultVal) {
Crs crsObject = null;
for (final Crs tmp : crsList) {
if (tmp.getCode().equals(srs)) {
crsObject = tmp;
break;
}
}
if (crsObject == null) {
LOG.error("CRS " + srs + " from the default home is not found in the crs list");
crsObject = new Crs(srs, srs, srs, true, false);
crsList.add(crsObject);
}
alm.setSrs(crsObject);
alm.setDefaultHomeSrs(crsObject);
CismapBroker.getInstance().setSrs(crsObject);
wtst = null;
getWtst();
}
}
}
} catch (final Exception ex) {
LOG.error("Fehler beim MasterConfigure der MappingComponent", ex); // NOI18N
}
try {
final Element defaultCrs = prefs.getChild("defaultCrs");
final int defaultCrsInt = Integer.parseInt(defaultCrs.getAttributeValue("geometrySridAlias"));
CismapBroker.getInstance().setDefaultCrsAlias(defaultCrsInt);
} catch (final Exception ex) {
LOG.error("Error while reading the default crs alias from the master configuration file.", ex);
}
try {
final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N
scales.clear();
for (final Object elem : scalesList) {
if (elem instanceof Element) {
final Scale s = new Scale((Element)elem);
scales.add(s);
}
}
} catch (final Exception skip) {
LOG.error("Fehler beim Lesen von Scale", skip); // NOI18N
}
// Und jetzt noch die PriningEinstellungen
initPrintingDialogs();
printingSettingsDialog.masterConfigure(prefs);
}
/**
* Configurates this MappingComponent.
*
* @param e JDOM-Element with configuration
*/
@Override
public void configure(final Element e) {
final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N
try {
final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N
for (final Object elem : crsElements) {
if (elem instanceof Element) {
final Crs s = new Crs((Element)elem);
// the crs is equals to an other crs, if the code is equal. If a crs has in the
// local configuration file an other name than in the master configuration file,
// the old crs will be removed and the local one should be added to use the
// local name and short name of the crs.
if (crsList.contains(s)) {
crsList.remove(s);
}
crsList.add(s);
}
}
} catch (final Exception skip) {
LOG.warn("Error while reading the crs list", skip); // NOI18N
}
// InteractionMode
try {
final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N
setInteractionMode(interactMode);
if (interactMode.equals(MappingComponent.NEW_POLYGON)) {
try {
final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N
((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode);
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des CreationInteractionMode", ex); // NOI18N
}
}
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des InteractionMode", ex); // NOI18N
}
try {
final String createSearchMode = prefs.getAttribute("createSearchMode").getValue();
final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON);
if ((inputListener instanceof CreateSearchGeometryListener) && (createSearchMode != null)) {
final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener;
listener.setMode(createSearchMode);
}
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des CreateSearchMode", ex); // NOI18N
}
try {
final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N
setHandleInteractionMode(handleInterMode);
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des HandleInteractionMode", ex); // NOI18N
}
try {
final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N
LOG.info("snapping=" + snapping); // NOI18N
setSnappingEnabled(snapping);
setVisualizeSnappingEnabled(snapping);
setInGlueIdenticalPointsMode(snapping);
} catch (final Exception ex) {
LOG.warn("Fehler beim setzen von snapping und Konsorten", ex); // NOI18N
}
// aktuelle Position
try {
final Element pos = prefs.getChild("Position"); // NOI18N
final BoundingBox b = new BoundingBox(pos);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Position:" + b); // NOI18N
}
}
final PBounds pb = b.getPBounds(getWtst());
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("PositionPb:" + pb); // NOI18N
}
}
if (Double.isNaN(b.getX1())
|| Double.isNaN(b.getX2())
|| Double.isNaN(b.getY1())
|| Double.isNaN(b.getY2())) {
LOG.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N
this.currentBoundingBox = getMappingModel().getInitialBoundingBox();
final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null);
addToHistory(new PBoundsWithCleverToString(
new PBounds(currentBoundingBox.getPBounds(wtst)),
wtst,
crsCode));
} else {
// set the current crs
final Attribute crsAtt = pos.getAttribute("CRS");
if (crsAtt != null) {
final String currentCrs = crsAtt.getValue();
Crs crsObject = null;
for (final Crs tmp : crsList) {
if (tmp.getCode().equals(currentCrs)) {
crsObject = tmp;
break;
}
}
if (crsObject == null) {
LOG.error("CRS " + currentCrs + " from the position element is not found in the crs list");
}
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
if (alm instanceof ActiveLayerModel) {
alm.setSrs(crsObject);
}
CismapBroker.getInstance().setSrs(crsObject);
wtst = null;
getWtst();
}
this.currentBoundingBox = b;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("added to History" + b); // NOI18N
}
}
}
} catch (final Exception ex) {
LOG.warn("Fehler beim lesen der aktuellen Position", ex); // NOI18N
this.currentBoundingBox = getMappingModel().getInitialBoundingBox();
}
if (printingSettingsDialog != null) {
printingSettingsDialog.configure(prefs);
}
try {
final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N
if (widgets != null) {
for (final Object widget : widgets.getChildren()) {
final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N
final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N
this.showInternalWidget(name, visible, 0);
}
}
} catch (final Exception ex) {
LOG.warn("could not enable internal widgets: " + ex, ex); // NOI18N
}
}
/**
* Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent
* will only pan to the featurecollection and not zoom.
*
* @param fixedScale true, if zoom is not allowed
*/
public void zoomToFeatureCollection(final boolean fixedScale) {
zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale);
}
/**
* Zooms to all features of the mappingcomponents featurecollection.
*/
public void zoomToFeatureCollection() {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("zoomToFeatureCollection"); // NOI18N
}
}
zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false);
}
/**
* Moves the view to the target Boundingbox.
*
* @param bb target BoundingBox
* @param history true, if the action sould be saved in the history
* @param scaleToFit true, to zoom
* @param animationDuration duration of the animation
*/
public void gotoBoundingBox(final BoundingBox bb,
final boolean history,
final boolean scaleToFit,
final int animationDuration) {
gotoBoundingBox(bb, history, scaleToFit, animationDuration, true);
}
/**
* Moves the view to the target Boundingbox.
*
* @param bb target BoundingBox
* @param history true, if the action sould be saved in the history
* @param scaleToFit true, to zoom
* @param animationDuration duration of the animation
* @param queryServices true, if the services should be refreshed after animation
*/
public void gotoBoundingBox(BoundingBox bb,
final boolean history,
final boolean scaleToFit,
final int animationDuration,
final boolean queryServices) {
if (bb != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
if (bb instanceof XBoundingBox) {
if (!((XBoundingBox)bb).getSrs().equals(mappingModel.getSrs().getCode())) {
try {
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
bb = trans.transformBoundingBox((XBoundingBox)bb);
} catch (final Exception e) {
LOG.warn("Cannot transform the bounding box", e);
}
}
}
final double x1 = getWtst().getScreenX(bb.getX1());
final double y1 = getWtst().getScreenY(bb.getY1());
final double x2 = getWtst().getScreenX(bb.getX2());
final double y2 = getWtst().getScreenY(bb.getY2());
final double w;
final double h;
final Rectangle2D pos = new Rectangle2D.Double();
pos.setRect(x1, y2, x2 - x1, y1 - y2);
getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration);
if (getCamera().getViewTransform().getScaleY() < 0) {
LOG.warn("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N
}
showHandles(true);
final Runnable handle = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(10);
} catch (final Exception e) {
LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N
}
}
if (history) {
if ((x1 == x2) || (y1 == y2) || !scaleToFit) {
setNewViewBounds(getCamera().getViewBounds());
} else {
setNewViewBounds(pos);
}
if (queryServices) {
queryServices();
}
} else {
if (queryServices) {
queryServicesWithoutHistory();
}
}
}
};
CismetThreadPool.execute(handle);
} else {
LOG.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N
}
}
/**
* Moves the view to the target Boundingbox without saving the action in the history.
*
* @param bb target BoundingBox
*/
public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) {
gotoBoundingBoxWithoutHistory(bb, animationDuration);
}
/**
* Moves the view to the target Boundingbox without saving the action in the history.
*
* @param bb target BoundingBox
* @param animationDuration the animation duration
*/
public void gotoBoundingBoxWithoutHistory(final BoundingBox bb, final int animationDuration) {
gotoBoundingBox(bb, false, true, animationDuration);
}
/**
* Moves the view to the target Boundingbox and saves the action in the history.
*
* @param bb target BoundingBox
*/
public void gotoBoundingBoxWithHistory(final BoundingBox bb) {
gotoBoundingBox(bb, true, true, animationDuration);
}
/**
* Returns a BoundingBox of the current view in another scale.
*
* @param scaleDenominator specific target scale
*
* @return DOCUMENT ME!
*/
public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) {
return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBox());
}
/**
* Returns the BoundingBox of the delivered BoundingBox in another scale.
*
* @param scaleDenominator specific target scale
* @param bb source BoundingBox
*
* @return DOCUMENT ME!
*/
public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) {
final double screenWidthInInch = getWidth() / screenResolution;
final double screenWidthInMeter = screenWidthInInch * 0.0254;
final double screenHeightInInch = getHeight() / screenResolution;
final double screenHeightInMeter = screenHeightInInch * 0.0254;
final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator;
final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator;
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
// transform the given bounding box to a metric coordinate system
bb = transformer.transformBoundingBox(bb, mappingModel.getSrs().getCode());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2);
final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2);
BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2),
midY
- (realWorldHeightInMeter / 2),
midX
+ (realWorldWidthInMeter / 2),
midY
+ (realWorldHeightInMeter / 2));
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
// transform the scaled bounding box to the current coordinate system
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
return scaledBox;
}
/**
* Calculate the current scaledenominator.
*
* @return DOCUMENT ME!
*/
public double getScaleDenominator() {
BoundingBox boundingBox = getCurrentBoundingBox();
final double screenWidthInInch = getWidth() / screenResolution;
final double screenWidthInMeter = screenWidthInInch * 0.0254;
final double screenHeightInInch = getHeight() / screenResolution;
final double screenHeightInMeter = screenHeightInInch * 0.0254;
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
boundingBox = transformer.transformBoundingBox(
boundingBox,
mappingModel.getSrs().getCode());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
final double realWorldWidthInMeter = boundingBox.getWidth();
return realWorldWidthInMeter / screenWidthInMeter;
}
/**
* Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code>
* DropTarget</code> registered with this listener.
*
* <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code>
* DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data
* object(s) to be transfered.</p>
*
* <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int
* dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P>
*
* <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be
* invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData()
* method.</P>
*
* <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the
* drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method.</P>
*
* <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code>
* Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only
* if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code>
* true</code>. Otherwise, the behavior of the call is implementation-dependent.</P>
*
* @param dtde the <code>DropTargetDropEvent</code>
*/
@Override
public void drop(final DropTargetDropEvent dtde) {
if (isDropEnabled(dtde)) {
try {
final MapDnDEvent mde = new MapDnDEvent();
mde.setDte(dtde);
final Point p = dtde.getLocation();
getCamera().getViewTransform().inverseTransform(p, p);
mde.setXPos(getWtst().getWorldX(p.getX()));
mde.setYPos(getWtst().getWorldY(p.getY()));
CismapBroker.getInstance().fireDropOnMap(mde);
} catch (final Exception ex) {
LOG.error("Error in drop", ex); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param dtde DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private boolean isDropEnabled(final DropTargetDropEvent dtde) {
if (ALKIS_PRINT.equals(getInteractionMode())) {
for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) {
// necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here
if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) {
return false;
}
}
}
return true;
}
/**
* Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site
* for the <code>DropTarget</code> registered with this listener.
*
* @param dte the <code>DropTargetEvent</code>
*/
@Override
public void dragExit(final DropTargetEvent dte) {
}
/**
* Called if the user has modified the current drop gesture.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dropActionChanged(final DropTargetDragEvent dtde) {
}
/**
* Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p
* site for the <code>DropTarget</code> registered with this listener.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dragOver(final DropTargetDragEvent dtde) {
try {
final MapDnDEvent mde = new MapDnDEvent();
mde.setDte(dtde);
// TODO: this seems to be buggy!
final Point p = dtde.getLocation();
getCamera().getViewTransform().inverseTransform(p, p);
mde.setXPos(getWtst().getWorldX(p.getX()));
mde.setYPos(getWtst().getWorldY(p.getY()));
CismapBroker.getInstance().fireDragOverMap(mde);
} catch (final Exception ex) {
LOG.error("Error in dragOver", ex); // NOI18N
}
}
/**
* Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for
* the <code>DropTarget</code> registered with this listener.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dragEnter(final DropTargetDragEvent dtde) {
}
/**
* Returns the PfeatureHashmap which assigns a Feature to a PFeature.
*
* @return DOCUMENT ME!
*/
public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() {
return pFeatureHM;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFixedMapExtent() {
return fixedMapExtent;
}
/**
* DOCUMENT ME!
*
* @param fixedMapExtent DOCUMENT ME!
*/
public void setFixedMapExtent(final boolean fixedMapExtent) {
this.fixedMapExtent = fixedMapExtent;
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(
StatusEvent.MAP_EXTEND_FIXED,
this.fixedMapExtent));
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFixedMapScale() {
return fixedMapScale;
}
/**
* DOCUMENT ME!
*
* @param fixedMapScale DOCUMENT ME!
*/
public void setFixedMapScale(final boolean fixedMapScale) {
this.fixedMapScale = fixedMapScale;
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(
StatusEvent.MAP_SCALE_FIXED,
this.fixedMapScale));
}
}
/**
* DOCUMENT ME!
*
* @param one DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
public void selectPFeatureManually(final PFeature one) {
if (one != null) {
featureCollection.select(one.getFeature());
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
public PFeature getSelectedNode() {
// gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist
// deshalb gebe ich mal nur das erste zur�ck
if (featureCollection.getSelectedFeatures().size() > 0) {
final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0];
if (selF == null) {
return null;
}
return pFeatureHM.get(selF);
} else {
return null;
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isInfoNodesVisible() {
return infoNodesVisible;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getPrintingFrameLayer() {
return printingFrameLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PrintingSettingsWidget getPrintingSettingsDialog() {
return printingSettingsDialog;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isInGlueIdenticalPointsMode() {
return inGlueIdenticalPointsMode;
}
/**
* DOCUMENT ME!
*
* @param inGlueIdenticalPointsMode DOCUMENT ME!
*/
public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) {
this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getHighlightingLayer() {
return highlightingLayer;
}
/**
* DOCUMENT ME!
*
* @param anno DOCUMENT ME!
*/
public void setPointerAnnotation(final PNode anno) {
((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno);
}
/**
* DOCUMENT ME!
*
* @param visib DOCUMENT ME!
*/
public void setPointerAnnotationVisibility(final boolean visib) {
if (getInputListener(MOTION) != null) {
((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib);
}
}
/**
* Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't
* equal MOTION.
*
* @return DOCUMENT ME!
*/
public boolean isPointerAnnotationVisible() {
if (getInputListener(MOTION) != null) {
return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible();
} else {
return false;
}
}
/**
* Returns a vector with different scales.
*
* @return DOCUMENT ME!
*/
public List<Scale> getScales() {
return scales;
}
/**
* Returns a list with different crs.
*
* @return DOCUMENT ME!
*/
public List<Crs> getCrsList() {
return crsList;
}
/**
* DOCUMENT ME!
*
* @return a transformer with the default crs as destination crs. The default crs is the first crs in the
* configuration file that has set the selected attribut on true). This crs must be metric.
*/
public CrsTransformer getMetricTransformer() {
return transformer;
}
/**
* Locks the MappingComponent.
*/
public void lock() {
locked = true;
}
/**
* Unlocks the MappingComponent.
*/
public void unlock() {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("unlock"); // NOI18N
}
}
locked = false;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N
}
}
gotoBoundingBoxWithHistory(currentBoundingBox);
}
/**
* Returns whether the MappingComponent is locked or not.
*
* @return DOCUMENT ME!
*/
public boolean isLocked() {
return locked;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isMainMappingComponent() {
return mainMappingComponent;
}
/**
* Returns the MementoInterface for redo-actions.
*
* @return DOCUMENT ME!
*/
public MementoInterface getMemRedo() {
return memRedo;
}
/**
* Returns the MementoInterface for undo-actions.
*
* @return DOCUMENT ME!
*/
public MementoInterface getMemUndo() {
return memUndo;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map<String, PBasicInputEventHandler> getInputEventListener() {
return inputEventListener;
}
/**
* DOCUMENT ME!
*
* @param inputEventListener DOCUMENT ME!
*/
public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) {
this.inputEventListener.clear();
this.inputEventListener.putAll(inputEventListener);
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
@Override
public synchronized void crsChanged(final CrsChangedEvent event) {
if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) {
if (locked) {
return;
}
try {
// the wtst object should not be null, so the getWtst method will be invoked
final WorldToScreenTransform oldWtst = getWtst();
final BoundingBox bbox = getCurrentBoundingBox(); // getCurrentBoundingBox();
final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode());
final BoundingBox newBbox = crsTransformer.transformBoundingBox(bbox, event.getFormerCrs().getCode());
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.setSrs(event.getCurrentCrs());
}
wtst = null;
getWtst();
gotoBoundingBoxWithoutHistory(newBbox, 0);
final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures());
featureCollection.removeAllFeatures();
featureCollection.addFeatures(list);
if (LOG.isDebugEnabled()) {
LOG.debug("debug features added: " + list.size());
}
// refresh all wfs layer
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.refreshWebFeatureServices();
alm.refreshShapeFileLayer();
}
// transform the highlighting layer
for (int i = 0; i < highlightingLayer.getChildrenCount(); ++i) {
final PNode node = highlightingLayer.getChild(i);
CrsTransformer.transformPNodeToGivenCrs(
node,
event.getFormerCrs().getCode(),
event.getCurrentCrs().getCode(),
oldWtst,
getWtst());
rescaleStickyNode(node);
}
} catch (final Exception e) {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"),
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"),
JOptionPane.ERROR_MESSAGE);
LOG.error("Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e);
resetCrs = true;
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.setSrs(event.getCurrentCrs());
CismapBroker.getInstance().setSrs(event.getFormerCrs());
}
} else {
resetCrs = false;
}
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public JInternalFrame getInternalWidget(final String name) {
if (this.internalWidgets.containsKey(name)) {
return this.internalWidgets.get(name);
} else {
LOG.warn("unknown internal widget '" + name + "'"); // NOI18N
return null;
}
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getInternalWidgetPosition(final String name) {
if (this.internalWidgetPositions.containsKey(name)) {
return this.internalWidgetPositions.get(name);
} else {
LOG.warn("unknown position for '" + name + "'"); // NOI18N
return -1;
}
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class MappingComponentRasterServiceListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
private final transient ServiceLayer rasterService;
private final XPImage pi;
private int position = -1;
//~ Constructors -------------------------------------------------------
/**
* Creates a new MappingComponentRasterServiceListener object.
*
* @param position DOCUMENT ME!
* @param pn DOCUMENT ME!
* @param rasterService DOCUMENT ME!
*/
public MappingComponentRasterServiceListener(final int position,
final PNode pn,
final ServiceLayer rasterService) {
this.position = position;
this.rasterService = rasterService;
if (pn instanceof XPImage) {
this.pi = (XPImage)pn;
} else {
this.pi = null;
}
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
fireActivityChanged();
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
this.log.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() // NOI18N
+ " Errors: " // NOI18N
+ e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N
fireActivityChanged();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
final Point2D localOrigin = getCamera().getViewBounds().getOrigin();
final double localScale = getCamera().getViewScale();
final PBounds localBounds = getCamera().getViewBounds();
final Object o = e.getRetrievedObject();
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
final Runnable paintImageOnMap = new Runnable() {
@Override
public void run() {
fireActivityChanged();
if ((o instanceof Image) && (e.isHasErrors() == false)) {
// TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden
if (isBackgroundEnabled()) {
final Image i = (Image)o;
if (rasterService.getName().startsWith("prefetching")) { // NOI18N
final double x = localOrigin.getX() - localBounds.getWidth();
final double y = localOrigin.getY() - localBounds.getHeight();
pi.setImage(i, 0);
pi.setScale(3 / localScale);
pi.setOffset(x, y);
} else {
pi.setImage(i, animationDuration * 2);
pi.setScale(1 / localScale);
pi.setOffset(localOrigin);
MappingComponent.this.repaint();
}
}
}
}
};
if (EventQueue.isDispatchThread()) {
paintImageOnMap.run();
} else {
EventQueue.invokeLater(paintImageOnMap);
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
this.log.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getPosition() {
return position;
}
/**
* DOCUMENT ME!
*
* @param position DOCUMENT ME!
*/
public void setPosition(final int position) {
this.position = position;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class DocumentProgressListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
/** Displays the loading progress of Documents, e.g. SHP Files */
private final transient DocumentProgressWidget documentProgressWidget;
private transient long requestId = -1;
//~ Constructors -------------------------------------------------------
/**
* Creates a new DocumentProgressListener object.
*/
public DocumentProgressListener() {
documentProgressWidget = new DocumentProgressWidget();
documentProgressWidget.setVisible(false);
if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) {
MappingComponent.this.addInternalWidget(
MappingComponent.PROGRESSWIDGET,
MappingComponent.POSITION_SOUTHWEST,
documentProgressWidget);
}
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalStarted aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != -1) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = e.getRequestIdentifier();
this.documentProgressWidget.setServiceName(e.getRetrievalService().toString());
this.documentProgressWidget.setProgress(-1);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalProgress, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: initialisation progress: " + e.getPercentageDone()); // NOI18N
}
}
this.documentProgressWidget.setProgress(e.getPercentageDone());
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalComplete, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N
}
e.getRetrievalService().removeRetrievalListener(this);
this.requestId = -1;
this.documentProgressWidget.setProgress(100);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalAborted aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = -1;
this.documentProgressWidget.setProgress(0);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalError aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = -1;
e.getRetrievalService().removeRetrievalListener(this);
this.documentProgressWidget.setProgress(0);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public long getRequestId() {
return this.requestId;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class MappingComponentFeatureServiceListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
private final transient ServiceLayer featureService;
private final transient PLayer parent;
private long requestIdentifier;
private Thread completionThread;
private final List deletionCandidates;
private final List twins;
//~ Constructors -------------------------------------------------------
/**
* Creates a new MappingComponentFeatureServiceListener.
*
* @param featureService the featureretrievalservice
* @param parent the featurelayer (PNode) connected with the servicelayer
*/
public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) {
this.featureService = featureService;
this.parent = parent;
this.deletionCandidates = new ArrayList();
this.twins = new ArrayList();
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
requestIdentifier = e.getRequestIdentifier();
}
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N
}
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: "
+ e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress()
+ ")"); // NOI18N
}
}
fireActivityChanged();
// TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das
// flüssiger ist
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
this.log.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: "
+ (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N
}
}
if (e.isInitialisationEvent()) {
this.log.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: initialisation complete"); // NOI18N
fireActivityChanged();
return;
}
if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N
completionThread.interrupt();
}
if (e.getRequestIdentifier() < requestIdentifier) {
if (DEBUG) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N
}
((RetrievalServiceLayer)featureService).setProgress(-1);
fireActivityChanged();
return;
}
final List newFeatures = new ArrayList();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
((RetrievalServiceLayer)featureService).setProgress(-1);
parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible());
}
});
// clear all old data to delete twins
deletionCandidates.clear();
twins.clear();
// if it's a refresh, add all old features which should be deleted in the
// newly acquired featurecollection
if (!e.isRefreshExisting()) {
deletionCandidates.addAll(parent.getChildrenReference());
}
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N
}
}
// only start parsing the features if there are no errors and a correct collection
if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) {
completionThread = new Thread() {
@Override
public void run() {
// this is the collection with the retrieved features
final List features = new ArrayList((Collection)e.getRetrievedObject());
final int size = features.size();
int counter = 0;
final Iterator it = features.iterator();
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(featureService + "[" + e.getRequestIdentifier() + " ("
+ requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N
}
}
while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()
&& it.hasNext()) {
counter++;
final Object o = it.next();
if (o instanceof Feature) {
final PFeature p = new PFeature(((Feature)o),
wtst,
clip_offset_x,
clip_offset_y,
MappingComponent.this);
PFeature twin = null;
for (final Object tester : deletionCandidates) {
// if tester and PFeature are FeatureWithId-objects
if ((((PFeature)tester).getFeature() instanceof FeatureWithId)
&& (p.getFeature() instanceof FeatureWithId)) {
final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId();
final int id2 = ((FeatureWithId)(p.getFeature())).getId();
if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id
if (id1 == id2) {
twin = ((PFeature)tester);
break;
}
} else { // else test the geometry for equality
if (((PFeature)tester).getFeature().getGeometry().equals(
p.getFeature().getGeometry())) {
twin = ((PFeature)tester);
break;
}
}
} else { // no FeatureWithId, test geometries for
// equality
if (((PFeature)tester).getFeature().getGeometry().equals(
p.getFeature().getGeometry())) {
twin = ((PFeature)tester);
break;
}
}
}
// if a twin is found remove him from the deletion candidates
// and add him to the twins
if (twin != null) {
deletionCandidates.remove(twin);
twins.add(twin);
} else { // else add the PFeature to the new features
newFeatures.add(p);
}
// calculate the advance of the progressbar
// fire event only wheen needed
final int currentProgress = (int)((double)counter / (double)size * 100d);
if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) {
((RetrievalServiceLayer)featureService).setProgress(currentProgress);
fireActivityChanged();
}
}
}
if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) {
// after all features are computed do stuff on the EDT
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N
}
}
// if it's a refresh, delete all previous features
if (e.isRefreshExisting()) {
parent.removeAllChildren();
}
final List deleteFeatures = new ArrayList();
for (final Object o : newFeatures) {
parent.addChild((PNode)o);
}
// set the prograssbar to full
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: set progress to 100"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(100);
fireActivityChanged();
// repaint the featurelayer
parent.repaint();
// remove stickyNode from all deletionCandidates and add
// each to the new deletefeature-collection
for (final Object o : deletionCandidates) {
if (o instanceof PFeature) {
final PNode p = ((PFeature)o).getPrimaryAnnotationNode();
if (p != null) {
removeStickyNode(p);
}
deleteFeatures.add(o);
}
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: parentCount before:"
+ parent.getChildrenCount()); // NOI18N
}
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: deleteFeatures="
+ deleteFeatures.size()); // + " :" +
// deleteFeatures);//NOI18N
}
}
parent.removeChildren(deleteFeatures);
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: parentCount after:"
+ parent.getChildrenCount()); // NOI18N
}
}
if (LOG.isInfoEnabled()) {
LOG.info(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: "
+ parent.getChildrenCount()
+ " features retrieved or updated"); // NOI18N
}
rescaleStickyNodes();
} catch (final Exception exception) {
log.warn(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: Fehler beim Aufr\u00E4umen",
exception); // NOI18N
}
}
});
} else {
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(featureService + "[" + e.getRequestIdentifier() + " ("
+ requestIdentifier
+ ")]: completion thread Interrupted or synchronisation lost"); // NOI18N
}
}
}
}
};
completionThread.setPriority(Thread.NORM_PRIORITY);
if (requestIdentifier == e.getRequestIdentifier()) {
completionThread.start();
} else {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: completion thread Interrupted or synchronisation lost"); // NOI18N
}
}
}
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: aborted, TaskCounter:" + taskCounter); // NOI18N
if (completionThread != null) {
completionThread.interrupt();
}
if (e.getRequestIdentifier() < requestIdentifier) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(-1);
} else {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(0);
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, featureService));
}
}
}
}
| public void setInteractionMode(final String interactionMode) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:"
+ this.interactionMode + "",
new Exception()); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
setPointerAnnotationVisibility(false);
if (getPrintingFrameLayer().getChildrenCount() > 1) {
getPrintingFrameLayer().removeAllChildren();
}
if (this.interactionMode != null) {
if (interactionMode.equals(FEATURE_INFO)) {
((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo()
.setVisible(true);
} else {
((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo()
.setVisible(false);
}
if (isReadOnly()) {
((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class);
}
final PInputEventListener pivl = this.getInputListener(this.interactionMode);
if (pivl != null) {
removeInputEventListener(pivl);
} else {
LOG.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N
}
if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) {
featureCollection.unselectAll();
}
if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEAR_REFERENCING)
|| interactionMode.equals(SPLIT_POLYGON))
&& (this.readOnly == false)) {
featureSelectionChanged(null);
}
if (interactionMode.equals(JOIN_POLYGONS)) {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
}
final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent(
this,
PROPERTY_MAP_INTERACTION_MODE,
this.interactionMode,
interactionMode);
this.interactionMode = interactionMode;
final PInputEventListener pivl = getInputListener(interactionMode);
if (pivl != null) {
addInputEventListener(pivl);
propertyChangeSupport.firePropertyChange(interactionModeChangedEvent);
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode));
} else {
LOG.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N
}
} catch (final Exception e) {
LOG.error("Fehler beim Ändern des InteractionModes", e); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
@Deprecated
public void formComponentResized(final ComponentEvent evt) {
this.componentResizedDelayed();
}
/**
* Resizes the map and does not reload all services.
*
* @see #componentResizedDelayed()
*/
public void componentResizedIntermediate() {
if (!this.isLocked()) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N
}
}
if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) {
if (mappingModel != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N
}
}
if (MappingComponent.this.currentBoundingBox == null) {
LOG.error("currentBoundingBox is null"); // NOI18N
currentBoundingBox = getCurrentBoundingBox();
}
// rescale map
if (historyModel.getCurrentElement() != null) {
final PBounds bounds = (PBounds)historyModel.getCurrentElement();
if (bounds.getWidth() < 0) {
bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight());
}
if (bounds.getHeight() < 0) {
bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1));
}
getCamera().animateViewToCenterBounds(bounds, true, animationDuration);
}
}
}
// move internal widgets
for (final String internalWidget : this.internalWidgets.keySet()) {
if (this.getInternalWidget(internalWidget).isVisible()) {
showInternalWidget(internalWidget, true, 0);
}
}
}
}
/**
* Resizes the map and reloads all services.
*
* @see #componentResizedIntermediate()
*/
public void componentResizedDelayed() {
if (!this.isLocked()) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N
}
}
if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) {
if (mappingModel != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N
}
}
if (MappingComponent.this.currentBoundingBox == null) {
LOG.error("currentBoundingBox is null"); // NOI18N
currentBoundingBox = getCurrentBoundingBox();
}
gotoBoundsWithoutHistory((PBounds)historyModel.getCurrentElement());
// move internal widgets
for (final String internalWidget : this.internalWidgets.keySet()) {
if (this.getInternalWidget(internalWidget).isVisible()) {
showInternalWidget(internalWidget, true, 0);
}
}
}
}
} catch (final Exception t) {
LOG.error("Fehler in formComponentResized()", t); // NOI18N
}
}
}
/**
* syncSelectedObjectPresenter(int i).
*
* @param i DOCUMENT ME!
*/
public void syncSelectedObjectPresenter(final int i) {
selectedObjectPresenter.setVisible(true);
if (featureCollection.getSelectedFeatures().size() > 0) {
if (featureCollection.getSelectedFeatures().size() == 1) {
final PFeature selectedFeature = (PFeature)pFeatureHM.get(
featureCollection.getSelectedFeatures().toArray()[0]);
if (selectedFeature != null) {
selectedObjectPresenter.getCamera()
.animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2);
}
} else {
// todo
}
} else {
LOG.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N
}
}
/**
* Returns the current featureCollection.
*
* @return DOCUMENT ME!
*/
public FeatureCollection getFeatureCollection() {
return featureCollection;
}
/**
* Replaces the old featureCollection with a new one.
*
* @param featureCollection the new featureCollection
*/
public void setFeatureCollection(final FeatureCollection featureCollection) {
this.featureCollection = featureCollection;
featureCollection.addFeatureCollectionListener(this);
}
/**
* DOCUMENT ME!
*
* @param visibility DOCUMENT ME!
*/
public void setFeatureCollectionVisibility(final boolean visibility) {
featureLayer.setVisible(visibility);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFeatureCollectionVisible() {
return featureLayer.getVisible();
}
/**
* Adds a new mapservice at a specific place of the layercontrols.
*
* @param mapService the new mapservice
* @param position the index where to position the mapservice
*/
public void addMapService(final MapService mapService, final int position) {
try {
PNode p = new PNode();
if (mapService instanceof RasterMapService) {
LOG.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N
if (mapService.getPNode() instanceof XPImage) {
p = (XPImage)mapService.getPNode();
} else {
p = new XPImage();
mapService.setPNode(p);
}
mapService.addRetrievalListener(new MappingComponentRasterServiceListener(
position,
p,
(ServiceLayer)mapService));
} else {
LOG.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName()
+ ")"); // NOI18N
p = new PLayer();
mapService.setPNode(p);
if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService
+ "): isDocumentFeatureService, checking document size"); // NOI18N
}
}
final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService;
if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) {
LOG.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '"
+ documentFeatureService.getName() + "' size of "
+ (documentFeatureService.getDocumentSize() / 1000000)
+ "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000)
+ "MB)"); // NOI18N
if (this.documentProgressListener == null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService
+ "): lazy instantiation of documentProgressListener"); // NOI18N
}
}
this.documentProgressListener = new DocumentProgressListener();
}
if (this.documentProgressListener.getRequestId() != -1) {
LOG.error("FeatureMapService(" + mapService
+ "): The documentProgressListener is already in use by request '"
+ this.documentProgressListener.getRequestId()
+ ", document progress cannot be tracked"); // NOI18N
} else {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N
}
}
documentFeatureService.addRetrievalListener(this.documentProgressListener);
}
}
}
mapService.addRetrievalListener(new MappingComponentFeatureServiceListener(
(ServiceLayer)mapService,
(PLayer)mapService.getPNode()));
}
p.setTransparency(mapService.getTranslucency());
p.setVisible(mapService.isVisible());
mapServicelayer.addChild(p);
} catch (final Exception e) {
LOG.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + e.getMessage(), e); // NOI18N
}
}
/**
* DOCUMENT ME!
*
* @param mm DOCUMENT ME!
*/
public void preparationSetMappingModel(final MappingModel mm) {
mappingModel = mm;
}
/**
* Sets a new mappingmodel in this MappingComponent.
*
* @param mm the new mappingmodel
*/
public void setMappingModel(final MappingModel mm) {
LOG.info("setMappingModel"); // NOI18N
// FIXME: why is the default uncaught exception handler set in such a random place?
if (Thread.getDefaultUncaughtExceptionHandler() == null) {
LOG.info("setDefaultUncaughtExceptionHandler"); // NOI18N
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
LOG.error("Error", e);
}
});
}
mappingModel = mm;
currentBoundingBox = mm.getInitialBoundingBox();
final Runnable r = new Runnable() {
@Override
public void run() {
mappingModel.addMappingModelListener(MappingComponent.this);
final TreeMap rs = mappingModel.getRasterServices();
// Rückwärts wegen der Reihenfolge der Layer im Layer Widget
final Iterator it = rs.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if (o instanceof MapService) {
addMapService(((MapService)o), rsi);
}
}
adjustLayers();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Set Mapping Modell done"); // NOI18N
}
}
}
};
CismetThreadPool.execute(r);
}
/**
* Returns the current mappingmodel.
*
* @return current mappingmodel
*/
public MappingModel getMappingModel() {
return mappingModel;
}
/**
* Animates a component to a given x/y-coordinate in a given time.
*
* @param c the component to animate
* @param toX final x-position
* @param toY final y-position
* @param animationDuration duration of the animation
* @param hideAfterAnimation should the component be hidden after animation?
*/
private void animateComponent(final JComponent c,
final int toX,
final int toY,
final int animationDuration,
final boolean hideAfterAnimation) {
if (animationDuration > 0) {
final int x = (int)c.getBounds().getX() - toX;
final int y = (int)c.getBounds().getY() - toY;
int sx;
int sy;
if (x > 0) {
sx = -1;
} else {
sx = 1;
}
if (y > 0) {
sy = -1;
} else {
sy = 1;
}
int big;
if (Math.abs(x) > Math.abs(y)) {
big = Math.abs(x);
} else {
big = Math.abs(y);
}
final int sleepy;
if ((animationDuration / big) < 1) {
sleepy = 1;
} else {
sleepy = animationDuration / big;
}
final int directionY = sy;
final int directionX = sx;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY
+ ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX="
+ toX + ", toY=" + toY); // NOI18N
}
}
final Thread timer = new Thread() {
@Override
public void run() {
while (!isInterrupted()) {
try {
sleep(sleepy);
} catch (final Exception iex) {
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
int currentY = (int)c.getBounds().getY();
int currentX = (int)c.getBounds().getX();
if (currentY != toY) {
currentY = currentY + directionY;
}
if (currentX != toX) {
currentX = currentX + directionX;
}
c.setBounds(currentX, currentY, c.getWidth(), c.getHeight());
}
});
if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) {
if (hideAfterAnimation) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
c.setVisible(false);
c.hide();
}
});
}
break;
}
}
}
};
timer.setPriority(Thread.NORM_PRIORITY);
timer.start();
} else {
c.setBounds(toX, toY, c.getWidth(), c.getHeight());
if (hideAfterAnimation) {
c.setVisible(false);
}
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
@Deprecated
public NewSimpleInternalLayerWidget getInternalLayerWidget() {
return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET);
}
/**
* Adds a new internal widget to the map.<br/>
* If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget
* will be added. If a widget with a different name already exisit at the same {@code position} the new widget will
* not be added and the operation returns {@code false}.
*
* @param name unique name of the widget
* @param position position of the widget
* @param widget the widget
*
* @return {@code true} if the widget could be added, {@code false} otherwise
*
* @see #POSITION_NORTHEAST
* @see #POSITION_NORTHWEST
* @see #POSITION_SOUTHEAST
* @see #POSITION_SOUTHWEST
*/
public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) {
if (LOG.isDebugEnabled()) {
LOG.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N
}
if (this.internalWidgets.containsKey(name)) {
LOG.warn("widget '" + name + "' already added, removing old widget"); // NOI18N
this.remove(this.getInternalWidget(name));
} else if (this.internalWidgetPositions.containsValue(position)) {
LOG.warn("widget position '" + position + "' already taken"); // NOI18N
return false;
}
this.internalWidgets.put(name, widget);
this.internalWidgetPositions.put(name, position);
widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N
this.add(widget);
widget.pack();
return true;
}
/**
* Removes an existing internal widget from the map.
*
* @param name name of the widget to be removed
*
* @return {@code true} id the widget was found and removed, {@code false} otherwise
*/
public boolean removeInternalWidget(final String name) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing internal widget '" + name + "'"); // NOI18N
}
if (!this.internalWidgets.containsKey(name)) {
LOG.warn("widget '" + name + "' not found"); // NOI18N
return false;
}
this.remove(this.getInternalWidget(name));
this.internalWidgets.remove(name);
this.internalWidgetPositions.remove(name);
return true;
}
/**
* Shows an InternalWidget by sliding it into the mappingcomponent.
*
* @param name name of the internl component to show
* @param visible should the widget be visible after the animation?
* @param animationDuration duration of the animation
*
* @return {@code true} if the operation was successful, {@code false} otherwise
*/
public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) {
final JInternalFrame internalWidget = this.getInternalWidget(name);
if (internalWidget == null) {
return false;
}
final int positionX;
final int positionY;
final int widgetPosition = this.getInternalWidgetPosition(name);
final boolean isHigher = (getHeight() < (internalWidget.getHeight() + 2)) && (getHeight() > 0);
final boolean isWider = (getWidth() < (internalWidget.getWidth() + 2)) && (getWidth() > 0);
switch (widgetPosition) {
case POSITION_NORTHWEST: {
positionX = 1;
positionY = 1;
break;
}
case POSITION_SOUTHWEST: {
positionX = 1;
positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1);
break;
}
case POSITION_NORTHEAST: {
positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1);
positionY = 1;
break;
}
case POSITION_SOUTHEAST: {
positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1);
positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1);
break;
}
default: {
LOG.warn("unkown widget position?!"); // NOI18N
return false;
}
}
if (visible) {
final int toY;
if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) {
if (isHigher) {
toY = getHeight() - 1;
} else {
toY = positionY - internalWidget.getHeight() - 1;
}
} else {
if (isHigher) {
toY = getHeight() + 1;
} else {
toY = positionY + internalWidget.getHeight() + 1;
}
}
internalWidget.setBounds(
positionX,
toY,
isWider ? (getWidth() - 2) : internalWidget.getWidth(),
isHigher ? (getHeight() - 2) : internalWidget.getHeight());
internalWidget.setVisible(true);
internalWidget.show();
animateComponent(internalWidget, positionX, positionY, animationDuration, false);
} else {
internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight());
int toY = positionY + internalWidget.getHeight() + 1;
if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) {
toY = positionY - internalWidget.getHeight() - 1;
}
animateComponent(internalWidget, positionX, toY, animationDuration, true);
}
return true;
}
/**
* DOCUMENT ME!
*
* @param visible DOCUMENT ME!
* @param animationDuration DOCUMENT ME!
*/
@Deprecated
public void showInternalLayerWidget(final boolean visible, final int animationDuration) {
this.showInternalWidget(LAYERWIDGET, visible, animationDuration);
}
/**
* Returns a boolean, if the InternalLayerWidget is visible.
*
* @return true, if visible, else false
*/
@Deprecated
public boolean isInternalLayerWidgetVisible() {
return this.getInternalLayerWidget().isVisible();
}
/**
* Returns a boolean, if the InternalWidget is visible.
*
* @param name name of the widget
*
* @return true, if visible, else false
*/
public boolean isInternalWidgetVisible(final String name) {
final JInternalFrame widget = this.getInternalWidget(name);
if (widget != null) {
return widget.isVisible();
}
return false;
}
/**
* Moves the camera to the initial bounding box (e.g. if the home-button is pressed).
*/
public void gotoInitialBoundingBox() {
final double x1;
final double y1;
final double x2;
final double y2;
final double w;
final double h;
x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1());
y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1());
x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2());
y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2());
final Rectangle2D home = new Rectangle2D.Double();
home.setRect(x1, y2, x2 - x1, y1 - y2);
getCamera().animateViewToCenterBounds(home, true, animationDuration);
if (getCamera().getViewTransform().getScaleY() < 0) {
LOG.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N
}
setNewViewBounds(home);
queryServices();
}
/**
* Refreshs all registered services.
*/
public void queryServices() {
if (newViewBounds != null) {
addToHistory(new PBoundsWithCleverToString(
new PBounds(newViewBounds),
wtst,
mappingModel.getSrs().getCode()));
queryServicesWithoutHistory();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServices()"); // NOI18N
}
}
rescaleStickyNodes();
}
}
/**
* Forces all services to refresh themselves.
*/
public void refresh() {
forceQueryServicesWithoutHistory();
}
/**
* Forces all services to refresh themselves.
*/
private void forceQueryServicesWithoutHistory() {
queryServicesWithoutHistory(true);
}
/**
* Refreshs all services, but not forced.
*/
private void queryServicesWithoutHistory() {
queryServicesWithoutHistory(false);
}
/**
* Waits until all animations are done, then iterates through all registered services and calls handleMapService()
* for each.
*
* @param forced forces the refresh
*/
private void queryServicesWithoutHistory(final boolean forced) {
if (forced && mainMappingComponent) {
CismapBroker.getInstance().fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_RESET, this));
}
if (!locked) {
final Runnable r = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception doNothing) {
}
}
CismapBroker.getInstance().fireMapBoundsChanged();
if (MappingComponent.this.isBackgroundEnabled()) {
final TreeMap rs = mappingModel.getRasterServices();
final TreeMap fs = mappingModel.getFeatureServices();
for (final Iterator it = rs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if (o instanceof MapService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N
}
}
handleMapService(rsi, (MapService)o, forced);
} else {
LOG.warn("service is not of type MapService:" + o); // NOI18N
}
}
for (final Iterator it = fs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int fsi = ((Integer)key).intValue();
final Object o = fs.get(key);
if (o instanceof MapService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N
}
}
handleMapService(fsi, (MapService)o, forced);
} else {
LOG.warn("service is not of type MapService:" + o); // NOI18N
}
}
}
}
};
CismetThreadPool.execute(r);
}
}
/**
* queryServicesIndependentFromMap.
*
* @param width DOCUMENT ME!
* @param height DOCUMENT ME!
* @param bb DOCUMENT ME!
* @param rl DOCUMENT ME!
*/
public void queryServicesIndependentFromMap(final int width,
final int height,
final BoundingBox bb,
final RetrievalListener rl) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N
}
}
final Runnable r = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception doNothing) {
}
}
if (MappingComponent.this.isBackgroundEnabled()) {
final TreeMap rs = mappingModel.getRasterServices();
final TreeMap fs = mappingModel.getFeatureServices();
for (final Iterator it = rs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int rsi = ((Integer)key).intValue();
final Object o = rs.get(key);
if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer)
&& ((ServiceLayer)o).isEnabled()
&& (o instanceof RetrievalServiceLayer)
&& ((RetrievalServiceLayer)o).getPNode().getVisible()) {
try {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap: cloning '"
+ o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N
}
}
AbstractRetrievalService r;
if (o instanceof WebFeatureService) {
final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o)
.clone();
wfsClone.removeAllListeners();
r = wfsClone;
} else {
r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners();
}
r.addRetrievalListener(rl);
((ServiceLayer)r).setLayerPosition(rsi);
handleMapService(rsi, (MapService)r, width, height, bb, true);
} catch (final Exception t) {
LOG.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N
}
} else {
LOG.warn("ignoring service '" + o + "' for printing"); // NOI18N
}
}
for (final Iterator it = fs.keySet().iterator(); it.hasNext();) {
final Object key = it.next();
final int fsi = ((Integer)key).intValue();
final Object o = fs.get(key);
if (o instanceof AbstractRetrievalService) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("queryServicesIndependentFromMap: cloning '"
+ o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N
}
}
AbstractRetrievalService r;
if (o instanceof WebFeatureService) {
final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o)
.clone();
wfsClone.removeAllListeners();
r = (AbstractRetrievalService)o;
} else {
r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners();
}
r.addRetrievalListener(rl);
((ServiceLayer)r).setLayerPosition(fsi);
handleMapService(fsi, (MapService)r, 0, 0, bb, true);
}
}
}
}
};
CismetThreadPool.execute(r);
}
/**
* former synchronized method.
*
* @param position DOCUMENT ME!
* @param service rs
* @param forced DOCUMENT ME!
*/
public void handleMapService(final int position, final MapService service, final boolean forced) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("in handleRasterService: " + service + "("
+ Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N
}
}
final PBounds bounds = getCamera().getViewBounds();
final BoundingBox bb = new BoundingBox();
final double x1 = getWtst().getWorldX(bounds.getMinX());
final double y1 = getWtst().getWorldY(bounds.getMaxY());
final double x2 = getWtst().getWorldX(bounds.getMaxX());
final double y2 = getWtst().getWorldY(bounds.getMinY());
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Bounds=" + bounds); // NOI18N
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N
}
}
if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N
bb.setX1(x1 - (x2 - x1));
bb.setY1(y1 - (y2 - y1));
bb.setX2(x2 + (x2 - x1));
bb.setY2(y2 + (y2 - y1));
} else {
bb.setX1(x1);
bb.setY1(y1);
bb.setX2(x2);
bb.setY2(y2);
}
handleMapService(position, service, getWidth(), getHeight(), bb, forced);
}
/**
* former synchronized method.
*
* @param position DOCUMENT ME!
* @param rs DOCUMENT ME!
* @param width DOCUMENT ME!
* @param height DOCUMENT ME!
* @param bb DOCUMENT ME!
* @param forced DOCUMENT ME!
*/
private void handleMapService(final int position,
final MapService rs,
final int width,
final int height,
final BoundingBox bb,
final boolean forced) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("handleMapService: " + rs); // NOI18N
}
}
rs.setSize(height, width);
if (((ServiceLayer)rs).isEnabled()) {
synchronized (serviceFuturesMap) {
final Future<?> sf = serviceFuturesMap.get(rs);
if ((sf == null) || sf.isDone()) {
final Runnable serviceCall = new Runnable() {
@Override
public void run() {
try {
while (getAnimating()) {
try {
Thread.currentThread().sleep(50);
} catch (final Exception e) {
}
}
rs.setBoundingBox(bb);
if (rs instanceof FeatureAwareRasterService) {
((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection);
}
rs.retrieve(forced);
} finally {
serviceFuturesMap.remove(rs);
}
}
};
synchronized (serviceFuturesMap) {
serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall));
}
}
}
}
}
/**
* Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it.
*
* @return new WorldToScreenTransform or null
*/
public WorldToScreenTransform getWtst() {
try {
if (wtst == null) {
final double y_real = mappingModel.getInitialBoundingBox().getY2()
- mappingModel.getInitialBoundingBox().getY1();
final double x_real = mappingModel.getInitialBoundingBox().getX2()
- mappingModel.getInitialBoundingBox().getX1();
double clip_height;
double clip_width;
double x_screen = getWidth();
double y_screen = getHeight();
if (x_screen == 0) {
x_screen = 100;
}
if (y_screen == 0) {
y_screen = 100;
}
if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert
clip_height = x_screen * y_real / x_real;
clip_width = x_screen;
clip_offset_y = 0; // (y_screen-clip_height)/2;
clip_offset_x = 0;
} else { // Y ist Bestimmer
clip_height = y_screen;
clip_width = y_screen * x_real / y_real;
clip_offset_y = 0;
clip_offset_x = 0; // (x_screen-clip_width)/2;
}
wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),
mappingModel.getInitialBoundingBox().getY2());
}
return wtst;
} catch (final Exception t) {
LOG.error("Fehler in getWtst()", t); // NOI18N
return null;
}
}
/**
* Resets the current WorldToScreenTransformation.
*/
public void resetWtst() {
wtst = null;
}
/**
* Returns 0.
*
* @return DOCUMENT ME!
*/
public double getClip_offset_x() {
return 0; // clip_offset_x;
}
/**
* Assigns a new value to the x-clip-offset.
*
* @param clip_offset_x new clipoffset
*/
public void setClip_offset_x(final double clip_offset_x) {
this.clip_offset_x = clip_offset_x;
}
/**
* Returns 0.
*
* @return DOCUMENT ME!
*/
public double getClip_offset_y() {
return 0; // clip_offset_y;
}
/**
* Assigns a new value to the y-clip-offset.
*
* @param clip_offset_y new clipoffset
*/
public void setClip_offset_y(final double clip_offset_y) {
this.clip_offset_y = clip_offset_y;
}
/**
* Returns the rubberband-PLayer.
*
* @return DOCUMENT ME!
*/
public PLayer getRubberBandLayer() {
return rubberBandLayer;
}
/**
* Assigns a given PLayer to the variable rubberBandLayer.
*
* @param rubberBandLayer a PLayer
*/
public void setRubberBandLayer(final PLayer rubberBandLayer) {
this.rubberBandLayer = rubberBandLayer;
}
/**
* Sets new viewbounds.
*
* @param r2d Rectangle2D
*/
public void setNewViewBounds(final Rectangle2D r2d) {
newViewBounds = r2d;
}
/**
* Will be called if the selection of features changes. It selects the PFeatures connected to the selected features
* of the featurecollectionevent and moves them to the front. Also repaints handles at the end.
*
* @param fce featurecollectionevent with selected features
*/
@Override
public void featureSelectionChanged(final FeatureCollectionEvent fce) {
final Collection allChildren = featureLayer.getChildrenReference();
final ArrayList<PFeature> all = new ArrayList<PFeature>();
for (final Object o : allChildren) {
if (o instanceof PFeature) {
all.add((PFeature)o);
} else if (o instanceof PLayer) {
// Handling von Feature-Gruppen-Layer, welche als Kinder dem Feature Layer hinzugefügt wurden
all.addAll(((PLayer)o).getChildrenReference());
}
}
// final Collection<PFeature> all = featureLayer.getChildrenReference();
for (final PFeature f : all) {
f.setSelected(false);
}
Collection<Feature> c;
if (fce != null) {
c = fce.getFeatureCollection().getSelectedFeatures();
} else {
c = featureCollection.getSelectedFeatures();
}
////handle featuregroup select-delegation////
final Set<Feature> selectionResult = new HashSet<Feature>();
for (final Feature current : c) {
if (current instanceof FeatureGroup) {
selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current));
} else {
selectionResult.add(current);
}
}
c = selectionResult;
for (final Feature f : c) {
if (f != null) {
final PFeature feature = getPFeatureHM().get(f);
if (feature != null) {
if (feature.getParent() != null) {
feature.getParent().moveToFront();
}
feature.setSelected(true);
feature.moveToFront();
// Fuer den selectedObjectPresenter (Eigener PCanvas)
syncSelectedObjectPresenter(1000);
} else {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
}
}
showHandles(false);
}
/**
* Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on
* each feature of the given featurecollectionevent. Repaints handles at the end.
*
* @param fce featurecollectionevent with changed features
*/
@Override
public void featuresChanged(final FeatureCollectionEvent fce) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("featuresChanged"); // NOI18N
}
}
final List<Feature> list = new ArrayList<Feature>();
list.addAll(fce.getEventFeatures());
for (final Feature elem : list) {
reconsiderFeature(elem);
}
showHandles(false);
}
/**
* Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls
* following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode()
*
* @param fce featurecollectionevent with features to reconsile
*/
@Override
public void featureReconsiderationRequested(final FeatureCollectionEvent fce) {
for (final Feature f : fce.getEventFeatures()) {
if (f != null) {
final PFeature node = pFeatureHM.get(f);
if (node != null) {
node.syncGeometry();
node.visualize();
node.resetInfoNodePosition();
node.refreshInfoNode();
repaint();
}
}
}
}
/**
* Method is deprecated and deactivated. Does nothing!!
*
* @param fce FeatureCollectionEvent with features to add
*/
@Override
@Deprecated
public void featuresAdded(final FeatureCollectionEvent fce) {
}
/**
* Method is deprecated and deactivated. Does nothing!!
*
* @deprecated DOCUMENT ME!
*/
@Override
@Deprecated
public void featureCollectionChanged() {
}
/**
* Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a
* checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent.
*
* @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice
*/
@Override
public void allFeaturesRemoved(final FeatureCollectionEvent fce) {
for (final PFeature feature : pFeatureHM.values()) {
feature.cleanup();
}
stickyPNodes.clear();
pFeatureHM.clear();
featureLayer.removeAllChildren();
// Lösche alle Features in den Gruppen-Layer, aber füge den Gruppen-Layer wieder dem FeatureLayer hinzu
for (final PLayer layer : featureGrpLayerMap.values()) {
layer.removeAllChildren();
featureLayer.addChild(layer);
}
checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce);
}
/**
* Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining
* supporting rasterservices and paints handles at the end.
*
* @param fce FeatureCollectionEvent with features to remove
*/
@Override
public void featuresRemoved(final FeatureCollectionEvent fce) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("featuresRemoved"); // NOI18N
}
}
removeFeatures(fce.getEventFeatures());
checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce);
showHandles(false);
}
/**
* Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and
* which need a refresh.
*
* @param fce FeatureCollectionEvent with removed features
*/
private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) {
final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved =
new HashSet<FeatureAwareRasterService>();
final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed =
new HashSet<FeatureAwareRasterService>();
final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>();
for (final Feature f : getFeatureCollection().getAllFeatures()) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N
}
}
rasterServices.add(rs); // DANGER
}
}
for (final Feature f : fce.getEventFeatures()) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N
}
}
if (rasterServices.contains(rs)) {
for (final Object o : getMappingModel().getRasterServices().values()) {
final MapService r = (MapService)o;
if (r.equals(rs)) {
rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r);
}
}
} else {
for (final Object o : getMappingModel().getRasterServices().values()) {
final MapService r = (MapService)o;
if (r.equals(rs)) {
rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r);
}
}
}
}
}
for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) {
getMappingModel().removeLayer(frs);
}
for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) {
handleMapService(0, frs, true);
}
}
/**
* public void showFeatureCollection(Feature[] features) { com.vividsolutions.jts.geom.Envelope
* env=computeFeatureEnvelope(features); showFeatureCollection(features,env); } public void
* showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { selectedFeature=null;
* handleLayer.removeAllChildren(); //setRasterServiceLayerImagesVisibility(false); Envelope eSquare=null; HashSet<Feature>
* featureSet=new HashSet<Feature>(); featureSet.addAll(holdFeatures);
* featureSet.addAll(java.util.Arrays.asList(f)); Feature[] features=featureSet.toArray(new Feature[0]);
* pFeatureHM.clear(); addFeaturesToMap(features); zoomToFullFeatureCollectionBounds(); }.
*
* @param groupId DOCUMENT ME!
* @param visible DOCUMENT ME!
*/
public void setGroupLayerVisibility(final String groupId, final boolean visible) {
final PLayer layer = this.featureGrpLayerMap.get(groupId);
if (layer != null) {
layer.setVisible(visible);
}
}
/**
* is called when new feature is added to FeatureCollection.
*
* @param features DOCUMENT ME!
*/
public void addFeaturesToMap(final Feature[] features) {
final double local_clip_offset_y = clip_offset_y;
final double local_clip_offset_x = clip_offset_x;
/// Hier muss der layer bestimmt werdenn
for (int i = 0; i < features.length; ++i) {
final Feature feature = features[i];
final PFeature p = new PFeature(
feature,
getWtst(),
local_clip_offset_x,
local_clip_offset_y,
MappingComponent.this);
try {
if (feature instanceof StyledFeature) {
p.setTransparency(((StyledFeature)(feature)).getTransparency());
} else {
p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency());
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (feature instanceof FeatureGroupMember) {
final FeatureGroupMember fgm = (FeatureGroupMember)feature;
final String groupId = fgm.getGroupId();
PLayer groupLayer = featureGrpLayerMap.get(groupId);
if (groupLayer == null) {
groupLayer = new PLayer();
featureLayer.addChild(groupLayer);
featureGrpLayerMap.put(groupId, groupLayer);
if (LOG.isDebugEnabled()) {
LOG.debug("created layer for group " + groupId);
}
}
groupLayer.addChild(p);
if (fgm.getGeometry() != null) {
pFeatureHM.put(fgm.getFeature(), p);
pFeatureHM.put(fgm, p);
}
if (LOG.isDebugEnabled()) {
LOG.debug("added feature to group " + groupId);
}
}
}
});
} catch (final Exception e) {
p.setTransparency(0.8f);
LOG.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N
}
// So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt)
if (!(feature instanceof FeatureGroupMember)) {
if (feature.getGeometry() != null) {
pFeatureHM.put(p.getFeature(), p);
final int ii = i;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
featureLayer.addChild(p);
if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) {
p.moveToFront();
}
}
});
}
}
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
rescaleStickyNodes();
repaint();
fireFeaturesAddedToMap(Arrays.asList(features));
// SuchFeatures in den Vordergrund stellen
for (final Feature feature : featureCollection.getAllFeatures()) {
if (feature instanceof SearchFeature) {
final PFeature pFeature = pFeatureHM.get(feature);
pFeature.moveToFront();
}
}
}
});
// check whether the feature has a rasterSupportLayer or not
for (final Feature f : features) {
if ((f instanceof RasterLayerSupportedFeature)
&& (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) {
final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService();
if (!getMappingModel().getRasterServices().containsValue(rs)) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("FeatureAwareRasterServiceAdded"); // NOI18N
}
}
rs.setFeatureCollection(getFeatureCollection());
getMappingModel().addLayer(rs);
}
}
}
showHandles(false);
}
/**
* DOCUMENT ME!
*
* @param cf DOCUMENT ME!
*/
private void fireFeaturesAddedToMap(final Collection<Feature> cf) {
for (final MapListener curMapListener : mapListeners) {
curMapListener.featuresAddedToMap(cf);
}
}
/**
* Creates an envelope around all features from the given array.
*
* @param features features to create the envelope around
*
* @return Envelope com.vividsolutions.jts.geom.Envelope
*/
private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) {
final PNode root = new PNode();
for (int i = 0; i < features.length; ++i) {
final PNode p = PNodeFactory.createPFeature(features[i], this);
if (p != null) {
root.addChild(p);
}
}
final PBounds ext = root.getFullBounds();
final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope(
ext.x,
ext.x
+ ext.width,
ext.y,
ext.y
+ ext.height);
return env;
}
/**
* Zooms in / out to match the bounds of the featurecollection.
*/
public void zoomToFullFeatureCollectionBounds() {
zoomToFeatureCollection();
}
/**
* Adds a new cursor to the cursor-hashmap.
*
* @param mode interactionmode as string
* @param cursor cursor-object
*/
public void putCursor(final String mode, final Cursor cursor) {
cursors.put(mode, cursor);
}
/**
* Returns the cursor assigned to the given mode.
*
* @param mode mode as String
*
* @return Cursor-object or null
*/
public Cursor getCursor(final String mode) {
return cursors.get(mode);
}
/**
* Adds a new PBasicInputEventHandler for a specific interactionmode.
*
* @param mode interactionmode as string
* @param listener new PBasicInputEventHandler
*/
public void addInputListener(final String mode, final PBasicInputEventHandler listener) {
inputEventListener.put(mode, listener);
}
/**
* Returns the PBasicInputEventHandler assigned to the committed interactionmode.
*
* @param mode interactionmode as string
*
* @return PBasicInputEventHandler-object or null
*/
public PInputEventListener getInputListener(final String mode) {
final Object o = inputEventListener.get(mode);
if (o instanceof PInputEventListener) {
return (PInputEventListener)o;
} else {
return null;
}
}
/**
* Returns whether the features are editable or not.
*
* @return DOCUMENT ME!
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Sets all Features ReadOnly use Feature.setEditable(boolean) instead.
*
* @param readOnly DOCUMENT ME!
*/
public void setReadOnly(final boolean readOnly) {
for (final Object f : featureCollection.getAllFeatures()) {
((Feature)f).setEditable(!readOnly);
}
this.readOnly = readOnly;
handleLayer.repaint();
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
snapHandleLayer.removeAllChildren();
}
/**
* Returns the current HandleInteractionMode.
*
* @return DOCUMENT ME!
*/
public String getHandleInteractionMode() {
return handleInteractionMode;
}
/**
* Changes the HandleInteractionMode. Repaints handles.
*
* @param handleInteractionMode the new HandleInteractionMode
*/
public void setHandleInteractionMode(final String handleInteractionMode) {
this.handleInteractionMode = handleInteractionMode;
showHandles(false);
}
/**
* Returns whether the background is enabled or not.
*
* @return DOCUMENT ME!
*/
public boolean isBackgroundEnabled() {
return backgroundEnabled;
}
/**
* TODO.
*
* @param backgroundEnabled DOCUMENT ME!
*/
public void setBackgroundEnabled(final boolean backgroundEnabled) {
if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) {
featureServiceLayerVisible = featureServiceLayer.getVisible();
}
this.mapServicelayer.setVisible(backgroundEnabled);
this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible);
for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) {
featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible);
}
if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) {
this.queryServices();
}
this.backgroundEnabled = backgroundEnabled;
}
/**
* Returns the featurelayer.
*
* @return DOCUMENT ME!
*/
public PLayer getFeatureLayer() {
return featureLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map<String, PLayer> getFeatureGroupLayers() {
return this.featureGrpLayerMap;
}
/**
* Adds a PFeature to the PFeatureHashmap.
*
* @param p PFeature to add
*/
public void refreshHM(final PFeature p) {
pFeatureHM.put(p.getFeature(), p);
}
/**
* Returns the selectedObjectPresenter (PCanvas).
*
* @return DOCUMENT ME!
*/
public PCanvas getSelectedObjectPresenter() {
return selectedObjectPresenter;
}
/**
* If f != null it calls the reconsiderFeature()-method of the featurecollection.
*
* @param f feature to reconcile
*/
public void reconsiderFeature(final Feature f) {
if (f != null) {
featureCollection.reconsiderFeature(f);
}
}
/**
* Removes all features of the collection from the hashmap.
*
* @param fc collection of features to remove
*/
public void removeFeatures(final Collection<Feature> fc) {
featureLayer.setVisible(false);
for (final Feature elem : fc) {
removeFromHM(elem);
}
featureLayer.setVisible(true);
}
/**
* Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key.
*
* @param f feature of the Pfeature that should be deleted
*/
public void removeFromHM(final Feature f) {
final PFeature pf = pFeatureHM.get(f);
if (pf != null) {
pf.cleanup();
pFeatureHM.remove(f);
stickyPNodes.remove(pf);
try {
LOG.info("Entferne Feature " + f); // NOI18N
featureLayer.removeChild(pf);
for (final PLayer grpLayer : this.featureGrpLayerMap.values()) {
if (grpLayer.removeChild(pf) != null) {
break;
}
}
} catch (Exception ex) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N
}
}
}
} else {
LOG.warn("Feature war nicht in pFeatureHM"); // NOI18N
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("pFeatureHM" + pFeatureHM); // NOI18N
}
}
}
/**
* Zooms to the current selected node.
*
* @deprecated DOCUMENT ME!
*/
public void zoomToSelectedNode() {
zoomToSelection();
}
/**
* Zooms to the current selected features.
*/
public void zoomToSelection() {
final Collection<Feature> selection = featureCollection.getSelectedFeatures();
zoomToAFeatureCollection(selection, true, false);
}
/**
* Zooms to a specific featurecollection.
*
* @param collection the featurecolltion
* @param withHistory should the zoomaction be undoable
* @param fixedScale fixedScale
*/
public void zoomToAFeatureCollection(final Collection<Feature> collection,
final boolean withHistory,
final boolean fixedScale) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("zoomToAFeatureCollection"); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
boolean first = true;
Geometry g = null;
for (final Feature f : collection) {
if (first) {
if (f.getGeometry() != null) {
g = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode())
.getEnvelope();
if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) {
g = g.buffer(((Bufferable)f).getBuffer() + 0.001);
}
first = false;
}
} else {
if (f.getGeometry() != null) {
Geometry geometry = CrsTransformer.transformToGivenCrs(f.getGeometry(),
mappingModel.getSrs().getCode())
.getEnvelope();
if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) {
geometry = geometry.buffer(((Bufferable)f).getBuffer() + 0.001);
}
g = g.getEnvelope().union(geometry);
}
}
}
if (g != null) {
// FIXME: we shouldn't only complain but do sth
if ((getHeight() == 0) || (getWidth() == 0)) {
LOG.warn("DIVISION BY ZERO"); // NOI18N
}
// dreisatz.de
final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10;
final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10;
double buff = 0;
if (hBuff > vBuff) {
buff = hBuff;
} else {
buff = vBuff;
}
if (buff == 0.0) {
if (mappingModel.getSrs().isMetric()) {
buff = 1.0;
} else {
buff = 0.01;
}
}
g = g.buffer(buff);
final BoundingBox bb = new BoundingBox(g);
final boolean onlyOnePoint = (collection.size() == 1)
&& (((Feature)(collection.toArray()[0])).getGeometry()
instanceof com.vividsolutions.jts.geom.Point);
gotoBoundingBox(bb, withHistory, !(fixedScale || (onlyOnePoint && (g.getArea() < 10))), animationDuration);
}
}
/**
* Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create
* their handles and to add them to the handlelayer.
*
* @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles
*/
public void showHandles(final boolean waitTillAllAnimationsAreComplete) {
// are there features selected?
if (featureCollection.getSelectedFeatures().size() > 0) {
// DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf
final Runnable handle = new Runnable() {
@Override
public void run() {
// alle bisherigen Handles entfernen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
});
while (getAnimating() && waitTillAllAnimationsAreComplete) {
try {
Thread.currentThread().sleep(10);
} catch (final Exception e) {
LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N
}
}
if (featureCollection.areFeaturesEditable()
&& (getInteractionMode().equals(SELECT)
|| getInteractionMode().equals(LINEAR_REFERENCING)
|| getInteractionMode().equals(PAN)
|| getInteractionMode().equals(ZOOM)
|| getInteractionMode().equals(ALKIS_PRINT)
|| getInteractionMode().equals(SPLIT_POLYGON))) {
// Handles für alle selektierten Features der Collection hinzufügen
if (getHandleInteractionMode().equals(ROTATE_POLYGON)) {
final LinkedHashSet<Feature> copy = new LinkedHashSet(
featureCollection.getSelectedFeatures());
for (final Feature selectedFeature : copy) {
if ((selectedFeature instanceof Feature) && selectedFeature.isEditable()) {
if (pFeatureHM.get(selectedFeature) != null) {
// manipulates gui -> edt
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
pFeatureHM.get(selectedFeature).addRotationHandles(handleLayer);
}
});
} else {
LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N
}
}
}
} else {
final LinkedHashSet<Feature> copy = new LinkedHashSet(
featureCollection.getSelectedFeatures());
for (final Feature selectedFeature : copy) {
if ((selectedFeature != null) && selectedFeature.isEditable()) {
if (pFeatureHM.get(selectedFeature) != null) {
// manipulates gui -> edt
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
pFeatureHM.get(selectedFeature).addHandles(handleLayer);
} catch (final Exception e) {
LOG.error("Error bei addHandles: ", e); // NOI18N
}
}
});
} else {
LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N
}
// DANGER mit break werden nur die Handles EINES slektierten Features angezeigt
// wird break auskommentiert werden jedoch zu viele Handles angezeigt break;
}
}
}
}
}
};
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("showHandles", new CurrentStackTrace()); // NOI18N
}
}
CismetThreadPool.execute(handle);
} else {
// alle bisherigen Handles entfernen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
}
});
}
}
/**
* Will return a PureNewFeature if there is only one in the featurecollection else null.
*
* @return DOCUMENT ME!
*/
public PFeature getSolePureNewFeature() {
int counter = 0;
PFeature sole = null;
for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) {
final Object o = it.next();
if (o instanceof PFeature) {
if (((PFeature)o).getFeature() instanceof PureNewFeature) {
++counter;
sole = ((PFeature)o);
}
}
}
if (counter == 1) {
return sole;
} else {
return null;
}
}
/**
* Returns the temporary featurelayer.
*
* @return DOCUMENT ME!
*/
public PLayer getTmpFeatureLayer() {
return tmpFeatureLayer;
}
/**
* Assigns a new temporary featurelayer.
*
* @param tmpFeatureLayer PLayer
*/
public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) {
this.tmpFeatureLayer = tmpFeatureLayer;
}
/**
* Returns whether the grid is enabled or not.
*
* @return DOCUMENT ME!
*/
public boolean isGridEnabled() {
return gridEnabled;
}
/**
* Enables or disables the grid.
*
* @param gridEnabled true, to enable the grid
*/
public void setGridEnabled(final boolean gridEnabled) {
this.gridEnabled = gridEnabled;
}
/**
* Returns a String from two double-values. Serves the visualization.
*
* @param x X-coordinate
* @param y Y-coordinate
*
* @return a String-object like "(X,Y)"
*/
public static String getCoordinateString(final double x, final double y) {
final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N
final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public com.vividsolutions.jts.geom.Point getPointGeometryFromPInputEvent(final PInputEvent event) {
final double xCoord = getWtst().getSourceX(event.getPosition().getX() - getClip_offset_x());
final double yCoord = getWtst().getSourceY(event.getPosition().getY() - getClip_offset_y());
final GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),
CrsTransformer.extractSridFromCrs(getMappingModel().getSrs().getCode()));
return gf.createPoint(new Coordinate(xCoord, yCoord));
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getHandleLayer() {
return handleLayer;
}
/**
* DOCUMENT ME!
*
* @param handleLayer DOCUMENT ME!
*/
public void setHandleLayer(final PLayer handleLayer) {
this.handleLayer = handleLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisualizeSnappingEnabled() {
return visualizeSnappingEnabled;
}
/**
* DOCUMENT ME!
*
* @param visualizeSnappingEnabled DOCUMENT ME!
*/
public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) {
this.visualizeSnappingEnabled = visualizeSnappingEnabled;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisualizeSnappingRectEnabled() {
return visualizeSnappingRectEnabled;
}
/**
* DOCUMENT ME!
*
* @param visualizeSnappingRectEnabled DOCUMENT ME!
*/
public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) {
this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getSnappingRectSize() {
return snappingRectSize;
}
/**
* DOCUMENT ME!
*
* @param snappingRectSize DOCUMENT ME!
*/
public void setSnappingRectSize(final int snappingRectSize) {
this.snappingRectSize = snappingRectSize;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getSnapHandleLayer() {
return snapHandleLayer;
}
/**
* DOCUMENT ME!
*
* @param snapHandleLayer DOCUMENT ME!
*/
public void setSnapHandleLayer(final PLayer snapHandleLayer) {
this.snapHandleLayer = snapHandleLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isSnappingEnabled() {
return snappingEnabled;
}
/**
* DOCUMENT ME!
*
* @param snappingEnabled DOCUMENT ME!
*/
public void setSnappingEnabled(final boolean snappingEnabled) {
this.snappingEnabled = snappingEnabled;
setVisualizeSnappingEnabled(snappingEnabled);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getFeatureServiceLayer() {
return featureServiceLayer;
}
/**
* DOCUMENT ME!
*
* @param featureServiceLayer DOCUMENT ME!
*/
public void setFeatureServiceLayer(final PLayer featureServiceLayer) {
this.featureServiceLayer = featureServiceLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getAnimationDuration() {
return animationDuration;
}
/**
* DOCUMENT ME!
*
* @param animationDuration DOCUMENT ME!
*/
public void setAnimationDuration(final int animationDuration) {
this.animationDuration = animationDuration;
}
/**
* DOCUMENT ME!
*
* @param prefs DOCUMENT ME!
*/
@Deprecated
public void setPreferences(final CismapPreferences prefs) {
LOG.warn("involing deprecated operation setPreferences()"); // NOI18N
cismapPrefs = prefs;
final ActiveLayerModel mm = new ActiveLayerModel();
final LayersPreferences layersPrefs = prefs.getLayersPrefs();
final GlobalPreferences globalPrefs = prefs.getGlobalPrefs();
setSnappingRectSize(globalPrefs.getSnappingRectSize());
setSnappingEnabled(globalPrefs.isSnappingEnabled());
setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled());
setAnimationDuration(globalPrefs.getAnimationDuration());
setInteractionMode(globalPrefs.getStartMode());
mm.addHome(globalPrefs.getInitialBoundingBox());
final Crs crs = new Crs();
crs.setCode(globalPrefs.getInitialBoundingBox().getSrs());
crs.setName(globalPrefs.getInitialBoundingBox().getSrs());
crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs());
mm.setSrs(crs);
final TreeMap raster = layersPrefs.getRasterServices();
if (raster != null) {
final Iterator it = raster.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final Object o = raster.get(key);
if (o instanceof MapService) {
mm.addLayer((RetrievalServiceLayer)o);
}
}
}
final TreeMap features = layersPrefs.getFeatureServices();
if (features != null) {
final Iterator it = features.keySet().iterator();
while (it.hasNext()) {
final Object key = it.next();
final Object o = features.get(key);
if (o instanceof MapService) {
// TODO
mm.addLayer((RetrievalServiceLayer)o);
}
}
}
setMappingModel(mm);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public CismapPreferences getCismapPrefs() {
return cismapPrefs;
}
/**
* DOCUMENT ME!
*
* @param duration DOCUMENT ME!
* @param animationDuration DOCUMENT ME!
* @param what DOCUMENT ME!
* @param number DOCUMENT ME!
*/
public void flash(final int duration, final int animationDuration, final int what, final int number) {
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getDragPerformanceImproverLayer() {
return dragPerformanceImproverLayer;
}
/**
* DOCUMENT ME!
*
* @param dragPerformanceImproverLayer DOCUMENT ME!
*/
public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) {
this.dragPerformanceImproverLayer = dragPerformanceImproverLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Deprecated
public PLayer getRasterServiceLayer() {
return mapServicelayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getMapServiceLayer() {
return mapServicelayer;
}
/**
* DOCUMENT ME!
*
* @param rasterServiceLayer DOCUMENT ME!
*/
public void setRasterServiceLayer(final PLayer rasterServiceLayer) {
this.mapServicelayer = rasterServiceLayer;
}
/**
* DOCUMENT ME!
*
* @param f DOCUMENT ME!
*/
public void showGeometryInfoPanel(final Feature f) {
}
/**
* Adds a PropertyChangeListener to the listener list.
*
* @param l The listener to add.
*/
@Override
public void addPropertyChangeListener(final PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
/**
* Removes a PropertyChangeListener from the listener list.
*
* @param l The listener to remove.
*/
@Override
public void removePropertyChangeListener(final PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
/**
* Setter for property taskCounter. former synchronized method
*/
public void fireActivityChanged() {
propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N
}
/**
* Returns true, if there's still one layercontrol running. Else false; former synchronized method
*
* @return DOCUMENT ME!
*/
public boolean isRunning() {
for (final LayerControl lc : layerControls) {
if (lc.isRunning()) {
return true;
}
}
return false;
}
/**
* Sets the visibility of all infonodes.
*
* @param visible true, if infonodes should be visible
*/
public void setInfoNodesVisible(final boolean visible) {
infoNodesVisible = visible;
for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) {
final Object elem = it.next();
if (elem instanceof PFeature) {
((PFeature)elem).setInfoNodeVisible(visible);
}
}
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("setInfoNodesVisible()"); // NOI18N
}
}
rescaleStickyNodes();
}
/**
* Adds an object to the historymodel.
*
* @param o Object to add
*/
@Override
public void addToHistory(final Object o) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("addToHistory:" + o.toString()); // NOI18N
}
}
historyModel.addToHistory(o);
}
/**
* Removes a specific HistoryModelListener from the historymodel.
*
* @param hml HistoryModelListener
*/
@Override
public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) {
historyModel.removeHistoryModelListener(hml);
}
/**
* Adds aHistoryModelListener to the historymodel.
*
* @param hml HistoryModelListener
*/
@Override
public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) {
historyModel.addHistoryModelListener(hml);
}
/**
* Sets the maximum value of saved historyactions.
*
* @param max new integer value
*/
@Override
public void setMaximumPossibilities(final int max) {
historyModel.setMaximumPossibilities(max);
}
/**
* Redos the last undone historyaction.
*
* @param external true, if fireHistoryChanged-action should be fired
*
* @return PBounds of the forward-action
*/
@Override
public Object forward(final boolean external) {
final PBounds fwd = (PBounds)historyModel.forward(external);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("HistoryModel.forward():" + fwd); // NOI18N
}
}
if (external) {
this.gotoBoundsWithoutHistory(fwd);
}
return fwd;
}
/**
* Undos the last action.
*
* @param external true, if fireHistoryChanged-action should be fired
*
* @return PBounds of the back-action
*/
@Override
public Object back(final boolean external) {
final PBounds back = (PBounds)historyModel.back(external);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("HistoryModel.back():" + back); // NOI18N
}
}
if (external) {
this.gotoBoundsWithoutHistory(back);
}
return back;
}
/**
* Returns true, if it's possible to redo an action.
*
* @return DOCUMENT ME!
*/
@Override
public boolean isForwardPossible() {
return historyModel.isForwardPossible();
}
/**
* Returns true, if it's possible to undo an action.
*
* @return DOCUMENT ME!
*/
@Override
public boolean isBackPossible() {
return historyModel.isBackPossible();
}
/**
* Returns a vector with all redo-possibilities.
*
* @return DOCUMENT ME!
*/
@Override
public Vector getForwardPossibilities() {
return historyModel.getForwardPossibilities();
}
/**
* Returns the current element of the historymodel.
*
* @return DOCUMENT ME!
*/
@Override
public Object getCurrentElement() {
return historyModel.getCurrentElement();
}
/**
* Returns a vector with all undo-possibilities.
*
* @return DOCUMENT ME!
*/
@Override
public Vector getBackPossibilities() {
return historyModel.getBackPossibilities();
}
/**
* Returns whether an internallayerwidget is available.
*
* @return DOCUMENT ME!
*/
@Deprecated
public boolean isInternalLayerWidgetAvailable() {
return this.getInternalWidget(LAYERWIDGET) != null;
}
/**
* Sets the variable, if an internallayerwidget is available or not.
*
* @param internalLayerWidgetAvailable true, if available
*/
@Deprecated
public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) {
if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) {
this.removeInternalWidget(LAYERWIDGET);
} else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) {
final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget(
MappingComponent.this);
MappingComponent.this.addInternalWidget(
LAYERWIDGET,
MappingComponent.POSITION_SOUTHEAST,
simpleInternalLayerWidget);
}
}
/**
* DOCUMENT ME!
*
* @param mme DOCUMENT ME!
*/
@Override
public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) {
}
/**
* Removes the mapservice from the rasterservicelayer.
*
* @param rasterService the removing mapservice
*/
@Override
public void mapServiceRemoved(final MapService rasterService) {
try {
mapServicelayer.removeChild(rasterService.getPNode());
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_REMOVED, rasterService));
}
System.gc();
} catch (final Exception e) {
LOG.warn("Fehler bei mapServiceRemoved", e); // NOI18N
}
}
/**
* Adds the commited mapservice on the last position to the rasterservicelayer.
*
* @param mapService the new mapservice
*/
@Override
public void mapServiceAdded(final MapService mapService) {
addMapService(mapService, mapServicelayer.getChildrenCount());
if (mapService instanceof FeatureAwareRasterService) {
((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection());
}
if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) {
handleMapService(0, mapService, false);
}
}
/**
* Returns the current OGC scale.
*
* @return DOCUMENT ME!
*/
public double getCurrentOGCScale() {
// funktioniert nur bei metrischen SRS's
final double h = getCamera().getViewBounds().getHeight() / getHeight();
final double w = getCamera().getViewBounds().getWidth() / getWidth();
return Math.sqrt((h * h) + (w * w));
}
/**
* Returns the current BoundingBox.
*
* @return DOCUMENT ME!
*/
public BoundingBox getCurrentBoundingBox() {
if (fixedBoundingBox != null) {
return fixedBoundingBox;
} else {
try {
final PBounds bounds = getCamera().getViewBounds();
final double x1 = wtst.getWorldX(bounds.getX());
final double y1 = wtst.getWorldY(bounds.getY());
final double x2 = x1 + bounds.width;
final double y2 = y1 - bounds.height;
final Crs currentCrs = CismapBroker.getInstance().getSrs();
final boolean metric;
// FIXME: this is a hack to overcome the "metric" issue for 4326 default srs
if (CrsTransformer.getCurrentSrid() == 4326) {
metric = false;
} else {
metric = currentCrs.isMetric();
}
currentBoundingBox = new XBoundingBox(x1, y1, x2, y2, currentCrs.getCode(), metric);
return currentBoundingBox;
} catch (final Exception e) {
LOG.error("cannot create bounding box from current view, return null", e); // NOI18N
return null;
}
}
}
/**
* Returns a BoundingBox with a fixed size.
*
* @return DOCUMENT ME!
*/
public BoundingBox getFixedBoundingBox() {
return fixedBoundingBox;
}
/**
* Assigns fixedBoundingBox a new value.
*
* @param fixedBoundingBox new boundingbox
*/
public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) {
this.fixedBoundingBox = fixedBoundingBox;
}
/**
* Paints the outline of the forwarded BoundingBox.
*
* @param bb BoundingBox
*/
public void outlineArea(final BoundingBox bb) {
outlineArea(bb, null);
}
/**
* Paints the outline of the forwarded PBounds.
*
* @param b PBounds
*/
public void outlineArea(final PBounds b) {
outlineArea(b, null);
}
/**
* Paints a filled rectangle of the area of the forwarded BoundingBox.
*
* @param bb BoundingBox
* @param fillingPaint Color to fill the rectangle
*/
public void outlineArea(final BoundingBox bb, final Paint fillingPaint) {
PBounds pb = null;
if (bb != null) {
pb = new PBounds(wtst.getScreenX(bb.getX1()),
wtst.getScreenY(bb.getY2()),
bb.getX2()
- bb.getX1(),
bb.getY2()
- bb.getY1());
}
outlineArea(pb, fillingPaint);
}
/**
* Paints a filled rectangle of the area of the forwarded PBounds.
*
* @param b PBounds to paint
* @param fillingColor Color to fill the rectangle
*/
public void outlineArea(final PBounds b, final Paint fillingColor) {
if (b == null) {
if (highlightingLayer.getChildrenCount() > 0) {
highlightingLayer.removeAllChildren();
}
} else {
highlightingLayer.removeAllChildren();
highlightingLayer.setTransparency(1);
final PPath rectangle = new PPath();
rectangle.setPaint(fillingColor);
rectangle.setStroke(new FixedWidthStroke());
rectangle.setStrokePaint(new Color(100, 100, 100, 255));
rectangle.setPathTo(b);
highlightingLayer.addChild(rectangle);
}
}
/**
* Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally.
*
* @param bb BoundingBox to highlight
*/
public void highlightArea(final BoundingBox bb) {
PBounds pb = null;
if (bb != null) {
pb = new PBounds(wtst.getScreenX(bb.getX1()),
wtst.getScreenY(bb.getY2()),
bb.getX2()
- bb.getX1(),
bb.getY2()
- bb.getY1());
}
highlightArea(pb);
}
/**
* Highlights the delivered PBounds by painting over with a transparent white.
*
* @param b PBounds to hightlight
*/
private void highlightArea(final PBounds b) {
if (b == null) {
if (highlightingLayer.getChildrenCount() > 0) {
}
highlightingLayer.animateToTransparency(0, animationDuration);
highlightingLayer.removeAllChildren();
} else {
highlightingLayer.removeAllChildren();
highlightingLayer.setTransparency(1);
final PPath rectangle = new PPath();
rectangle.setPaint(new Color(255, 255, 255, 100));
rectangle.setStroke(null);
rectangle.setPathTo(this.getCamera().getViewBounds());
highlightingLayer.addChild(rectangle);
rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration);
}
}
/**
* Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls
* crossHairPoint(Point p) internally.
*
* @param c coordinate of the crosshair's venue
*/
public void crossHairPoint(final Coordinate c) {
Point p = null;
if (c != null) {
p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y));
}
crossHairPoint(p);
}
/**
* Paints a crosshair at the delivered point.
*
* @param p point of the crosshair's venue
*/
public void crossHairPoint(final Point p) {
if (p == null) {
if (crosshairLayer.getChildrenCount() > 0) {
crosshairLayer.removeAllChildren();
}
} else {
crosshairLayer.removeAllChildren();
crosshairLayer.setTransparency(1);
final PPath lineX = new PPath();
final PPath lineY = new PPath();
lineX.setStroke(new FixedWidthStroke());
lineX.setStrokePaint(new Color(100, 100, 100, 255));
lineY.setStroke(new FixedWidthStroke());
lineY.setStrokePaint(new Color(100, 100, 100, 255));
final PBounds current = getCamera().getViewBounds();
final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1);
final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2);
lineX.setPathTo(x);
crosshairLayer.addChild(lineX);
lineY.setPathTo(y);
crosshairLayer.addChild(lineY);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Element getConfiguration() {
if (LOG.isDebugEnabled()) {
LOG.debug("writing configuration <cismapMappingPreferences>"); // NOI18N
}
final Element ret = new Element("cismapMappingPreferences"); // NOI18N
ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N
ret.setAttribute(
"creationMode",
((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N
ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N
ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N
final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON);
if (inputListener instanceof CreateSearchGeometryListener) {
final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener;
ret.setAttribute("createSearchMode", listener.getMode());
}
// Position
final Element currentPosition = new Element("Position"); // NOI18N
currentPosition.addContent(currentBoundingBox.getJDOMElement());
currentPosition.setAttribute("CRS", mappingModel.getSrs().getCode());
ret.addContent(currentPosition);
// Crs
final Element crsListElement = new Element("crsList");
for (final Crs tmp : crsList) {
crsListElement.addContent(tmp.getJDOMElement());
}
ret.addContent(crsListElement);
if (printingSettingsDialog != null) {
ret.addContent(printingSettingsDialog.getConfiguration());
}
// save internal widgets status
final Element widgets = new Element("InternalWidgets"); // NOI18N
for (final String name : this.internalWidgets.keySet()) {
final Element widget = new Element("Widget"); // NOI18N
widget.setAttribute("name", name); // NOI18N
widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N
widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N
widgets.addContent(widget);
}
ret.addContent(widgets);
return ret;
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void masterConfigure(final Element e) {
final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N
// CRS List
try {
final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N
boolean defaultCrsFound = false;
crsList.clear();
for (final Object elem : crsElements) {
if (elem instanceof Element) {
final Crs s = new Crs((Element)elem);
crsList.add(s);
if (s.isSelected() && s.isMetric()) {
try {
if (defaultCrsFound) {
LOG.warn("More than one default CRS is set. "
+ "Please check your master configuration file."); // NOI18N
}
CismapBroker.getInstance().setDefaultCrs(s.getCode());
defaultCrsFound = true;
transformer = new CrsTransformer(s.getCode());
} catch (final Exception ex) {
LOG.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex);
}
}
}
}
} catch (final Exception skip) {
LOG.error("Error while reading the crs list", skip); // NOI18N
}
if (CismapBroker.getInstance().getDefaultCrs() == null) {
LOG.fatal("The default CRS is not set. This can lead to almost irreparable data errors. "
+ "Keep in mind: The default CRS must be metric"); // NOI18N
}
if (transformer == null) {
LOG.error("No metric default crs found. Use EPSG:31466 as default crs"); // NOI18N
try {
transformer = new CrsTransformer("EPSG:31466"); // NOI18N
CismapBroker.getInstance().setDefaultCrs("EPSG:31466"); // NOI18N
} catch (final Exception ex) {
LOG.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); // NOI18N
}
}
// HOME
try {
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N
}
}
while (it.hasNext()) {
final Element elem = it.next();
final String srs = elem.getAttribute("srs").getValue(); // NOI18N
boolean metric = false;
try {
metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N
} catch (DataConversionException dce) {
LOG.warn("Metric hat falschen Syntax", dce); // NOI18N
}
boolean defaultVal = false;
try {
defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N
} catch (DataConversionException dce) {
LOG.warn("default hat falschen Syntax", dce); // NOI18N
}
final XBoundingBox xbox = new XBoundingBox(elem, srs, metric);
alm.addHome(xbox);
if (defaultVal) {
Crs crsObject = null;
for (final Crs tmp : crsList) {
if (tmp.getCode().equals(srs)) {
crsObject = tmp;
break;
}
}
if (crsObject == null) {
LOG.error("CRS " + srs + " from the default home is not found in the crs list");
crsObject = new Crs(srs, srs, srs, true, false);
crsList.add(crsObject);
}
alm.setSrs(crsObject);
alm.setDefaultHomeSrs(crsObject);
CismapBroker.getInstance().setSrs(crsObject);
wtst = null;
getWtst();
}
}
}
} catch (final Exception ex) {
LOG.error("Fehler beim MasterConfigure der MappingComponent", ex); // NOI18N
}
try {
final Element defaultCrs = prefs.getChild("defaultCrs");
final int defaultCrsInt = Integer.parseInt(defaultCrs.getAttributeValue("geometrySridAlias"));
CismapBroker.getInstance().setDefaultCrsAlias(defaultCrsInt);
} catch (final Exception ex) {
LOG.error("Error while reading the default crs alias from the master configuration file.", ex);
}
try {
final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N
scales.clear();
for (final Object elem : scalesList) {
if (elem instanceof Element) {
final Scale s = new Scale((Element)elem);
scales.add(s);
}
}
} catch (final Exception skip) {
LOG.error("Fehler beim Lesen von Scale", skip); // NOI18N
}
// Und jetzt noch die PriningEinstellungen
initPrintingDialogs();
printingSettingsDialog.masterConfigure(prefs);
}
/**
* Configurates this MappingComponent.
*
* @param e JDOM-Element with configuration
*/
@Override
public void configure(final Element e) {
final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N
try {
final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N
for (final Object elem : crsElements) {
if (elem instanceof Element) {
final Crs s = new Crs((Element)elem);
// the crs is equals to an other crs, if the code is equal. If a crs has in the
// local configuration file an other name than in the master configuration file,
// the old crs will be removed and the local one should be added to use the
// local name and short name of the crs.
if (crsList.contains(s)) {
crsList.remove(s);
}
crsList.add(s);
}
}
} catch (final Exception skip) {
LOG.warn("Error while reading the crs list", skip); // NOI18N
}
// InteractionMode
try {
final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N
setInteractionMode(interactMode);
if (interactMode.equals(MappingComponent.NEW_POLYGON)) {
try {
final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N
((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode);
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des CreationInteractionMode", ex); // NOI18N
}
}
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des InteractionMode", ex); // NOI18N
}
try {
final String createSearchMode = prefs.getAttribute("createSearchMode").getValue();
final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON);
if ((inputListener instanceof CreateSearchGeometryListener) && (createSearchMode != null)) {
final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener;
listener.setMode(createSearchMode);
}
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des CreateSearchMode", ex); // NOI18N
}
try {
final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N
setHandleInteractionMode(handleInterMode);
} catch (final Exception ex) {
LOG.warn("Fehler beim Setzen des HandleInteractionMode", ex); // NOI18N
}
try {
final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N
LOG.info("snapping=" + snapping); // NOI18N
setSnappingEnabled(snapping);
setVisualizeSnappingEnabled(snapping);
setInGlueIdenticalPointsMode(snapping);
} catch (final Exception ex) {
LOG.warn("Fehler beim setzen von snapping und Konsorten", ex); // NOI18N
}
// aktuelle Position
try {
final Element pos = prefs.getChild("Position"); // NOI18N
final BoundingBox b = new BoundingBox(pos);
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("Position:" + b); // NOI18N
}
}
final PBounds pb = b.getPBounds(getWtst());
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("PositionPb:" + pb); // NOI18N
}
}
if (Double.isNaN(b.getX1())
|| Double.isNaN(b.getX2())
|| Double.isNaN(b.getY1())
|| Double.isNaN(b.getY2())) {
LOG.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N
this.currentBoundingBox = getMappingModel().getInitialBoundingBox();
final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null);
addToHistory(new PBoundsWithCleverToString(
new PBounds(currentBoundingBox.getPBounds(wtst)),
wtst,
crsCode));
} else {
// set the current crs
final Attribute crsAtt = pos.getAttribute("CRS");
if (crsAtt != null) {
final String currentCrs = crsAtt.getValue();
Crs crsObject = null;
for (final Crs tmp : crsList) {
if (tmp.getCode().equals(currentCrs)) {
crsObject = tmp;
break;
}
}
if (crsObject == null) {
LOG.error("CRS " + currentCrs + " from the position element is not found in the crs list");
}
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
if (alm instanceof ActiveLayerModel) {
alm.setSrs(crsObject);
}
CismapBroker.getInstance().setSrs(crsObject);
wtst = null;
getWtst();
}
this.currentBoundingBox = b;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("added to History" + b); // NOI18N
}
}
}
} catch (final Exception ex) {
LOG.warn("Fehler beim lesen der aktuellen Position", ex); // NOI18N
this.currentBoundingBox = getMappingModel().getInitialBoundingBox();
}
if (printingSettingsDialog != null) {
printingSettingsDialog.configure(prefs);
}
try {
final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N
if (widgets != null) {
for (final Object widget : widgets.getChildren()) {
final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N
final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N
this.showInternalWidget(name, visible, 0);
}
}
} catch (final Exception ex) {
LOG.warn("could not enable internal widgets: " + ex, ex); // NOI18N
}
}
/**
* Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent
* will only pan to the featurecollection and not zoom.
*
* @param fixedScale true, if zoom is not allowed
*/
public void zoomToFeatureCollection(final boolean fixedScale) {
zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale);
}
/**
* Zooms to all features of the mappingcomponents featurecollection.
*/
public void zoomToFeatureCollection() {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("zoomToFeatureCollection"); // NOI18N
}
}
zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false);
}
/**
* Moves the view to the target Boundingbox.
*
* @param bb target BoundingBox
* @param history true, if the action sould be saved in the history
* @param scaleToFit true, to zoom
* @param animationDuration duration of the animation
*/
public void gotoBoundingBox(final BoundingBox bb,
final boolean history,
final boolean scaleToFit,
final int animationDuration) {
gotoBoundingBox(bb, history, scaleToFit, animationDuration, true);
}
/**
* Moves the view to the target Boundingbox.
*
* @param bb target BoundingBox
* @param history true, if the action sould be saved in the history
* @param scaleToFit true, to zoom
* @param animationDuration duration of the animation
* @param queryServices true, if the services should be refreshed after animation
*/
public void gotoBoundingBox(BoundingBox bb,
final boolean history,
final boolean scaleToFit,
final int animationDuration,
final boolean queryServices) {
if (bb != null) {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N
}
}
try {
handleLayer.removeAllChildren();
} catch (final Exception e) {
LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N
}
if (bb instanceof XBoundingBox) {
if (!((XBoundingBox)bb).getSrs().equals(mappingModel.getSrs().getCode())) {
try {
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
bb = trans.transformBoundingBox((XBoundingBox)bb);
} catch (final Exception e) {
LOG.warn("Cannot transform the bounding box", e);
}
}
}
final double x1 = getWtst().getScreenX(bb.getX1());
final double y1 = getWtst().getScreenY(bb.getY1());
final double x2 = getWtst().getScreenX(bb.getX2());
final double y2 = getWtst().getScreenY(bb.getY2());
final double w;
final double h;
final Rectangle2D pos = new Rectangle2D.Double();
pos.setRect(x1, y2, x2 - x1, y1 - y2);
getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration);
if (getCamera().getViewTransform().getScaleY() < 0) {
LOG.warn("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N
}
showHandles(true);
final Runnable handle = new Runnable() {
@Override
public void run() {
while (getAnimating()) {
try {
Thread.currentThread().sleep(10);
} catch (final Exception e) {
LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N
}
}
if (history) {
if ((x1 == x2) || (y1 == y2) || !scaleToFit) {
setNewViewBounds(getCamera().getViewBounds());
} else {
setNewViewBounds(pos);
}
if (queryServices) {
queryServices();
}
} else {
if (queryServices) {
queryServicesWithoutHistory();
}
}
}
};
CismetThreadPool.execute(handle);
} else {
LOG.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N
}
}
/**
* Moves the view to the target Boundingbox without saving the action in the history.
*
* @param bb target BoundingBox
*/
public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) {
gotoBoundingBoxWithoutHistory(bb, animationDuration);
}
/**
* Moves the view to the target Boundingbox without saving the action in the history.
*
* @param bb target BoundingBox
* @param animationDuration the animation duration
*/
public void gotoBoundingBoxWithoutHistory(final BoundingBox bb, final int animationDuration) {
gotoBoundingBox(bb, false, true, animationDuration);
}
/**
* Moves the view to the target Boundingbox and saves the action in the history.
*
* @param bb target BoundingBox
*/
public void gotoBoundingBoxWithHistory(final BoundingBox bb) {
gotoBoundingBox(bb, true, true, animationDuration);
}
/**
* Returns a BoundingBox of the current view in another scale.
*
* @param scaleDenominator specific target scale
*
* @return DOCUMENT ME!
*/
public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) {
return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBox());
}
/**
* Returns the BoundingBox of the delivered BoundingBox in another scale.
*
* @param scaleDenominator specific target scale
* @param bb source BoundingBox
*
* @return DOCUMENT ME!
*/
public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) {
final double screenWidthInInch = getWidth() / screenResolution;
final double screenWidthInMeter = screenWidthInInch * 0.0254;
final double screenHeightInInch = getHeight() / screenResolution;
final double screenHeightInMeter = screenHeightInInch * 0.0254;
final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator;
final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator;
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
// transform the given bounding box to a metric coordinate system
bb = transformer.transformBoundingBox(bb, mappingModel.getSrs().getCode());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2);
final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2);
BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2),
midY
- (realWorldHeightInMeter / 2),
midX
+ (realWorldWidthInMeter / 2),
midY
+ (realWorldHeightInMeter / 2));
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
// transform the scaled bounding box to the current coordinate system
final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode());
scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
return scaledBox;
}
/**
* Calculate the current scaledenominator.
*
* @return DOCUMENT ME!
*/
public double getScaleDenominator() {
BoundingBox boundingBox = getCurrentBoundingBox();
final double screenWidthInInch = getWidth() / screenResolution;
final double screenWidthInMeter = screenWidthInInch * 0.0254;
final double screenHeightInInch = getHeight() / screenResolution;
final double screenHeightInMeter = screenHeightInInch * 0.0254;
if (!mappingModel.getSrs().isMetric() && (transformer != null)) {
try {
boundingBox = transformer.transformBoundingBox(
boundingBox,
mappingModel.getSrs().getCode());
} catch (final Exception e) {
LOG.error("Cannot transform the current bounding box.", e);
}
}
final double realWorldWidthInMeter = boundingBox.getWidth();
return realWorldWidthInMeter / screenWidthInMeter;
}
/**
* Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code>
* DropTarget</code> registered with this listener.
*
* <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code>
* DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data
* object(s) to be transfered.</p>
*
* <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int
* dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P>
*
* <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be
* invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData()
* method.</P>
*
* <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the
* drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method.</P>
*
* <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code>
* Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only
* if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code>
* true</code>. Otherwise, the behavior of the call is implementation-dependent.</P>
*
* @param dtde the <code>DropTargetDropEvent</code>
*/
@Override
public void drop(final DropTargetDropEvent dtde) {
if (isDropEnabled(dtde)) {
try {
final MapDnDEvent mde = new MapDnDEvent();
mde.setDte(dtde);
final Point p = dtde.getLocation();
getCamera().getViewTransform().inverseTransform(p, p);
mde.setXPos(getWtst().getWorldX(p.getX()));
mde.setYPos(getWtst().getWorldY(p.getY()));
CismapBroker.getInstance().fireDropOnMap(mde);
} catch (final Exception ex) {
LOG.error("Error in drop", ex); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param dtde DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private boolean isDropEnabled(final DropTargetDropEvent dtde) {
if (ALKIS_PRINT.equals(getInteractionMode())) {
for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) {
// necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here
if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) {
return false;
}
}
}
return true;
}
/**
* Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site
* for the <code>DropTarget</code> registered with this listener.
*
* @param dte the <code>DropTargetEvent</code>
*/
@Override
public void dragExit(final DropTargetEvent dte) {
}
/**
* Called if the user has modified the current drop gesture.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dropActionChanged(final DropTargetDragEvent dtde) {
}
/**
* Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p
* site for the <code>DropTarget</code> registered with this listener.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dragOver(final DropTargetDragEvent dtde) {
try {
final MapDnDEvent mde = new MapDnDEvent();
mde.setDte(dtde);
// TODO: this seems to be buggy!
final Point p = dtde.getLocation();
getCamera().getViewTransform().inverseTransform(p, p);
mde.setXPos(getWtst().getWorldX(p.getX()));
mde.setYPos(getWtst().getWorldY(p.getY()));
CismapBroker.getInstance().fireDragOverMap(mde);
} catch (final Exception ex) {
LOG.error("Error in dragOver", ex); // NOI18N
}
}
/**
* Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for
* the <code>DropTarget</code> registered with this listener.
*
* @param dtde the <code>DropTargetDragEvent</code>
*/
@Override
public void dragEnter(final DropTargetDragEvent dtde) {
}
/**
* Returns the PfeatureHashmap which assigns a Feature to a PFeature.
*
* @return DOCUMENT ME!
*/
public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() {
return pFeatureHM;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFixedMapExtent() {
return fixedMapExtent;
}
/**
* DOCUMENT ME!
*
* @param fixedMapExtent DOCUMENT ME!
*/
public void setFixedMapExtent(final boolean fixedMapExtent) {
this.fixedMapExtent = fixedMapExtent;
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(
StatusEvent.MAP_EXTEND_FIXED,
this.fixedMapExtent));
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFixedMapScale() {
return fixedMapScale;
}
/**
* DOCUMENT ME!
*
* @param fixedMapScale DOCUMENT ME!
*/
public void setFixedMapScale(final boolean fixedMapScale) {
this.fixedMapScale = fixedMapScale;
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(
StatusEvent.MAP_SCALE_FIXED,
this.fixedMapScale));
}
}
/**
* DOCUMENT ME!
*
* @param one DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
public void selectPFeatureManually(final PFeature one) {
if (one != null) {
featureCollection.select(one.getFeature());
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @deprecated DOCUMENT ME!
*/
public PFeature getSelectedNode() {
// gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist
// deshalb gebe ich mal nur das erste zur�ck
if (featureCollection.getSelectedFeatures().size() > 0) {
final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0];
if (selF == null) {
return null;
}
return pFeatureHM.get(selF);
} else {
return null;
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isInfoNodesVisible() {
return infoNodesVisible;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getPrintingFrameLayer() {
return printingFrameLayer;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PrintingSettingsWidget getPrintingSettingsDialog() {
return printingSettingsDialog;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isInGlueIdenticalPointsMode() {
return inGlueIdenticalPointsMode;
}
/**
* DOCUMENT ME!
*
* @param inGlueIdenticalPointsMode DOCUMENT ME!
*/
public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) {
this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PLayer getHighlightingLayer() {
return highlightingLayer;
}
/**
* DOCUMENT ME!
*
* @param anno DOCUMENT ME!
*/
public void setPointerAnnotation(final PNode anno) {
((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno);
}
/**
* DOCUMENT ME!
*
* @param visib DOCUMENT ME!
*/
public void setPointerAnnotationVisibility(final boolean visib) {
if (getInputListener(MOTION) != null) {
((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib);
}
}
/**
* Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't
* equal MOTION.
*
* @return DOCUMENT ME!
*/
public boolean isPointerAnnotationVisible() {
if (getInputListener(MOTION) != null) {
return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible();
} else {
return false;
}
}
/**
* Returns a vector with different scales.
*
* @return DOCUMENT ME!
*/
public List<Scale> getScales() {
return scales;
}
/**
* Returns a list with different crs.
*
* @return DOCUMENT ME!
*/
public List<Crs> getCrsList() {
return crsList;
}
/**
* DOCUMENT ME!
*
* @return a transformer with the default crs as destination crs. The default crs is the first crs in the
* configuration file that has set the selected attribut on true). This crs must be metric.
*/
public CrsTransformer getMetricTransformer() {
return transformer;
}
/**
* Locks the MappingComponent.
*/
public void lock() {
locked = true;
}
/**
* Unlocks the MappingComponent.
*/
public void unlock() {
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("unlock"); // NOI18N
}
}
locked = false;
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N
}
}
gotoBoundingBoxWithHistory(currentBoundingBox);
}
/**
* Returns whether the MappingComponent is locked or not.
*
* @return DOCUMENT ME!
*/
public boolean isLocked() {
return locked;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isMainMappingComponent() {
return mainMappingComponent;
}
/**
* Returns the MementoInterface for redo-actions.
*
* @return DOCUMENT ME!
*/
public MementoInterface getMemRedo() {
return memRedo;
}
/**
* Returns the MementoInterface for undo-actions.
*
* @return DOCUMENT ME!
*/
public MementoInterface getMemUndo() {
return memUndo;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map<String, PBasicInputEventHandler> getInputEventListener() {
return inputEventListener;
}
/**
* DOCUMENT ME!
*
* @param inputEventListener DOCUMENT ME!
*/
public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) {
this.inputEventListener.clear();
this.inputEventListener.putAll(inputEventListener);
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
@Override
public synchronized void crsChanged(final CrsChangedEvent event) {
if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) {
if (locked) {
return;
}
try {
// the wtst object should not be null, so the getWtst method will be invoked
final WorldToScreenTransform oldWtst = getWtst();
final BoundingBox bbox = getCurrentBoundingBox(); // getCurrentBoundingBox();
final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode());
final BoundingBox newBbox = crsTransformer.transformBoundingBox(bbox, event.getFormerCrs().getCode());
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.setSrs(event.getCurrentCrs());
}
wtst = null;
getWtst();
gotoBoundingBoxWithoutHistory(newBbox, 0);
final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures());
featureCollection.removeAllFeatures();
featureCollection.addFeatures(list);
if (LOG.isDebugEnabled()) {
LOG.debug("debug features added: " + list.size());
}
// refresh all wfs layer
if (getMappingModel() instanceof ActiveLayerModel) {
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.refreshWebFeatureServices();
alm.refreshShapeFileLayer();
}
// transform the highlighting layer
for (int i = 0; i < highlightingLayer.getChildrenCount(); ++i) {
final PNode node = highlightingLayer.getChild(i);
CrsTransformer.transformPNodeToGivenCrs(
node,
event.getFormerCrs().getCode(),
event.getCurrentCrs().getCode(),
oldWtst,
getWtst());
rescaleStickyNode(node);
}
} catch (final Exception e) {
JOptionPane.showMessageDialog(
this,
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"),
org.openide.util.NbBundle.getMessage(
MappingComponent.class,
"MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"),
JOptionPane.ERROR_MESSAGE);
LOG.error("Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e);
resetCrs = true;
final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel();
alm.setSrs(event.getCurrentCrs());
CismapBroker.getInstance().setSrs(event.getFormerCrs());
}
} else {
resetCrs = false;
}
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public JInternalFrame getInternalWidget(final String name) {
if (this.internalWidgets.containsKey(name)) {
return this.internalWidgets.get(name);
} else {
LOG.warn("unknown internal widget '" + name + "'"); // NOI18N
return null;
}
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getInternalWidgetPosition(final String name) {
if (this.internalWidgetPositions.containsKey(name)) {
return this.internalWidgetPositions.get(name);
} else {
LOG.warn("unknown position for '" + name + "'"); // NOI18N
return -1;
}
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class MappingComponentRasterServiceListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
private final transient ServiceLayer rasterService;
private final XPImage pi;
private int position = -1;
//~ Constructors -------------------------------------------------------
/**
* Creates a new MappingComponentRasterServiceListener object.
*
* @param position DOCUMENT ME!
* @param pn DOCUMENT ME!
* @param rasterService DOCUMENT ME!
*/
public MappingComponentRasterServiceListener(final int position,
final PNode pn,
final ServiceLayer rasterService) {
this.position = position;
this.rasterService = rasterService;
if (pn instanceof XPImage) {
this.pi = (XPImage)pn;
} else {
this.pi = null;
}
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
fireActivityChanged();
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
this.log.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() // NOI18N
+ " Errors: " // NOI18N
+ e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N
fireActivityChanged();
if (DEBUG) {
if (LOG.isDebugEnabled()) {
LOG.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
final Point2D localOrigin = getCamera().getViewBounds().getOrigin();
final double localScale = getCamera().getViewScale();
final PBounds localBounds = getCamera().getViewBounds();
final Object o = e.getRetrievedObject();
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N
}
}
final Runnable paintImageOnMap = new Runnable() {
@Override
public void run() {
fireActivityChanged();
if ((o instanceof Image) && (e.isHasErrors() == false)) {
// TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden
if (isBackgroundEnabled()) {
final Image i = (Image)o;
if (rasterService.getName().startsWith("prefetching")) { // NOI18N
final double x = localOrigin.getX() - localBounds.getWidth();
final double y = localOrigin.getY() - localBounds.getHeight();
pi.setImage(i, 0);
pi.setScale(3 / localScale);
pi.setOffset(x, y);
} else {
pi.setImage(i, animationDuration * 2);
pi.setScale(1 / localScale);
pi.setOffset(localOrigin);
MappingComponent.this.repaint();
}
}
}
}
};
if (EventQueue.isDispatchThread()) {
paintImageOnMap.run();
} else {
EventQueue.invokeLater(paintImageOnMap);
}
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
this.log.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, rasterService));
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getPosition() {
return position;
}
/**
* DOCUMENT ME!
*
* @param position DOCUMENT ME!
*/
public void setPosition(final int position) {
this.position = position;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class DocumentProgressListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
/** Displays the loading progress of Documents, e.g. SHP Files */
private final transient DocumentProgressWidget documentProgressWidget;
private transient long requestId = -1;
//~ Constructors -------------------------------------------------------
/**
* Creates a new DocumentProgressListener object.
*/
public DocumentProgressListener() {
documentProgressWidget = new DocumentProgressWidget();
documentProgressWidget.setVisible(false);
if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) {
MappingComponent.this.addInternalWidget(
MappingComponent.PROGRESSWIDGET,
MappingComponent.POSITION_SOUTHWEST,
documentProgressWidget);
}
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalStarted aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != -1) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = e.getRequestIdentifier();
this.documentProgressWidget.setServiceName(e.getRetrievalService().toString());
this.documentProgressWidget.setProgress(-1);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalProgress, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: initialisation progress: " + e.getPercentageDone()); // NOI18N
}
}
this.documentProgressWidget.setProgress(e.getPercentageDone());
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalComplete, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N
}
e.getRetrievalService().removeRetrievalListener(this);
this.requestId = -1;
this.documentProgressWidget.setProgress(100);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalAborted aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = -1;
this.documentProgressWidget.setProgress(0);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalError aborted, no initialisation event"); // NOI18N
return;
}
if (this.requestId != e.getRequestIdentifier()) {
log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier()
+ "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N
}
this.requestId = -1;
e.getRetrievalService().removeRetrievalListener(this);
this.documentProgressWidget.setProgress(0);
MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public long getRequestId() {
return this.requestId;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private class MappingComponentFeatureServiceListener implements RetrievalListener {
//~ Instance fields ----------------------------------------------------
private final transient Logger log = Logger.getLogger(this.getClass());
private final transient ServiceLayer featureService;
private final transient PLayer parent;
private long requestIdentifier;
private Thread completionThread;
private final List deletionCandidates;
private final List twins;
//~ Constructors -------------------------------------------------------
/**
* Creates a new MappingComponentFeatureServiceListener.
*
* @param featureService the featureretrievalservice
* @param parent the featurelayer (PNode) connected with the servicelayer
*/
public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) {
this.featureService = featureService;
this.parent = parent;
this.deletionCandidates = new ArrayList();
this.twins = new ArrayList();
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalStarted(final RetrievalEvent e) {
if (!e.isInitialisationEvent()) {
requestIdentifier = e.getRequestIdentifier();
}
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N
}
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalProgress(final RetrievalEvent e) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: "
+ e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress()
+ ")"); // NOI18N
}
}
fireActivityChanged();
// TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das
// flüssiger ist
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalError(final RetrievalEvent e) {
this.log.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: "
+ (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalComplete(final RetrievalEvent e) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N
}
}
if (e.isInitialisationEvent()) {
this.log.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: initialisation complete"); // NOI18N
fireActivityChanged();
return;
}
if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N
completionThread.interrupt();
}
if (e.getRequestIdentifier() < requestIdentifier) {
if (DEBUG) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N
}
((RetrievalServiceLayer)featureService).setProgress(-1);
fireActivityChanged();
return;
}
final List newFeatures = new ArrayList();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
((RetrievalServiceLayer)featureService).setProgress(-1);
parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible());
}
});
// clear all old data to delete twins
deletionCandidates.clear();
twins.clear();
// if it's a refresh, add all old features which should be deleted in the
// newly acquired featurecollection
if (!e.isRefreshExisting()) {
deletionCandidates.addAll(parent.getChildrenReference());
}
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier
+ ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N
}
}
// only start parsing the features if there are no errors and a correct collection
if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) {
completionThread = new Thread() {
@Override
public void run() {
// this is the collection with the retrieved features
final List features = new ArrayList((Collection)e.getRetrievedObject());
final int size = features.size();
int counter = 0;
final Iterator it = features.iterator();
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(featureService + "[" + e.getRequestIdentifier() + " ("
+ requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N
}
}
while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()
&& it.hasNext()) {
counter++;
final Object o = it.next();
if (o instanceof Feature) {
final PFeature p = new PFeature(((Feature)o),
wtst,
clip_offset_x,
clip_offset_y,
MappingComponent.this);
PFeature twin = null;
for (final Object tester : deletionCandidates) {
// if tester and PFeature are FeatureWithId-objects
if ((((PFeature)tester).getFeature() instanceof FeatureWithId)
&& (p.getFeature() instanceof FeatureWithId)) {
final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId();
final int id2 = ((FeatureWithId)(p.getFeature())).getId();
if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id
if (id1 == id2) {
twin = ((PFeature)tester);
break;
}
} else { // else test the geometry for equality
if (((PFeature)tester).getFeature().getGeometry().equals(
p.getFeature().getGeometry())) {
twin = ((PFeature)tester);
break;
}
}
} else { // no FeatureWithId, test geometries for
// equality
if (((PFeature)tester).getFeature().getGeometry().equals(
p.getFeature().getGeometry())) {
twin = ((PFeature)tester);
break;
}
}
}
// if a twin is found remove him from the deletion candidates
// and add him to the twins
if (twin != null) {
deletionCandidates.remove(twin);
twins.add(twin);
} else { // else add the PFeature to the new features
newFeatures.add(p);
}
// calculate the advance of the progressbar
// fire event only wheen needed
final int currentProgress = (int)((double)counter / (double)size * 100d);
if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) {
((RetrievalServiceLayer)featureService).setProgress(currentProgress);
fireActivityChanged();
}
}
}
if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) {
// after all features are computed do stuff on the EDT
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N
}
}
// if it's a refresh, delete all previous features
if (e.isRefreshExisting()) {
parent.removeAllChildren();
}
final List deleteFeatures = new ArrayList();
for (final Object o : newFeatures) {
parent.addChild((PNode)o);
}
// set the prograssbar to full
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: set progress to 100"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(100);
fireActivityChanged();
// repaint the featurelayer
parent.repaint();
// remove stickyNode from all deletionCandidates and add
// each to the new deletefeature-collection
for (final Object o : deletionCandidates) {
if (o instanceof PFeature) {
final PNode p = ((PFeature)o).getPrimaryAnnotationNode();
if (p != null) {
removeStickyNode(p);
}
deleteFeatures.add(o);
}
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: parentCount before:"
+ parent.getChildrenCount()); // NOI18N
}
}
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: deleteFeatures="
+ deleteFeatures.size()); // + " :" +
// deleteFeatures);//NOI18N
}
}
parent.removeChildren(deleteFeatures);
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: parentCount after:"
+ parent.getChildrenCount()); // NOI18N
}
}
if (LOG.isInfoEnabled()) {
LOG.info(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: "
+ parent.getChildrenCount()
+ " features retrieved or updated"); // NOI18N
}
rescaleStickyNodes();
} catch (final Exception exception) {
log.warn(
featureService
+ "["
+ e.getRequestIdentifier()
+ " ("
+ requestIdentifier
+ ")]: Fehler beim Aufr\u00E4umen",
exception); // NOI18N
}
}
});
} else {
if (DEBUG) {
if (log.isDebugEnabled()) {
log.debug(featureService + "[" + e.getRequestIdentifier() + " ("
+ requestIdentifier
+ ")]: completion thread Interrupted or synchronisation lost"); // NOI18N
}
}
}
}
};
completionThread.setPriority(Thread.NORM_PRIORITY);
if (requestIdentifier == e.getRequestIdentifier()) {
completionThread.start();
} else {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: completion thread Interrupted or synchronisation lost"); // NOI18N
}
}
}
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, featureService));
}
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void retrievalAborted(final RetrievalEvent e) {
this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: aborted, TaskCounter:" + taskCounter); // NOI18N
if (completionThread != null) {
completionThread.interrupt();
}
if (e.getRequestIdentifier() < requestIdentifier) {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(-1);
} else {
if (DEBUG) {
if (this.log.isDebugEnabled()) {
this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier
+ ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N
}
}
((RetrievalServiceLayer)featureService).setProgress(0);
}
fireActivityChanged();
if (mainMappingComponent) {
CismapBroker.getInstance()
.fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, featureService));
}
}
}
}
|
diff --git a/openengsb-link-http/src/main/java/org/openengsb/link/http/LinkHttpMarshaler.java b/openengsb-link-http/src/main/java/org/openengsb/link/http/LinkHttpMarshaler.java
index f5b191381..f85638eaa 100644
--- a/openengsb-link-http/src/main/java/org/openengsb/link/http/LinkHttpMarshaler.java
+++ b/openengsb-link-http/src/main/java/org/openengsb/link/http/LinkHttpMarshaler.java
@@ -1,102 +1,106 @@
/**
Copyright 2009 OpenEngSB Division, Vienna University of Technology
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.openengsb.link.http;
import javax.jbi.component.ComponentContext;
import javax.jbi.messaging.Fault;
import javax.jbi.messaging.InOnly;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.servicemix.http.endpoints.AbstractHttpConsumerMarshaler;
import org.apache.servicemix.jbi.jaxp.StringSource;
/**
* serves as an interface between the http-service-unit and the associated
* processor-service. It is responsible for the conversion of HTTP-requests to
* JBI-messages and vice versa
*/
public class LinkHttpMarshaler extends AbstractHttpConsumerMarshaler {
public static final String STRING_WHOAMI = "whoami";
private static final Log log = LogFactory.getLog(LinkHttpMarshaler.class);
@Override
public MessageExchange createExchange(HttpServletRequest request, ComponentContext context) throws Exception {
InOnly result = context.getDeliveryChannel().createExchangeFactory().createInOnlyExchange();
NormalizedMessage inMessage = result.createMessage();
String query = request.getQueryString();
String ip = request.getRemoteAddr();
+ String message;
/* parse the query */
- if (query.startsWith("UUID:")) {
- query = query.substring(5);
- } else if (!query.equalsIgnoreCase(STRING_WHOAMI)) {
- return result;
+ if (query.equalsIgnoreCase(STRING_WHOAMI)) {
+ message = String.format("<whoami>%s</whoami>", ip);
+ } else {
+ if (!query.startsWith("UUID:")) {
+ query = "UUID:" + query;
+ }
+ message = String.format(
+ "<httpLinkRequest><query>%s</query><requestorIP>%s</requestorIP></httpLinkRequest>", query, ip);
}
/* create a message with the parsed query as content */
- String msg = "<httpLinkRequest><query>%s</query><requestorIP>%s</requestorIP></httpLinkRequest>";
- Source content = new StringSource(String.format(msg, query, ip));
+ Source content = new StringSource(message);
log.info("create exchange with content: " + content);
inMessage.setContent(content);
result.setInMessage(inMessage);
return result;
}
@Override
public void sendAccepted(MessageExchange exchange, HttpServletRequest request, HttpServletResponse response)
throws Exception {
/* always send a HTML-document containing the clients remote IP-address */
response.getWriter().append(
"<html><body><h1>You are " + request.getRemoteAddr() + "</h1>" + request.getRemoteHost()
+ "</body></html>");
// TODO more beautiful response
log.debug("send HTTP-accepted");
}
@Override
public void sendError(MessageExchange exchange, Exception error, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO expose the error to the user completely?
error.printStackTrace(response.getWriter());
log.error(error.getMessage());
error.printStackTrace();
}
@Override
public void sendFault(MessageExchange exchange, Fault fault, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.getWriter().append("JBI-fault occured: " + fault.getContent().toString());
log.error("send JBI-fault");
log.error(fault.getContent());
}
@Override
public void sendOut(MessageExchange exchange, NormalizedMessage outMsg, HttpServletRequest request,
HttpServletResponse response) throws Exception {
log.info("send out");
};
}
| false | true | public MessageExchange createExchange(HttpServletRequest request, ComponentContext context) throws Exception {
InOnly result = context.getDeliveryChannel().createExchangeFactory().createInOnlyExchange();
NormalizedMessage inMessage = result.createMessage();
String query = request.getQueryString();
String ip = request.getRemoteAddr();
/* parse the query */
if (query.startsWith("UUID:")) {
query = query.substring(5);
} else if (!query.equalsIgnoreCase(STRING_WHOAMI)) {
return result;
}
/* create a message with the parsed query as content */
String msg = "<httpLinkRequest><query>%s</query><requestorIP>%s</requestorIP></httpLinkRequest>";
Source content = new StringSource(String.format(msg, query, ip));
log.info("create exchange with content: " + content);
inMessage.setContent(content);
result.setInMessage(inMessage);
return result;
}
| public MessageExchange createExchange(HttpServletRequest request, ComponentContext context) throws Exception {
InOnly result = context.getDeliveryChannel().createExchangeFactory().createInOnlyExchange();
NormalizedMessage inMessage = result.createMessage();
String query = request.getQueryString();
String ip = request.getRemoteAddr();
String message;
/* parse the query */
if (query.equalsIgnoreCase(STRING_WHOAMI)) {
message = String.format("<whoami>%s</whoami>", ip);
} else {
if (!query.startsWith("UUID:")) {
query = "UUID:" + query;
}
message = String.format(
"<httpLinkRequest><query>%s</query><requestorIP>%s</requestorIP></httpLinkRequest>", query, ip);
}
/* create a message with the parsed query as content */
Source content = new StringSource(message);
log.info("create exchange with content: " + content);
inMessage.setContent(content);
result.setInMessage(inMessage);
return result;
}
|
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java
index f5b18841..524b4a1a 100644
--- a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java
+++ b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java
@@ -1,386 +1,386 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.sparkimpl.plugin.transcripts;
import org.jdesktop.swingx.calendar.DateUtils;
import org.jivesoftware.MainWindowListener;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.BackgroundPanel;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomButton;
import org.jivesoftware.spark.ui.ChatRoomListener;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.ui.VCardPanel;
import org.jivesoftware.spark.ui.rooms.ChatRoomImpl;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.text.html.HTMLEditorKit;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
/**
* The <code>ChatTranscriptPlugin</code> is responsible for transcript handling within Spark.
*
* @author Derek DeMoro
*/
public class ChatTranscriptPlugin implements ChatRoomListener {
private final SimpleDateFormat notificationDateFormatter;
private final SimpleDateFormat messageDateFormatter;
/**
* Register the listeners for transcript persistence.
*/
public ChatTranscriptPlugin() {
SparkManager.getChatManager().addChatRoomListener(this);
notificationDateFormatter = new SimpleDateFormat("EEEEE, MMMMM d, yyyy");
messageDateFormatter = new SimpleDateFormat("h:mm a");
final ContactList contactList = SparkManager.getWorkspace().getContactList();
final Action viewHistoryAction = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
ContactItem item = (ContactItem)contactList.getSelectedUsers().iterator().next();
final String jid = item.getJID();
showHistory(jid);
}
};
viewHistoryAction.putValue(Action.NAME, Res.getString("menuitem.view.contact.history"));
viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));
contactList.addContextMenuListener(new ContextMenuListener() {
public void poppingUp(Object object, JPopupMenu popup) {
if (object instanceof ContactItem) {
popup.add(viewHistoryAction);
}
}
public void poppingDown(JPopupMenu popup) {
}
public boolean handleDefaultAction(MouseEvent e) {
return false;
}
});
SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {
public void shutdown() {
persistConversations();
}
public void mainWindowActivated() {
}
public void mainWindowDeactivated() {
}
});
SparkManager.getConnection().addConnectionListener(new ConnectionListener() {
public void connectionClosed() {
}
public void connectionClosedOnError(Exception e) {
persistConversations();
}
public void reconnectingIn(int i) {
}
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception exception) {
}
});
}
public void persistConversations() {
for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {
if (room instanceof ChatRoomImpl) {
ChatRoomImpl roomImpl = (ChatRoomImpl)room;
if (roomImpl.isActive()) {
persistChatRoom(roomImpl);
}
}
}
}
public boolean canShutDown() {
return true;
}
public void chatRoomOpened(final ChatRoom room) {
LocalPreferences pref = SettingsManager.getLocalPreferences();
if (!pref.isChatHistoryEnabled()) {
return;
}
final String jid = room.getRoomname();
File transcriptFile = ChatTranscripts.getTranscriptFile(jid);
if (!transcriptFile.exists()) {
return;
}
if (room instanceof ChatRoomImpl) {
// Add History Button
ChatRoomButton chatRoomButton = new ChatRoomButton(SparkRes.getImageIcon(SparkRes.HISTORY_24x24_IMAGE));
room.getToolBar().addChatRoomButton(chatRoomButton);
chatRoomButton.setToolTipText(Res.getString("tooltip.view.history"));
chatRoomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
ChatRoomImpl roomImpl = (ChatRoomImpl)room;
showHistory(roomImpl.getParticipantJID());
}
});
}
}
public void chatRoomLeft(ChatRoom room) {
}
public void chatRoomClosed(final ChatRoom room) {
// Persist only agent to agent chat rooms.
if (room.getChatType() == Message.Type.chat) {
persistChatRoom(room);
}
}
private void persistChatRoom(final ChatRoom room) {
LocalPreferences pref = SettingsManager.getLocalPreferences();
if (!pref.isChatHistoryEnabled()) {
return;
}
final String jid = room.getRoomname();
final List<Message> transcripts = room.getTranscripts();
ChatTranscript transcript = new ChatTranscript();
for (Message message : transcripts) {
HistoryMessage history = new HistoryMessage();
history.setTo(message.getTo());
history.setFrom(message.getFrom());
history.setBody(message.getBody());
Date date = (Date)message.getProperty("date");
if (date != null) {
history.setDate(date);
}
else {
history.setDate(new Date());
}
transcript.addHistoryMessage(history);
}
ChatTranscripts.appendToTranscript(jid, transcript);
}
public void chatRoomActivated(ChatRoom room) {
}
public void userHasJoined(ChatRoom room, String userid) {
}
public void userHasLeft(ChatRoom room, String userid) {
}
public void uninstall() {
// Do nothing.
}
private void showHistory(final String jid) {
SwingWorker transcriptLoader = new SwingWorker() {
public Object construct() {
String bareJID = StringUtils.parseBareAddress(jid);
return ChatTranscripts.getChatTranscript(bareJID);
}
public void finished() {
final JPanel mainPanel = new BackgroundPanel();
mainPanel.setLayout(new BorderLayout());
final VCardPanel topPanel = new VCardPanel(jid);
mainPanel.add(topPanel, BorderLayout.NORTH);
final JEditorPane window = new JEditorPane();
window.setEditorKit(new HTMLEditorKit());
window.setBackground(Color.white);
final JScrollPane pane = new JScrollPane(window);
pane.getVerticalScrollBar().setBlockIncrement(50);
pane.getVerticalScrollBar().setUnitIncrement(20);
mainPanel.add(pane, BorderLayout.CENTER);
final ChatTranscript transcript = (ChatTranscript)get();
final List<HistoryMessage> list = transcript.getMessages();
final String personalNickname = SparkManager.getUserManager().getNickname();
final JFrame frame = new JFrame(Res.getString("title.history.for", jid));
frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(600, 400);
window.setCaretPosition(0);
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
window.setEditable(false);
final StringBuilder builder = new StringBuilder();
builder.append("<html><body><table cellpadding=0 cellspacing=0>");
final TimerTask transcriptTask = new TimerTask() {
public void run() {
Date lastPost = null;
String lastPerson = null;
boolean initialized = false;
for (HistoryMessage message : list) {
String color = "blue";
String from = message.getFrom();
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String body = message.getBody();
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
color = "red";
}
long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
int diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime());
if (diff != 0) {
if (initialized) {
builder.append("<tr><td><br></td></tr>");
}
builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>" + notificationDateFormatter.format(message.getDate()) + "</u></b></font></td></tr>");
lastPerson = null;
initialized = true;
}
String value = "[" + messageDateFormatter.format(message.getDate()) + "] ";
boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname);
if (newInsertions) {
builder.append("<tr valign=top><td colspan=2 nowrap>");
builder.append("<font size=4 color='" + color + "'><b>");
builder.append(nickname);
builder.append("</b></font>");
builder.append("</td></tr>");
}
builder.append("<tr valign=top><td align=left nowrap>");
builder.append(value);
builder.append("</td><td align=left>");
builder.append(body);
builder.append("</td></tr>");
lastPost = message.getDate();
lastPerson = nickname;
}
builder.append("</table></body></html>");
// Handle no history
if (transcript.getMessages().size() == 0) {
builder.append("<b>" + Res.getString("message.no.history.found") + "</b>");
}
window.setText(builder.toString());
}
};
- TaskEngine.getInstance().schedule(transcriptTask, 500);
+ TaskEngine.getInstance().schedule(transcriptTask, 10);
}
};
transcriptLoader.start();
}
/**
* Sort HistoryMessages by date.
*/
final Comparator dateComparator = new Comparator() {
public int compare(Object messageOne, Object messageTwo) {
final HistoryMessage historyMessageOne = (HistoryMessage)messageOne;
final HistoryMessage historyMessageTwo = (HistoryMessage)messageTwo;
long time1 = historyMessageOne.getDate().getTime();
long time2 = historyMessageTwo.getDate().getTime();
if (time1 < time2) {
return 1;
}
else if (time1 > time2) {
return -1;
}
return 0;
}
};
}
| true | true | private void showHistory(final String jid) {
SwingWorker transcriptLoader = new SwingWorker() {
public Object construct() {
String bareJID = StringUtils.parseBareAddress(jid);
return ChatTranscripts.getChatTranscript(bareJID);
}
public void finished() {
final JPanel mainPanel = new BackgroundPanel();
mainPanel.setLayout(new BorderLayout());
final VCardPanel topPanel = new VCardPanel(jid);
mainPanel.add(topPanel, BorderLayout.NORTH);
final JEditorPane window = new JEditorPane();
window.setEditorKit(new HTMLEditorKit());
window.setBackground(Color.white);
final JScrollPane pane = new JScrollPane(window);
pane.getVerticalScrollBar().setBlockIncrement(50);
pane.getVerticalScrollBar().setUnitIncrement(20);
mainPanel.add(pane, BorderLayout.CENTER);
final ChatTranscript transcript = (ChatTranscript)get();
final List<HistoryMessage> list = transcript.getMessages();
final String personalNickname = SparkManager.getUserManager().getNickname();
final JFrame frame = new JFrame(Res.getString("title.history.for", jid));
frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(600, 400);
window.setCaretPosition(0);
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
window.setEditable(false);
final StringBuilder builder = new StringBuilder();
builder.append("<html><body><table cellpadding=0 cellspacing=0>");
final TimerTask transcriptTask = new TimerTask() {
public void run() {
Date lastPost = null;
String lastPerson = null;
boolean initialized = false;
for (HistoryMessage message : list) {
String color = "blue";
String from = message.getFrom();
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String body = message.getBody();
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
color = "red";
}
long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
int diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime());
if (diff != 0) {
if (initialized) {
builder.append("<tr><td><br></td></tr>");
}
builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>" + notificationDateFormatter.format(message.getDate()) + "</u></b></font></td></tr>");
lastPerson = null;
initialized = true;
}
String value = "[" + messageDateFormatter.format(message.getDate()) + "] ";
boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname);
if (newInsertions) {
builder.append("<tr valign=top><td colspan=2 nowrap>");
builder.append("<font size=4 color='" + color + "'><b>");
builder.append(nickname);
builder.append("</b></font>");
builder.append("</td></tr>");
}
builder.append("<tr valign=top><td align=left nowrap>");
builder.append(value);
builder.append("</td><td align=left>");
builder.append(body);
builder.append("</td></tr>");
lastPost = message.getDate();
lastPerson = nickname;
}
builder.append("</table></body></html>");
// Handle no history
if (transcript.getMessages().size() == 0) {
builder.append("<b>" + Res.getString("message.no.history.found") + "</b>");
}
window.setText(builder.toString());
}
};
TaskEngine.getInstance().schedule(transcriptTask, 500);
}
};
transcriptLoader.start();
}
| private void showHistory(final String jid) {
SwingWorker transcriptLoader = new SwingWorker() {
public Object construct() {
String bareJID = StringUtils.parseBareAddress(jid);
return ChatTranscripts.getChatTranscript(bareJID);
}
public void finished() {
final JPanel mainPanel = new BackgroundPanel();
mainPanel.setLayout(new BorderLayout());
final VCardPanel topPanel = new VCardPanel(jid);
mainPanel.add(topPanel, BorderLayout.NORTH);
final JEditorPane window = new JEditorPane();
window.setEditorKit(new HTMLEditorKit());
window.setBackground(Color.white);
final JScrollPane pane = new JScrollPane(window);
pane.getVerticalScrollBar().setBlockIncrement(50);
pane.getVerticalScrollBar().setUnitIncrement(20);
mainPanel.add(pane, BorderLayout.CENTER);
final ChatTranscript transcript = (ChatTranscript)get();
final List<HistoryMessage> list = transcript.getMessages();
final String personalNickname = SparkManager.getUserManager().getNickname();
final JFrame frame = new JFrame(Res.getString("title.history.for", jid));
frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(600, 400);
window.setCaretPosition(0);
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
window.setEditable(false);
final StringBuilder builder = new StringBuilder();
builder.append("<html><body><table cellpadding=0 cellspacing=0>");
final TimerTask transcriptTask = new TimerTask() {
public void run() {
Date lastPost = null;
String lastPerson = null;
boolean initialized = false;
for (HistoryMessage message : list) {
String color = "blue";
String from = message.getFrom();
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String body = message.getBody();
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
color = "red";
}
long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
int diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime());
if (diff != 0) {
if (initialized) {
builder.append("<tr><td><br></td></tr>");
}
builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>" + notificationDateFormatter.format(message.getDate()) + "</u></b></font></td></tr>");
lastPerson = null;
initialized = true;
}
String value = "[" + messageDateFormatter.format(message.getDate()) + "] ";
boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname);
if (newInsertions) {
builder.append("<tr valign=top><td colspan=2 nowrap>");
builder.append("<font size=4 color='" + color + "'><b>");
builder.append(nickname);
builder.append("</b></font>");
builder.append("</td></tr>");
}
builder.append("<tr valign=top><td align=left nowrap>");
builder.append(value);
builder.append("</td><td align=left>");
builder.append(body);
builder.append("</td></tr>");
lastPost = message.getDate();
lastPerson = nickname;
}
builder.append("</table></body></html>");
// Handle no history
if (transcript.getMessages().size() == 0) {
builder.append("<b>" + Res.getString("message.no.history.found") + "</b>");
}
window.setText(builder.toString());
}
};
TaskEngine.getInstance().schedule(transcriptTask, 10);
}
};
transcriptLoader.start();
}
|
diff --git a/client/web/src/main/java/org/sagebionetworks/web/client/presenter/LayerPresenter.java b/client/web/src/main/java/org/sagebionetworks/web/client/presenter/LayerPresenter.java
index 072d1a50d..f5f3173ad 100644
--- a/client/web/src/main/java/org/sagebionetworks/web/client/presenter/LayerPresenter.java
+++ b/client/web/src/main/java/org/sagebionetworks/web/client/presenter/LayerPresenter.java
@@ -1,505 +1,508 @@
package org.sagebionetworks.web.client.presenter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.PlaceChanger;
import org.sagebionetworks.web.client.place.LoginPlace;
import org.sagebionetworks.web.client.place.ProjectsHome;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.services.NodeServiceAsync;
import org.sagebionetworks.web.client.transform.NodeModelCreator;
import org.sagebionetworks.web.client.view.LayerView;
import org.sagebionetworks.web.client.widget.licenseddownloader.LicenceServiceAsync;
import org.sagebionetworks.web.shared.Agreement;
import org.sagebionetworks.web.shared.Dataset;
import org.sagebionetworks.web.shared.DownloadLocation;
import org.sagebionetworks.web.shared.EULA;
import org.sagebionetworks.web.shared.FileDownload;
import org.sagebionetworks.web.shared.Layer;
import org.sagebionetworks.web.shared.LayerPreview;
import org.sagebionetworks.web.shared.LicenseAgreement;
import org.sagebionetworks.web.shared.NodeType;
import org.sagebionetworks.web.shared.PagedResults;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import org.sagebionetworks.web.shared.users.AclUtils;
import org.sagebionetworks.web.shared.users.PermissionLevel;
import org.sagebionetworks.web.shared.users.UserData;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.inject.Inject;
public class LayerPresenter extends AbstractActivity implements LayerView.Presenter{
private org.sagebionetworks.web.client.place.Layer place;
private NodeServiceAsync nodeService;
private PlaceController placeController;
private PlaceChanger placeChanger;
private LayerView view;
private String layerId;
private Boolean showDownload;
private Layer model;
private LayerPreview layerPreview;
private boolean hasAcceptedLicenseAgreement;
private LicenceServiceAsync licenseService;
private LicenseAgreement licenseAgreement;
private NodeModelCreator nodeModelCreator;
private AuthenticationController authenticationController;
private boolean iisAdministrator;
private boolean ccanEdit;
/**
* Everything is injected via Guice.
* @param view
* @param datasetService
*/
@Inject
public LayerPresenter(LayerView view, NodeServiceAsync nodeService, LicenceServiceAsync licenseService, NodeModelCreator nodeModelCreator, AuthenticationController authenticationController) {
this.view = view;
this.nodeService = nodeService;
this.licenseService = licenseService;
this.nodeModelCreator = nodeModelCreator;
this.authenticationController = authenticationController;
view.setPresenter(this);
this.hasAcceptedLicenseAgreement = false;
}
@Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
this.placeController = DisplayUtils.placeController;
this.placeChanger = new PlaceChanger() {
@Override
public void goTo(Place place) {
placeController.goTo(place);
}
};
// add the view to the panel
panel.setWidget(view);
}
/**
* Called when this presenter gets focus from AppActivityManager
* @param place
*/
public void setPlace(org.sagebionetworks.web.client.place.Layer place) {
this.place = place;
this.layerId = place.getLayerId();
this.showDownload = place.getDownload();
view.setPresenter(this);
refresh();
}
@Override
public void licenseAccepted() {
if(!hasAcceptedLicenseAgreement && licenseAgreement != null) {
UserData user = authenticationController.getLoggedInUser();
Agreement agreement = new Agreement();
agreement.setEulaId(licenseAgreement.getEulaId());
agreement.setName(DisplayUtils.cleanForEntityName("Synapse Web Agreement by "+ user.getEmail()));
agreement.setDatasetId(model.getParentId());
nodeService.createNode(NodeType.AGREEMENT, agreement.toJson(), new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
// agreement saved, load download locations
step5LoadDownloadLocations();
}
@Override
public void onFailure(Throwable caught) {
view.showInfo("Error", DisplayConstants.ERROR_FAILED_PERSIST_AGREEMENT_TEXT);
}
});
}
}
@Override
public void refresh() {
step1RefreshFromServer();
}
@Override
public PlaceChanger getPlaceChanger() {
return placeChanger;
}
@Override
public boolean downloadAttempted() {
if(authenticationController.getLoggedInUser() != null) {
return true;
} else {
view.showInfo("Login Required", "Please Login to download data.");
placeChanger.goTo(new LoginPlace(new org.sagebionetworks.web.client.place.Layer(layerId, null, false)));
}
return false;
}
@Override
public void delete() {
nodeService.deleteNode(NodeType.LAYER, layerId, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
view.showInfo("Layer Deleted", "The layer was successfully deleted.");
placeChanger.goTo(new ProjectsHome(DisplayUtils.DEFAULT_PLACE_TOKEN));
}
@Override
public void onFailure(Throwable caught) {
view.showErrorMessage("Layer delete failed.");
}
});
}
/*
* Protected Methods
*/
private void step1RefreshFromServer() {
view.clear();
// Fetch the data about this dataset from the server
nodeService.getNodeJSON(NodeType.LAYER, this.layerId, new AsyncCallback<String>() {
@Override
public void onSuccess(String layerJson) {
Layer layer = null;
try {
layer = nodeModelCreator.createLayer(layerJson);
} catch (RestServiceException ex) {
if(!DisplayUtils.handleServiceException(ex, placeChanger)) {
onFailure(null);
}
return;
}
step2SetLayer(layer);
}
@Override
public void onFailure(Throwable caught) {
view.showErrorMessage("An error occured retrieving this Layer. Please try reloading the page.");
}
});
}
protected void step2SetLayer(final Layer layer) {
this.model = layer;
if(layer != null) {
UserData currentUser = authenticationController.getLoggedInUser();
if(currentUser != null) {
AclUtils.getHighestPermissionLevel(NodeType.PROJECT, layer.getId(), nodeService, new AsyncCallback<PermissionLevel>() {
@Override
public void onSuccess(PermissionLevel result) {
iisAdministrator = false;
ccanEdit = false;
if(result == PermissionLevel.CAN_EDIT) {
ccanEdit = true;
} else if(result == PermissionLevel.CAN_ADMINISTER) {
ccanEdit = true;
iisAdministrator = true;
}
step3GetLayerPreview();
}
@Override
public void onFailure(Throwable caught) {
view.showErrorMessage(DisplayConstants.ERROR_GETTING_PERMISSIONS_TEXT);
iisAdministrator = false;
ccanEdit = false;
step3GetLayerPreview();
}
});
} else {
// because this is a public page, they can view
iisAdministrator = false;
ccanEdit = false;
step3GetLayerPreview();
}
}
}
private void step3GetLayerPreview() {
// get the preview string to get file header order, then get the previewAsData
nodeService.getNodePreview(NodeType.LAYER, layerId, new AsyncCallback<String>() {
@Override
public void onSuccess(String pagedResultString) {
LayerPreview layerPreview = null;
try {
PagedResults pagedResult = nodeModelCreator.createPagedResults(pagedResultString);
List<String> results = pagedResult.getResults();
if(results.size() > 0) {
layerPreview = nodeModelCreator.createLayerPreview(results.get(0));
} else {
view.showLayerPreviewUnavailable();
onFailure(null);
return;
}
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
setLayerPreview(layerPreview);
// continue
step4SetLicenseAgreement();
}
@Override
public void onFailure(Throwable caught) {
// continue
step4SetLicenseAgreement();
view.showLayerPreviewUnavailable();
}
});
}
private void step6SetLayerDetails() {
// process the layer and send values to view
view.setLayerDetails(model.getId(),
model.getName(),
model.getProcessingFacility(),
model.getQcBy(), "#ComingSoon:0",
"qc_script.R", "#ComingSoon:0",
model.getQcDate(),
model.getDescription(),
5,
Integer.MAX_VALUE, // TODO : get total number of rows in layer
"Public", // TODO : replace with security object
"<a href=\"#Dataset:"+ model.getParentId() +"\">Dataset</a>", // TODO : have dataset name included in layer metadata
model.getPlatform(),
iisAdministrator,
ccanEdit);
}
private void step4SetLicenseAgreement() {
// get Dataset to get its EULA id
nodeService.getNodeJSON(NodeType.DATASET, model.getParentId(), new AsyncCallback<String>() {
@Override
public void onSuccess(String datasetJson) {
Dataset dataset = null;
try {
dataset = nodeModelCreator.createDataset(datasetJson);
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
if(dataset != null) {
// Dataset found, get EULA id if exists
final String eulaId = dataset.getEulaId();
if(eulaId == null) {
// No EULA id means that this has open downloads
view.requireLicenseAcceptance(false);
licenseAgreement = null;
view.setLicenseAgreement(licenseAgreement);
step5LoadDownloadLocations();
} else {
// EULA required
// now query to see if user has accepted the agreement
UserData currentUser = authenticationController.getLoggedInUser();
licenseService.hasAccepted(currentUser.getEmail(), eulaId, model.getParentId(), new AsyncCallback<Boolean>() {
@Override
public void onSuccess(final Boolean hasAccepted) {
hasAcceptedLicenseAgreement = hasAccepted;
view.requireLicenseAcceptance(!hasAccepted);
// load license agreement (needed for viewing even if hasAccepted)
nodeService.getNodeJSON(NodeType.EULA, eulaId, new AsyncCallback<String>() {
@Override
public void onSuccess(String eulaJson) {
EULA eula = null;
try {
eula = nodeModelCreator.createEULA(eulaJson);
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
if(eula != null) {
// set licence agreement text
licenseAgreement = new LicenseAgreement();
licenseAgreement.setLicenseHtml(eula.getAgreement());
licenseAgreement.setEulaId(eulaId);
view.setLicenseAgreement(licenseAgreement);
if(hasAcceptedLicenseAgreement) {
// will throw security exception if user has not accepted this yet
step5LoadDownloadLocations();
- }
+ } else {
+ // TODO: this is pretty weak
+ step6SetLayerDetails();
+ }
} else {
step5ErrorSetDownloadFailure();
}
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
} else {
step5ErrorSetDownloadFailure();
}
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
private void step5ErrorSetDownloadFailure() {
view.showErrorMessage("Dataset downloading unavailable. Please try reloading the page.");
view.setDownloadUnavailable();
view.disableLicensedDownloads(true);
step6SetLayerDetails();
}
protected void setLayerPreview(LayerPreview preview) {
this.layerPreview = preview;
// get column display order, if possible from the layer preview
List<String> columnDisplayOrder = preview.getHeaders();
// TODO : get columns descriptions from service
Map<String, String> columnDescriptions = getTempColumnDescriptions();
Map<String, String> columnUnits = getTempColumnUnits();
// append units onto description
for(String key : columnUnits.keySet()) {
String units = columnUnits.get(key);
columnDescriptions.put(key, columnDescriptions.get(key) + " (" + units + ")");
}
view.setLayerPreviewTable(preview.getRows(), columnDisplayOrder, columnDescriptions, columnUnits);
}
private void step5LoadDownloadLocations() {
view.showDownloadsLoading();
nodeService.getNodeLocations(NodeType.LAYER, layerId, new AsyncCallback<String>() {
@Override
public void onSuccess(String pagedResultString) {
List<FileDownload> downloads = new ArrayList<FileDownload>();
try {
PagedResults pagedResult = nodeModelCreator.createPagedResults(pagedResultString);
List<String> results = pagedResult.getResults();
for(String fileDownloadString : results) {
DownloadLocation downloadLocation = nodeModelCreator.createDownloadLocation(fileDownloadString);
if(downloadLocation != null && downloadLocation.getPath() != null) {
FileDownload dl = new FileDownload(downloadLocation.getPath(), "Download " + model.getName(), downloadLocation.getMd5sum());
downloads.add(dl);
}
}
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
view.setLicensedDownloads(downloads);
// show download if requested
if(showDownload != null && showDownload == true) {
if(downloadAttempted()) {
view.showDownload();
}
}
step6SetLayerDetails();
}
@Override
public void onFailure(Throwable caught) {
view.setDownloadUnavailable();
step6SetLayerDetails();
}
});
}
private Map<String, String> getTempColumnUnits() {
Map<String,String> units = new LinkedHashMap<String, String>();
units.put("predxbxpsa","ng/mL");
units.put("age","years");
units.put("pre_treatment_psa","ng/mL");
units.put("bcr_freetime","years");
units.put("survtime","months");
units.put("nomogram_pfp_postrp","probability");
units.put("nomogram_nomopred_extra_capsular_extension","probability");
units.put("nomogram_nomopred_lni","probability");
units.put("nomogram_nomopred_ocd","probability");
units.put("nomogram_nomopred_seminal_vesicle_invasion","probability");
return units;
}
private Map<String, String> getTempColumnDescriptions() {
Map<String,String> descriptions = new LinkedHashMap<String, String>();
descriptions.put("sample_type","Type of sample that was profiled. One of: Benign=benign tumor ,CELL LINE=cancer cell line , MET=metastatic tumor, PRIMARY=primary tumor or XENOGRAFT. ");
descriptions.put("metastatic_site","Site in the body where metastatic tumor was detected.");
descriptions.put("ethnicity","ethnicity of the individual");
descriptions.put("predxbxpsa","PSA prior to diagnostic biopsy");
descriptions.put("age","Age at diagnosis");
descriptions.put("clinical_primary_gleason","clinical gleason score of the majority of the tumor");
descriptions.put("clinical_secondary_gleason","clinical gleason score of the minority of the tumor");
descriptions.put("clinical_gleason_score","clinical tertiary gleason score");
descriptions.put("pre_treatment_psa","Prostate specific antigen level prior to treatment");
descriptions.put("clinical_tnm_stage_t","Cancer stage based on the Tumor, Node, Metastasis scoring system");
descriptions.put("neoadjradtx","neo-adjuvant treatment");
descriptions.put("chemotx","chemotherapy treatment");
descriptions.put("hormtx","Hormone treatment");
descriptions.put("radtxtype","radiation treatment type");
descriptions.put("rp_type","Surgical treatment. RP=radical prostatectomy, LP=laproscopic prostatectomy, SALRP=Salvage radical prostatectomy");
descriptions.put("sms","somatostatin");
descriptions.put("extra_capsular_extension","extra-capsular extension: cancer extending beyond the prostate capsule");
descriptions.put("seminal_vesicle_invasion","seminal vesicle invasion. Either \"positive\" or \"negative\"");
descriptions.put("tnm_stage_n","TNM \"N\" stage");
descriptions.put("number_nodes_removed","Number of cancerous nodes removed");
descriptions.put("number_nodes_positive","number node-positive nodes");
descriptions.put("pathologic_tnm_stage_t","pathologic TNM \"T\" stage");
descriptions.put("pathologic_primary_gleason","pathalogic gleason score of the majority of the tumor");
descriptions.put("pathologic_secondary_gleason","pathalagic gleason score of the minority of the tumor");
descriptions.put("pathologic_gleason_score","pathalogic tertiary gleason score");
descriptions.put("bcr_freetime","elapsed time before bichemical recurrance");
descriptions.put("bcr_event","was a biochemical recurrance event detected");
descriptions.put("metsevent","metastatic event");
descriptions.put("survtime","Survival time post-diagnosis");
descriptions.put("event","Cause of death");
descriptions.put("nomogram_pfp_postrp","nomogram progression-free probability post radical prostatectomy");
descriptions.put("nomogram_nomopred_extra_capsular_extension","probability of extra capsular extension");
descriptions.put("nomogram_nomopred_lni","probability of lymph node involvement");
descriptions.put("nomogram_nomopred_ocd","probability of organ confined disease");
descriptions.put("nomogram_nomopred_seminal_vesicle_invasion","probability of seminal vesicle invasion");
descriptions.put("copy_number_cluster","copy number cluster size");
descriptions.put("expression_array_tissue_source","Source of tissue used for expression profiling");
return descriptions;
}
}
| true | true | private void step4SetLicenseAgreement() {
// get Dataset to get its EULA id
nodeService.getNodeJSON(NodeType.DATASET, model.getParentId(), new AsyncCallback<String>() {
@Override
public void onSuccess(String datasetJson) {
Dataset dataset = null;
try {
dataset = nodeModelCreator.createDataset(datasetJson);
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
if(dataset != null) {
// Dataset found, get EULA id if exists
final String eulaId = dataset.getEulaId();
if(eulaId == null) {
// No EULA id means that this has open downloads
view.requireLicenseAcceptance(false);
licenseAgreement = null;
view.setLicenseAgreement(licenseAgreement);
step5LoadDownloadLocations();
} else {
// EULA required
// now query to see if user has accepted the agreement
UserData currentUser = authenticationController.getLoggedInUser();
licenseService.hasAccepted(currentUser.getEmail(), eulaId, model.getParentId(), new AsyncCallback<Boolean>() {
@Override
public void onSuccess(final Boolean hasAccepted) {
hasAcceptedLicenseAgreement = hasAccepted;
view.requireLicenseAcceptance(!hasAccepted);
// load license agreement (needed for viewing even if hasAccepted)
nodeService.getNodeJSON(NodeType.EULA, eulaId, new AsyncCallback<String>() {
@Override
public void onSuccess(String eulaJson) {
EULA eula = null;
try {
eula = nodeModelCreator.createEULA(eulaJson);
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
if(eula != null) {
// set licence agreement text
licenseAgreement = new LicenseAgreement();
licenseAgreement.setLicenseHtml(eula.getAgreement());
licenseAgreement.setEulaId(eulaId);
view.setLicenseAgreement(licenseAgreement);
if(hasAcceptedLicenseAgreement) {
// will throw security exception if user has not accepted this yet
step5LoadDownloadLocations();
}
} else {
step5ErrorSetDownloadFailure();
}
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
} else {
step5ErrorSetDownloadFailure();
}
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
| private void step4SetLicenseAgreement() {
// get Dataset to get its EULA id
nodeService.getNodeJSON(NodeType.DATASET, model.getParentId(), new AsyncCallback<String>() {
@Override
public void onSuccess(String datasetJson) {
Dataset dataset = null;
try {
dataset = nodeModelCreator.createDataset(datasetJson);
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
if(dataset != null) {
// Dataset found, get EULA id if exists
final String eulaId = dataset.getEulaId();
if(eulaId == null) {
// No EULA id means that this has open downloads
view.requireLicenseAcceptance(false);
licenseAgreement = null;
view.setLicenseAgreement(licenseAgreement);
step5LoadDownloadLocations();
} else {
// EULA required
// now query to see if user has accepted the agreement
UserData currentUser = authenticationController.getLoggedInUser();
licenseService.hasAccepted(currentUser.getEmail(), eulaId, model.getParentId(), new AsyncCallback<Boolean>() {
@Override
public void onSuccess(final Boolean hasAccepted) {
hasAcceptedLicenseAgreement = hasAccepted;
view.requireLicenseAcceptance(!hasAccepted);
// load license agreement (needed for viewing even if hasAccepted)
nodeService.getNodeJSON(NodeType.EULA, eulaId, new AsyncCallback<String>() {
@Override
public void onSuccess(String eulaJson) {
EULA eula = null;
try {
eula = nodeModelCreator.createEULA(eulaJson);
} catch (RestServiceException ex) {
DisplayUtils.handleServiceException(ex, placeChanger);
onFailure(null);
return;
}
if(eula != null) {
// set licence agreement text
licenseAgreement = new LicenseAgreement();
licenseAgreement.setLicenseHtml(eula.getAgreement());
licenseAgreement.setEulaId(eulaId);
view.setLicenseAgreement(licenseAgreement);
if(hasAcceptedLicenseAgreement) {
// will throw security exception if user has not accepted this yet
step5LoadDownloadLocations();
} else {
// TODO: this is pretty weak
step6SetLayerDetails();
}
} else {
step5ErrorSetDownloadFailure();
}
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
} else {
step5ErrorSetDownloadFailure();
}
}
@Override
public void onFailure(Throwable caught) {
step5ErrorSetDownloadFailure();
}
});
}
|
diff --git a/Coupling/src/coupling/app/BL/BLShopList.java b/Coupling/src/coupling/app/BL/BLShopList.java
index 76dfd39..ad0041c 100644
--- a/Coupling/src/coupling/app/BL/BLShopList.java
+++ b/Coupling/src/coupling/app/BL/BLShopList.java
@@ -1,173 +1,173 @@
package coupling.app.BL;
import org.json.JSONException;
import org.json.JSONObject;
import android.database.Cursor;
import android.util.Log;
import coupling.app.Ids;
import coupling.app.Utils;
import coupling.app.com.API;
import coupling.app.com.AppFeature;
import coupling.app.com.IBLConnector;
import coupling.app.com.ITask;
import coupling.app.com.Message;
import coupling.app.data.DALShopList;
import coupling.app.data.Enums.ActionType;
import coupling.app.data.Enums.CategoryType;
import static coupling.app.com.Constants.*;
public class BLShopList extends AppFeature{
private static final String GLOBAL_LIST_ID = "GlobalListId";
private static final String ITEM_NAME = "ItemName";
private static final String QUANTITY = "Quantity";
private static final String IS_DONE = "IsDone";
private DALShopList dataSource;
private API api;
private ITask tasker;
private Long GlobalListId;
IBLConnector connector;
public BLShopList(){
}
public BLShopList(long listId){
dataSource = new DALShopList(listId);
api = API.getInstance();
categoryType = CategoryType.SHOPLIST;
GlobalListId = dataSource.getGlobalListId();
}
public void setBLConnector(IBLConnector connector){
this.connector = connector;
}
public void unsetBLConnector(){
this.connector = null;
}
public boolean createItem(String name, int quantity){
return createItem(null,name, quantity, true);
}
public boolean createItem(Long UId, String name, int quantity, boolean remote){
long localId = dataSource.createItem(UId, name, quantity);
boolean createdSuccessfuly = (localId != -1);
if(remote && createdSuccessfuly) {
Message message = new Message();
GlobalListId = (GlobalListId == null) ? dataSource.getGlobalListId() : GlobalListId;
message.getData().put(GLOBAL_LIST_ID, GlobalListId);
message.getData().put(LOCALID, localId);
message.getData().put(UID, UId);
message.getData().put(ITEM_NAME, name);
message.getData().put(QUANTITY, quantity);
message.setCategoryType(categoryType);
message.setActionType(ActionType.CREATE);
api.sync(message);
}
return createdSuccessfuly;
}
public boolean updateItem(Ids ids, String name, Integer quantity, Boolean isDone){
return updateItem(ids, name, quantity, isDone, true);
}
public boolean updateItem(Ids ids, String name, Integer quantity, Boolean isDone, boolean remote){
boolean res = dataSource.updateItem(ids, name, quantity, isDone);
if(remote && res){
Message message = new Message();
GlobalListId = (GlobalListId == null) ? dataSource.getGlobalListId() : GlobalListId;
message.getData().put(GLOBAL_LIST_ID, GlobalListId);
message.getData().put(UID, ids.getGlobalId());
if(name != null)
message.getData().put(ITEM_NAME, name);
if(quantity != null)
message.getData().put(QUANTITY, quantity);
if(isDone != null)
message.getData().put(IS_DONE, isDone);
message.setCategoryType(categoryType);
message.setActionType(ActionType.UPDATE);
api.sync(message);
}
return res;
}
public boolean deleteItem(Ids ids){
return deleteItem(ids, true);
}
public boolean deleteItem(Ids ids, boolean remote){
boolean res = dataSource.deleteItem(ids);
if(remote && res){
Message message = new Message();
GlobalListId = (GlobalListId == null) ? dataSource.getGlobalListId() : GlobalListId;
message.getData().put(GLOBAL_LIST_ID, GlobalListId);
message.getData().put(UID, ids.getGlobalId());
message.setCategoryType(categoryType);
message.setActionType(ActionType.DELETE);
api.sync(message);
}
return res;
}
public boolean updateId(Ids ids){
return dataSource.updateId(ids);
}
public Cursor getSource(){
return dataSource.getSource();
}
@Override
public void recieveData(JSONObject data, ActionType actionType) {
try{
Ids ids = new Ids();
- if(data.has(UID) && data.get(UID).equals("null"))
+ if(data.has(UID) && !data.get(UID).equals("null"))
ids.setGlobalId(data.getLong(UID));
String itemName = null;
Integer quantity = null;
Boolean isDone = null;
if(data.has(ITEM_NAME)) itemName = data.getString(ITEM_NAME);
if(data.has(QUANTITY)) quantity = data.getInt(QUANTITY);
if(data.has(IS_DONE)) isDone = data.getBoolean(IS_DONE);
switch (actionType) {
case CREATE:
createItem(ids.getGlobalId(), itemName, quantity, false);
break;
case UPDATE:
updateItem(ids, itemName, quantity , isDone, false);
break;
case DELETE:
deleteItem(ids, false);
break;
}
if(connector != null)
connector.Refresh();
}catch(JSONException e){
e.printStackTrace();
}
}
}
| true | true | public void recieveData(JSONObject data, ActionType actionType) {
try{
Ids ids = new Ids();
if(data.has(UID) && data.get(UID).equals("null"))
ids.setGlobalId(data.getLong(UID));
String itemName = null;
Integer quantity = null;
Boolean isDone = null;
if(data.has(ITEM_NAME)) itemName = data.getString(ITEM_NAME);
if(data.has(QUANTITY)) quantity = data.getInt(QUANTITY);
if(data.has(IS_DONE)) isDone = data.getBoolean(IS_DONE);
switch (actionType) {
case CREATE:
createItem(ids.getGlobalId(), itemName, quantity, false);
break;
case UPDATE:
updateItem(ids, itemName, quantity , isDone, false);
break;
case DELETE:
deleteItem(ids, false);
break;
}
if(connector != null)
connector.Refresh();
}catch(JSONException e){
e.printStackTrace();
}
}
| public void recieveData(JSONObject data, ActionType actionType) {
try{
Ids ids = new Ids();
if(data.has(UID) && !data.get(UID).equals("null"))
ids.setGlobalId(data.getLong(UID));
String itemName = null;
Integer quantity = null;
Boolean isDone = null;
if(data.has(ITEM_NAME)) itemName = data.getString(ITEM_NAME);
if(data.has(QUANTITY)) quantity = data.getInt(QUANTITY);
if(data.has(IS_DONE)) isDone = data.getBoolean(IS_DONE);
switch (actionType) {
case CREATE:
createItem(ids.getGlobalId(), itemName, quantity, false);
break;
case UPDATE:
updateItem(ids, itemName, quantity , isDone, false);
break;
case DELETE:
deleteItem(ids, false);
break;
}
if(connector != null)
connector.Refresh();
}catch(JSONException e){
e.printStackTrace();
}
}
|
diff --git a/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandlerDispatch.java b/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandlerDispatch.java
index ca1355fc..28630cf9 100644
--- a/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandlerDispatch.java
+++ b/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandlerDispatch.java
@@ -1,196 +1,197 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.solder.exception.control;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.enterprise.context.ConversationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Named;
import org.jboss.solder.exception.control.extension.CatchExtension;
import org.jboss.solder.exception.control.log.ExceptionHandlerDispatcherLog;
import org.jboss.solder.logging.Logger;
/**
* Observer of {@link ExceptionToCatch} events and handler dispatcher. All handlers are invoked from this class. This
* class is immutable.
*/
public class ExceptionHandlerDispatch {
private ExceptionToCatch exceptionToCatch;
private ExceptionStack exceptionStack;
private final ExceptionHandlerDispatcherLog log = Logger.getMessageLogger(ExceptionHandlerDispatcherLog.class,
ExceptionHandlerDispatcherLog.class.getPackage().getName());
/**
* Observes the event, finds the correct exception handler(s) and invokes them.
*
* @param eventException exception to be invoked
* @param bm active bean manager
* @param extension catch extension instance to obtain handlers
* @param stackEvent Event for modifying the exception stack
* @throws Throwable If a handler requests the exception to be re-thrown.
*/
@SuppressWarnings({"unchecked", "MethodWithMultipleLoops", "ThrowableResultOfMethodCallIgnored"})
public void executeHandlers(@Observes @Any ExceptionToCatch eventException, final BeanManager bm,
CatchExtension extension, Event<ExceptionStack> stackEvent) throws Throwable {
log.enteringExceptionHandlerDispatcher(eventException.getException());
CreationalContext<Object> ctx = null;
this.exceptionToCatch = eventException;
Throwable throwException = null;
try {
ctx = bm.createCreationalContext(null);
final Set<HandlerMethod<?>> processedHandlers = new HashSet<HandlerMethod<?>>();
final ExceptionStack stack = new ExceptionStack(eventException.getException());
stackEvent.fire(stack); // Allow for modifying the exception stack
// TODO: Clean this up so there's only the while and one for loop
inbound_cause:
while (stack.getCurrent() != null) {
this.exceptionStack = stack;
final List<HandlerMethod<?>> breadthFirstHandlerMethods = new ArrayList<HandlerMethod<?>>(
extension.getHandlersForExceptionType(stack.getCurrent().getClass(),
bm, eventException.getQualifiers(), TraversalMode.BREADTH_FIRST));
for (HandlerMethod<?> handler : breadthFirstHandlerMethods) {
if (!processedHandlers.contains(handler)) {
log.notifyingHandler(handler);
@SuppressWarnings("rawtypes")
final CaughtException breadthFirstEvent = new CaughtException(stack, true, eventException.isHandled());
handler.notify(breadthFirstEvent, bm);
log.returnFromHandler(handler, breadthFirstEvent.getFlow().name());
if (!breadthFirstEvent.isUnmute()) {
processedHandlers.add(handler);
}
switch (breadthFirstEvent.getFlow()) {
case HANDLED:
eventException.setHandled(true);
return;
case MARK_HANDLED:
eventException.setHandled(true);
break;
case ABORT:
return;
case DROP_CAUSE:
eventException.setHandled(true);
stack.dropCause();
continue inbound_cause;
case RETHROW:
throwException = eventException.getException();
break;
case THROW:
throwException = breadthFirstEvent.getThrowNewException();
}
}
}
final List<HandlerMethod<? extends Throwable>> depthFirstHandlerMethods = new ArrayList<HandlerMethod<? extends Throwable>>(
extension.getHandlersForExceptionType(stack.getCurrent().getClass(),
bm, eventException.getQualifiers(), TraversalMode.DEPTH_FIRST));
// Reverse these so category handlers are last
Collections.reverse(depthFirstHandlerMethods);
for (HandlerMethod<?> handler : depthFirstHandlerMethods) {
if (!processedHandlers.contains(handler)) {
log.notifyingHandler(handler);
@SuppressWarnings("rawtypes")
final CaughtException depthFirstEvent = new CaughtException(stack, false, eventException.isHandled());
handler.notify(depthFirstEvent, bm);
log.returnFromHandler(handler, depthFirstEvent.getFlow().name());
if (!depthFirstEvent.isUnmute()) {
processedHandlers.add(handler);
}
switch (depthFirstEvent.getFlow()) {
case HANDLED:
eventException.setHandled(true);
return;
case MARK_HANDLED:
eventException.setHandled(true);
break;
case ABORT:
return;
case DROP_CAUSE:
eventException.setHandled(true);
stack.dropCause();
continue inbound_cause;
case RETHROW:
throwException = eventException.getException();
break;
case THROW:
throwException = depthFirstEvent.getThrowNewException();
}
}
}
this.exceptionStack.dropCause();
}
if (!eventException.isHandled() && throwException == null) {
log.noHandlersFound(eventException.getException());
+ throw eventException.getException();
}
if (throwException != null) {
throw throwException;
}
} finally {
if (ctx != null) {
ctx.release();
}
}
log.endingExceptionHandlerDispatcher(exceptionToCatch.getException());
}
@Produces
@ConversationScoped
@Named("handledException")
public ExceptionStack getExceptionStack() {
return this.exceptionStack;
}
@Produces
@ConversationScoped
@Named("caughtException")
public ExceptionToCatch getExceptionToCatch() {
return this.exceptionToCatch;
}
}
| true | true | public void executeHandlers(@Observes @Any ExceptionToCatch eventException, final BeanManager bm,
CatchExtension extension, Event<ExceptionStack> stackEvent) throws Throwable {
log.enteringExceptionHandlerDispatcher(eventException.getException());
CreationalContext<Object> ctx = null;
this.exceptionToCatch = eventException;
Throwable throwException = null;
try {
ctx = bm.createCreationalContext(null);
final Set<HandlerMethod<?>> processedHandlers = new HashSet<HandlerMethod<?>>();
final ExceptionStack stack = new ExceptionStack(eventException.getException());
stackEvent.fire(stack); // Allow for modifying the exception stack
// TODO: Clean this up so there's only the while and one for loop
inbound_cause:
while (stack.getCurrent() != null) {
this.exceptionStack = stack;
final List<HandlerMethod<?>> breadthFirstHandlerMethods = new ArrayList<HandlerMethod<?>>(
extension.getHandlersForExceptionType(stack.getCurrent().getClass(),
bm, eventException.getQualifiers(), TraversalMode.BREADTH_FIRST));
for (HandlerMethod<?> handler : breadthFirstHandlerMethods) {
if (!processedHandlers.contains(handler)) {
log.notifyingHandler(handler);
@SuppressWarnings("rawtypes")
final CaughtException breadthFirstEvent = new CaughtException(stack, true, eventException.isHandled());
handler.notify(breadthFirstEvent, bm);
log.returnFromHandler(handler, breadthFirstEvent.getFlow().name());
if (!breadthFirstEvent.isUnmute()) {
processedHandlers.add(handler);
}
switch (breadthFirstEvent.getFlow()) {
case HANDLED:
eventException.setHandled(true);
return;
case MARK_HANDLED:
eventException.setHandled(true);
break;
case ABORT:
return;
case DROP_CAUSE:
eventException.setHandled(true);
stack.dropCause();
continue inbound_cause;
case RETHROW:
throwException = eventException.getException();
break;
case THROW:
throwException = breadthFirstEvent.getThrowNewException();
}
}
}
final List<HandlerMethod<? extends Throwable>> depthFirstHandlerMethods = new ArrayList<HandlerMethod<? extends Throwable>>(
extension.getHandlersForExceptionType(stack.getCurrent().getClass(),
bm, eventException.getQualifiers(), TraversalMode.DEPTH_FIRST));
// Reverse these so category handlers are last
Collections.reverse(depthFirstHandlerMethods);
for (HandlerMethod<?> handler : depthFirstHandlerMethods) {
if (!processedHandlers.contains(handler)) {
log.notifyingHandler(handler);
@SuppressWarnings("rawtypes")
final CaughtException depthFirstEvent = new CaughtException(stack, false, eventException.isHandled());
handler.notify(depthFirstEvent, bm);
log.returnFromHandler(handler, depthFirstEvent.getFlow().name());
if (!depthFirstEvent.isUnmute()) {
processedHandlers.add(handler);
}
switch (depthFirstEvent.getFlow()) {
case HANDLED:
eventException.setHandled(true);
return;
case MARK_HANDLED:
eventException.setHandled(true);
break;
case ABORT:
return;
case DROP_CAUSE:
eventException.setHandled(true);
stack.dropCause();
continue inbound_cause;
case RETHROW:
throwException = eventException.getException();
break;
case THROW:
throwException = depthFirstEvent.getThrowNewException();
}
}
}
this.exceptionStack.dropCause();
}
if (!eventException.isHandled() && throwException == null) {
log.noHandlersFound(eventException.getException());
}
if (throwException != null) {
throw throwException;
}
} finally {
if (ctx != null) {
ctx.release();
}
}
log.endingExceptionHandlerDispatcher(exceptionToCatch.getException());
}
| public void executeHandlers(@Observes @Any ExceptionToCatch eventException, final BeanManager bm,
CatchExtension extension, Event<ExceptionStack> stackEvent) throws Throwable {
log.enteringExceptionHandlerDispatcher(eventException.getException());
CreationalContext<Object> ctx = null;
this.exceptionToCatch = eventException;
Throwable throwException = null;
try {
ctx = bm.createCreationalContext(null);
final Set<HandlerMethod<?>> processedHandlers = new HashSet<HandlerMethod<?>>();
final ExceptionStack stack = new ExceptionStack(eventException.getException());
stackEvent.fire(stack); // Allow for modifying the exception stack
// TODO: Clean this up so there's only the while and one for loop
inbound_cause:
while (stack.getCurrent() != null) {
this.exceptionStack = stack;
final List<HandlerMethod<?>> breadthFirstHandlerMethods = new ArrayList<HandlerMethod<?>>(
extension.getHandlersForExceptionType(stack.getCurrent().getClass(),
bm, eventException.getQualifiers(), TraversalMode.BREADTH_FIRST));
for (HandlerMethod<?> handler : breadthFirstHandlerMethods) {
if (!processedHandlers.contains(handler)) {
log.notifyingHandler(handler);
@SuppressWarnings("rawtypes")
final CaughtException breadthFirstEvent = new CaughtException(stack, true, eventException.isHandled());
handler.notify(breadthFirstEvent, bm);
log.returnFromHandler(handler, breadthFirstEvent.getFlow().name());
if (!breadthFirstEvent.isUnmute()) {
processedHandlers.add(handler);
}
switch (breadthFirstEvent.getFlow()) {
case HANDLED:
eventException.setHandled(true);
return;
case MARK_HANDLED:
eventException.setHandled(true);
break;
case ABORT:
return;
case DROP_CAUSE:
eventException.setHandled(true);
stack.dropCause();
continue inbound_cause;
case RETHROW:
throwException = eventException.getException();
break;
case THROW:
throwException = breadthFirstEvent.getThrowNewException();
}
}
}
final List<HandlerMethod<? extends Throwable>> depthFirstHandlerMethods = new ArrayList<HandlerMethod<? extends Throwable>>(
extension.getHandlersForExceptionType(stack.getCurrent().getClass(),
bm, eventException.getQualifiers(), TraversalMode.DEPTH_FIRST));
// Reverse these so category handlers are last
Collections.reverse(depthFirstHandlerMethods);
for (HandlerMethod<?> handler : depthFirstHandlerMethods) {
if (!processedHandlers.contains(handler)) {
log.notifyingHandler(handler);
@SuppressWarnings("rawtypes")
final CaughtException depthFirstEvent = new CaughtException(stack, false, eventException.isHandled());
handler.notify(depthFirstEvent, bm);
log.returnFromHandler(handler, depthFirstEvent.getFlow().name());
if (!depthFirstEvent.isUnmute()) {
processedHandlers.add(handler);
}
switch (depthFirstEvent.getFlow()) {
case HANDLED:
eventException.setHandled(true);
return;
case MARK_HANDLED:
eventException.setHandled(true);
break;
case ABORT:
return;
case DROP_CAUSE:
eventException.setHandled(true);
stack.dropCause();
continue inbound_cause;
case RETHROW:
throwException = eventException.getException();
break;
case THROW:
throwException = depthFirstEvent.getThrowNewException();
}
}
}
this.exceptionStack.dropCause();
}
if (!eventException.isHandled() && throwException == null) {
log.noHandlersFound(eventException.getException());
throw eventException.getException();
}
if (throwException != null) {
throw throwException;
}
} finally {
if (ctx != null) {
ctx.release();
}
}
log.endingExceptionHandlerDispatcher(exceptionToCatch.getException());
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/html/HeadInferringTPI.java b/src/uk/org/ponder/rsf/renderer/html/HeadInferringTPI.java
index 7f2affb..a19ba7c 100644
--- a/src/uk/org/ponder/rsf/renderer/html/HeadInferringTPI.java
+++ b/src/uk/org/ponder/rsf/renderer/html/HeadInferringTPI.java
@@ -1,25 +1,25 @@
/*
* Created on 18 Sep 2006
*/
package uk.org.ponder.rsf.renderer.html;
import java.util.Map;
import uk.org.ponder.rsf.content.ContentTypeInfoRegistry;
import uk.org.ponder.rsf.template.ContentTypedTPI;
import uk.org.ponder.rsf.template.XMLLump;
public class HeadInferringTPI implements ContentTypedTPI {
public String[] getInterceptedContentTypes() {
return new String[] { ContentTypeInfoRegistry.HTML,
ContentTypeInfoRegistry.HTML_FRAGMENT };
}
public void adjustAttributes(String tag, Map attributes) {
- if (tag.equals("head")) {
+ if (tag.equals("head") && attributes.get(XMLLump.ID_ATTRIBUTE) == null) {
attributes.put(XMLLump.ID_ATTRIBUTE, XMLLump.SCR_PREFIX
+ HeadCollectingSCR.NAME);
}
}
}
| true | true | public void adjustAttributes(String tag, Map attributes) {
if (tag.equals("head")) {
attributes.put(XMLLump.ID_ATTRIBUTE, XMLLump.SCR_PREFIX
+ HeadCollectingSCR.NAME);
}
}
| public void adjustAttributes(String tag, Map attributes) {
if (tag.equals("head") && attributes.get(XMLLump.ID_ATTRIBUTE) == null) {
attributes.put(XMLLump.ID_ATTRIBUTE, XMLLump.SCR_PREFIX
+ HeadCollectingSCR.NAME);
}
}
|
diff --git a/lib-core/src/test/java/org/silverpeas/quota/model/QuotaTest.java b/lib-core/src/test/java/org/silverpeas/quota/model/QuotaTest.java
index b93fbecc87..2b861960f4 100644
--- a/lib-core/src/test/java/org/silverpeas/quota/model/QuotaTest.java
+++ b/lib-core/src/test/java/org/silverpeas/quota/model/QuotaTest.java
@@ -1,132 +1,132 @@
package org.silverpeas.quota.model;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.math.BigDecimal;
import org.junit.Test;
import org.silverpeas.quota.contant.QuotaLoad;
import org.silverpeas.quota.contant.QuotaType;
import org.silverpeas.quota.exception.QuotaException;
import com.stratelia.webactiv.util.exception.SilverpeasException;
public class QuotaTest {
@Test
public void testValidate() {
Quota quota = initializeQuota();
assertValidate(quota, true);
quota = initializeQuota();
quota.setId(null);
assertValidate(quota, true);
quota = initializeQuota();
quota.setSaveDate(null);
assertValidate(quota, true);
quota = initializeQuota();
quota.setCount(-100);
assertValidate(quota, true);
quota = initializeQuota();
quota.setType(null);
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId(null);
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId("");
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId(" ");
- assertValidate(quota, true);
+ assertValidate(quota, false);
quota = initializeQuota();
quota.setMinCount(-1);
assertValidate(quota, false);
quota = initializeQuota();
quota.setMaxCount(-1);
assertValidate(quota, false);
quota = initializeQuota();
quota.setMinCount(2);
quota.setMaxCount(1);
assertValidate(quota, false);
}
private <T extends SilverpeasException> void assertValidate(final Quota quota,
final boolean isValid) {
boolean isException = false;
try {
quota.validate();
} catch (final QuotaException qe) {
isException = true;
}
assertThat(isException, is(!isValid));
}
@Test
public void testGetLoad() {
Quota quota = initializeQuota();
quota.setMaxCount(0);
assertThat(quota.getLoad(), is(QuotaLoad.UNLIMITED));
quota = initializeQuota();
quota.setCount(0);
assertThat(quota.getLoad(), is(QuotaLoad.EMPTY));
quota = initializeQuota();
quota.setCount(1);
assertThat(quota.getLoad(), is(QuotaLoad.NOT_ENOUGH));
quota = initializeQuota();
quota.setCount(quota.getMaxCount() - 1);
assertThat(quota.getLoad(), is(QuotaLoad.NOT_FULL));
quota = initializeQuota();
quota.setCount(quota.getMaxCount());
assertThat(quota.getLoad(), is(QuotaLoad.FULL));
quota = initializeQuota();
quota.setMinCount(0);
quota.setCount(0);
assertThat(quota.getLoad(), is(QuotaLoad.EMPTY));
quota = initializeQuota();
quota.setCount(1000);
assertThat(quota.getLoad(), is(QuotaLoad.OUT_OF_BOUNDS));
}
@Test
public void testGetLoadRate() {
Quota quota = initializeQuota();
BigDecimal loadRate = quota.getLoadRate();
assertThat(loadRate, is(new BigDecimal("0.60869565217391304348")));
}
@Test
public void testGetLoadPercentage() {
Quota quota = initializeQuota();
BigDecimal loadPercentage = quota.getLoadPercentage();
assertThat(loadPercentage, is(new BigDecimal("60.87")));
}
private Quota initializeQuota() {
final Quota quota = new Quota();
quota.setId(26L);
quota.setType(QuotaType.USERS_IN_DOMAIN);
quota.setResourceId("26");
quota.setMinCount(10);
quota.setMaxCount(23);
quota.setCount(14);
quota.setSaveDate(java.sql.Date.valueOf("2012-01-01"));
return quota;
}
}
| true | true | public void testValidate() {
Quota quota = initializeQuota();
assertValidate(quota, true);
quota = initializeQuota();
quota.setId(null);
assertValidate(quota, true);
quota = initializeQuota();
quota.setSaveDate(null);
assertValidate(quota, true);
quota = initializeQuota();
quota.setCount(-100);
assertValidate(quota, true);
quota = initializeQuota();
quota.setType(null);
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId(null);
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId("");
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId(" ");
assertValidate(quota, true);
quota = initializeQuota();
quota.setMinCount(-1);
assertValidate(quota, false);
quota = initializeQuota();
quota.setMaxCount(-1);
assertValidate(quota, false);
quota = initializeQuota();
quota.setMinCount(2);
quota.setMaxCount(1);
assertValidate(quota, false);
}
| public void testValidate() {
Quota quota = initializeQuota();
assertValidate(quota, true);
quota = initializeQuota();
quota.setId(null);
assertValidate(quota, true);
quota = initializeQuota();
quota.setSaveDate(null);
assertValidate(quota, true);
quota = initializeQuota();
quota.setCount(-100);
assertValidate(quota, true);
quota = initializeQuota();
quota.setType(null);
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId(null);
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId("");
assertValidate(quota, false);
quota = initializeQuota();
quota.setResourceId(" ");
assertValidate(quota, false);
quota = initializeQuota();
quota.setMinCount(-1);
assertValidate(quota, false);
quota = initializeQuota();
quota.setMaxCount(-1);
assertValidate(quota, false);
quota = initializeQuota();
quota.setMinCount(2);
quota.setMaxCount(1);
assertValidate(quota, false);
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/TVShowBannerImageGalleryAdapter.java b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/TVShowBannerImageGalleryAdapter.java
index 0b75b115..d96b6a5d 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/TVShowBannerImageGalleryAdapter.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/TVShowBannerImageGalleryAdapter.java
@@ -1,160 +1,159 @@
/**
* The MIT License (MIT)
* Copyright (c) 2013 David Carver
* 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 us.nineworlds.serenity.ui.browser.tv;
import java.util.ArrayList;
import java.util.List;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.model.impl.AbstractSeriesContentInfo;
import us.nineworlds.serenity.core.model.impl.TVShowSeriesInfo;
import us.nineworlds.serenity.core.services.ShowRetrievalIntentService;
import us.nineworlds.serenity.ui.adapters.AbstractPosterImageGalleryAdapter;
import us.nineworlds.serenity.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.TextView;
/**
*
* @author dcarver
*
*/
public class TVShowBannerImageGalleryAdapter extends AbstractPosterImageGalleryAdapter {
private static List<TVShowSeriesInfo> tvShowList = null;
private String baseUrl;
private String key;
private static ProgressDialog pd;
public TVShowBannerImageGalleryAdapter(Context c, String key, String category) {
super(c, key, category);
tvShowList = new ArrayList<TVShowSeriesInfo>();
imageLoader = SerenityApplication.getImageLoader();
this.key = key;
try {
baseUrl = SerenityApplication.getPlexFactory().baseURL();
fetchData();
} catch (Exception ex) {
Log.e(getClass().getName(), "Error connecting to plex.", ex);
}
}
protected void fetchData() {
pd = ProgressDialog.show(context, "", "Retrieving Shows.");
handler = new ShowRetrievalHandler();
Messenger messenger = new Messenger(handler);
Intent intent = new Intent(context, ShowRetrievalIntentService.class);
intent.putExtra("MESSENGER", messenger);
intent.putExtra("key", key);
intent.putExtra("category", category);
context.startService(intent);
}
/* (non-Javadoc)
* @see android.widget.Adapter#getCount()
*/
public int getCount() {
return tvShowList.size();
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItem(int)
*/
public Object getItem(int position) {
return tvShowList.get(position);
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
}
/* (non-Javadoc)
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
public View getView(int position, View convertView, ViewGroup parent) {
AbstractSeriesContentInfo pi = tvShowList.get(position);
TVShowBannerImageView mpiv = new TVShowBannerImageView(context, pi);
mpiv.setBackgroundColor(Color.BLACK);
mpiv.setScaleType(ImageView.ScaleType.FIT_XY);
int width = 768;
int height = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
mpiv.setLayoutParams(new Gallery.LayoutParams(width, height));
imageLoader.displayImage(pi.getPosterURL(), mpiv);
return mpiv;
}
private class ShowRetrievalHandler extends Handler {
@Override
public void handleMessage(Message msg) {
tvShowList = (List<TVShowSeriesInfo>) msg.obj;
+ Gallery posterGallery = (Gallery) context.findViewById(R.id.tvShowBannerGallery);
if (tvShowList != null) {
if (tvShowList.isEmpty()) {
Toast.makeText(context, "No Shows found for the category: " + category, Toast.LENGTH_LONG).show();
- } else {
- Gallery posterGallery = (Gallery) context.findViewById(R.id.tvShowBannerGallery);
- posterGallery.requestFocus();
}
TextView tv = (TextView)context.findViewById(R.id.tvShowItemCount);
tv.setText(Integer.toString(tvShowList.size()) + " Item(s)");
- }
+ }
notifyDataSetChanged();
+ posterGallery.requestFocus();
pd.dismiss();
}
}
/* (non-Javadoc)
* @see com.github.kingargyle.plexappclient.ui.adapters.AbstractPosterImageGalleryAdapter#fetchDataFromService()
*/
@Override
protected void fetchDataFromService() {
// TODO Auto-generated method stub
}
}
| false | true | public void handleMessage(Message msg) {
tvShowList = (List<TVShowSeriesInfo>) msg.obj;
if (tvShowList != null) {
if (tvShowList.isEmpty()) {
Toast.makeText(context, "No Shows found for the category: " + category, Toast.LENGTH_LONG).show();
} else {
Gallery posterGallery = (Gallery) context.findViewById(R.id.tvShowBannerGallery);
posterGallery.requestFocus();
}
TextView tv = (TextView)context.findViewById(R.id.tvShowItemCount);
tv.setText(Integer.toString(tvShowList.size()) + " Item(s)");
}
notifyDataSetChanged();
pd.dismiss();
}
| public void handleMessage(Message msg) {
tvShowList = (List<TVShowSeriesInfo>) msg.obj;
Gallery posterGallery = (Gallery) context.findViewById(R.id.tvShowBannerGallery);
if (tvShowList != null) {
if (tvShowList.isEmpty()) {
Toast.makeText(context, "No Shows found for the category: " + category, Toast.LENGTH_LONG).show();
}
TextView tv = (TextView)context.findViewById(R.id.tvShowItemCount);
tv.setText(Integer.toString(tvShowList.size()) + " Item(s)");
}
notifyDataSetChanged();
posterGallery.requestFocus();
pd.dismiss();
}
|
diff --git a/Goobi/src/org/goobi/mq/ActiveMQDirector.java b/Goobi/src/org/goobi/mq/ActiveMQDirector.java
index a5814b5cc..d1b9f5070 100644
--- a/Goobi/src/org/goobi/mq/ActiveMQDirector.java
+++ b/Goobi/src/org/goobi/mq/ActiveMQDirector.java
@@ -1,223 +1,225 @@
/**
* This file is part of the Goobi Application - a Workflow tool for the support of mass digitization.
*
* Visit the websites for more information.
* - http://www.goobi.org
* - http://launchpad.net/goobi-production
* - http://gdz.sub.uni-goettingen.de
* - http://www.intranda.com
* - http://digiverso.com
*
* 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
*
* Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions
* of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to
* link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you are not obliged to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package org.goobi.mq;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;
import org.goobi.mq.processors.CreateNewProcessProcessor;
import org.goobi.mq.processors.FinaliseStepProcessor;
import de.sub.goobi.config.ConfigMain;
/**
* The class ActiveMQDirector is the head of all Active MQ processors. It implements the ServletContextListener interface and is − if configured in
* web.xml − called automatically upon server starup. Its job is to connect to the Active MQ server and register the listeners configured.
*
* The ActiveMQDirector should ALWAYS be declared in web.xml. The Active MQ services are intended to be run in case that “activeMQ.hostURL” is
* configured in the GoobiConfig.properties file. To disable the service, the entry there should be emptied or commented out. Otherwise, a valid
* configuration would not start working and an administrator will hardly have a chance to find out why without inspecting the source code.
*
* The class ActiveMQDirector also provides a basic ExceptionListener implementation as required for the connection.
*
* @author Matthias Ronge <[email protected]>
*/
public class ActiveMQDirector implements ServletContextListener, ExceptionListener {
private static final Logger logger = Logger.getLogger(ActiveMQDirector.class);
// *** CONFIGURATION ***
// When implementing new Services, add them to this list:
protected static ActiveMQProcessor[] services;
static {
services = new ActiveMQProcessor[] { new CreateNewProcessProcessor(), new FinaliseStepProcessor() };
}
protected static Connection connection = null;
protected static Session session = null;
protected static MessageProducer resultsTopic;
/**
* The method contextInitialized() is called by the web container on startup and is used to start up the active MQ connection. All processors from
* services[] are registered.
*
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet .ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent initialisation) {
String activeMQHost = ConfigMain.getParameter("activeMQ.hostURL", null);
if (activeMQHost != null) {
session = connectToServer(activeMQHost);
if (session != null) {
registerListeners(services);
if (ConfigMain.getParameter("activeMQ.results.topic", null) != null) {
resultsTopic = setUpReportChannel(ConfigMain.getParameter("activeMQ.results.topic"));
}
}
}
}
/**
* Sets up a connection to an active MQ server. The connection object is global because it is needed later to shut down the connection.
*
* @param server
* should be “tcp://{host}:{port}” or “vm://localhost” in case that the server is run inside the same virtual machine
* @return the session object or “null” upon error
*/
protected Session connectToServer(String server) {
try {
connection = new ActiveMQConnectionFactory(server).createConnection();
connection.start();
connection.setExceptionListener(this); // → ActiveMQDirector.onException()
return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
} catch (Exception e) {
logger.fatal("Error connecting to ActiveMQ server, giving up.", e);
}
return null;
}
/**
* This method registers the listeners with the active MQ server.
*
* If a queue name was configured for a service, a MessageConsumer is set up to listen on that queue and, in case of incoming messages, make the
* service process the message. The message checker is saved inside the service to be able to shut it down later.
*/
protected void registerListeners(ActiveMQProcessor[] processors) {
for (ActiveMQProcessor processor : processors) {
if (processor.getQueueName() != null) {
MessageConsumer messageChecker = null;
try {
Destination queue = session.createQueue(processor.getQueueName());
messageChecker = session.createConsumer(queue);
messageChecker.setMessageListener(processor);
processor.saveChecker(messageChecker);
} catch (Exception e) {
logger.fatal("Error setting up monitoring for \"" + processor.getQueueName() + "\": Giving up.", e);
}
}
}
}
/**
* This sets up a connection to the topic the results shall be written to. The delivery mode is set so “persistent” to allow consumers not online
* with the server in the moment of message submission to read the messages later. The log messages are set to be kept on the server for 7 days.
* This value can be overridden from the GoobiConfig.properties parameter “activeMQ.results.timeToLive”. The time to live must be specified in
* milliseconds; 0 disables the oblivion. (See also: http://docs.oracle.com/javaee/6/api/javax/jms/MessageProducer.html#setTimeToLive%28long%29 )
*
* @param topic
* name of the active MQ topic
* @return a MessageProducer object ready for writing or “null” on error
*/
protected MessageProducer setUpReportChannel(String topic) {
MessageProducer result;
try {
Destination channel = session.createTopic(topic);
result = session.createProducer(channel);
result.setDeliveryMode(DeliveryMode.PERSISTENT);
result.setTimeToLive(ConfigMain.getLongParameter("activeMQ.results.timeToLive", 604800000));
return result;
} catch (Exception e) {
logger.fatal("Error setting up report channel \"" + topic + "\": Giving up.", e);
}
return null;
}
/**
* This method is referenced from this.connectToServer() − see there.
*
* @see javax.jms.ExceptionListener#onException(javax.jms.JMSException)
*/
@Override
public void onException(JMSException exce) {
logger.error(exce);
}
/**
* Any class that wants to create new Active MQ Messages needs read access to the session, since Active MQ messages don’t have a constructor.
*
* @return the session object
*/
public static Session getSession() {
return session;
}
/**
* Instances of WebServiceResult can be sent by calling their send() method. Therefore, they need read access on their topic.
*
* @return the resultsTopic object
*/
public static MessageProducer getResultsTopic() {
return resultsTopic;
}
/**
* The method contextDestroyed is called by the web container on shutdown. It shuts down all listeners, the session and last, the connection.
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet. ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent destruction) {
// Shut down all watchers on any queues
for (ActiveMQProcessor service : services) {
MessageConsumer watcher = service.getChecker();
if (watcher != null) {
try {
watcher.close();
} catch (JMSException e) {
logger.error(e);
}
}
}
// quit session
try {
if (session != null) {
session.close();
}
} catch (JMSException e) {
logger.error(e);
}
// shut down connection
try {
- connection.close();
+ if (connection != null) {
+ connection.close();
+ }
} catch (JMSException e) {
logger.error(e);
}
}
}
| true | true | public void contextDestroyed(ServletContextEvent destruction) {
// Shut down all watchers on any queues
for (ActiveMQProcessor service : services) {
MessageConsumer watcher = service.getChecker();
if (watcher != null) {
try {
watcher.close();
} catch (JMSException e) {
logger.error(e);
}
}
}
// quit session
try {
if (session != null) {
session.close();
}
} catch (JMSException e) {
logger.error(e);
}
// shut down connection
try {
connection.close();
} catch (JMSException e) {
logger.error(e);
}
}
| public void contextDestroyed(ServletContextEvent destruction) {
// Shut down all watchers on any queues
for (ActiveMQProcessor service : services) {
MessageConsumer watcher = service.getChecker();
if (watcher != null) {
try {
watcher.close();
} catch (JMSException e) {
logger.error(e);
}
}
}
// quit session
try {
if (session != null) {
session.close();
}
} catch (JMSException e) {
logger.error(e);
}
// shut down connection
try {
if (connection != null) {
connection.close();
}
} catch (JMSException e) {
logger.error(e);
}
}
|
diff --git a/src/com/fsck/k9/helper/ContactsSdk3_4.java b/src/com/fsck/k9/helper/ContactsSdk3_4.java
index d01f8e8..773ead7 100644
--- a/src/com/fsck/k9/helper/ContactsSdk3_4.java
+++ b/src/com/fsck/k9/helper/ContactsSdk3_4.java
@@ -1,257 +1,260 @@
package com.fsck.k9.helper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;
import com.fsck.k9.mail.Address;
/**
* Access the contacts on the device using the old API (introduced in SDK 1).
*
* @see android.provider.Contacts
*/
@SuppressWarnings("deprecation")
public class ContactsSdk3_4 extends com.fsck.k9.helper.Contacts
{
/**
* The order in which the search results are returned by
* {@link #searchContacts(CharSequence)}.
*/
private static final String SORT_ORDER =
Contacts.ContactMethods.TIMES_CONTACTED + " DESC, " +
Contacts.ContactMethods.DISPLAY_NAME + ", " +
Contacts.ContactMethods._ID;
/**
* Array of columns to load from the database.
*
* Important: The _ID field is needed by
* {@link com.fsck.k9.EmailAddressAdapter} or more specificly by
* {@link android.widget.ResourceCursorAdapter}.
*/
private static final String PROJECTION[] =
{
Contacts.ContactMethods._ID,
Contacts.ContactMethods.DISPLAY_NAME,
Contacts.ContactMethods.DATA,
Contacts.ContactMethods.PERSON_ID
};
/**
* Index of the name field in the projection. This must match the order in
* {@link #PROJECTION}.
*/
private static final int NAME_INDEX = 1;
/**
* Index of the email address field in the projection. This must match the
* order in {@link #PROJECTION}.
*/
private static final int EMAIL_INDEX = 2;
/**
* Index of the contact id field in the projection. This must match the order in
* {@link #PROJECTION}.
*/
private static final int CONTACT_ID_INDEX = 3;
public ContactsSdk3_4(final Context context)
{
super(context);
}
@Override
public void createContact(final Activity activity, final Address email)
{
final Uri contactUri = Uri.fromParts("mailto", email.getAddress(), null);
final Intent contactIntent = new Intent(Contacts.Intents.SHOW_OR_CREATE_CONTACT);
contactIntent.setData(contactUri);
// Pass along full E-mail string for possible create dialog
contactIntent.putExtra(Contacts.Intents.EXTRA_CREATE_DESCRIPTION,
email.toString());
// Only provide personal name hint if we have one
final String senderPersonal = email.getPersonal();
if (senderPersonal != null)
{
contactIntent.putExtra(Contacts.Intents.Insert.NAME, senderPersonal);
}
activity.startActivity(contactIntent);
}
@Override
public String getOwnerName()
{
String name = null;
final Cursor c = mContentResolver.query(
Uri.withAppendedPath(Contacts.People.CONTENT_URI, "owner"),
PROJECTION,
null,
null,
null);
if (c != null)
{
if (c.getCount() > 0)
{
c.moveToFirst();
name = getName(c);
}
c.close();
}
return name;
}
@Override
public boolean isInContacts(final String emailAddress)
{
boolean result = false;
final Cursor c = getContactByAddress(emailAddress);
if (c != null)
{
if (c.getCount() > 0)
{
result = true;
}
c.close();
}
return result;
}
@Override
public Cursor searchContacts(final CharSequence constraint)
{
final String where;
final String[] args;
if (constraint == null)
{
where = null;
args = null;
}
else
{
where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND" + "(" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
+ Contacts.People.NAME + " LIKE ?" +
+ ") OR (" +
Contacts.ContactMethods.DATA + " LIKE ?" +
")";
final String filter = constraint.toString() + "%";
- args = new String[] {filter, filter};
+ final String filter2 = "% " + filter;
+ args = new String[] {filter, filter2, filter};
}
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
if (c != null)
{
/*
* To prevent expensive execution in the UI thread:
* Cursors get lazily executed, so if you don't call anything on
* the cursor before returning it from the background thread you'll
* have a complied program for the cursor, but it won't have been
* executed to generate the data yet. Often the execution is more
* expensive than the compilation...
*/
c.getCount();
}
return c;
}
@Override
public String getNameForAddress(String address)
{
if (address == null)
{
return null;
}
final Cursor c = getContactByAddress(address);
String name = null;
if (c != null)
{
if (c.getCount() > 0)
{
c.moveToFirst();
name = getName(c);
}
c.close();
}
return name;
}
@Override
public String getName(Cursor c)
{
return c.getString(NAME_INDEX);
}
@Override
public String getEmail(Cursor c)
{
return c.getString(EMAIL_INDEX);
}
@Override
public void markAsContacted(final Address[] addresses)
{
//TODO: Optimize! Potentially a lot of database queries
for (final Address address : addresses)
{
final Cursor c = getContactByAddress(address.getAddress());
if (c != null)
{
if (c.getCount() > 0)
{
c.moveToFirst();
final long personId = c.getLong(CONTACT_ID_INDEX);
Contacts.People.markAsContacted(mContentResolver, personId);
}
c.close();
}
}
}
/**
* Return a {@link Cursor} instance that can be used to fetch information
* about the contact with the given email address.
*
* @param address The email address to search for.
* @return A {@link Cursor} instance that can be used to fetch information
* about the contact with the given email address
*/
private Cursor getContactByAddress(String address)
{
final String where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND " +
Contacts.ContactMethods.DATA + " = ?";
final String[] args = new String[] {address};
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
return c;
}
}
| false | true | public Cursor searchContacts(final CharSequence constraint)
{
final String where;
final String[] args;
if (constraint == null)
{
where = null;
args = null;
}
else
{
where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND" + "(" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
Contacts.ContactMethods.DATA + " LIKE ?" +
")";
final String filter = constraint.toString() + "%";
args = new String[] {filter, filter};
}
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
if (c != null)
{
/*
* To prevent expensive execution in the UI thread:
* Cursors get lazily executed, so if you don't call anything on
* the cursor before returning it from the background thread you'll
* have a complied program for the cursor, but it won't have been
* executed to generate the data yet. Often the execution is more
* expensive than the compilation...
*/
c.getCount();
}
return c;
}
| public Cursor searchContacts(final CharSequence constraint)
{
final String where;
final String[] args;
if (constraint == null)
{
where = null;
args = null;
}
else
{
where = Contacts.ContactMethods.KIND + " = " + Contacts.KIND_EMAIL +
" AND" + "(" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
Contacts.People.NAME + " LIKE ?" +
") OR (" +
Contacts.ContactMethods.DATA + " LIKE ?" +
")";
final String filter = constraint.toString() + "%";
final String filter2 = "% " + filter;
args = new String[] {filter, filter2, filter};
}
final Cursor c = mContentResolver.query(
Contacts.ContactMethods.CONTENT_URI,
PROJECTION,
where,
args,
SORT_ORDER);
if (c != null)
{
/*
* To prevent expensive execution in the UI thread:
* Cursors get lazily executed, so if you don't call anything on
* the cursor before returning it from the background thread you'll
* have a complied program for the cursor, but it won't have been
* executed to generate the data yet. Often the execution is more
* expensive than the compilation...
*/
c.getCount();
}
return c;
}
|
diff --git a/app/controllers/Ways.java b/app/controllers/Ways.java
index 3c70aeb..7a6bde7 100644
--- a/app/controllers/Ways.java
+++ b/app/controllers/Ways.java
@@ -1,29 +1,29 @@
package controllers;
import java.util.List;
import models.AccessControl;
import models.Way;
import play.mvc.Controller;
import java.util.Date;
import play.Logger;
public class Ways extends Services {
public static void search(String callback, String city, String search) {
- if (city == null || search == null) {
+ if (city == null || search == null || city.trim().equals("") || search.trim().equals("")) {
response.status = 400;
renderJSON("{message: \"Parameters 'city' and 'search' are required.\"}");
}
Date start = new Date();
String referentialCode = getAccessControl().referential.code;
List<Way> ways = Way.search(referentialCode, city, search);
Logger.debug("%s ms", new Date().getTime() - start.getTime());
String jsonResult = Way.toJson(ways);
if (callback != null) {
response.contentType = "text/javascript";
renderText(callback + "(" + jsonResult + ")");
}
renderJSON(jsonResult);
}
}
| true | true | public static void search(String callback, String city, String search) {
if (city == null || search == null) {
response.status = 400;
renderJSON("{message: \"Parameters 'city' and 'search' are required.\"}");
}
Date start = new Date();
String referentialCode = getAccessControl().referential.code;
List<Way> ways = Way.search(referentialCode, city, search);
Logger.debug("%s ms", new Date().getTime() - start.getTime());
String jsonResult = Way.toJson(ways);
if (callback != null) {
response.contentType = "text/javascript";
renderText(callback + "(" + jsonResult + ")");
}
renderJSON(jsonResult);
}
| public static void search(String callback, String city, String search) {
if (city == null || search == null || city.trim().equals("") || search.trim().equals("")) {
response.status = 400;
renderJSON("{message: \"Parameters 'city' and 'search' are required.\"}");
}
Date start = new Date();
String referentialCode = getAccessControl().referential.code;
List<Way> ways = Way.search(referentialCode, city, search);
Logger.debug("%s ms", new Date().getTime() - start.getTime());
String jsonResult = Way.toJson(ways);
if (callback != null) {
response.contentType = "text/javascript";
renderText(callback + "(" + jsonResult + ")");
}
renderJSON(jsonResult);
}
|
diff --git a/src/main/java/dk/statsbiblioteket/medieplatform/bitrepository/ingester/Ingester.java b/src/main/java/dk/statsbiblioteket/medieplatform/bitrepository/ingester/Ingester.java
index e47d3cc..6ee39a2 100644
--- a/src/main/java/dk/statsbiblioteket/medieplatform/bitrepository/ingester/Ingester.java
+++ b/src/main/java/dk/statsbiblioteket/medieplatform/bitrepository/ingester/Ingester.java
@@ -1,130 +1,129 @@
package dk.statsbiblioteket.medieplatform.bitrepository.ingester;
import dk.statsbiblioteket.medieplatform.bitrepository.ingester.ClientExitCodes.ExitCodes;
import org.bitrepository.protocol.utils.LogbackConfigLoader;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* The main executable class for ingesting files in a configured bit repository.
*/
public class Ingester {
public static final int CONFIG_DIR_ARG_INDEX = 0;
public static final int FILE_LOCATION_ARG_INDEX = 1;
public static final int FILEID_ARG_INDEX = 2;
public static final int CHECKSUM_ARG_INDEX = 3;
public static final int FILESIZE_ARG_INDEX = 4;
private final static Logger log = LoggerFactory.getLogger(Ingester.class);
private Ingester() {}
public static void main(String[] args) {
int exitCode = -1;
try {
verifyInputParams(args);
} catch (ClientFailureException e) {
System.out.println(e.getMessage());
System.exit(e.getExitCode().getCode());
}
FilePutter putter = null;
System.err.println("Log dir: " + args[CONFIG_DIR_ARG_INDEX]);
try {
setupLogging(args[CONFIG_DIR_ARG_INDEX]);
log.info("Ingest of file requested: " + args);
- log.debug("#### Starting client");
+ log.debug("Starting client");
putter = new FilePutter(args[CONFIG_DIR_ARG_INDEX], args[FILEID_ARG_INDEX],
args[FILE_LOCATION_ARG_INDEX], args[CHECKSUM_ARG_INDEX],
Long.parseLong(args[FILESIZE_ARG_INDEX]));
putter.putFile();
JSONObject obj = new JSONObject();
try {
obj.put("UrlToFile", putter.getUrl());
System.out.println(obj.toString());
exitCode = ExitCodes.SUCCESS.getCode();
} catch (JSONException e) {
exitCode = ExitCodes.JSON_ERROR.getCode();
}
} catch (ClientFailureException e) {
log.error("File:" + args[FILEID_ARG_INDEX] + " Failed to ingest file: " + args[FILE_LOCATION_ARG_INDEX], e);
System.out.println(e.getMessage());
exitCode = e.getExitCode().getCode();
} catch (Exception e) {
log.error("Caught unexpected exception", e);
exitCode = 100;
} finally {
if(putter != null) {
- log.debug("#### Shutting down messagebus");
+ log.debug("Shutting down messagebus connection");
putter.shutdown();
- log.debug("#### Finished shutting down messagebus");
}
}
System.exit(exitCode);
}
/**
* Method to verify the input parameters
* Verifies the validity of:
* - Number of arguments
* - The existence and readability of the configuration directory
* - The ability to parse the file size parameter as a long
* - The length and content of the checksum parameter
* If validation fails error is printed to console and program is exited.
*/
private static void verifyInputParams(String[] args) throws ClientFailureException {
if(args.length != 5) {
throw new ClientFailureException("Unexpected number of arguments, got " + args.length + " but expected 5" +
"Expecting: ConfigDirPath FileUrl FileID FileChecksum FileSize",
ExitCodes.INPUT_PARAM_COUNT_ERROR);
}
File configDir = new File(args[CONFIG_DIR_ARG_INDEX]);
if(!configDir.exists()) {
throw new ClientFailureException("Config dir (parm " + CONFIG_DIR_ARG_INDEX + ": " +
configDir.getAbsolutePath() + ") doesn't exist!",
ExitCodes.CONFIG_DIR_ERROR);
}
if(!configDir.isDirectory()) {
throw new ClientFailureException("Config dir (parm " + CONFIG_DIR_ARG_INDEX + ": " + configDir +
") is not a directory!",
ExitCodes.CONFIG_DIR_ERROR);
}
if(!configDir.canRead()) {
throw new ClientFailureException("Config dir '" + configDir + "' cannot be read!",
ExitCodes.CONFIG_DIR_ERROR);
}
try {
Long.parseLong(args[FILESIZE_ARG_INDEX]);
} catch (Exception e) {
throw new ClientFailureException("Failed to parse filesize argument " + args[FILESIZE_ARG_INDEX] +
" as long.", ExitCodes.FILE_SIZE_ERROR);
}
String checksum = args[CHECKSUM_ARG_INDEX];
if((checksum.length() % 2) != 0) {
throw new ClientFailureException("Checksum argument " + checksum +
" does not contain an even number of characters.",
ExitCodes.CHECKSUM_ERROR);
}
if(!checksum.matches("^\\p{XDigit}*$")) {
throw new ClientFailureException("Checksum argument " + checksum +
" contains non hexadecimal value!", ExitCodes.CHECKSUM_ERROR);
}
}
private static void setupLogging(String configDir) throws ClientFailureException {
try {
new LogbackConfigLoader(configDir + "/logback.xml");
} catch (Exception e) {
throw new ClientFailureException("Logging setup failed!", ExitCodes.LOGGING_ERROR);
}
}
}
| false | true | public static void main(String[] args) {
int exitCode = -1;
try {
verifyInputParams(args);
} catch (ClientFailureException e) {
System.out.println(e.getMessage());
System.exit(e.getExitCode().getCode());
}
FilePutter putter = null;
System.err.println("Log dir: " + args[CONFIG_DIR_ARG_INDEX]);
try {
setupLogging(args[CONFIG_DIR_ARG_INDEX]);
log.info("Ingest of file requested: " + args);
log.debug("#### Starting client");
putter = new FilePutter(args[CONFIG_DIR_ARG_INDEX], args[FILEID_ARG_INDEX],
args[FILE_LOCATION_ARG_INDEX], args[CHECKSUM_ARG_INDEX],
Long.parseLong(args[FILESIZE_ARG_INDEX]));
putter.putFile();
JSONObject obj = new JSONObject();
try {
obj.put("UrlToFile", putter.getUrl());
System.out.println(obj.toString());
exitCode = ExitCodes.SUCCESS.getCode();
} catch (JSONException e) {
exitCode = ExitCodes.JSON_ERROR.getCode();
}
} catch (ClientFailureException e) {
log.error("File:" + args[FILEID_ARG_INDEX] + " Failed to ingest file: " + args[FILE_LOCATION_ARG_INDEX], e);
System.out.println(e.getMessage());
exitCode = e.getExitCode().getCode();
} catch (Exception e) {
log.error("Caught unexpected exception", e);
exitCode = 100;
} finally {
if(putter != null) {
log.debug("#### Shutting down messagebus");
putter.shutdown();
log.debug("#### Finished shutting down messagebus");
}
}
System.exit(exitCode);
}
| public static void main(String[] args) {
int exitCode = -1;
try {
verifyInputParams(args);
} catch (ClientFailureException e) {
System.out.println(e.getMessage());
System.exit(e.getExitCode().getCode());
}
FilePutter putter = null;
System.err.println("Log dir: " + args[CONFIG_DIR_ARG_INDEX]);
try {
setupLogging(args[CONFIG_DIR_ARG_INDEX]);
log.info("Ingest of file requested: " + args);
log.debug("Starting client");
putter = new FilePutter(args[CONFIG_DIR_ARG_INDEX], args[FILEID_ARG_INDEX],
args[FILE_LOCATION_ARG_INDEX], args[CHECKSUM_ARG_INDEX],
Long.parseLong(args[FILESIZE_ARG_INDEX]));
putter.putFile();
JSONObject obj = new JSONObject();
try {
obj.put("UrlToFile", putter.getUrl());
System.out.println(obj.toString());
exitCode = ExitCodes.SUCCESS.getCode();
} catch (JSONException e) {
exitCode = ExitCodes.JSON_ERROR.getCode();
}
} catch (ClientFailureException e) {
log.error("File:" + args[FILEID_ARG_INDEX] + " Failed to ingest file: " + args[FILE_LOCATION_ARG_INDEX], e);
System.out.println(e.getMessage());
exitCode = e.getExitCode().getCode();
} catch (Exception e) {
log.error("Caught unexpected exception", e);
exitCode = 100;
} finally {
if(putter != null) {
log.debug("Shutting down messagebus connection");
putter.shutdown();
}
}
System.exit(exitCode);
}
|
diff --git a/src/org/broad/igv/ui/PreferencesEditor.java b/src/org/broad/igv/ui/PreferencesEditor.java
index f06e6d21..815fd0ab 100644
--- a/src/org/broad/igv/ui/PreferencesEditor.java
+++ b/src/org/broad/igv/ui/PreferencesEditor.java
@@ -1,3019 +1,3018 @@
/*
* Copyright (c) 2007-2011 by The Broad Institute, Inc. and the Massachusetts Institute of
* Technology. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
package org.broad.igv.ui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import com.jidesoft.combobox.*;
import com.jidesoft.dialog.*;
import com.jidesoft.swing.*;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.ProbeToLocusMap;
import org.broad.igv.batch.CommandListener;
import org.broad.igv.ui.legend.LegendDialog;
import org.broad.igv.ui.util.FontChooser;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.ui.util.UIUtilities;
import org.broad.igv.util.ColorUtilities;
import org.broad.igv.util.IGVHttpUtils;
import org.broad.igv.util.Utilities;
import javax.swing.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.LayoutStyle;
/**
* @author jrobinso
*/
public class PreferencesEditor extends javax.swing.JDialog {
private boolean canceled = false;
Map<String, String> updatedPreferenceMap = new HashMap();
PreferenceManager prefMgr = PreferenceManager.getInstance();
boolean updateOverlays = false;
boolean inputValidated = true;
private static int lastSelectedIndex = 0;
boolean proxySettingsChanged;
private void backgroundColorPanelMouseClicked(MouseEvent e) {
final PreferenceManager prefMgr = PreferenceManager.getInstance();
Color backgroundColor = UIUtilities.showColorChooserDialog("Choose background color",
prefMgr.getAsColor(PreferenceManager.BACKGROUND_COLOR));
if (backgroundColor != null) {
prefMgr.put(PreferenceManager.BACKGROUND_COLOR, ColorUtilities.colorToString(backgroundColor));
IGV.getInstance().getMainPanel().setBackground(backgroundColor);
backgroundColorPanel.setBackground(backgroundColor);
}
}
private void resetBackgroundButtonActionPerformed(ActionEvent e) {
final PreferenceManager prefMgr = PreferenceManager.getInstance();
prefMgr.remove(PreferenceManager.BACKGROUND_COLOR);
Color backgroundColor = prefMgr.getAsColor(PreferenceManager.BACKGROUND_COLOR);
if (backgroundColor != null) {
prefMgr.put(PreferenceManager.BACKGROUND_COLOR, ColorUtilities.colorToString(backgroundColor));
IGV.getInstance().getMainPanel().setBackground(backgroundColor);
backgroundColorPanel.setBackground(backgroundColor);
}
}
public PreferencesEditor(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
initValues();
tabbedPane.setSelectedIndex(lastSelectedIndex);
setLocationRelativeTo(parent);
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
private void initComponents() {
tabbedPane = new JTabbedPane();
generalPanel = new JPanel();
jPanel10 = new JPanel();
missingDataExplanation = new JLabel();
showMissingDataCB = new JCheckBox();
combinePanelsCB = new JCheckBox();
showAttributesDisplayCheckBox = new JCheckBox();
searchZoomCB = new JCheckBox();
zoomToFeatureExplanation = new JLabel();
label4 = new JLabel();
geneListFlankingField = new JTextField();
zoomToFeatureExplanation2 = new JLabel();
label5 = new JLabel();
label6 = new JLabel();
seqResolutionThreshold = new JTextField();
label10 = new JLabel();
defaultFontField = new JTextField();
fontChangeButton = new JButton();
showRegionBoundariesCB = new JCheckBox();
label7 = new JLabel();
backgroundColorPanel = new JPanel();
resetBackgroundButton = new JButton();
tracksPanel = new JPanel();
jPanel6 = new JPanel();
jLabel5 = new JLabel();
defaultChartTrackHeightField = new JTextField();
trackNameAttributeLabel = new JLabel();
trackNameAttributeField = new JTextField();
missingDataExplanation2 = new JLabel();
jLabel8 = new JLabel();
defaultTrackHeightField = new JTextField();
missingDataExplanation4 = new JLabel();
missingDataExplanation5 = new JLabel();
missingDataExplanation3 = new JLabel();
expandCB = new JCheckBox();
normalizeCoverageCB = new JCheckBox();
missingDataExplanation8 = new JLabel();
expandIconCB = new JCheckBox();
overlaysPanel = new JPanel();
jPanel5 = new JPanel();
jLabel3 = new JLabel();
overlayAttributeTextField = new JTextField();
overlayTrackCB = new JCheckBox();
jLabel2 = new JLabel();
displayTracksCB = new JCheckBox();
jLabel4 = new JLabel();
colorOverlyCB = new JCheckBox();
chooseOverlayColorsButton = new JideButton();
chartPanel = new JPanel();
jPanel4 = new JPanel();
topBorderCB = new JCheckBox();
label1 = new Label();
chartDrawTrackNameCB = new JCheckBox();
bottomBorderCB = new JCheckBox();
jLabel7 = new JLabel();
colorBordersCB = new JCheckBox();
labelYAxisCB = new JCheckBox();
autoscaleCB = new JCheckBox();
jLabel9 = new JLabel();
showDatarangeCB = new JCheckBox();
alignmentPanel = new JPanel();
jPanel1 = new JPanel();
jPanel11 = new JPanel();
samMaxDepthField = new JTextField();
jLabel11 = new JLabel();
jLabel16 = new JLabel();
mappingQualityThresholdField = new JTextField();
jLabel14 = new JLabel();
jLabel13 = new JLabel();
jLabel15 = new JLabel();
samMaxWindowSizeField = new JTextField();
jLabel12 = new JLabel();
jLabel26 = new JLabel();
snpThresholdField = new JTextField();
jPanel12 = new JPanel();
samMinBaseQualityField = new JTextField();
samShadeMismatchedBaseCB = new JCheckBox();
samMaxBaseQualityField = new JTextField();
showCovTrackCB = new JCheckBox();
samFilterDuplicatesCB = new JCheckBox();
jLabel19 = new JLabel();
filterCB = new JCheckBox();
filterURL = new JTextField();
samFlagUnmappedPairCB = new JCheckBox();
filterFailedReadsCB = new JCheckBox();
label2 = new JLabel();
showSoftClippedCB = new JCheckBox();
showJunctionTrackCB = new JCheckBox();
panel2 = new JPanel();
isizeComputeCB = new JCheckBox();
jLabel17 = new JLabel();
insertSizeMinThresholdField = new JTextField();
jLabel20 = new JLabel();
insertSizeThresholdField = new JTextField();
jLabel30 = new JLabel();
jLabel18 = new JLabel();
insertSizeMinPercentileField = new JTextField();
insertSizeMaxPercentileField = new JTextField();
label8 = new JLabel();
label9 = new JLabel();
expressionPane = new JPanel();
jPanel8 = new JPanel();
expMapToGeneCB = new JRadioButton();
jLabel24 = new JLabel();
expMapToLociCB = new JRadioButton();
jLabel21 = new JLabel();
advancedPanel = new JPanel();
jPanel3 = new JPanel();
jPanel2 = new JPanel();
jLabel1 = new JLabel();
genomeServerURLTextField = new JTextField();
jLabel6 = new JLabel();
dataServerURLTextField = new JTextField();
editServerPropertiesCB = new JCheckBox();
jButton1 = new JButton();
clearGenomeCacheButton = new JButton();
genomeUpdateCB = new JCheckBox();
jPanel7 = new JPanel();
enablePortCB = new JCheckBox();
portField = new JTextField();
jLabel22 = new JLabel();
jPanel9 = new JPanel();
useByteRangeCB = new JCheckBox();
jLabel25 = new JLabel();
proxyPanel = new JPanel();
jPanel15 = new JPanel();
jPanel16 = new JPanel();
proxyUsernameField = new JTextField();
jLabel28 = new JLabel();
authenticateProxyCB = new JCheckBox();
jLabel29 = new JLabel();
proxyPasswordField = new JPasswordField();
jPanel17 = new JPanel();
proxyHostField = new JTextField();
proxyPortField = new JTextField();
jLabel27 = new JLabel();
jLabel23 = new JLabel();
useProxyCB = new JCheckBox();
label3 = new JLabel();
clearProxySettingsButton = new JButton();
okCancelButtonPanel = new ButtonPanel();
okButton = new JButton();
cancelButton = new JButton();
//======== this ========
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== tabbedPane ========
{
//======== generalPanel ========
{
generalPanel.setLayout(new BorderLayout());
//======== jPanel10 ========
{
jPanel10.setBorder(new BevelBorder(BevelBorder.RAISED));
jPanel10.setLayout(null);
//---- missingDataExplanation ----
missingDataExplanation.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation.setText("<html>Distinguish regions with zero values from regions with no data on plots <br>(e.g. bar charts). Regions with no data are indicated with a gray background.");
jPanel10.add(missingDataExplanation);
missingDataExplanation.setBounds(41, 35, 474, missingDataExplanation.getPreferredSize().height);
//---- showMissingDataCB ----
showMissingDataCB.setText("Distinguish Missing Data");
showMissingDataCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMissingDataCBActionPerformed(e);
}
});
jPanel10.add(showMissingDataCB);
showMissingDataCB.setBounds(new Rectangle(new Point(10, 6), showMissingDataCB.getPreferredSize()));
//---- combinePanelsCB ----
combinePanelsCB.setText("Combine Data and Feature Panels");
combinePanelsCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
combinePanelsCBActionPerformed(e);
}
});
jPanel10.add(combinePanelsCB);
combinePanelsCB.setBounds(new Rectangle(new Point(10, 95), combinePanelsCB.getPreferredSize()));
//---- showAttributesDisplayCheckBox ----
showAttributesDisplayCheckBox.setText("Show Attribute Display");
showAttributesDisplayCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAttributesDisplayCheckBoxActionPerformed(e);
}
});
jPanel10.add(showAttributesDisplayCheckBox);
showAttributesDisplayCheckBox.setBounds(new Rectangle(new Point(10, 130), showAttributesDisplayCheckBox.getPreferredSize()));
//---- searchZoomCB ----
searchZoomCB.setText("Zoom to features");
searchZoomCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchZoomCBActionPerformed(e);
}
});
jPanel10.add(searchZoomCB);
searchZoomCB.setBounds(new Rectangle(new Point(10, 205), searchZoomCB.getPreferredSize()));
//---- zoomToFeatureExplanation ----
zoomToFeatureExplanation.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
zoomToFeatureExplanation.setText("<html>This option controls the behavior of feature searchs. If true, the zoom level is changed as required to size the view to the feature size. If false the zoom level is unchanged.");
zoomToFeatureExplanation.setVerticalAlignment(SwingConstants.TOP);
jPanel10.add(zoomToFeatureExplanation);
zoomToFeatureExplanation.setBounds(50, 230, 644, 50);
//---- label4 ----
label4.setText("Feature flanking region (bp): ");
jPanel10.add(label4);
label4.setBounds(new Rectangle(new Point(15, 365), label4.getPreferredSize()));
//---- geneListFlankingField ----
geneListFlankingField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
geneListFlankingFieldFocusLost(e);
}
});
geneListFlankingField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
geneListFlankingFieldActionPerformed(e);
}
});
jPanel10.add(geneListFlankingField);
geneListFlankingField.setBounds(215, 360, 255, geneListFlankingField.getPreferredSize().height);
//---- zoomToFeatureExplanation2 ----
zoomToFeatureExplanation2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
zoomToFeatureExplanation2.setText("<html><i>Added before and after feature locus when zooming to a feature. Also used when defining panel extents in gene/loci list views.");
zoomToFeatureExplanation2.setVerticalAlignment(SwingConstants.TOP);
jPanel10.add(zoomToFeatureExplanation2);
zoomToFeatureExplanation2.setBounds(45, 395, 637, 50);
//---- label5 ----
label5.setText("<html><i>Resolution in base-pairs per pixel at which sequence track becomes visible. ");
label5.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
jPanel10.add(label5);
label5.setBounds(new Rectangle(new Point(50, 320), label5.getPreferredSize()));
//---- label6 ----
label6.setText("Sequence Resolution Threshold (bp/pixel):");
jPanel10.add(label6);
label6.setBounds(new Rectangle(new Point(15, 290), label6.getPreferredSize()));
//---- seqResolutionThreshold ----
seqResolutionThreshold.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
seqResolutionThresholdFocusLost(e);
}
});
seqResolutionThreshold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seqResolutionThresholdActionPerformed(e);
}
});
jPanel10.add(seqResolutionThreshold);
seqResolutionThreshold.setBounds(315, 285, 105, seqResolutionThreshold.getPreferredSize().height);
//---- label10 ----
label10.setText("Default font: ");
label10.setLabelFor(defaultFontField);
jPanel10.add(label10);
label10.setBounds(new Rectangle(new Point(15, 530), label10.getPreferredSize()));
//---- defaultFontField ----
defaultFontField.setEditable(false);
jPanel10.add(defaultFontField);
defaultFontField.setBounds(105, 525, 238, defaultFontField.getPreferredSize().height);
//---- fontChangeButton ----
fontChangeButton.setText("Change...");
fontChangeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontChangeButtonActionPerformed(e);
}
});
jPanel10.add(fontChangeButton);
fontChangeButton.setBounds(360, 525, 97, fontChangeButton.getPreferredSize().height);
//---- showRegionBoundariesCB ----
showRegionBoundariesCB.setText("Show Region Boundaries");
showRegionBoundariesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
- showAttributesDisplayCheckBoxActionPerformed(e);
showRegionBoundariesCBActionPerformed(e);
}
});
jPanel10.add(showRegionBoundariesCB);
showRegionBoundariesCB.setBounds(10, 165, 275, 23);
//---- label7 ----
label7.setText("Background color click to change): ");
jPanel10.add(label7);
label7.setBounds(15, 480, 235, label7.getPreferredSize().height);
//======== backgroundColorPanel ========
{
backgroundColorPanel.setPreferredSize(new Dimension(20, 20));
backgroundColorPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
backgroundColorPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
backgroundColorPanelMouseClicked(e);
}
});
backgroundColorPanel.setLayout(null);
}
jPanel10.add(backgroundColorPanel);
backgroundColorPanel.setBounds(255, 474, 30, 29);
//---- resetBackgroundButton ----
resetBackgroundButton.setText("Reset to default");
resetBackgroundButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetBackgroundButtonActionPerformed(e);
}
});
jPanel10.add(resetBackgroundButton);
resetBackgroundButton.setBounds(315, 474, 150, resetBackgroundButton.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel10.getComponentCount(); i++) {
Rectangle bounds = jPanel10.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel10.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel10.setMinimumSize(preferredSize);
jPanel10.setPreferredSize(preferredSize);
}
}
generalPanel.add(jPanel10, BorderLayout.CENTER);
}
tabbedPane.addTab("General", generalPanel);
//======== tracksPanel ========
{
tracksPanel.setLayout(null);
//======== jPanel6 ========
{
jPanel6.setLayout(null);
//---- jLabel5 ----
jLabel5.setText("Default Track Height, Charts (Pixels)");
jPanel6.add(jLabel5);
jLabel5.setBounds(new Rectangle(new Point(10, 12), jLabel5.getPreferredSize()));
//---- defaultChartTrackHeightField ----
defaultChartTrackHeightField.setText("40");
defaultChartTrackHeightField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultChartTrackHeightFieldActionPerformed(e);
}
});
defaultChartTrackHeightField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
defaultChartTrackHeightFieldFocusLost(e);
}
});
jPanel6.add(defaultChartTrackHeightField);
defaultChartTrackHeightField.setBounds(271, 6, 57, defaultChartTrackHeightField.getPreferredSize().height);
//---- trackNameAttributeLabel ----
trackNameAttributeLabel.setText("Track Name Attribute");
jPanel6.add(trackNameAttributeLabel);
trackNameAttributeLabel.setBounds(new Rectangle(new Point(10, 120), trackNameAttributeLabel.getPreferredSize()));
//---- trackNameAttributeField ----
trackNameAttributeField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trackNameAttributeFieldActionPerformed(e);
}
});
trackNameAttributeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
trackNameAttributeFieldFocusLost(e);
}
});
jPanel6.add(trackNameAttributeField);
trackNameAttributeField.setBounds(150, 115, 216, trackNameAttributeField.getPreferredSize().height);
//---- missingDataExplanation2 ----
missingDataExplanation2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation2.setText("<html>Name of an attribute to be used to label tracks. If provided tracks will be labeled with the corresponding attribute values from the sample information file");
missingDataExplanation2.setVerticalAlignment(SwingConstants.TOP);
jPanel6.add(missingDataExplanation2);
missingDataExplanation2.setBounds(40, 170, 578, 54);
//---- jLabel8 ----
jLabel8.setText("Default Track Height, Other (Pixels)");
jPanel6.add(jLabel8);
jLabel8.setBounds(new Rectangle(new Point(10, 45), jLabel8.getPreferredSize()));
//---- defaultTrackHeightField ----
defaultTrackHeightField.setText("15");
defaultTrackHeightField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultTrackHeightFieldActionPerformed(e);
}
});
defaultTrackHeightField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
defaultTrackHeightFieldFocusLost(e);
}
});
jPanel6.add(defaultTrackHeightField);
defaultTrackHeightField.setBounds(271, 39, 57, defaultTrackHeightField.getPreferredSize().height);
//---- missingDataExplanation4 ----
missingDataExplanation4.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation4.setText("<html>Default height of chart tracks (barcharts, scatterplots, etc)");
jPanel6.add(missingDataExplanation4);
missingDataExplanation4.setBounds(350, 5, 354, 25);
//---- missingDataExplanation5 ----
missingDataExplanation5.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation5.setText("<html>Default height of all other tracks");
jPanel6.add(missingDataExplanation5);
missingDataExplanation5.setBounds(350, 41, 1141, 25);
//---- missingDataExplanation3 ----
missingDataExplanation3.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation3.setText("<html><i> If selected feature tracks are expanded by default.");
jPanel6.add(missingDataExplanation3);
missingDataExplanation3.setBounds(new Rectangle(new Point(876, 318), missingDataExplanation3.getPreferredSize()));
//---- expandCB ----
expandCB.setText("Expand Feature Tracks");
expandCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandCBActionPerformed(e);
}
});
jPanel6.add(expandCB);
expandCB.setBounds(new Rectangle(new Point(6, 272), expandCB.getPreferredSize()));
//---- normalizeCoverageCB ----
normalizeCoverageCB.setText("Normalize Coverage Data");
normalizeCoverageCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalizeCoverageCBActionPerformed(e);
}
});
normalizeCoverageCB.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
normalizeCoverageCBFocusLost(e);
}
});
jPanel6.add(normalizeCoverageCB);
normalizeCoverageCB.setBounds(new Rectangle(new Point(6, 372), normalizeCoverageCB.getPreferredSize()));
//---- missingDataExplanation8 ----
missingDataExplanation8.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation8.setText("<html><i> Applies to coverage tracks computed with igvtools (.tdf files). If selected coverage values are scaled by (1,000,000 / totalCount), where totalCount is the total number of features or alignments.");
missingDataExplanation8.setVerticalAlignment(SwingConstants.TOP);
jPanel6.add(missingDataExplanation8);
missingDataExplanation8.setBounds(50, 413, 608, 52);
//---- expandIconCB ----
expandIconCB.setText("Show Expand Icon");
expandIconCB.setToolTipText("If checked displays an expand/collapse icon on feature tracks.");
expandIconCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandIconCBActionPerformed(e);
}
});
jPanel6.add(expandIconCB);
expandIconCB.setBounds(new Rectangle(new Point(6, 318), expandIconCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel6.getComponentCount(); i++) {
Rectangle bounds = jPanel6.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel6.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel6.setMinimumSize(preferredSize);
jPanel6.setPreferredSize(preferredSize);
}
}
tracksPanel.add(jPanel6);
jPanel6.setBounds(40, 20, 725, 480);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < tracksPanel.getComponentCount(); i++) {
Rectangle bounds = tracksPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = tracksPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
tracksPanel.setMinimumSize(preferredSize);
tracksPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Tracks", tracksPanel);
//======== overlaysPanel ========
{
//======== jPanel5 ========
{
jPanel5.setLayout(null);
//---- jLabel3 ----
jLabel3.setText("Sample attribute column:");
jPanel5.add(jLabel3);
jLabel3.setBounds(new Rectangle(new Point(65, 86), jLabel3.getPreferredSize()));
//---- overlayAttributeTextField ----
overlayAttributeTextField.setText("LINKING_ID");
overlayAttributeTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayAttributeTextFieldActionPerformed(e);
}
});
overlayAttributeTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
overlayAttributeTextFieldFocusLost(e);
}
});
overlayAttributeTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
overlayAttributeTextFieldKeyTyped(e);
}
});
jPanel5.add(overlayAttributeTextField);
overlayAttributeTextField.setBounds(229, 80, 228, overlayAttributeTextField.getPreferredSize().height);
//---- overlayTrackCB ----
overlayTrackCB.setSelected(true);
overlayTrackCB.setText("Overlay mutation tracks");
overlayTrackCB.setActionCommand("overlayTracksCB");
overlayTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayTrackCBActionPerformed(e);
}
});
jPanel5.add(overlayTrackCB);
overlayTrackCB.setBounds(new Rectangle(new Point(6, 51), overlayTrackCB.getPreferredSize()));
//---- jLabel2 ----
jLabel2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
jPanel5.add(jLabel2);
jLabel2.setBounds(new Rectangle(new Point(6, 6), jLabel2.getPreferredSize()));
//---- displayTracksCB ----
displayTracksCB.setText("Display mutation data as distinct tracks");
displayTracksCB.setActionCommand("displayTracksCB");
displayTracksCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayTracksCBActionPerformed(e);
}
});
jPanel5.add(displayTracksCB);
displayTracksCB.setBounds(new Rectangle(new Point(5, 230), displayTracksCB.getPreferredSize()));
//---- jLabel4 ----
jLabel4.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
jPanel5.add(jLabel4);
jLabel4.setBounds(new Rectangle(new Point(6, 12), jLabel4.getPreferredSize()));
//---- colorOverlyCB ----
colorOverlyCB.setText("Color code overlay");
colorOverlyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorOverlyCBActionPerformed(e);
}
});
jPanel5.add(colorOverlyCB);
colorOverlyCB.setBounds(new Rectangle(new Point(65, 114), colorOverlyCB.getPreferredSize()));
//---- chooseOverlayColorsButton ----
chooseOverlayColorsButton.setForeground(new Color(0, 0, 247));
chooseOverlayColorsButton.setText("Choose colors");
chooseOverlayColorsButton.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
chooseOverlayColorsButton.setVerticalAlignment(SwingConstants.BOTTOM);
chooseOverlayColorsButton.setVerticalTextPosition(SwingConstants.BOTTOM);
chooseOverlayColorsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooseOverlayColorsButtonActionPerformed(e);
}
});
jPanel5.add(chooseOverlayColorsButton);
chooseOverlayColorsButton.setBounds(new Rectangle(new Point(220, 116), chooseOverlayColorsButton.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel5.getComponentCount(); i++) {
Rectangle bounds = jPanel5.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel5.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel5.setMinimumSize(preferredSize);
jPanel5.setPreferredSize(preferredSize);
}
}
GroupLayout overlaysPanelLayout = new GroupLayout(overlaysPanel);
overlaysPanel.setLayout(overlaysPanelLayout);
overlaysPanelLayout.setHorizontalGroup(
overlaysPanelLayout.createParallelGroup()
.add(overlaysPanelLayout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel5, GroupLayout.PREFERRED_SIZE, 673, GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
);
overlaysPanelLayout.setVerticalGroup(
overlaysPanelLayout.createParallelGroup()
.add(overlaysPanelLayout.createSequentialGroup()
.add(55, 55, 55)
.add(jPanel5, GroupLayout.PREFERRED_SIZE, 394, GroupLayout.PREFERRED_SIZE)
.addContainerGap(117, Short.MAX_VALUE))
);
}
tabbedPane.addTab("Mutations", overlaysPanel);
//======== chartPanel ========
{
chartPanel.setLayout(null);
//======== jPanel4 ========
{
//---- topBorderCB ----
topBorderCB.setText("Draw Top Border");
topBorderCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
topBorderCBActionPerformed(e);
}
});
//---- label1 ----
label1.setFont(label1.getFont());
label1.setText("Default settings for barcharts and scatterplots:");
//---- chartDrawTrackNameCB ----
chartDrawTrackNameCB.setText("Draw Track Label");
chartDrawTrackNameCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chartDrawTrackNameCBActionPerformed(e);
}
});
//---- bottomBorderCB ----
bottomBorderCB.setText("Draw Bottom Border");
bottomBorderCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bottomBorderCBActionPerformed(e);
}
});
//---- jLabel7 ----
jLabel7.setText("<html><i>If selected charts are dynamically rescaled to the range of the data in view.");
//---- colorBordersCB ----
colorBordersCB.setText("Color Borders");
colorBordersCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorBordersCBActionPerformed(e);
}
});
//---- labelYAxisCB ----
labelYAxisCB.setText("Label Y Axis");
labelYAxisCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
labelYAxisCBActionPerformed(e);
}
});
//---- autoscaleCB ----
autoscaleCB.setText("Continuous Autoscale");
autoscaleCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
autoscaleCBActionPerformed(e);
}
});
//---- jLabel9 ----
jLabel9.setText("<html><i>Draw a label centered over the track provided<br>the track height is at least 25 pixels. ");
//---- showDatarangeCB ----
showDatarangeCB.setText("Show Data Range");
showDatarangeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showDatarangeCBActionPerformed(e);
}
});
showDatarangeCB.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
showDatarangeCBFocusLost(e);
}
});
GroupLayout jPanel4Layout = new GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(221, Short.MAX_VALUE)
.add(jLabel9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(84, 84, 84)))
.add(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel4Layout.createParallelGroup()
.add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(jPanel4Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createSequentialGroup()
.add(jPanel4Layout.createParallelGroup()
.add(autoscaleCB)
.add(showDatarangeCB))
.add(18, 18, 18)
.add(jLabel7, GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))
.add(jPanel4Layout.createSequentialGroup()
.add(jPanel4Layout.createParallelGroup()
.add(topBorderCB)
.add(colorBordersCB)
.add(bottomBorderCB)
.add(labelYAxisCB)
.add(chartDrawTrackNameCB))
.addPreferredGap(LayoutStyle.RELATED, 403, Short.MAX_VALUE)))))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createSequentialGroup()
.add(131, 131, 131)
.add(jLabel9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(181, Short.MAX_VALUE)))
.add(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(topBorderCB)
.addPreferredGap(LayoutStyle.RELATED)
.add(bottomBorderCB)
.add(7, 7, 7)
.add(colorBordersCB)
.add(18, 18, 18)
.add(chartDrawTrackNameCB)
.add(23, 23, 23)
.add(labelYAxisCB)
.add(18, 18, 18)
.add(jPanel4Layout.createParallelGroup(GroupLayout.BASELINE)
.add(autoscaleCB)
.add(jLabel7, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(showDatarangeCB)
.add(36, 36, 36))
);
}
chartPanel.add(jPanel4);
jPanel4.setBounds(20, 30, 590, 340);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < chartPanel.getComponentCount(); i++) {
Rectangle bounds = chartPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = chartPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
chartPanel.setMinimumSize(preferredSize);
chartPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Charts", chartPanel);
//======== alignmentPanel ========
{
alignmentPanel.setLayout(null);
//======== jPanel1 ========
{
jPanel1.setLayout(null);
//======== jPanel11 ========
{
jPanel11.setBorder(null);
jPanel11.setLayout(null);
//---- samMaxDepthField ----
samMaxDepthField.setText("jTextField1");
samMaxDepthField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxLevelFieldActionPerformed(e);
}
});
samMaxDepthField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxLevelFieldFocusLost(e);
}
});
jPanel11.add(samMaxDepthField);
samMaxDepthField.setBounds(new Rectangle(new Point(206, 40), samMaxDepthField.getPreferredSize()));
//---- jLabel11 ----
jLabel11.setText("Visibility range threshold (kb)");
jPanel11.add(jLabel11);
jLabel11.setBounds(new Rectangle(new Point(6, 12), jLabel11.getPreferredSize()));
//---- jLabel16 ----
jLabel16.setText("<html><i>Reads with qualities below the threshold are not shown.");
jPanel11.add(jLabel16);
jLabel16.setBounds(new Rectangle(new Point(296, 80), jLabel16.getPreferredSize()));
//---- mappingQualityThresholdField ----
mappingQualityThresholdField.setText("0");
mappingQualityThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mappingQualityThresholdFieldActionPerformed(e);
}
});
mappingQualityThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
mappingQualityThresholdFieldFocusLost(e);
}
});
jPanel11.add(mappingQualityThresholdField);
mappingQualityThresholdField.setBounds(206, 74, 84, mappingQualityThresholdField.getPreferredSize().height);
//---- jLabel14 ----
jLabel14.setText("<html><i>Maximum read depth to load (approximate).");
jPanel11.add(jLabel14);
jLabel14.setBounds(296, 39, 390, 30);
//---- jLabel13 ----
jLabel13.setText("Maximum read depth:");
jPanel11.add(jLabel13);
jLabel13.setBounds(new Rectangle(new Point(6, 46), jLabel13.getPreferredSize()));
//---- jLabel15 ----
jLabel15.setText("Mapping quality threshold:");
jPanel11.add(jLabel15);
jLabel15.setBounds(new Rectangle(new Point(6, 80), jLabel15.getPreferredSize()));
//---- samMaxWindowSizeField ----
samMaxWindowSizeField.setText("jTextField1");
samMaxWindowSizeField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxWindowSizeFieldActionPerformed(e);
}
});
samMaxWindowSizeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxWindowSizeFieldFocusLost(e);
}
});
jPanel11.add(samMaxWindowSizeField);
samMaxWindowSizeField.setBounds(new Rectangle(new Point(206, 6), samMaxWindowSizeField.getPreferredSize()));
//---- jLabel12 ----
jLabel12.setText("<html><i>Nominal window size at which alignments become visible");
jPanel11.add(jLabel12);
jLabel12.setBounds(new Rectangle(new Point(296, 12), jLabel12.getPreferredSize()));
//---- jLabel26 ----
jLabel26.setText("Coverage allele-freq threshold");
jPanel11.add(jLabel26);
jLabel26.setBounds(6, 114, 200, jLabel26.getPreferredSize().height);
//---- snpThresholdField ----
snpThresholdField.setText("0");
snpThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snpThresholdFieldActionPerformed(e);
}
});
snpThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
snpThresholdFieldFocusLost(e);
}
});
jPanel11.add(snpThresholdField);
snpThresholdField.setBounds(206, 108, 84, snpThresholdField.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel11.getComponentCount(); i++) {
Rectangle bounds = jPanel11.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel11.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel11.setMinimumSize(preferredSize);
jPanel11.setPreferredSize(preferredSize);
}
}
jPanel1.add(jPanel11);
jPanel11.setBounds(5, 10, 755, 150);
//======== jPanel12 ========
{
jPanel12.setBorder(null);
jPanel12.setLayout(null);
//---- samMinBaseQualityField ----
samMinBaseQualityField.setText("0");
samMinBaseQualityField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMinBaseQualityFieldActionPerformed(e);
}
});
samMinBaseQualityField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMinBaseQualityFieldFocusLost(e);
}
});
jPanel12.add(samMinBaseQualityField);
samMinBaseQualityField.setBounds(380, 105, 50, samMinBaseQualityField.getPreferredSize().height);
//---- samShadeMismatchedBaseCB ----
samShadeMismatchedBaseCB.setText("Shade mismatched bases by quality. ");
samShadeMismatchedBaseCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samShadeMismatchedBaseCBActionPerformed(e);
}
});
jPanel12.add(samShadeMismatchedBaseCB);
samShadeMismatchedBaseCB.setBounds(6, 109, 264, samShadeMismatchedBaseCB.getPreferredSize().height);
//---- samMaxBaseQualityField ----
samMaxBaseQualityField.setText("0");
samMaxBaseQualityField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxBaseQualityFieldActionPerformed(e);
}
});
samMaxBaseQualityField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxBaseQualityFieldFocusLost(e);
}
});
jPanel12.add(samMaxBaseQualityField);
samMaxBaseQualityField.setBounds(505, 105, 50, samMaxBaseQualityField.getPreferredSize().height);
//---- showCovTrackCB ----
showCovTrackCB.setText("Show coverage track");
showCovTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCovTrackCBActionPerformed(e);
}
});
jPanel12.add(showCovTrackCB);
showCovTrackCB.setBounds(375, 10, 270, showCovTrackCB.getPreferredSize().height);
//---- samFilterDuplicatesCB ----
samFilterDuplicatesCB.setText("Filter duplicate reads");
samFilterDuplicatesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samShowDuplicatesCBActionPerformed(e);
}
});
jPanel12.add(samFilterDuplicatesCB);
samFilterDuplicatesCB.setBounds(6, 10, 290, samFilterDuplicatesCB.getPreferredSize().height);
//---- jLabel19 ----
jLabel19.setText("Min: ");
jPanel12.add(jLabel19);
jLabel19.setBounds(new Rectangle(new Point(340, 110), jLabel19.getPreferredSize()));
//---- filterCB ----
filterCB.setText("Filter alignments by read group");
filterCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterCBActionPerformed(e);
}
});
jPanel12.add(filterCB);
filterCB.setBounds(6, 142, 244, filterCB.getPreferredSize().height);
//---- filterURL ----
filterURL.setText("URL or path to filter file");
filterURL.setEnabled(false);
filterURL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterURLActionPerformed(e);
}
});
filterURL.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
filterURLFocusLost(e);
}
});
jPanel12.add(filterURL);
filterURL.setBounds(275, 140, 440, filterURL.getPreferredSize().height);
//---- samFlagUnmappedPairCB ----
samFlagUnmappedPairCB.setText("Flag unmapped pairs");
samFlagUnmappedPairCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samFlagUnmappedPairCBActionPerformed(e);
}
});
jPanel12.add(samFlagUnmappedPairCB);
samFlagUnmappedPairCB.setBounds(6, 76, 310, samFlagUnmappedPairCB.getPreferredSize().height);
//---- filterFailedReadsCB ----
filterFailedReadsCB.setText("Filter vendor failed reads");
filterFailedReadsCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterVendorFailedReadsCBActionPerformed(e);
}
});
jPanel12.add(filterFailedReadsCB);
filterFailedReadsCB.setBounds(new Rectangle(new Point(6, 43), filterFailedReadsCB.getPreferredSize()));
//---- label2 ----
label2.setText("Max:");
jPanel12.add(label2);
label2.setBounds(new Rectangle(new Point(455, 110), label2.getPreferredSize()));
//---- showSoftClippedCB ----
showSoftClippedCB.setText("Show soft-clipped bases");
showSoftClippedCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showSoftClippedCBActionPerformed(e);
}
});
jPanel12.add(showSoftClippedCB);
showSoftClippedCB.setBounds(new Rectangle(new Point(375, 76), showSoftClippedCB.getPreferredSize()));
//---- showJunctionTrackCB ----
showJunctionTrackCB.setText("Show splice junction track");
showJunctionTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showJunctionTrackCBActionPerformed(e);
}
});
jPanel12.add(showJunctionTrackCB);
showJunctionTrackCB.setBounds(new Rectangle(new Point(375, 43), showJunctionTrackCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel12.getComponentCount(); i++) {
Rectangle bounds = jPanel12.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel12.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel12.setMinimumSize(preferredSize);
jPanel12.setPreferredSize(preferredSize);
}
}
jPanel1.add(jPanel12);
jPanel12.setBounds(5, 145, 755, 175);
//======== panel2 ========
{
panel2.setBorder(new TitledBorder("Insert Size Options"));
panel2.setLayout(null);
//---- isizeComputeCB ----
isizeComputeCB.setText("Compute");
isizeComputeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isizeComputeCBActionPerformed(e);
isizeComputeCBActionPerformed(e);
isizeComputeCBActionPerformed(e);
}
});
panel2.add(isizeComputeCB);
isizeComputeCB.setBounds(new Rectangle(new Point(360, 76), isizeComputeCB.getPreferredSize()));
//---- jLabel17 ----
jLabel17.setText("Maximum (bp):");
panel2.add(jLabel17);
jLabel17.setBounds(100, 110, 110, jLabel17.getPreferredSize().height);
//---- insertSizeMinThresholdField ----
insertSizeMinThresholdField.setText("0");
insertSizeMinThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
}
});
insertSizeMinThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMinThresholdFieldFocusLost(e);
}
});
panel2.add(insertSizeMinThresholdField);
insertSizeMinThresholdField.setBounds(220, 75, 84, 28);
//---- jLabel20 ----
jLabel20.setText("Minimum (bp):");
panel2.add(jLabel20);
jLabel20.setBounds(100, 80, 110, 16);
//---- insertSizeThresholdField ----
insertSizeThresholdField.setText("0");
insertSizeThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeThresholdFieldActionPerformed(e);
}
});
insertSizeThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
}
});
panel2.add(insertSizeThresholdField);
insertSizeThresholdField.setBounds(220, 105, 84, insertSizeThresholdField.getPreferredSize().height);
//---- jLabel30 ----
jLabel30.setText("Minimum (percentile):");
panel2.add(jLabel30);
jLabel30.setBounds(460, 80, 155, 16);
//---- jLabel18 ----
jLabel18.setText("Maximum (percentile):");
panel2.add(jLabel18);
jLabel18.setBounds(460, 110, 155, 16);
//---- insertSizeMinPercentileField ----
insertSizeMinPercentileField.setText("0");
insertSizeMinPercentileField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinPercentileFieldActionPerformed(e);
}
});
insertSizeMinPercentileField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMinThresholdFieldFocusLost(e);
insertSizeMinPercentileFieldFocusLost(e);
}
});
panel2.add(insertSizeMinPercentileField);
insertSizeMinPercentileField.setBounds(625, 75, 84, 28);
//---- insertSizeMaxPercentileField ----
insertSizeMaxPercentileField.setText("0");
insertSizeMaxPercentileField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeThresholdFieldActionPerformed(e);
insertSizeMaxPercentileFieldActionPerformed(e);
}
});
insertSizeMaxPercentileField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMaxPercentileFieldFocusLost(e);
}
});
panel2.add(insertSizeMaxPercentileField);
insertSizeMaxPercentileField.setBounds(625, 105, 84, 28);
//---- label8 ----
label8.setText("<html><i>These options control the color coding of paired alignments by inferred insert size. Base pair values set default values. If \"compute\" is selected values are computed from the actual size distribution of each library.");
panel2.add(label8);
label8.setBounds(5, 15, 735, 55);
//---- label9 ----
label9.setText("Defaults ");
panel2.add(label9);
label9.setBounds(new Rectangle(new Point(15, 80), label9.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel2.getComponentCount(); i++) {
Rectangle bounds = panel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel2.setMinimumSize(preferredSize);
panel2.setPreferredSize(preferredSize);
}
}
jPanel1.add(panel2);
panel2.setBounds(5, 350, 755, 145);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel1.getComponentCount(); i++) {
Rectangle bounds = jPanel1.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel1.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel1.setMinimumSize(preferredSize);
jPanel1.setPreferredSize(preferredSize);
}
}
alignmentPanel.add(jPanel1);
jPanel1.setBounds(0, 0, 760, 510);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < alignmentPanel.getComponentCount(); i++) {
Rectangle bounds = alignmentPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = alignmentPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
alignmentPanel.setMinimumSize(preferredSize);
alignmentPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Alignments", alignmentPanel);
//======== expressionPane ========
{
expressionPane.setLayout(null);
//======== jPanel8 ========
{
//---- expMapToGeneCB ----
expMapToGeneCB.setText("Map probes to genes");
expMapToGeneCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expMapToGeneCBActionPerformed(e);
}
});
//---- jLabel24 ----
jLabel24.setText("Expression probe mapping options: ");
//---- expMapToLociCB ----
expMapToLociCB.setText("<html>Map probes to target loci");
expMapToLociCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expMapToLociCBActionPerformed(e);
}
});
//---- jLabel21 ----
jLabel21.setText("<html><i>Note: Changes will not affect currently loaded datasets.");
GroupLayout jPanel8Layout = new GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(45, 45, 45)
.add(jPanel8Layout.createParallelGroup()
.add(expMapToLociCB, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(expMapToGeneCB)))
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(24, 24, 24)
.add(jLabel21, GroupLayout.PREFERRED_SIZE, 497, GroupLayout.PREFERRED_SIZE))
.add(jLabel24))))
.addContainerGap(193, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel24)
.addPreferredGap(LayoutStyle.RELATED)
.add(jLabel21, GroupLayout.PREFERRED_SIZE, 44, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(expMapToLociCB, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(14, 14, 14)
.add(expMapToGeneCB)
.addContainerGap(172, Short.MAX_VALUE))
);
}
expressionPane.add(jPanel8);
jPanel8.setBounds(10, 30, 720, 310);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < expressionPane.getComponentCount(); i++) {
Rectangle bounds = expressionPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = expressionPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
expressionPane.setMinimumSize(preferredSize);
expressionPane.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Probes", expressionPane);
//======== advancedPanel ========
{
advancedPanel.setBorder(new EmptyBorder(1, 10, 1, 10));
advancedPanel.setLayout(null);
//======== jPanel3 ========
{
//======== jPanel2 ========
{
jPanel2.setLayout(null);
//---- jLabel1 ----
jLabel1.setText("Genome Server URL");
jPanel2.add(jLabel1);
jLabel1.setBounds(new Rectangle(new Point(35, 47), jLabel1.getPreferredSize()));
//---- genomeServerURLTextField ----
genomeServerURLTextField.setText("jTextField1");
genomeServerURLTextField.setEnabled(false);
genomeServerURLTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
genomeServerURLTextFieldActionPerformed(e);
}
});
genomeServerURLTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
genomeServerURLTextFieldFocusLost(e);
}
});
jPanel2.add(genomeServerURLTextField);
genomeServerURLTextField.setBounds(191, 41, 494, genomeServerURLTextField.getPreferredSize().height);
//---- jLabel6 ----
jLabel6.setText("Data Registry URL");
jPanel2.add(jLabel6);
jLabel6.setBounds(new Rectangle(new Point(35, 81), jLabel6.getPreferredSize()));
//---- dataServerURLTextField ----
dataServerURLTextField.setEnabled(false);
dataServerURLTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dataServerURLTextFieldActionPerformed(e);
}
});
dataServerURLTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
dataServerURLTextFieldFocusLost(e);
}
});
jPanel2.add(dataServerURLTextField);
dataServerURLTextField.setBounds(191, 75, 494, dataServerURLTextField.getPreferredSize().height);
//---- editServerPropertiesCB ----
editServerPropertiesCB.setText("Edit server properties");
editServerPropertiesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editServerPropertiesCBActionPerformed(e);
}
});
jPanel2.add(editServerPropertiesCB);
editServerPropertiesCB.setBounds(new Rectangle(new Point(6, 7), editServerPropertiesCB.getPreferredSize()));
//---- jButton1 ----
jButton1.setText("Reset to Defaults");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});
jPanel2.add(jButton1);
jButton1.setBounds(new Rectangle(new Point(190, 6), jButton1.getPreferredSize()));
//---- clearGenomeCacheButton ----
clearGenomeCacheButton.setText("Clear Genome Cache");
clearGenomeCacheButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearGenomeCacheButtonActionPerformed(e);
}
});
jPanel2.add(clearGenomeCacheButton);
clearGenomeCacheButton.setBounds(new Rectangle(new Point(6, 155), clearGenomeCacheButton.getPreferredSize()));
//---- genomeUpdateCB ----
genomeUpdateCB.setText("<html>Automatically check for updated genomes. <i>Most users should leave this checked.");
genomeUpdateCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
genomeUpdateCBActionPerformed(e);
}
});
jPanel2.add(genomeUpdateCB);
genomeUpdateCB.setBounds(new Rectangle(new Point(14, 121), genomeUpdateCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel2.getComponentCount(); i++) {
Rectangle bounds = jPanel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel2.setMinimumSize(preferredSize);
jPanel2.setPreferredSize(preferredSize);
}
}
//======== jPanel7 ========
{
//---- enablePortCB ----
enablePortCB.setText("Enable port");
enablePortCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enablePortCBActionPerformed(e);
}
});
//---- portField ----
portField.setText("60151");
portField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
portFieldActionPerformed(e);
}
});
portField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
portFieldFocusLost(e);
}
});
//---- jLabel22 ----
jLabel22.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
jLabel22.setText("Enable port to send commands and http requests to IGV. ");
GroupLayout jPanel7Layout = new GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.add(jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.add(enablePortCB)
.add(39, 39, 39)
.add(portField, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE))
.add(jPanel7Layout.createSequentialGroup()
.add(48, 48, 48)
.add(jLabel22)))
.addContainerGap(330, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel7Layout.createParallelGroup(GroupLayout.CENTER)
.add(enablePortCB)
.add(portField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(jLabel22)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}
GroupLayout jPanel3Layout = new GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup()
.add(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel3Layout.createParallelGroup()
.add(jPanel7, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup()
.add(jPanel3Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel7, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED, 36, Short.MAX_VALUE)
.add(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
);
}
advancedPanel.add(jPanel3);
jPanel3.setBounds(10, 0, 750, 330);
//======== jPanel9 ========
{
//---- useByteRangeCB ----
useByteRangeCB.setText("Use http byte-range requests");
useByteRangeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
useByteRangeCBActionPerformed(e);
}
});
//---- jLabel25 ----
jLabel25.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
jLabel25.setText("<html>This option applies to certain \"Load from Server...\" tracks hosted at the Broad. Disable this option if you are unable to load the phastCons conservation track under the hg18 annotations.");
GroupLayout jPanel9Layout = new GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup()
.add(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel9Layout.createParallelGroup()
.add(jPanel9Layout.createSequentialGroup()
.add(38, 38, 38)
.add(jLabel25, GroupLayout.PREFERRED_SIZE, 601, GroupLayout.PREFERRED_SIZE))
.add(useByteRangeCB))
.addContainerGap(65, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel9Layout.createSequentialGroup()
.add(59, 59, 59)
.add(useByteRangeCB, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
- .add(jLabel25)
+ .add(jLabel25, GroupLayout.DEFAULT_SIZE, 16, Short.MAX_VALUE)
.addContainerGap())
);
}
advancedPanel.add(jPanel9);
jPanel9.setBounds(30, 340, 710, 120);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < advancedPanel.getComponentCount(); i++) {
Rectangle bounds = advancedPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = advancedPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
advancedPanel.setMinimumSize(preferredSize);
advancedPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Advanced", advancedPanel);
//======== proxyPanel ========
{
proxyPanel.setLayout(new BoxLayout(proxyPanel, BoxLayout.X_AXIS));
//======== jPanel15 ========
{
//======== jPanel16 ========
{
//---- proxyUsernameField ----
proxyUsernameField.setText("jTextField1");
proxyUsernameField.setEnabled(false);
proxyUsernameField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyUsernameFieldActionPerformed(e);
}
});
proxyUsernameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyUsernameFieldFocusLost(e);
}
});
//---- jLabel28 ----
jLabel28.setText("Username");
//---- authenticateProxyCB ----
authenticateProxyCB.setText("Authentication required");
authenticateProxyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
authenticateProxyCBActionPerformed(e);
}
});
//---- jLabel29 ----
jLabel29.setText("Password");
//---- proxyPasswordField ----
proxyPasswordField.setText("jPasswordField1");
proxyPasswordField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyPasswordFieldFocusLost(e);
}
});
GroupLayout jPanel16Layout = new GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel16Layout.createParallelGroup()
.add(jLabel28)
.add(jLabel29))
.add(37, 37, 37)
.add(jPanel16Layout.createParallelGroup(GroupLayout.LEADING, false)
.add(proxyPasswordField)
.add(proxyUsernameField, GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)))
.add(jPanel16Layout.createSequentialGroup()
.addContainerGap()
.add(authenticateProxyCB)))
.addContainerGap(381, Short.MAX_VALUE))
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(17, 17, 17)
.add(authenticateProxyCB)
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel16Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel28)
.add(proxyUsernameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel16Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel29)
.add(proxyPasswordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(70, Short.MAX_VALUE))
);
}
//======== jPanel17 ========
{
//---- proxyHostField ----
proxyHostField.setText("jTextField1");
proxyHostField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyHostFieldActionPerformed(e);
}
});
proxyHostField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyHostFieldFocusLost(e);
}
});
//---- proxyPortField ----
proxyPortField.setText("jTextField1");
proxyPortField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyPortFieldActionPerformed(e);
}
});
proxyPortField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyPortFieldFocusLost(e);
}
});
//---- jLabel27 ----
jLabel27.setText("Proxy port");
//---- jLabel23 ----
jLabel23.setText("Proxy host");
//---- useProxyCB ----
useProxyCB.setText("Use proxy");
useProxyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
useProxyCBActionPerformed(e);
}
});
GroupLayout jPanel17Layout = new GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup()
.add(jPanel17Layout.createSequentialGroup()
.add(jPanel17Layout.createParallelGroup()
.add(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel17Layout.createParallelGroup()
.add(jLabel27)
.add(jLabel23))
.add(28, 28, 28)
.add(jPanel17Layout.createParallelGroup()
.add(proxyPortField, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
.add(proxyHostField, GroupLayout.PREFERRED_SIZE, 485, GroupLayout.PREFERRED_SIZE)))
.add(jPanel17Layout.createSequentialGroup()
.add(9, 9, 9)
.add(useProxyCB)))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel17Layout.createSequentialGroup()
.addContainerGap(29, Short.MAX_VALUE)
.add(useProxyCB)
.add(18, 18, 18)
.add(jPanel17Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel23)
.add(proxyHostField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel17Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel27)
.add(proxyPortField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
}
//---- label3 ----
label3.setText("<html>Note: do not use these settings unless you receive error or warning messages about server connections. On most systems the correct settings will be automatically copied from your web browser.");
//---- clearProxySettingsButton ----
clearProxySettingsButton.setText("Clear All");
clearProxySettingsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearProxySettingsButtonActionPerformed(e);
}
});
GroupLayout jPanel15Layout = new GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.add(jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.add(22, 22, 22)
.add(label3, GroupLayout.PREFERRED_SIZE, 630, GroupLayout.PREFERRED_SIZE))
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15Layout.createParallelGroup()
.add(jPanel16, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel17, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(clearProxySettingsButton)))
.addContainerGap())
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(label3, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel17, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(jPanel16, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(clearProxySettingsButton)
.addContainerGap(110, Short.MAX_VALUE))
);
}
proxyPanel.add(jPanel15);
}
tabbedPane.addTab("Proxy", proxyPanel);
}
contentPane.add(tabbedPane, BorderLayout.CENTER);
//======== okCancelButtonPanel ========
{
//---- okButton ----
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonActionPerformed(e);
}
});
okCancelButtonPanel.add(okButton);
//---- cancelButton ----
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButtonActionPerformed(e);
}
});
okCancelButtonPanel.add(cancelButton);
}
contentPane.add(okCancelButtonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(getOwner());
//---- buttonGroup1 ----
ButtonGroup buttonGroup1 = new ButtonGroup();
buttonGroup1.add(expMapToGeneCB);
buttonGroup1.add(expMapToLociCB);
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
canceled = true;
setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
if (inputValidated) {
checkForProbeChanges();
lastSelectedIndex = tabbedPane.getSelectedIndex();
// Store the changed preferences
prefMgr.putAll(updatedPreferenceMap);
if (updatedPreferenceMap.containsKey(PreferenceManager.PORT_ENABLED) ||
updatedPreferenceMap.containsKey(PreferenceManager.PORT_NUMBER)) {
CommandListener.halt();
if (enablePortCB.isSelected()) {
int port = Integer.parseInt(updatedPreferenceMap.get(PreferenceManager.PORT_NUMBER));
CommandListener.start(port);
}
}
checkForSAMChanges();
// Overlays
if (updateOverlays) {
IGV.getInstance().getTrackManager().resetOverlayTracks();
}
// Proxies
if (proxySettingsChanged) {
IGVHttpUtils.updateProxySettings();
}
updatedPreferenceMap.clear();
IGV.getInstance().repaint();
setVisible(false);
} else {
resetValidation();
}
}
private void fontChangeButtonActionPerformed(ActionEvent e) {
Font defaultFont = FontManager.getDefaultFont();
FontChooser chooser = new FontChooser(this, defaultFont);
chooser.setModal(true);
chooser.setVisible(true);
if (!chooser.isCanceled()) {
Font font = chooser.getSelectedFont();
if (font != null) {
prefMgr.put(PreferenceManager.DEFAULT_FONT_FAMILY, font.getFamily());
prefMgr.put(PreferenceManager.DEFAULT_FONT_SIZE, String.valueOf(font.getSize()));
int attrs = Font.PLAIN;
if (font.isBold()) attrs = Font.BOLD;
if (font.isItalic()) attrs |= Font.ITALIC;
prefMgr.put(PreferenceManager.DEFAULT_FONT_ATTRIBUTE, String.valueOf(attrs));
FontManager.updateDefaultFont();
updateFontField();
IGV.getInstance().repaint();
}
}
}
private void expMapToLociCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expMapToLociCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.PROBE_MAPPING_KEY, String.valueOf(expMapToGeneCB.isSelected()));
}
private void clearGenomeCacheButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearGenomeCacheButtonActionPerformed
IGV.getInstance().getGenomeManager().clearGenomeCache();
JOptionPane.showMessageDialog(this, "<html>Cached genomes have been removed.");
}
private void editServerPropertiesCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editServerPropertiesCBActionPerformed
boolean edit = editServerPropertiesCB.isSelected();
dataServerURLTextField.setEnabled(edit);
genomeServerURLTextField.setEnabled(edit);
}
private void dataServerURLTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dataServerURLTextFieldFocusLost
String attributeName = dataServerURLTextField.getText().trim();
updatedPreferenceMap.put(PreferenceManager.DATA_SERVER_URL_KEY, attributeName);
}
private void dataServerURLTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataServerURLTextFieldActionPerformed
String attributeName = dataServerURLTextField.getText().trim();
updatedPreferenceMap.put(PreferenceManager.DATA_SERVER_URL_KEY, attributeName);
}
private void genomeServerURLTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_genomeServerURLTextFieldFocusLost
String attributeName = genomeServerURLTextField.getText().trim();
updatedPreferenceMap.put(PreferenceManager.GENOMES_SERVER_URL, attributeName);
}
private void genomeServerURLTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_genomeServerURLTextFieldActionPerformed
String attributeName = genomeServerURLTextField.getText().trim();
updatedPreferenceMap.put(PreferenceManager.GENOMES_SERVER_URL, attributeName);
}
private void expandIconCBActionPerformed(ActionEvent e) {
updatedPreferenceMap.put(PreferenceManager.SHOW_EXPAND_ICON, String.valueOf(expandIconCB.isSelected()));
}
private void normalizeCoverageCBFocusLost(FocusEvent e) {
// TODO add your code here
}
private void insertSizeThresholdFieldFocusLost(java.awt.event.FocusEvent evt) {
this.insertSizeThresholdFieldActionPerformed(null);
}
private void insertSizeThresholdFieldActionPerformed(java.awt.event.ActionEvent evt) {
String insertThreshold = insertSizeThresholdField.getText().trim();
try {
Integer.parseInt(insertThreshold);
updatedPreferenceMap.put(PreferenceManager.SAM_MAX_INSERT_SIZE_THRESHOLD, insertThreshold);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("BlastMapping quality threshold must be an integer.");
}
}
private void insertSizeMinThresholdFieldFocusLost(FocusEvent e) {
insertSizeMinThresholdFieldActionPerformed(null);
}
private void insertSizeMinThresholdFieldActionPerformed(ActionEvent e) {
String insertThreshold = insertSizeMinThresholdField.getText().trim();
try {
Integer.parseInt(insertThreshold);
updatedPreferenceMap.put(PreferenceManager.SAM_MIN_INSERT_SIZE_THRESHOLD, insertThreshold);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("BlastMapping quality threshold must be an integer.");
}
}
private void mappingQualityThresholdFieldFocusLost(java.awt.event.FocusEvent evt) {
mappingQualityThresholdFieldActionPerformed(null);
}//GEN-LAST:event_mappingQualityThresholdFieldFocusLost
private void mappingQualityThresholdFieldActionPerformed(java.awt.event.ActionEvent evt) {
String qualityThreshold = mappingQualityThresholdField.getText().trim();
try {
Integer.parseInt(qualityThreshold);
updatedPreferenceMap.put(PreferenceManager.SAM_QUALITY_THRESHOLD, qualityThreshold);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage(
"BlastMapping quality threshold must be an integer.");
}
}
private void samMaxLevelFieldFocusLost(java.awt.event.FocusEvent evt) {
samMaxLevelFieldActionPerformed(null);
}
private void samMaxLevelFieldActionPerformed(java.awt.event.ActionEvent evt) {
String maxLevelString = samMaxDepthField.getText().trim();
try {
Integer.parseInt(maxLevelString);
updatedPreferenceMap.put(PreferenceManager.SAM_MAX_LEVELS, maxLevelString);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Maximum read count must be an integer.");
}
}//GEN-LAST:event_samMaxLevelFieldActionPerformed
private void samShadeMismatchedBaseCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(
PreferenceManager.SAM_SHADE_BASE_QUALITY,
String.valueOf(samShadeMismatchedBaseCB.isSelected()));
samMinBaseQualityField.setEnabled(samShadeMismatchedBaseCB.isSelected());
samMaxBaseQualityField.setEnabled(samShadeMismatchedBaseCB.isSelected());
}
private void genomeUpdateCBActionPerformed(ActionEvent e) {
updatedPreferenceMap.put(
PreferenceManager.AUTO_UPDATE_GENOMES,
String.valueOf(this.genomeUpdateCB.isSelected()));
}
private void samFlagUnmappedPairCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(
PreferenceManager.SAM_FLAG_UNMAPPED_PAIR,
String.valueOf(samFlagUnmappedPairCB.isSelected()));
}
private void samShowDuplicatesCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(
PreferenceManager.SAM_SHOW_DUPLICATES,
String.valueOf(!samFilterDuplicatesCB.isSelected()));
}
private void showSoftClippedCBActionPerformed(ActionEvent e) {
updatedPreferenceMap.put(
PreferenceManager.SAM_SHOW_SOFT_CLIPPED,
String.valueOf(showSoftClippedCB.isSelected()));
}
private void isizeComputeCBActionPerformed(ActionEvent e) {
updatedPreferenceMap.put(
PreferenceManager.SAM_COMPUTE_ISIZES,
String.valueOf(isizeComputeCB.isSelected()));
}
private void insertSizeMinPercentileFieldFocusLost(FocusEvent e) {
insertSizeMinPercentileFieldActionPerformed(null);
}
private void insertSizeMinPercentileFieldActionPerformed(ActionEvent e) {
String valueString = insertSizeMinPercentileField.getText().trim();
try {
Double.parseDouble(valueString);
updatedPreferenceMap.put(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE, valueString);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Minimum insert size percentile must be a number.");
}
}
private void insertSizeMaxPercentileFieldFocusLost(FocusEvent e) {
insertSizeMaxPercentileFieldActionPerformed(null);
}
private void insertSizeMaxPercentileFieldActionPerformed(ActionEvent e) {
String valueString = insertSizeMaxPercentileField.getText().trim();
try {
Double.parseDouble(valueString);
updatedPreferenceMap.put(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE, valueString);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Maximum insert size percentile must be a number.");
}
}
private void samMaxWindowSizeFieldFocusLost(java.awt.event.FocusEvent evt) {
String maxSAMWindowSize = samMaxWindowSizeField.getText().trim();
try {
Float.parseFloat(maxSAMWindowSize);
updatedPreferenceMap.put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, maxSAMWindowSize);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Visibility range must be a number.");
}
}
private void samMaxWindowSizeFieldActionPerformed(java.awt.event.ActionEvent evt) {
String maxSAMWindowSize = String.valueOf(samMaxWindowSizeField.getText());
try {
Float.parseFloat(maxSAMWindowSize);
updatedPreferenceMap.put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, maxSAMWindowSize);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Visibility range must be a number.");
}
}
private void seqResolutionThresholdActionPerformed(ActionEvent e) {
samMaxWindowSizeFieldFocusLost(null);
}
private void seqResolutionThresholdFocusLost(FocusEvent e) {
String seqResolutionSize = String.valueOf(seqResolutionThreshold.getText());
try {
float value = Float.parseFloat(seqResolutionSize.replace(",", ""));
if (value < 1 || value > 10000) {
MessageUtils.showMessage("Visibility range must be a number between 1 and 10000.");
} else {
updatedPreferenceMap.put(PreferenceManager.MAX_SEQUENCE_RESOLUTION, seqResolutionSize);
}
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Visibility range must be a number between 1 and 10000.");
}
}
private void chartDrawTrackNameCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.CHART_DRAW_TRACK_NAME,
String.valueOf(chartDrawTrackNameCB.isSelected()));
}
private void autoscaleCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.CHART_AUTOSCALE, String.valueOf(autoscaleCB.isSelected()));
}
private void colorBordersCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(
PreferenceManager.CHART_COLOR_BORDERS,
String.valueOf(colorBordersCB.isSelected()));
}//GEN-LAST:event_colorBordersCBActionPerformed
private void bottomBorderCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(
PreferenceManager.CHART_DRAW_BOTTOM_BORDER,
String.valueOf(bottomBorderCB.isSelected()));
}//GEN-LAST:event_bottomBorderCBActionPerformed
private void topBorderCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(
PreferenceManager.CHART_DRAW_TOP_BORDER,
String.valueOf(topBorderCB.isSelected()));
}//GEN-LAST:event_topBorderCBActionPerformed
private void chooseOverlayColorsButtonActionPerformed(java.awt.event.ActionEvent evt) {
(new LegendDialog(IGV.getMainFrame(), true)).setVisible(true);
}//GEN-LAST:event_chooseOverlayColorsButtonActionPerformed
private void colorOverlyCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.COLOR_OVERLAY_KEY, String.valueOf(
colorOverlyCB.isSelected()));
}//GEN-LAST:event_colorOverlyCBActionPerformed
private void displayTracksCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.DISPLAY_OVERLAY_TRACKS_KEY, String.valueOf(
displayTracksCB.isSelected()));
updateOverlays = true;
}//GEN-LAST:event_displayTracksCBActionPerformed
private void overlayTrackCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.OVERLAY_TRACKS_KEY, String.valueOf(
overlayTrackCB.isSelected()));
overlayAttributeTextField.setEnabled(overlayTrackCB.isSelected());
colorOverlyCB.setEnabled(overlayTrackCB.isSelected());
chooseOverlayColorsButton.setEnabled(overlayTrackCB.isSelected());
updateOverlays = true;
}//GEN-LAST:event_overlayTrackCBActionPerformed
private void overlayAttributeTextFieldKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}//GEN-LAST:event_overlayAttributeTextFieldKeyTyped
private void overlayAttributeTextFieldFocusLost(java.awt.event.FocusEvent evt) {
String attributeName = String.valueOf(overlayAttributeTextField.getText());
if (attributeName != null) {
attributeName = attributeName.trim();
}
updatedPreferenceMap.put(PreferenceManager.OVERLAY_ATTRIBUTE_KEY, attributeName);
updateOverlays = true;
}//GEN-LAST:event_overlayAttributeTextFieldFocusLost
private void overlayAttributeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.OVERLAY_ATTRIBUTE_KEY, String.valueOf(
overlayAttributeTextField.getText()));
updateOverlays = true;
// TODO add your handling code here:
}//GEN-LAST:event_overlayAttributeTextFieldActionPerformed
private void defaultTrackHeightFieldFocusLost(java.awt.event.FocusEvent evt) {
String defaultTrackHeight = String.valueOf(defaultChartTrackHeightField.getText());
try {
Integer.parseInt(defaultTrackHeight);
updatedPreferenceMap.put(PreferenceManager.TRACK_HEIGHT_KEY, defaultTrackHeight);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Track height must be an integer number.");
}
}//GEN-LAST:event_defaultTrackHeightFieldFocusLost
private void defaultTrackHeightFieldActionPerformed(java.awt.event.ActionEvent evt) {
String defaultTrackHeight = String.valueOf(defaultChartTrackHeightField.getText());
try {
Integer.parseInt(defaultTrackHeight);
updatedPreferenceMap.put(PreferenceManager.TRACK_HEIGHT_KEY, defaultTrackHeight);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Track height must be an integer number.");
}
}
private void trackNameAttributeFieldFocusLost(java.awt.event.FocusEvent evt) {
String attributeName = String.valueOf(trackNameAttributeField.getText());
if (attributeName != null) {
attributeName = attributeName.trim();
}
updatedPreferenceMap.put(PreferenceManager.TRACK_ATTRIBUTE_NAME_KEY, attributeName);
}
private void trackNameAttributeFieldActionPerformed(java.awt.event.ActionEvent evt) {
String attributeName = String.valueOf(trackNameAttributeField.getText());
if (attributeName != null) {
attributeName = attributeName.trim();
}
updatedPreferenceMap.put(PreferenceManager.TRACK_ATTRIBUTE_NAME_KEY, attributeName);
}
private void defaultChartTrackHeightFieldFocusLost(java.awt.event.FocusEvent evt) {
defaultChartTrackHeightFieldActionPerformed(null);
}
private void defaultChartTrackHeightFieldActionPerformed(java.awt.event.ActionEvent evt) {
String defaultTrackHeight = String.valueOf(defaultChartTrackHeightField.getText());
try {
Integer.parseInt(defaultTrackHeight);
updatedPreferenceMap.put(PreferenceManager.CHART_TRACK_HEIGHT_KEY, defaultTrackHeight);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Track height must be an integer number.");
}
}
private void geneListFlankingFieldFocusLost(FocusEvent e) {
// TODO add your code here
}
private void geneListFlankingFieldActionPerformed(ActionEvent e) {
String flankingRegion = String.valueOf(geneListFlankingField.getText());
try {
Integer.parseInt(flankingRegion);
updatedPreferenceMap.put(PreferenceManager.FLANKING_REGION, flankingRegion);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Track height must be an integer number.");
}
}
private void showAttributesDisplayCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
boolean state = ((JCheckBox) evt.getSource()).isSelected();
updatedPreferenceMap.put(PreferenceManager.SHOW_ATTRIBUTE_VIEWS_KEY, String.valueOf(state));
IGV.getInstance().doShowAttributeDisplay(state);
}
private void combinePanelsCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.SHOW_SINGLE_TRACK_PANE_KEY, String.valueOf(
combinePanelsCB.isSelected()));
}
private void showMissingDataCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.SHOW_MISSING_DATA_KEY, String.valueOf(
showMissingDataCB.isSelected()));
}
private void showRegionBoundariesCBActionPerformed(ActionEvent e) {
updatedPreferenceMap.put(PreferenceManager.SHOW_REGION_BARS, String.valueOf(
showRegionBoundariesCB.isSelected()));
}
private void filterVendorFailedReadsCBActionPerformed(ActionEvent e) {
updatedPreferenceMap.put(
PreferenceManager.SAM_FILTER_FAILED_READS,
String.valueOf(filterFailedReadsCB.isSelected()));
}
private void samMinBaseQualityFieldActionPerformed(java.awt.event.ActionEvent evt) {
String baseQuality = samMinBaseQualityField.getText().trim();
try {
Integer.parseInt(baseQuality);
updatedPreferenceMap.put(PreferenceManager.SAM_BASE_QUALITY_MIN, baseQuality);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Base quality must be an integer.");
}
}//GEN-LAST:event_samMinBaseQualityFieldActionPerformed
private void samMinBaseQualityFieldFocusLost(java.awt.event.FocusEvent evt) {
samMinBaseQualityFieldActionPerformed(null);
}//GEN-LAST:event_samMinBaseQualityFieldFocusLost
private void samMaxBaseQualityFieldActionPerformed(java.awt.event.ActionEvent evt) {
String baseQuality = samMaxBaseQualityField.getText().trim();
try {
Integer.parseInt(baseQuality);
updatedPreferenceMap.put(PreferenceManager.SAM_BASE_QUALITY_MAX, baseQuality);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Base quality must be an integer.");
}
}//GEN-LAST:event_samMaxBaseQualityFieldActionPerformed
private void samMaxBaseQualityFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_samMaxBaseQualityFieldFocusLost
samMaxBaseQualityFieldActionPerformed(null);
}//GEN-LAST:event_samMaxBaseQualityFieldFocusLost
private void expMapToGeneCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expMapToGeneCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.PROBE_MAPPING_KEY, String.valueOf(expMapToGeneCB.isSelected()));
}//GEN-LAST:event_expMapToGeneCBActionPerformed
private void labelYAxisCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelYAxisCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.CHART_DRAW_Y_AXIS, String.valueOf(labelYAxisCB.isSelected()));
}
private void showCovTrackCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showCovTrackCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.SAM_SHOW_COV_TRACK, String.valueOf(showCovTrackCB.isSelected()));
}
private void showJunctionTrackCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showCovTrackCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.SAM_SHOW_JUNCTION_TRACK, String.valueOf(showJunctionTrackCB.isSelected()));
}
private void filterCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.SAM_FILTER_ALIGNMENTS, String.valueOf(filterCB.isSelected()));
filterURL.setEnabled(filterCB.isSelected());
}
private void filterURLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterURLActionPerformed
updatedPreferenceMap.put(
PreferenceManager.SAM_FILTER_URL,
String.valueOf(filterURL.getText()));
}//GEN-LAST:event_filterURLActionPerformed
private void filterURLFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_filterURLFocusLost
filterURLActionPerformed(null);
}//GEN-LAST:event_filterURLFocusLost
private void portFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portFieldActionPerformed
String portString = portField.getText().trim();
try {
Integer.parseInt(portString);
updatedPreferenceMap.put(PreferenceManager.PORT_NUMBER, portString);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Port must be an integer.");
}
}//GEN-LAST:event_portFieldActionPerformed
private void portFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_portFieldFocusLost
portFieldActionPerformed(null);
}//GEN-LAST:event_portFieldFocusLost
private void enablePortCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enablePortCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.PORT_ENABLED, String.valueOf(enablePortCB.isSelected()));
portField.setEnabled(enablePortCB.isSelected());
}//GEN-LAST:event_enablePortCBActionPerformed
private void expandCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expandCBActionPerformed
updatedPreferenceMap.put(
PreferenceManager.EXPAND_FEAUTRE_TRACKS,
String.valueOf(expandCB.isSelected()));
}//GEN-LAST:event_expandCBActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
PreferenceManager prefMgr = PreferenceManager.getInstance();
genomeServerURLTextField.setEnabled(true);
genomeServerURLTextField.setText(UIConstants.DEFAULT_SERVER_GENOME_ARCHIVE_LIST);
updatedPreferenceMap.put(PreferenceManager.GENOMES_SERVER_URL, null);
dataServerURLTextField.setEnabled(true);
dataServerURLTextField.setText(PreferenceManager.DEFAULT_DATA_SERVER_URL);
updatedPreferenceMap.put(PreferenceManager.DATA_SERVER_URL_KEY, null);
}//GEN-LAST:event_jButton1ActionPerformed
private void searchZoomCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchZoomCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.SEARCH_ZOOM, String.valueOf(searchZoomCB.isSelected()));
}//GEN-LAST:event_searchZoomCBActionPerformed
private void useByteRangeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useByteRangeCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.USE_BYTE_RANGE, String.valueOf(useByteRangeCB.isSelected()));
}//GEN-LAST:event_useByteRangeCBActionPerformed
private void showDatarangeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showDatarangeCBActionPerformed
updatedPreferenceMap.put(PreferenceManager.CHART_SHOW_DATA_RANGE, String.valueOf(showDatarangeCB.isSelected()));
}//GEN-LAST:event_showDatarangeCBActionPerformed
private void showDatarangeCBFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_showDatarangeCBFocusLost
showDatarangeCBActionPerformed(null);
}//GEN-LAST:event_showDatarangeCBFocusLost
private void snpThresholdFieldActionPerformed(java.awt.event.ActionEvent evt) {
String snpThreshold = snpThresholdField.getText().trim();
try {
Double.parseDouble(snpThreshold);
updatedPreferenceMap.put(PreferenceManager.SAM_ALLELE_THRESHOLD, snpThreshold);
} catch (NumberFormatException numberFormatException) {
inputValidated = false;
MessageUtils.showMessage("Allele frequency threshold must be a number.");
}
}
private void snpThresholdFieldFocusLost(java.awt.event.FocusEvent evt) {
snpThresholdFieldActionPerformed(null);
}
private void normalizeCoverageCBActionPerformed(java.awt.event.ActionEvent evt) {
updatedPreferenceMap.put(PreferenceManager.NORMALIZE_COVERAGE, String.valueOf(normalizeCoverageCB.isSelected()));
portField.setEnabled(enablePortCB.isSelected());
}
// Proxy settings
private void clearProxySettingsButtonActionPerformed(ActionEvent e) {
if (MessageUtils.confirm("This will immediately clear all proxy settings. Are you sure?")) {
this.proxyHostField.setText("");
this.proxyPortField.setText("");
this.proxyUsernameField.setText("");
this.proxyPasswordField.setText("");
this.useProxyCB.setSelected(false);
PreferenceManager.getInstance().clearProxySettings();
}
}
private void useProxyCBActionPerformed(java.awt.event.ActionEvent evt) {
proxySettingsChanged = true;
boolean useProxy = useProxyCB.isSelected();
boolean authenticateProxy = authenticateProxyCB.isSelected();
portField.setEnabled(enablePortCB.isSelected());
updateProxyState(useProxy, authenticateProxy);
updatedPreferenceMap.put(PreferenceManager.USE_PROXY, String.valueOf(useProxy));
}
private void authenticateProxyCBActionPerformed(java.awt.event.ActionEvent evt) {
proxySettingsChanged = true;
boolean useProxy = useProxyCB.isSelected();
boolean authenticateProxy = authenticateProxyCB.isSelected();
portField.setEnabled(enablePortCB.isSelected());
updateProxyState(useProxy, authenticateProxy);
updatedPreferenceMap.put(PreferenceManager.PROXY_AUTHENTICATE, String.valueOf(authenticateProxy));
}
// Host
private void proxyHostFieldFocusLost(java.awt.event.FocusEvent evt) {
proxyHostFieldActionPerformed(null);
}
private void proxyHostFieldActionPerformed(java.awt.event.ActionEvent evt) {
proxySettingsChanged = true;
updatedPreferenceMap.put(PreferenceManager.PROXY_HOST, proxyHostField.getText());
}
private void proxyPortFieldFocusLost(java.awt.event.FocusEvent evt) {
proxyPortFieldActionPerformed(null);
}
private void proxyPortFieldActionPerformed(java.awt.event.ActionEvent evt) {
try {
Integer.parseInt(proxyPortField.getText());
proxySettingsChanged = true;
updatedPreferenceMap.put(PreferenceManager.PROXY_PORT, proxyPortField.getText());
}
catch (NumberFormatException e) {
MessageUtils.showMessage("Proxy port must be an integer.");
}
}
// Username
private void proxyUsernameFieldFocusLost(java.awt.event.FocusEvent evt) {
proxyUsernameFieldActionPerformed(null);
}
private void proxyUsernameFieldActionPerformed(java.awt.event.ActionEvent evt) {
proxySettingsChanged = true;
String user = proxyUsernameField.getText();
updatedPreferenceMap.put(PreferenceManager.PROXY_USER, user);
}
// Password
private void proxyPasswordFieldFocusLost(java.awt.event.FocusEvent evt) {
proxyPasswordFieldActionPerformed(null);
}
private void proxyPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {
proxySettingsChanged = true;
String pw = proxyPasswordField.getText();
String pwEncoded = Utilities.base64Encode(pw);
updatedPreferenceMap.put(PreferenceManager.PROXY_PW, pwEncoded);
}
private void updateProxyState(boolean useProxy, boolean authenticateProxy) {
proxyHostField.setEnabled(useProxy);
proxyPortField.setEnabled(useProxy);
proxyUsernameField.setEnabled(useProxy && authenticateProxy);
proxyPasswordField.setEnabled(useProxy && authenticateProxy);
}
private void resetValidation() {
// Assume valid input until proven otherwise
inputValidated = true;
}
/*
* Object selection = geneMappingFile.getSelectedItem();
String filename = (selection == null ? null : selection.toString().trim());
updatedPreferenceMap.put(
PreferenceManager.USER_PROBE_MAP_KEY,
filename);
* */
private void initValues() {
combinePanelsCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SHOW_SINGLE_TRACK_PANE_KEY));
//drawExonNumbersCB.setSelected(preferenceManager.getDrawExonNumbers());
showRegionBoundariesCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SHOW_REGION_BARS));
defaultChartTrackHeightField.setText(prefMgr.get(PreferenceManager.CHART_TRACK_HEIGHT_KEY));
defaultTrackHeightField.setText(prefMgr.get(PreferenceManager.TRACK_HEIGHT_KEY));
displayTracksCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.DISPLAY_OVERLAY_TRACKS_KEY));
overlayAttributeTextField.setText(prefMgr.get(PreferenceManager.OVERLAY_ATTRIBUTE_KEY));
overlayTrackCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.OVERLAY_TRACKS_KEY));
showMissingDataCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SHOW_MISSING_DATA_KEY));
colorOverlyCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.COLOR_OVERLAY_KEY));
overlayAttributeTextField.setEnabled(overlayTrackCB.isSelected());
colorOverlyCB.setEnabled(overlayTrackCB.isSelected());
chooseOverlayColorsButton.setEnabled(overlayTrackCB.isSelected());
seqResolutionThreshold.setText(prefMgr.get(PreferenceManager.MAX_SEQUENCE_RESOLUTION));
geneListFlankingField.setText(prefMgr.get(PreferenceManager.FLANKING_REGION));
enablePortCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.PORT_ENABLED));
portField.setText(String.valueOf(prefMgr.getAsInt(PreferenceManager.PORT_NUMBER)));
portField.setEnabled(enablePortCB.isSelected());
expandCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.EXPAND_FEAUTRE_TRACKS));
searchZoomCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SEARCH_ZOOM));
useByteRangeCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.USE_BYTE_RANGE));
showAttributesDisplayCheckBox.setSelected(prefMgr.getAsBoolean(PreferenceManager.SHOW_ATTRIBUTE_VIEWS_KEY));
trackNameAttributeField.setText(prefMgr.get(PreferenceManager.TRACK_ATTRIBUTE_NAME_KEY));
genomeServerURLTextField.setText(prefMgr.getGenomeListURL());
dataServerURLTextField.setText(prefMgr.getDataServerURL());
// Chart panel
topBorderCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_DRAW_TOP_BORDER));
bottomBorderCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_DRAW_BOTTOM_BORDER));
colorBordersCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_COLOR_BORDERS));
chartDrawTrackNameCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_DRAW_TRACK_NAME));
autoscaleCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_AUTOSCALE));
showDatarangeCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_SHOW_DATA_RANGE));
labelYAxisCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.CHART_DRAW_Y_AXIS));
samMaxWindowSizeField.setText(prefMgr.get(PreferenceManager.SAM_MAX_VISIBLE_RANGE));
samMaxDepthField.setText(prefMgr.get(PreferenceManager.SAM_MAX_LEVELS));
mappingQualityThresholdField.setText(prefMgr.get(PreferenceManager.SAM_QUALITY_THRESHOLD));
insertSizeThresholdField.setText(prefMgr.get(PreferenceManager.SAM_MAX_INSERT_SIZE_THRESHOLD));
insertSizeMinThresholdField.setText(prefMgr.get(PreferenceManager.SAM_MIN_INSERT_SIZE_THRESHOLD));
insertSizeMinPercentileField.setText(prefMgr.get(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE));
insertSizeMaxPercentileField.setText(prefMgr.get(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE));
snpThresholdField.setText((String.valueOf(prefMgr.getAsFloat(PreferenceManager.SAM_ALLELE_THRESHOLD))));
//samShowZeroQualityCB.setSelected(samPrefs.isShowZeroQuality());
samFilterDuplicatesCB.setSelected(!prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES));
filterFailedReadsCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS));
showSoftClippedCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_SOFT_CLIPPED));
samFlagUnmappedPairCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_FLAG_UNMAPPED_PAIR));
samShadeMismatchedBaseCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_SHADE_BASE_QUALITY));
samMinBaseQualityField.setText((String.valueOf(prefMgr.getAsInt(PreferenceManager.SAM_BASE_QUALITY_MIN))));
samMaxBaseQualityField.setText((String.valueOf(prefMgr.getAsInt(PreferenceManager.SAM_BASE_QUALITY_MAX))));
samMinBaseQualityField.setEnabled(samShadeMismatchedBaseCB.isSelected());
samMaxBaseQualityField.setEnabled(samShadeMismatchedBaseCB.isSelected());
showCovTrackCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_COV_TRACK));
isizeComputeCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_COMPUTE_ISIZES));
//dhmay adding 20110208
showJunctionTrackCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_TRACK));
filterCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_ALIGNMENTS));
if (prefMgr.get(PreferenceManager.SAM_FILTER_URL) != null) {
filterURL.setText(prefMgr.get(PreferenceManager.SAM_FILTER_URL));
}
genomeUpdateCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.AUTO_UPDATE_GENOMES));
final boolean mapProbesToGenes = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.PROBE_MAPPING_KEY);
expMapToGeneCB.setSelected(mapProbesToGenes);
expMapToLociCB.setSelected(!mapProbesToGenes);
normalizeCoverageCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.NORMALIZE_COVERAGE));
expandIconCB.setSelected(prefMgr.getAsBoolean(PreferenceManager.SHOW_EXPAND_ICON));
boolean useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY);
useProxyCB.setSelected(useProxy);
boolean authenticateProxy = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE);
authenticateProxyCB.setSelected(authenticateProxy);
proxyHostField.setText(prefMgr.get(PreferenceManager.PROXY_HOST, ""));
proxyPortField.setText(prefMgr.get(PreferenceManager.PROXY_PORT, ""));
proxyUsernameField.setText(prefMgr.get(PreferenceManager.PROXY_USER, ""));
String pwCoded = prefMgr.get(PreferenceManager.PROXY_PW, "");
proxyPasswordField.setText(Utilities.base64Decode(pwCoded));
backgroundColorPanel.setBackground(
PreferenceManager.getInstance().getAsColor(PreferenceManager.BACKGROUND_COLOR));
updateFontField();
updateProxyState(useProxy, authenticateProxy);
}
private void updateFontField() {
Font font = FontManager.getDefaultFont();
StringBuffer buf = new StringBuffer();
buf.append(font.getFamily());
if (font.isBold()) {
buf.append(" bold");
}
if (font.isItalic()) {
buf.append(" italic");
}
buf.append(" " + font.getSize());
defaultFontField.setText(buf.toString());
}
private void checkForSAMChanges() {
WaitCursorManager.CursorToken token = WaitCursorManager.showWaitCursor();
try {
boolean reloadSAM = false;
for (String key : SAM_PREFERENCE_KEYS) {
if (updatedPreferenceMap.containsKey(key)) {
reloadSAM = true;
break;
}
}
if (reloadSAM) {
IGV.getInstance().getTrackManager().reloadSAMTracks();
}
} catch (NumberFormatException numberFormatException) {
} finally {
WaitCursorManager.removeWaitCursor(token);
}
}
private void checkForProbeChanges() {
if (updatedPreferenceMap.containsKey(PreferenceManager.PROBE_MAPPING_KEY)) {
ProbeToLocusMap.getInstance().clearProbeMappings();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
PreferencesEditor dialog = new PreferencesEditor(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
//TODO move this to another class, or resource bundle
static String overlayText = "<html>These options control the treatment of mutation tracks. " +
"Mutation data may optionally<br>be overlayed on other tracks that have a matching attribute value " +
"from the sample info <br>file. " +
"This is normally an attribute that identifies a sample or patient. The attribute key <br>is specified in the" +
"text field below.";
public String getOverlayText() {
return overlayText;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// Generated using JFormDesigner non-commercial license
private JTabbedPane tabbedPane;
private JPanel generalPanel;
private JPanel jPanel10;
private JLabel missingDataExplanation;
private JCheckBox showMissingDataCB;
private JCheckBox combinePanelsCB;
private JCheckBox showAttributesDisplayCheckBox;
private JCheckBox searchZoomCB;
private JLabel zoomToFeatureExplanation;
private JLabel label4;
private JTextField geneListFlankingField;
private JLabel zoomToFeatureExplanation2;
private JLabel label5;
private JLabel label6;
private JTextField seqResolutionThreshold;
private JLabel label10;
private JTextField defaultFontField;
private JButton fontChangeButton;
private JCheckBox showRegionBoundariesCB;
private JLabel label7;
private JPanel backgroundColorPanel;
private JButton resetBackgroundButton;
private JPanel tracksPanel;
private JPanel jPanel6;
private JLabel jLabel5;
private JTextField defaultChartTrackHeightField;
private JLabel trackNameAttributeLabel;
private JTextField trackNameAttributeField;
private JLabel missingDataExplanation2;
private JLabel jLabel8;
private JTextField defaultTrackHeightField;
private JLabel missingDataExplanation4;
private JLabel missingDataExplanation5;
private JLabel missingDataExplanation3;
private JCheckBox expandCB;
private JCheckBox normalizeCoverageCB;
private JLabel missingDataExplanation8;
private JCheckBox expandIconCB;
private JPanel overlaysPanel;
private JPanel jPanel5;
private JLabel jLabel3;
private JTextField overlayAttributeTextField;
private JCheckBox overlayTrackCB;
private JLabel jLabel2;
private JCheckBox displayTracksCB;
private JLabel jLabel4;
private JCheckBox colorOverlyCB;
private JideButton chooseOverlayColorsButton;
private JPanel chartPanel;
private JPanel jPanel4;
private JCheckBox topBorderCB;
private Label label1;
private JCheckBox chartDrawTrackNameCB;
private JCheckBox bottomBorderCB;
private JLabel jLabel7;
private JCheckBox colorBordersCB;
private JCheckBox labelYAxisCB;
private JCheckBox autoscaleCB;
private JLabel jLabel9;
private JCheckBox showDatarangeCB;
private JPanel alignmentPanel;
private JPanel jPanel1;
private JPanel jPanel11;
private JTextField samMaxDepthField;
private JLabel jLabel11;
private JLabel jLabel16;
private JTextField mappingQualityThresholdField;
private JLabel jLabel14;
private JLabel jLabel13;
private JLabel jLabel15;
private JTextField samMaxWindowSizeField;
private JLabel jLabel12;
private JLabel jLabel26;
private JTextField snpThresholdField;
private JPanel jPanel12;
private JTextField samMinBaseQualityField;
private JCheckBox samShadeMismatchedBaseCB;
private JTextField samMaxBaseQualityField;
private JCheckBox showCovTrackCB;
private JCheckBox samFilterDuplicatesCB;
private JLabel jLabel19;
private JCheckBox filterCB;
private JTextField filterURL;
private JCheckBox samFlagUnmappedPairCB;
private JCheckBox filterFailedReadsCB;
private JLabel label2;
private JCheckBox showSoftClippedCB;
private JCheckBox showJunctionTrackCB;
private JPanel panel2;
private JCheckBox isizeComputeCB;
private JLabel jLabel17;
private JTextField insertSizeMinThresholdField;
private JLabel jLabel20;
private JTextField insertSizeThresholdField;
private JLabel jLabel30;
private JLabel jLabel18;
private JTextField insertSizeMinPercentileField;
private JTextField insertSizeMaxPercentileField;
private JLabel label8;
private JLabel label9;
private JPanel expressionPane;
private JPanel jPanel8;
private JRadioButton expMapToGeneCB;
private JLabel jLabel24;
private JRadioButton expMapToLociCB;
private JLabel jLabel21;
private JPanel advancedPanel;
private JPanel jPanel3;
private JPanel jPanel2;
private JLabel jLabel1;
private JTextField genomeServerURLTextField;
private JLabel jLabel6;
private JTextField dataServerURLTextField;
private JCheckBox editServerPropertiesCB;
private JButton jButton1;
private JButton clearGenomeCacheButton;
private JCheckBox genomeUpdateCB;
private JPanel jPanel7;
private JCheckBox enablePortCB;
private JTextField portField;
private JLabel jLabel22;
private JPanel jPanel9;
private JCheckBox useByteRangeCB;
private JLabel jLabel25;
private JPanel proxyPanel;
private JPanel jPanel15;
private JPanel jPanel16;
private JTextField proxyUsernameField;
private JLabel jLabel28;
private JCheckBox authenticateProxyCB;
private JLabel jLabel29;
private JPasswordField proxyPasswordField;
private JPanel jPanel17;
private JTextField proxyHostField;
private JTextField proxyPortField;
private JLabel jLabel27;
private JLabel jLabel23;
private JCheckBox useProxyCB;
private JLabel label3;
private JButton clearProxySettingsButton;
private ButtonPanel okCancelButtonPanel;
private JButton okButton;
private JButton cancelButton;
// End of variables declaration//GEN-END:variables
public boolean isCanceled() {
return canceled;
}
/**
* List of keys that affect the alignments loaded. This list is used to trigger a reload, if required.
* Not all alignment preferences need trigger a reload, this is a subset.
*/
static java.util.List<String> SAM_PREFERENCE_KEYS = Arrays.asList(
PreferenceManager.SAM_QUALITY_THRESHOLD,
PreferenceManager.SAM_FILTER_ALIGNMENTS,
PreferenceManager.SAM_FILTER_URL,
PreferenceManager.SAM_MAX_VISIBLE_RANGE,
PreferenceManager.SAM_SHOW_DUPLICATES,
PreferenceManager.SAM_SHOW_SOFT_CLIPPED,
PreferenceManager.SAM_MAX_LEVELS,
PreferenceManager.SAM_MAX_READS,
PreferenceManager.SAM_FILTER_FAILED_READS
);
}
| false | true | private void initComponents() {
tabbedPane = new JTabbedPane();
generalPanel = new JPanel();
jPanel10 = new JPanel();
missingDataExplanation = new JLabel();
showMissingDataCB = new JCheckBox();
combinePanelsCB = new JCheckBox();
showAttributesDisplayCheckBox = new JCheckBox();
searchZoomCB = new JCheckBox();
zoomToFeatureExplanation = new JLabel();
label4 = new JLabel();
geneListFlankingField = new JTextField();
zoomToFeatureExplanation2 = new JLabel();
label5 = new JLabel();
label6 = new JLabel();
seqResolutionThreshold = new JTextField();
label10 = new JLabel();
defaultFontField = new JTextField();
fontChangeButton = new JButton();
showRegionBoundariesCB = new JCheckBox();
label7 = new JLabel();
backgroundColorPanel = new JPanel();
resetBackgroundButton = new JButton();
tracksPanel = new JPanel();
jPanel6 = new JPanel();
jLabel5 = new JLabel();
defaultChartTrackHeightField = new JTextField();
trackNameAttributeLabel = new JLabel();
trackNameAttributeField = new JTextField();
missingDataExplanation2 = new JLabel();
jLabel8 = new JLabel();
defaultTrackHeightField = new JTextField();
missingDataExplanation4 = new JLabel();
missingDataExplanation5 = new JLabel();
missingDataExplanation3 = new JLabel();
expandCB = new JCheckBox();
normalizeCoverageCB = new JCheckBox();
missingDataExplanation8 = new JLabel();
expandIconCB = new JCheckBox();
overlaysPanel = new JPanel();
jPanel5 = new JPanel();
jLabel3 = new JLabel();
overlayAttributeTextField = new JTextField();
overlayTrackCB = new JCheckBox();
jLabel2 = new JLabel();
displayTracksCB = new JCheckBox();
jLabel4 = new JLabel();
colorOverlyCB = new JCheckBox();
chooseOverlayColorsButton = new JideButton();
chartPanel = new JPanel();
jPanel4 = new JPanel();
topBorderCB = new JCheckBox();
label1 = new Label();
chartDrawTrackNameCB = new JCheckBox();
bottomBorderCB = new JCheckBox();
jLabel7 = new JLabel();
colorBordersCB = new JCheckBox();
labelYAxisCB = new JCheckBox();
autoscaleCB = new JCheckBox();
jLabel9 = new JLabel();
showDatarangeCB = new JCheckBox();
alignmentPanel = new JPanel();
jPanel1 = new JPanel();
jPanel11 = new JPanel();
samMaxDepthField = new JTextField();
jLabel11 = new JLabel();
jLabel16 = new JLabel();
mappingQualityThresholdField = new JTextField();
jLabel14 = new JLabel();
jLabel13 = new JLabel();
jLabel15 = new JLabel();
samMaxWindowSizeField = new JTextField();
jLabel12 = new JLabel();
jLabel26 = new JLabel();
snpThresholdField = new JTextField();
jPanel12 = new JPanel();
samMinBaseQualityField = new JTextField();
samShadeMismatchedBaseCB = new JCheckBox();
samMaxBaseQualityField = new JTextField();
showCovTrackCB = new JCheckBox();
samFilterDuplicatesCB = new JCheckBox();
jLabel19 = new JLabel();
filterCB = new JCheckBox();
filterURL = new JTextField();
samFlagUnmappedPairCB = new JCheckBox();
filterFailedReadsCB = new JCheckBox();
label2 = new JLabel();
showSoftClippedCB = new JCheckBox();
showJunctionTrackCB = new JCheckBox();
panel2 = new JPanel();
isizeComputeCB = new JCheckBox();
jLabel17 = new JLabel();
insertSizeMinThresholdField = new JTextField();
jLabel20 = new JLabel();
insertSizeThresholdField = new JTextField();
jLabel30 = new JLabel();
jLabel18 = new JLabel();
insertSizeMinPercentileField = new JTextField();
insertSizeMaxPercentileField = new JTextField();
label8 = new JLabel();
label9 = new JLabel();
expressionPane = new JPanel();
jPanel8 = new JPanel();
expMapToGeneCB = new JRadioButton();
jLabel24 = new JLabel();
expMapToLociCB = new JRadioButton();
jLabel21 = new JLabel();
advancedPanel = new JPanel();
jPanel3 = new JPanel();
jPanel2 = new JPanel();
jLabel1 = new JLabel();
genomeServerURLTextField = new JTextField();
jLabel6 = new JLabel();
dataServerURLTextField = new JTextField();
editServerPropertiesCB = new JCheckBox();
jButton1 = new JButton();
clearGenomeCacheButton = new JButton();
genomeUpdateCB = new JCheckBox();
jPanel7 = new JPanel();
enablePortCB = new JCheckBox();
portField = new JTextField();
jLabel22 = new JLabel();
jPanel9 = new JPanel();
useByteRangeCB = new JCheckBox();
jLabel25 = new JLabel();
proxyPanel = new JPanel();
jPanel15 = new JPanel();
jPanel16 = new JPanel();
proxyUsernameField = new JTextField();
jLabel28 = new JLabel();
authenticateProxyCB = new JCheckBox();
jLabel29 = new JLabel();
proxyPasswordField = new JPasswordField();
jPanel17 = new JPanel();
proxyHostField = new JTextField();
proxyPortField = new JTextField();
jLabel27 = new JLabel();
jLabel23 = new JLabel();
useProxyCB = new JCheckBox();
label3 = new JLabel();
clearProxySettingsButton = new JButton();
okCancelButtonPanel = new ButtonPanel();
okButton = new JButton();
cancelButton = new JButton();
//======== this ========
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== tabbedPane ========
{
//======== generalPanel ========
{
generalPanel.setLayout(new BorderLayout());
//======== jPanel10 ========
{
jPanel10.setBorder(new BevelBorder(BevelBorder.RAISED));
jPanel10.setLayout(null);
//---- missingDataExplanation ----
missingDataExplanation.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation.setText("<html>Distinguish regions with zero values from regions with no data on plots <br>(e.g. bar charts). Regions with no data are indicated with a gray background.");
jPanel10.add(missingDataExplanation);
missingDataExplanation.setBounds(41, 35, 474, missingDataExplanation.getPreferredSize().height);
//---- showMissingDataCB ----
showMissingDataCB.setText("Distinguish Missing Data");
showMissingDataCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMissingDataCBActionPerformed(e);
}
});
jPanel10.add(showMissingDataCB);
showMissingDataCB.setBounds(new Rectangle(new Point(10, 6), showMissingDataCB.getPreferredSize()));
//---- combinePanelsCB ----
combinePanelsCB.setText("Combine Data and Feature Panels");
combinePanelsCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
combinePanelsCBActionPerformed(e);
}
});
jPanel10.add(combinePanelsCB);
combinePanelsCB.setBounds(new Rectangle(new Point(10, 95), combinePanelsCB.getPreferredSize()));
//---- showAttributesDisplayCheckBox ----
showAttributesDisplayCheckBox.setText("Show Attribute Display");
showAttributesDisplayCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAttributesDisplayCheckBoxActionPerformed(e);
}
});
jPanel10.add(showAttributesDisplayCheckBox);
showAttributesDisplayCheckBox.setBounds(new Rectangle(new Point(10, 130), showAttributesDisplayCheckBox.getPreferredSize()));
//---- searchZoomCB ----
searchZoomCB.setText("Zoom to features");
searchZoomCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchZoomCBActionPerformed(e);
}
});
jPanel10.add(searchZoomCB);
searchZoomCB.setBounds(new Rectangle(new Point(10, 205), searchZoomCB.getPreferredSize()));
//---- zoomToFeatureExplanation ----
zoomToFeatureExplanation.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
zoomToFeatureExplanation.setText("<html>This option controls the behavior of feature searchs. If true, the zoom level is changed as required to size the view to the feature size. If false the zoom level is unchanged.");
zoomToFeatureExplanation.setVerticalAlignment(SwingConstants.TOP);
jPanel10.add(zoomToFeatureExplanation);
zoomToFeatureExplanation.setBounds(50, 230, 644, 50);
//---- label4 ----
label4.setText("Feature flanking region (bp): ");
jPanel10.add(label4);
label4.setBounds(new Rectangle(new Point(15, 365), label4.getPreferredSize()));
//---- geneListFlankingField ----
geneListFlankingField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
geneListFlankingFieldFocusLost(e);
}
});
geneListFlankingField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
geneListFlankingFieldActionPerformed(e);
}
});
jPanel10.add(geneListFlankingField);
geneListFlankingField.setBounds(215, 360, 255, geneListFlankingField.getPreferredSize().height);
//---- zoomToFeatureExplanation2 ----
zoomToFeatureExplanation2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
zoomToFeatureExplanation2.setText("<html><i>Added before and after feature locus when zooming to a feature. Also used when defining panel extents in gene/loci list views.");
zoomToFeatureExplanation2.setVerticalAlignment(SwingConstants.TOP);
jPanel10.add(zoomToFeatureExplanation2);
zoomToFeatureExplanation2.setBounds(45, 395, 637, 50);
//---- label5 ----
label5.setText("<html><i>Resolution in base-pairs per pixel at which sequence track becomes visible. ");
label5.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
jPanel10.add(label5);
label5.setBounds(new Rectangle(new Point(50, 320), label5.getPreferredSize()));
//---- label6 ----
label6.setText("Sequence Resolution Threshold (bp/pixel):");
jPanel10.add(label6);
label6.setBounds(new Rectangle(new Point(15, 290), label6.getPreferredSize()));
//---- seqResolutionThreshold ----
seqResolutionThreshold.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
seqResolutionThresholdFocusLost(e);
}
});
seqResolutionThreshold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seqResolutionThresholdActionPerformed(e);
}
});
jPanel10.add(seqResolutionThreshold);
seqResolutionThreshold.setBounds(315, 285, 105, seqResolutionThreshold.getPreferredSize().height);
//---- label10 ----
label10.setText("Default font: ");
label10.setLabelFor(defaultFontField);
jPanel10.add(label10);
label10.setBounds(new Rectangle(new Point(15, 530), label10.getPreferredSize()));
//---- defaultFontField ----
defaultFontField.setEditable(false);
jPanel10.add(defaultFontField);
defaultFontField.setBounds(105, 525, 238, defaultFontField.getPreferredSize().height);
//---- fontChangeButton ----
fontChangeButton.setText("Change...");
fontChangeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontChangeButtonActionPerformed(e);
}
});
jPanel10.add(fontChangeButton);
fontChangeButton.setBounds(360, 525, 97, fontChangeButton.getPreferredSize().height);
//---- showRegionBoundariesCB ----
showRegionBoundariesCB.setText("Show Region Boundaries");
showRegionBoundariesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAttributesDisplayCheckBoxActionPerformed(e);
showRegionBoundariesCBActionPerformed(e);
}
});
jPanel10.add(showRegionBoundariesCB);
showRegionBoundariesCB.setBounds(10, 165, 275, 23);
//---- label7 ----
label7.setText("Background color click to change): ");
jPanel10.add(label7);
label7.setBounds(15, 480, 235, label7.getPreferredSize().height);
//======== backgroundColorPanel ========
{
backgroundColorPanel.setPreferredSize(new Dimension(20, 20));
backgroundColorPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
backgroundColorPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
backgroundColorPanelMouseClicked(e);
}
});
backgroundColorPanel.setLayout(null);
}
jPanel10.add(backgroundColorPanel);
backgroundColorPanel.setBounds(255, 474, 30, 29);
//---- resetBackgroundButton ----
resetBackgroundButton.setText("Reset to default");
resetBackgroundButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetBackgroundButtonActionPerformed(e);
}
});
jPanel10.add(resetBackgroundButton);
resetBackgroundButton.setBounds(315, 474, 150, resetBackgroundButton.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel10.getComponentCount(); i++) {
Rectangle bounds = jPanel10.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel10.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel10.setMinimumSize(preferredSize);
jPanel10.setPreferredSize(preferredSize);
}
}
generalPanel.add(jPanel10, BorderLayout.CENTER);
}
tabbedPane.addTab("General", generalPanel);
//======== tracksPanel ========
{
tracksPanel.setLayout(null);
//======== jPanel6 ========
{
jPanel6.setLayout(null);
//---- jLabel5 ----
jLabel5.setText("Default Track Height, Charts (Pixels)");
jPanel6.add(jLabel5);
jLabel5.setBounds(new Rectangle(new Point(10, 12), jLabel5.getPreferredSize()));
//---- defaultChartTrackHeightField ----
defaultChartTrackHeightField.setText("40");
defaultChartTrackHeightField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultChartTrackHeightFieldActionPerformed(e);
}
});
defaultChartTrackHeightField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
defaultChartTrackHeightFieldFocusLost(e);
}
});
jPanel6.add(defaultChartTrackHeightField);
defaultChartTrackHeightField.setBounds(271, 6, 57, defaultChartTrackHeightField.getPreferredSize().height);
//---- trackNameAttributeLabel ----
trackNameAttributeLabel.setText("Track Name Attribute");
jPanel6.add(trackNameAttributeLabel);
trackNameAttributeLabel.setBounds(new Rectangle(new Point(10, 120), trackNameAttributeLabel.getPreferredSize()));
//---- trackNameAttributeField ----
trackNameAttributeField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trackNameAttributeFieldActionPerformed(e);
}
});
trackNameAttributeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
trackNameAttributeFieldFocusLost(e);
}
});
jPanel6.add(trackNameAttributeField);
trackNameAttributeField.setBounds(150, 115, 216, trackNameAttributeField.getPreferredSize().height);
//---- missingDataExplanation2 ----
missingDataExplanation2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation2.setText("<html>Name of an attribute to be used to label tracks. If provided tracks will be labeled with the corresponding attribute values from the sample information file");
missingDataExplanation2.setVerticalAlignment(SwingConstants.TOP);
jPanel6.add(missingDataExplanation2);
missingDataExplanation2.setBounds(40, 170, 578, 54);
//---- jLabel8 ----
jLabel8.setText("Default Track Height, Other (Pixels)");
jPanel6.add(jLabel8);
jLabel8.setBounds(new Rectangle(new Point(10, 45), jLabel8.getPreferredSize()));
//---- defaultTrackHeightField ----
defaultTrackHeightField.setText("15");
defaultTrackHeightField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultTrackHeightFieldActionPerformed(e);
}
});
defaultTrackHeightField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
defaultTrackHeightFieldFocusLost(e);
}
});
jPanel6.add(defaultTrackHeightField);
defaultTrackHeightField.setBounds(271, 39, 57, defaultTrackHeightField.getPreferredSize().height);
//---- missingDataExplanation4 ----
missingDataExplanation4.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation4.setText("<html>Default height of chart tracks (barcharts, scatterplots, etc)");
jPanel6.add(missingDataExplanation4);
missingDataExplanation4.setBounds(350, 5, 354, 25);
//---- missingDataExplanation5 ----
missingDataExplanation5.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation5.setText("<html>Default height of all other tracks");
jPanel6.add(missingDataExplanation5);
missingDataExplanation5.setBounds(350, 41, 1141, 25);
//---- missingDataExplanation3 ----
missingDataExplanation3.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation3.setText("<html><i> If selected feature tracks are expanded by default.");
jPanel6.add(missingDataExplanation3);
missingDataExplanation3.setBounds(new Rectangle(new Point(876, 318), missingDataExplanation3.getPreferredSize()));
//---- expandCB ----
expandCB.setText("Expand Feature Tracks");
expandCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandCBActionPerformed(e);
}
});
jPanel6.add(expandCB);
expandCB.setBounds(new Rectangle(new Point(6, 272), expandCB.getPreferredSize()));
//---- normalizeCoverageCB ----
normalizeCoverageCB.setText("Normalize Coverage Data");
normalizeCoverageCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalizeCoverageCBActionPerformed(e);
}
});
normalizeCoverageCB.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
normalizeCoverageCBFocusLost(e);
}
});
jPanel6.add(normalizeCoverageCB);
normalizeCoverageCB.setBounds(new Rectangle(new Point(6, 372), normalizeCoverageCB.getPreferredSize()));
//---- missingDataExplanation8 ----
missingDataExplanation8.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation8.setText("<html><i> Applies to coverage tracks computed with igvtools (.tdf files). If selected coverage values are scaled by (1,000,000 / totalCount), where totalCount is the total number of features or alignments.");
missingDataExplanation8.setVerticalAlignment(SwingConstants.TOP);
jPanel6.add(missingDataExplanation8);
missingDataExplanation8.setBounds(50, 413, 608, 52);
//---- expandIconCB ----
expandIconCB.setText("Show Expand Icon");
expandIconCB.setToolTipText("If checked displays an expand/collapse icon on feature tracks.");
expandIconCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandIconCBActionPerformed(e);
}
});
jPanel6.add(expandIconCB);
expandIconCB.setBounds(new Rectangle(new Point(6, 318), expandIconCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel6.getComponentCount(); i++) {
Rectangle bounds = jPanel6.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel6.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel6.setMinimumSize(preferredSize);
jPanel6.setPreferredSize(preferredSize);
}
}
tracksPanel.add(jPanel6);
jPanel6.setBounds(40, 20, 725, 480);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < tracksPanel.getComponentCount(); i++) {
Rectangle bounds = tracksPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = tracksPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
tracksPanel.setMinimumSize(preferredSize);
tracksPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Tracks", tracksPanel);
//======== overlaysPanel ========
{
//======== jPanel5 ========
{
jPanel5.setLayout(null);
//---- jLabel3 ----
jLabel3.setText("Sample attribute column:");
jPanel5.add(jLabel3);
jLabel3.setBounds(new Rectangle(new Point(65, 86), jLabel3.getPreferredSize()));
//---- overlayAttributeTextField ----
overlayAttributeTextField.setText("LINKING_ID");
overlayAttributeTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayAttributeTextFieldActionPerformed(e);
}
});
overlayAttributeTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
overlayAttributeTextFieldFocusLost(e);
}
});
overlayAttributeTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
overlayAttributeTextFieldKeyTyped(e);
}
});
jPanel5.add(overlayAttributeTextField);
overlayAttributeTextField.setBounds(229, 80, 228, overlayAttributeTextField.getPreferredSize().height);
//---- overlayTrackCB ----
overlayTrackCB.setSelected(true);
overlayTrackCB.setText("Overlay mutation tracks");
overlayTrackCB.setActionCommand("overlayTracksCB");
overlayTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayTrackCBActionPerformed(e);
}
});
jPanel5.add(overlayTrackCB);
overlayTrackCB.setBounds(new Rectangle(new Point(6, 51), overlayTrackCB.getPreferredSize()));
//---- jLabel2 ----
jLabel2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
jPanel5.add(jLabel2);
jLabel2.setBounds(new Rectangle(new Point(6, 6), jLabel2.getPreferredSize()));
//---- displayTracksCB ----
displayTracksCB.setText("Display mutation data as distinct tracks");
displayTracksCB.setActionCommand("displayTracksCB");
displayTracksCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayTracksCBActionPerformed(e);
}
});
jPanel5.add(displayTracksCB);
displayTracksCB.setBounds(new Rectangle(new Point(5, 230), displayTracksCB.getPreferredSize()));
//---- jLabel4 ----
jLabel4.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
jPanel5.add(jLabel4);
jLabel4.setBounds(new Rectangle(new Point(6, 12), jLabel4.getPreferredSize()));
//---- colorOverlyCB ----
colorOverlyCB.setText("Color code overlay");
colorOverlyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorOverlyCBActionPerformed(e);
}
});
jPanel5.add(colorOverlyCB);
colorOverlyCB.setBounds(new Rectangle(new Point(65, 114), colorOverlyCB.getPreferredSize()));
//---- chooseOverlayColorsButton ----
chooseOverlayColorsButton.setForeground(new Color(0, 0, 247));
chooseOverlayColorsButton.setText("Choose colors");
chooseOverlayColorsButton.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
chooseOverlayColorsButton.setVerticalAlignment(SwingConstants.BOTTOM);
chooseOverlayColorsButton.setVerticalTextPosition(SwingConstants.BOTTOM);
chooseOverlayColorsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooseOverlayColorsButtonActionPerformed(e);
}
});
jPanel5.add(chooseOverlayColorsButton);
chooseOverlayColorsButton.setBounds(new Rectangle(new Point(220, 116), chooseOverlayColorsButton.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel5.getComponentCount(); i++) {
Rectangle bounds = jPanel5.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel5.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel5.setMinimumSize(preferredSize);
jPanel5.setPreferredSize(preferredSize);
}
}
GroupLayout overlaysPanelLayout = new GroupLayout(overlaysPanel);
overlaysPanel.setLayout(overlaysPanelLayout);
overlaysPanelLayout.setHorizontalGroup(
overlaysPanelLayout.createParallelGroup()
.add(overlaysPanelLayout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel5, GroupLayout.PREFERRED_SIZE, 673, GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
);
overlaysPanelLayout.setVerticalGroup(
overlaysPanelLayout.createParallelGroup()
.add(overlaysPanelLayout.createSequentialGroup()
.add(55, 55, 55)
.add(jPanel5, GroupLayout.PREFERRED_SIZE, 394, GroupLayout.PREFERRED_SIZE)
.addContainerGap(117, Short.MAX_VALUE))
);
}
tabbedPane.addTab("Mutations", overlaysPanel);
//======== chartPanel ========
{
chartPanel.setLayout(null);
//======== jPanel4 ========
{
//---- topBorderCB ----
topBorderCB.setText("Draw Top Border");
topBorderCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
topBorderCBActionPerformed(e);
}
});
//---- label1 ----
label1.setFont(label1.getFont());
label1.setText("Default settings for barcharts and scatterplots:");
//---- chartDrawTrackNameCB ----
chartDrawTrackNameCB.setText("Draw Track Label");
chartDrawTrackNameCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chartDrawTrackNameCBActionPerformed(e);
}
});
//---- bottomBorderCB ----
bottomBorderCB.setText("Draw Bottom Border");
bottomBorderCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bottomBorderCBActionPerformed(e);
}
});
//---- jLabel7 ----
jLabel7.setText("<html><i>If selected charts are dynamically rescaled to the range of the data in view.");
//---- colorBordersCB ----
colorBordersCB.setText("Color Borders");
colorBordersCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorBordersCBActionPerformed(e);
}
});
//---- labelYAxisCB ----
labelYAxisCB.setText("Label Y Axis");
labelYAxisCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
labelYAxisCBActionPerformed(e);
}
});
//---- autoscaleCB ----
autoscaleCB.setText("Continuous Autoscale");
autoscaleCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
autoscaleCBActionPerformed(e);
}
});
//---- jLabel9 ----
jLabel9.setText("<html><i>Draw a label centered over the track provided<br>the track height is at least 25 pixels. ");
//---- showDatarangeCB ----
showDatarangeCB.setText("Show Data Range");
showDatarangeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showDatarangeCBActionPerformed(e);
}
});
showDatarangeCB.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
showDatarangeCBFocusLost(e);
}
});
GroupLayout jPanel4Layout = new GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(221, Short.MAX_VALUE)
.add(jLabel9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(84, 84, 84)))
.add(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel4Layout.createParallelGroup()
.add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(jPanel4Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createSequentialGroup()
.add(jPanel4Layout.createParallelGroup()
.add(autoscaleCB)
.add(showDatarangeCB))
.add(18, 18, 18)
.add(jLabel7, GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))
.add(jPanel4Layout.createSequentialGroup()
.add(jPanel4Layout.createParallelGroup()
.add(topBorderCB)
.add(colorBordersCB)
.add(bottomBorderCB)
.add(labelYAxisCB)
.add(chartDrawTrackNameCB))
.addPreferredGap(LayoutStyle.RELATED, 403, Short.MAX_VALUE)))))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createSequentialGroup()
.add(131, 131, 131)
.add(jLabel9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(181, Short.MAX_VALUE)))
.add(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(topBorderCB)
.addPreferredGap(LayoutStyle.RELATED)
.add(bottomBorderCB)
.add(7, 7, 7)
.add(colorBordersCB)
.add(18, 18, 18)
.add(chartDrawTrackNameCB)
.add(23, 23, 23)
.add(labelYAxisCB)
.add(18, 18, 18)
.add(jPanel4Layout.createParallelGroup(GroupLayout.BASELINE)
.add(autoscaleCB)
.add(jLabel7, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(showDatarangeCB)
.add(36, 36, 36))
);
}
chartPanel.add(jPanel4);
jPanel4.setBounds(20, 30, 590, 340);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < chartPanel.getComponentCount(); i++) {
Rectangle bounds = chartPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = chartPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
chartPanel.setMinimumSize(preferredSize);
chartPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Charts", chartPanel);
//======== alignmentPanel ========
{
alignmentPanel.setLayout(null);
//======== jPanel1 ========
{
jPanel1.setLayout(null);
//======== jPanel11 ========
{
jPanel11.setBorder(null);
jPanel11.setLayout(null);
//---- samMaxDepthField ----
samMaxDepthField.setText("jTextField1");
samMaxDepthField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxLevelFieldActionPerformed(e);
}
});
samMaxDepthField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxLevelFieldFocusLost(e);
}
});
jPanel11.add(samMaxDepthField);
samMaxDepthField.setBounds(new Rectangle(new Point(206, 40), samMaxDepthField.getPreferredSize()));
//---- jLabel11 ----
jLabel11.setText("Visibility range threshold (kb)");
jPanel11.add(jLabel11);
jLabel11.setBounds(new Rectangle(new Point(6, 12), jLabel11.getPreferredSize()));
//---- jLabel16 ----
jLabel16.setText("<html><i>Reads with qualities below the threshold are not shown.");
jPanel11.add(jLabel16);
jLabel16.setBounds(new Rectangle(new Point(296, 80), jLabel16.getPreferredSize()));
//---- mappingQualityThresholdField ----
mappingQualityThresholdField.setText("0");
mappingQualityThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mappingQualityThresholdFieldActionPerformed(e);
}
});
mappingQualityThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
mappingQualityThresholdFieldFocusLost(e);
}
});
jPanel11.add(mappingQualityThresholdField);
mappingQualityThresholdField.setBounds(206, 74, 84, mappingQualityThresholdField.getPreferredSize().height);
//---- jLabel14 ----
jLabel14.setText("<html><i>Maximum read depth to load (approximate).");
jPanel11.add(jLabel14);
jLabel14.setBounds(296, 39, 390, 30);
//---- jLabel13 ----
jLabel13.setText("Maximum read depth:");
jPanel11.add(jLabel13);
jLabel13.setBounds(new Rectangle(new Point(6, 46), jLabel13.getPreferredSize()));
//---- jLabel15 ----
jLabel15.setText("Mapping quality threshold:");
jPanel11.add(jLabel15);
jLabel15.setBounds(new Rectangle(new Point(6, 80), jLabel15.getPreferredSize()));
//---- samMaxWindowSizeField ----
samMaxWindowSizeField.setText("jTextField1");
samMaxWindowSizeField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxWindowSizeFieldActionPerformed(e);
}
});
samMaxWindowSizeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxWindowSizeFieldFocusLost(e);
}
});
jPanel11.add(samMaxWindowSizeField);
samMaxWindowSizeField.setBounds(new Rectangle(new Point(206, 6), samMaxWindowSizeField.getPreferredSize()));
//---- jLabel12 ----
jLabel12.setText("<html><i>Nominal window size at which alignments become visible");
jPanel11.add(jLabel12);
jLabel12.setBounds(new Rectangle(new Point(296, 12), jLabel12.getPreferredSize()));
//---- jLabel26 ----
jLabel26.setText("Coverage allele-freq threshold");
jPanel11.add(jLabel26);
jLabel26.setBounds(6, 114, 200, jLabel26.getPreferredSize().height);
//---- snpThresholdField ----
snpThresholdField.setText("0");
snpThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snpThresholdFieldActionPerformed(e);
}
});
snpThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
snpThresholdFieldFocusLost(e);
}
});
jPanel11.add(snpThresholdField);
snpThresholdField.setBounds(206, 108, 84, snpThresholdField.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel11.getComponentCount(); i++) {
Rectangle bounds = jPanel11.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel11.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel11.setMinimumSize(preferredSize);
jPanel11.setPreferredSize(preferredSize);
}
}
jPanel1.add(jPanel11);
jPanel11.setBounds(5, 10, 755, 150);
//======== jPanel12 ========
{
jPanel12.setBorder(null);
jPanel12.setLayout(null);
//---- samMinBaseQualityField ----
samMinBaseQualityField.setText("0");
samMinBaseQualityField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMinBaseQualityFieldActionPerformed(e);
}
});
samMinBaseQualityField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMinBaseQualityFieldFocusLost(e);
}
});
jPanel12.add(samMinBaseQualityField);
samMinBaseQualityField.setBounds(380, 105, 50, samMinBaseQualityField.getPreferredSize().height);
//---- samShadeMismatchedBaseCB ----
samShadeMismatchedBaseCB.setText("Shade mismatched bases by quality. ");
samShadeMismatchedBaseCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samShadeMismatchedBaseCBActionPerformed(e);
}
});
jPanel12.add(samShadeMismatchedBaseCB);
samShadeMismatchedBaseCB.setBounds(6, 109, 264, samShadeMismatchedBaseCB.getPreferredSize().height);
//---- samMaxBaseQualityField ----
samMaxBaseQualityField.setText("0");
samMaxBaseQualityField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxBaseQualityFieldActionPerformed(e);
}
});
samMaxBaseQualityField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxBaseQualityFieldFocusLost(e);
}
});
jPanel12.add(samMaxBaseQualityField);
samMaxBaseQualityField.setBounds(505, 105, 50, samMaxBaseQualityField.getPreferredSize().height);
//---- showCovTrackCB ----
showCovTrackCB.setText("Show coverage track");
showCovTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCovTrackCBActionPerformed(e);
}
});
jPanel12.add(showCovTrackCB);
showCovTrackCB.setBounds(375, 10, 270, showCovTrackCB.getPreferredSize().height);
//---- samFilterDuplicatesCB ----
samFilterDuplicatesCB.setText("Filter duplicate reads");
samFilterDuplicatesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samShowDuplicatesCBActionPerformed(e);
}
});
jPanel12.add(samFilterDuplicatesCB);
samFilterDuplicatesCB.setBounds(6, 10, 290, samFilterDuplicatesCB.getPreferredSize().height);
//---- jLabel19 ----
jLabel19.setText("Min: ");
jPanel12.add(jLabel19);
jLabel19.setBounds(new Rectangle(new Point(340, 110), jLabel19.getPreferredSize()));
//---- filterCB ----
filterCB.setText("Filter alignments by read group");
filterCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterCBActionPerformed(e);
}
});
jPanel12.add(filterCB);
filterCB.setBounds(6, 142, 244, filterCB.getPreferredSize().height);
//---- filterURL ----
filterURL.setText("URL or path to filter file");
filterURL.setEnabled(false);
filterURL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterURLActionPerformed(e);
}
});
filterURL.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
filterURLFocusLost(e);
}
});
jPanel12.add(filterURL);
filterURL.setBounds(275, 140, 440, filterURL.getPreferredSize().height);
//---- samFlagUnmappedPairCB ----
samFlagUnmappedPairCB.setText("Flag unmapped pairs");
samFlagUnmappedPairCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samFlagUnmappedPairCBActionPerformed(e);
}
});
jPanel12.add(samFlagUnmappedPairCB);
samFlagUnmappedPairCB.setBounds(6, 76, 310, samFlagUnmappedPairCB.getPreferredSize().height);
//---- filterFailedReadsCB ----
filterFailedReadsCB.setText("Filter vendor failed reads");
filterFailedReadsCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterVendorFailedReadsCBActionPerformed(e);
}
});
jPanel12.add(filterFailedReadsCB);
filterFailedReadsCB.setBounds(new Rectangle(new Point(6, 43), filterFailedReadsCB.getPreferredSize()));
//---- label2 ----
label2.setText("Max:");
jPanel12.add(label2);
label2.setBounds(new Rectangle(new Point(455, 110), label2.getPreferredSize()));
//---- showSoftClippedCB ----
showSoftClippedCB.setText("Show soft-clipped bases");
showSoftClippedCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showSoftClippedCBActionPerformed(e);
}
});
jPanel12.add(showSoftClippedCB);
showSoftClippedCB.setBounds(new Rectangle(new Point(375, 76), showSoftClippedCB.getPreferredSize()));
//---- showJunctionTrackCB ----
showJunctionTrackCB.setText("Show splice junction track");
showJunctionTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showJunctionTrackCBActionPerformed(e);
}
});
jPanel12.add(showJunctionTrackCB);
showJunctionTrackCB.setBounds(new Rectangle(new Point(375, 43), showJunctionTrackCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel12.getComponentCount(); i++) {
Rectangle bounds = jPanel12.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel12.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel12.setMinimumSize(preferredSize);
jPanel12.setPreferredSize(preferredSize);
}
}
jPanel1.add(jPanel12);
jPanel12.setBounds(5, 145, 755, 175);
//======== panel2 ========
{
panel2.setBorder(new TitledBorder("Insert Size Options"));
panel2.setLayout(null);
//---- isizeComputeCB ----
isizeComputeCB.setText("Compute");
isizeComputeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isizeComputeCBActionPerformed(e);
isizeComputeCBActionPerformed(e);
isizeComputeCBActionPerformed(e);
}
});
panel2.add(isizeComputeCB);
isizeComputeCB.setBounds(new Rectangle(new Point(360, 76), isizeComputeCB.getPreferredSize()));
//---- jLabel17 ----
jLabel17.setText("Maximum (bp):");
panel2.add(jLabel17);
jLabel17.setBounds(100, 110, 110, jLabel17.getPreferredSize().height);
//---- insertSizeMinThresholdField ----
insertSizeMinThresholdField.setText("0");
insertSizeMinThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
}
});
insertSizeMinThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMinThresholdFieldFocusLost(e);
}
});
panel2.add(insertSizeMinThresholdField);
insertSizeMinThresholdField.setBounds(220, 75, 84, 28);
//---- jLabel20 ----
jLabel20.setText("Minimum (bp):");
panel2.add(jLabel20);
jLabel20.setBounds(100, 80, 110, 16);
//---- insertSizeThresholdField ----
insertSizeThresholdField.setText("0");
insertSizeThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeThresholdFieldActionPerformed(e);
}
});
insertSizeThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
}
});
panel2.add(insertSizeThresholdField);
insertSizeThresholdField.setBounds(220, 105, 84, insertSizeThresholdField.getPreferredSize().height);
//---- jLabel30 ----
jLabel30.setText("Minimum (percentile):");
panel2.add(jLabel30);
jLabel30.setBounds(460, 80, 155, 16);
//---- jLabel18 ----
jLabel18.setText("Maximum (percentile):");
panel2.add(jLabel18);
jLabel18.setBounds(460, 110, 155, 16);
//---- insertSizeMinPercentileField ----
insertSizeMinPercentileField.setText("0");
insertSizeMinPercentileField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinPercentileFieldActionPerformed(e);
}
});
insertSizeMinPercentileField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMinThresholdFieldFocusLost(e);
insertSizeMinPercentileFieldFocusLost(e);
}
});
panel2.add(insertSizeMinPercentileField);
insertSizeMinPercentileField.setBounds(625, 75, 84, 28);
//---- insertSizeMaxPercentileField ----
insertSizeMaxPercentileField.setText("0");
insertSizeMaxPercentileField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeThresholdFieldActionPerformed(e);
insertSizeMaxPercentileFieldActionPerformed(e);
}
});
insertSizeMaxPercentileField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMaxPercentileFieldFocusLost(e);
}
});
panel2.add(insertSizeMaxPercentileField);
insertSizeMaxPercentileField.setBounds(625, 105, 84, 28);
//---- label8 ----
label8.setText("<html><i>These options control the color coding of paired alignments by inferred insert size. Base pair values set default values. If \"compute\" is selected values are computed from the actual size distribution of each library.");
panel2.add(label8);
label8.setBounds(5, 15, 735, 55);
//---- label9 ----
label9.setText("Defaults ");
panel2.add(label9);
label9.setBounds(new Rectangle(new Point(15, 80), label9.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel2.getComponentCount(); i++) {
Rectangle bounds = panel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel2.setMinimumSize(preferredSize);
panel2.setPreferredSize(preferredSize);
}
}
jPanel1.add(panel2);
panel2.setBounds(5, 350, 755, 145);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel1.getComponentCount(); i++) {
Rectangle bounds = jPanel1.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel1.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel1.setMinimumSize(preferredSize);
jPanel1.setPreferredSize(preferredSize);
}
}
alignmentPanel.add(jPanel1);
jPanel1.setBounds(0, 0, 760, 510);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < alignmentPanel.getComponentCount(); i++) {
Rectangle bounds = alignmentPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = alignmentPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
alignmentPanel.setMinimumSize(preferredSize);
alignmentPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Alignments", alignmentPanel);
//======== expressionPane ========
{
expressionPane.setLayout(null);
//======== jPanel8 ========
{
//---- expMapToGeneCB ----
expMapToGeneCB.setText("Map probes to genes");
expMapToGeneCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expMapToGeneCBActionPerformed(e);
}
});
//---- jLabel24 ----
jLabel24.setText("Expression probe mapping options: ");
//---- expMapToLociCB ----
expMapToLociCB.setText("<html>Map probes to target loci");
expMapToLociCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expMapToLociCBActionPerformed(e);
}
});
//---- jLabel21 ----
jLabel21.setText("<html><i>Note: Changes will not affect currently loaded datasets.");
GroupLayout jPanel8Layout = new GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(45, 45, 45)
.add(jPanel8Layout.createParallelGroup()
.add(expMapToLociCB, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(expMapToGeneCB)))
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(24, 24, 24)
.add(jLabel21, GroupLayout.PREFERRED_SIZE, 497, GroupLayout.PREFERRED_SIZE))
.add(jLabel24))))
.addContainerGap(193, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel24)
.addPreferredGap(LayoutStyle.RELATED)
.add(jLabel21, GroupLayout.PREFERRED_SIZE, 44, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(expMapToLociCB, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(14, 14, 14)
.add(expMapToGeneCB)
.addContainerGap(172, Short.MAX_VALUE))
);
}
expressionPane.add(jPanel8);
jPanel8.setBounds(10, 30, 720, 310);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < expressionPane.getComponentCount(); i++) {
Rectangle bounds = expressionPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = expressionPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
expressionPane.setMinimumSize(preferredSize);
expressionPane.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Probes", expressionPane);
//======== advancedPanel ========
{
advancedPanel.setBorder(new EmptyBorder(1, 10, 1, 10));
advancedPanel.setLayout(null);
//======== jPanel3 ========
{
//======== jPanel2 ========
{
jPanel2.setLayout(null);
//---- jLabel1 ----
jLabel1.setText("Genome Server URL");
jPanel2.add(jLabel1);
jLabel1.setBounds(new Rectangle(new Point(35, 47), jLabel1.getPreferredSize()));
//---- genomeServerURLTextField ----
genomeServerURLTextField.setText("jTextField1");
genomeServerURLTextField.setEnabled(false);
genomeServerURLTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
genomeServerURLTextFieldActionPerformed(e);
}
});
genomeServerURLTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
genomeServerURLTextFieldFocusLost(e);
}
});
jPanel2.add(genomeServerURLTextField);
genomeServerURLTextField.setBounds(191, 41, 494, genomeServerURLTextField.getPreferredSize().height);
//---- jLabel6 ----
jLabel6.setText("Data Registry URL");
jPanel2.add(jLabel6);
jLabel6.setBounds(new Rectangle(new Point(35, 81), jLabel6.getPreferredSize()));
//---- dataServerURLTextField ----
dataServerURLTextField.setEnabled(false);
dataServerURLTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dataServerURLTextFieldActionPerformed(e);
}
});
dataServerURLTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
dataServerURLTextFieldFocusLost(e);
}
});
jPanel2.add(dataServerURLTextField);
dataServerURLTextField.setBounds(191, 75, 494, dataServerURLTextField.getPreferredSize().height);
//---- editServerPropertiesCB ----
editServerPropertiesCB.setText("Edit server properties");
editServerPropertiesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editServerPropertiesCBActionPerformed(e);
}
});
jPanel2.add(editServerPropertiesCB);
editServerPropertiesCB.setBounds(new Rectangle(new Point(6, 7), editServerPropertiesCB.getPreferredSize()));
//---- jButton1 ----
jButton1.setText("Reset to Defaults");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});
jPanel2.add(jButton1);
jButton1.setBounds(new Rectangle(new Point(190, 6), jButton1.getPreferredSize()));
//---- clearGenomeCacheButton ----
clearGenomeCacheButton.setText("Clear Genome Cache");
clearGenomeCacheButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearGenomeCacheButtonActionPerformed(e);
}
});
jPanel2.add(clearGenomeCacheButton);
clearGenomeCacheButton.setBounds(new Rectangle(new Point(6, 155), clearGenomeCacheButton.getPreferredSize()));
//---- genomeUpdateCB ----
genomeUpdateCB.setText("<html>Automatically check for updated genomes. <i>Most users should leave this checked.");
genomeUpdateCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
genomeUpdateCBActionPerformed(e);
}
});
jPanel2.add(genomeUpdateCB);
genomeUpdateCB.setBounds(new Rectangle(new Point(14, 121), genomeUpdateCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel2.getComponentCount(); i++) {
Rectangle bounds = jPanel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel2.setMinimumSize(preferredSize);
jPanel2.setPreferredSize(preferredSize);
}
}
//======== jPanel7 ========
{
//---- enablePortCB ----
enablePortCB.setText("Enable port");
enablePortCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enablePortCBActionPerformed(e);
}
});
//---- portField ----
portField.setText("60151");
portField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
portFieldActionPerformed(e);
}
});
portField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
portFieldFocusLost(e);
}
});
//---- jLabel22 ----
jLabel22.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
jLabel22.setText("Enable port to send commands and http requests to IGV. ");
GroupLayout jPanel7Layout = new GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.add(jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.add(enablePortCB)
.add(39, 39, 39)
.add(portField, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE))
.add(jPanel7Layout.createSequentialGroup()
.add(48, 48, 48)
.add(jLabel22)))
.addContainerGap(330, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel7Layout.createParallelGroup(GroupLayout.CENTER)
.add(enablePortCB)
.add(portField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(jLabel22)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}
GroupLayout jPanel3Layout = new GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup()
.add(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel3Layout.createParallelGroup()
.add(jPanel7, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup()
.add(jPanel3Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel7, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED, 36, Short.MAX_VALUE)
.add(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
);
}
advancedPanel.add(jPanel3);
jPanel3.setBounds(10, 0, 750, 330);
//======== jPanel9 ========
{
//---- useByteRangeCB ----
useByteRangeCB.setText("Use http byte-range requests");
useByteRangeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
useByteRangeCBActionPerformed(e);
}
});
//---- jLabel25 ----
jLabel25.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
jLabel25.setText("<html>This option applies to certain \"Load from Server...\" tracks hosted at the Broad. Disable this option if you are unable to load the phastCons conservation track under the hg18 annotations.");
GroupLayout jPanel9Layout = new GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup()
.add(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel9Layout.createParallelGroup()
.add(jPanel9Layout.createSequentialGroup()
.add(38, 38, 38)
.add(jLabel25, GroupLayout.PREFERRED_SIZE, 601, GroupLayout.PREFERRED_SIZE))
.add(useByteRangeCB))
.addContainerGap(65, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel9Layout.createSequentialGroup()
.add(59, 59, 59)
.add(useByteRangeCB, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(jLabel25)
.addContainerGap())
);
}
advancedPanel.add(jPanel9);
jPanel9.setBounds(30, 340, 710, 120);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < advancedPanel.getComponentCount(); i++) {
Rectangle bounds = advancedPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = advancedPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
advancedPanel.setMinimumSize(preferredSize);
advancedPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Advanced", advancedPanel);
//======== proxyPanel ========
{
proxyPanel.setLayout(new BoxLayout(proxyPanel, BoxLayout.X_AXIS));
//======== jPanel15 ========
{
//======== jPanel16 ========
{
//---- proxyUsernameField ----
proxyUsernameField.setText("jTextField1");
proxyUsernameField.setEnabled(false);
proxyUsernameField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyUsernameFieldActionPerformed(e);
}
});
proxyUsernameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyUsernameFieldFocusLost(e);
}
});
//---- jLabel28 ----
jLabel28.setText("Username");
//---- authenticateProxyCB ----
authenticateProxyCB.setText("Authentication required");
authenticateProxyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
authenticateProxyCBActionPerformed(e);
}
});
//---- jLabel29 ----
jLabel29.setText("Password");
//---- proxyPasswordField ----
proxyPasswordField.setText("jPasswordField1");
proxyPasswordField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyPasswordFieldFocusLost(e);
}
});
GroupLayout jPanel16Layout = new GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel16Layout.createParallelGroup()
.add(jLabel28)
.add(jLabel29))
.add(37, 37, 37)
.add(jPanel16Layout.createParallelGroup(GroupLayout.LEADING, false)
.add(proxyPasswordField)
.add(proxyUsernameField, GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)))
.add(jPanel16Layout.createSequentialGroup()
.addContainerGap()
.add(authenticateProxyCB)))
.addContainerGap(381, Short.MAX_VALUE))
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(17, 17, 17)
.add(authenticateProxyCB)
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel16Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel28)
.add(proxyUsernameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel16Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel29)
.add(proxyPasswordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(70, Short.MAX_VALUE))
);
}
//======== jPanel17 ========
{
//---- proxyHostField ----
proxyHostField.setText("jTextField1");
proxyHostField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyHostFieldActionPerformed(e);
}
});
proxyHostField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyHostFieldFocusLost(e);
}
});
//---- proxyPortField ----
proxyPortField.setText("jTextField1");
proxyPortField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyPortFieldActionPerformed(e);
}
});
proxyPortField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyPortFieldFocusLost(e);
}
});
//---- jLabel27 ----
jLabel27.setText("Proxy port");
//---- jLabel23 ----
jLabel23.setText("Proxy host");
//---- useProxyCB ----
useProxyCB.setText("Use proxy");
useProxyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
useProxyCBActionPerformed(e);
}
});
GroupLayout jPanel17Layout = new GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup()
.add(jPanel17Layout.createSequentialGroup()
.add(jPanel17Layout.createParallelGroup()
.add(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel17Layout.createParallelGroup()
.add(jLabel27)
.add(jLabel23))
.add(28, 28, 28)
.add(jPanel17Layout.createParallelGroup()
.add(proxyPortField, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
.add(proxyHostField, GroupLayout.PREFERRED_SIZE, 485, GroupLayout.PREFERRED_SIZE)))
.add(jPanel17Layout.createSequentialGroup()
.add(9, 9, 9)
.add(useProxyCB)))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel17Layout.createSequentialGroup()
.addContainerGap(29, Short.MAX_VALUE)
.add(useProxyCB)
.add(18, 18, 18)
.add(jPanel17Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel23)
.add(proxyHostField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel17Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel27)
.add(proxyPortField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
}
//---- label3 ----
label3.setText("<html>Note: do not use these settings unless you receive error or warning messages about server connections. On most systems the correct settings will be automatically copied from your web browser.");
//---- clearProxySettingsButton ----
clearProxySettingsButton.setText("Clear All");
clearProxySettingsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearProxySettingsButtonActionPerformed(e);
}
});
GroupLayout jPanel15Layout = new GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.add(jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.add(22, 22, 22)
.add(label3, GroupLayout.PREFERRED_SIZE, 630, GroupLayout.PREFERRED_SIZE))
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15Layout.createParallelGroup()
.add(jPanel16, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel17, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(clearProxySettingsButton)))
.addContainerGap())
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(label3, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel17, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(jPanel16, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(clearProxySettingsButton)
.addContainerGap(110, Short.MAX_VALUE))
);
}
proxyPanel.add(jPanel15);
}
tabbedPane.addTab("Proxy", proxyPanel);
}
contentPane.add(tabbedPane, BorderLayout.CENTER);
//======== okCancelButtonPanel ========
{
//---- okButton ----
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonActionPerformed(e);
}
});
okCancelButtonPanel.add(okButton);
//---- cancelButton ----
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButtonActionPerformed(e);
}
});
okCancelButtonPanel.add(cancelButton);
}
contentPane.add(okCancelButtonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(getOwner());
//---- buttonGroup1 ----
ButtonGroup buttonGroup1 = new ButtonGroup();
buttonGroup1.add(expMapToGeneCB);
buttonGroup1.add(expMapToLociCB);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
tabbedPane = new JTabbedPane();
generalPanel = new JPanel();
jPanel10 = new JPanel();
missingDataExplanation = new JLabel();
showMissingDataCB = new JCheckBox();
combinePanelsCB = new JCheckBox();
showAttributesDisplayCheckBox = new JCheckBox();
searchZoomCB = new JCheckBox();
zoomToFeatureExplanation = new JLabel();
label4 = new JLabel();
geneListFlankingField = new JTextField();
zoomToFeatureExplanation2 = new JLabel();
label5 = new JLabel();
label6 = new JLabel();
seqResolutionThreshold = new JTextField();
label10 = new JLabel();
defaultFontField = new JTextField();
fontChangeButton = new JButton();
showRegionBoundariesCB = new JCheckBox();
label7 = new JLabel();
backgroundColorPanel = new JPanel();
resetBackgroundButton = new JButton();
tracksPanel = new JPanel();
jPanel6 = new JPanel();
jLabel5 = new JLabel();
defaultChartTrackHeightField = new JTextField();
trackNameAttributeLabel = new JLabel();
trackNameAttributeField = new JTextField();
missingDataExplanation2 = new JLabel();
jLabel8 = new JLabel();
defaultTrackHeightField = new JTextField();
missingDataExplanation4 = new JLabel();
missingDataExplanation5 = new JLabel();
missingDataExplanation3 = new JLabel();
expandCB = new JCheckBox();
normalizeCoverageCB = new JCheckBox();
missingDataExplanation8 = new JLabel();
expandIconCB = new JCheckBox();
overlaysPanel = new JPanel();
jPanel5 = new JPanel();
jLabel3 = new JLabel();
overlayAttributeTextField = new JTextField();
overlayTrackCB = new JCheckBox();
jLabel2 = new JLabel();
displayTracksCB = new JCheckBox();
jLabel4 = new JLabel();
colorOverlyCB = new JCheckBox();
chooseOverlayColorsButton = new JideButton();
chartPanel = new JPanel();
jPanel4 = new JPanel();
topBorderCB = new JCheckBox();
label1 = new Label();
chartDrawTrackNameCB = new JCheckBox();
bottomBorderCB = new JCheckBox();
jLabel7 = new JLabel();
colorBordersCB = new JCheckBox();
labelYAxisCB = new JCheckBox();
autoscaleCB = new JCheckBox();
jLabel9 = new JLabel();
showDatarangeCB = new JCheckBox();
alignmentPanel = new JPanel();
jPanel1 = new JPanel();
jPanel11 = new JPanel();
samMaxDepthField = new JTextField();
jLabel11 = new JLabel();
jLabel16 = new JLabel();
mappingQualityThresholdField = new JTextField();
jLabel14 = new JLabel();
jLabel13 = new JLabel();
jLabel15 = new JLabel();
samMaxWindowSizeField = new JTextField();
jLabel12 = new JLabel();
jLabel26 = new JLabel();
snpThresholdField = new JTextField();
jPanel12 = new JPanel();
samMinBaseQualityField = new JTextField();
samShadeMismatchedBaseCB = new JCheckBox();
samMaxBaseQualityField = new JTextField();
showCovTrackCB = new JCheckBox();
samFilterDuplicatesCB = new JCheckBox();
jLabel19 = new JLabel();
filterCB = new JCheckBox();
filterURL = new JTextField();
samFlagUnmappedPairCB = new JCheckBox();
filterFailedReadsCB = new JCheckBox();
label2 = new JLabel();
showSoftClippedCB = new JCheckBox();
showJunctionTrackCB = new JCheckBox();
panel2 = new JPanel();
isizeComputeCB = new JCheckBox();
jLabel17 = new JLabel();
insertSizeMinThresholdField = new JTextField();
jLabel20 = new JLabel();
insertSizeThresholdField = new JTextField();
jLabel30 = new JLabel();
jLabel18 = new JLabel();
insertSizeMinPercentileField = new JTextField();
insertSizeMaxPercentileField = new JTextField();
label8 = new JLabel();
label9 = new JLabel();
expressionPane = new JPanel();
jPanel8 = new JPanel();
expMapToGeneCB = new JRadioButton();
jLabel24 = new JLabel();
expMapToLociCB = new JRadioButton();
jLabel21 = new JLabel();
advancedPanel = new JPanel();
jPanel3 = new JPanel();
jPanel2 = new JPanel();
jLabel1 = new JLabel();
genomeServerURLTextField = new JTextField();
jLabel6 = new JLabel();
dataServerURLTextField = new JTextField();
editServerPropertiesCB = new JCheckBox();
jButton1 = new JButton();
clearGenomeCacheButton = new JButton();
genomeUpdateCB = new JCheckBox();
jPanel7 = new JPanel();
enablePortCB = new JCheckBox();
portField = new JTextField();
jLabel22 = new JLabel();
jPanel9 = new JPanel();
useByteRangeCB = new JCheckBox();
jLabel25 = new JLabel();
proxyPanel = new JPanel();
jPanel15 = new JPanel();
jPanel16 = new JPanel();
proxyUsernameField = new JTextField();
jLabel28 = new JLabel();
authenticateProxyCB = new JCheckBox();
jLabel29 = new JLabel();
proxyPasswordField = new JPasswordField();
jPanel17 = new JPanel();
proxyHostField = new JTextField();
proxyPortField = new JTextField();
jLabel27 = new JLabel();
jLabel23 = new JLabel();
useProxyCB = new JCheckBox();
label3 = new JLabel();
clearProxySettingsButton = new JButton();
okCancelButtonPanel = new ButtonPanel();
okButton = new JButton();
cancelButton = new JButton();
//======== this ========
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== tabbedPane ========
{
//======== generalPanel ========
{
generalPanel.setLayout(new BorderLayout());
//======== jPanel10 ========
{
jPanel10.setBorder(new BevelBorder(BevelBorder.RAISED));
jPanel10.setLayout(null);
//---- missingDataExplanation ----
missingDataExplanation.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation.setText("<html>Distinguish regions with zero values from regions with no data on plots <br>(e.g. bar charts). Regions with no data are indicated with a gray background.");
jPanel10.add(missingDataExplanation);
missingDataExplanation.setBounds(41, 35, 474, missingDataExplanation.getPreferredSize().height);
//---- showMissingDataCB ----
showMissingDataCB.setText("Distinguish Missing Data");
showMissingDataCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMissingDataCBActionPerformed(e);
}
});
jPanel10.add(showMissingDataCB);
showMissingDataCB.setBounds(new Rectangle(new Point(10, 6), showMissingDataCB.getPreferredSize()));
//---- combinePanelsCB ----
combinePanelsCB.setText("Combine Data and Feature Panels");
combinePanelsCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
combinePanelsCBActionPerformed(e);
}
});
jPanel10.add(combinePanelsCB);
combinePanelsCB.setBounds(new Rectangle(new Point(10, 95), combinePanelsCB.getPreferredSize()));
//---- showAttributesDisplayCheckBox ----
showAttributesDisplayCheckBox.setText("Show Attribute Display");
showAttributesDisplayCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAttributesDisplayCheckBoxActionPerformed(e);
}
});
jPanel10.add(showAttributesDisplayCheckBox);
showAttributesDisplayCheckBox.setBounds(new Rectangle(new Point(10, 130), showAttributesDisplayCheckBox.getPreferredSize()));
//---- searchZoomCB ----
searchZoomCB.setText("Zoom to features");
searchZoomCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchZoomCBActionPerformed(e);
}
});
jPanel10.add(searchZoomCB);
searchZoomCB.setBounds(new Rectangle(new Point(10, 205), searchZoomCB.getPreferredSize()));
//---- zoomToFeatureExplanation ----
zoomToFeatureExplanation.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
zoomToFeatureExplanation.setText("<html>This option controls the behavior of feature searchs. If true, the zoom level is changed as required to size the view to the feature size. If false the zoom level is unchanged.");
zoomToFeatureExplanation.setVerticalAlignment(SwingConstants.TOP);
jPanel10.add(zoomToFeatureExplanation);
zoomToFeatureExplanation.setBounds(50, 230, 644, 50);
//---- label4 ----
label4.setText("Feature flanking region (bp): ");
jPanel10.add(label4);
label4.setBounds(new Rectangle(new Point(15, 365), label4.getPreferredSize()));
//---- geneListFlankingField ----
geneListFlankingField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
geneListFlankingFieldFocusLost(e);
}
});
geneListFlankingField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
geneListFlankingFieldActionPerformed(e);
}
});
jPanel10.add(geneListFlankingField);
geneListFlankingField.setBounds(215, 360, 255, geneListFlankingField.getPreferredSize().height);
//---- zoomToFeatureExplanation2 ----
zoomToFeatureExplanation2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
zoomToFeatureExplanation2.setText("<html><i>Added before and after feature locus when zooming to a feature. Also used when defining panel extents in gene/loci list views.");
zoomToFeatureExplanation2.setVerticalAlignment(SwingConstants.TOP);
jPanel10.add(zoomToFeatureExplanation2);
zoomToFeatureExplanation2.setBounds(45, 395, 637, 50);
//---- label5 ----
label5.setText("<html><i>Resolution in base-pairs per pixel at which sequence track becomes visible. ");
label5.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
jPanel10.add(label5);
label5.setBounds(new Rectangle(new Point(50, 320), label5.getPreferredSize()));
//---- label6 ----
label6.setText("Sequence Resolution Threshold (bp/pixel):");
jPanel10.add(label6);
label6.setBounds(new Rectangle(new Point(15, 290), label6.getPreferredSize()));
//---- seqResolutionThreshold ----
seqResolutionThreshold.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
seqResolutionThresholdFocusLost(e);
}
});
seqResolutionThreshold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seqResolutionThresholdActionPerformed(e);
}
});
jPanel10.add(seqResolutionThreshold);
seqResolutionThreshold.setBounds(315, 285, 105, seqResolutionThreshold.getPreferredSize().height);
//---- label10 ----
label10.setText("Default font: ");
label10.setLabelFor(defaultFontField);
jPanel10.add(label10);
label10.setBounds(new Rectangle(new Point(15, 530), label10.getPreferredSize()));
//---- defaultFontField ----
defaultFontField.setEditable(false);
jPanel10.add(defaultFontField);
defaultFontField.setBounds(105, 525, 238, defaultFontField.getPreferredSize().height);
//---- fontChangeButton ----
fontChangeButton.setText("Change...");
fontChangeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontChangeButtonActionPerformed(e);
}
});
jPanel10.add(fontChangeButton);
fontChangeButton.setBounds(360, 525, 97, fontChangeButton.getPreferredSize().height);
//---- showRegionBoundariesCB ----
showRegionBoundariesCB.setText("Show Region Boundaries");
showRegionBoundariesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showRegionBoundariesCBActionPerformed(e);
}
});
jPanel10.add(showRegionBoundariesCB);
showRegionBoundariesCB.setBounds(10, 165, 275, 23);
//---- label7 ----
label7.setText("Background color click to change): ");
jPanel10.add(label7);
label7.setBounds(15, 480, 235, label7.getPreferredSize().height);
//======== backgroundColorPanel ========
{
backgroundColorPanel.setPreferredSize(new Dimension(20, 20));
backgroundColorPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
backgroundColorPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
backgroundColorPanelMouseClicked(e);
}
});
backgroundColorPanel.setLayout(null);
}
jPanel10.add(backgroundColorPanel);
backgroundColorPanel.setBounds(255, 474, 30, 29);
//---- resetBackgroundButton ----
resetBackgroundButton.setText("Reset to default");
resetBackgroundButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetBackgroundButtonActionPerformed(e);
}
});
jPanel10.add(resetBackgroundButton);
resetBackgroundButton.setBounds(315, 474, 150, resetBackgroundButton.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel10.getComponentCount(); i++) {
Rectangle bounds = jPanel10.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel10.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel10.setMinimumSize(preferredSize);
jPanel10.setPreferredSize(preferredSize);
}
}
generalPanel.add(jPanel10, BorderLayout.CENTER);
}
tabbedPane.addTab("General", generalPanel);
//======== tracksPanel ========
{
tracksPanel.setLayout(null);
//======== jPanel6 ========
{
jPanel6.setLayout(null);
//---- jLabel5 ----
jLabel5.setText("Default Track Height, Charts (Pixels)");
jPanel6.add(jLabel5);
jLabel5.setBounds(new Rectangle(new Point(10, 12), jLabel5.getPreferredSize()));
//---- defaultChartTrackHeightField ----
defaultChartTrackHeightField.setText("40");
defaultChartTrackHeightField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultChartTrackHeightFieldActionPerformed(e);
}
});
defaultChartTrackHeightField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
defaultChartTrackHeightFieldFocusLost(e);
}
});
jPanel6.add(defaultChartTrackHeightField);
defaultChartTrackHeightField.setBounds(271, 6, 57, defaultChartTrackHeightField.getPreferredSize().height);
//---- trackNameAttributeLabel ----
trackNameAttributeLabel.setText("Track Name Attribute");
jPanel6.add(trackNameAttributeLabel);
trackNameAttributeLabel.setBounds(new Rectangle(new Point(10, 120), trackNameAttributeLabel.getPreferredSize()));
//---- trackNameAttributeField ----
trackNameAttributeField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trackNameAttributeFieldActionPerformed(e);
}
});
trackNameAttributeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
trackNameAttributeFieldFocusLost(e);
}
});
jPanel6.add(trackNameAttributeField);
trackNameAttributeField.setBounds(150, 115, 216, trackNameAttributeField.getPreferredSize().height);
//---- missingDataExplanation2 ----
missingDataExplanation2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation2.setText("<html>Name of an attribute to be used to label tracks. If provided tracks will be labeled with the corresponding attribute values from the sample information file");
missingDataExplanation2.setVerticalAlignment(SwingConstants.TOP);
jPanel6.add(missingDataExplanation2);
missingDataExplanation2.setBounds(40, 170, 578, 54);
//---- jLabel8 ----
jLabel8.setText("Default Track Height, Other (Pixels)");
jPanel6.add(jLabel8);
jLabel8.setBounds(new Rectangle(new Point(10, 45), jLabel8.getPreferredSize()));
//---- defaultTrackHeightField ----
defaultTrackHeightField.setText("15");
defaultTrackHeightField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultTrackHeightFieldActionPerformed(e);
}
});
defaultTrackHeightField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
defaultTrackHeightFieldFocusLost(e);
}
});
jPanel6.add(defaultTrackHeightField);
defaultTrackHeightField.setBounds(271, 39, 57, defaultTrackHeightField.getPreferredSize().height);
//---- missingDataExplanation4 ----
missingDataExplanation4.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation4.setText("<html>Default height of chart tracks (barcharts, scatterplots, etc)");
jPanel6.add(missingDataExplanation4);
missingDataExplanation4.setBounds(350, 5, 354, 25);
//---- missingDataExplanation5 ----
missingDataExplanation5.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation5.setText("<html>Default height of all other tracks");
jPanel6.add(missingDataExplanation5);
missingDataExplanation5.setBounds(350, 41, 1141, 25);
//---- missingDataExplanation3 ----
missingDataExplanation3.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation3.setText("<html><i> If selected feature tracks are expanded by default.");
jPanel6.add(missingDataExplanation3);
missingDataExplanation3.setBounds(new Rectangle(new Point(876, 318), missingDataExplanation3.getPreferredSize()));
//---- expandCB ----
expandCB.setText("Expand Feature Tracks");
expandCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandCBActionPerformed(e);
}
});
jPanel6.add(expandCB);
expandCB.setBounds(new Rectangle(new Point(6, 272), expandCB.getPreferredSize()));
//---- normalizeCoverageCB ----
normalizeCoverageCB.setText("Normalize Coverage Data");
normalizeCoverageCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalizeCoverageCBActionPerformed(e);
}
});
normalizeCoverageCB.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
normalizeCoverageCBFocusLost(e);
}
});
jPanel6.add(normalizeCoverageCB);
normalizeCoverageCB.setBounds(new Rectangle(new Point(6, 372), normalizeCoverageCB.getPreferredSize()));
//---- missingDataExplanation8 ----
missingDataExplanation8.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
missingDataExplanation8.setText("<html><i> Applies to coverage tracks computed with igvtools (.tdf files). If selected coverage values are scaled by (1,000,000 / totalCount), where totalCount is the total number of features or alignments.");
missingDataExplanation8.setVerticalAlignment(SwingConstants.TOP);
jPanel6.add(missingDataExplanation8);
missingDataExplanation8.setBounds(50, 413, 608, 52);
//---- expandIconCB ----
expandIconCB.setText("Show Expand Icon");
expandIconCB.setToolTipText("If checked displays an expand/collapse icon on feature tracks.");
expandIconCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandIconCBActionPerformed(e);
}
});
jPanel6.add(expandIconCB);
expandIconCB.setBounds(new Rectangle(new Point(6, 318), expandIconCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel6.getComponentCount(); i++) {
Rectangle bounds = jPanel6.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel6.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel6.setMinimumSize(preferredSize);
jPanel6.setPreferredSize(preferredSize);
}
}
tracksPanel.add(jPanel6);
jPanel6.setBounds(40, 20, 725, 480);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < tracksPanel.getComponentCount(); i++) {
Rectangle bounds = tracksPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = tracksPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
tracksPanel.setMinimumSize(preferredSize);
tracksPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Tracks", tracksPanel);
//======== overlaysPanel ========
{
//======== jPanel5 ========
{
jPanel5.setLayout(null);
//---- jLabel3 ----
jLabel3.setText("Sample attribute column:");
jPanel5.add(jLabel3);
jLabel3.setBounds(new Rectangle(new Point(65, 86), jLabel3.getPreferredSize()));
//---- overlayAttributeTextField ----
overlayAttributeTextField.setText("LINKING_ID");
overlayAttributeTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayAttributeTextFieldActionPerformed(e);
}
});
overlayAttributeTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
overlayAttributeTextFieldFocusLost(e);
}
});
overlayAttributeTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
overlayAttributeTextFieldKeyTyped(e);
}
});
jPanel5.add(overlayAttributeTextField);
overlayAttributeTextField.setBounds(229, 80, 228, overlayAttributeTextField.getPreferredSize().height);
//---- overlayTrackCB ----
overlayTrackCB.setSelected(true);
overlayTrackCB.setText("Overlay mutation tracks");
overlayTrackCB.setActionCommand("overlayTracksCB");
overlayTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayTrackCBActionPerformed(e);
}
});
jPanel5.add(overlayTrackCB);
overlayTrackCB.setBounds(new Rectangle(new Point(6, 51), overlayTrackCB.getPreferredSize()));
//---- jLabel2 ----
jLabel2.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
jPanel5.add(jLabel2);
jLabel2.setBounds(new Rectangle(new Point(6, 6), jLabel2.getPreferredSize()));
//---- displayTracksCB ----
displayTracksCB.setText("Display mutation data as distinct tracks");
displayTracksCB.setActionCommand("displayTracksCB");
displayTracksCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayTracksCBActionPerformed(e);
}
});
jPanel5.add(displayTracksCB);
displayTracksCB.setBounds(new Rectangle(new Point(5, 230), displayTracksCB.getPreferredSize()));
//---- jLabel4 ----
jLabel4.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
jPanel5.add(jLabel4);
jLabel4.setBounds(new Rectangle(new Point(6, 12), jLabel4.getPreferredSize()));
//---- colorOverlyCB ----
colorOverlyCB.setText("Color code overlay");
colorOverlyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorOverlyCBActionPerformed(e);
}
});
jPanel5.add(colorOverlyCB);
colorOverlyCB.setBounds(new Rectangle(new Point(65, 114), colorOverlyCB.getPreferredSize()));
//---- chooseOverlayColorsButton ----
chooseOverlayColorsButton.setForeground(new Color(0, 0, 247));
chooseOverlayColorsButton.setText("Choose colors");
chooseOverlayColorsButton.setFont(new Font("Lucida Grande", Font.ITALIC, 12));
chooseOverlayColorsButton.setVerticalAlignment(SwingConstants.BOTTOM);
chooseOverlayColorsButton.setVerticalTextPosition(SwingConstants.BOTTOM);
chooseOverlayColorsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooseOverlayColorsButtonActionPerformed(e);
}
});
jPanel5.add(chooseOverlayColorsButton);
chooseOverlayColorsButton.setBounds(new Rectangle(new Point(220, 116), chooseOverlayColorsButton.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel5.getComponentCount(); i++) {
Rectangle bounds = jPanel5.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel5.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel5.setMinimumSize(preferredSize);
jPanel5.setPreferredSize(preferredSize);
}
}
GroupLayout overlaysPanelLayout = new GroupLayout(overlaysPanel);
overlaysPanel.setLayout(overlaysPanelLayout);
overlaysPanelLayout.setHorizontalGroup(
overlaysPanelLayout.createParallelGroup()
.add(overlaysPanelLayout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel5, GroupLayout.PREFERRED_SIZE, 673, GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
);
overlaysPanelLayout.setVerticalGroup(
overlaysPanelLayout.createParallelGroup()
.add(overlaysPanelLayout.createSequentialGroup()
.add(55, 55, 55)
.add(jPanel5, GroupLayout.PREFERRED_SIZE, 394, GroupLayout.PREFERRED_SIZE)
.addContainerGap(117, Short.MAX_VALUE))
);
}
tabbedPane.addTab("Mutations", overlaysPanel);
//======== chartPanel ========
{
chartPanel.setLayout(null);
//======== jPanel4 ========
{
//---- topBorderCB ----
topBorderCB.setText("Draw Top Border");
topBorderCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
topBorderCBActionPerformed(e);
}
});
//---- label1 ----
label1.setFont(label1.getFont());
label1.setText("Default settings for barcharts and scatterplots:");
//---- chartDrawTrackNameCB ----
chartDrawTrackNameCB.setText("Draw Track Label");
chartDrawTrackNameCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chartDrawTrackNameCBActionPerformed(e);
}
});
//---- bottomBorderCB ----
bottomBorderCB.setText("Draw Bottom Border");
bottomBorderCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bottomBorderCBActionPerformed(e);
}
});
//---- jLabel7 ----
jLabel7.setText("<html><i>If selected charts are dynamically rescaled to the range of the data in view.");
//---- colorBordersCB ----
colorBordersCB.setText("Color Borders");
colorBordersCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorBordersCBActionPerformed(e);
}
});
//---- labelYAxisCB ----
labelYAxisCB.setText("Label Y Axis");
labelYAxisCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
labelYAxisCBActionPerformed(e);
}
});
//---- autoscaleCB ----
autoscaleCB.setText("Continuous Autoscale");
autoscaleCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
autoscaleCBActionPerformed(e);
}
});
//---- jLabel9 ----
jLabel9.setText("<html><i>Draw a label centered over the track provided<br>the track height is at least 25 pixels. ");
//---- showDatarangeCB ----
showDatarangeCB.setText("Show Data Range");
showDatarangeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showDatarangeCBActionPerformed(e);
}
});
showDatarangeCB.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
showDatarangeCBFocusLost(e);
}
});
GroupLayout jPanel4Layout = new GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(221, Short.MAX_VALUE)
.add(jLabel9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(84, 84, 84)))
.add(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel4Layout.createParallelGroup()
.add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(jPanel4Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createSequentialGroup()
.add(jPanel4Layout.createParallelGroup()
.add(autoscaleCB)
.add(showDatarangeCB))
.add(18, 18, 18)
.add(jLabel7, GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))
.add(jPanel4Layout.createSequentialGroup()
.add(jPanel4Layout.createParallelGroup()
.add(topBorderCB)
.add(colorBordersCB)
.add(bottomBorderCB)
.add(labelYAxisCB)
.add(chartDrawTrackNameCB))
.addPreferredGap(LayoutStyle.RELATED, 403, Short.MAX_VALUE)))))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createParallelGroup()
.add(jPanel4Layout.createSequentialGroup()
.add(131, 131, 131)
.add(jLabel9, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(181, Short.MAX_VALUE)))
.add(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.add(label1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(topBorderCB)
.addPreferredGap(LayoutStyle.RELATED)
.add(bottomBorderCB)
.add(7, 7, 7)
.add(colorBordersCB)
.add(18, 18, 18)
.add(chartDrawTrackNameCB)
.add(23, 23, 23)
.add(labelYAxisCB)
.add(18, 18, 18)
.add(jPanel4Layout.createParallelGroup(GroupLayout.BASELINE)
.add(autoscaleCB)
.add(jLabel7, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(showDatarangeCB)
.add(36, 36, 36))
);
}
chartPanel.add(jPanel4);
jPanel4.setBounds(20, 30, 590, 340);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < chartPanel.getComponentCount(); i++) {
Rectangle bounds = chartPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = chartPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
chartPanel.setMinimumSize(preferredSize);
chartPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Charts", chartPanel);
//======== alignmentPanel ========
{
alignmentPanel.setLayout(null);
//======== jPanel1 ========
{
jPanel1.setLayout(null);
//======== jPanel11 ========
{
jPanel11.setBorder(null);
jPanel11.setLayout(null);
//---- samMaxDepthField ----
samMaxDepthField.setText("jTextField1");
samMaxDepthField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxLevelFieldActionPerformed(e);
}
});
samMaxDepthField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxLevelFieldFocusLost(e);
}
});
jPanel11.add(samMaxDepthField);
samMaxDepthField.setBounds(new Rectangle(new Point(206, 40), samMaxDepthField.getPreferredSize()));
//---- jLabel11 ----
jLabel11.setText("Visibility range threshold (kb)");
jPanel11.add(jLabel11);
jLabel11.setBounds(new Rectangle(new Point(6, 12), jLabel11.getPreferredSize()));
//---- jLabel16 ----
jLabel16.setText("<html><i>Reads with qualities below the threshold are not shown.");
jPanel11.add(jLabel16);
jLabel16.setBounds(new Rectangle(new Point(296, 80), jLabel16.getPreferredSize()));
//---- mappingQualityThresholdField ----
mappingQualityThresholdField.setText("0");
mappingQualityThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mappingQualityThresholdFieldActionPerformed(e);
}
});
mappingQualityThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
mappingQualityThresholdFieldFocusLost(e);
}
});
jPanel11.add(mappingQualityThresholdField);
mappingQualityThresholdField.setBounds(206, 74, 84, mappingQualityThresholdField.getPreferredSize().height);
//---- jLabel14 ----
jLabel14.setText("<html><i>Maximum read depth to load (approximate).");
jPanel11.add(jLabel14);
jLabel14.setBounds(296, 39, 390, 30);
//---- jLabel13 ----
jLabel13.setText("Maximum read depth:");
jPanel11.add(jLabel13);
jLabel13.setBounds(new Rectangle(new Point(6, 46), jLabel13.getPreferredSize()));
//---- jLabel15 ----
jLabel15.setText("Mapping quality threshold:");
jPanel11.add(jLabel15);
jLabel15.setBounds(new Rectangle(new Point(6, 80), jLabel15.getPreferredSize()));
//---- samMaxWindowSizeField ----
samMaxWindowSizeField.setText("jTextField1");
samMaxWindowSizeField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxWindowSizeFieldActionPerformed(e);
}
});
samMaxWindowSizeField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxWindowSizeFieldFocusLost(e);
}
});
jPanel11.add(samMaxWindowSizeField);
samMaxWindowSizeField.setBounds(new Rectangle(new Point(206, 6), samMaxWindowSizeField.getPreferredSize()));
//---- jLabel12 ----
jLabel12.setText("<html><i>Nominal window size at which alignments become visible");
jPanel11.add(jLabel12);
jLabel12.setBounds(new Rectangle(new Point(296, 12), jLabel12.getPreferredSize()));
//---- jLabel26 ----
jLabel26.setText("Coverage allele-freq threshold");
jPanel11.add(jLabel26);
jLabel26.setBounds(6, 114, 200, jLabel26.getPreferredSize().height);
//---- snpThresholdField ----
snpThresholdField.setText("0");
snpThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snpThresholdFieldActionPerformed(e);
}
});
snpThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
snpThresholdFieldFocusLost(e);
}
});
jPanel11.add(snpThresholdField);
snpThresholdField.setBounds(206, 108, 84, snpThresholdField.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel11.getComponentCount(); i++) {
Rectangle bounds = jPanel11.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel11.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel11.setMinimumSize(preferredSize);
jPanel11.setPreferredSize(preferredSize);
}
}
jPanel1.add(jPanel11);
jPanel11.setBounds(5, 10, 755, 150);
//======== jPanel12 ========
{
jPanel12.setBorder(null);
jPanel12.setLayout(null);
//---- samMinBaseQualityField ----
samMinBaseQualityField.setText("0");
samMinBaseQualityField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMinBaseQualityFieldActionPerformed(e);
}
});
samMinBaseQualityField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMinBaseQualityFieldFocusLost(e);
}
});
jPanel12.add(samMinBaseQualityField);
samMinBaseQualityField.setBounds(380, 105, 50, samMinBaseQualityField.getPreferredSize().height);
//---- samShadeMismatchedBaseCB ----
samShadeMismatchedBaseCB.setText("Shade mismatched bases by quality. ");
samShadeMismatchedBaseCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samShadeMismatchedBaseCBActionPerformed(e);
}
});
jPanel12.add(samShadeMismatchedBaseCB);
samShadeMismatchedBaseCB.setBounds(6, 109, 264, samShadeMismatchedBaseCB.getPreferredSize().height);
//---- samMaxBaseQualityField ----
samMaxBaseQualityField.setText("0");
samMaxBaseQualityField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samMaxBaseQualityFieldActionPerformed(e);
}
});
samMaxBaseQualityField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
samMaxBaseQualityFieldFocusLost(e);
}
});
jPanel12.add(samMaxBaseQualityField);
samMaxBaseQualityField.setBounds(505, 105, 50, samMaxBaseQualityField.getPreferredSize().height);
//---- showCovTrackCB ----
showCovTrackCB.setText("Show coverage track");
showCovTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCovTrackCBActionPerformed(e);
}
});
jPanel12.add(showCovTrackCB);
showCovTrackCB.setBounds(375, 10, 270, showCovTrackCB.getPreferredSize().height);
//---- samFilterDuplicatesCB ----
samFilterDuplicatesCB.setText("Filter duplicate reads");
samFilterDuplicatesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samShowDuplicatesCBActionPerformed(e);
}
});
jPanel12.add(samFilterDuplicatesCB);
samFilterDuplicatesCB.setBounds(6, 10, 290, samFilterDuplicatesCB.getPreferredSize().height);
//---- jLabel19 ----
jLabel19.setText("Min: ");
jPanel12.add(jLabel19);
jLabel19.setBounds(new Rectangle(new Point(340, 110), jLabel19.getPreferredSize()));
//---- filterCB ----
filterCB.setText("Filter alignments by read group");
filterCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterCBActionPerformed(e);
}
});
jPanel12.add(filterCB);
filterCB.setBounds(6, 142, 244, filterCB.getPreferredSize().height);
//---- filterURL ----
filterURL.setText("URL or path to filter file");
filterURL.setEnabled(false);
filterURL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterURLActionPerformed(e);
}
});
filterURL.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
filterURLFocusLost(e);
}
});
jPanel12.add(filterURL);
filterURL.setBounds(275, 140, 440, filterURL.getPreferredSize().height);
//---- samFlagUnmappedPairCB ----
samFlagUnmappedPairCB.setText("Flag unmapped pairs");
samFlagUnmappedPairCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
samFlagUnmappedPairCBActionPerformed(e);
}
});
jPanel12.add(samFlagUnmappedPairCB);
samFlagUnmappedPairCB.setBounds(6, 76, 310, samFlagUnmappedPairCB.getPreferredSize().height);
//---- filterFailedReadsCB ----
filterFailedReadsCB.setText("Filter vendor failed reads");
filterFailedReadsCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterVendorFailedReadsCBActionPerformed(e);
}
});
jPanel12.add(filterFailedReadsCB);
filterFailedReadsCB.setBounds(new Rectangle(new Point(6, 43), filterFailedReadsCB.getPreferredSize()));
//---- label2 ----
label2.setText("Max:");
jPanel12.add(label2);
label2.setBounds(new Rectangle(new Point(455, 110), label2.getPreferredSize()));
//---- showSoftClippedCB ----
showSoftClippedCB.setText("Show soft-clipped bases");
showSoftClippedCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showSoftClippedCBActionPerformed(e);
}
});
jPanel12.add(showSoftClippedCB);
showSoftClippedCB.setBounds(new Rectangle(new Point(375, 76), showSoftClippedCB.getPreferredSize()));
//---- showJunctionTrackCB ----
showJunctionTrackCB.setText("Show splice junction track");
showJunctionTrackCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showJunctionTrackCBActionPerformed(e);
}
});
jPanel12.add(showJunctionTrackCB);
showJunctionTrackCB.setBounds(new Rectangle(new Point(375, 43), showJunctionTrackCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel12.getComponentCount(); i++) {
Rectangle bounds = jPanel12.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel12.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel12.setMinimumSize(preferredSize);
jPanel12.setPreferredSize(preferredSize);
}
}
jPanel1.add(jPanel12);
jPanel12.setBounds(5, 145, 755, 175);
//======== panel2 ========
{
panel2.setBorder(new TitledBorder("Insert Size Options"));
panel2.setLayout(null);
//---- isizeComputeCB ----
isizeComputeCB.setText("Compute");
isizeComputeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isizeComputeCBActionPerformed(e);
isizeComputeCBActionPerformed(e);
isizeComputeCBActionPerformed(e);
}
});
panel2.add(isizeComputeCB);
isizeComputeCB.setBounds(new Rectangle(new Point(360, 76), isizeComputeCB.getPreferredSize()));
//---- jLabel17 ----
jLabel17.setText("Maximum (bp):");
panel2.add(jLabel17);
jLabel17.setBounds(100, 110, 110, jLabel17.getPreferredSize().height);
//---- insertSizeMinThresholdField ----
insertSizeMinThresholdField.setText("0");
insertSizeMinThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
}
});
insertSizeMinThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMinThresholdFieldFocusLost(e);
}
});
panel2.add(insertSizeMinThresholdField);
insertSizeMinThresholdField.setBounds(220, 75, 84, 28);
//---- jLabel20 ----
jLabel20.setText("Minimum (bp):");
panel2.add(jLabel20);
jLabel20.setBounds(100, 80, 110, 16);
//---- insertSizeThresholdField ----
insertSizeThresholdField.setText("0");
insertSizeThresholdField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeThresholdFieldActionPerformed(e);
}
});
insertSizeThresholdField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
}
});
panel2.add(insertSizeThresholdField);
insertSizeThresholdField.setBounds(220, 105, 84, insertSizeThresholdField.getPreferredSize().height);
//---- jLabel30 ----
jLabel30.setText("Minimum (percentile):");
panel2.add(jLabel30);
jLabel30.setBounds(460, 80, 155, 16);
//---- jLabel18 ----
jLabel18.setText("Maximum (percentile):");
panel2.add(jLabel18);
jLabel18.setBounds(460, 110, 155, 16);
//---- insertSizeMinPercentileField ----
insertSizeMinPercentileField.setText("0");
insertSizeMinPercentileField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinThresholdFieldActionPerformed(e);
insertSizeMinPercentileFieldActionPerformed(e);
}
});
insertSizeMinPercentileField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMinThresholdFieldFocusLost(e);
insertSizeMinPercentileFieldFocusLost(e);
}
});
panel2.add(insertSizeMinPercentileField);
insertSizeMinPercentileField.setBounds(625, 75, 84, 28);
//---- insertSizeMaxPercentileField ----
insertSizeMaxPercentileField.setText("0");
insertSizeMaxPercentileField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertSizeThresholdFieldActionPerformed(e);
insertSizeThresholdFieldActionPerformed(e);
insertSizeMaxPercentileFieldActionPerformed(e);
}
});
insertSizeMaxPercentileField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
insertSizeThresholdFieldFocusLost(e);
insertSizeMaxPercentileFieldFocusLost(e);
}
});
panel2.add(insertSizeMaxPercentileField);
insertSizeMaxPercentileField.setBounds(625, 105, 84, 28);
//---- label8 ----
label8.setText("<html><i>These options control the color coding of paired alignments by inferred insert size. Base pair values set default values. If \"compute\" is selected values are computed from the actual size distribution of each library.");
panel2.add(label8);
label8.setBounds(5, 15, 735, 55);
//---- label9 ----
label9.setText("Defaults ");
panel2.add(label9);
label9.setBounds(new Rectangle(new Point(15, 80), label9.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel2.getComponentCount(); i++) {
Rectangle bounds = panel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel2.setMinimumSize(preferredSize);
panel2.setPreferredSize(preferredSize);
}
}
jPanel1.add(panel2);
panel2.setBounds(5, 350, 755, 145);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel1.getComponentCount(); i++) {
Rectangle bounds = jPanel1.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel1.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel1.setMinimumSize(preferredSize);
jPanel1.setPreferredSize(preferredSize);
}
}
alignmentPanel.add(jPanel1);
jPanel1.setBounds(0, 0, 760, 510);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < alignmentPanel.getComponentCount(); i++) {
Rectangle bounds = alignmentPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = alignmentPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
alignmentPanel.setMinimumSize(preferredSize);
alignmentPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Alignments", alignmentPanel);
//======== expressionPane ========
{
expressionPane.setLayout(null);
//======== jPanel8 ========
{
//---- expMapToGeneCB ----
expMapToGeneCB.setText("Map probes to genes");
expMapToGeneCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expMapToGeneCBActionPerformed(e);
}
});
//---- jLabel24 ----
jLabel24.setText("Expression probe mapping options: ");
//---- expMapToLociCB ----
expMapToLociCB.setText("<html>Map probes to target loci");
expMapToLociCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expMapToLociCBActionPerformed(e);
}
});
//---- jLabel21 ----
jLabel21.setText("<html><i>Note: Changes will not affect currently loaded datasets.");
GroupLayout jPanel8Layout = new GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(45, 45, 45)
.add(jPanel8Layout.createParallelGroup()
.add(expMapToLociCB, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(expMapToGeneCB)))
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.add(24, 24, 24)
.add(jLabel21, GroupLayout.PREFERRED_SIZE, 497, GroupLayout.PREFERRED_SIZE))
.add(jLabel24))))
.addContainerGap(193, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup()
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel24)
.addPreferredGap(LayoutStyle.RELATED)
.add(jLabel21, GroupLayout.PREFERRED_SIZE, 44, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(expMapToLociCB, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(14, 14, 14)
.add(expMapToGeneCB)
.addContainerGap(172, Short.MAX_VALUE))
);
}
expressionPane.add(jPanel8);
jPanel8.setBounds(10, 30, 720, 310);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < expressionPane.getComponentCount(); i++) {
Rectangle bounds = expressionPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = expressionPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
expressionPane.setMinimumSize(preferredSize);
expressionPane.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Probes", expressionPane);
//======== advancedPanel ========
{
advancedPanel.setBorder(new EmptyBorder(1, 10, 1, 10));
advancedPanel.setLayout(null);
//======== jPanel3 ========
{
//======== jPanel2 ========
{
jPanel2.setLayout(null);
//---- jLabel1 ----
jLabel1.setText("Genome Server URL");
jPanel2.add(jLabel1);
jLabel1.setBounds(new Rectangle(new Point(35, 47), jLabel1.getPreferredSize()));
//---- genomeServerURLTextField ----
genomeServerURLTextField.setText("jTextField1");
genomeServerURLTextField.setEnabled(false);
genomeServerURLTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
genomeServerURLTextFieldActionPerformed(e);
}
});
genomeServerURLTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
genomeServerURLTextFieldFocusLost(e);
}
});
jPanel2.add(genomeServerURLTextField);
genomeServerURLTextField.setBounds(191, 41, 494, genomeServerURLTextField.getPreferredSize().height);
//---- jLabel6 ----
jLabel6.setText("Data Registry URL");
jPanel2.add(jLabel6);
jLabel6.setBounds(new Rectangle(new Point(35, 81), jLabel6.getPreferredSize()));
//---- dataServerURLTextField ----
dataServerURLTextField.setEnabled(false);
dataServerURLTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dataServerURLTextFieldActionPerformed(e);
}
});
dataServerURLTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
dataServerURLTextFieldFocusLost(e);
}
});
jPanel2.add(dataServerURLTextField);
dataServerURLTextField.setBounds(191, 75, 494, dataServerURLTextField.getPreferredSize().height);
//---- editServerPropertiesCB ----
editServerPropertiesCB.setText("Edit server properties");
editServerPropertiesCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editServerPropertiesCBActionPerformed(e);
}
});
jPanel2.add(editServerPropertiesCB);
editServerPropertiesCB.setBounds(new Rectangle(new Point(6, 7), editServerPropertiesCB.getPreferredSize()));
//---- jButton1 ----
jButton1.setText("Reset to Defaults");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});
jPanel2.add(jButton1);
jButton1.setBounds(new Rectangle(new Point(190, 6), jButton1.getPreferredSize()));
//---- clearGenomeCacheButton ----
clearGenomeCacheButton.setText("Clear Genome Cache");
clearGenomeCacheButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearGenomeCacheButtonActionPerformed(e);
}
});
jPanel2.add(clearGenomeCacheButton);
clearGenomeCacheButton.setBounds(new Rectangle(new Point(6, 155), clearGenomeCacheButton.getPreferredSize()));
//---- genomeUpdateCB ----
genomeUpdateCB.setText("<html>Automatically check for updated genomes. <i>Most users should leave this checked.");
genomeUpdateCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
genomeUpdateCBActionPerformed(e);
}
});
jPanel2.add(genomeUpdateCB);
genomeUpdateCB.setBounds(new Rectangle(new Point(14, 121), genomeUpdateCB.getPreferredSize()));
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < jPanel2.getComponentCount(); i++) {
Rectangle bounds = jPanel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = jPanel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
jPanel2.setMinimumSize(preferredSize);
jPanel2.setPreferredSize(preferredSize);
}
}
//======== jPanel7 ========
{
//---- enablePortCB ----
enablePortCB.setText("Enable port");
enablePortCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enablePortCBActionPerformed(e);
}
});
//---- portField ----
portField.setText("60151");
portField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
portFieldActionPerformed(e);
}
});
portField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
portFieldFocusLost(e);
}
});
//---- jLabel22 ----
jLabel22.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
jLabel22.setText("Enable port to send commands and http requests to IGV. ");
GroupLayout jPanel7Layout = new GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.add(jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.add(enablePortCB)
.add(39, 39, 39)
.add(portField, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE))
.add(jPanel7Layout.createSequentialGroup()
.add(48, 48, 48)
.add(jLabel22)))
.addContainerGap(330, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup()
.add(jPanel7Layout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel7Layout.createParallelGroup(GroupLayout.CENTER)
.add(enablePortCB)
.add(portField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(jLabel22)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}
GroupLayout jPanel3Layout = new GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup()
.add(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel3Layout.createParallelGroup()
.add(jPanel7, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup()
.add(jPanel3Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel7, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED, 36, Short.MAX_VALUE)
.add(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
);
}
advancedPanel.add(jPanel3);
jPanel3.setBounds(10, 0, 750, 330);
//======== jPanel9 ========
{
//---- useByteRangeCB ----
useByteRangeCB.setText("Use http byte-range requests");
useByteRangeCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
useByteRangeCBActionPerformed(e);
}
});
//---- jLabel25 ----
jLabel25.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
jLabel25.setText("<html>This option applies to certain \"Load from Server...\" tracks hosted at the Broad. Disable this option if you are unable to load the phastCons conservation track under the hg18 annotations.");
GroupLayout jPanel9Layout = new GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup()
.add(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel9Layout.createParallelGroup()
.add(jPanel9Layout.createSequentialGroup()
.add(38, 38, 38)
.add(jLabel25, GroupLayout.PREFERRED_SIZE, 601, GroupLayout.PREFERRED_SIZE))
.add(useByteRangeCB))
.addContainerGap(65, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel9Layout.createSequentialGroup()
.add(59, 59, 59)
.add(useByteRangeCB, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(jLabel25, GroupLayout.DEFAULT_SIZE, 16, Short.MAX_VALUE)
.addContainerGap())
);
}
advancedPanel.add(jPanel9);
jPanel9.setBounds(30, 340, 710, 120);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < advancedPanel.getComponentCount(); i++) {
Rectangle bounds = advancedPanel.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = advancedPanel.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
advancedPanel.setMinimumSize(preferredSize);
advancedPanel.setPreferredSize(preferredSize);
}
}
tabbedPane.addTab("Advanced", advancedPanel);
//======== proxyPanel ========
{
proxyPanel.setLayout(new BoxLayout(proxyPanel, BoxLayout.X_AXIS));
//======== jPanel15 ========
{
//======== jPanel16 ========
{
//---- proxyUsernameField ----
proxyUsernameField.setText("jTextField1");
proxyUsernameField.setEnabled(false);
proxyUsernameField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyUsernameFieldActionPerformed(e);
}
});
proxyUsernameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyUsernameFieldFocusLost(e);
}
});
//---- jLabel28 ----
jLabel28.setText("Username");
//---- authenticateProxyCB ----
authenticateProxyCB.setText("Authentication required");
authenticateProxyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
authenticateProxyCBActionPerformed(e);
}
});
//---- jLabel29 ----
jLabel29.setText("Password");
//---- proxyPasswordField ----
proxyPasswordField.setText("jPasswordField1");
proxyPasswordField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyPasswordFieldFocusLost(e);
}
});
GroupLayout jPanel16Layout = new GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(28, 28, 28)
.add(jPanel16Layout.createParallelGroup()
.add(jLabel28)
.add(jLabel29))
.add(37, 37, 37)
.add(jPanel16Layout.createParallelGroup(GroupLayout.LEADING, false)
.add(proxyPasswordField)
.add(proxyUsernameField, GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)))
.add(jPanel16Layout.createSequentialGroup()
.addContainerGap()
.add(authenticateProxyCB)))
.addContainerGap(381, Short.MAX_VALUE))
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup()
.add(jPanel16Layout.createSequentialGroup()
.add(17, 17, 17)
.add(authenticateProxyCB)
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel16Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel28)
.add(proxyUsernameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel16Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel29)
.add(proxyPasswordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(70, Short.MAX_VALUE))
);
}
//======== jPanel17 ========
{
//---- proxyHostField ----
proxyHostField.setText("jTextField1");
proxyHostField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyHostFieldActionPerformed(e);
}
});
proxyHostField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyHostFieldFocusLost(e);
}
});
//---- proxyPortField ----
proxyPortField.setText("jTextField1");
proxyPortField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
proxyPortFieldActionPerformed(e);
}
});
proxyPortField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
proxyPortFieldFocusLost(e);
}
});
//---- jLabel27 ----
jLabel27.setText("Proxy port");
//---- jLabel23 ----
jLabel23.setText("Proxy host");
//---- useProxyCB ----
useProxyCB.setText("Use proxy");
useProxyCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
useProxyCBActionPerformed(e);
}
});
GroupLayout jPanel17Layout = new GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup()
.add(jPanel17Layout.createSequentialGroup()
.add(jPanel17Layout.createParallelGroup()
.add(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel17Layout.createParallelGroup()
.add(jLabel27)
.add(jLabel23))
.add(28, 28, 28)
.add(jPanel17Layout.createParallelGroup()
.add(proxyPortField, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
.add(proxyHostField, GroupLayout.PREFERRED_SIZE, 485, GroupLayout.PREFERRED_SIZE)))
.add(jPanel17Layout.createSequentialGroup()
.add(9, 9, 9)
.add(useProxyCB)))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup()
.add(GroupLayout.TRAILING, jPanel17Layout.createSequentialGroup()
.addContainerGap(29, Short.MAX_VALUE)
.add(useProxyCB)
.add(18, 18, 18)
.add(jPanel17Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel23)
.add(proxyHostField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel17Layout.createParallelGroup(GroupLayout.BASELINE)
.add(jLabel27)
.add(proxyPortField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
}
//---- label3 ----
label3.setText("<html>Note: do not use these settings unless you receive error or warning messages about server connections. On most systems the correct settings will be automatically copied from your web browser.");
//---- clearProxySettingsButton ----
clearProxySettingsButton.setText("Clear All");
clearProxySettingsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearProxySettingsButtonActionPerformed(e);
}
});
GroupLayout jPanel15Layout = new GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.add(jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.add(22, 22, 22)
.add(label3, GroupLayout.PREFERRED_SIZE, 630, GroupLayout.PREFERRED_SIZE))
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15Layout.createParallelGroup()
.add(jPanel16, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel17, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(clearProxySettingsButton)))
.addContainerGap())
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup()
.add(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.add(label3, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(jPanel17, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(jPanel16, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(clearProxySettingsButton)
.addContainerGap(110, Short.MAX_VALUE))
);
}
proxyPanel.add(jPanel15);
}
tabbedPane.addTab("Proxy", proxyPanel);
}
contentPane.add(tabbedPane, BorderLayout.CENTER);
//======== okCancelButtonPanel ========
{
//---- okButton ----
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonActionPerformed(e);
}
});
okCancelButtonPanel.add(okButton);
//---- cancelButton ----
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButtonActionPerformed(e);
}
});
okCancelButtonPanel.add(cancelButton);
}
contentPane.add(okCancelButtonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(getOwner());
//---- buttonGroup1 ----
ButtonGroup buttonGroup1 = new ButtonGroup();
buttonGroup1.add(expMapToGeneCB);
buttonGroup1.add(expMapToLociCB);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/streamfish/MainMenu.java b/src/streamfish/MainMenu.java
index 68080ea..8a8ec34 100644
--- a/src/streamfish/MainMenu.java
+++ b/src/streamfish/MainMenu.java
@@ -1,401 +1,401 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package streamfish;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import static javax.swing.JOptionPane.*;
/**
*
* @author Kristian
*/
public class MainMenu extends javax.swing.JPanel {
private int kundenr = -1;
private final GUI gui;
private Customer[] customers;
private int viewRow;
private Orderinfo[] orderinfo;
/**
* Creates new form MainMenu
*/
public MainMenu(final GUI gui) {
this.gui = gui;
gui.setTitle("Main Menu");
initComponents();
customers = gui.getCustomers(jTextField1.getText(), jCheckBox1.isSelected());
// jTable1.setModel();1
if (customers != null && customers.length > 0) {
for (int i = 0; i < customers.length; i++) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{customers[i].getCustomerID(), customers[i].getCustomerName(), customers[i].getPhoneNumber(), customers[i].isBusiness()});
}
}
// from here tab2 NorC
orderinfo = gui.getTodaysTasks();
if (orderinfo != null && orderinfo.length > 0) {
for (int i = 0; i < orderinfo.length; i++) {
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.addRow(new Object[]{orderinfo[i].getAddress(), orderinfo[i].getCustomerName(), orderinfo[i].getPhone()});
}
}
jTable1.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
viewRow = jTable1.getSelectedRow();
}
}
});
//to here tab2 Norc
jTextField1.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
customers = gui.getCustomers(jTextField1.getText(), jCheckBox1.isSelected());
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
if (customers != null && customers.length > 0) {
for (int i = 0; i < customers.length; i++) {
model.addRow(new Object[]{customers[i].getCustomerID(), customers[i].getCustomerName(), customers[i].getPhoneNumber(), customers[i].isBusiness()});
}
}
}
@Override
public void removeUpdate(DocumentEvent e) {
customers = gui.getCustomers(jTextField1.getText(), jCheckBox1.isSelected());
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
if (customers != null && customers.length > 0) {
for (int i = 0; i < customers.length; i++) {
model.addRow(new Object[]{customers[i].getCustomerID(), customers[i].getCustomerName(), customers[i].getPhoneNumber(), customers[i].isBusiness()});
}
}
}
@Override
public void changedUpdate(DocumentEvent e) {
customers = gui.getCustomers(jTextField1.getText(), jCheckBox1.isSelected());
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
if (customers != null && customers.length > 0) {
for (int i = 0; i < customers.length; i++) {
model.addRow(new Object[]{customers[i].getCustomerID(), customers[i].getCustomerName(), customers[i].getPhoneNumber(), customers[i].isBusiness()});
}
}
}
});
jCheckBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
customers = gui.getCustomers(jTextField1.getText(), jCheckBox1.isSelected());
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
if (customers != null && customers.length > 0) {
for (int i = 0; i < customers.length; i++) {
model.addRow(new Object[]{customers[i].getCustomerID(), customers[i].getCustomerName(), customers[i].getPhoneNumber(), customers[i].isBusiness()});
}
}
}
});
jTable1.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int viewRow = jTable1.getSelectedRow();
if (!event.getValueIsAdjusting()) {
try {
kundenr = Integer.parseInt(jTable1.getValueAt(viewRow, 0).toString());
} catch (Exception e) {
}
}
}
});
}
public void updt() {
customers = gui.getCustomers(jTextField1.getText(), jCheckBox1.isSelected());
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
if (customers != null && customers.length > 0) {
for (int i = 0; i < customers.length; i++) {
model.addRow(new Object[]{customers[i].getCustomerID(), customers[i].getCustomerName(), customers[i].getPhoneNumber(), customers[i].isBusiness()});
}
}
}
/**
* 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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jButton5 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jButton1.setText("Register customer");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Register order");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setText("Search:");
jButton3.setText("Edit customer");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Get info");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jCheckBox1.setText("Show only inactive");
jButton5.setText("Storage");
jButton5.setToolTipText("");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer_id", "Customer name", "Phone", "Business"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setMaximumSize(new java.awt.Dimension(300, 64));
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane2.setViewportView(jTable1);
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Customers", jPanel1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Address", "Name", "Phone number"
}
));
jScrollPane1.setViewportView(jTable2);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Todays tasks", jPanel2);
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTable3);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
- .addGap(0, 0, Short.MAX_VALUE)
- .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGap(0, 0, 0)
+ .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
+ .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Subscriptions", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jButton4)
.addGap(18, 18, 18)
.addComponent(jButton2))
.addGroup(layout.createSequentialGroup()
.addComponent(jCheckBox1)
.addGap(18, 18, 18)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jTabbedPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jCheckBox1)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if (kundenr == -1) {
showMessageDialog(null, "Ingen kunde er valgt.");
} else {
gui.byttVindu(this, new Reg_ordre(kundenr, gui));
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
gui.byttVindu(this, new Reg_kunde(gui));
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
if (kundenr == -1) {
showMessageDialog(null, "Ingen kunde er valgt.");
} else {
gui.byttVindu(this, new Edit_customer(kundenr, gui));
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
if(jPanel1.hasFocus()){
System.out.println("pane1 works");
}else if(jPanel2.hasFocus()){
new TodaysTasksFrame(orderinfo[viewRow], gui);
}
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
gui.byttVindu(this, new Storage(gui));
}//GEN-LAST:event_jButton5ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTable jTable3;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jButton5 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jButton1.setText("Register customer");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Register order");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setText("Search:");
jButton3.setText("Edit customer");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Get info");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jCheckBox1.setText("Show only inactive");
jButton5.setText("Storage");
jButton5.setToolTipText("");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer_id", "Customer name", "Phone", "Business"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setMaximumSize(new java.awt.Dimension(300, 64));
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane2.setViewportView(jTable1);
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Customers", jPanel1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Address", "Name", "Phone number"
}
));
jScrollPane1.setViewportView(jTable2);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Todays tasks", jPanel2);
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTable3);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Subscriptions", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jButton4)
.addGap(18, 18, 18)
.addComponent(jButton2))
.addGroup(layout.createSequentialGroup()
.addComponent(jCheckBox1)
.addGap(18, 18, 18)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jTabbedPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jCheckBox1)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jButton5 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jButton1.setText("Register customer");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Register order");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setText("Search:");
jButton3.setText("Edit customer");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Get info");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jCheckBox1.setText("Show only inactive");
jButton5.setText("Storage");
jButton5.setToolTipText("");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer_id", "Customer name", "Phone", "Business"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setMaximumSize(new java.awt.Dimension(300, 64));
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane2.setViewportView(jTable1);
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Customers", jPanel1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Address", "Name", "Phone number"
}
));
jScrollPane1.setViewportView(jTable2);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Todays tasks", jPanel2);
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTable3);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Subscriptions", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jButton4)
.addGap(18, 18, 18)
.addComponent(jButton2))
.addGroup(layout.createSequentialGroup()
.addComponent(jCheckBox1)
.addGap(18, 18, 18)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jTabbedPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jCheckBox1)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java b/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java
index d0e8b87..a9bc596 100644
--- a/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java
+++ b/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java
@@ -1,252 +1,251 @@
/*
* 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.crawler.restlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.archive.spring.PathSharingContext;
import org.archive.util.TextUtils;
import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.restlet.resource.WriterRepresentation;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
/**
* Restlet Resource which allows browsing the constructed beans in
* a hierarchical fashion.
*
* @contributor gojomo
* @contributor nlevitt
*/
public class BeanBrowseResource extends JobRelatedResource {
PathSharingContext appCtx;
String beanPath;
public BeanBrowseResource(Context ctx, Request req, Response res) throws ResourceException {
super(ctx, req, res);
getVariants().add(new Variant(MediaType.TEXT_HTML));
getVariants().add(new Variant(MediaType.APPLICATION_XML));
setModifiable(true); // accept POSTs
appCtx = cj.getJobContext();
beanPath = (String)req.getAttributes().get("beanPath");
if (beanPath!=null) {
try {
beanPath = URLDecoder.decode(beanPath,"UTF-8");
} catch (UnsupportedEncodingException e) {
// inconceivable! UTF-8 required all Java impls
}
} else {
beanPath = "";
}
}
public void acceptRepresentation(Representation entity) throws ResourceException {
if (appCtx == null) {
throw new ResourceException(404);
}
// copy op?
Form form = getRequest().getEntityAsForm();
beanPath = form.getFirstValue("beanPath");
String newVal = form.getFirstValue("newVal");
if(newVal!=null) {
int i = beanPath.indexOf(".");
String beanName = i<0?beanPath:beanPath.substring(0,i);
Object namedBean = appCtx.getBean(beanName);
BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean);
String propPath = beanPath.substring(i+1);
Object coercedVal = bwrap.convertIfNecessary(newVal, bwrap.getPropertyValue(propPath).getClass());
bwrap.setPropertyValue(propPath, coercedVal);
}
Reference ref = getRequest().getResourceRef();
ref.setPath(getBeansRefPath());
ref.addSegment(beanPath);
getResponse().redirectSeeOther(ref);
}
public String getBeansRefPath() {
Reference ref = getRequest().getResourceRef();
String path = ref.getPath();
int i = path.indexOf("/beans/");
if(i>0) {
return path.substring(0,i+"/beans/".length());
}
if(!path.endsWith("/")) {
path += "/";
}
return path;
}
public Representation represent(Variant variant) throws ResourceException {
if (appCtx == null) {
throw new ResourceException(404);
}
Representation representation;
if (variant.getMediaType() == MediaType.APPLICATION_XML) {
representation = new WriterRepresentation(MediaType.APPLICATION_XML) {
public void write(Writer writer) throws IOException {
XmlMarshaller.marshalDocument(writer, "script", makePresentableMap());
}
};
} else {
representation = new WriterRepresentation(
MediaType.TEXT_HTML) {
public void write(Writer writer) throws IOException {
BeanBrowseResource.this.writeHtml(writer);
}
};
}
// TODO: remove if not necessary in future?
representation.setCharacterSet(CharacterSet.UTF_8);
return representation;
}
/**
* Constructs a nested Map data structure with the information represented
* by this Resource. The result is particularly suitable for use with with
* {@link XmlMarshaller}.
*
* @return the nested Map data structure
*/
protected LinkedHashMap<String,Object> makePresentableMap() {
LinkedHashMap<String,Object> info = new LinkedHashMap<String,Object>();
info.put("crawlJobShortName", cj.getShortName());
info.put("crawlJobUrl", new Reference(getRequest().getResourceRef().getBaseRef(), "..").getTargetRef());
if (StringUtils.isNotBlank(beanPath)) {
info.put("beanPath", beanPath);
try {
int firstDot = beanPath.indexOf(".");
String beanName = firstDot<0?beanPath:beanPath.substring(0,firstDot);
Object namedBean = appCtx.getBean(beanName);
Object target;
if (firstDot < 0) {
target = namedBean;
info.put("bean", makePresentableMapFor(null, target, beanPath));
} else {
BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean);
String propPath = beanPath.substring(firstDot+1);
target = bwrap.getPropertyValue(propPath);
Class<?> type = bwrap.getPropertyType(propPath);
if(bwrap.isWritableProperty(propPath)
&& (bwrap.getDefaultEditor(type)!=null|| type == String.class)
&& !Collection.class.isAssignableFrom(type)) {
info.put("editable", true);
info.put("bean", makePresentableMapFor(null, target));
} else {
info.put("bean", makePresentableMapFor(null, target, beanPath));
}
}
} catch (BeansException e) {
info.put("problem", e.toString());
}
}
Collection<Object> nestedNames = new LinkedList<Object>();
Set<Object> alreadyWritten = new HashSet<Object>();
addPresentableNestedNames(nestedNames, appCtx.getBean("crawlController"), alreadyWritten);
for(String name: appCtx.getBeanDefinitionNames()) {
addPresentableNestedNames(nestedNames, appCtx.getBean(name), alreadyWritten);
}
info.put("allNamedCrawlBeans", nestedNames);
return info;
}
protected void writeHtml(Writer writer) {
PrintWriter pw = new PrintWriter(writer);
pw.println("<head><title>Crawl beans in "+cj.getShortName()+"</title></head>");
pw.println("<h1>Crawl beans in built job <i><a href='/engine/job/"
+TextUtils.urlEscape(cj.getShortName())
+"'>"+cj.getShortName()+"</a></i></h1>");
pw.println("Enter a bean path of the form <i>beanName</i>, <i>beanName.property</i>, <i>beanName.property[indexOrKey]</i>, etc.");
pw.println("<form method='POST'><input type='text' name='beanPath' style='width:400px' value='"+beanPath+"'/>");
pw.println("<input type='submit' value='view'/></form>");
if (StringUtils.isNotBlank(beanPath)) {
pw.println("<h2>Bean path <i>"+beanPath+"</i></h2>");
try {
int i = beanPath.indexOf(".");
String beanName = i<0?beanPath:beanPath.substring(0,i);
Object namedBean = appCtx.getBean(beanName);
Object target;
if (i<0) {
target = namedBean;
writeObject(pw, null, target, beanPath);
} else {
BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean);
String propPath = beanPath.substring(i+1);
target = bwrap.getPropertyValue(propPath);
Class<?> type = bwrap.getPropertyType(propPath);
if(bwrap.isWritableProperty(propPath)
&& (bwrap.getDefaultEditor(type)!=null|| type == String.class)
&& !Collection.class.isAssignableFrom(type)) {
pw.println(beanPath+" = ");
writeObject(pw, null, target);
pw.println("<a href=\"javascript:document.getElementById('editform').style.display='inline';void(0);\">edit</a>");
pw.println("<span id='editform' style=\'display:none\'>Note: it may not be appropriate/effective to change this value in an already-built crawl context.<br/>");
pw.println("<form id='editform' method='POST'>");
pw.println("<input type='hidden' name='beanPath' value='"+beanPath+"'/>");
pw.println(beanPath + " = <input type='text' name='newVal' style='width:400px' value='"+target+"'/>");
pw.println("<input type='submit' value='update'/></form></span>");
} else {
writeObject(pw, null, target, beanPath);
}
}
} catch (BeansException e) {
pw.println("<i style='color:red'>problem: "+e.getMessage()+"</i>");
}
}
pw.println("<h2>All named crawl beans</h2");
pw.println("<ul>");
Set<Object> alreadyWritten = new HashSet<Object>();
writeNestedNames(pw, appCtx.getBean("crawlController"), getBeansRefPath(), alreadyWritten);
for(String name : appCtx.getBeanDefinitionNames() ) {
writeNestedNames(pw, appCtx.getBean(name), getBeansRefPath(), alreadyWritten);
}
pw.println("</ul>");
- pw.close();
}
}
| true | true | protected void writeHtml(Writer writer) {
PrintWriter pw = new PrintWriter(writer);
pw.println("<head><title>Crawl beans in "+cj.getShortName()+"</title></head>");
pw.println("<h1>Crawl beans in built job <i><a href='/engine/job/"
+TextUtils.urlEscape(cj.getShortName())
+"'>"+cj.getShortName()+"</a></i></h1>");
pw.println("Enter a bean path of the form <i>beanName</i>, <i>beanName.property</i>, <i>beanName.property[indexOrKey]</i>, etc.");
pw.println("<form method='POST'><input type='text' name='beanPath' style='width:400px' value='"+beanPath+"'/>");
pw.println("<input type='submit' value='view'/></form>");
if (StringUtils.isNotBlank(beanPath)) {
pw.println("<h2>Bean path <i>"+beanPath+"</i></h2>");
try {
int i = beanPath.indexOf(".");
String beanName = i<0?beanPath:beanPath.substring(0,i);
Object namedBean = appCtx.getBean(beanName);
Object target;
if (i<0) {
target = namedBean;
writeObject(pw, null, target, beanPath);
} else {
BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean);
String propPath = beanPath.substring(i+1);
target = bwrap.getPropertyValue(propPath);
Class<?> type = bwrap.getPropertyType(propPath);
if(bwrap.isWritableProperty(propPath)
&& (bwrap.getDefaultEditor(type)!=null|| type == String.class)
&& !Collection.class.isAssignableFrom(type)) {
pw.println(beanPath+" = ");
writeObject(pw, null, target);
pw.println("<a href=\"javascript:document.getElementById('editform').style.display='inline';void(0);\">edit</a>");
pw.println("<span id='editform' style=\'display:none\'>Note: it may not be appropriate/effective to change this value in an already-built crawl context.<br/>");
pw.println("<form id='editform' method='POST'>");
pw.println("<input type='hidden' name='beanPath' value='"+beanPath+"'/>");
pw.println(beanPath + " = <input type='text' name='newVal' style='width:400px' value='"+target+"'/>");
pw.println("<input type='submit' value='update'/></form></span>");
} else {
writeObject(pw, null, target, beanPath);
}
}
} catch (BeansException e) {
pw.println("<i style='color:red'>problem: "+e.getMessage()+"</i>");
}
}
pw.println("<h2>All named crawl beans</h2");
pw.println("<ul>");
Set<Object> alreadyWritten = new HashSet<Object>();
writeNestedNames(pw, appCtx.getBean("crawlController"), getBeansRefPath(), alreadyWritten);
for(String name : appCtx.getBeanDefinitionNames() ) {
writeNestedNames(pw, appCtx.getBean(name), getBeansRefPath(), alreadyWritten);
}
pw.println("</ul>");
pw.close();
}
| protected void writeHtml(Writer writer) {
PrintWriter pw = new PrintWriter(writer);
pw.println("<head><title>Crawl beans in "+cj.getShortName()+"</title></head>");
pw.println("<h1>Crawl beans in built job <i><a href='/engine/job/"
+TextUtils.urlEscape(cj.getShortName())
+"'>"+cj.getShortName()+"</a></i></h1>");
pw.println("Enter a bean path of the form <i>beanName</i>, <i>beanName.property</i>, <i>beanName.property[indexOrKey]</i>, etc.");
pw.println("<form method='POST'><input type='text' name='beanPath' style='width:400px' value='"+beanPath+"'/>");
pw.println("<input type='submit' value='view'/></form>");
if (StringUtils.isNotBlank(beanPath)) {
pw.println("<h2>Bean path <i>"+beanPath+"</i></h2>");
try {
int i = beanPath.indexOf(".");
String beanName = i<0?beanPath:beanPath.substring(0,i);
Object namedBean = appCtx.getBean(beanName);
Object target;
if (i<0) {
target = namedBean;
writeObject(pw, null, target, beanPath);
} else {
BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean);
String propPath = beanPath.substring(i+1);
target = bwrap.getPropertyValue(propPath);
Class<?> type = bwrap.getPropertyType(propPath);
if(bwrap.isWritableProperty(propPath)
&& (bwrap.getDefaultEditor(type)!=null|| type == String.class)
&& !Collection.class.isAssignableFrom(type)) {
pw.println(beanPath+" = ");
writeObject(pw, null, target);
pw.println("<a href=\"javascript:document.getElementById('editform').style.display='inline';void(0);\">edit</a>");
pw.println("<span id='editform' style=\'display:none\'>Note: it may not be appropriate/effective to change this value in an already-built crawl context.<br/>");
pw.println("<form id='editform' method='POST'>");
pw.println("<input type='hidden' name='beanPath' value='"+beanPath+"'/>");
pw.println(beanPath + " = <input type='text' name='newVal' style='width:400px' value='"+target+"'/>");
pw.println("<input type='submit' value='update'/></form></span>");
} else {
writeObject(pw, null, target, beanPath);
}
}
} catch (BeansException e) {
pw.println("<i style='color:red'>problem: "+e.getMessage()+"</i>");
}
}
pw.println("<h2>All named crawl beans</h2");
pw.println("<ul>");
Set<Object> alreadyWritten = new HashSet<Object>();
writeNestedNames(pw, appCtx.getBean("crawlController"), getBeansRefPath(), alreadyWritten);
for(String name : appCtx.getBeanDefinitionNames() ) {
writeNestedNames(pw, appCtx.getBean(name), getBeansRefPath(), alreadyWritten);
}
pw.println("</ul>");
}
|
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java b/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
index e0fc610..dd3d2e5 100644
--- a/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
+++ b/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
@@ -1,827 +1,829 @@
/*
* 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.pdfbox.pdfparser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.exceptions.WrappedIOException;
import org.apache.pdfbox.io.RandomAccess;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.fdf.FDFDocument;
import org.apache.pdfbox.persistence.util.COSObjectKey;
/**
* This class will handle the parsing of the PDF document.
*
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.53 $
*/
public class PDFParser extends BaseParser
{
/**
* Log instance.
*/
private static final Log log = LogFactory.getLog(PDFParser.class);
private static final int SPACE_BYTE = 32;
private static final String PDF_HEADER = "%PDF-";
private static final String FDF_HEADER = "%FDF-";
/**
* A list of duplicate objects found when Parsing the PDF
* File.
*/
private List conflictList = new ArrayList();
/**
* Temp file directory.
*/
private File tempDirectory = null;
private RandomAccess raf = null;
/**
* Constructor.
*
* @param input The input stream that contains the PDF document.
*
* @throws IOException If there is an error initializing the stream.
*/
public PDFParser( InputStream input ) throws IOException {
this(input, null, FORCE_PARSING);
}
/**
* Constructor to allow control over RandomAccessFile.
* @param input The input stream that contains the PDF document.
* @param rafi The RandomAccessFile to be used in internal COSDocument
*
* @throws IOException If there is an error initializing the stream.
*/
public PDFParser(InputStream input, RandomAccess rafi)
throws IOException {
this(input, rafi, FORCE_PARSING);
}
/**
* Constructor to allow control over RandomAccessFile.
* Also enables parser to skip corrupt objects to try and force parsing
* @param input The input stream that contains the PDF document.
* @param rafi The RandomAccessFile to be used in internal COSDocument
* @param force When true, the parser will skip corrupt pdf objects and
* will continue parsing at the next object in the file
*
* @throws IOException If there is an error initializing the stream.
*/
public PDFParser(InputStream input, RandomAccess rafi, boolean force)
throws IOException {
super(input, force);
this.raf = rafi;
}
/**
* This is the directory where pdfbox will create a temporary file
* for storing pdf document stream in. By default this directory will
* be the value of the system property java.io.tmpdir.
*
* @param tmpDir The directory to create scratch files needed to store
* pdf document streams.
*/
public void setTempDirectory( File tmpDir )
{
tempDirectory = tmpDir;
}
/**
* Returns true if parsing should be continued. By default, forceParsing is returned.
* This can be overridden to add application specific handling (for example to stop
* parsing when the number of exceptions thrown exceed a certain number).
*
* @param e The exception if vailable. Can be null if there is no exception available
*/
protected boolean isContinueOnError(Exception e)
{
return forceParsing;
}
/**
* This will parse the stream and populate the COSDocument object. This will close
* the stream when it is done parsing.
*
* @throws IOException If there is an error reading from the stream or corrupt data
* is found.
*/
public void parse() throws IOException
{
try
{
if ( raf == null )
{
if( tempDirectory != null )
{
document = new COSDocument( tempDirectory );
}
else
{
document = new COSDocument();
}
}
else
{
document = new COSDocument( raf );
}
setDocument( document );
parseHeader();
//Some PDF files have garbage between the header and the
//first object
skipToNextObj();
boolean wasLastParsedObjectEOF = false;
try
{
while(true)
{
if(pdfSource.isEOF())
{
break;
}
try
{
wasLastParsedObjectEOF = parseObject();
}
catch(IOException e)
{
if(isContinueOnError(e))
{
/*
* Warning is sent to the PDFBox.log and to the Console that
* we skipped over an object
*/
log.warn("Parsing Error, Skipping Object", e);
skipToNextObj();
}
else
{
throw e;
}
}
skipSpaces();
}
//Test if we saw a trailer section. If not, look for an XRef Stream (Cross-Reference Stream)
//to populate the trailer and xref information. For PDF 1.5 and above
if( document.getTrailer() == null )
{
document.parseXrefStreams();
}
if( !document.isEncrypted() )
{
document.dereferenceObjectStreams();
}
ConflictObj.resolveConflicts(document, conflictList);
}
catch( IOException e )
{
/*
* PDF files may have random data after the EOF marker. Ignore errors if
* last object processed is EOF.
*/
if( !wasLastParsedObjectEOF )
{
throw e;
}
}
}
catch( Throwable t )
{
//so if the PDF is corrupt then close the document and clear
//all resources to it
if( document != null )
{
document.close();
}
if( t instanceof IOException )
{
throw (IOException)t;
}
else
{
throw new WrappedIOException( t );
}
}
finally
{
pdfSource.close();
}
}
/**
* Skip to the start of the next object. This is used to recover
* from a corrupt object. This should handle all cases that parseObject
* supports. This assumes that the next object will
* start on its own line.
*
* @throws IOException
*/
private void skipToNextObj() throws IOException
{
byte[] b = new byte[16];
Pattern p = Pattern.compile("\\d+\\s+\\d+\\s+obj.*", Pattern.DOTALL);
/* Read a buffer of data each time to see if it starts with a
* known keyword. This is not the most efficient design, but we should
* rarely be needing this function. We could update this to use the
* circular buffer, like in readUntilEndStream().
*/
while(!pdfSource.isEOF())
{
int l = pdfSource.read(b);
if(l < 1)
{
break;
}
String s = new String(b, "US-ASCII");
if(s.startsWith("trailer") ||
s.startsWith("xref") ||
s.startsWith("startxref") ||
s.startsWith("stream") ||
p.matcher(s).matches())
{
pdfSource.unread(b);
break;
}
else
{
pdfSource.unread(b, 1, l-1);
}
}
}
private void parseHeader() throws IOException
{
// read first line
String header = readLine();
// some pdf-documents are broken and the pdf-version is in one of the following lines
if ((header.indexOf( PDF_HEADER ) == -1) && (header.indexOf( FDF_HEADER ) == -1))
{
header = readLine();
while ((header.indexOf( PDF_HEADER ) == -1) && (header.indexOf( FDF_HEADER ) == -1))
{
// if a line starts with a digit, it has to be the first one with data in it
if ((header.length() > 0) && (Character.isDigit(header.charAt(0))))
{
break;
}
header = readLine();
}
}
// nothing found
if ((header.indexOf( PDF_HEADER ) == -1) && (header.indexOf( FDF_HEADER ) == -1))
{
throw new IOException( "Error: Header doesn't contain versioninfo" );
}
//sometimes there are some garbage bytes in the header before the header
//actually starts, so lets try to find the header first.
int headerStart = header.indexOf( PDF_HEADER );
if (headerStart == -1)
{
headerStart = header.indexOf(FDF_HEADER);
}
//greater than zero because if it is zero then
//there is no point of trimming
if ( headerStart > 0 )
{
//trim off any leading characters
header = header.substring( headerStart, header.length() );
}
/*
* This is used if there is garbage after the header on the same line
*/
if (header.startsWith(PDF_HEADER))
{
if(!header.matches(PDF_HEADER + "\\d.\\d"))
{
String headerGarbage = header.substring(PDF_HEADER.length()+3, header.length()) + "\n";
header = header.substring(0, PDF_HEADER.length()+3);
pdfSource.unread(headerGarbage.getBytes("ISO-8859-1"));
}
}
else
{
if(!header.matches(FDF_HEADER + "\\d.\\d"))
{
String headerGarbage = header.substring(FDF_HEADER.length()+3, header.length()) + "\n";
header = header.substring(0, FDF_HEADER.length()+3);
pdfSource.unread(headerGarbage.getBytes("ISO-8859-1"));
}
}
document.setHeaderString(header);
try
{
if (header.startsWith( PDF_HEADER ))
{
float pdfVersion = Float. parseFloat(
header.substring( PDF_HEADER.length(), Math.min( header.length(), PDF_HEADER .length()+3) ) );
document.setVersion( pdfVersion );
}
else
{
float pdfVersion = Float. parseFloat(
header.substring( FDF_HEADER.length(), Math.min( header.length(), FDF_HEADER.length()+3) ) );
document.setVersion( pdfVersion );
}
}
catch ( NumberFormatException e )
{
throw new IOException( "Error getting pdf version:" + e );
}
}
/**
* This will get the document that was parsed. parse() must be called before this is called.
* When you are done with this document you must call close() on it to release
* resources.
*
* @return The document that was parsed.
*
* @throws IOException If there is an error getting the document.
*/
public COSDocument getDocument() throws IOException
{
if( document == null )
{
throw new IOException( "You must call parse() before calling getDocument()" );
}
return document;
}
/**
* This will get the PD document that was parsed. When you are done with
* this document you must call close() on it to release resources.
*
* @return The document at the PD layer.
*
* @throws IOException If there is an error getting the document.
*/
public PDDocument getPDDocument() throws IOException
{
return new PDDocument( getDocument() );
}
/**
* This will get the FDF document that was parsed. When you are done with
* this document you must call close() on it to release resources.
*
* @return The document at the PD layer.
*
* @throws IOException If there is an error getting the document.
*/
public FDFDocument getFDFDocument() throws IOException
{
return new FDFDocument( getDocument() );
}
/**
* This will parse the next object from the stream and add it to
* the local state.
*
* @return Returns true if the processed object had an endOfFile marker
*
* @throws IOException If an IO error occurs.
*/
private boolean parseObject() throws IOException
{
int currentObjByteOffset = pdfSource.getOffset();
boolean isEndOfFile = false;
skipSpaces();
//peek at the next character to determine the type of object we are parsing
char peekedChar = (char)pdfSource.peek();
//ignore endobj and endstream sections.
while( peekedChar == 'e' )
{
//there are times when there are multiple endobj, so lets
//just read them and move on.
readString();
skipSpaces();
peekedChar = (char)pdfSource.peek();
}
if( pdfSource.isEOF())
{
//"Skipping because of EOF" );
//end of file we will return a false and call it a day.
}
//xref table. Note: The contents of the Xref table are currently ignored
else if( peekedChar == 'x')
{
parseXrefTable();
}
// Note: startxref can occur in either a trailer section or by itself
else if (peekedChar == 't' || peekedChar == 's')
{
if(peekedChar == 't')
{
parseTrailer();
peekedChar = (char)pdfSource.peek();
}
if (peekedChar == 's')
{
parseStartXref();
// readString() calls skipSpaces() will skip comments... that's
// bad for us b/c the %%EOF flag is a comment
while(isWhitespace(pdfSource.peek()) && !pdfSource.isEOF())
pdfSource.read(); // read (get rid of) all the whitespace
String eof = "";
if(!pdfSource.isEOF())
- readLine(); // if there's more data to read, get the EOF flag
+ eof = readLine(); // if there's more data to read, get the EOF flag
// verify that EOF exists
- if("%%EOF".equals(eof)) {
+ if(!"%%EOF".equals(eof)) {
// PDF does not conform to spec, we should warn someone
log.warn("expected='%%EOF' actual='" + eof + "'");
// if we're not at the end of a file, just put it back and move on
- if(!pdfSource.isEOF())
+ if(!pdfSource.isEOF()) {
pdfSource.unread(eof.getBytes("ISO-8859-1"));
+ pdfSource.unread( SPACE_BYTE ); // we read a whole line; add space as newline replacement
+ }
}
isEndOfFile = true;
}
}
//we are going to parse an normal object
else
{
int number = -1;
int genNum = -1;
String objectKey = null;
boolean missingObjectNumber = false;
try
{
char peeked = (char)pdfSource.peek();
if( peeked == '<' )
{
missingObjectNumber = true;
}
else
{
number = readInt();
}
}
catch( IOException e )
{
//ok for some reason "GNU Ghostscript 5.10" puts two endobj
//statements after an object, of course this is nonsense
//but because we want to support as many PDFs as possible
//we will simply try again
number = readInt();
}
if( !missingObjectNumber )
{
skipSpaces();
genNum = readInt();
objectKey = readString( 3 );
//System.out.println( "parseObject() num=" + number +
//" genNumber=" + genNum + " key='" + objectKey + "'" );
if( !objectKey.equals( "obj" ) )
{
if (!isContinueOnError(null) || !objectKey.equals("o")) {
throw new IOException("expected='obj' actual='" + objectKey + "' " + pdfSource);
}
//assume that "o" was meant to be "obj" (this is a workaround for
// PDFBOX-773 attached PDF Andersens_Fairy_Tales.pdf).
}
}
else
{
number = -1;
genNum = -1;
}
skipSpaces();
COSBase pb = parseDirObject();
String endObjectKey = readString();
if( endObjectKey.equals( "stream" ) )
{
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
pdfSource.unread( ' ' );
if( pb instanceof COSDictionary )
{
pb = parseCOSStream( (COSDictionary)pb, getDocument().getScratchFile() );
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream forms a complete stream object
throw new IOException("stream not preceded by dictionary");
}
skipSpaces();
endObjectKey = readLine();
}
COSObjectKey key = new COSObjectKey( number, genNum );
COSObject pdfObject = document.getObjectFromPool( key );
if(pdfObject.getObject() == null)
{
pdfObject.setObject(pb);
}
/*
* If the object we returned already has a baseobject, then we have a conflict
* which we will resolve using information after we parse the xref table.
*/
else
{
addObjectToConflicts(currentObjByteOffset, key, pb);
}
if( !endObjectKey.equals( "endobj" ) )
{
if (endObjectKey.startsWith( "endobj" ) )
{
/*
* Some PDF files don't contain a new line after endobj so we
* need to make sure that the next object number is getting read separately
* and not part of the endobj keyword. Ex. Some files would have "endobj28"
* instead of "endobj"
*/
pdfSource.unread( endObjectKey.substring( 6 ).getBytes("ISO-8859-1") );
}
else if(endObjectKey.trim().endsWith("endobj"))
{
/*
* Some PDF files contain junk (like ">> ", in the case of a PDF
* I found which was created by Exstream Dialogue Version 5.0.039)
* in which case we ignore the data before endobj and just move on
*/
log.warn("expected='endobj' actual='" + endObjectKey + "' ");
}
else if( !pdfSource.isEOF() )
{
//It is possible that the endobj is missing, there
//are several PDFs out there that do that so. Unread
//and assume that endobj was missing
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
}
}
skipSpaces();
}
return isEndOfFile;
}
/**
* Adds a new ConflictObj to the conflictList.
* @param offset the offset of the ConflictObj
* @param key The COSObjectKey of this object
* @param pb The COSBase of this conflictObj
* @throws IOException
*/
private void addObjectToConflicts(int offset, COSObjectKey key, COSBase pb) throws IOException
{
COSObject obj = new COSObject(null);
obj.setObjectNumber( COSInteger.get( key.getNumber() ) );
obj.setGenerationNumber( COSInteger.get( key.getGeneration() ) );
obj.setObject(pb);
ConflictObj conflictObj = new ConflictObj(offset, key, obj);
conflictList.add(conflictObj);
}
/**
* This will parse the startxref section from the stream.
* The startxref value is ignored.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseStartXref() throws IOException
{
if(pdfSource.peek() != 's')
{
return false;
}
String startXRef = readString();
if( !startXRef.trim().equals( "startxref" ) )
{
return false;
}
skipSpaces();
/* This integer is the byte offset of the first object referenced by the xref or xref stream
* Not needed for PDFbox
*/
readInt();
return true;
}
/**
* This will parse the xref table from the stream and add it to the state
* The XrefTable contents are ignored.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseXrefTable() throws IOException
{
if(pdfSource.peek() != 'x')
{
return false;
}
String xref = readString();
if( !xref.trim().equals( "xref" ) )
{
return false;
}
/*
* Xref tables can have multiple sections.
* Each starts with a starting object id and a count.
*/
while(true)
{
int currObjID = readInt(); // first obj id
int count = readInt(); // the number of objects in the xref table
skipSpaces();
for(int i = 0; i < count; i++)
{
if(pdfSource.isEOF() || isEndOfName((char)pdfSource.peek()))
{
break;
}
if(pdfSource.peek() == 't')
{
break;
}
//Ignore table contents
String currentLine = readLine();
String[] splitString = currentLine.split(" ");
if (splitString.length < 3)
{
log.warn("invalid xref line: " + currentLine);
break;
}
/* This supports the corrupt table as reported in
* PDFBOX-474 (XXXX XXX XX n) */
if(splitString[splitString.length-1].equals("n"))
{
try
{
int currOffset = Integer.parseInt(splitString[0]);
int currGenID = Integer.parseInt(splitString[1]);
COSObjectKey objKey = new COSObjectKey(currObjID, currGenID);
document.setXRef(objKey, currOffset);
}
catch(NumberFormatException e)
{
throw new IOException(e.getMessage());
}
}
else if(!splitString[2].equals("f"))
{
throw new IOException("Corrupt XRefTable Entry - ObjID:" + currObjID);
}
currObjID++;
skipSpaces();
}
skipSpaces();
char c = (char)pdfSource.peek();
if(c < '0' || c > '9')
{
break;
}
}
return true;
}
/**
* This will parse the trailer from the stream and add it to the state.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseTrailer() throws IOException
{
if(pdfSource.peek() != 't')
{
return false;
}
//read "trailer"
String nextLine = readLine();
if( !nextLine.trim().equals( "trailer" ) )
{
// in some cases the EOL is missing and the trailer immediately
// continues with "<<" or with a blank character
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
if (nextLine.startsWith("trailer"))
{
byte[] b = nextLine.getBytes("ISO-8859-1");
int len = "trailer".length();
pdfSource.unread('\n');
pdfSource.unread(b, len, b.length-len);
}
else
{
return false;
}
}
// in some cases the EOL is missing and the trailer continues with " <<"
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
skipSpaces();
COSDictionary parsedTrailer = parseCOSDictionary();
COSDictionary docTrailer = document.getTrailer();
if( docTrailer == null )
{
document.setTrailer( parsedTrailer );
}
else
{
docTrailer.addAll( parsedTrailer );
}
skipSpaces();
return true;
}
/**
* Used to resolve conflicts when a PDF Document has multiple objects with
* the same id number. Ideally, we could use the Xref table when parsing
* the document to be able to determine which of the objects with the same ID
* is correct, but we do not have access to the Xref Table during parsing.
* Instead, we queue up the conflicts and resolve them after the Xref has
* been parsed. The Objects listed in the Xref Table are kept and the
* others are ignored.
*/
private static class ConflictObj
{
private int offset;
private COSObjectKey objectKey;
private COSObject object;
public ConflictObj(int offsetValue, COSObjectKey key, COSObject pdfObject)
{
this.offset = offsetValue;
this.objectKey = key;
this.object = pdfObject;
}
public String toString()
{
return "Object(" + offset + ", " + objectKey + ")";
}
/**
* Sometimes pdf files have objects with the same ID number yet are
* not referenced by the Xref table and therefore should be excluded.
* This method goes through the conflicts list and replaces the object stored
* in the objects array with this one if it is referenced by the xref
* table.
* @throws IOException
*/
private static void resolveConflicts(COSDocument document, List conflictList) throws IOException
{
Iterator conflicts = conflictList.iterator();
while(conflicts.hasNext())
{
ConflictObj o = (ConflictObj)conflicts.next();
Integer offset = new Integer(o.offset);
if(document.getXrefTable().containsValue(offset))
{
COSObject pdfObject = document.getObjectFromPool(o.objectKey);
pdfObject.setObject(o.object.getObject());
}
}
}
}
}
| false | true | private boolean parseObject() throws IOException
{
int currentObjByteOffset = pdfSource.getOffset();
boolean isEndOfFile = false;
skipSpaces();
//peek at the next character to determine the type of object we are parsing
char peekedChar = (char)pdfSource.peek();
//ignore endobj and endstream sections.
while( peekedChar == 'e' )
{
//there are times when there are multiple endobj, so lets
//just read them and move on.
readString();
skipSpaces();
peekedChar = (char)pdfSource.peek();
}
if( pdfSource.isEOF())
{
//"Skipping because of EOF" );
//end of file we will return a false and call it a day.
}
//xref table. Note: The contents of the Xref table are currently ignored
else if( peekedChar == 'x')
{
parseXrefTable();
}
// Note: startxref can occur in either a trailer section or by itself
else if (peekedChar == 't' || peekedChar == 's')
{
if(peekedChar == 't')
{
parseTrailer();
peekedChar = (char)pdfSource.peek();
}
if (peekedChar == 's')
{
parseStartXref();
// readString() calls skipSpaces() will skip comments... that's
// bad for us b/c the %%EOF flag is a comment
while(isWhitespace(pdfSource.peek()) && !pdfSource.isEOF())
pdfSource.read(); // read (get rid of) all the whitespace
String eof = "";
if(!pdfSource.isEOF())
readLine(); // if there's more data to read, get the EOF flag
// verify that EOF exists
if("%%EOF".equals(eof)) {
// PDF does not conform to spec, we should warn someone
log.warn("expected='%%EOF' actual='" + eof + "'");
// if we're not at the end of a file, just put it back and move on
if(!pdfSource.isEOF())
pdfSource.unread(eof.getBytes("ISO-8859-1"));
}
isEndOfFile = true;
}
}
//we are going to parse an normal object
else
{
int number = -1;
int genNum = -1;
String objectKey = null;
boolean missingObjectNumber = false;
try
{
char peeked = (char)pdfSource.peek();
if( peeked == '<' )
{
missingObjectNumber = true;
}
else
{
number = readInt();
}
}
catch( IOException e )
{
//ok for some reason "GNU Ghostscript 5.10" puts two endobj
//statements after an object, of course this is nonsense
//but because we want to support as many PDFs as possible
//we will simply try again
number = readInt();
}
if( !missingObjectNumber )
{
skipSpaces();
genNum = readInt();
objectKey = readString( 3 );
//System.out.println( "parseObject() num=" + number +
//" genNumber=" + genNum + " key='" + objectKey + "'" );
if( !objectKey.equals( "obj" ) )
{
if (!isContinueOnError(null) || !objectKey.equals("o")) {
throw new IOException("expected='obj' actual='" + objectKey + "' " + pdfSource);
}
//assume that "o" was meant to be "obj" (this is a workaround for
// PDFBOX-773 attached PDF Andersens_Fairy_Tales.pdf).
}
}
else
{
number = -1;
genNum = -1;
}
skipSpaces();
COSBase pb = parseDirObject();
String endObjectKey = readString();
if( endObjectKey.equals( "stream" ) )
{
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
pdfSource.unread( ' ' );
if( pb instanceof COSDictionary )
{
pb = parseCOSStream( (COSDictionary)pb, getDocument().getScratchFile() );
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream forms a complete stream object
throw new IOException("stream not preceded by dictionary");
}
skipSpaces();
endObjectKey = readLine();
}
COSObjectKey key = new COSObjectKey( number, genNum );
COSObject pdfObject = document.getObjectFromPool( key );
if(pdfObject.getObject() == null)
{
pdfObject.setObject(pb);
}
/*
* If the object we returned already has a baseobject, then we have a conflict
* which we will resolve using information after we parse the xref table.
*/
else
{
addObjectToConflicts(currentObjByteOffset, key, pb);
}
if( !endObjectKey.equals( "endobj" ) )
{
if (endObjectKey.startsWith( "endobj" ) )
{
/*
* Some PDF files don't contain a new line after endobj so we
* need to make sure that the next object number is getting read separately
* and not part of the endobj keyword. Ex. Some files would have "endobj28"
* instead of "endobj"
*/
pdfSource.unread( endObjectKey.substring( 6 ).getBytes("ISO-8859-1") );
}
else if(endObjectKey.trim().endsWith("endobj"))
{
/*
* Some PDF files contain junk (like ">> ", in the case of a PDF
* I found which was created by Exstream Dialogue Version 5.0.039)
* in which case we ignore the data before endobj and just move on
*/
log.warn("expected='endobj' actual='" + endObjectKey + "' ");
}
else if( !pdfSource.isEOF() )
{
//It is possible that the endobj is missing, there
//are several PDFs out there that do that so. Unread
//and assume that endobj was missing
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
}
}
skipSpaces();
}
return isEndOfFile;
}
| private boolean parseObject() throws IOException
{
int currentObjByteOffset = pdfSource.getOffset();
boolean isEndOfFile = false;
skipSpaces();
//peek at the next character to determine the type of object we are parsing
char peekedChar = (char)pdfSource.peek();
//ignore endobj and endstream sections.
while( peekedChar == 'e' )
{
//there are times when there are multiple endobj, so lets
//just read them and move on.
readString();
skipSpaces();
peekedChar = (char)pdfSource.peek();
}
if( pdfSource.isEOF())
{
//"Skipping because of EOF" );
//end of file we will return a false and call it a day.
}
//xref table. Note: The contents of the Xref table are currently ignored
else if( peekedChar == 'x')
{
parseXrefTable();
}
// Note: startxref can occur in either a trailer section or by itself
else if (peekedChar == 't' || peekedChar == 's')
{
if(peekedChar == 't')
{
parseTrailer();
peekedChar = (char)pdfSource.peek();
}
if (peekedChar == 's')
{
parseStartXref();
// readString() calls skipSpaces() will skip comments... that's
// bad for us b/c the %%EOF flag is a comment
while(isWhitespace(pdfSource.peek()) && !pdfSource.isEOF())
pdfSource.read(); // read (get rid of) all the whitespace
String eof = "";
if(!pdfSource.isEOF())
eof = readLine(); // if there's more data to read, get the EOF flag
// verify that EOF exists
if(!"%%EOF".equals(eof)) {
// PDF does not conform to spec, we should warn someone
log.warn("expected='%%EOF' actual='" + eof + "'");
// if we're not at the end of a file, just put it back and move on
if(!pdfSource.isEOF()) {
pdfSource.unread(eof.getBytes("ISO-8859-1"));
pdfSource.unread( SPACE_BYTE ); // we read a whole line; add space as newline replacement
}
}
isEndOfFile = true;
}
}
//we are going to parse an normal object
else
{
int number = -1;
int genNum = -1;
String objectKey = null;
boolean missingObjectNumber = false;
try
{
char peeked = (char)pdfSource.peek();
if( peeked == '<' )
{
missingObjectNumber = true;
}
else
{
number = readInt();
}
}
catch( IOException e )
{
//ok for some reason "GNU Ghostscript 5.10" puts two endobj
//statements after an object, of course this is nonsense
//but because we want to support as many PDFs as possible
//we will simply try again
number = readInt();
}
if( !missingObjectNumber )
{
skipSpaces();
genNum = readInt();
objectKey = readString( 3 );
//System.out.println( "parseObject() num=" + number +
//" genNumber=" + genNum + " key='" + objectKey + "'" );
if( !objectKey.equals( "obj" ) )
{
if (!isContinueOnError(null) || !objectKey.equals("o")) {
throw new IOException("expected='obj' actual='" + objectKey + "' " + pdfSource);
}
//assume that "o" was meant to be "obj" (this is a workaround for
// PDFBOX-773 attached PDF Andersens_Fairy_Tales.pdf).
}
}
else
{
number = -1;
genNum = -1;
}
skipSpaces();
COSBase pb = parseDirObject();
String endObjectKey = readString();
if( endObjectKey.equals( "stream" ) )
{
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
pdfSource.unread( ' ' );
if( pb instanceof COSDictionary )
{
pb = parseCOSStream( (COSDictionary)pb, getDocument().getScratchFile() );
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream forms a complete stream object
throw new IOException("stream not preceded by dictionary");
}
skipSpaces();
endObjectKey = readLine();
}
COSObjectKey key = new COSObjectKey( number, genNum );
COSObject pdfObject = document.getObjectFromPool( key );
if(pdfObject.getObject() == null)
{
pdfObject.setObject(pb);
}
/*
* If the object we returned already has a baseobject, then we have a conflict
* which we will resolve using information after we parse the xref table.
*/
else
{
addObjectToConflicts(currentObjByteOffset, key, pb);
}
if( !endObjectKey.equals( "endobj" ) )
{
if (endObjectKey.startsWith( "endobj" ) )
{
/*
* Some PDF files don't contain a new line after endobj so we
* need to make sure that the next object number is getting read separately
* and not part of the endobj keyword. Ex. Some files would have "endobj28"
* instead of "endobj"
*/
pdfSource.unread( endObjectKey.substring( 6 ).getBytes("ISO-8859-1") );
}
else if(endObjectKey.trim().endsWith("endobj"))
{
/*
* Some PDF files contain junk (like ">> ", in the case of a PDF
* I found which was created by Exstream Dialogue Version 5.0.039)
* in which case we ignore the data before endobj and just move on
*/
log.warn("expected='endobj' actual='" + endObjectKey + "' ");
}
else if( !pdfSource.isEOF() )
{
//It is possible that the endobj is missing, there
//are several PDFs out there that do that so. Unread
//and assume that endobj was missing
pdfSource.unread( endObjectKey.getBytes("ISO-8859-1") );
}
}
skipSpaces();
}
return isEndOfFile;
}
|
diff --git a/plugins/org.jboss.tools.ws.creation.core/src/org/jboss/tools/ws/creation/core/commands/AbstractGenerateCodeCommand.java b/plugins/org.jboss.tools.ws.creation.core/src/org/jboss/tools/ws/creation/core/commands/AbstractGenerateCodeCommand.java
index af3a8d36..8f61ce67 100644
--- a/plugins/org.jboss.tools.ws.creation.core/src/org/jboss/tools/ws/creation/core/commands/AbstractGenerateCodeCommand.java
+++ b/plugins/org.jboss.tools.ws.creation.core/src/org/jboss/tools/ws/creation/core/commands/AbstractGenerateCodeCommand.java
@@ -1,169 +1,169 @@
package org.jboss.tools.ws.creation.core.commands;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.osgi.util.NLS;
import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
import org.jboss.tools.ws.core.utils.StatusUtils;
import org.jboss.tools.ws.creation.core.JBossWSCreationCore;
import org.jboss.tools.ws.creation.core.data.ServiceModel;
import org.jboss.tools.ws.creation.core.messages.JBossWSCreationCoreMessages;
import org.jboss.tools.ws.creation.core.utils.JBossWSCreationUtils;
abstract class AbstractGenerateCodeCommand extends AbstractDataModelOperation {
protected ServiceModel model;
private String cmdFileName_linux;
private String cmdFileName_win;
public AbstractGenerateCodeCommand(ServiceModel model) {
this.model = model;
cmdFileName_linux = getCommandLineFileName_linux();
cmdFileName_win = getCommandLineFileName_win();
}
@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
IStatus status = Status.OK_STATUS;
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(
model.getWebProjectName());
String projectRoot = JBossWSCreationUtils.getProjectRoot(
model.getWebProjectName()).toOSString();
IJavaProject javaProject = JavaCore.create(project);
try {
String runtimeLocation = JBossWSCreationUtils
.getJBossWSRuntimeLocation(project);
String commandLocation = runtimeLocation + Path.SEPARATOR + "bin";
IPath path = new Path(commandLocation);
StringBuffer command = new StringBuffer();
if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
command.append("cmd.exe /c ").append(cmdFileName_win);
path = path.append(cmdFileName_win);
} else {
command.append("sh ").append(cmdFileName_linux);
path = path.append(cmdFileName_linux);
}
if (!path.toFile().getAbsoluteFile().exists()) {
return StatusUtils
.errorStatus(NLS
.bind(
JBossWSCreationCoreMessages.Error_Message_Command_File_Not_Found,
new String[] { path.toOSString() }));
}
String args = getCommandlineArgs();
command.append(" -k ").append(args).append(" ");
if(model.getWsdlURI() != null){
command.append(model.getWsdlURI());
}
command.append(" -o ").append(projectRoot).append(Path.SEPARATOR)
.append(
javaProject.getOutputLocation()
.removeFirstSegments(1).toOSString());
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command.toString(), null, new File(
commandLocation));
StringBuffer errorResult = new StringBuffer();
StringBuffer inputResult = new StringBuffer();
convertInputStreamToString(errorResult, proc.getErrorStream());
convertInputStreamToString(inputResult, proc.getInputStream());
int exitValue = proc.waitFor();
if (exitValue != 0) {
return StatusUtils.errorStatus(errorResult.toString());
} else {
String resultInput = inputResult.toString();
if (resultInput != null && resultInput.indexOf("[ERROR]") >= 0) {
JBossWSCreationCore.getDefault().logError(resultInput);
- IStatus errorStatus = StatusUtils.errorStatus(resultInput);
+ IStatus errorStatus = StatusUtils.warningStatus(resultInput);
status = StatusUtils
- .errorStatus(
+ .warningStatus(
JBossWSCreationCoreMessages.Error_Message_Failed_To_Generate_Code,
new CoreException(errorStatus));
} else {
JBossWSCreationCore.getDefault().logInfo(resultInput);
}
}
} catch (IOException e) {
JBossWSCreationCore.getDefault().logError(e);
} catch (InterruptedException e) {
// ignore
} catch (CoreException e) {
JBossWSCreationCore.getDefault().logError(e);
// unable to get runtime location
return e.getStatus();
}
refreshProject(model.getWebProjectName(), monitor);
return status;
}
private void convertInputStreamToString(final StringBuffer result,
final InputStream input) {
Thread thread = new Thread() {
public void run() {
try {
InputStreamReader ir = new InputStreamReader(input);
LineNumberReader reader = new LineNumberReader(ir);
String str;
str = reader.readLine();
while (str != null) {
result.append(str).append("\t\r");
str = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void refreshProject(String project, IProgressMonitor monitor) {
try {
JBossWSCreationUtils.getProjectByName(project).refreshLocal(2,
monitor);
} catch (CoreException e) {
e.printStackTrace();
JBossWSCreationCore.getDefault().logError(e);
}
}
abstract protected String getCommandlineArgs();
abstract protected String getCommandLineFileName_linux();
abstract protected String getCommandLineFileName_win();
}
| false | true | public IStatus execute(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
IStatus status = Status.OK_STATUS;
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(
model.getWebProjectName());
String projectRoot = JBossWSCreationUtils.getProjectRoot(
model.getWebProjectName()).toOSString();
IJavaProject javaProject = JavaCore.create(project);
try {
String runtimeLocation = JBossWSCreationUtils
.getJBossWSRuntimeLocation(project);
String commandLocation = runtimeLocation + Path.SEPARATOR + "bin";
IPath path = new Path(commandLocation);
StringBuffer command = new StringBuffer();
if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
command.append("cmd.exe /c ").append(cmdFileName_win);
path = path.append(cmdFileName_win);
} else {
command.append("sh ").append(cmdFileName_linux);
path = path.append(cmdFileName_linux);
}
if (!path.toFile().getAbsoluteFile().exists()) {
return StatusUtils
.errorStatus(NLS
.bind(
JBossWSCreationCoreMessages.Error_Message_Command_File_Not_Found,
new String[] { path.toOSString() }));
}
String args = getCommandlineArgs();
command.append(" -k ").append(args).append(" ");
if(model.getWsdlURI() != null){
command.append(model.getWsdlURI());
}
command.append(" -o ").append(projectRoot).append(Path.SEPARATOR)
.append(
javaProject.getOutputLocation()
.removeFirstSegments(1).toOSString());
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command.toString(), null, new File(
commandLocation));
StringBuffer errorResult = new StringBuffer();
StringBuffer inputResult = new StringBuffer();
convertInputStreamToString(errorResult, proc.getErrorStream());
convertInputStreamToString(inputResult, proc.getInputStream());
int exitValue = proc.waitFor();
if (exitValue != 0) {
return StatusUtils.errorStatus(errorResult.toString());
} else {
String resultInput = inputResult.toString();
if (resultInput != null && resultInput.indexOf("[ERROR]") >= 0) {
JBossWSCreationCore.getDefault().logError(resultInput);
IStatus errorStatus = StatusUtils.errorStatus(resultInput);
status = StatusUtils
.errorStatus(
JBossWSCreationCoreMessages.Error_Message_Failed_To_Generate_Code,
new CoreException(errorStatus));
} else {
JBossWSCreationCore.getDefault().logInfo(resultInput);
}
}
} catch (IOException e) {
JBossWSCreationCore.getDefault().logError(e);
} catch (InterruptedException e) {
// ignore
} catch (CoreException e) {
JBossWSCreationCore.getDefault().logError(e);
// unable to get runtime location
return e.getStatus();
}
refreshProject(model.getWebProjectName(), monitor);
return status;
}
| public IStatus execute(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
IStatus status = Status.OK_STATUS;
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(
model.getWebProjectName());
String projectRoot = JBossWSCreationUtils.getProjectRoot(
model.getWebProjectName()).toOSString();
IJavaProject javaProject = JavaCore.create(project);
try {
String runtimeLocation = JBossWSCreationUtils
.getJBossWSRuntimeLocation(project);
String commandLocation = runtimeLocation + Path.SEPARATOR + "bin";
IPath path = new Path(commandLocation);
StringBuffer command = new StringBuffer();
if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
command.append("cmd.exe /c ").append(cmdFileName_win);
path = path.append(cmdFileName_win);
} else {
command.append("sh ").append(cmdFileName_linux);
path = path.append(cmdFileName_linux);
}
if (!path.toFile().getAbsoluteFile().exists()) {
return StatusUtils
.errorStatus(NLS
.bind(
JBossWSCreationCoreMessages.Error_Message_Command_File_Not_Found,
new String[] { path.toOSString() }));
}
String args = getCommandlineArgs();
command.append(" -k ").append(args).append(" ");
if(model.getWsdlURI() != null){
command.append(model.getWsdlURI());
}
command.append(" -o ").append(projectRoot).append(Path.SEPARATOR)
.append(
javaProject.getOutputLocation()
.removeFirstSegments(1).toOSString());
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command.toString(), null, new File(
commandLocation));
StringBuffer errorResult = new StringBuffer();
StringBuffer inputResult = new StringBuffer();
convertInputStreamToString(errorResult, proc.getErrorStream());
convertInputStreamToString(inputResult, proc.getInputStream());
int exitValue = proc.waitFor();
if (exitValue != 0) {
return StatusUtils.errorStatus(errorResult.toString());
} else {
String resultInput = inputResult.toString();
if (resultInput != null && resultInput.indexOf("[ERROR]") >= 0) {
JBossWSCreationCore.getDefault().logError(resultInput);
IStatus errorStatus = StatusUtils.warningStatus(resultInput);
status = StatusUtils
.warningStatus(
JBossWSCreationCoreMessages.Error_Message_Failed_To_Generate_Code,
new CoreException(errorStatus));
} else {
JBossWSCreationCore.getDefault().logInfo(resultInput);
}
}
} catch (IOException e) {
JBossWSCreationCore.getDefault().logError(e);
} catch (InterruptedException e) {
// ignore
} catch (CoreException e) {
JBossWSCreationCore.getDefault().logError(e);
// unable to get runtime location
return e.getStatus();
}
refreshProject(model.getWebProjectName(), monitor);
return status;
}
|
diff --git a/esup-ecm-dashboard-web-springmvc-portlet/src/main/java/org/esup/ecm/dashboard/web/taglib/IntranetTagLib.java b/esup-ecm-dashboard-web-springmvc-portlet/src/main/java/org/esup/ecm/dashboard/web/taglib/IntranetTagLib.java
index 160e354..841ff24 100644
--- a/esup-ecm-dashboard-web-springmvc-portlet/src/main/java/org/esup/ecm/dashboard/web/taglib/IntranetTagLib.java
+++ b/esup-ecm-dashboard-web-springmvc-portlet/src/main/java/org/esup/ecm/dashboard/web/taglib/IntranetTagLib.java
@@ -1,35 +1,38 @@
package org.esup.ecm.dashboard.web.taglib;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.nuxeo.ecm.automation.client.model.PropertyMap;
import org.nuxeo.ecm.core.schema.utils.DateParser;
public class IntranetTagLib {
private static SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
private static final String dateColumns = "modified:created:issued:valid:expired";
public static String getValue(PropertyMap map, String key){
return map.getString(key);
}
public static String getLastModifiedDate(PropertyMap map){
Date d = DateParser.parseDate(map.getString("dc:modified"));
return sdf.format(d);
}
public static String getImgFileName(PropertyMap map){
return map.getString("common:icon");
}
public static String getDublinCoreProperty(PropertyMap map, String name){
if(dateColumns.contains(name)){
Date d = DateParser.parseDate(map.getString("dc:"+name));
return sdf.format(d);
}
+ String rtnValue = map.getString("dc:"+name);
+ if(rtnValue == null || rtnValue.equals("null"))
+ return "";
- return map.getString("dc:"+name);
+ return rtnValue;
}
}
| false | true | public static String getDublinCoreProperty(PropertyMap map, String name){
if(dateColumns.contains(name)){
Date d = DateParser.parseDate(map.getString("dc:"+name));
return sdf.format(d);
}
return map.getString("dc:"+name);
}
| public static String getDublinCoreProperty(PropertyMap map, String name){
if(dateColumns.contains(name)){
Date d = DateParser.parseDate(map.getString("dc:"+name));
return sdf.format(d);
}
String rtnValue = map.getString("dc:"+name);
if(rtnValue == null || rtnValue.equals("null"))
return "";
return rtnValue;
}
|
diff --git a/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionCancel.java b/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionCancel.java
index 44f15f2..b96b0c1 100644
--- a/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionCancel.java
+++ b/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionCancel.java
@@ -1,39 +1,43 @@
package net.invisioncraft.plugins.salesmania.commands.auction;
import net.invisioncraft.plugins.salesmania.CommandHandler;
import net.invisioncraft.plugins.salesmania.Salesmania;
import net.invisioncraft.plugins.salesmania.configuration.Locale;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* Owner: Justin
* Date: 5/17/12
* Time: 10:27 AM
*/
public class AuctionCancel extends CommandHandler {
public AuctionCancel(Salesmania plugin) {
super(plugin);
}
@Override
public boolean execute(CommandSender sender, Command command, String label, String[] args) {
Locale locale = plugin.getLocaleHandler().getLocale(sender);
+ boolean hasPermission = false;
if((sender instanceof Player)) {
- if(!sender.hasPermission("salesmania.auction.cancel") | (Player)sender != plugin.getAuction().getOwner()) {
- sender.sendMessage(
- locale.getMessage("Permission.noPermission") +
- locale.getMessage("Permission.Auction.cancel"));
+ if(sender == plugin.getAuction().getOwner() | sender.hasPermission("salesmania.auction.cancel")) {
+ hasPermission = true;
}
+ }
+ if(!hasPermission) {
+ sender.sendMessage(
+ locale.getMessage("Permission.noPermission") +
+ locale.getMessage("Permission.Auction.cancel"));
return false;
}
switch(plugin.getAuction().cancel()) {
case NOT_RUNNING:
sender.sendMessage(locale.getMessage("Auction.notRunning"));
return true;
}
return false;
}
}
| false | true | public boolean execute(CommandSender sender, Command command, String label, String[] args) {
Locale locale = plugin.getLocaleHandler().getLocale(sender);
if((sender instanceof Player)) {
if(!sender.hasPermission("salesmania.auction.cancel") | (Player)sender != plugin.getAuction().getOwner()) {
sender.sendMessage(
locale.getMessage("Permission.noPermission") +
locale.getMessage("Permission.Auction.cancel"));
}
return false;
}
switch(plugin.getAuction().cancel()) {
case NOT_RUNNING:
sender.sendMessage(locale.getMessage("Auction.notRunning"));
return true;
}
return false;
}
| public boolean execute(CommandSender sender, Command command, String label, String[] args) {
Locale locale = plugin.getLocaleHandler().getLocale(sender);
boolean hasPermission = false;
if((sender instanceof Player)) {
if(sender == plugin.getAuction().getOwner() | sender.hasPermission("salesmania.auction.cancel")) {
hasPermission = true;
}
}
if(!hasPermission) {
sender.sendMessage(
locale.getMessage("Permission.noPermission") +
locale.getMessage("Permission.Auction.cancel"));
return false;
}
switch(plugin.getAuction().cancel()) {
case NOT_RUNNING:
sender.sendMessage(locale.getMessage("Auction.notRunning"));
return true;
}
return false;
}
|
diff --git a/h2spatial-ext/src/main/java/org/h2gis/h2spatialext/function/spatial/edit/ST_RemoveRepeatedPoints.java b/h2spatial-ext/src/main/java/org/h2gis/h2spatialext/function/spatial/edit/ST_RemoveRepeatedPoints.java
index 930807aa..78b1b036 100644
--- a/h2spatial-ext/src/main/java/org/h2gis/h2spatialext/function/spatial/edit/ST_RemoveRepeatedPoints.java
+++ b/h2spatial-ext/src/main/java/org/h2gis/h2spatialext/function/spatial/edit/ST_RemoveRepeatedPoints.java
@@ -1,177 +1,180 @@
/**
* h2spatial is a library that brings spatial support to the H2 Java database.
*
* h2spatial is distributed under GPL 3 license. It is produced by the "Atelier
* SIG" team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* h2patial 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.
*
* h2spatial 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
* h2spatial. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly: info_at_ orbisgis.org
*/
package org.h2gis.h2spatialext.function.spatial.edit;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateArrays;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import java.util.ArrayList;
import org.h2gis.h2spatialapi.DeterministicScalarFunction;
/**
* Remove duplicated points on a geometry
*
* @author Erwan Bocher
*/
public class ST_RemoveRepeatedPoints extends DeterministicScalarFunction {
private static final GeometryFactory FACTORY = new GeometryFactory();
public ST_RemoveRepeatedPoints() {
addProperty(PROP_REMARKS, "Returns a version of the given geometry with duplicated points removed.");
}
@Override
public String getJavaStaticMethod() {
return "removeRepeatedPoints";
}
/**
* Returns a version of the given geometry with duplicated points removed.
*
* @param geometry
* @return
*/
public static Geometry removeRepeatedPoints(Geometry geometry) {
return removeDuplicateCoordinates(geometry);
}
/**
* Removes duplicated points within a geometry.
*
* @param geom
* @return
*/
public static Geometry removeDuplicateCoordinates(Geometry geom) {
- if (geom.isEmpty()) {
+ if(geom ==null){
+ return null;
+ }
+ else if (geom.isEmpty()) {
return geom;
} else if (geom instanceof Point || geom instanceof MultiPoint) {
return geom;
} else if (geom instanceof LineString) {
return removeDuplicateCoordinates((LineString) geom);
} else if (geom instanceof MultiLineString) {
return removeDuplicateCoordinates((MultiLineString) geom);
} else if (geom instanceof Polygon) {
return removeDuplicateCoordinates((Polygon) geom);
} else if (geom instanceof MultiPolygon) {
return removeDuplicateCoordinates((MultiPolygon) geom);
} else if (geom instanceof GeometryCollection) {
return removeDuplicateCoordinates((GeometryCollection) geom);
}
return null;
}
/**
* Removes duplicated coordinates within a LineString.
*
* @param g
* @return
*/
public static LineString removeDuplicateCoordinates(LineString g) {
Coordinate[] coords = CoordinateArrays.removeRepeatedPoints(g.getCoordinates());
return FACTORY.createLineString(coords);
}
/**
* Removes duplicated coordinates within a linearRing.
*
* @param g
* @return
*/
public static LinearRing removeDuplicateCoordinates(LinearRing g) {
Coordinate[] coords = CoordinateArrays.removeRepeatedPoints(g.getCoordinates());
return FACTORY.createLinearRing(coords);
}
/**
* Removes duplicated coordinates in a MultiLineString.
*
* @param g
* @return
*/
public static MultiLineString removeDuplicateCoordinates(MultiLineString g) {
ArrayList<LineString> lines = new ArrayList<LineString>();
for (int i = 0; i < g.getNumGeometries(); i++) {
LineString line = (LineString) g.getGeometryN(i);
lines.add(removeDuplicateCoordinates(line));
}
return FACTORY.createMultiLineString(GeometryFactory.toLineStringArray(lines));
}
/**
* Removes duplicated coordinates within a Polygon.
*
* @param poly
* @return
*/
public static Polygon removeDuplicateCoordinates(Polygon poly) {
Coordinate[] shellCoords = CoordinateArrays.removeRepeatedPoints(poly.getExteriorRing().getCoordinates());
LinearRing shell = FACTORY.createLinearRing(shellCoords);
ArrayList<LinearRing> holes = new ArrayList<LinearRing>();
for (int i = 0; i < poly.getNumInteriorRing(); i++) {
Coordinate[] holeCoords = CoordinateArrays.removeRepeatedPoints(poly.getInteriorRingN(i).getCoordinates());
holes.add(FACTORY.createLinearRing(holeCoords));
}
return FACTORY.createPolygon(shell, GeometryFactory.toLinearRingArray(holes));
}
/**
* Removes duplicated coordinates within a MultiPolygon.
*
* @param g
* @return
*/
public static MultiPolygon removeDuplicateCoordinates(MultiPolygon g) {
ArrayList<Polygon> polys = new ArrayList<Polygon>();
for (int i = 0; i < g.getNumGeometries(); i++) {
Polygon poly = (Polygon) g.getGeometryN(i);
polys.add(removeDuplicateCoordinates(poly));
}
return FACTORY.createMultiPolygon(GeometryFactory.toPolygonArray(polys));
}
/**
* Removes duplicated coordinates within a GeometryCollection
*
* @param g
* @return
*/
public static GeometryCollection removeDuplicateCoordinates(GeometryCollection g) {
ArrayList<Geometry> geoms = new ArrayList<Geometry>();
for (int i = 0; i < g.getNumGeometries(); i++) {
Geometry geom = g.getGeometryN(i);
geoms.add(removeDuplicateCoordinates(geom));
}
return FACTORY.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
}
}
| true | true | public static Geometry removeDuplicateCoordinates(Geometry geom) {
if (geom.isEmpty()) {
return geom;
} else if (geom instanceof Point || geom instanceof MultiPoint) {
return geom;
} else if (geom instanceof LineString) {
return removeDuplicateCoordinates((LineString) geom);
} else if (geom instanceof MultiLineString) {
return removeDuplicateCoordinates((MultiLineString) geom);
} else if (geom instanceof Polygon) {
return removeDuplicateCoordinates((Polygon) geom);
} else if (geom instanceof MultiPolygon) {
return removeDuplicateCoordinates((MultiPolygon) geom);
} else if (geom instanceof GeometryCollection) {
return removeDuplicateCoordinates((GeometryCollection) geom);
}
return null;
}
| public static Geometry removeDuplicateCoordinates(Geometry geom) {
if(geom ==null){
return null;
}
else if (geom.isEmpty()) {
return geom;
} else if (geom instanceof Point || geom instanceof MultiPoint) {
return geom;
} else if (geom instanceof LineString) {
return removeDuplicateCoordinates((LineString) geom);
} else if (geom instanceof MultiLineString) {
return removeDuplicateCoordinates((MultiLineString) geom);
} else if (geom instanceof Polygon) {
return removeDuplicateCoordinates((Polygon) geom);
} else if (geom instanceof MultiPolygon) {
return removeDuplicateCoordinates((MultiPolygon) geom);
} else if (geom instanceof GeometryCollection) {
return removeDuplicateCoordinates((GeometryCollection) geom);
}
return null;
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
index 65f833f..e76d079 100644
--- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
@@ -1,223 +1,226 @@
/*
* YUI Compressor
* Author: Julien Lecomte <[email protected]>
* Copyright (c) 2007, Yahoo! Inc. All rights reserved.
* Code licensed under the BSD License:
* http://developer.yahoo.net/yui/license.txt
*
* This code is a port of Isaac Schlueter's cssmin utility.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Map;
import java.util.Hashtable;
import java.util.Set;
import java.util.Iterator;
public class CssCompressor {
private static final Map name2hexcolor = new Hashtable();
private static final Map hexcolor2name = new Hashtable();
static {
// Here, we only list colors that can be shortened
name2hexcolor.put("black", "#000");
name2hexcolor.put("fuchsia", "#F0F");
name2hexcolor.put("white", "#fff");
hexcolor2name.put("#F00", "red");
hexcolor2name.put("#808080", "gray");
hexcolor2name.put("#008000", "green");
hexcolor2name.put("#800000", "maroon");
hexcolor2name.put("#000080", "navy");
hexcolor2name.put("#808000", "olive");
hexcolor2name.put("#800080", "purple");
hexcolor2name.put("#C0C0C0", "silver");
hexcolor2name.put("#008080", "teal");
hexcolor2name.put("#FFFF00", "yellow");
}
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Set keys;
Pattern p;
Matcher m;
String css;
Iterator it;
StringBuffer sb, regexp;
int startIndex, endIndex;
// Remove all comment blocks...
sb = new StringBuffer(srcsb.toString());
while ((startIndex = sb.indexOf("/*")) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex >= startIndex + 2)
sb.delete(startIndex, endIndex + 2);
}
css = sb.toString();
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// Add the semicolon where it's missing.
css = css.replaceAll("([^;\\}])}", "$1;}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0;", ":0;");
css = css.replaceAll(":0 0 0;", ":0;");
css = css.replaceAll(":0 0;", ":0;");
// Replace background-position:0; with background-position:0 0;
css = css.replaceAll("background-position:0;", "background-position:0 0;");
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (int i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
+ if (val < 16) {
+ hexcolor.append("0");
+ }
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])\\s*#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
// Test for AABBCC pattern
if (m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
m.appendReplacement(sb, m.group(1) + "#" + m.group(2) + m.group(4) + m.group(6));
} else {
m.appendReplacement(sb, m.group());
}
}
m.appendTail(sb);
css = sb.toString();
// Use name2hexcolor to shorten color names...
regexp = new StringBuffer("([^.#\\s])\\s*(");
keys = name2hexcolor.keySet();
it = keys.iterator();
while (it.hasNext()) {
regexp.append(it.next());
regexp.append('|');
}
regexp.deleteCharAt(regexp.length()-1);
regexp.append(')');
p = Pattern.compile(regexp.toString());
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1) + name2hexcolor.get(m.group(2)));
}
m.appendTail(sb);
css = sb.toString();
// Use hexcolor2name to shorten color codes...
regexp = new StringBuffer();
keys = hexcolor2name.keySet();
it = keys.iterator();
while (it.hasNext()) {
regexp.append(it.next());
regexp.append('|');
}
regexp.deleteCharAt(regexp.length()-1);
p = Pattern.compile(regexp.toString());
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, (String) hexcolor2name.get(m.group()));
}
m.appendTail(sb);
css = sb.toString();
// Remove empty rules.
css = css.replaceAll("[^\\}]+\\{;\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
int i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| true | true | public void compress(Writer out, int linebreakpos)
throws IOException {
Set keys;
Pattern p;
Matcher m;
String css;
Iterator it;
StringBuffer sb, regexp;
int startIndex, endIndex;
// Remove all comment blocks...
sb = new StringBuffer(srcsb.toString());
while ((startIndex = sb.indexOf("/*")) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex >= startIndex + 2)
sb.delete(startIndex, endIndex + 2);
}
css = sb.toString();
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// Add the semicolon where it's missing.
css = css.replaceAll("([^;\\}])}", "$1;}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0;", ":0;");
css = css.replaceAll(":0 0 0;", ":0;");
css = css.replaceAll(":0 0;", ":0;");
// Replace background-position:0; with background-position:0 0;
css = css.replaceAll("background-position:0;", "background-position:0 0;");
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (int i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])\\s*#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
// Test for AABBCC pattern
if (m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
m.appendReplacement(sb, m.group(1) + "#" + m.group(2) + m.group(4) + m.group(6));
} else {
m.appendReplacement(sb, m.group());
}
}
m.appendTail(sb);
css = sb.toString();
// Use name2hexcolor to shorten color names...
regexp = new StringBuffer("([^.#\\s])\\s*(");
keys = name2hexcolor.keySet();
it = keys.iterator();
while (it.hasNext()) {
regexp.append(it.next());
regexp.append('|');
}
regexp.deleteCharAt(regexp.length()-1);
regexp.append(')');
p = Pattern.compile(regexp.toString());
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1) + name2hexcolor.get(m.group(2)));
}
m.appendTail(sb);
css = sb.toString();
// Use hexcolor2name to shorten color codes...
regexp = new StringBuffer();
keys = hexcolor2name.keySet();
it = keys.iterator();
while (it.hasNext()) {
regexp.append(it.next());
regexp.append('|');
}
regexp.deleteCharAt(regexp.length()-1);
p = Pattern.compile(regexp.toString());
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, (String) hexcolor2name.get(m.group()));
}
m.appendTail(sb);
css = sb.toString();
// Remove empty rules.
css = css.replaceAll("[^\\}]+\\{;\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
int i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
| public void compress(Writer out, int linebreakpos)
throws IOException {
Set keys;
Pattern p;
Matcher m;
String css;
Iterator it;
StringBuffer sb, regexp;
int startIndex, endIndex;
// Remove all comment blocks...
sb = new StringBuffer(srcsb.toString());
while ((startIndex = sb.indexOf("/*")) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex >= startIndex + 2)
sb.delete(startIndex, endIndex + 2);
}
css = sb.toString();
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// Add the semicolon where it's missing.
css = css.replaceAll("([^;\\}])}", "$1;}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0;", ":0;");
css = css.replaceAll(":0 0 0;", ":0;");
css = css.replaceAll(":0 0;", ":0;");
// Replace background-position:0; with background-position:0 0;
css = css.replaceAll("background-position:0;", "background-position:0 0;");
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (int i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])\\s*#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
// Test for AABBCC pattern
if (m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
m.appendReplacement(sb, m.group(1) + "#" + m.group(2) + m.group(4) + m.group(6));
} else {
m.appendReplacement(sb, m.group());
}
}
m.appendTail(sb);
css = sb.toString();
// Use name2hexcolor to shorten color names...
regexp = new StringBuffer("([^.#\\s])\\s*(");
keys = name2hexcolor.keySet();
it = keys.iterator();
while (it.hasNext()) {
regexp.append(it.next());
regexp.append('|');
}
regexp.deleteCharAt(regexp.length()-1);
regexp.append(')');
p = Pattern.compile(regexp.toString());
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1) + name2hexcolor.get(m.group(2)));
}
m.appendTail(sb);
css = sb.toString();
// Use hexcolor2name to shorten color codes...
regexp = new StringBuffer();
keys = hexcolor2name.keySet();
it = keys.iterator();
while (it.hasNext()) {
regexp.append(it.next());
regexp.append('|');
}
regexp.deleteCharAt(regexp.length()-1);
p = Pattern.compile(regexp.toString());
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, (String) hexcolor2name.get(m.group()));
}
m.appendTail(sb);
css = sb.toString();
// Remove empty rules.
css = css.replaceAll("[^\\}]+\\{;\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
int i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
|
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/metadata/MemoryMetadataProvider.java b/araqne-logdb/src/main/java/org/araqne/logdb/metadata/MemoryMetadataProvider.java
index 3f5b2038..29ed56fc 100644
--- a/araqne-logdb/src/main/java/org/araqne/logdb/metadata/MemoryMetadataProvider.java
+++ b/araqne-logdb/src/main/java/org/araqne/logdb/metadata/MemoryMetadataProvider.java
@@ -1,64 +1,64 @@
/*
* Copyright 2015 Eediom Inc. All rights reserved.
*/
package org.araqne.logdb.metadata;
import java.util.HashMap;
import java.util.Map;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.araqne.logdb.MetadataCallback;
import org.araqne.logdb.MetadataProvider;
import org.araqne.logdb.MetadataService;
import org.araqne.logdb.QueryContext;
import org.araqne.logdb.Row;
import org.araqne.storage.api.RCDirectBufferManager;
@Component(name = "logdb-memory-metadata")
public class MemoryMetadataProvider implements MetadataProvider {
@Requires
private MetadataService metadataService;
@Requires
private RCDirectBufferManager manager;
@Override
public String getType() {
return "memory";
}
@Validate
public void start() {
metadataService.addProvider(this);
}
@Invalidate
public void stop() {
if (metadataService != null)
metadataService.removeProvider(this);
}
@Override
public void verify(QueryContext context, String queryString) {
}
@Override
public void query(QueryContext context, String queryString, MetadataCallback callback) {
Map<String, Object> heap = new HashMap<String, Object>();
Runtime runtime = Runtime.getRuntime();
heap.put("type", "heap");
heap.put("free", runtime.freeMemory());
heap.put("total", runtime.totalMemory());
callback.onPush(new Row(heap));
Map<String, Object> rc = new HashMap<String, Object>();
- rc.put("type", "rcdirectbuffer");
+ rc.put("type", "offheap");
rc.put("total_capacity", manager.getTotalCapacity());
rc.put("object_count", manager.getObjectCount());
callback.onPush(new Row(rc));
}
}
| true | true | public void query(QueryContext context, String queryString, MetadataCallback callback) {
Map<String, Object> heap = new HashMap<String, Object>();
Runtime runtime = Runtime.getRuntime();
heap.put("type", "heap");
heap.put("free", runtime.freeMemory());
heap.put("total", runtime.totalMemory());
callback.onPush(new Row(heap));
Map<String, Object> rc = new HashMap<String, Object>();
rc.put("type", "rcdirectbuffer");
rc.put("total_capacity", manager.getTotalCapacity());
rc.put("object_count", manager.getObjectCount());
callback.onPush(new Row(rc));
}
| public void query(QueryContext context, String queryString, MetadataCallback callback) {
Map<String, Object> heap = new HashMap<String, Object>();
Runtime runtime = Runtime.getRuntime();
heap.put("type", "heap");
heap.put("free", runtime.freeMemory());
heap.put("total", runtime.totalMemory());
callback.onPush(new Row(heap));
Map<String, Object> rc = new HashMap<String, Object>();
rc.put("type", "offheap");
rc.put("total_capacity", manager.getTotalCapacity());
rc.put("object_count", manager.getObjectCount());
callback.onPush(new Row(rc));
}
|
diff --git a/src/java/com/sapienter/jbilling/server/mediation/task/SaveToJDBCMediationErrorHandler.java b/src/java/com/sapienter/jbilling/server/mediation/task/SaveToJDBCMediationErrorHandler.java
index 04bc723e..7431b866 100644
--- a/src/java/com/sapienter/jbilling/server/mediation/task/SaveToJDBCMediationErrorHandler.java
+++ b/src/java/com/sapienter/jbilling/server/mediation/task/SaveToJDBCMediationErrorHandler.java
@@ -1,251 +1,255 @@
/*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package com.sapienter.jbilling.server.mediation.task;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.server.item.PricingField;
import com.sapienter.jbilling.server.mediation.Record;
import com.sapienter.jbilling.server.mediation.db.MediationConfiguration;
import com.sapienter.jbilling.server.pluggableTask.PluggableTask;
import com.sapienter.jbilling.server.pluggableTask.TaskException;
import com.sapienter.jbilling.server.pluggableTask.admin.ParameterDescription;
/**
* This plug-in saves mediation errors to a JDBC database by generating insert statements
* matching the set of {@link PricingField} objects from the mediation process. This effectively
* preserves the original CDR record along with error states for later review.
*
* This class requires that a database table be created with columns matching the field
* names from the mediation format XML definition. jBilling does not create this table, it must
* be created by the end user when installing and configuring this plug-in.
*
* Plug-in parameters:
*
* url mandatory parameter, url for JDBC connection to database,
* i.e. jdbc:postgresql://localhost:5432/jbilling_test
*
* driver JDBC driver class for connection to DB, defaults to 'org.postgresql.Driver'
* username username for database, defaults to 'SA'
* password password for database, defaults to a blank string ("")
* table_name table name for saving records, defaults to 'mediation_errors'
* errors_column column name for saving error codes, defaults to 'error_message'
* retry_column column name for saving flag of reprocessing, defaults to 'should_retry'
* mediation_cfg_id id of mediation configuration for filtering errors handling (if param presented)
*
* @author Alexander Aksenov
* @since 31.01.2010
*/
public class SaveToJDBCMediationErrorHandler extends PluggableTask
implements IMediationErrorHandler {
private static final Logger log = Logger.getLogger(SaveToJDBCMediationErrorHandler.class);
// plug-in parameters
// mandatory parameter, url with host, port, database, etc
protected static final ParameterDescription PARAM_DATABASE_URL =
new ParameterDescription("url", true, ParameterDescription.Type.STR);
// optional, may be used default values
protected static final ParameterDescription PARAM_DRIVER =
new ParameterDescription("driver", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_DATABASE_USERNAME =
new ParameterDescription("username", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_DATABASE_PASSWORD =
new ParameterDescription("password", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_TABLE_NAME =
new ParameterDescription("table_name", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_ERRORS_COLUMN_NAME =
new ParameterDescription("errors_column", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_RETRY_COLUMN_NAME =
new ParameterDescription("retry_column", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_JBILLING_TIMESTAMP_COLUMN_NAME =
new ParameterDescription("timestamp_column", false, ParameterDescription.Type.STR);
protected static final ParameterDescription PARAM_MEDIATION_CONFIGURATION_ID =
new ParameterDescription("mediation_cfg_id", false, ParameterDescription.Type.STR);
// defaults
public static final String DRIVER_DEFAULT = "org.postgresql.Driver";
public static final String DATABASE_USERNAME_DEFAULT = "SA";
public static final String DATABASE_PASSWORD_DEFAULT = "";
public static final String TABLE_NAME_DEFAULT = "mediation_errors";
public static final String ERRORS_COLUMN_NAME_DEFAULT = "error_message";
public static final String RETRY_COLUMN_NAME_DEFAULT = "should_retry";
public static final String JBILLING_TIMESTAMP_COLUMN_NAME_DEFAULT = "jbilling_timestamp";
private Boolean mysql;
//initializer for pluggable params
{
descriptions.add(PARAM_DATABASE_URL);
descriptions.add(PARAM_DRIVER);
descriptions.add(PARAM_DATABASE_USERNAME);
descriptions.add(PARAM_DATABASE_PASSWORD);
descriptions.add(PARAM_TABLE_NAME);
descriptions.add(PARAM_ERRORS_COLUMN_NAME);
descriptions.add(PARAM_RETRY_COLUMN_NAME);
descriptions.add(PARAM_JBILLING_TIMESTAMP_COLUMN_NAME);
descriptions.add(PARAM_MEDIATION_CONFIGURATION_ID);
}
public void process(Record record, List<String> errors, Date processingTime, MediationConfiguration mediationConfiguration) throws TaskException {
if (mediationConfiguration != null && getParameter(PARAM_MEDIATION_CONFIGURATION_ID.getName(), (String) null) != null) {
try {
Integer configId = Integer.parseInt(getParameter(PARAM_MEDIATION_CONFIGURATION_ID.getName(), ""));
if (!mediationConfiguration.getId().equals(configId)) {
return;
}
} catch (NumberFormatException ex) {
log.error("Error during plug-in parameters parsing, check the configuration", ex);
}
}
log.debug("Perform saving errors to database ");
Connection connection = null;
try {
connection = getConnection();
String errorColumn = getParameter(PARAM_ERRORS_COLUMN_NAME.getName(), ERRORS_COLUMN_NAME_DEFAULT);
String retryColumn = getParameter(PARAM_RETRY_COLUMN_NAME.getName(), RETRY_COLUMN_NAME_DEFAULT);
String timestampColumn = getParameter(PARAM_JBILLING_TIMESTAMP_COLUMN_NAME.getName(), JBILLING_TIMESTAMP_COLUMN_NAME_DEFAULT);
List<String> columnNames = new LinkedList<String>();
// remove extra error columns from incoming pricing fields.
// if we're re-reading errors from the error table, then we'll end up with duplicate columns
List<PricingField> fields = record.getFields();
for (Iterator<PricingField> it = fields.iterator(); it.hasNext();) {
PricingField field = it.next();
if (field.getName().equals(errorColumn)) it.remove();
if (field.getName().equals(retryColumn)) it.remove();
if (field.getName().equals(timestampColumn)) it.remove();
}
for (PricingField field : fields) {
- // the word 'end' is a reserved word in many databases so it can't be used.
+ // the word 'end' or 'start' is a reserved word in many databases so it can't be used.
// Change it to 'end_time'
- columnNames.add(escapedKeywordsColumnName(field.getName().equals("end") ? "end_time" : field.getName()));
+ String fieldName = field.getName();
+ if (fieldName.equals("end") || fieldName.equals("start")) {
+ fieldName = fieldName + "_time";
+ }
+ columnNames.add(escapedKeywordsColumnName(fieldName));
}
columnNames.add(errorColumn);
columnNames.add(retryColumn);
StringBuilder query = new StringBuilder("insert into ");
query.append(getParameter(PARAM_TABLE_NAME.getName(), TABLE_NAME_DEFAULT));
query.append("(");
query.append(com.sapienter.jbilling.server.util.Util.join(columnNames, ", "));
query.append(") values (");
query.append(com.sapienter.jbilling.server.util.Util.join(Collections.nCopies(columnNames.size(), "?"), ", "));
query.append(")");
PreparedStatement preparedStatement = connection.prepareStatement(query.toString());
int index = 1;
for (PricingField field : fields) {
switch (field.getType()) {
case STRING:
preparedStatement.setString(index, field.getStrValue());
break;
case INTEGER:
preparedStatement.setInt(index, field.getIntValue());
break;
case DECIMAL:
preparedStatement.setDouble(index, field.getDoubleValue());
break;
case DATE:
if (field.getDateValue() != null) {
preparedStatement.setTimestamp(index, new Timestamp(field.getDateValue().getTime()));
} else {
preparedStatement.setNull(index, Types.TIMESTAMP);
}
break;
case BOOLEAN:
preparedStatement.setBoolean(index, field.getBooleanValue());
break;
}
index++;
}
// errors column
preparedStatement.setString(index, com.sapienter.jbilling.server.util.Util.join(errors, " "));
index++;
// retry column
preparedStatement.setBoolean(index, false);
// save data
preparedStatement.executeUpdate();
} catch (SQLException e) {
log.error("Saving errors to database failed", e);
throw new TaskException(e);
} catch (ClassNotFoundException e) {
log.error("Saving errors to database failed, incorrect configuration", e);
throw new TaskException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e);
}
}
}
}
protected Connection getConnection() throws SQLException, ClassNotFoundException, TaskException {
String driver = getParameter(PARAM_DRIVER.getName(), DRIVER_DEFAULT);
Object url = parameters.get(PARAM_DATABASE_URL.getName());
if (url == null) {
throw new TaskException("Error, expected mandatory parameter databae_url");
}
String username = getParameter(PARAM_DATABASE_USERNAME.getName(), DATABASE_USERNAME_DEFAULT);
String password = getParameter(PARAM_DATABASE_PASSWORD.getName(), DATABASE_PASSWORD_DEFAULT);
// create connection
Class.forName(driver); // load driver
return DriverManager.getConnection((String) url, username, password);
}
protected String escapedKeywordsColumnName(String columnName) {
String escape = isMySQL() ? "`" : "\""; // escape mysql column names with backtick
return escape + columnName + escape;
}
/**
* returns true if the driver is a MySQL database driver, false if not.
* @return true if MySQL
*/
private boolean isMySQL() {
if (mysql == null)
mysql = getParameter(PARAM_DRIVER.getName(), DRIVER_DEFAULT).contains("mysql");
return mysql;
}
}
| false | true | public void process(Record record, List<String> errors, Date processingTime, MediationConfiguration mediationConfiguration) throws TaskException {
if (mediationConfiguration != null && getParameter(PARAM_MEDIATION_CONFIGURATION_ID.getName(), (String) null) != null) {
try {
Integer configId = Integer.parseInt(getParameter(PARAM_MEDIATION_CONFIGURATION_ID.getName(), ""));
if (!mediationConfiguration.getId().equals(configId)) {
return;
}
} catch (NumberFormatException ex) {
log.error("Error during plug-in parameters parsing, check the configuration", ex);
}
}
log.debug("Perform saving errors to database ");
Connection connection = null;
try {
connection = getConnection();
String errorColumn = getParameter(PARAM_ERRORS_COLUMN_NAME.getName(), ERRORS_COLUMN_NAME_DEFAULT);
String retryColumn = getParameter(PARAM_RETRY_COLUMN_NAME.getName(), RETRY_COLUMN_NAME_DEFAULT);
String timestampColumn = getParameter(PARAM_JBILLING_TIMESTAMP_COLUMN_NAME.getName(), JBILLING_TIMESTAMP_COLUMN_NAME_DEFAULT);
List<String> columnNames = new LinkedList<String>();
// remove extra error columns from incoming pricing fields.
// if we're re-reading errors from the error table, then we'll end up with duplicate columns
List<PricingField> fields = record.getFields();
for (Iterator<PricingField> it = fields.iterator(); it.hasNext();) {
PricingField field = it.next();
if (field.getName().equals(errorColumn)) it.remove();
if (field.getName().equals(retryColumn)) it.remove();
if (field.getName().equals(timestampColumn)) it.remove();
}
for (PricingField field : fields) {
// the word 'end' is a reserved word in many databases so it can't be used.
// Change it to 'end_time'
columnNames.add(escapedKeywordsColumnName(field.getName().equals("end") ? "end_time" : field.getName()));
}
columnNames.add(errorColumn);
columnNames.add(retryColumn);
StringBuilder query = new StringBuilder("insert into ");
query.append(getParameter(PARAM_TABLE_NAME.getName(), TABLE_NAME_DEFAULT));
query.append("(");
query.append(com.sapienter.jbilling.server.util.Util.join(columnNames, ", "));
query.append(") values (");
query.append(com.sapienter.jbilling.server.util.Util.join(Collections.nCopies(columnNames.size(), "?"), ", "));
query.append(")");
PreparedStatement preparedStatement = connection.prepareStatement(query.toString());
int index = 1;
for (PricingField field : fields) {
switch (field.getType()) {
case STRING:
preparedStatement.setString(index, field.getStrValue());
break;
case INTEGER:
preparedStatement.setInt(index, field.getIntValue());
break;
case DECIMAL:
preparedStatement.setDouble(index, field.getDoubleValue());
break;
case DATE:
if (field.getDateValue() != null) {
preparedStatement.setTimestamp(index, new Timestamp(field.getDateValue().getTime()));
} else {
preparedStatement.setNull(index, Types.TIMESTAMP);
}
break;
case BOOLEAN:
preparedStatement.setBoolean(index, field.getBooleanValue());
break;
}
index++;
}
// errors column
preparedStatement.setString(index, com.sapienter.jbilling.server.util.Util.join(errors, " "));
index++;
// retry column
preparedStatement.setBoolean(index, false);
// save data
preparedStatement.executeUpdate();
} catch (SQLException e) {
log.error("Saving errors to database failed", e);
throw new TaskException(e);
} catch (ClassNotFoundException e) {
log.error("Saving errors to database failed, incorrect configuration", e);
throw new TaskException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e);
}
}
}
}
| public void process(Record record, List<String> errors, Date processingTime, MediationConfiguration mediationConfiguration) throws TaskException {
if (mediationConfiguration != null && getParameter(PARAM_MEDIATION_CONFIGURATION_ID.getName(), (String) null) != null) {
try {
Integer configId = Integer.parseInt(getParameter(PARAM_MEDIATION_CONFIGURATION_ID.getName(), ""));
if (!mediationConfiguration.getId().equals(configId)) {
return;
}
} catch (NumberFormatException ex) {
log.error("Error during plug-in parameters parsing, check the configuration", ex);
}
}
log.debug("Perform saving errors to database ");
Connection connection = null;
try {
connection = getConnection();
String errorColumn = getParameter(PARAM_ERRORS_COLUMN_NAME.getName(), ERRORS_COLUMN_NAME_DEFAULT);
String retryColumn = getParameter(PARAM_RETRY_COLUMN_NAME.getName(), RETRY_COLUMN_NAME_DEFAULT);
String timestampColumn = getParameter(PARAM_JBILLING_TIMESTAMP_COLUMN_NAME.getName(), JBILLING_TIMESTAMP_COLUMN_NAME_DEFAULT);
List<String> columnNames = new LinkedList<String>();
// remove extra error columns from incoming pricing fields.
// if we're re-reading errors from the error table, then we'll end up with duplicate columns
List<PricingField> fields = record.getFields();
for (Iterator<PricingField> it = fields.iterator(); it.hasNext();) {
PricingField field = it.next();
if (field.getName().equals(errorColumn)) it.remove();
if (field.getName().equals(retryColumn)) it.remove();
if (field.getName().equals(timestampColumn)) it.remove();
}
for (PricingField field : fields) {
// the word 'end' or 'start' is a reserved word in many databases so it can't be used.
// Change it to 'end_time'
String fieldName = field.getName();
if (fieldName.equals("end") || fieldName.equals("start")) {
fieldName = fieldName + "_time";
}
columnNames.add(escapedKeywordsColumnName(fieldName));
}
columnNames.add(errorColumn);
columnNames.add(retryColumn);
StringBuilder query = new StringBuilder("insert into ");
query.append(getParameter(PARAM_TABLE_NAME.getName(), TABLE_NAME_DEFAULT));
query.append("(");
query.append(com.sapienter.jbilling.server.util.Util.join(columnNames, ", "));
query.append(") values (");
query.append(com.sapienter.jbilling.server.util.Util.join(Collections.nCopies(columnNames.size(), "?"), ", "));
query.append(")");
PreparedStatement preparedStatement = connection.prepareStatement(query.toString());
int index = 1;
for (PricingField field : fields) {
switch (field.getType()) {
case STRING:
preparedStatement.setString(index, field.getStrValue());
break;
case INTEGER:
preparedStatement.setInt(index, field.getIntValue());
break;
case DECIMAL:
preparedStatement.setDouble(index, field.getDoubleValue());
break;
case DATE:
if (field.getDateValue() != null) {
preparedStatement.setTimestamp(index, new Timestamp(field.getDateValue().getTime()));
} else {
preparedStatement.setNull(index, Types.TIMESTAMP);
}
break;
case BOOLEAN:
preparedStatement.setBoolean(index, field.getBooleanValue());
break;
}
index++;
}
// errors column
preparedStatement.setString(index, com.sapienter.jbilling.server.util.Util.join(errors, " "));
index++;
// retry column
preparedStatement.setBoolean(index, false);
// save data
preparedStatement.executeUpdate();
} catch (SQLException e) {
log.error("Saving errors to database failed", e);
throw new TaskException(e);
} catch (ClassNotFoundException e) {
log.error("Saving errors to database failed, incorrect configuration", e);
throw new TaskException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e);
}
}
}
}
|
diff --git a/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/columnandbar/ColumnWithDrilldown.java b/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/columnandbar/ColumnWithDrilldown.java
index 56fef9b1..5744cf85 100644
--- a/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/columnandbar/ColumnWithDrilldown.java
+++ b/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/columnandbar/ColumnWithDrilldown.java
@@ -1,115 +1,116 @@
package com.vaadin.addon.charts.demoandtestapp.columnandbar;
import com.vaadin.addon.charts.Chart;
import com.vaadin.addon.charts.PointClickEvent;
import com.vaadin.addon.charts.PointClickListener;
import com.vaadin.addon.charts.demoandtestapp.AbstractVaadinChartExample;
import com.vaadin.addon.charts.model.ChartType;
import com.vaadin.addon.charts.model.Configuration;
import com.vaadin.addon.charts.model.Cursor;
import com.vaadin.addon.charts.model.PlotOptionsColumn;
import com.vaadin.addon.charts.model.Tooltip;
import com.vaadin.addon.charts.model.XAxis;
import com.vaadin.addon.charts.model.YAxis;
import com.vaadin.addon.charts.model.style.Color;
import com.vaadin.addon.charts.model.style.FontWeight;
import com.vaadin.addon.charts.model.style.SolidColor;
import com.vaadin.addon.charts.themes.VaadinTheme;
import com.vaadin.ui.Component;
@SuppressWarnings("serial")
public class ColumnWithDrilldown extends AbstractVaadinChartExample {
@Override
public String getDescription() {
return "Basic column";
}
@Override
protected Component getChart() {
- Chart chart = new Chart(ChartType.COLUMN);
+ final Chart chart = new Chart(ChartType.COLUMN);
Color[] colors = new VaadinTheme().getColors();
- Configuration conf = chart.getConfiguration();
+ final Configuration conf = chart.getConfiguration();
conf.setTitle("Browser market share, April, 2011");
conf.setSubTitle("Click the columns to view versions. Click again to view brands.");
XAxis x = new XAxis();
x.setCategories("MSIE", "Firefox", "Chrome", "Safari", "Opera");
conf.addxAxis(x);
YAxis y = new YAxis();
y.setTitle("Total percent market share");
conf.addyAxis(y);
PlotOptionsColumn column = new PlotOptionsColumn();
column.setCursor(Cursor.POINTER);
column.getDataLabels().setEnabled(true);
column.getDataLabels().setColor(colors[0]);
column.getDataLabels().getStyle().setFontWeight(FontWeight.BOLD);
column.getDataLabels().setFormatter("function() {return this.y +'%';}");
conf.setPlotOptions(column);
Tooltip tooltip = new Tooltip();
- tooltip.setFormatter("function() { var point = this.point, s = this.x +':<b>'+ this.y +'% market share</b><br/>'; if (point.drilldown) { s += 'Click to view '+ point.category +' versions'; } else { s += 'Click to return to browser brands'; } return s; }");
+ tooltip.setFormatter("function() { var point = this.point, s = this.x +':<b>'+ this.y +'% market share</b><br/>'; if (!point.drilldown) { s += 'Click to view '+ point.category +' versions'; } else { s += 'Click to return to browser brands'; } return s; }");
conf.setTooltip(tooltip);
final DrilldownSeries series = new DrilldownSeries(conf, 55.11, 21.63,
11.94, 7.15, 2.14);
series.setName("Browser brands");
series.setColor(new SolidColor("#ffffff"));
Drilldown drill = new Drilldown("MSIE versions");
drill.setData(10.85, 7.35, 33.06, 2.81);
drill.setCategories("MSIE 6.0", "MSIE 7.0", "MSIE 8.0", "MSIE 9.0");
drill.setColor(colors[0]);
series.addDrilldown("MSIE", drill);
drill = new Drilldown("Firefox versions");
drill.setData(0.20, 0.83, 1.58, 13.12, 5.43);
drill.setCategories("Firefox 2.0", "Firefox 3.0", "Firefox 3.5",
"Firefox 3.6", "Firefox 4.0");
drill.setColor(colors[1]);
series.addDrilldown("Firefox", drill);
drill = new Drilldown("Chrome versions");
drill.setData(0.12, 0.19, 0.12, 0.36, 0.32, 9.91, 0.50, 0.22);
drill.setCategories("Chrome 5.0", "Chrome 6.0", "Chrome 7.0",
"Chrome 8.0", "Chrome 9.0", "Chrome 10.0", "Chrome 11.0",
"Chrome 12.0");
drill.setColor(colors[2]);
series.addDrilldown("Chrome", drill);
drill = new Drilldown("Safari versions");
drill.setData(4.55, 1.42, 0.23, 0.21, 0.20, 0.19, 0.14);
drill.setCategories("Safari 5.0", "Safari 4.0", "Safari Win 5.0",
"Safari 4.1", "Safari/Maxthon", "Safari 3.1", "Safari 4.1");
drill.setColor(colors[3]);
series.addDrilldown("Safari", drill);
drill = new Drilldown("Opera versions");
drill.setData(0.12, 0.37, 1.65);
drill.setCategories("Opera 9.x", "Opera 10.x", "Opera 11.x");
drill.setColor(colors[4]);
series.addDrilldown("Opera", drill);
conf.setSeries(series);
conf.setExporting(false);
chart.addColumnClickListener(new PointClickListener() {
@Override
public void onClick(PointClickEvent event) {
if (!series.isDrilldown()) {
series.drillDown(event.getCategory());
} else {
series.backToUp();
}
+ chart.drawChart(conf);
}
});
chart.drawChart(conf);
return chart;
}
}
| false | true | protected Component getChart() {
Chart chart = new Chart(ChartType.COLUMN);
Color[] colors = new VaadinTheme().getColors();
Configuration conf = chart.getConfiguration();
conf.setTitle("Browser market share, April, 2011");
conf.setSubTitle("Click the columns to view versions. Click again to view brands.");
XAxis x = new XAxis();
x.setCategories("MSIE", "Firefox", "Chrome", "Safari", "Opera");
conf.addxAxis(x);
YAxis y = new YAxis();
y.setTitle("Total percent market share");
conf.addyAxis(y);
PlotOptionsColumn column = new PlotOptionsColumn();
column.setCursor(Cursor.POINTER);
column.getDataLabels().setEnabled(true);
column.getDataLabels().setColor(colors[0]);
column.getDataLabels().getStyle().setFontWeight(FontWeight.BOLD);
column.getDataLabels().setFormatter("function() {return this.y +'%';}");
conf.setPlotOptions(column);
Tooltip tooltip = new Tooltip();
tooltip.setFormatter("function() { var point = this.point, s = this.x +':<b>'+ this.y +'% market share</b><br/>'; if (point.drilldown) { s += 'Click to view '+ point.category +' versions'; } else { s += 'Click to return to browser brands'; } return s; }");
conf.setTooltip(tooltip);
final DrilldownSeries series = new DrilldownSeries(conf, 55.11, 21.63,
11.94, 7.15, 2.14);
series.setName("Browser brands");
series.setColor(new SolidColor("#ffffff"));
Drilldown drill = new Drilldown("MSIE versions");
drill.setData(10.85, 7.35, 33.06, 2.81);
drill.setCategories("MSIE 6.0", "MSIE 7.0", "MSIE 8.0", "MSIE 9.0");
drill.setColor(colors[0]);
series.addDrilldown("MSIE", drill);
drill = new Drilldown("Firefox versions");
drill.setData(0.20, 0.83, 1.58, 13.12, 5.43);
drill.setCategories("Firefox 2.0", "Firefox 3.0", "Firefox 3.5",
"Firefox 3.6", "Firefox 4.0");
drill.setColor(colors[1]);
series.addDrilldown("Firefox", drill);
drill = new Drilldown("Chrome versions");
drill.setData(0.12, 0.19, 0.12, 0.36, 0.32, 9.91, 0.50, 0.22);
drill.setCategories("Chrome 5.0", "Chrome 6.0", "Chrome 7.0",
"Chrome 8.0", "Chrome 9.0", "Chrome 10.0", "Chrome 11.0",
"Chrome 12.0");
drill.setColor(colors[2]);
series.addDrilldown("Chrome", drill);
drill = new Drilldown("Safari versions");
drill.setData(4.55, 1.42, 0.23, 0.21, 0.20, 0.19, 0.14);
drill.setCategories("Safari 5.0", "Safari 4.0", "Safari Win 5.0",
"Safari 4.1", "Safari/Maxthon", "Safari 3.1", "Safari 4.1");
drill.setColor(colors[3]);
series.addDrilldown("Safari", drill);
drill = new Drilldown("Opera versions");
drill.setData(0.12, 0.37, 1.65);
drill.setCategories("Opera 9.x", "Opera 10.x", "Opera 11.x");
drill.setColor(colors[4]);
series.addDrilldown("Opera", drill);
conf.setSeries(series);
conf.setExporting(false);
chart.addColumnClickListener(new PointClickListener() {
@Override
public void onClick(PointClickEvent event) {
if (!series.isDrilldown()) {
series.drillDown(event.getCategory());
} else {
series.backToUp();
}
}
});
chart.drawChart(conf);
return chart;
}
| protected Component getChart() {
final Chart chart = new Chart(ChartType.COLUMN);
Color[] colors = new VaadinTheme().getColors();
final Configuration conf = chart.getConfiguration();
conf.setTitle("Browser market share, April, 2011");
conf.setSubTitle("Click the columns to view versions. Click again to view brands.");
XAxis x = new XAxis();
x.setCategories("MSIE", "Firefox", "Chrome", "Safari", "Opera");
conf.addxAxis(x);
YAxis y = new YAxis();
y.setTitle("Total percent market share");
conf.addyAxis(y);
PlotOptionsColumn column = new PlotOptionsColumn();
column.setCursor(Cursor.POINTER);
column.getDataLabels().setEnabled(true);
column.getDataLabels().setColor(colors[0]);
column.getDataLabels().getStyle().setFontWeight(FontWeight.BOLD);
column.getDataLabels().setFormatter("function() {return this.y +'%';}");
conf.setPlotOptions(column);
Tooltip tooltip = new Tooltip();
tooltip.setFormatter("function() { var point = this.point, s = this.x +':<b>'+ this.y +'% market share</b><br/>'; if (!point.drilldown) { s += 'Click to view '+ point.category +' versions'; } else { s += 'Click to return to browser brands'; } return s; }");
conf.setTooltip(tooltip);
final DrilldownSeries series = new DrilldownSeries(conf, 55.11, 21.63,
11.94, 7.15, 2.14);
series.setName("Browser brands");
series.setColor(new SolidColor("#ffffff"));
Drilldown drill = new Drilldown("MSIE versions");
drill.setData(10.85, 7.35, 33.06, 2.81);
drill.setCategories("MSIE 6.0", "MSIE 7.0", "MSIE 8.0", "MSIE 9.0");
drill.setColor(colors[0]);
series.addDrilldown("MSIE", drill);
drill = new Drilldown("Firefox versions");
drill.setData(0.20, 0.83, 1.58, 13.12, 5.43);
drill.setCategories("Firefox 2.0", "Firefox 3.0", "Firefox 3.5",
"Firefox 3.6", "Firefox 4.0");
drill.setColor(colors[1]);
series.addDrilldown("Firefox", drill);
drill = new Drilldown("Chrome versions");
drill.setData(0.12, 0.19, 0.12, 0.36, 0.32, 9.91, 0.50, 0.22);
drill.setCategories("Chrome 5.0", "Chrome 6.0", "Chrome 7.0",
"Chrome 8.0", "Chrome 9.0", "Chrome 10.0", "Chrome 11.0",
"Chrome 12.0");
drill.setColor(colors[2]);
series.addDrilldown("Chrome", drill);
drill = new Drilldown("Safari versions");
drill.setData(4.55, 1.42, 0.23, 0.21, 0.20, 0.19, 0.14);
drill.setCategories("Safari 5.0", "Safari 4.0", "Safari Win 5.0",
"Safari 4.1", "Safari/Maxthon", "Safari 3.1", "Safari 4.1");
drill.setColor(colors[3]);
series.addDrilldown("Safari", drill);
drill = new Drilldown("Opera versions");
drill.setData(0.12, 0.37, 1.65);
drill.setCategories("Opera 9.x", "Opera 10.x", "Opera 11.x");
drill.setColor(colors[4]);
series.addDrilldown("Opera", drill);
conf.setSeries(series);
conf.setExporting(false);
chart.addColumnClickListener(new PointClickListener() {
@Override
public void onClick(PointClickEvent event) {
if (!series.isDrilldown()) {
series.drillDown(event.getCategory());
} else {
series.backToUp();
}
chart.drawChart(conf);
}
});
chart.drawChart(conf);
return chart;
}
|
diff --git a/src/org/apache/xalan/xsltc/compiler/Mode.java b/src/org/apache/xalan/xsltc/compiler/Mode.java
index 876e2e96..ec1627d6 100644
--- a/src/org/apache/xalan/xsltc/compiler/Mode.java
+++ b/src/org/apache/xalan/xsltc/compiler/Mode.java
@@ -1,901 +1,903 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
* @author Erwin Bolwidt <[email protected]>
*
*/
package org.apache.xalan.xsltc.compiler;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import org.apache.xalan.xsltc.compiler.util.Type;
import de.fub.bytecode.generic.*;
import org.apache.xalan.xsltc.compiler.util.*;
import org.apache.xalan.xsltc.DOM;
/**
* Mode gathers all the templates belonging to a given mode; it is responsible
* for generating an appropriate applyTemplates + (mode name) function
*/
final class Mode implements Constants {
private final QName _name; // The QName of this mode
private final Stylesheet _stylesheet; // The owning stylesheet
private final String _methodName; // The method name for this mode
private final Vector _templates; // All templates in this mode
// Pattern/test sequence for pattern with node()-type kernel
private Vector _nodeGroup = null;
private TestSeq _nodeTestSeq = null;
// Pattern/test sequence for pattern with id() or key()-type kernel
private Vector _idxGroup = null;
private TestSeq _idxTestSeq = null;
// Pattern/test sequence for patterns with any other kernel type
private Vector[] _patternGroups;
private TestSeq[] _testSeq;
private final Hashtable _neededTemplates = new Hashtable();
private final Hashtable _namedTemplates = new Hashtable();
private final Hashtable _templateIHs = new Hashtable();
private final Hashtable _templateILs = new Hashtable();
private LocationPathPattern _rootPattern = null;
// Variable index for the current node - used in code generation
private int _currentIndex;
/**
* Creates a new Mode
* @param name A textual representation of the mode's QName
* @param stylesheet The Stylesheet in which the mode occured
* @param suffix A suffix to append to the method name for this mode
* (normally a sequence number - still in a String).
*/
public Mode(QName name, Stylesheet stylesheet, String suffix) {
// Save global info
_name = name;
_stylesheet = stylesheet;
_methodName = APPLY_TEMPLATES + suffix;
// Initialise some data structures
_templates = new Vector();
_patternGroups = new Vector[32];
}
/**
* Returns the name of the method (_not_ function) that will be compiled
* for this mode. Normally takes the form 'applyTemplates()' or
* 'applyTemplates2()'.
* @return Method name for this mode
*/
public String functionName() {
return _methodName;
}
/**
* Shortcut to get the class compiled for this mode (will be inlined).
*/
private String getClassName() {
return _stylesheet.getClassName();
}
/**
* Add a template to this mode
* @param template The template to add
*/
public void addTemplate(Template template) {
_templates.addElement(template);
}
/**
* Process all the test patterns in this mode
*/
public void processPatterns(Hashtable keys) {
// Traverse all templates
final Enumeration templates = _templates.elements();
while (templates.hasMoreElements()) {
// Get the next template
final Template template = (Template)templates.nextElement();
// Add this template to a table of named templates if it has a name.
// If there are multiple templates with the same name, all but one
// (the one with highest priority) will be disabled.
if (template.isNamed() && !template.disabled())
_namedTemplates.put(template, this);
// Add this template to a test sequence if it has a pattern
final Pattern pattern = template.getPattern();
if (pattern != null) flattenAlternative(pattern, template, keys);
}
prepareTestSequences();
}
/**
* This method will break up alternative patterns (ie. unions of patterns,
* such as match="A/B | C/B") and add the basic patterns to their
* respective pattern groups.
*/
private void flattenAlternative(Pattern pattern,
Template template,
Hashtable keys) {
// Patterns on type id() and key() are special since they do not have
// any kernel node type (it can be anything as long as the node is in
// the id's or key's index).
if (pattern instanceof IdKeyPattern) {
final IdKeyPattern idkey = (IdKeyPattern)pattern;
idkey.setTemplate(template);
if (_idxGroup == null) _idxGroup = new Vector();
_idxGroup.add(pattern);
}
// Alternative patterns are broken up and re-processed recursively
else if (pattern instanceof AlternativePattern) {
final AlternativePattern alt = (AlternativePattern)pattern;
flattenAlternative(alt.getLeft(), template, keys);
flattenAlternative(alt.getRight(), template, keys);
}
// Finally we have a pattern that can be added to a test sequence!
else if (pattern instanceof LocationPathPattern) {
final LocationPathPattern lpp = (LocationPathPattern)pattern;
lpp.setTemplate(template);
addPatternToGroup(lpp);
}
}
/**
* Adds a pattern to a pattern group
*/
private void addPattern(int kernelType, LocationPathPattern pattern) {
// Make sure the array of pattern groups is long enough
final int oldLength = _patternGroups.length;
if (kernelType >= oldLength) {
Vector[] newGroups = new Vector[kernelType * 2];
System.arraycopy(_patternGroups, 0, newGroups, 0, oldLength);
_patternGroups = newGroups;
}
// Find the vector to put this pattern into
Vector patterns;
// Use the vector for id()/key()/node() patterns if no kernel type
if (kernelType == -1)
patterns = _nodeGroup;
else
patterns = _patternGroups[kernelType];
// Create a new vector if needed and insert the very first pattern
if (patterns == null) {
patterns = new Vector(2);
patterns.addElement(pattern);
if (kernelType == -1)
_nodeGroup = patterns;
else
_patternGroups[kernelType] = patterns;
}
// Otherwise make sure patterns are ordered by precedence/priorities
else {
boolean inserted = false;
for (int i = 0; i < patterns.size(); i++) {
final LocationPathPattern lppToCompare =
(LocationPathPattern)patterns.elementAt(i);
if (pattern.noSmallerThan(lppToCompare)) {
inserted = true;
patterns.insertElementAt(pattern, i);
break;
}
}
if (inserted == false) {
patterns.addElement(pattern);
}
}
}
/**
* Group patterns by NodeTests of their last Step
* Keep them sorted by priority within group
*/
private void addPatternToGroup(final LocationPathPattern lpp) {
// id() and key()-type patterns do not have a kernel type
if (lpp instanceof IdKeyPattern) {
addPattern(-1, lpp);
}
// Otherwise get the kernel pattern from the LPP
else {
// kernel pattern is the last (maybe only) Step
final StepPattern kernel = lpp.getKernelPattern();
if (kernel != null) {
addPattern(kernel.getNodeType(), lpp);
}
else if (_rootPattern == null ||
lpp.noSmallerThan(_rootPattern)) {
_rootPattern = lpp;
}
}
}
/**
* Build test sequences
*/
private void prepareTestSequences() {
final Vector names = _stylesheet.getXSLTC().getNamesIndex();
_testSeq = new TestSeq[DOM.NTYPES + names.size()];
final int n = _patternGroups.length;
for (int i = 0; i < n; i++) {
final Vector patterns = _patternGroups[i];
if (patterns != null) {
final TestSeq testSeq = new TestSeq(patterns, this);
testSeq.reduce();
_testSeq[i] = testSeq;
testSeq.findTemplates(_neededTemplates);
}
}
if ((_nodeGroup != null) && (_nodeGroup.size() > 0)) {
_nodeTestSeq = new TestSeq(_nodeGroup, this);
_nodeTestSeq.reduce();
_nodeTestSeq.findTemplates(_neededTemplates);
}
if ((_idxGroup != null) && (_idxGroup.size() > 0)) {
_idxTestSeq = new TestSeq(_idxGroup, this);
_idxTestSeq.reduce();
_idxTestSeq.findTemplates(_neededTemplates);
}
if (_rootPattern != null) {
// doesn't matter what is 'put', only key matters
_neededTemplates.put(_rootPattern.getTemplate(), this);
}
}
private void compileNamedTemplate(Template template,
ClassGenerator classGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = new InstructionList();
String methodName = template.getName().toString();
methodName = methodName.replace('.', '$');
methodName = methodName.replace('-', '$');
final NamedMethodGenerator methodGen =
new NamedMethodGenerator(ACC_PUBLIC,
de.fub.bytecode.generic.Type.VOID,
new de.fub.bytecode.generic.Type[] {
Util.getJCRefType(DOM_INTF_SIG),
Util.getJCRefType(NODE_ITERATOR_SIG),
Util.getJCRefType(TRANSLET_OUTPUT_SIG),
de.fub.bytecode.generic.Type.INT
},
new String[] {
DOCUMENT_PNAME,
ITERATOR_PNAME,
TRANSLET_OUTPUT_PNAME,
NODE_PNAME
},
methodName,
getClassName(),
il, cpg);
il.append(template.compile(classGen, methodGen));
il.append(RETURN);
methodGen.stripAttributes(true);
methodGen.setMaxLocals();
methodGen.setMaxStack();
methodGen.removeNOPs();
classGen.addMethod(methodGen.getMethod());
}
private void compileTemplates(ClassGenerator classGen,
MethodGenerator methodGen,
InstructionHandle next) {
Enumeration templates = _namedTemplates.keys();
while (templates.hasMoreElements()) {
final Template template = (Template)templates.nextElement();
compileNamedTemplate(template, classGen);
}
templates = _neededTemplates.keys();
while (templates.hasMoreElements()) {
final Template template = (Template)templates.nextElement();
if (template.hasContents()) {
// !!! TODO templates both named and matched
InstructionList til = template.compile(classGen, methodGen);
til.append(new GOTO_W(next));
_templateILs.put(template, til);
_templateIHs.put(template, til.getStart());
}
else {
// empty template
_templateIHs.put(template, next);
}
}
}
private void appendTemplateCode(InstructionList body) {
final Enumeration templates = _neededTemplates.keys();
while (templates.hasMoreElements()) {
final Object iList =
_templateILs.get(templates.nextElement());
if (iList != null) {
body.append((InstructionList)iList);
}
}
}
private void appendTestSequences(InstructionList body) {
final int n = _testSeq.length;
for (int i = 0; i < n; i++) {
final TestSeq testSeq = _testSeq[i];
if (testSeq != null) {
InstructionList il = testSeq.getInstructionList();
if (il != null)
body.append(il);
// else trivial TestSeq
}
}
}
public static void compileGetChildren(ClassGenerator classGen,
MethodGenerator methodGen,
int node) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
final int git = cpg.addInterfaceMethodref(DOM_INTF,
GET_CHILDREN,
GET_CHILDREN_SIG);
il.append(methodGen.loadDOM());
il.append(new ILOAD(node));
il.append(new INVOKEINTERFACE(git, 2));
}
/**
* Compiles the default handling for DOM elements: traverse all children
*/
private InstructionList compileDefaultRecursion(ClassGenerator classGen,
MethodGenerator methodGen,
InstructionHandle next) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = new InstructionList();
final String applyTemplatesSig = classGen.getApplyTemplatesSig();
final int git = cpg.addInterfaceMethodref(DOM_INTF,
GET_CHILDREN,
GET_CHILDREN_SIG);
final int applyTemplates = cpg.addMethodref(getClassName(),
functionName(),
applyTemplatesSig);
il.append(classGen.loadTranslet());
il.append(methodGen.loadDOM());
il.append(methodGen.loadDOM());
il.append(new ILOAD(_currentIndex));
il.append(new INVOKEINTERFACE(git, 2));
il.append(methodGen.loadHandler());
il.append(new INVOKEVIRTUAL(applyTemplates));
il.append(new GOTO_W(next));
return il;
}
/**
* Compiles the default action for DOM text nodes and attribute nodes:
* output the node's text value
*/
private InstructionList compileDefaultText(ClassGenerator classGen,
MethodGenerator methodGen,
InstructionHandle next) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = new InstructionList();
final int chars = cpg.addInterfaceMethodref(DOM_INTF,
CHARACTERS,
CHARACTERS_SIG);
il.append(methodGen.loadDOM());
il.append(new ILOAD(_currentIndex));
il.append(methodGen.loadHandler());
il.append(new INVOKEINTERFACE(chars, 3));
il.append(new GOTO_W(next));
return il;
}
private InstructionList compileNamespaces(ClassGenerator classGen,
MethodGenerator methodGen,
boolean[] isNamespace,
boolean[] isAttribute,
boolean attrFlag,
InstructionHandle defaultTarget) {
final XSLTC xsltc = classGen.getParser().getXSLTC();
final ConstantPoolGen cpg = classGen.getConstantPool();
// Append switch() statement - namespace test dispatch loop
final Vector namespaces = xsltc.getNamespaceIndex();
final Vector names = xsltc.getNamesIndex();
final int namespaceCount = namespaces.size() + 1;
final int namesCount = names.size();
final InstructionList il = new InstructionList();
final int[] types = new int[namespaceCount];
final InstructionHandle[] targets = new InstructionHandle[types.length];
if (namespaceCount > 0) {
boolean compiled = false;
// Initialize targets for namespace() switch statement
for (int i = 0; i < namespaceCount; i++) {
targets[i] = defaultTarget;
types[i] = i;
}
// Add test sequences for known namespace types
for (int i = DOM.NTYPES; i < (DOM.NTYPES+namesCount); i++) {
if ((isNamespace[i]) && (isAttribute[i] == attrFlag)) {
String name = (String)names.elementAt(i-DOM.NTYPES);
String namespace = name.substring(0,name.lastIndexOf(':'));
final int type = xsltc.registerNamespace(namespace);
if ((i < _testSeq.length) &&
(_testSeq[i] != null)) {
targets[type] =
(_testSeq[i]).compile(classGen,
methodGen,
defaultTarget);
compiled = true;
}
}
}
// Return "null" if no test sequences were compiled
if (!compiled) return(null);
// Append first code in applyTemplates() - get type of current node
final int getNS = cpg.addInterfaceMethodref(DOM_INTF,
"getNamespaceType",
"(I)I");
il.append(methodGen.loadDOM());
il.append(new ILOAD(_currentIndex));
il.append(new INVOKEINTERFACE(getNS, 2));
il.append(new SWITCH(types, targets, defaultTarget));
return(il);
}
else {
return(null);
}
}
/**
* Auxillary method to determine if a qname describes an attribute/element
*/
private static boolean isAttributeName(String qname) {
final int col = qname.indexOf(':') + 1;
if (qname.charAt(col) == '@')
return(true);
else
return(false);
}
private static boolean isNamespaceName(String qname) {
final int col = qname.lastIndexOf(':');
if ((col > -1) && (qname.charAt(qname.length()-1) == '*'))
return(true);
else
return(false);
}
/**
* Compiles the applyTemplates() method and adds it to the translet.
* This is the main dispatch method.
*/
public void compileApplyTemplates(ClassGenerator classGen) {
final XSLTC xsltc = classGen.getParser().getXSLTC();
final ConstantPoolGen cpg = classGen.getConstantPool();
final Vector names = xsltc.getNamesIndex();
// (*) Create the applyTemplates() method
final de.fub.bytecode.generic.Type[] argTypes =
new de.fub.bytecode.generic.Type[3];
argTypes[0] = Util.getJCRefType(DOM_INTF_SIG);
argTypes[1] = Util.getJCRefType(NODE_ITERATOR_SIG);
argTypes[2] = Util.getJCRefType(TRANSLET_OUTPUT_SIG);
final String[] argNames = new String[3];
argNames[0] = DOCUMENT_PNAME;
argNames[1] = ITERATOR_PNAME;
argNames[2] = TRANSLET_OUTPUT_PNAME;
final InstructionList mainIL = new InstructionList();
final MethodGenerator methodGen =
new MethodGenerator(ACC_PUBLIC | ACC_FINAL,
de.fub.bytecode.generic.Type.VOID,
argTypes, argNames, functionName(),
getClassName(), mainIL,
classGen.getConstantPool());
methodGen.addException("org.apache.xalan.xsltc.TransletException");
// (*) Create the local variablea
final LocalVariableGen current;
current = methodGen.addLocalVariable2("current",
de.fub.bytecode.generic.Type.INT,
mainIL.getEnd());
_currentIndex = current.getIndex();
// (*) Create the "body" instruction list that will eventually hold the
// code for the entire method (other ILs will be appended).
final InstructionList body = new InstructionList();
body.append(NOP);
// (*) Create an instruction list that contains the default next-node
// iteration
final InstructionList ilLoop = new InstructionList();
ilLoop.append(methodGen.loadIterator());
ilLoop.append(methodGen.nextNode());
ilLoop.append(DUP);
ilLoop.append(new ISTORE(_currentIndex));
// The body of this code can get very large - large than can be handled
// by a single IFNE(body.getStart()) instruction - need workaround:
final BranchHandle ifeq = ilLoop.append(new IFEQ(null));
final BranchHandle loop = ilLoop.append(new GOTO_W(null));
ifeq.setTarget(ilLoop.append(RETURN)); // applyTemplates() ends here!
final InstructionHandle ihLoop = ilLoop.getStart();
// (*) Compile default handling of elements (traverse children)
InstructionList ilRecurse =
compileDefaultRecursion(classGen, methodGen, ihLoop);
InstructionHandle ihRecurse = ilRecurse.getStart();
// (*) Compile default handling of text/attribute nodes (output text)
InstructionList ilText =
compileDefaultText(classGen, methodGen, ihLoop);
InstructionHandle ihText = ilText.getStart();
// Distinguish attribute/element/namespace tests for further processing
final int[] types = new int[DOM.NTYPES + names.size()];
for (int i = 0; i < types.length; i++) types[i] = i;
final boolean[] isAttribute = new boolean[types.length];
final boolean[] isNamespace = new boolean[types.length];
for (int i = 0; i < names.size(); i++) {
final String name = (String)names.elementAt(i);
isAttribute[i+DOM.NTYPES] = isAttributeName(name);
isNamespace[i+DOM.NTYPES] = isNamespaceName(name);
}
// (*) Compile all templates - regardless of pattern type
compileTemplates(classGen, methodGen, ihLoop);
// (*) Handle template with explicit "*" pattern
final TestSeq elemTest = _testSeq[DOM.ELEMENT];
InstructionHandle ihElem = ihRecurse;
if (elemTest != null)
ihElem = elemTest.compile(classGen, methodGen, ihRecurse);
// (*) Handle template with explicit "@*" pattern
final TestSeq attrTest = _testSeq[DOM.ATTRIBUTE];
InstructionHandle ihAttr = ihText;
if (attrTest != null)
ihAttr = attrTest.compile(classGen, methodGen, ihText);
// Do tests for id() and key() patterns first
InstructionList ilKey = null;
if (_idxTestSeq != null) {
loop.setTarget(_idxTestSeq.compile(classGen, methodGen, body.getStart()));
ilKey = _idxTestSeq.getInstructionList();
}
else {
loop.setTarget(body.getStart());
}
// (*) If there is a match on node() we need to replace ihElem
// and ihText (default behaviour for elements & text).
if (_nodeTestSeq != null) {
double nodePrio = -0.5; //_nodeTestSeq.getPriority();
int nodePos = _nodeTestSeq.getPosition();
double elemPrio = (0 - Double.MAX_VALUE);
int elemPos = Integer.MIN_VALUE;
if (elemTest != null) {
elemPrio = elemTest.getPriority();
elemPos = elemTest.getPosition();
}
if ((elemPrio == Double.NaN) || (elemPrio < nodePrio) ||
((elemPrio == nodePrio) && (elemPos < nodePos))) {
ihElem = _nodeTestSeq.compile(classGen, methodGen, ihLoop);
ihText = ihElem;
}
}
// (*) Handle templates with "ns:*" pattern
InstructionHandle elemNamespaceHandle = ihElem;
InstructionList nsElem = compileNamespaces(classGen, methodGen,
isNamespace, isAttribute,
false, ihElem);
if (nsElem != null) elemNamespaceHandle = nsElem.getStart();
// (*) Handle templates with "ns:@*" pattern
InstructionList nsAttr = compileNamespaces(classGen, methodGen,
isNamespace, isAttribute,
true, ihAttr);
InstructionHandle attrNamespaceHandle = ihAttr;
if (nsAttr != null) attrNamespaceHandle = nsAttr.getStart();
// (*) Handle templates with "ns:elem" or "ns:@attr" pattern
final InstructionHandle[] targets = new InstructionHandle[types.length];
for (int i = DOM.NTYPES; i < targets.length; i++) {
final TestSeq testSeq = _testSeq[i];
// Jump straight to namespace tests ?
if (isNamespace[i]) {
if (isAttribute[i])
targets[i] = attrNamespaceHandle;
else
targets[i] = elemNamespaceHandle;
}
// Test first, then jump to namespace tests
else if (testSeq != null) {
if (isAttribute[i])
targets[i] = testSeq.compile(classGen, methodGen,
attrNamespaceHandle);
else
targets[i] = testSeq.compile(classGen, methodGen,
elemNamespaceHandle);
}
else {
targets[i] = ihLoop;
}
}
// Handle pattern with match on root node - default: traverse children
targets[DOM.ROOT] = _rootPattern != null
? getTemplateInstructionHandle(_rootPattern.getTemplate())
: ihRecurse;
// Handle any pattern with match on text nodes - default: output text
targets[DOM.TEXT] = _testSeq[DOM.TEXT] != null
? _testSeq[DOM.TEXT].compile(classGen, methodGen, ihText)
: ihText;
// This DOM-type is not in use - default: process next node
targets[DOM.UNUSED] = ihLoop;
// Match unknown element in DOM - default: check for namespace match
targets[DOM.ELEMENT] = elemNamespaceHandle;
// Match unknown attribute in DOM - default: check for namespace match
targets[DOM.ATTRIBUTE] = attrNamespaceHandle;
// Match on processing instruction - default: process next node
- InstructionHandle ihPI = ihElem;
+ InstructionHandle ihPI = ihLoop;
+ if (_nodeTestSeq != null) ihPI = ihElem;
if (_testSeq[DOM.PROCESSING_INSTRUCTION] != null)
targets[DOM.PROCESSING_INSTRUCTION] =
_testSeq[DOM.PROCESSING_INSTRUCTION].
compile(classGen, methodGen, ihPI);
else
targets[DOM.PROCESSING_INSTRUCTION] = ihPI;
// Match on comments - default: process next node
- InstructionHandle ihComment = ihElem;
+ InstructionHandle ihComment = ihLoop;
+ if (_nodeTestSeq != null) ihComment = ihElem;
targets[DOM.COMMENT] = _testSeq[DOM.COMMENT] != null
? _testSeq[DOM.COMMENT].compile(classGen, methodGen, ihComment)
: ihComment;
// Now compile test sequences for various match patterns:
for (int i = DOM.NTYPES; i < targets.length; i++) {
final TestSeq testSeq = _testSeq[i];
// Jump straight to namespace tests ?
if ((testSeq == null) || (isNamespace[i])) {
if (isAttribute[i])
targets[i] = attrNamespaceHandle;
else
targets[i] = elemNamespaceHandle;
}
// Match on node type
else {
if (isAttribute[i])
targets[i] = testSeq.compile(classGen, methodGen,
attrNamespaceHandle);
else
targets[i] = testSeq.compile(classGen, methodGen,
elemNamespaceHandle);
}
}
if (ilKey != null) body.insert(ilKey);
// Append first code in applyTemplates() - get type of current node
final int getType = cpg.addInterfaceMethodref(DOM_INTF,
"getType", "(I)I");
body.append(methodGen.loadDOM());
body.append(new ILOAD(_currentIndex));
body.append(new INVOKEINTERFACE(getType, 2));
// Append switch() statement - main dispatch loop in applyTemplates()
InstructionHandle disp = body.append(new SWITCH(types, targets, ihLoop));
// Append all the "case:" statements
appendTestSequences(body);
// Append the actual template code
appendTemplateCode(body);
// Append NS:* node tests (if any)
if (nsElem != null) body.append(nsElem);
// Append NS:@* node tests (if any)
if (nsAttr != null) body.append(nsAttr);
// Append default action for element and root nodes
body.append(ilRecurse);
// Append default action for text and attribute nodes
body.append(ilText);
// putting together constituent instruction lists
mainIL.append(new GOTO_W(ihLoop));
mainIL.append(body);
// fall through to ilLoop
mainIL.append(ilLoop);
peepHoleOptimization(methodGen);
methodGen.stripAttributes(true);
methodGen.setMaxLocals();
methodGen.setMaxStack();
methodGen.removeNOPs();
classGen.addMethod(methodGen.getMethod());
}
/**
* Peephole optimization: Remove sequences of [ALOAD, POP].
*/
private void peepHoleOptimization(MethodGenerator methodGen) {
InstructionList il = methodGen.getInstructionList();
FindPattern find = new FindPattern(il);
InstructionHandle ih;
String pattern;
// Remove sequences of ALOAD, POP
pattern = "`ALOAD'`POP'`Instruction'";
ih = find.search(pattern);
while (ih != null) {
final InstructionHandle[] match = find.getMatch();
try {
if ((!match[0].hasTargeters()) && (!match[1].hasTargeters())) {
il.delete(match[0], match[1]);
}
}
catch (TargetLostException e) {
// TODO: move target down into the list
}
ih = find.search(pattern, match[2]);
}
// Replace sequences of ILOAD_?, ALOAD_?, SWAP with ALOAD_?, ILOAD_?
pattern = "`ILOAD__'`ALOAD__'`SWAP'`Instruction'";
ih = find.search(pattern);
while (ih != null) {
final InstructionHandle[] match = find.getMatch();
try {
de.fub.bytecode.generic.Instruction iload;
de.fub.bytecode.generic.Instruction aload;
if ((!match[0].hasTargeters()) &&
(!match[1].hasTargeters()) &&
(!match[2].hasTargeters())) {
iload = match[0].getInstruction();
aload = match[1].getInstruction();
il.insert(match[0], aload);
il.insert(match[0], iload);
il.delete(match[0], match[2]);
}
}
catch (TargetLostException e) {
// TODO: move target down into the list
}
ih = find.search(pattern, match[3]);
}
// Replaces sequences of ALOAD_1, ALOAD_1 with ALOAD_1, DUP
pattern = "`ALOAD_1'`ALOAD_1'`Instruction'";
ih = find.search(pattern);
while (ih != null) {
final InstructionHandle[] match = find.getMatch();
try {
de.fub.bytecode.generic.Instruction iload;
de.fub.bytecode.generic.Instruction aload;
if ((!match[0].hasTargeters()) && (!match[1].hasTargeters())) {
il.insert(match[1], new DUP());
il.delete(match[1]);
}
}
catch (TargetLostException e) {
// TODO: move target down into the list
}
ih = find.search(pattern, match[2]);
}
// Removes uncessecary GOTOs
/*
pattern = "`GOTO'`GOTO'`Instruction'";
ih = find.search(pattern);
while (ih != null) {
final InstructionHandle[] match = find.getMatch();
try {
de.fub.bytecode.generic.Instruction iload;
de.fub.bytecode.generic.Instruction aload;
InstructionTargeter tgtrs[] = match[1].getTargeters();
if (tgtrs != null) {
InstructionHandle newTarget =
((BranchHandle)match[1]).getTarget();
for (int i=0; i<tgtrs.length; i++)
tgtrs[i].updateTarget(match[1],newTarget);
}
il.delete(match[1]);
}
catch (TargetLostException e) {
// TODO: move target down into the list
}
ih = find.search(pattern, match[2]);
}
*/
}
public InstructionHandle getTemplateInstructionHandle(Template template) {
return (InstructionHandle)_templateIHs.get(template);
}
}
| false | true | public void compileApplyTemplates(ClassGenerator classGen) {
final XSLTC xsltc = classGen.getParser().getXSLTC();
final ConstantPoolGen cpg = classGen.getConstantPool();
final Vector names = xsltc.getNamesIndex();
// (*) Create the applyTemplates() method
final de.fub.bytecode.generic.Type[] argTypes =
new de.fub.bytecode.generic.Type[3];
argTypes[0] = Util.getJCRefType(DOM_INTF_SIG);
argTypes[1] = Util.getJCRefType(NODE_ITERATOR_SIG);
argTypes[2] = Util.getJCRefType(TRANSLET_OUTPUT_SIG);
final String[] argNames = new String[3];
argNames[0] = DOCUMENT_PNAME;
argNames[1] = ITERATOR_PNAME;
argNames[2] = TRANSLET_OUTPUT_PNAME;
final InstructionList mainIL = new InstructionList();
final MethodGenerator methodGen =
new MethodGenerator(ACC_PUBLIC | ACC_FINAL,
de.fub.bytecode.generic.Type.VOID,
argTypes, argNames, functionName(),
getClassName(), mainIL,
classGen.getConstantPool());
methodGen.addException("org.apache.xalan.xsltc.TransletException");
// (*) Create the local variablea
final LocalVariableGen current;
current = methodGen.addLocalVariable2("current",
de.fub.bytecode.generic.Type.INT,
mainIL.getEnd());
_currentIndex = current.getIndex();
// (*) Create the "body" instruction list that will eventually hold the
// code for the entire method (other ILs will be appended).
final InstructionList body = new InstructionList();
body.append(NOP);
// (*) Create an instruction list that contains the default next-node
// iteration
final InstructionList ilLoop = new InstructionList();
ilLoop.append(methodGen.loadIterator());
ilLoop.append(methodGen.nextNode());
ilLoop.append(DUP);
ilLoop.append(new ISTORE(_currentIndex));
// The body of this code can get very large - large than can be handled
// by a single IFNE(body.getStart()) instruction - need workaround:
final BranchHandle ifeq = ilLoop.append(new IFEQ(null));
final BranchHandle loop = ilLoop.append(new GOTO_W(null));
ifeq.setTarget(ilLoop.append(RETURN)); // applyTemplates() ends here!
final InstructionHandle ihLoop = ilLoop.getStart();
// (*) Compile default handling of elements (traverse children)
InstructionList ilRecurse =
compileDefaultRecursion(classGen, methodGen, ihLoop);
InstructionHandle ihRecurse = ilRecurse.getStart();
// (*) Compile default handling of text/attribute nodes (output text)
InstructionList ilText =
compileDefaultText(classGen, methodGen, ihLoop);
InstructionHandle ihText = ilText.getStart();
// Distinguish attribute/element/namespace tests for further processing
final int[] types = new int[DOM.NTYPES + names.size()];
for (int i = 0; i < types.length; i++) types[i] = i;
final boolean[] isAttribute = new boolean[types.length];
final boolean[] isNamespace = new boolean[types.length];
for (int i = 0; i < names.size(); i++) {
final String name = (String)names.elementAt(i);
isAttribute[i+DOM.NTYPES] = isAttributeName(name);
isNamespace[i+DOM.NTYPES] = isNamespaceName(name);
}
// (*) Compile all templates - regardless of pattern type
compileTemplates(classGen, methodGen, ihLoop);
// (*) Handle template with explicit "*" pattern
final TestSeq elemTest = _testSeq[DOM.ELEMENT];
InstructionHandle ihElem = ihRecurse;
if (elemTest != null)
ihElem = elemTest.compile(classGen, methodGen, ihRecurse);
// (*) Handle template with explicit "@*" pattern
final TestSeq attrTest = _testSeq[DOM.ATTRIBUTE];
InstructionHandle ihAttr = ihText;
if (attrTest != null)
ihAttr = attrTest.compile(classGen, methodGen, ihText);
// Do tests for id() and key() patterns first
InstructionList ilKey = null;
if (_idxTestSeq != null) {
loop.setTarget(_idxTestSeq.compile(classGen, methodGen, body.getStart()));
ilKey = _idxTestSeq.getInstructionList();
}
else {
loop.setTarget(body.getStart());
}
// (*) If there is a match on node() we need to replace ihElem
// and ihText (default behaviour for elements & text).
if (_nodeTestSeq != null) {
double nodePrio = -0.5; //_nodeTestSeq.getPriority();
int nodePos = _nodeTestSeq.getPosition();
double elemPrio = (0 - Double.MAX_VALUE);
int elemPos = Integer.MIN_VALUE;
if (elemTest != null) {
elemPrio = elemTest.getPriority();
elemPos = elemTest.getPosition();
}
if ((elemPrio == Double.NaN) || (elemPrio < nodePrio) ||
((elemPrio == nodePrio) && (elemPos < nodePos))) {
ihElem = _nodeTestSeq.compile(classGen, methodGen, ihLoop);
ihText = ihElem;
}
}
// (*) Handle templates with "ns:*" pattern
InstructionHandle elemNamespaceHandle = ihElem;
InstructionList nsElem = compileNamespaces(classGen, methodGen,
isNamespace, isAttribute,
false, ihElem);
if (nsElem != null) elemNamespaceHandle = nsElem.getStart();
// (*) Handle templates with "ns:@*" pattern
InstructionList nsAttr = compileNamespaces(classGen, methodGen,
isNamespace, isAttribute,
true, ihAttr);
InstructionHandle attrNamespaceHandle = ihAttr;
if (nsAttr != null) attrNamespaceHandle = nsAttr.getStart();
// (*) Handle templates with "ns:elem" or "ns:@attr" pattern
final InstructionHandle[] targets = new InstructionHandle[types.length];
for (int i = DOM.NTYPES; i < targets.length; i++) {
final TestSeq testSeq = _testSeq[i];
// Jump straight to namespace tests ?
if (isNamespace[i]) {
if (isAttribute[i])
targets[i] = attrNamespaceHandle;
else
targets[i] = elemNamespaceHandle;
}
// Test first, then jump to namespace tests
else if (testSeq != null) {
if (isAttribute[i])
targets[i] = testSeq.compile(classGen, methodGen,
attrNamespaceHandle);
else
targets[i] = testSeq.compile(classGen, methodGen,
elemNamespaceHandle);
}
else {
targets[i] = ihLoop;
}
}
// Handle pattern with match on root node - default: traverse children
targets[DOM.ROOT] = _rootPattern != null
? getTemplateInstructionHandle(_rootPattern.getTemplate())
: ihRecurse;
// Handle any pattern with match on text nodes - default: output text
targets[DOM.TEXT] = _testSeq[DOM.TEXT] != null
? _testSeq[DOM.TEXT].compile(classGen, methodGen, ihText)
: ihText;
// This DOM-type is not in use - default: process next node
targets[DOM.UNUSED] = ihLoop;
// Match unknown element in DOM - default: check for namespace match
targets[DOM.ELEMENT] = elemNamespaceHandle;
// Match unknown attribute in DOM - default: check for namespace match
targets[DOM.ATTRIBUTE] = attrNamespaceHandle;
// Match on processing instruction - default: process next node
InstructionHandle ihPI = ihElem;
if (_testSeq[DOM.PROCESSING_INSTRUCTION] != null)
targets[DOM.PROCESSING_INSTRUCTION] =
_testSeq[DOM.PROCESSING_INSTRUCTION].
compile(classGen, methodGen, ihPI);
else
targets[DOM.PROCESSING_INSTRUCTION] = ihPI;
// Match on comments - default: process next node
InstructionHandle ihComment = ihElem;
targets[DOM.COMMENT] = _testSeq[DOM.COMMENT] != null
? _testSeq[DOM.COMMENT].compile(classGen, methodGen, ihComment)
: ihComment;
// Now compile test sequences for various match patterns:
for (int i = DOM.NTYPES; i < targets.length; i++) {
final TestSeq testSeq = _testSeq[i];
// Jump straight to namespace tests ?
if ((testSeq == null) || (isNamespace[i])) {
if (isAttribute[i])
targets[i] = attrNamespaceHandle;
else
targets[i] = elemNamespaceHandle;
}
// Match on node type
else {
if (isAttribute[i])
targets[i] = testSeq.compile(classGen, methodGen,
attrNamespaceHandle);
else
targets[i] = testSeq.compile(classGen, methodGen,
elemNamespaceHandle);
}
}
if (ilKey != null) body.insert(ilKey);
// Append first code in applyTemplates() - get type of current node
final int getType = cpg.addInterfaceMethodref(DOM_INTF,
"getType", "(I)I");
body.append(methodGen.loadDOM());
body.append(new ILOAD(_currentIndex));
body.append(new INVOKEINTERFACE(getType, 2));
// Append switch() statement - main dispatch loop in applyTemplates()
InstructionHandle disp = body.append(new SWITCH(types, targets, ihLoop));
// Append all the "case:" statements
appendTestSequences(body);
// Append the actual template code
appendTemplateCode(body);
// Append NS:* node tests (if any)
if (nsElem != null) body.append(nsElem);
// Append NS:@* node tests (if any)
if (nsAttr != null) body.append(nsAttr);
// Append default action for element and root nodes
body.append(ilRecurse);
// Append default action for text and attribute nodes
body.append(ilText);
// putting together constituent instruction lists
mainIL.append(new GOTO_W(ihLoop));
mainIL.append(body);
// fall through to ilLoop
mainIL.append(ilLoop);
peepHoleOptimization(methodGen);
methodGen.stripAttributes(true);
methodGen.setMaxLocals();
methodGen.setMaxStack();
methodGen.removeNOPs();
classGen.addMethod(methodGen.getMethod());
}
| public void compileApplyTemplates(ClassGenerator classGen) {
final XSLTC xsltc = classGen.getParser().getXSLTC();
final ConstantPoolGen cpg = classGen.getConstantPool();
final Vector names = xsltc.getNamesIndex();
// (*) Create the applyTemplates() method
final de.fub.bytecode.generic.Type[] argTypes =
new de.fub.bytecode.generic.Type[3];
argTypes[0] = Util.getJCRefType(DOM_INTF_SIG);
argTypes[1] = Util.getJCRefType(NODE_ITERATOR_SIG);
argTypes[2] = Util.getJCRefType(TRANSLET_OUTPUT_SIG);
final String[] argNames = new String[3];
argNames[0] = DOCUMENT_PNAME;
argNames[1] = ITERATOR_PNAME;
argNames[2] = TRANSLET_OUTPUT_PNAME;
final InstructionList mainIL = new InstructionList();
final MethodGenerator methodGen =
new MethodGenerator(ACC_PUBLIC | ACC_FINAL,
de.fub.bytecode.generic.Type.VOID,
argTypes, argNames, functionName(),
getClassName(), mainIL,
classGen.getConstantPool());
methodGen.addException("org.apache.xalan.xsltc.TransletException");
// (*) Create the local variablea
final LocalVariableGen current;
current = methodGen.addLocalVariable2("current",
de.fub.bytecode.generic.Type.INT,
mainIL.getEnd());
_currentIndex = current.getIndex();
// (*) Create the "body" instruction list that will eventually hold the
// code for the entire method (other ILs will be appended).
final InstructionList body = new InstructionList();
body.append(NOP);
// (*) Create an instruction list that contains the default next-node
// iteration
final InstructionList ilLoop = new InstructionList();
ilLoop.append(methodGen.loadIterator());
ilLoop.append(methodGen.nextNode());
ilLoop.append(DUP);
ilLoop.append(new ISTORE(_currentIndex));
// The body of this code can get very large - large than can be handled
// by a single IFNE(body.getStart()) instruction - need workaround:
final BranchHandle ifeq = ilLoop.append(new IFEQ(null));
final BranchHandle loop = ilLoop.append(new GOTO_W(null));
ifeq.setTarget(ilLoop.append(RETURN)); // applyTemplates() ends here!
final InstructionHandle ihLoop = ilLoop.getStart();
// (*) Compile default handling of elements (traverse children)
InstructionList ilRecurse =
compileDefaultRecursion(classGen, methodGen, ihLoop);
InstructionHandle ihRecurse = ilRecurse.getStart();
// (*) Compile default handling of text/attribute nodes (output text)
InstructionList ilText =
compileDefaultText(classGen, methodGen, ihLoop);
InstructionHandle ihText = ilText.getStart();
// Distinguish attribute/element/namespace tests for further processing
final int[] types = new int[DOM.NTYPES + names.size()];
for (int i = 0; i < types.length; i++) types[i] = i;
final boolean[] isAttribute = new boolean[types.length];
final boolean[] isNamespace = new boolean[types.length];
for (int i = 0; i < names.size(); i++) {
final String name = (String)names.elementAt(i);
isAttribute[i+DOM.NTYPES] = isAttributeName(name);
isNamespace[i+DOM.NTYPES] = isNamespaceName(name);
}
// (*) Compile all templates - regardless of pattern type
compileTemplates(classGen, methodGen, ihLoop);
// (*) Handle template with explicit "*" pattern
final TestSeq elemTest = _testSeq[DOM.ELEMENT];
InstructionHandle ihElem = ihRecurse;
if (elemTest != null)
ihElem = elemTest.compile(classGen, methodGen, ihRecurse);
// (*) Handle template with explicit "@*" pattern
final TestSeq attrTest = _testSeq[DOM.ATTRIBUTE];
InstructionHandle ihAttr = ihText;
if (attrTest != null)
ihAttr = attrTest.compile(classGen, methodGen, ihText);
// Do tests for id() and key() patterns first
InstructionList ilKey = null;
if (_idxTestSeq != null) {
loop.setTarget(_idxTestSeq.compile(classGen, methodGen, body.getStart()));
ilKey = _idxTestSeq.getInstructionList();
}
else {
loop.setTarget(body.getStart());
}
// (*) If there is a match on node() we need to replace ihElem
// and ihText (default behaviour for elements & text).
if (_nodeTestSeq != null) {
double nodePrio = -0.5; //_nodeTestSeq.getPriority();
int nodePos = _nodeTestSeq.getPosition();
double elemPrio = (0 - Double.MAX_VALUE);
int elemPos = Integer.MIN_VALUE;
if (elemTest != null) {
elemPrio = elemTest.getPriority();
elemPos = elemTest.getPosition();
}
if ((elemPrio == Double.NaN) || (elemPrio < nodePrio) ||
((elemPrio == nodePrio) && (elemPos < nodePos))) {
ihElem = _nodeTestSeq.compile(classGen, methodGen, ihLoop);
ihText = ihElem;
}
}
// (*) Handle templates with "ns:*" pattern
InstructionHandle elemNamespaceHandle = ihElem;
InstructionList nsElem = compileNamespaces(classGen, methodGen,
isNamespace, isAttribute,
false, ihElem);
if (nsElem != null) elemNamespaceHandle = nsElem.getStart();
// (*) Handle templates with "ns:@*" pattern
InstructionList nsAttr = compileNamespaces(classGen, methodGen,
isNamespace, isAttribute,
true, ihAttr);
InstructionHandle attrNamespaceHandle = ihAttr;
if (nsAttr != null) attrNamespaceHandle = nsAttr.getStart();
// (*) Handle templates with "ns:elem" or "ns:@attr" pattern
final InstructionHandle[] targets = new InstructionHandle[types.length];
for (int i = DOM.NTYPES; i < targets.length; i++) {
final TestSeq testSeq = _testSeq[i];
// Jump straight to namespace tests ?
if (isNamespace[i]) {
if (isAttribute[i])
targets[i] = attrNamespaceHandle;
else
targets[i] = elemNamespaceHandle;
}
// Test first, then jump to namespace tests
else if (testSeq != null) {
if (isAttribute[i])
targets[i] = testSeq.compile(classGen, methodGen,
attrNamespaceHandle);
else
targets[i] = testSeq.compile(classGen, methodGen,
elemNamespaceHandle);
}
else {
targets[i] = ihLoop;
}
}
// Handle pattern with match on root node - default: traverse children
targets[DOM.ROOT] = _rootPattern != null
? getTemplateInstructionHandle(_rootPattern.getTemplate())
: ihRecurse;
// Handle any pattern with match on text nodes - default: output text
targets[DOM.TEXT] = _testSeq[DOM.TEXT] != null
? _testSeq[DOM.TEXT].compile(classGen, methodGen, ihText)
: ihText;
// This DOM-type is not in use - default: process next node
targets[DOM.UNUSED] = ihLoop;
// Match unknown element in DOM - default: check for namespace match
targets[DOM.ELEMENT] = elemNamespaceHandle;
// Match unknown attribute in DOM - default: check for namespace match
targets[DOM.ATTRIBUTE] = attrNamespaceHandle;
// Match on processing instruction - default: process next node
InstructionHandle ihPI = ihLoop;
if (_nodeTestSeq != null) ihPI = ihElem;
if (_testSeq[DOM.PROCESSING_INSTRUCTION] != null)
targets[DOM.PROCESSING_INSTRUCTION] =
_testSeq[DOM.PROCESSING_INSTRUCTION].
compile(classGen, methodGen, ihPI);
else
targets[DOM.PROCESSING_INSTRUCTION] = ihPI;
// Match on comments - default: process next node
InstructionHandle ihComment = ihLoop;
if (_nodeTestSeq != null) ihComment = ihElem;
targets[DOM.COMMENT] = _testSeq[DOM.COMMENT] != null
? _testSeq[DOM.COMMENT].compile(classGen, methodGen, ihComment)
: ihComment;
// Now compile test sequences for various match patterns:
for (int i = DOM.NTYPES; i < targets.length; i++) {
final TestSeq testSeq = _testSeq[i];
// Jump straight to namespace tests ?
if ((testSeq == null) || (isNamespace[i])) {
if (isAttribute[i])
targets[i] = attrNamespaceHandle;
else
targets[i] = elemNamespaceHandle;
}
// Match on node type
else {
if (isAttribute[i])
targets[i] = testSeq.compile(classGen, methodGen,
attrNamespaceHandle);
else
targets[i] = testSeq.compile(classGen, methodGen,
elemNamespaceHandle);
}
}
if (ilKey != null) body.insert(ilKey);
// Append first code in applyTemplates() - get type of current node
final int getType = cpg.addInterfaceMethodref(DOM_INTF,
"getType", "(I)I");
body.append(methodGen.loadDOM());
body.append(new ILOAD(_currentIndex));
body.append(new INVOKEINTERFACE(getType, 2));
// Append switch() statement - main dispatch loop in applyTemplates()
InstructionHandle disp = body.append(new SWITCH(types, targets, ihLoop));
// Append all the "case:" statements
appendTestSequences(body);
// Append the actual template code
appendTemplateCode(body);
// Append NS:* node tests (if any)
if (nsElem != null) body.append(nsElem);
// Append NS:@* node tests (if any)
if (nsAttr != null) body.append(nsAttr);
// Append default action for element and root nodes
body.append(ilRecurse);
// Append default action for text and attribute nodes
body.append(ilText);
// putting together constituent instruction lists
mainIL.append(new GOTO_W(ihLoop));
mainIL.append(body);
// fall through to ilLoop
mainIL.append(ilLoop);
peepHoleOptimization(methodGen);
methodGen.stripAttributes(true);
methodGen.setMaxLocals();
methodGen.setMaxStack();
methodGen.removeNOPs();
classGen.addMethod(methodGen.getMethod());
}
|
diff --git a/job/command/src/main/java/org/talend/esb/job/command/RunCommand.java b/job/command/src/main/java/org/talend/esb/job/command/RunCommand.java
index d99bee3d8..fd9232f53 100644
--- a/job/command/src/main/java/org/talend/esb/job/command/RunCommand.java
+++ b/job/command/src/main/java/org/talend/esb/job/command/RunCommand.java
@@ -1,36 +1,39 @@
package org.talend.esb.job.command;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.talend.esb.job.controller.Controller;
/**
* Run a Talend job identified by name.
*/
@Command(scope = "job", name = "run", description ="Run a Talend job")
public class RunCommand extends OsgiCommandSupport {
@Option(name = "-a", aliases = {"--args"}, description = "Arguments to use when running the Talend job", required = false, multiValued = false)
String args;
@Argument(index = 0, name = "name", description = "The name of the Talend job to run", required = true, multiValued = false)
String job = null;
private Controller controller;
public void setController(Controller controller) {
this.controller = controller;
}
public Object doExecute() throws Exception {
String[] arguments = null;
if (args != null) {
arguments = args.split(" ");
}
+ if (arguments == null) {
+ arguments = new String[0];
+ }
controller.run(job, arguments);
return null;
}
}
| true | true | public Object doExecute() throws Exception {
String[] arguments = null;
if (args != null) {
arguments = args.split(" ");
}
controller.run(job, arguments);
return null;
}
| public Object doExecute() throws Exception {
String[] arguments = null;
if (args != null) {
arguments = args.split(" ");
}
if (arguments == null) {
arguments = new String[0];
}
controller.run(job, arguments);
return null;
}
|
diff --git a/src/eu/alefzero/owncloud/ui/adapter/FileListListAdapter.java b/src/eu/alefzero/owncloud/ui/adapter/FileListListAdapter.java
index fc28e1f..6008d16 100644
--- a/src/eu/alefzero/owncloud/ui/adapter/FileListListAdapter.java
+++ b/src/eu/alefzero/owncloud/ui/adapter/FileListListAdapter.java
@@ -1,158 +1,158 @@
/* ownCloud Android client application
* Copyright (C) 2011 Bartek Przybylski
*
* 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 eu.alefzero.owncloud.ui.adapter;
import java.util.Vector;
import eu.alefzero.owncloud.DisplayUtils;
import eu.alefzero.owncloud.R;
import eu.alefzero.owncloud.datamodel.DataStorageManager;
import eu.alefzero.owncloud.datamodel.OCFile;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
/**
* This Adapter populates a ListView with all files and folders in an ownCloud
* instance.
*
* @author Bartek Przybylski
*
*/
public class FileListListAdapter implements ListAdapter {
private Context mContext;
private OCFile mFile;
private Vector<OCFile> mFiles;
private DataStorageManager mStorageManager;
public FileListListAdapter(OCFile file, DataStorageManager storage_man,
Context context) {
mFile = file;
mStorageManager = storage_man;
mFiles = mStorageManager.getDirectoryContent(mFile);
mContext = context;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return true;
}
@Override
public int getCount() {
return mFiles != null ? mFiles.size() : 0;
}
@Override
public Object getItem(int position) {
if (mFiles.size() <= position)
return null;
return mFiles.get(position);
}
@Override
public long getItemId(int position) {
return mFiles != null ? mFiles.get(position).getFileId() : 0;
}
@Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflator = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.list_layout, null);
}
if (mFiles.size() > position) {
OCFile file = mFiles.get(position);
TextView fileName = (TextView) view.findViewById(R.id.Filename);
String name = file.getFileName();
fileName.setText(name);
ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
- if (!file.getMimetype().equals("DIR")) {
+ if (file.getMimetype() == null || !file.getMimetype().equals("DIR")) {
fileIcon.setImageResource(R.drawable.file);
} else {
fileIcon.setImageResource(R.drawable.ic_menu_archive);
}
ImageView down = (ImageView) view.findViewById(R.id.imageView2);
if (file.getStoragePath() != null)
down.setVisibility(View.VISIBLE);
else
down.setVisibility(View.INVISIBLE);
if (!file.isDirectory()) {
view.findViewById(R.id.file_size).setVisibility(View.VISIBLE);
view.findViewById(R.id.last_mod).setVisibility(View.VISIBLE);
((TextView)view.findViewById(R.id.file_size)).setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
((TextView)view.findViewById(R.id.last_mod)).setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
} else {
view.findViewById(R.id.file_size).setVisibility(View.GONE);
view.findViewById(R.id.last_mod).setVisibility(View.GONE);
}
}
return view;
}
@Override
public int getViewTypeCount() {
return 4;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return mFiles != null ? mFiles.isEmpty() : false;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflator = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.list_layout, null);
}
if (mFiles.size() > position) {
OCFile file = mFiles.get(position);
TextView fileName = (TextView) view.findViewById(R.id.Filename);
String name = file.getFileName();
fileName.setText(name);
ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
if (!file.getMimetype().equals("DIR")) {
fileIcon.setImageResource(R.drawable.file);
} else {
fileIcon.setImageResource(R.drawable.ic_menu_archive);
}
ImageView down = (ImageView) view.findViewById(R.id.imageView2);
if (file.getStoragePath() != null)
down.setVisibility(View.VISIBLE);
else
down.setVisibility(View.INVISIBLE);
if (!file.isDirectory()) {
view.findViewById(R.id.file_size).setVisibility(View.VISIBLE);
view.findViewById(R.id.last_mod).setVisibility(View.VISIBLE);
((TextView)view.findViewById(R.id.file_size)).setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
((TextView)view.findViewById(R.id.last_mod)).setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
} else {
view.findViewById(R.id.file_size).setVisibility(View.GONE);
view.findViewById(R.id.last_mod).setVisibility(View.GONE);
}
}
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflator = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.list_layout, null);
}
if (mFiles.size() > position) {
OCFile file = mFiles.get(position);
TextView fileName = (TextView) view.findViewById(R.id.Filename);
String name = file.getFileName();
fileName.setText(name);
ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
if (file.getMimetype() == null || !file.getMimetype().equals("DIR")) {
fileIcon.setImageResource(R.drawable.file);
} else {
fileIcon.setImageResource(R.drawable.ic_menu_archive);
}
ImageView down = (ImageView) view.findViewById(R.id.imageView2);
if (file.getStoragePath() != null)
down.setVisibility(View.VISIBLE);
else
down.setVisibility(View.INVISIBLE);
if (!file.isDirectory()) {
view.findViewById(R.id.file_size).setVisibility(View.VISIBLE);
view.findViewById(R.id.last_mod).setVisibility(View.VISIBLE);
((TextView)view.findViewById(R.id.file_size)).setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
((TextView)view.findViewById(R.id.last_mod)).setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
} else {
view.findViewById(R.id.file_size).setVisibility(View.GONE);
view.findViewById(R.id.last_mod).setVisibility(View.GONE);
}
}
return view;
}
|
diff --git a/src/main/java/de/minestar/castaway/listener/RegisterListener.java b/src/main/java/de/minestar/castaway/listener/RegisterListener.java
index 93647e9..98b54e5 100644
--- a/src/main/java/de/minestar/castaway/listener/RegisterListener.java
+++ b/src/main/java/de/minestar/castaway/listener/RegisterListener.java
@@ -1,90 +1,90 @@
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of CastAway.
*
* CastAway 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, version 3 of the License.
*
* CastAway 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 CastAway. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.castaway.listener;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import com.bukkit.gemo.utils.UtilPermissions;
import de.minestar.castaway.blocks.AbstractBlock;
import de.minestar.castaway.blocks.DungeonEndBlock;
import de.minestar.castaway.blocks.DungeonStartBlock;
import de.minestar.castaway.core.CastAwayCore;
import de.minestar.castaway.data.BlockVector;
import de.minestar.castaway.data.Dungeon;
import de.minestar.minestarlibrary.utils.PlayerUtils;
public class RegisterListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
// only some actions are handled
if (event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
// is the ItemInHand correct?
if (event.getPlayer().getItemInHand().getType().equals(Material.BONE)) {
// check permissions?
if (!UtilPermissions.playerCanUseCommand(event.getPlayer(), "castaway.admin")) {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "You are not allowed to do this!");
event.setCancelled(true);
return;
}
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
Player player = event.getPlayer();
boolean isLeftClick = (event.getAction() == Action.LEFT_CLICK_BLOCK);
if (player.isSneaking()) {
Dungeon dungeon = CastAwayCore.gameManager.getDungeonByName("test");
if (dungeon != null) {
if (isLeftClick && event.getClickedBlock().getType().equals(Material.STONE_PLATE)) {
AbstractBlock actionBlock = new DungeonStartBlock(new BlockVector(event.getClickedBlock()), dungeon);
if (CastAwayCore.databaseManager.addActionBlock(actionBlock)) {
CastAwayCore.databaseManager.addActionBlock(actionBlock);
CastAwayCore.gameManager.addBlock(actionBlock.getVector(), actionBlock);
PlayerUtils.sendSuccess(event.getPlayer(), CastAwayCore.NAME, "Start block added for '" + dungeon.getDungeonName() + "'.");
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Error creating block in database!");
}
} else if (!isLeftClick && event.getClickedBlock().getType().equals(Material.STONE_BUTTON)) {
AbstractBlock actionBlock = new DungeonEndBlock(new BlockVector(event.getClickedBlock()), dungeon);
if (CastAwayCore.databaseManager.addActionBlock(actionBlock)) {
CastAwayCore.gameManager.addBlock(actionBlock.getVector(), actionBlock);
PlayerUtils.sendSuccess(event.getPlayer(), CastAwayCore.NAME, "End block added for '" + dungeon.getDungeonName() + "'.");
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Error creating block in database!");
}
}
+ } else {
+ PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Dungeon 'test' not found!");
}
- } else {
- PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Dungeon 'test' not found!");
}
}
}
}
| false | true | public void onPlayerInteract(PlayerInteractEvent event) {
// only some actions are handled
if (event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
// is the ItemInHand correct?
if (event.getPlayer().getItemInHand().getType().equals(Material.BONE)) {
// check permissions?
if (!UtilPermissions.playerCanUseCommand(event.getPlayer(), "castaway.admin")) {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "You are not allowed to do this!");
event.setCancelled(true);
return;
}
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
Player player = event.getPlayer();
boolean isLeftClick = (event.getAction() == Action.LEFT_CLICK_BLOCK);
if (player.isSneaking()) {
Dungeon dungeon = CastAwayCore.gameManager.getDungeonByName("test");
if (dungeon != null) {
if (isLeftClick && event.getClickedBlock().getType().equals(Material.STONE_PLATE)) {
AbstractBlock actionBlock = new DungeonStartBlock(new BlockVector(event.getClickedBlock()), dungeon);
if (CastAwayCore.databaseManager.addActionBlock(actionBlock)) {
CastAwayCore.databaseManager.addActionBlock(actionBlock);
CastAwayCore.gameManager.addBlock(actionBlock.getVector(), actionBlock);
PlayerUtils.sendSuccess(event.getPlayer(), CastAwayCore.NAME, "Start block added for '" + dungeon.getDungeonName() + "'.");
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Error creating block in database!");
}
} else if (!isLeftClick && event.getClickedBlock().getType().equals(Material.STONE_BUTTON)) {
AbstractBlock actionBlock = new DungeonEndBlock(new BlockVector(event.getClickedBlock()), dungeon);
if (CastAwayCore.databaseManager.addActionBlock(actionBlock)) {
CastAwayCore.gameManager.addBlock(actionBlock.getVector(), actionBlock);
PlayerUtils.sendSuccess(event.getPlayer(), CastAwayCore.NAME, "End block added for '" + dungeon.getDungeonName() + "'.");
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Error creating block in database!");
}
}
}
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Dungeon 'test' not found!");
}
}
}
| public void onPlayerInteract(PlayerInteractEvent event) {
// only some actions are handled
if (event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
// is the ItemInHand correct?
if (event.getPlayer().getItemInHand().getType().equals(Material.BONE)) {
// check permissions?
if (!UtilPermissions.playerCanUseCommand(event.getPlayer(), "castaway.admin")) {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "You are not allowed to do this!");
event.setCancelled(true);
return;
}
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
Player player = event.getPlayer();
boolean isLeftClick = (event.getAction() == Action.LEFT_CLICK_BLOCK);
if (player.isSneaking()) {
Dungeon dungeon = CastAwayCore.gameManager.getDungeonByName("test");
if (dungeon != null) {
if (isLeftClick && event.getClickedBlock().getType().equals(Material.STONE_PLATE)) {
AbstractBlock actionBlock = new DungeonStartBlock(new BlockVector(event.getClickedBlock()), dungeon);
if (CastAwayCore.databaseManager.addActionBlock(actionBlock)) {
CastAwayCore.databaseManager.addActionBlock(actionBlock);
CastAwayCore.gameManager.addBlock(actionBlock.getVector(), actionBlock);
PlayerUtils.sendSuccess(event.getPlayer(), CastAwayCore.NAME, "Start block added for '" + dungeon.getDungeonName() + "'.");
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Error creating block in database!");
}
} else if (!isLeftClick && event.getClickedBlock().getType().equals(Material.STONE_BUTTON)) {
AbstractBlock actionBlock = new DungeonEndBlock(new BlockVector(event.getClickedBlock()), dungeon);
if (CastAwayCore.databaseManager.addActionBlock(actionBlock)) {
CastAwayCore.gameManager.addBlock(actionBlock.getVector(), actionBlock);
PlayerUtils.sendSuccess(event.getPlayer(), CastAwayCore.NAME, "End block added for '" + dungeon.getDungeonName() + "'.");
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Error creating block in database!");
}
}
} else {
PlayerUtils.sendError(event.getPlayer(), CastAwayCore.NAME, "Dungeon 'test' not found!");
}
}
}
}
|
diff --git a/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java b/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java
index 4e566962..b126d404 100644
--- a/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java
+++ b/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java
@@ -1,838 +1,838 @@
/*
* 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.proc.out;
import java.io.IOException;
import java.io.StringWriter;
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 javax.management.RuntimeErrorException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xmlvm.Log;
import org.xmlvm.main.Arguments;
import org.xmlvm.proc.XmlvmProcess;
import org.xmlvm.proc.XmlvmProcessImpl;
import org.xmlvm.proc.XmlvmResource;
import org.xmlvm.proc.XmlvmResourceProvider;
import org.xmlvm.proc.XmlvmResource.Type;
import org.xmlvm.proc.in.InputProcess.ClassInputProcess;
import com.android.dx.cf.code.ConcreteMethod;
import com.android.dx.cf.code.Ropper;
import com.android.dx.cf.direct.DirectClassFile;
import com.android.dx.cf.direct.StdAttributeFactory;
import com.android.dx.cf.iface.Field;
import com.android.dx.cf.iface.FieldList;
import com.android.dx.cf.iface.Method;
import com.android.dx.cf.iface.MethodList;
import com.android.dx.dex.cf.CfTranslator;
import com.android.dx.dex.code.CatchHandlerList;
import com.android.dx.dex.code.CatchTable;
import com.android.dx.dex.code.CodeAddress;
import com.android.dx.dex.code.CstInsn;
import com.android.dx.dex.code.DalvCode;
import com.android.dx.dex.code.DalvInsn;
import com.android.dx.dex.code.DalvInsnList;
import com.android.dx.dex.code.Dop;
import com.android.dx.dex.code.Dops;
import com.android.dx.dex.code.HighRegisterPrefix;
import com.android.dx.dex.code.LocalList;
import com.android.dx.dex.code.LocalSnapshot;
import com.android.dx.dex.code.LocalStart;
import com.android.dx.dex.code.OddSpacer;
import com.android.dx.dex.code.PositionList;
import com.android.dx.dex.code.RopTranslator;
import com.android.dx.dex.code.SimpleInsn;
import com.android.dx.dex.code.SwitchData;
import com.android.dx.dex.code.TargetInsn;
import com.android.dx.dex.code.CatchTable.Entry;
import com.android.dx.rop.code.AccessFlags;
import com.android.dx.rop.code.DexTranslationAdvice;
import com.android.dx.rop.code.LocalVariableExtractor;
import com.android.dx.rop.code.LocalVariableInfo;
import com.android.dx.rop.code.RegisterSpec;
import com.android.dx.rop.code.RegisterSpecList;
import com.android.dx.rop.code.RopMethod;
import com.android.dx.rop.code.TranslationAdvice;
import com.android.dx.rop.cst.Constant;
import com.android.dx.rop.cst.CstMemberRef;
import com.android.dx.rop.cst.CstMethodRef;
import com.android.dx.rop.cst.CstNat;
import com.android.dx.rop.cst.CstString;
import com.android.dx.rop.cst.CstType;
import com.android.dx.rop.type.Prototype;
import com.android.dx.rop.type.StdTypeList;
import com.android.dx.rop.type.TypeList;
import com.android.dx.ssa.Optimizer;
import com.android.dx.util.ExceptionWithContext;
import com.android.dx.util.IntList;
/**
* This OutputProcess emits XMLVM code containing register-based DEX
* instructions (XMLVM-DEX).
* <p>
* Android's own DX compiler tool is used to parse class files and to create the
* register-based DEX code in-memory which is then converted to XML.
* <p>
* TODO(Sascha): Work in progress!
*/
public class DEXmlvmOutputProcess extends XmlvmProcessImpl<XmlvmProcess<?>> implements
XmlvmResourceProvider {
/**
* A little helper class that contains package- and class name.
*/
private static class PackagePlusClassName {
public String packageName = "";
public String className = "";
public PackagePlusClassName(String className) {
this.className = className;
}
public PackagePlusClassName(String packageName, String className) {
this.packageName = packageName;
this.className = className;
}
@Override
public String toString() {
if (packageName.isEmpty()) {
return className;
} else {
return packageName + "." + className;
}
}
}
private static final boolean LOTS_OF_DEBUG = false;
private static final String DEXMLVM_ENDING = ".dexmlvm";
private static final Namespace NS_XMLVM = XmlvmResource.xmlvmNamespace;
private static final Namespace NS_DEX = Namespace.getNamespace("dex",
"http://xmlvm.org/dex");
private List<OutputFile> outputFiles = new ArrayList<OutputFile>();
private List<XmlvmResource> generatedResources = new ArrayList<XmlvmResource>();
private static Element lastInvokeInstruction = null;
public DEXmlvmOutputProcess(Arguments arguments) {
super(arguments);
// We can either read class files directly or use the
// JavaByteCodeOutputProcess to use generated bytecode as the input.
addSupportedInput(ClassInputProcess.class);
addSupportedInput(JavaByteCodeOutputProcess.class);
}
@Override
public List<OutputFile> getOutputFiles() {
return outputFiles;
}
@Override
public boolean process() {
generatedResources.clear();
List<XmlvmProcess<?>> preprocesses = preprocess();
for (XmlvmProcess<?> process : preprocesses) {
for (OutputFile preOutputFile : process.getOutputFiles()) {
OutputFile outputFile = generateDEXmlvmFile(preOutputFile);
if (outputFile == null) {
return false;
}
outputFiles.add(outputFile);
}
}
return true;
}
@Override
public List<XmlvmResource> getXmlvmResources() {
return generatedResources;
}
private OutputFile generateDEXmlvmFile(OutputFile classFile) {
Log.debug("DExing:" + classFile.getFileName());
DirectClassFile directClassFile = new DirectClassFile(classFile.getDataAsBytes(), classFile
.getFileName(), false);
Document document = createDocument();
String className = process(directClassFile, document.getRootElement()).replace('.', '_');
generatedResources.add(new XmlvmResource(className, Type.DEX, document));
String fileName = className + DEXMLVM_ENDING;
OutputFile result = new OutputFile();
result.setLocation(arguments.option_out());
result.setFileName(fileName);
result.setData(documentToString(document));
return result;
}
/**
* Converts a class name in the form of a/b/C into a
* {@link PackagePlusClassName} object.
*
*/
private static PackagePlusClassName parseClassName(String packagePlusClassName) {
int lastSlash = packagePlusClassName.lastIndexOf('/');
if (lastSlash == -1) {
return new PackagePlusClassName(packagePlusClassName);
}
String className = packagePlusClassName.substring(lastSlash + 1);
String packageName = packagePlusClassName.substring(0, lastSlash).replace('/', '.');
return new PackagePlusClassName(packageName, className);
}
/**
* Creates a basic XMLVM document.
*/
private static Document createDocument() {
Element root = new Element("xmlvm", NS_XMLVM);
root.addNamespaceDeclaration(NS_DEX);
Document document = new Document();
document.addContent(root);
return document;
}
/**
* Process the given Java Class file and add the classes to the given root.
*
* @param cf
* the class file to process
* @param root
* the root element to append the classes to
* @return the class name for the DEXMLVM file
*/
private String process(DirectClassFile cf, Element root) {
cf.setAttributeFactory(StdAttributeFactory.THE_ONE);
cf.getMagic();
Element classElement = processClass(cf, root);
processFields(cf.getFields(), classElement);
MethodList methods = cf.getMethods();
int sz = methods.size();
for (int i = 0; i < sz; i++) {
Method one = methods.get(i);
try {
processMethod(one, cf, classElement);
} catch (RuntimeException ex) {
String msg = "...while processing " + one.getName().toHuman() + " "
+ one.getDescriptor().toHuman();
throw ExceptionWithContext.withContext(ex, msg);
}
}
CstType thisClass = cf.getThisClass();
return thisClass.getClassType().toHuman();
}
/**
* Creates an XMLVM element for the given type and appends it to the given
* root element.
*
* @param cf
* the {@link DirectClassFile} instance of this class
* @param root
* the root element to append the generated element to
* @return the generated element
*/
private static Element processClass(DirectClassFile cf, Element root) {
Element classElement = new Element("class", NS_XMLVM);
CstType type = cf.getThisClass();
PackagePlusClassName parsedClassName = parseClassName(type.getClassType().getClassName());
classElement.setAttribute("name", parsedClassName.className);
classElement.setAttribute("package", parsedClassName.packageName);
classElement.setAttribute("extends", parseClassName(
cf.getSuperclass().getClassType().getClassName()).toString());
processAccessFlags(cf.getAccessFlags(), classElement);
TypeList interfaces = cf.getInterfaces();
if (interfaces.size() > 0) {
String interfaceList = "";
for (int i = 0; i < interfaces.size(); ++i) {
if (i > 0) {
interfaceList += ",";
}
interfaceList += parseClassName(interfaces.getType(i).getClassName());
}
classElement.setAttribute("interfaces", interfaceList);
}
root.addContent(classElement);
return classElement;
}
/**
* Processes the fields and adds corresponding elements to the class
* element.
*/
private static void processFields(FieldList fieldList, Element classElement) {
for (int i = 0; i < fieldList.size(); ++i) {
Field field = fieldList.get(i);
Element fieldElement = new Element("field", NS_XMLVM);
fieldElement.setAttribute("name", field.getName().toHuman());
fieldElement.setAttribute("type", field.getNat().getFieldType().toHuman());
processAccessFlags(field.getAccessFlags(), fieldElement);
classElement.addContent(fieldElement);
}
}
/**
* Creates an XMLVM element for the given method and appends it to the given
* class element.
* <p>
* This method is roughly based on
* {@link CfTranslator#translate(String, byte[], com.android.dx.dex.cf.CfOptions)}
*
* @param method
* the method to create the element for
* @param classElement
* the class element to append the generated element to
* @param cf
* the class file where this method was originally defined in
*/
private static void processMethod(Method method, DirectClassFile cf, Element classElement) {
final boolean localInfo = true;
final int positionInfo = PositionList.NONE;
CstMethodRef meth = new CstMethodRef(method.getDefiningClass(), method.getNat());
// Extract flags for this method.
int accessFlags = method.getAccessFlags();
boolean isNative = AccessFlags.isNative(accessFlags);
boolean isStatic = AccessFlags.isStatic(accessFlags);
boolean isAbstract = AccessFlags.isAbstract(accessFlags);
// Create XMLVM element for this method
Element methodElement = new Element("method", NS_XMLVM);
methodElement.setAttribute("name", method.getName().getString());
classElement.addContent(methodElement);
// Set the access flag attrobutes for this method.
processAccessFlags(accessFlags, methodElement);
// Create signature element.
methodElement.addContent(processSignature(meth));
// Create code element.
Element codeElement = new Element("code", NS_DEX);
methodElement.addContent(codeElement);
if (isNative || isAbstract) {
// There's no code for native or abstract methods.
} else {
ConcreteMethod concrete = new ConcreteMethod(method, cf,
(positionInfo != PositionList.NONE), localInfo);
TranslationAdvice advice = DexTranslationAdvice.THE_ONE;
RopMethod rmeth = Ropper.convert(concrete, advice);
int paramSize = meth.getParameterWordCount(isStatic);
String canonicalName = method.getDefiningClass().getClassType().getDescriptor() + "."
+ method.getName().getString();
if (LOTS_OF_DEBUG) {
System.out.println("\n\nMethod: " + canonicalName);
}
// Optimize
rmeth = Optimizer.optimize(rmeth, paramSize, isStatic, localInfo, advice);
LocalVariableInfo locals = null;
if (localInfo) {
locals = LocalVariableExtractor.extract(rmeth);
}
DalvCode code = RopTranslator.translate(rmeth, positionInfo, locals, paramSize);
DalvCode.AssignIndicesCallback callback = new DalvCode.AssignIndicesCallback() {
public int getIndex(Constant cst) {
// Everything is at index 0!
return 0;
}
};
code.assignIndices(callback);
DalvInsnList instructions = code.getInsns();
codeElement.setAttribute("register-size", String.valueOf(instructions
.getRegistersSize()));
processLocals(code.getLocals(), codeElement);
processCatchTable(code.getCatches(), codeElement);
Set<Integer> targets = extractTargets(instructions);
Map<Integer, SwitchData> switchDataBlocks = extractSwitchData(instructions);
for (int j = 0; j < instructions.size(); ++j) {
processInstruction(instructions.get(j), codeElement, targets, switchDataBlocks);
}
}
}
/**
* Sets attributes in the element according to the access flags given.
*/
private static void processAccessFlags(int accessFlags, Element element) {
boolean isStatic = AccessFlags.isStatic(accessFlags);
boolean isPrivate = AccessFlags.isPrivate(accessFlags);
boolean isPublic = AccessFlags.isPublic(accessFlags);
boolean isNative = AccessFlags.isNative(accessFlags);
boolean isAbstract = AccessFlags.isAbstract(accessFlags);
boolean isSynthetic = AccessFlags.isSynthetic(accessFlags);
boolean isInterface = AccessFlags.isInterface(accessFlags);
setAttributeIfTrue(element, "isStatic", isStatic);
setAttributeIfTrue(element, "isPrivate", isPrivate);
setAttributeIfTrue(element, "isPublic", isPublic);
setAttributeIfTrue(element, "isNative", isNative);
setAttributeIfTrue(element, "isAbstract", isAbstract);
setAttributeIfTrue(element, "isSynthetic", isSynthetic);
setAttributeIfTrue(element, "isInterface", isInterface);
}
/**
* Extracts the local variables and add {@code var} elements to the {@code
* code} element for each of them.
*/
private static void processLocals(LocalList localList, Element codeElement) {
for (int i = 0; i < localList.size(); ++i) {
com.android.dx.dex.code.LocalList.Entry localEntry = localList.get(i);
Element localElement = new Element("var", NS_DEX);
localElement.setAttribute("name", localEntry.getName().toHuman());
localElement.setAttribute("register", String.valueOf(localEntry.getRegister()));
localElement.setAttribute("type", localEntry.getType().toHuman());
codeElement.addContent(localElement);
}
}
private static void processCatchTable(CatchTable catchTable, Element codeElement) {
if (catchTable.size() == 0) {
return;
}
Element catchTableElement = new Element("catches", NS_DEX);
for (int i = 0; i < catchTable.size(); ++i) {
Entry entry = catchTable.get(i);
Element entryElement = new Element("entry", NS_DEX);
entryElement.setAttribute("start", String.valueOf(entry.getStart()));
entryElement.setAttribute("end", String.valueOf(entry.getEnd()));
CatchHandlerList catchHandlers = entry.getHandlers();
for (int j = 0; j < catchHandlers.size(); ++j) {
com.android.dx.dex.code.CatchHandlerList.Entry handlerEntry = catchHandlers.get(j);
Element handlerElement = new Element("handler", NS_DEX);
handlerElement.setAttribute("type", handlerEntry.getExceptionType().toHuman());
handlerElement.setAttribute("target", String.valueOf(handlerEntry.getHandler()));
entryElement.addContent(handlerElement);
}
catchTableElement.addContent(entryElement);
}
codeElement.addContent(catchTableElement);
}
/**
* Extracts targets that are being jumped to, so we can later add labels at
* the corresponding positions when generating the code.
*
* @return a set containing the addresses of all jump targets
*/
private static Set<Integer> extractTargets(DalvInsnList instructions) {
Set<Integer> targets = new HashSet<Integer>();
for (int i = 0; i < instructions.size(); ++i) {
if (instructions.get(i) instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instructions.get(i);
targets.add(targetInsn.getTargetAddress());
} else if (instructions.get(i) instanceof SwitchData) {
SwitchData switchData = (SwitchData) instructions.get(i);
CodeAddress[] caseTargets = switchData.getTargets();
for (CodeAddress caseTarget : caseTargets) {
targets.add(caseTarget.getAddress());
}
}
}
return targets;
}
/**
* Extracts all {@link SwitchData} pseudo-instructions from the given list
* of instructions.
*
* @param instructions
* the list of instructions from where to extract
* @return a map containing all found {@link SwitchData} instructions,
* indexed by address.
*/
private static Map<Integer, SwitchData> extractSwitchData(DalvInsnList instructions) {
Map<Integer, SwitchData> result = new HashMap<Integer, SwitchData>();
for (int i = 0; i < instructions.size(); ++i) {
if (instructions.get(i) instanceof SwitchData) {
SwitchData switchData = (SwitchData) instructions.get(i);
result.put(switchData.getAddress(), switchData);
}
}
return result;
}
/**
* Creates an element for the given instruction and puts it into the given
* code element. It is possible that no element is added for the given
* instruction.
*
* @param instruction
* the instruction to process
* @param codeElement
* the element to add the instruction element to
* @param targets
* the set of jump targets
*/
private static void processInstruction(DalvInsn instruction, Element codeElement,
Set<Integer> targets, Map<Integer, SwitchData> switchDataBlocks) {
Element dexInstruction = null;
if (instruction.hasAddress()) {
int address = instruction.getAddress();
if (targets.contains(address)) {
Element labelElement = new Element("label", NS_DEX);
labelElement.setAttribute("id", String.valueOf(address));
codeElement.addContent(labelElement);
targets.remove(address);
}
}
if (instruction instanceof CodeAddress) {
// Ignore.
} else if (instruction instanceof LocalSnapshot) {
- // Ingore.
+ // Ignore.
} else if (instruction instanceof OddSpacer) {
- // Ingore NOPs.
+ // Ignore NOPs.
} else if (instruction instanceof SwitchData) {
- // Ingore here because we already processes these and they were
+ // Ignore here because we already processes these and they were
// given to this method as an argument.
} else if (instruction instanceof LocalStart) {
// As we extract the locals information up-front we don't need to
// handle local-start.
} else if (instruction instanceof SimpleInsn) {
SimpleInsn simpleInsn = (SimpleInsn) instruction;
String instructionName = simpleInsn.getOpcode().getName();
// If this is a move-result instruction, we don't add it
// explicitly, but instead add the result register to the previous
// invoke instruction's return.
if (instructionName.startsWith("move-result")) {
// Sanity Check
if (simpleInsn.getRegisters().size() != 1) {
Log.error("DEXmlvmOutputProcess: Register Size doesn't fit 'move-result'.");
System.exit(-1);
}
RegisterSpec register = simpleInsn.getRegisters().get(0);
Element returnElement = lastInvokeInstruction.getChild("parameters", NS_DEX)
.getChild("return", NS_DEX);
returnElement.setAttribute("register", String.valueOf(registerNumber(register
.regString())));
} else {
RegisterSpecList registers = simpleInsn.getRegisters();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(registers, dexInstruction);
// For simple instructions with only one register, we also add
// the type of the register. This includes the return
// instructions.
if (registers.size() == 1) {
dexInstruction.setAttribute("class-type", registers.get(0).getType().toHuman());
}
}
} else if (instruction instanceof CstInsn) {
CstInsn cstInsn = (CstInsn) instruction;
if (isInvokeInstruction(cstInsn)) {
dexInstruction = processInvokeInstruction(cstInsn);
lastInvokeInstruction = dexInstruction;
} else {
dexInstruction = new Element(
sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
Constant constant = cstInsn.getConstant();
dexInstruction.setAttribute("type", constant.typeName());
if (constant instanceof CstMemberRef) {
CstMemberRef memberRef = (CstMemberRef) constant;
dexInstruction.setAttribute("class-type", memberRef.getDefiningClass()
.getClassType().toHuman());
CstNat nameAndType = memberRef.getNat();
dexInstruction.setAttribute("member-type", nameAndType.getFieldType().getType()
.toHuman());
dexInstruction.setAttribute("member-name", nameAndType.getName().toHuman());
} else if (constant instanceof CstString) {
CstString cstString = (CstString) constant;
dexInstruction.setAttribute("value", cstString.getString().getString());
} else {
dexInstruction.setAttribute("value", constant.toHuman());
}
processRegisters(cstInsn.getRegisters(), dexInstruction);
}
} else if (instruction instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instruction;
String instructionName = targetInsn.getOpcode().getName();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(targetInsn.getRegisters(), dexInstruction);
if (instructionName.equals("packed-switch") || instructionName.equals("sparse-switch")) {
SwitchData switchData = switchDataBlocks.get(targetInsn.getTargetAddress());
if (switchData == null) {
Log.error("DEXmlvmOutputProcess: Couldn't find SwitchData block.");
System.exit(-1);
}
IntList cases = switchData.getCases();
CodeAddress[] caseTargets = switchData.getTargets();
// Sanity check.
if (cases.size() != caseTargets.length) {
Log.error("DEXmlvmOutputProcess: SwitchData size mismatch: cases vs targets.");
System.exit(-1);
}
for (int i = 0; i < cases.size(); ++i) {
Element caseElement = new Element("case", NS_DEX);
caseElement.setAttribute("key", String.valueOf(cases.get(i)));
caseElement.setAttribute("label", String.valueOf(caseTargets[i].getAddress()));
dexInstruction.addContent(caseElement);
}
} else {
dexInstruction
.setAttribute("target", String.valueOf(targetInsn.getTargetAddress()));
}
} else if (instruction instanceof HighRegisterPrefix) {
HighRegisterPrefix highRegisterPrefix = (HighRegisterPrefix) instruction;
SimpleInsn[] moveInstructions = highRegisterPrefix.getMoveInstructions();
for (SimpleInsn moveInstruction : moveInstructions) {
processInstruction(moveInstruction, codeElement, targets, switchDataBlocks);
}
} else {
System.err.print(">>> Unknown instruction: ");
System.err.print("(" + instruction.getClass().getName() + ") ");
System.err.print(instruction.listingString("", 0, true));
System.exit(-1);
}
if (LOTS_OF_DEBUG) {
System.out.print("(" + instruction.getClass().getName() + ") ");
System.out.print(instruction.listingString("", 0, true));
}
if (dexInstruction != null) {
codeElement.addContent(dexInstruction);
}
}
/**
* Takes the registers given and appends corresponding attributes to the
* given element.
*/
private static void processRegisters(RegisterSpecList registers, Element element) {
final String[] REGISTER_NAMES = { "vx", "vy", "vz" };
// Sanity check.
if (registers.size() > 3) {
Log.error("DEXmlvmOutputProcess.processRegisters: Too many registers.");
System.exit(-1);
}
for (int i = 0; i < registers.size(); ++i) {
// String type = registers.get(i).getTypeBearer().toHuman();
element.setAttribute(REGISTER_NAMES[i], String.valueOf(registerNumber(registers.get(i)
.regString())));
}
}
/**
* Returns whether the given instruction is an invoke instruction that can
* be handled by {@link #processInvokeInstruction(CstInsn)}.
*/
private static boolean isInvokeInstruction(CstInsn cstInsn) {
final Dop[] invokeInstructions = { Dops.INVOKE_VIRTUAL, Dops.INVOKE_VIRTUAL_RANGE,
Dops.INVOKE_STATIC, Dops.INVOKE_STATIC_RANGE, Dops.INVOKE_DIRECT,
Dops.INVOKE_DIRECT_RANGE, Dops.INVOKE_INTERFACE, Dops.INVOKE_INTERFACE_RANGE,
Dops.INVOKE_SUPER, Dops.INVOKE_SUPER_RANGE };
for (Dop dop : invokeInstructions) {
if (dop.equals(cstInsn.getOpcode())) {
return true;
}
}
return false;
}
/**
* Returns whether the given instruction is an invoke-static instruction.
*/
private static boolean isInvokeStaticInstruction(CstInsn cstInsn) {
final Dop[] staticInvokeInstructions = { Dops.INVOKE_STATIC, Dops.INVOKE_STATIC_RANGE };
for (Dop dop : staticInvokeInstructions) {
if (dop.equals(cstInsn.getOpcode())) {
return true;
}
}
return false;
}
/**
* Returns an element representing the given invoke instruction.
*/
private static Element processInvokeInstruction(CstInsn cstInsn) {
Element result = new Element(sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
CstMethodRef methodRef = (CstMethodRef) cstInsn.getConstant();
result.setAttribute("class-type", methodRef.getDefiningClass().toHuman());
result.setAttribute("method", methodRef.getNat().getName().toHuman());
RegisterSpecList registerList = cstInsn.getRegisters();
List<RegisterSpec> registers = new ArrayList<RegisterSpec>();
if (isInvokeStaticInstruction(cstInsn)) {
if (registerList.size() > 0) {
registers.add(registerList.get(0));
}
} else {
// For non-static invoke instruction, the first register is the
// instance the method is called on.
result.setAttribute("register", String.valueOf(registerNumber(registerList.get(0)
.regString())));
}
// Adds the rest of the registers, if any.
for (int i = 1; i < registerList.size(); ++i) {
registers.add(registerList.get(i));
}
result.addContent(processParameterList(methodRef, registers));
return result;
}
/**
* Processes the signature of the given method reference and returns a
* corresponding element.
*/
private static Element processParameterList(CstMethodRef methodRef, List<RegisterSpec> registers) {
Element result = new Element("parameters", NS_DEX);
Prototype prototype = methodRef.getPrototype();
StdTypeList parameters = prototype.getParameterTypes();
// Sanity check.
if (parameters.size() != registers.size()) {
Log.error("DEXmlvmOutputProcess.processParameterList: Size mismatch: "
+ "registers vs parameters");
System.exit(-1);
}
for (int i = 0; i < parameters.size(); ++i) {
Element parameterElement = new Element("parameter", NS_DEX);
parameterElement.setAttribute("type", parameters.get(i).toHuman());
parameterElement.setAttribute("register", String.valueOf(registerNumber(registers
.get(i).regString())));
result.addContent(parameterElement);
}
Element returnElement = new Element("return", NS_DEX);
returnElement.setAttribute("type", prototype.getReturnType().getType().toHuman());
result.addContent(returnElement);
return result;
}
/**
* Processes the signature of the given method reference and returns a
* corresponding element. It uses 'registers' to add register
*/
private static Element processSignature(CstMethodRef methodRef) {
Prototype prototype = methodRef.getPrototype();
StdTypeList parameters = prototype.getParameterTypes();
Element result = new Element("signature", NS_XMLVM);
for (int i = 0; i < parameters.size(); ++i) {
Element parameterElement = new Element("parameter", NS_XMLVM);
parameterElement.setAttribute("type", parameters.get(i).toHuman());
result.addContent(parameterElement);
}
Element returnElement = new Element("return", NS_XMLVM);
returnElement.setAttribute("type", prototype.getReturnType().getType().toHuman());
result.addContent(returnElement);
return result;
}
/**
* Makes sure the instruction name is valid as an XML tag name.
*/
private static String sanitizeInstructionName(String rawName) {
return rawName.replaceAll("/", "-");
}
/**
* Sets the given attribute in the given element if the value is true only.
* Otherwise, nothing changes.
*/
private static void setAttributeIfTrue(Element element, String attributeName, boolean value) {
if (value) {
element.setAttribute(attributeName, Boolean.toString(value));
}
}
/**
* Extracts the number out of the register name of the format (v0, v1, v2,
* etc).
*
* @param vFormat
* the register name in v-format
* @return the extracted register number
*/
private static int registerNumber(String vFormat) throws RuntimeException {
if (!vFormat.startsWith("v")) {
throw new RuntimeErrorException(new Error(
"Register name doesn't start with 'v' prefix: " + vFormat));
}
try {
int registerNumber = Integer.parseInt(vFormat.substring(1));
return registerNumber;
} catch (NumberFormatException ex) {
throw new RuntimeErrorException(new Error(
"Couldn't extract register number from register name: " + vFormat, ex));
}
}
/**
* Converts a {@link Document} into XML text.
*/
private String documentToString(Document document) {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
StringWriter writer = new StringWriter();
try {
outputter.output(document, writer);
} catch (IOException e) {
e.printStackTrace();
return "";
}
return writer.toString();
}
}
| false | true | private static void processInstruction(DalvInsn instruction, Element codeElement,
Set<Integer> targets, Map<Integer, SwitchData> switchDataBlocks) {
Element dexInstruction = null;
if (instruction.hasAddress()) {
int address = instruction.getAddress();
if (targets.contains(address)) {
Element labelElement = new Element("label", NS_DEX);
labelElement.setAttribute("id", String.valueOf(address));
codeElement.addContent(labelElement);
targets.remove(address);
}
}
if (instruction instanceof CodeAddress) {
// Ignore.
} else if (instruction instanceof LocalSnapshot) {
// Ingore.
} else if (instruction instanceof OddSpacer) {
// Ingore NOPs.
} else if (instruction instanceof SwitchData) {
// Ingore here because we already processes these and they were
// given to this method as an argument.
} else if (instruction instanceof LocalStart) {
// As we extract the locals information up-front we don't need to
// handle local-start.
} else if (instruction instanceof SimpleInsn) {
SimpleInsn simpleInsn = (SimpleInsn) instruction;
String instructionName = simpleInsn.getOpcode().getName();
// If this is a move-result instruction, we don't add it
// explicitly, but instead add the result register to the previous
// invoke instruction's return.
if (instructionName.startsWith("move-result")) {
// Sanity Check
if (simpleInsn.getRegisters().size() != 1) {
Log.error("DEXmlvmOutputProcess: Register Size doesn't fit 'move-result'.");
System.exit(-1);
}
RegisterSpec register = simpleInsn.getRegisters().get(0);
Element returnElement = lastInvokeInstruction.getChild("parameters", NS_DEX)
.getChild("return", NS_DEX);
returnElement.setAttribute("register", String.valueOf(registerNumber(register
.regString())));
} else {
RegisterSpecList registers = simpleInsn.getRegisters();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(registers, dexInstruction);
// For simple instructions with only one register, we also add
// the type of the register. This includes the return
// instructions.
if (registers.size() == 1) {
dexInstruction.setAttribute("class-type", registers.get(0).getType().toHuman());
}
}
} else if (instruction instanceof CstInsn) {
CstInsn cstInsn = (CstInsn) instruction;
if (isInvokeInstruction(cstInsn)) {
dexInstruction = processInvokeInstruction(cstInsn);
lastInvokeInstruction = dexInstruction;
} else {
dexInstruction = new Element(
sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
Constant constant = cstInsn.getConstant();
dexInstruction.setAttribute("type", constant.typeName());
if (constant instanceof CstMemberRef) {
CstMemberRef memberRef = (CstMemberRef) constant;
dexInstruction.setAttribute("class-type", memberRef.getDefiningClass()
.getClassType().toHuman());
CstNat nameAndType = memberRef.getNat();
dexInstruction.setAttribute("member-type", nameAndType.getFieldType().getType()
.toHuman());
dexInstruction.setAttribute("member-name", nameAndType.getName().toHuman());
} else if (constant instanceof CstString) {
CstString cstString = (CstString) constant;
dexInstruction.setAttribute("value", cstString.getString().getString());
} else {
dexInstruction.setAttribute("value", constant.toHuman());
}
processRegisters(cstInsn.getRegisters(), dexInstruction);
}
} else if (instruction instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instruction;
String instructionName = targetInsn.getOpcode().getName();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(targetInsn.getRegisters(), dexInstruction);
if (instructionName.equals("packed-switch") || instructionName.equals("sparse-switch")) {
SwitchData switchData = switchDataBlocks.get(targetInsn.getTargetAddress());
if (switchData == null) {
Log.error("DEXmlvmOutputProcess: Couldn't find SwitchData block.");
System.exit(-1);
}
IntList cases = switchData.getCases();
CodeAddress[] caseTargets = switchData.getTargets();
// Sanity check.
if (cases.size() != caseTargets.length) {
Log.error("DEXmlvmOutputProcess: SwitchData size mismatch: cases vs targets.");
System.exit(-1);
}
for (int i = 0; i < cases.size(); ++i) {
Element caseElement = new Element("case", NS_DEX);
caseElement.setAttribute("key", String.valueOf(cases.get(i)));
caseElement.setAttribute("label", String.valueOf(caseTargets[i].getAddress()));
dexInstruction.addContent(caseElement);
}
} else {
dexInstruction
.setAttribute("target", String.valueOf(targetInsn.getTargetAddress()));
}
} else if (instruction instanceof HighRegisterPrefix) {
HighRegisterPrefix highRegisterPrefix = (HighRegisterPrefix) instruction;
SimpleInsn[] moveInstructions = highRegisterPrefix.getMoveInstructions();
for (SimpleInsn moveInstruction : moveInstructions) {
processInstruction(moveInstruction, codeElement, targets, switchDataBlocks);
}
} else {
System.err.print(">>> Unknown instruction: ");
System.err.print("(" + instruction.getClass().getName() + ") ");
System.err.print(instruction.listingString("", 0, true));
System.exit(-1);
}
if (LOTS_OF_DEBUG) {
System.out.print("(" + instruction.getClass().getName() + ") ");
System.out.print(instruction.listingString("", 0, true));
}
if (dexInstruction != null) {
codeElement.addContent(dexInstruction);
}
}
| private static void processInstruction(DalvInsn instruction, Element codeElement,
Set<Integer> targets, Map<Integer, SwitchData> switchDataBlocks) {
Element dexInstruction = null;
if (instruction.hasAddress()) {
int address = instruction.getAddress();
if (targets.contains(address)) {
Element labelElement = new Element("label", NS_DEX);
labelElement.setAttribute("id", String.valueOf(address));
codeElement.addContent(labelElement);
targets.remove(address);
}
}
if (instruction instanceof CodeAddress) {
// Ignore.
} else if (instruction instanceof LocalSnapshot) {
// Ignore.
} else if (instruction instanceof OddSpacer) {
// Ignore NOPs.
} else if (instruction instanceof SwitchData) {
// Ignore here because we already processes these and they were
// given to this method as an argument.
} else if (instruction instanceof LocalStart) {
// As we extract the locals information up-front we don't need to
// handle local-start.
} else if (instruction instanceof SimpleInsn) {
SimpleInsn simpleInsn = (SimpleInsn) instruction;
String instructionName = simpleInsn.getOpcode().getName();
// If this is a move-result instruction, we don't add it
// explicitly, but instead add the result register to the previous
// invoke instruction's return.
if (instructionName.startsWith("move-result")) {
// Sanity Check
if (simpleInsn.getRegisters().size() != 1) {
Log.error("DEXmlvmOutputProcess: Register Size doesn't fit 'move-result'.");
System.exit(-1);
}
RegisterSpec register = simpleInsn.getRegisters().get(0);
Element returnElement = lastInvokeInstruction.getChild("parameters", NS_DEX)
.getChild("return", NS_DEX);
returnElement.setAttribute("register", String.valueOf(registerNumber(register
.regString())));
} else {
RegisterSpecList registers = simpleInsn.getRegisters();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(registers, dexInstruction);
// For simple instructions with only one register, we also add
// the type of the register. This includes the return
// instructions.
if (registers.size() == 1) {
dexInstruction.setAttribute("class-type", registers.get(0).getType().toHuman());
}
}
} else if (instruction instanceof CstInsn) {
CstInsn cstInsn = (CstInsn) instruction;
if (isInvokeInstruction(cstInsn)) {
dexInstruction = processInvokeInstruction(cstInsn);
lastInvokeInstruction = dexInstruction;
} else {
dexInstruction = new Element(
sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
Constant constant = cstInsn.getConstant();
dexInstruction.setAttribute("type", constant.typeName());
if (constant instanceof CstMemberRef) {
CstMemberRef memberRef = (CstMemberRef) constant;
dexInstruction.setAttribute("class-type", memberRef.getDefiningClass()
.getClassType().toHuman());
CstNat nameAndType = memberRef.getNat();
dexInstruction.setAttribute("member-type", nameAndType.getFieldType().getType()
.toHuman());
dexInstruction.setAttribute("member-name", nameAndType.getName().toHuman());
} else if (constant instanceof CstString) {
CstString cstString = (CstString) constant;
dexInstruction.setAttribute("value", cstString.getString().getString());
} else {
dexInstruction.setAttribute("value", constant.toHuman());
}
processRegisters(cstInsn.getRegisters(), dexInstruction);
}
} else if (instruction instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instruction;
String instructionName = targetInsn.getOpcode().getName();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(targetInsn.getRegisters(), dexInstruction);
if (instructionName.equals("packed-switch") || instructionName.equals("sparse-switch")) {
SwitchData switchData = switchDataBlocks.get(targetInsn.getTargetAddress());
if (switchData == null) {
Log.error("DEXmlvmOutputProcess: Couldn't find SwitchData block.");
System.exit(-1);
}
IntList cases = switchData.getCases();
CodeAddress[] caseTargets = switchData.getTargets();
// Sanity check.
if (cases.size() != caseTargets.length) {
Log.error("DEXmlvmOutputProcess: SwitchData size mismatch: cases vs targets.");
System.exit(-1);
}
for (int i = 0; i < cases.size(); ++i) {
Element caseElement = new Element("case", NS_DEX);
caseElement.setAttribute("key", String.valueOf(cases.get(i)));
caseElement.setAttribute("label", String.valueOf(caseTargets[i].getAddress()));
dexInstruction.addContent(caseElement);
}
} else {
dexInstruction
.setAttribute("target", String.valueOf(targetInsn.getTargetAddress()));
}
} else if (instruction instanceof HighRegisterPrefix) {
HighRegisterPrefix highRegisterPrefix = (HighRegisterPrefix) instruction;
SimpleInsn[] moveInstructions = highRegisterPrefix.getMoveInstructions();
for (SimpleInsn moveInstruction : moveInstructions) {
processInstruction(moveInstruction, codeElement, targets, switchDataBlocks);
}
} else {
System.err.print(">>> Unknown instruction: ");
System.err.print("(" + instruction.getClass().getName() + ") ");
System.err.print(instruction.listingString("", 0, true));
System.exit(-1);
}
if (LOTS_OF_DEBUG) {
System.out.print("(" + instruction.getClass().getName() + ") ");
System.out.print(instruction.listingString("", 0, true));
}
if (dexInstruction != null) {
codeElement.addContent(dexInstruction);
}
}
|
diff --git a/Economy/src/iggy/Economy/Economy.java b/Economy/src/iggy/Economy/Economy.java
index 700ef77..68d890f 100644
--- a/Economy/src/iggy/Economy/Economy.java
+++ b/Economy/src/iggy/Economy/Economy.java
@@ -1,546 +1,554 @@
/******************************************************************************\
| ,, |
| db `7MM |
| ;MM: MM |
| ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 |
| ,M `MM 8I `" MM MM ,M' Yb MM' "' |
| AbmmmqMA `YMMMa. MM MM 8M"""""" MM |
| A' VML L. I8 MM MM YM. , MM |
| .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. |
| |
| |
| ,, ,, |
| .g8"""bgd `7MM db `7MM |
| .dP' `M MM MM |
| dM' ` MM `7MM ,p6"bo MM ,MP' |
| MM MM MM 6M' OO MM ;Y |
| MM. `7MMF' MM MM 8M MM;Mm |
| `Mb. MM MM MM YM. , MM `Mb. |
| `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. |
| |
\******************************************************************************/
/******************************************************************************\
| Copyright (c) 2012, Asher Glick |
| 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. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| POSSIBILITY OF SUCH DAMAGE. |
\******************************************************************************/
package iggy.Economy;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
public class Economy extends JavaPlugin{
//////////////////////////////////////////////////////////////////////////////
///////////////////////////// GLOBAL DECLARATIONS ////////////////////////////
//////////////////////////////////////////////////////////////////////////////
public static Economy plugin;
public final Logger logger = Logger.getLogger("Minecraft");
public Map<String,Long> playerBanks = new HashMap<String,Long>();
// prices of each block
// TODO: make a way of separating the blocks into categories that can be sold by salesNPCs
public Map<Material,Long> blockPrices = new HashMap<Material,Long>();
// prices of each Mob//// BROKEN
//public Map<Class<? extends Entity>,Long> creatureBounties = new HashMap<Class<? extends Entity>,Long>();
// Keep a record of where to send the player back to when they leave the shop
public Map<Player,Location> returnPoint = new HashMap<Player,Location>();
// Initialize the clickable items class
public ItemSelector itemSelector = new ItemSelector(this);
// Initialize income events
public GetMoney incomeEvents = new GetMoney(this);
// Initialize sign shop events
public SignShops signshops = new SignShops(this);
PluginDescriptionFile pdFile;
String pluginName;
String pluginTitle;
// world list
World shopworld;
World mainworld;
World thenether;
World endworld;
//////////////////////////////////////////////////////////////////////////////
////////////////////////////// ENABLE / DISABLE //////////////////////////////
//////////////////////////////////////////////////////////////////////////////
@Override
public void onDisable() {
// save all the configuration info
//saveBounties();//BROKEN
saveMoney();
savePrices();
// reporth that the plugin is disabled
info(" version " + pdFile.getVersion() +" is disabled");
}
@Override
public void onEnable() {
pdFile = this.getDescription();
pluginName = pdFile.getName();
pluginTitle = "[\033[0;32m"+pluginName+"\033[0m]";
// create shop world
shopworld = Bukkit.getServer().getWorld("shopworld");
if (shopworld == null){
info(" Shopworld not found, creating shopworld");
WorldCreator worldCreator = new WorldCreator("shopworld");
worldCreator.generator(new ShopGenerator());
shopworld = worldCreator.createWorld();
shopworld.setSpawnFlags(false, false);
shopworld.setPVP(false);
shopworld.setTime(0);
shopworld.setSpawnLocation(0, 65, 0);
info(" Created shopworld");
}
// set world variables
mainworld = Bukkit.getServer().getWorld("world");
thenether = Bukkit.getServer().getWorld("world_nether");
endworld = Bukkit.getServer().getWorld("world_the_end");
// TODO:spawn and maintain items
//TODO: spawn items
Bukkit.getServer().getPluginManager().registerEvents(itemSelector, this);
Bukkit.getServer().getPluginManager().registerEvents(signshops, this);
// Load all the configuration info
//loadBounties();// BROKEN
loadMoney();
loadPrices();
// activate income events
Bukkit.getServer().getPluginManager().registerEvents(incomeEvents, this);
// report that the plugin is enabled
info(" version " + pdFile.getVersion() +" is enabled");
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// INPUT COMMANDS ///////////////////////////////
//////////////////////////////////////////////////////////////////////////////
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
//World world = player.getWorld();
/************************************ SHOP ************************************\
| This command will teleport the player to and from the shop world. It saves |
| where they are and teleports them to the center of the shop world. If the |
| player does not have a saved location when they try to teleport back they |
| respawn at the world spawn point. It will not let players teleport to the |
| shop if they are not in the main world or the nether |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("shop")){
if (player == null) {
info(" This command can only be run by a pldayer");
return false;
}
else {
// teleporting when you are in a minecart breaks some stuff
if (player.isInsideVehicle()){player.getVehicle().eject();}
// teleporting from the main world or the nether
if (player.getWorld() == mainworld || player.getWorld() == thenether) {
returnPoint.put(player,player.getLocation());
player.teleport(shopworld.getSpawnLocation());
player.sendMessage("Teleported to the shop");
}
// teleporting back from the shop world
else if (player.getWorld() == shopworld){
if (returnPoint.containsKey(player)) {
player.teleport(returnPoint.get(player));
returnPoint.remove(player);
player.sendMessage("Returned you to your world");
}
else {
player.teleport(mainworld.getSpawnLocation());
player.sendMessage("Your old location was corrupted, respawning");
}
}
else {
player.sendMessage("you cant go to the shop from here");
}
}
}
/************************************ PRICE ***********************************\
| This command gets the price of the item stack you are holding. If the block |
| cannot be sold then the buy price is set to 0 and the sell price is not |
| given. The sell price is multiplied by the quantity of the block as well |
| |
| TODO: allow the console to run this function with one argument as well |
\******************************************************************************/
else if (commandLabel.equalsIgnoreCase("price")){
// Prevent the console from running this command
if (player == null) {info(" This command can only be run by a player");}
// Set the default quantity of the item to be questioned
int amount = 1;
Material material;
// If no arguments get the item the player is holding
+ // If the player is not holding an item, get the item
+ // the player is pointing at
if (args.length == 0) {
amount = player.getItemInHand().getAmount();
- material = player.getItemInHand().getType();
+ if( amount > 0 ){
+ material = player.getItemInHand().getType();
+ }
+ else{
+ material = player.getTargetBlock(null, 16).getType();
+ amount = 1;
+ }
}
// if one argument try to find the material requested
else if (args.length == 1){
material = Material.matchMaterial(args[0]);
if (material == null) {
player.sendMessage("Unknown material " + args[0]);
return false;
}
}
// if more then 1 argument report error and exit
else {
player.sendMessage("You cannot list more then one item at a time");
return false;
}
long blockPrice = blockPrices.get(material);
if (blockPrice == -1) {
player.sendMessage(""+amount+" "+material.toString()+" will sell for $"+ChatColor.GREEN+"0"+ChatColor.WHITE+" and cannot be bought");
}
else {
player.sendMessage(""+amount+" "+material.toString()+" will sell for $"+ChatColor.GREEN+(amount*blockPrice/2)+ChatColor.WHITE+" and can be bought for $"+ChatColor.GREEN+(amount*blockPrice)+ChatColor.WHITE);
itemSelector.placeItem(player.getLocation().add(2, 1, 0), material);
}
}
/************************************ MONEY ***********************************\
| Check to see how much money you have. If you are op, have the permission |
| economy.moneymonitor or you are the console you can check the money of any |
| player that you specify |
\******************************************************************************/
else if (commandLabel.equalsIgnoreCase("money")){
// if no player is specified return the caller's balance
if (args.length == 0){
if (player == null){
info(" You need to type in a player name");
}
else {
long money = getMoney(player.getName());
player.sendMessage("You have $"+ChatColor.GREEN+money+ChatColor.WHITE+" in the bank");
}
}
// if a player is specified try to find that player and return the balance
else if (args.length == 1){
if (player == null){
String playername = getFullPlayerName(args[0]);
if (playername == null) return false;
long money = getMoney(playername);
info(" "+playername+" has $"+money);
}
else if (player.hasPermission("economy.moneymonitor")||player.isOp()) {
String playername = getFullPlayerName(args[0]);
if (playername == null) return false;
long money = getMoney(playername);
player.sendMessage(playername+" has $"+ChatColor.GREEN+money+ChatColor.WHITE+" in the bank");
}
}
}
else if (commandLabel.equalsIgnoreCase("grant")) {
if (args.length != 2) {
if (player == null) {
info(" Correct usage is /grant <money> <player>");
}
else {
player.sendMessage(" Correct usage is /grant <money> <player>");
}
}
else if (args.length == 2) {
if (player != null) {
if (!player.isOp() && !player.hasPermission("economy.moneygive")) {
return false;
}
}
String target = getFullPlayerName(args[1]);
if (target == null) return false;
long money = (long)Long.parseLong(args[0]);
giveMoney(target, money);
}
}
else if (commandLabel.equalsIgnoreCase("")){
}
// return false if none of these commands are called (to make java happy)
return false;
}
/**************************** GET FULL PLAYER NAME ****************************\
| This is a helper function for the commands when trying to find a player. |
| if a player is not found it returns null |
| |
| TODO: find offline players as well as online players |
\******************************************************************************/
public String getFullPlayerName (String name) {
String playername = "";
Player findplayer = Bukkit.getServer().getPlayer(name);
if (findplayer == null){
info(" No online player found by that name");
return null;
}
else {
playername = findplayer.getName();
}
return playername;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// Money ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
public void saveMoney() {
this.getConfig().set("banks", "");
Iterator<Entry<String, Long>> bankIterator = playerBanks.entrySet().iterator();
while (bankIterator.hasNext()) {
Entry<String, Long> pairs = bankIterator.next();
this.getConfig().set("banks."+pairs.getKey(), pairs.getValue());
}
this.saveConfig();
info(" Players' accounts saved");
}
public void loadMoney() {
playerBanks.clear();
ConfigurationSection bankConfig = this.getConfig().getConfigurationSection("banks");
if (bankConfig == null) {
severe(" Failed to load bank accounts from config (banks section not found)");
return;
}
Set<String> players = bankConfig.getKeys(false);
if (players == null) {
severe(" Failed to load bank accounts from config (No players found)");
return;
}
Iterator<String> it = players.iterator();
while (it.hasNext()) {
String player = it.next();
long money = this.getConfig().getLong("banks."+player);
playerBanks.put(player, money);
}
info(" Players' accounts loaded");
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// Prices ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
public void savePrices() {
this.getConfig().set("blocks", "");
Iterator<Entry<Material, Long>> blockIterator = blockPrices.entrySet().iterator();
while (blockIterator.hasNext()) {
Entry<Material, Long> pairs = blockIterator.next();
this.getConfig().set("blocks."+pairs.getKey().toString(), pairs.getValue());
}
this.saveConfig();
info(" Block Prices Saved");
}
public void loadPrices() {
blockPrices.clear();
for (int i = 0; i < Material.values().length; i++) {
long price = -1;
blockPrices.put(Material.values()[i], price);
}
ConfigurationSection blockConfig = this.getConfig().getConfigurationSection("blocks");
if (blockConfig == null) {
severe(" Failed to load Block prices from configuration (Blocks section not found)");
return;
}
Set<String> blocks = blockConfig.getKeys(false);
if (blocks == null) {
severe(" Failed to load block prices from config (No blocks found)");
return;
}
Iterator<String> it = blocks.iterator();
while (it.hasNext()) {
String blockname = it.next();
Material block = Material.getMaterial(blockname);
if (block == null) {
severe(" unknown block found in price list ("+blockname+")");
continue;
}
long price = this.getConfig().getLong("blocks."+blockname);
blockPrices.put(block, price);
}
info(" Block Prices Loaded");
}
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////// Bounties //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/*public void saveBounties() {
this.getConfig().set("creatures", "");
Iterator<Entry<Class<? extends Entity>, Long>> creatureIterator = creatureBounties.entrySet().iterator();
while (creatureIterator.hasNext()) {
Entry<Class<? extends Entity>, Long> pairs = creatureIterator.next();
this.getConfig().set("creatures."+pairs.getKey().getSimpleName(), pairs.getValue());
}
this.saveConfig();
info(" Creature Bounties Saved");
}*/
/////////////////////////////////////////BROKEN//////////////////////////////////////////////////////////////
/*public void loadBounties() {
creatureBounties.clear();
Map<String,Class<? extends Entity> > creatureLookup = new HashMap<String,Class<? extends Entity>>();
for (int i = 0; i < CreatureType.values().length; i++) {
long bounty = -1;
Class<? extends Entity> clazz = CreatureType.values()[i].getEntityClass();
creatureBounties.put(clazz, bounty);
creatureLookup.put(clazz.getSimpleName(), clazz);
}
ConfigurationSection creatureConfig = this.getConfig().getConfigurationSection("creatures");
if (creatureConfig == null) {
severe(" Failed to load creature bounties from configuration (creature section not found)");
return;
}
Set<String> creatures = creatureConfig.getKeys(false);
if (creatures == null){
severe(" failed to load creature bounties from configuration (no creatures found)");
return;
}
Iterator<String> it = creatures.iterator();
while(it.hasNext()) {
String creaturename = it.next();
Class<? extends Entity> creature = creatureLookup.get(creaturename);
if (creature == null) {
severe(" unknown creature found in bounty list ("+creaturename+")");
continue;
}
long price = this.getConfig().getLong("creatures."+creaturename);
creatureBounties.put(creature, price);
}
info (" Creature bounties loaded");
}*/
//////////////////////////////////////////////////////////////////////////////
///////////////////////////// Money Modification /////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//the amount of money needed to change at once for any account to be saved
public long moneyDeadZone = 10;
/********************************** GET MONEY *********************************\
| This function returns the amount of money a player has in the bank, if they |
| don't have a bank account yet the create account function is called to |
| create one with the default amount of money |
\******************************************************************************/
public long getMoney(String player) {
long playerMoney = 0;
if (playerBanks.containsKey(player)){
playerMoney = playerBanks.get(player);
}
else {
playerMoney = createAccount (player);
}
return playerMoney;
}
/********************************** SET MONEY *********************************\
| Sets a player's money to a specific value. This function does not do an |
| error checking. It also does not save the money to the config because it |
| cannot check to see if the amount of money added is above the 'deadzone' |
\******************************************************************************/
public void setMoney(String player, long money) {
playerBanks.put(player, money);
}
/******************************* CREATE ACCOUNT *******************************\
| Creates a new user account for a player with a default amount of money. Then |
| returns the amount of money placed in the new player's account |
\******************************************************************************/
public long createAccount(String player) {
long money = 10000;
playerBanks.put(player, money);
saveMoney();
return money;
}
/******************************** CHARGE MONEY ********************************\
| This function will charge money from the player, it will first check to see |
| if the player has enough money and will return true if the money was |
| successfully charged to the account. It will return false if it was not. If |
| a player account cannot be found then it creates an account with the default |
| amount of money, then attempts to charge it |
\******************************************************************************/
public boolean chargeMoney (Player player, long money) {return chargeMoney(player.getName(),money);}
public boolean chargeMoney (String player, long money) {
long playerMoney = getMoney(player);
if (playerMoney >= money) {
playerBanks.put(player, playerMoney-money);
info (player+" was charged $"+money);
if (money > moneyDeadZone){
saveMoney();
}
return true;
}
return false;
}
/********************************* GIVE MONEY *********************************\
| This function gives money to the player, it will not first check the amount |
| of money in the players account (only a problem if the player has more then |
| 9000000000000000 money |
\******************************************************************************/
public boolean giveMoney (Player player,long money) {return giveMoney(player.getName(),money);}
public boolean giveMoney (String player,long money) {
setMoney(player,getMoney(player)+money);
if (money > moneyDeadZone){
saveMoney();
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DISPLAY HELPERS //////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/************************************ INFO ************************************\
| Info will display to the terminal prefacing it with the colored plugin title |
\******************************************************************************/
public void info(String input) {this.logger.info(pluginTitle + input);}
/*********************************** SEVERE ***********************************\
| Severe will display a severe message to the terminal window and color it red |
\******************************************************************************/
public void severe (String input) {this.logger.severe(pluginTitle+"\033[31m"+input+"\033[0m");}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
//World world = player.getWorld();
/************************************ SHOP ************************************\
| This command will teleport the player to and from the shop world. It saves |
| where they are and teleports them to the center of the shop world. If the |
| player does not have a saved location when they try to teleport back they |
| respawn at the world spawn point. It will not let players teleport to the |
| shop if they are not in the main world or the nether |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("shop")){
if (player == null) {
info(" This command can only be run by a pldayer");
return false;
}
else {
// teleporting when you are in a minecart breaks some stuff
if (player.isInsideVehicle()){player.getVehicle().eject();}
// teleporting from the main world or the nether
if (player.getWorld() == mainworld || player.getWorld() == thenether) {
returnPoint.put(player,player.getLocation());
player.teleport(shopworld.getSpawnLocation());
player.sendMessage("Teleported to the shop");
}
// teleporting back from the shop world
else if (player.getWorld() == shopworld){
if (returnPoint.containsKey(player)) {
player.teleport(returnPoint.get(player));
returnPoint.remove(player);
player.sendMessage("Returned you to your world");
}
else {
player.teleport(mainworld.getSpawnLocation());
player.sendMessage("Your old location was corrupted, respawning");
}
}
else {
player.sendMessage("you cant go to the shop from here");
}
}
}
/************************************ PRICE ***********************************\
| This command gets the price of the item stack you are holding. If the block |
| cannot be sold then the buy price is set to 0 and the sell price is not |
| given. The sell price is multiplied by the quantity of the block as well |
| |
| TODO: allow the console to run this function with one argument as well |
\******************************************************************************/
else if (commandLabel.equalsIgnoreCase("price")){
// Prevent the console from running this command
if (player == null) {info(" This command can only be run by a player");}
// Set the default quantity of the item to be questioned
int amount = 1;
Material material;
// If no arguments get the item the player is holding
if (args.length == 0) {
amount = player.getItemInHand().getAmount();
material = player.getItemInHand().getType();
}
// if one argument try to find the material requested
else if (args.length == 1){
material = Material.matchMaterial(args[0]);
if (material == null) {
player.sendMessage("Unknown material " + args[0]);
return false;
}
}
// if more then 1 argument report error and exit
else {
player.sendMessage("You cannot list more then one item at a time");
return false;
}
long blockPrice = blockPrices.get(material);
if (blockPrice == -1) {
player.sendMessage(""+amount+" "+material.toString()+" will sell for $"+ChatColor.GREEN+"0"+ChatColor.WHITE+" and cannot be bought");
}
else {
player.sendMessage(""+amount+" "+material.toString()+" will sell for $"+ChatColor.GREEN+(amount*blockPrice/2)+ChatColor.WHITE+" and can be bought for $"+ChatColor.GREEN+(amount*blockPrice)+ChatColor.WHITE);
itemSelector.placeItem(player.getLocation().add(2, 1, 0), material);
}
}
/************************************ MONEY ***********************************\
| Check to see how much money you have. If you are op, have the permission |
| economy.moneymonitor or you are the console you can check the money of any |
| player that you specify |
\******************************************************************************/
else if (commandLabel.equalsIgnoreCase("money")){
// if no player is specified return the caller's balance
if (args.length == 0){
if (player == null){
info(" You need to type in a player name");
}
else {
long money = getMoney(player.getName());
player.sendMessage("You have $"+ChatColor.GREEN+money+ChatColor.WHITE+" in the bank");
}
}
// if a player is specified try to find that player and return the balance
else if (args.length == 1){
if (player == null){
String playername = getFullPlayerName(args[0]);
if (playername == null) return false;
long money = getMoney(playername);
info(" "+playername+" has $"+money);
}
else if (player.hasPermission("economy.moneymonitor")||player.isOp()) {
String playername = getFullPlayerName(args[0]);
if (playername == null) return false;
long money = getMoney(playername);
player.sendMessage(playername+" has $"+ChatColor.GREEN+money+ChatColor.WHITE+" in the bank");
}
}
}
else if (commandLabel.equalsIgnoreCase("grant")) {
if (args.length != 2) {
if (player == null) {
info(" Correct usage is /grant <money> <player>");
}
else {
player.sendMessage(" Correct usage is /grant <money> <player>");
}
}
else if (args.length == 2) {
if (player != null) {
if (!player.isOp() && !player.hasPermission("economy.moneygive")) {
return false;
}
}
String target = getFullPlayerName(args[1]);
if (target == null) return false;
long money = (long)Long.parseLong(args[0]);
giveMoney(target, money);
}
}
else if (commandLabel.equalsIgnoreCase("")){
}
// return false if none of these commands are called (to make java happy)
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
//World world = player.getWorld();
/************************************ SHOP ************************************\
| This command will teleport the player to and from the shop world. It saves |
| where they are and teleports them to the center of the shop world. If the |
| player does not have a saved location when they try to teleport back they |
| respawn at the world spawn point. It will not let players teleport to the |
| shop if they are not in the main world or the nether |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("shop")){
if (player == null) {
info(" This command can only be run by a pldayer");
return false;
}
else {
// teleporting when you are in a minecart breaks some stuff
if (player.isInsideVehicle()){player.getVehicle().eject();}
// teleporting from the main world or the nether
if (player.getWorld() == mainworld || player.getWorld() == thenether) {
returnPoint.put(player,player.getLocation());
player.teleport(shopworld.getSpawnLocation());
player.sendMessage("Teleported to the shop");
}
// teleporting back from the shop world
else if (player.getWorld() == shopworld){
if (returnPoint.containsKey(player)) {
player.teleport(returnPoint.get(player));
returnPoint.remove(player);
player.sendMessage("Returned you to your world");
}
else {
player.teleport(mainworld.getSpawnLocation());
player.sendMessage("Your old location was corrupted, respawning");
}
}
else {
player.sendMessage("you cant go to the shop from here");
}
}
}
/************************************ PRICE ***********************************\
| This command gets the price of the item stack you are holding. If the block |
| cannot be sold then the buy price is set to 0 and the sell price is not |
| given. The sell price is multiplied by the quantity of the block as well |
| |
| TODO: allow the console to run this function with one argument as well |
\******************************************************************************/
else if (commandLabel.equalsIgnoreCase("price")){
// Prevent the console from running this command
if (player == null) {info(" This command can only be run by a player");}
// Set the default quantity of the item to be questioned
int amount = 1;
Material material;
// If no arguments get the item the player is holding
// If the player is not holding an item, get the item
// the player is pointing at
if (args.length == 0) {
amount = player.getItemInHand().getAmount();
if( amount > 0 ){
material = player.getItemInHand().getType();
}
else{
material = player.getTargetBlock(null, 16).getType();
amount = 1;
}
}
// if one argument try to find the material requested
else if (args.length == 1){
material = Material.matchMaterial(args[0]);
if (material == null) {
player.sendMessage("Unknown material " + args[0]);
return false;
}
}
// if more then 1 argument report error and exit
else {
player.sendMessage("You cannot list more then one item at a time");
return false;
}
long blockPrice = blockPrices.get(material);
if (blockPrice == -1) {
player.sendMessage(""+amount+" "+material.toString()+" will sell for $"+ChatColor.GREEN+"0"+ChatColor.WHITE+" and cannot be bought");
}
else {
player.sendMessage(""+amount+" "+material.toString()+" will sell for $"+ChatColor.GREEN+(amount*blockPrice/2)+ChatColor.WHITE+" and can be bought for $"+ChatColor.GREEN+(amount*blockPrice)+ChatColor.WHITE);
itemSelector.placeItem(player.getLocation().add(2, 1, 0), material);
}
}
/************************************ MONEY ***********************************\
| Check to see how much money you have. If you are op, have the permission |
| economy.moneymonitor or you are the console you can check the money of any |
| player that you specify |
\******************************************************************************/
else if (commandLabel.equalsIgnoreCase("money")){
// if no player is specified return the caller's balance
if (args.length == 0){
if (player == null){
info(" You need to type in a player name");
}
else {
long money = getMoney(player.getName());
player.sendMessage("You have $"+ChatColor.GREEN+money+ChatColor.WHITE+" in the bank");
}
}
// if a player is specified try to find that player and return the balance
else if (args.length == 1){
if (player == null){
String playername = getFullPlayerName(args[0]);
if (playername == null) return false;
long money = getMoney(playername);
info(" "+playername+" has $"+money);
}
else if (player.hasPermission("economy.moneymonitor")||player.isOp()) {
String playername = getFullPlayerName(args[0]);
if (playername == null) return false;
long money = getMoney(playername);
player.sendMessage(playername+" has $"+ChatColor.GREEN+money+ChatColor.WHITE+" in the bank");
}
}
}
else if (commandLabel.equalsIgnoreCase("grant")) {
if (args.length != 2) {
if (player == null) {
info(" Correct usage is /grant <money> <player>");
}
else {
player.sendMessage(" Correct usage is /grant <money> <player>");
}
}
else if (args.length == 2) {
if (player != null) {
if (!player.isOp() && !player.hasPermission("economy.moneygive")) {
return false;
}
}
String target = getFullPlayerName(args[1]);
if (target == null) return false;
long money = (long)Long.parseLong(args[0]);
giveMoney(target, money);
}
}
else if (commandLabel.equalsIgnoreCase("")){
}
// return false if none of these commands are called (to make java happy)
return false;
}
|
diff --git a/src/main/groovy/nl/javadude/gradle/plugins/license/maven/LicenseCheckMojo.java b/src/main/groovy/nl/javadude/gradle/plugins/license/maven/LicenseCheckMojo.java
index 93d01d5..2212e53 100644
--- a/src/main/groovy/nl/javadude/gradle/plugins/license/maven/LicenseCheckMojo.java
+++ b/src/main/groovy/nl/javadude/gradle/plugins/license/maven/LicenseCheckMojo.java
@@ -1,75 +1,76 @@
/**
* Copyright (C) 2008 http://code.google.com/p/maven-license-plugin/
*
* 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 nl.javadude.gradle.plugins.license.maven;
import com.google.code.mojo.license.document.Document;
import com.google.code.mojo.license.header.Header;
import java.io.File;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
/**
* Check if the source files of the project have a valid license header
*
* @author Mathieu Carbou ([email protected])
*/
public final class LicenseCheckMojo implements CallbackWithFailure {
Logger logger = Logging.getLogger(LicenseCheckMojo.class);
private final File basedir;
public final Collection<File> missingHeaders = new ConcurrentLinkedQueue<File>();
/**
* Whether to skip file where a header has been detected
*/
protected boolean skipExistingHeaders = false;
public LicenseCheckMojo(File basedir, boolean skipExistingHeaders) {
this.basedir = basedir;
this.skipExistingHeaders = skipExistingHeaders;
}
@Override
public void onHeaderNotFound(Document document, Header header) {
- if (skipExistingHeaders) {
+ document.parseHeader();
+ if (document.headerDetected() && skipExistingHeaders) {
logger.lifecycle("Ignoring header in: {}", DocumentFactory.getRelativeFile(basedir, document));
return;
} else {
logger.lifecycle("Missing header in: {}", DocumentFactory.getRelativeFile(basedir, document));
}
missingHeaders.add(document.getFile());
}
@Override
public void onExistingHeader(Document document, Header header) {
logger.info("Header OK in: {}", DocumentFactory.getRelativeFile(basedir, document));
}
@Override
public boolean hadFailure() {
return !missingHeaders.isEmpty();
}
@Override
public Collection<File> getAffected() {
return missingHeaders;
}
}
| true | true | public void onHeaderNotFound(Document document, Header header) {
if (skipExistingHeaders) {
logger.lifecycle("Ignoring header in: {}", DocumentFactory.getRelativeFile(basedir, document));
return;
} else {
logger.lifecycle("Missing header in: {}", DocumentFactory.getRelativeFile(basedir, document));
}
missingHeaders.add(document.getFile());
}
| public void onHeaderNotFound(Document document, Header header) {
document.parseHeader();
if (document.headerDetected() && skipExistingHeaders) {
logger.lifecycle("Ignoring header in: {}", DocumentFactory.getRelativeFile(basedir, document));
return;
} else {
logger.lifecycle("Missing header in: {}", DocumentFactory.getRelativeFile(basedir, document));
}
missingHeaders.add(document.getFile());
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
index a59a21641..9715d9c47 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
@@ -1,1134 +1,1139 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import static com.google.gerrit.server.git.MergeUtil.getSubmitter;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.base.Objects;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Sets;
import com.google.gerrit.common.ChangeHooks;
import com.google.gerrit.common.data.Capable;
import com.google.gerrit.common.data.SubmitTypeRecord;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.Project.SubmitType;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.mail.MergeFailSender;
import com.google.gerrit.server.mail.MergedSender;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.util.RequestScopePropagator;
import com.google.gwtorm.server.AtomicUpdate;
import com.google.gwtorm.server.OrmConcurrencyException;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Merges changes in submission order into a single branch.
* <p>
* Branches are reduced to the minimum number of heads needed to merge
* everything. This allows commits to be entered into the queue in any order
* (such as ancestors before descendants) and only the most recent commit on any
* line of development will be merged. All unmerged commits along a line of
* development must be in the submission queue in order to merge the tip of that
* line.
* <p>
* Conflicts are handled by discarding the entire line of development and
* marking it as conflicting, even if an earlier commit along that same line can
* be merged cleanly.
*/
public class MergeOp {
public interface Factory {
MergeOp create(Branch.NameKey branch);
}
private static final Logger log = LoggerFactory.getLogger(MergeOp.class);
/** Amount of time to wait between submit and checking for missing deps. */
private static final long DEPENDENCY_DELAY =
MILLISECONDS.convert(15, MINUTES);
private static final long LOCK_FAILURE_RETRY_DELAY =
MILLISECONDS.convert(15, SECONDS);
private static final long DUPLICATE_MESSAGE_INTERVAL =
MILLISECONDS.convert(1, DAYS);
private final GitRepositoryManager repoManager;
private final SchemaFactory<ReviewDb> schemaFactory;
private final ProjectCache projectCache;
private final LabelNormalizer labelNormalizer;
private final GitReferenceUpdated gitRefUpdated;
private final MergedSender.Factory mergedSenderFactory;
private final MergeFailSender.Factory mergeFailSenderFactory;
private final PatchSetInfoFactory patchSetInfoFactory;
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final ChangeControl.GenericFactory changeControlFactory;
private final MergeQueue mergeQueue;
private final Branch.NameKey destBranch;
private ProjectState destProject;
private final ListMultimap<SubmitType, CodeReviewCommit> toMerge;
private final List<CodeReviewCommit> potentiallyStillSubmittable;
private final Map<Change.Id, CodeReviewCommit> commits;
private ReviewDb db;
private Repository repo;
private RevWalk rw;
private RevFlag canMergeFlag;
private CodeReviewCommit branchTip;
private CodeReviewCommit mergeTip;
private ObjectInserter inserter;
private PersonIdent refLogIdent;
private final ChangeHooks hooks;
private final AccountCache accountCache;
private final TagCache tagCache;
private final SubmitStrategyFactory submitStrategyFactory;
private final SubmoduleOp.Factory subOpFactory;
private final WorkQueue workQueue;
private final RequestScopePropagator requestScopePropagator;
private final AllProjectsName allProjectsName;
@Inject
MergeOp(final GitRepositoryManager grm, final SchemaFactory<ReviewDb> sf,
final ProjectCache pc, final LabelNormalizer fs,
final GitReferenceUpdated gru, final MergedSender.Factory msf,
final MergeFailSender.Factory mfsf,
final PatchSetInfoFactory psif, final IdentifiedUser.GenericFactory iuf,
final ChangeControl.GenericFactory changeControlFactory,
final MergeQueue mergeQueue, @Assisted final Branch.NameKey branch,
final ChangeHooks hooks, final AccountCache accountCache,
final TagCache tagCache,
final SubmitStrategyFactory submitStrategyFactory,
final SubmoduleOp.Factory subOpFactory,
final WorkQueue workQueue,
final RequestScopePropagator requestScopePropagator,
final AllProjectsName allProjectsName) {
repoManager = grm;
schemaFactory = sf;
labelNormalizer = fs;
projectCache = pc;
gitRefUpdated = gru;
mergedSenderFactory = msf;
mergeFailSenderFactory = mfsf;
patchSetInfoFactory = psif;
identifiedUserFactory = iuf;
this.changeControlFactory = changeControlFactory;
this.mergeQueue = mergeQueue;
this.hooks = hooks;
this.accountCache = accountCache;
this.tagCache = tagCache;
this.submitStrategyFactory = submitStrategyFactory;
this.subOpFactory = subOpFactory;
this.workQueue = workQueue;
this.requestScopePropagator = requestScopePropagator;
this.allProjectsName = allProjectsName;
destBranch = branch;
toMerge = ArrayListMultimap.create();
potentiallyStillSubmittable = new ArrayList<CodeReviewCommit>();
commits = new HashMap<Change.Id, CodeReviewCommit>();
}
public void verifyMergeability(Change change) throws NoSuchProjectException {
try {
setDestProject();
openRepository();
final Ref destBranchRef = repo.getRef(destBranch.get());
// Test mergeability of the change if the last merged sha1
// in the branch is different from the last sha1
// the change was tested against.
if ((destBranchRef == null && change.getLastSha1MergeTested() == null)
|| change.getLastSha1MergeTested() == null
|| (destBranchRef != null && !destBranchRef.getObjectId().getName()
.equals(change.getLastSha1MergeTested().get()))) {
openSchema();
openBranch();
validateChangeList(Collections.singletonList(change));
if (!toMerge.isEmpty()) {
final Entry<SubmitType, CodeReviewCommit> e =
toMerge.entries().iterator().next();
final boolean isMergeable =
createStrategy(e.getKey()).dryRun(branchTip, e.getValue());
// update sha1 tested merge.
if (destBranchRef != null) {
change.setLastSha1MergeTested(new RevId(destBranchRef
.getObjectId().getName()));
} else {
change.setLastSha1MergeTested(new RevId(""));
}
change.setMergeable(isMergeable);
db.changes().update(Collections.singleton(change));
} else {
log.error("Test merge attempt for change: " + change.getId()
+ " failed");
}
}
} catch (MergeException e) {
log.error("Test merge attempt for change: " + change.getId()
+ " failed", e);
} catch (OrmException e) {
log.error("Test merge attempt for change: " + change.getId()
+ " failed: Not able to query the database", e);
} catch (IOException e) {
log.error("Test merge attempt for change: " + change.getId()
+ " failed", e);
} finally {
if (repo != null) {
repo.close();
}
if (db != null) {
db.close();
}
}
}
private void setDestProject() throws MergeException {
destProject = projectCache.get(destBranch.getParentKey());
if (destProject == null) {
throw new MergeException("No such project: " + destBranch.getParentKey());
}
}
private void openSchema() throws OrmException {
if (db == null) {
db = schemaFactory.open();
}
}
public void merge() throws MergeException, NoSuchProjectException {
setDestProject();
try {
openSchema();
openRepository();
openBranch();
final ListMultimap<SubmitType, Change> toSubmit =
validateChangeList(db.changes().submitted(destBranch).toList());
final ListMultimap<SubmitType, CodeReviewCommit> toMergeNextTurn =
ArrayListMultimap.create();
final List<CodeReviewCommit> potentiallyStillSubmittableOnNextRun =
new ArrayList<CodeReviewCommit>();
while (!toMerge.isEmpty()) {
toMergeNextTurn.clear();
final Set<SubmitType> submitTypes =
new HashSet<Project.SubmitType>(toMerge.keySet());
for (final SubmitType submitType : submitTypes) {
final RefUpdate branchUpdate = openBranch();
final SubmitStrategy strategy = createStrategy(submitType);
preMerge(strategy, toMerge.get(submitType));
updateBranch(strategy, branchUpdate);
updateChangeStatus(toSubmit.get(submitType));
updateSubscriptions(toSubmit.get(submitType));
for (final Iterator<CodeReviewCommit> it =
potentiallyStillSubmittable.iterator(); it.hasNext();) {
final CodeReviewCommit commit = it.next();
if (containsMissingCommits(toMerge, commit)
|| containsMissingCommits(toMergeNextTurn, commit)) {
// change has missing dependencies, but all commits which are
// missing are still attempted to be merged with another submit
// strategy, retry to merge this commit in the next turn
it.remove();
commit.statusCode = null;
commit.missing = null;
toMergeNextTurn.put(submitType, commit);
}
}
potentiallyStillSubmittableOnNextRun.addAll(potentiallyStillSubmittable);
potentiallyStillSubmittable.clear();
}
toMerge.clear();
toMerge.putAll(toMergeNextTurn);
}
for (final CodeReviewCommit commit : potentiallyStillSubmittableOnNextRun) {
final Capable capable = isSubmitStillPossible(commit);
if (capable != Capable.OK) {
sendMergeFail(commit.change,
message(commit.change, capable.getMessage()), false);
}
}
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
} finally {
if (inserter != null) {
inserter.release();
}
if (rw != null) {
rw.release();
}
if (repo != null) {
repo.close();
}
if (db != null) {
db.close();
}
}
}
private boolean containsMissingCommits(
final ListMultimap<SubmitType, CodeReviewCommit> map,
final CodeReviewCommit commit) {
if (!isSubmitForMissingCommitsStillPossible(commit)) {
return false;
}
for (final CodeReviewCommit missingCommit : commit.missing) {
if (!map.containsValue(missingCommit)) {
return false;
}
}
return true;
}
private boolean isSubmitForMissingCommitsStillPossible(final CodeReviewCommit commit) {
if (commit.missing == null || commit.missing.isEmpty()) {
return false;
}
for (CodeReviewCommit missingCommit : commit.missing) {
loadChangeInfo(missingCommit);
if (missingCommit.patchsetId == null) {
// The commit doesn't have a patch set, so it cannot be
// submitted to the branch.
//
return false;
}
if (!missingCommit.change.currentPatchSetId().equals(
missingCommit.patchsetId)) {
// If the missing commit is not the current patch set,
// the change must be rebased to use the proper parent.
//
return false;
}
}
return true;
}
private void preMerge(final SubmitStrategy strategy,
final List<CodeReviewCommit> toMerge) throws MergeException {
mergeTip = strategy.run(branchTip, toMerge);
refLogIdent = strategy.getRefLogIdent();
commits.putAll(strategy.getNewCommits());
}
private SubmitStrategy createStrategy(final SubmitType submitType)
throws MergeException, NoSuchProjectException {
return submitStrategyFactory.create(submitType, db, repo, rw, inserter,
canMergeFlag, getAlreadyAccepted(branchTip), destBranch);
}
private void openRepository() throws MergeException {
final Project.NameKey name = destBranch.getParentKey();
try {
repo = repoManager.openRepository(name);
} catch (RepositoryNotFoundException notGit) {
final String m = "Repository \"" + name.get() + "\" unknown.";
throw new MergeException(m, notGit);
} catch (IOException err) {
final String m = "Error opening repository \"" + name.get() + '"';
throw new MergeException(m, err);
}
rw = new RevWalk(repo) {
@Override
protected RevCommit createCommit(final AnyObjectId id) {
return new CodeReviewCommit(id);
}
};
rw.sort(RevSort.TOPO);
rw.sort(RevSort.COMMIT_TIME_DESC, true);
canMergeFlag = rw.newFlag("CAN_MERGE");
inserter = repo.newObjectInserter();
}
private RefUpdate openBranch() throws MergeException, OrmException {
try {
final RefUpdate branchUpdate = repo.updateRef(destBranch.get());
if (branchUpdate.getOldObjectId() != null) {
branchTip =
(CodeReviewCommit) rw.parseCommit(branchUpdate.getOldObjectId());
} else {
branchTip = null;
}
try {
final Ref destRef = repo.getRef(destBranch.get());
if (destRef != null) {
branchUpdate.setExpectedOldObjectId(destRef.getObjectId());
} else if (repo.getFullBranch().equals(destBranch.get())) {
branchUpdate.setExpectedOldObjectId(ObjectId.zeroId());
} else {
for (final Change c : db.changes().submitted(destBranch).toList()) {
setNew(c, message(c, "Your change could not be merged, "
+ "because the destination branch does not exist anymore."));
}
}
} catch (IOException e) {
throw new MergeException(
"Failed to check existence of destination branch", e);
}
return branchUpdate;
} catch (IOException e) {
throw new MergeException("Cannot open branch", e);
}
}
private Set<RevCommit> getAlreadyAccepted(final CodeReviewCommit branchTip)
throws MergeException {
final Set<RevCommit> alreadyAccepted = new HashSet<RevCommit>();
if (branchTip != null) {
alreadyAccepted.add(branchTip);
}
try {
for (final Ref r : repo.getAllRefs().values()) {
if (r.getName().startsWith(Constants.R_HEADS)
|| r.getName().startsWith(Constants.R_TAGS)) {
try {
alreadyAccepted.add(rw.parseCommit(r.getObjectId()));
} catch (IncorrectObjectTypeException iote) {
// Not a commit? Skip over it.
}
}
}
} catch (IOException e) {
throw new MergeException("Failed to determine already accepted commits.", e);
}
return alreadyAccepted;
}
private ListMultimap<SubmitType, Change> validateChangeList(
final List<Change> submitted) throws MergeException {
final ListMultimap<SubmitType, Change> toSubmit =
ArrayListMultimap.create();
final Set<ObjectId> tips = new HashSet<ObjectId>();
for (final Ref r : repo.getAllRefs().values()) {
tips.add(r.getObjectId());
}
int commitOrder = 0;
for (final Change chg : submitted) {
final Change.Id changeId = chg.getId();
if (chg.currentPatchSetId() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final PatchSet ps;
try {
ps = db.patchSets().get(chg.currentPatchSetId());
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
}
if (ps == null || ps.getRevision() == null
|| ps.getRevision().get() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final String idstr = ps.getRevision().get();
final ObjectId id;
try {
id = ObjectId.fromString(idstr);
} catch (IllegalArgumentException iae) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
if (!tips.contains(id)) {
// TODO Technically the proper way to do this test is to use a
// RevWalk on "$id --not --all" and test for an empty set. But
// that is way slower than looking for a ref directly pointing
// at the desired tip. We should always have a ref available.
//
// TODO this is actually an error, the branch is gone but we
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
final CodeReviewCommit commit;
try {
commit = (CodeReviewCommit) rw.parseCommit(id);
} catch (IOException e) {
log.error("Invalid commit " + id.name() + " on " + chg.getKey(), e);
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
if (GitRepositoryManager.REF_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
} catch (Exception e) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION));
continue;
}
final Project.NameKey oldParent =
destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT));
continue;
}
} else {
if (!oldParent.equals(newParent)) {
final PatchSetApproval psa = getSubmitter(db, ps.getId());
if (psa == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
final IdentifiedUser submitter =
identifiedUserFactory.create(psa.getAccountId());
if (!submitter.getCapabilities().canAdministrateServer()) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
if (projectCache.get(newParent) == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND));
continue;
}
}
}
}
commit.change = chg;
commit.patchsetId = ps.getId();
commit.originalOrder = commitOrder++;
commits.put(changeId, commit);
if (branchTip != null) {
// If this commit is already merged its a bug in the queuing code
// that we got back here. Just mark it complete and move on. It's
// merged and that is all that mattered to the requestor.
//
try {
if (rw.isMergedInto(commit, branchTip)) {
commit.statusCode = CommitMergeStatus.ALREADY_MERGED;
+ try {
+ setMergedPatchSet(chg.getId(), ps.getId());
+ } catch (OrmException e) {
+ log.error("Cannot mark change " + chg.getId() + " merged", e);
+ }
continue;
}
} catch (IOException err) {
throw new MergeException("Cannot perform merge base test", err);
}
}
final SubmitType submitType = getSubmitType(chg, ps);
if (submitType == null) {
commits.put(changeId,
CodeReviewCommit.error(CommitMergeStatus.NO_SUBMIT_TYPE));
continue;
}
commit.add(canMergeFlag);
toMerge.put(submitType, commit);
toSubmit.put(submitType, chg);
}
return toSubmit;
}
private SubmitType getSubmitType(final Change change, final PatchSet ps) {
try {
final SubmitTypeRecord r =
changeControlFactory.controlFor(change,
identifiedUserFactory.create(change.getOwner()))
.getSubmitTypeRecord(db, ps);
if (r.status != SubmitTypeRecord.Status.OK) {
log.error("Failed to get submit type for " + change.getKey());
return null;
}
return r.type;
} catch (NoSuchChangeException e) {
log.error("Failed to get submit type for " + change.getKey(), e);
return null;
}
}
private void updateBranch(final SubmitStrategy strategy,
final RefUpdate branchUpdate) throws MergeException {
if ((branchTip == null && mergeTip == null) || branchTip == mergeTip) {
// nothing to do
return;
}
if (mergeTip != null && (branchTip == null || branchTip != mergeTip)) {
if (GitRepositoryManager.REF_CONFIG.equals(branchUpdate.getName())) {
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, mergeTip);
} catch (Exception e) {
throw new MergeException("Submit would store invalid"
+ " project configuration " + mergeTip.name() + " for "
+ destProject.getProject().getName(), e);
}
}
branchUpdate.setRefLogIdent(refLogIdent);
branchUpdate.setForceUpdate(false);
branchUpdate.setNewObjectId(mergeTip);
branchUpdate.setRefLogMessage("merged", true);
try {
switch (branchUpdate.update(rw)) {
case NEW:
case FAST_FORWARD:
if (branchUpdate.getResult() == RefUpdate.Result.FAST_FORWARD) {
tagCache.updateFastForward(destBranch.getParentKey(),
branchUpdate.getName(),
branchUpdate.getOldObjectId(),
mergeTip);
}
if (GitRepositoryManager.REF_CONFIG.equals(branchUpdate.getName())) {
projectCache.evict(destProject.getProject());
destProject = projectCache.get(destProject.getProject().getNameKey());
repoManager.setProjectDescription(
destProject.getProject().getNameKey(),
destProject.getProject().getDescription());
}
gitRefUpdated.fire(destBranch.getParentKey(), branchUpdate);
Account account = null;
final PatchSetApproval submitter = getSubmitter(db, mergeTip.patchsetId);
if (submitter != null) {
account = accountCache.get(submitter.getAccountId()).getAccount();
}
hooks.doRefUpdatedHook(destBranch, branchUpdate, account);
break;
case LOCK_FAILURE:
String msg;
if (strategy.retryOnLockFailure()) {
mergeQueue.recheckAfter(destBranch, LOCK_FAILURE_RETRY_DELAY,
MILLISECONDS);
msg = "will retry";
} else {
msg = "will not retry";
}
throw new IOException(branchUpdate.getResult().name() + ", " + msg);
default:
throw new IOException(branchUpdate.getResult().name());
}
} catch (IOException e) {
throw new MergeException("Cannot update " + branchUpdate.getName(), e);
}
}
}
private void updateChangeStatus(final List<Change> submitted) {
for (final Change c : submitted) {
final CodeReviewCommit commit = commits.get(c.getId());
final CommitMergeStatus s = commit != null ? commit.statusCode : null;
if (s == null) {
// Shouldn't ever happen, but leave the change alone. We'll pick
// it up on the next pass.
//
continue;
}
final String txt = s.getMessage();
try {
switch (s) {
case CLEAN_MERGE:
setMerged(c, message(c, txt));
break;
case CLEAN_REBASE:
case CLEAN_PICK:
setMerged(c, message(c, txt + " as " + commit.name()));
break;
case ALREADY_MERGED:
setMerged(c, null);
break;
case PATH_CONFLICT:
case MANUAL_RECURSIVE_MERGE:
case CANNOT_CHERRY_PICK_ROOT:
case NOT_FAST_FORWARD:
case INVALID_PROJECT_CONFIGURATION:
case INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND:
case INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT:
case SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN:
setNew(c, message(c, txt));
break;
case MISSING_DEPENDENCY:
potentiallyStillSubmittable.add(commit);
break;
default:
setNew(c, message(c, "Unspecified merge failure: " + s.name()));
break;
}
} catch (OrmException err) {
log.warn("Error updating change status for " + c.getId(), err);
}
}
}
private void updateSubscriptions(final List<Change> submitted) {
if (mergeTip != null && (branchTip == null || branchTip != mergeTip)) {
SubmoduleOp subOp =
subOpFactory.create(destBranch, mergeTip, rw, repo,
destProject.getProject(), submitted, commits);
try {
subOp.update();
} catch (SubmoduleException e) {
log
.error("The gitLinks were not updated according to the subscriptions "
+ e.getMessage());
}
}
}
private Capable isSubmitStillPossible(final CodeReviewCommit commit) {
final Capable capable;
final Change c = commit.change;
final boolean submitStillPossible = isSubmitForMissingCommitsStillPossible(commit);
final long now = System.currentTimeMillis();
final long waitUntil = c.getLastUpdatedOn().getTime() + DEPENDENCY_DELAY;
if (submitStillPossible && now < waitUntil) {
// If we waited a short while we might still be able to get
// this change submitted. Reschedule an attempt in a bit.
//
mergeQueue.recheckAfter(destBranch, waitUntil - now, MILLISECONDS);
capable = Capable.OK;
} else if (submitStillPossible) {
// It would be possible to submit the change if the missing
// dependencies are also submitted. Perhaps the user just
// forgot to submit those.
//
StringBuilder m = new StringBuilder();
m.append("Change could not be merged because of a missing dependency.");
m.append("\n");
m.append("\n");
m.append("The following changes must also be submitted:\n");
m.append("\n");
for (CodeReviewCommit missingCommit : commit.missing) {
m.append("* ");
m.append(missingCommit.change.getKey().get());
m.append("\n");
}
capable = new Capable(m.toString());
} else {
// It is impossible to submit this change as-is. The author
// needs to rebase it in order to work around the missing
// dependencies.
//
StringBuilder m = new StringBuilder();
m.append("Change cannot be merged due"
+ " to unsatisfiable dependencies.\n");
m.append("\n");
m.append("The following dependency errors were found:\n");
m.append("\n");
for (CodeReviewCommit missingCommit : commit.missing) {
if (missingCommit.patchsetId != null) {
m.append("* Depends on patch set ");
m.append(missingCommit.patchsetId.get());
m.append(" of ");
m.append(missingCommit.change.getKey().abbreviate());
if (missingCommit.patchsetId.get() != missingCommit.change.currentPatchSetId().get()) {
m.append(", however the current patch set is ");
m.append(missingCommit.change.currentPatchSetId().get());
}
m.append(".\n");
} else {
m.append("* Depends on commit ");
m.append(missingCommit.name());
m.append(" which has no change associated with it.\n");
}
}
m.append("\n");
m.append("Please rebase the change and upload a replacement commit.");
capable = new Capable(m.toString());
}
return capable;
}
private void loadChangeInfo(final CodeReviewCommit commit) {
if (commit.patchsetId == null) {
try {
List<PatchSet> matches =
db.patchSets().byRevision(new RevId(commit.name())).toList();
if (matches.size() == 1) {
final PatchSet ps = matches.get(0);
commit.patchsetId = ps.getId();
commit.change = db.changes().get(ps.getId().getParentKey());
}
} catch (OrmException e) {
}
}
}
private ChangeMessage message(final Change c, final String body) {
final String uuid;
try {
uuid = ChangeUtil.messageUUID(db);
} catch (OrmException e) {
return null;
}
final ChangeMessage m =
new ChangeMessage(new ChangeMessage.Key(c.getId(), uuid), null,
c.currentPatchSetId());
m.setMessage(body);
return m;
}
private void setMerged(final Change c, final ChangeMessage msg)
throws OrmException {
try {
db.changes().beginTransaction(c.getId());
// We must pull the patchset out of commits, because the patchset ID is
// modified when using the cherry-pick merge strategy.
CodeReviewCommit commit = commits.get(c.getId());
PatchSet.Id merged = commit.change.currentPatchSetId();
setMergedPatchSet(c.getId(), merged);
PatchSetApproval submitter = saveApprovals(c, merged);
addMergedMessage(submitter, msg);
db.commit();
sendMergedEmail(c, submitter);
if (submitter != null) {
try {
hooks.doChangeMergedHook(c,
accountCache.get(submitter.getAccountId()).getAccount(),
db.patchSets().get(c.currentPatchSetId()), db);
} catch (OrmException ex) {
log.error("Cannot run hook for submitted patch set " + c.getId(), ex);
}
}
} finally {
db.rollback();
}
}
private void setMergedPatchSet(Change.Id changeId, final PatchSet.Id merged)
throws OrmException {
db.changes().atomicUpdate(changeId, new AtomicUpdate<Change>() {
@Override
public Change update(Change c) {
c.setStatus(Change.Status.MERGED);
// It could be possible that the change being merged
// has never had its mergeability tested. So we insure
// merged changes has mergeable field true.
c.setMergeable(true);
if (!merged.equals(c.currentPatchSetId())) {
// Uncool; the patch set changed after we merged it.
// Go back to the patch set that was actually merged.
//
try {
c.setCurrentPatchSet(patchSetInfoFactory.get(db, merged));
} catch (PatchSetInfoNotAvailableException e1) {
log.error("Cannot read merged patch set " + merged, e1);
}
}
ChangeUtil.updated(c);
return c;
}
});
}
private PatchSetApproval saveApprovals(Change c, PatchSet.Id merged)
throws OrmException {
// Flatten out existing approvals for this patch set based upon the current
// permissions. Once the change is closed the approvals are not updated at
// presentation view time, except for zero votes used to indicate a reviewer
// was added. So we need to make sure votes are accurate now. This way if
// permissions get modified in the future, historical records stay accurate.
PatchSetApproval submitter = null;
try {
c.setStatus(Change.Status.MERGED);
List<PatchSetApproval> approvals =
db.patchSetApprovals().byPatchSet(merged).toList();
Set<PatchSetApproval.Key> toDelete =
Sets.newHashSetWithExpectedSize(approvals.size());
for (PatchSetApproval a : approvals) {
if (a.getValue() != 0) {
toDelete.add(a.getKey());
}
}
approvals = labelNormalizer.normalize(c, approvals);
for (PatchSetApproval a : approvals) {
toDelete.remove(a.getKey());
if (a.getValue() > 0 && a.isSubmit()) {
if (submitter == null
|| a.getGranted().compareTo(submitter.getGranted()) > 0) {
submitter = a;
}
}
a.cache(c);
}
db.patchSetApprovals().update(approvals);
db.patchSetApprovals().deleteKeys(toDelete);
} catch (NoSuchChangeException err) {
throw new OrmException(err);
}
return submitter;
}
private void addMergedMessage(PatchSetApproval submitter, ChangeMessage msg)
throws OrmException {
if (msg != null) {
if (submitter != null && msg.getAuthor() == null) {
msg.setAuthor(submitter.getAccountId());
}
db.changeMessages().insert(Collections.singleton(msg));
}
}
private void sendMergedEmail(final Change c, final PatchSetApproval from) {
workQueue.getDefaultQueue()
.submit(requestScopePropagator.wrap(new Runnable() {
@Override
public void run() {
PatchSet patchSet;
try {
ReviewDb reviewDb = schemaFactory.open();
try {
patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
} finally {
reviewDb.close();
}
} catch (Exception e) {
log.error("Cannot send email for submitted patch set " + c.getId(), e);
return;
}
try {
final ChangeControl control = changeControlFactory.controlFor(c,
identifiedUserFactory.create(c.getOwner()));
final MergedSender cm = mergedSenderFactory.create(control);
if (from != null) {
cm.setFrom(from.getAccountId());
}
cm.setPatchSet(patchSet);
cm.send();
} catch (Exception e) {
log.error("Cannot send email for submitted patch set " + c.getId(), e);
}
}
@Override
public String toString() {
return "send-email merged";
}
}));
}
private void setNew(Change c, ChangeMessage msg) {
sendMergeFail(c, msg, true);
}
private boolean isDuplicate(ChangeMessage msg) {
try {
ChangeMessage last = Iterables.getLast(db.changeMessages().byChange(
msg.getPatchSetId().getParentKey()), null);
if (last != null) {
long lastMs = last.getWrittenOn().getTime();
long msgMs = msg.getWrittenOn().getTime();
if (Objects.equal(last.getAuthor(), msg.getAuthor())
&& Objects.equal(last.getMessage(), msg.getMessage())
&& msgMs - lastMs < DUPLICATE_MESSAGE_INTERVAL) {
return true;
}
}
} catch (OrmException err) {
log.warn("Cannot check previous merge failure message", err);
}
return false;
}
private void sendMergeFail(final Change c, final ChangeMessage msg,
final boolean makeNew) {
if (isDuplicate(msg)) {
return;
}
try {
db.changeMessages().insert(Collections.singleton(msg));
} catch (OrmException err) {
log.warn("Cannot record merge failure message", err);
}
if (makeNew) {
try {
db.changes().atomicUpdate(c.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change c) {
if (c.getStatus().isOpen()) {
c.setStatus(Change.Status.NEW);
ChangeUtil.updated(c);
}
return c;
}
});
} catch (OrmConcurrencyException err) {
} catch (OrmException err) {
log.warn("Cannot update change status", err);
}
} else {
try {
ChangeUtil.touch(c, db);
} catch (OrmException err) {
log.warn("Cannot update change timestamp", err);
}
}
PatchSetApproval submitter = null;
try {
submitter = getSubmitter(db, c.currentPatchSetId());
} catch (Exception e) {
log.error("Cannot get submitter", e);
}
final PatchSetApproval from = submitter;
workQueue.getDefaultQueue()
.submit(requestScopePropagator.wrap(new Runnable() {
@Override
public void run() {
PatchSet patchSet;
try {
ReviewDb reviewDb = schemaFactory.open();
try {
patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
} finally {
reviewDb.close();
}
} catch (Exception e) {
log.error("Cannot send email notifications about merge failure", e);
return;
}
try {
final MergeFailSender cm = mergeFailSenderFactory.create(c);
if (from != null) {
cm.setFrom(from.getAccountId());
}
cm.setPatchSet(patchSet);
cm.setChangeMessage(msg);
cm.send();
} catch (Exception e) {
log.error("Cannot send email notifications about merge failure", e);
}
}
@Override
public String toString() {
return "send-email merge-failed";
}
}));
if (submitter != null) {
try {
hooks.doMergeFailedHook(c,
accountCache.get(submitter.getAccountId()).getAccount(),
db.patchSets().get(c.currentPatchSetId()), msg.getMessage(), db);
} catch (OrmException ex) {
log.error("Cannot run hook for merge failed " + c.getId(), ex);
}
}
}
}
| true | true | private ListMultimap<SubmitType, Change> validateChangeList(
final List<Change> submitted) throws MergeException {
final ListMultimap<SubmitType, Change> toSubmit =
ArrayListMultimap.create();
final Set<ObjectId> tips = new HashSet<ObjectId>();
for (final Ref r : repo.getAllRefs().values()) {
tips.add(r.getObjectId());
}
int commitOrder = 0;
for (final Change chg : submitted) {
final Change.Id changeId = chg.getId();
if (chg.currentPatchSetId() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final PatchSet ps;
try {
ps = db.patchSets().get(chg.currentPatchSetId());
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
}
if (ps == null || ps.getRevision() == null
|| ps.getRevision().get() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final String idstr = ps.getRevision().get();
final ObjectId id;
try {
id = ObjectId.fromString(idstr);
} catch (IllegalArgumentException iae) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
if (!tips.contains(id)) {
// TODO Technically the proper way to do this test is to use a
// RevWalk on "$id --not --all" and test for an empty set. But
// that is way slower than looking for a ref directly pointing
// at the desired tip. We should always have a ref available.
//
// TODO this is actually an error, the branch is gone but we
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
final CodeReviewCommit commit;
try {
commit = (CodeReviewCommit) rw.parseCommit(id);
} catch (IOException e) {
log.error("Invalid commit " + id.name() + " on " + chg.getKey(), e);
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
if (GitRepositoryManager.REF_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
} catch (Exception e) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION));
continue;
}
final Project.NameKey oldParent =
destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT));
continue;
}
} else {
if (!oldParent.equals(newParent)) {
final PatchSetApproval psa = getSubmitter(db, ps.getId());
if (psa == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
final IdentifiedUser submitter =
identifiedUserFactory.create(psa.getAccountId());
if (!submitter.getCapabilities().canAdministrateServer()) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
if (projectCache.get(newParent) == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND));
continue;
}
}
}
}
commit.change = chg;
commit.patchsetId = ps.getId();
commit.originalOrder = commitOrder++;
commits.put(changeId, commit);
if (branchTip != null) {
// If this commit is already merged its a bug in the queuing code
// that we got back here. Just mark it complete and move on. It's
// merged and that is all that mattered to the requestor.
//
try {
if (rw.isMergedInto(commit, branchTip)) {
commit.statusCode = CommitMergeStatus.ALREADY_MERGED;
continue;
}
} catch (IOException err) {
throw new MergeException("Cannot perform merge base test", err);
}
}
final SubmitType submitType = getSubmitType(chg, ps);
if (submitType == null) {
commits.put(changeId,
CodeReviewCommit.error(CommitMergeStatus.NO_SUBMIT_TYPE));
continue;
}
commit.add(canMergeFlag);
toMerge.put(submitType, commit);
toSubmit.put(submitType, chg);
}
return toSubmit;
}
| private ListMultimap<SubmitType, Change> validateChangeList(
final List<Change> submitted) throws MergeException {
final ListMultimap<SubmitType, Change> toSubmit =
ArrayListMultimap.create();
final Set<ObjectId> tips = new HashSet<ObjectId>();
for (final Ref r : repo.getAllRefs().values()) {
tips.add(r.getObjectId());
}
int commitOrder = 0;
for (final Change chg : submitted) {
final Change.Id changeId = chg.getId();
if (chg.currentPatchSetId() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final PatchSet ps;
try {
ps = db.patchSets().get(chg.currentPatchSetId());
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
}
if (ps == null || ps.getRevision() == null
|| ps.getRevision().get() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final String idstr = ps.getRevision().get();
final ObjectId id;
try {
id = ObjectId.fromString(idstr);
} catch (IllegalArgumentException iae) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
if (!tips.contains(id)) {
// TODO Technically the proper way to do this test is to use a
// RevWalk on "$id --not --all" and test for an empty set. But
// that is way slower than looking for a ref directly pointing
// at the desired tip. We should always have a ref available.
//
// TODO this is actually an error, the branch is gone but we
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
final CodeReviewCommit commit;
try {
commit = (CodeReviewCommit) rw.parseCommit(id);
} catch (IOException e) {
log.error("Invalid commit " + id.name() + " on " + chg.getKey(), e);
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
if (GitRepositoryManager.REF_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
} catch (Exception e) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION));
continue;
}
final Project.NameKey oldParent =
destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT));
continue;
}
} else {
if (!oldParent.equals(newParent)) {
final PatchSetApproval psa = getSubmitter(db, ps.getId());
if (psa == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
final IdentifiedUser submitter =
identifiedUserFactory.create(psa.getAccountId());
if (!submitter.getCapabilities().canAdministrateServer()) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
if (projectCache.get(newParent) == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND));
continue;
}
}
}
}
commit.change = chg;
commit.patchsetId = ps.getId();
commit.originalOrder = commitOrder++;
commits.put(changeId, commit);
if (branchTip != null) {
// If this commit is already merged its a bug in the queuing code
// that we got back here. Just mark it complete and move on. It's
// merged and that is all that mattered to the requestor.
//
try {
if (rw.isMergedInto(commit, branchTip)) {
commit.statusCode = CommitMergeStatus.ALREADY_MERGED;
try {
setMergedPatchSet(chg.getId(), ps.getId());
} catch (OrmException e) {
log.error("Cannot mark change " + chg.getId() + " merged", e);
}
continue;
}
} catch (IOException err) {
throw new MergeException("Cannot perform merge base test", err);
}
}
final SubmitType submitType = getSubmitType(chg, ps);
if (submitType == null) {
commits.put(changeId,
CodeReviewCommit.error(CommitMergeStatus.NO_SUBMIT_TYPE));
continue;
}
commit.add(canMergeFlag);
toMerge.put(submitType, commit);
toSubmit.put(submitType, chg);
}
return toSubmit;
}
|
diff --git a/src/spia1001/InvFall/InvFallPlayerListener.java b/src/spia1001/InvFall/InvFallPlayerListener.java
index 84a360e..24772a2 100644
--- a/src/spia1001/InvFall/InvFallPlayerListener.java
+++ b/src/spia1001/InvFall/InvFallPlayerListener.java
@@ -1,47 +1,47 @@
package spia1001.InvFall;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
/*
InvFall Plugin
@author Chris Lloyd (SPIA1001)
*/
public class InvFallPlayerListener extends PlayerListener
{
private PlayerManager playerManager;
private InvFall plugin;
public InvFallPlayerListener(PlayerManager pm,InvFall p)
{
playerManager = pm;
plugin = p;
}
public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
if(plugin.permissionWrapper.hasPermission(player,PermissionWrapper.NODE_INVFALL))
if(playerManager.playerIsEnabled(player))
- event.setJoinMessage(ChatColor.GREEN + "InvFall is Enabled");
+ player.sendMessage(ChatColor.GREEN + "InvFall is Enabled");
else
- event.setJoinMessage(ChatColor.RED + "InvFall is Disabled");
+ player.sendMessage(ChatColor.RED + "InvFall is Disabled");
}
public void onPlayerDropItem(PlayerDropItemEvent event)
{
Player player = event.getPlayer();
if(playerManager.playerIsEnabled(player) && plugin.permissionWrapper.hasPermission(player,PermissionWrapper.NODE_BLOCKFALL))
new ItemFall(player,playerManager.freeFallEnabled(player),0);
}
public void onPlayerInteract(PlayerInteractEvent event)
{
Player player = event.getPlayer();
if(playerManager.playerIsEnabled(player) && plugin.permissionWrapper.hasPermission(player,PermissionWrapper.NODE_TOOLFALL))
new ToolFall(player,playerManager);
}
}
| false | true | public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
if(plugin.permissionWrapper.hasPermission(player,PermissionWrapper.NODE_INVFALL))
if(playerManager.playerIsEnabled(player))
event.setJoinMessage(ChatColor.GREEN + "InvFall is Enabled");
else
event.setJoinMessage(ChatColor.RED + "InvFall is Disabled");
}
| public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
if(plugin.permissionWrapper.hasPermission(player,PermissionWrapper.NODE_INVFALL))
if(playerManager.playerIsEnabled(player))
player.sendMessage(ChatColor.GREEN + "InvFall is Enabled");
else
player.sendMessage(ChatColor.RED + "InvFall is Disabled");
}
|
diff --git a/src/main/java/com/github/ucchyocean/ct/listener/PlayerDeathListener.java b/src/main/java/com/github/ucchyocean/ct/listener/PlayerDeathListener.java
index a0e6c92..6e8a320 100644
--- a/src/main/java/com/github/ucchyocean/ct/listener/PlayerDeathListener.java
+++ b/src/main/java/com/github/ucchyocean/ct/listener/PlayerDeathListener.java
@@ -1,274 +1,269 @@
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2013
*/
package com.github.ucchyocean.ct.listener;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.scoreboard.Team;
import org.bukkit.util.Vector;
import com.github.ucchyocean.ct.ColorTeaming;
import com.github.ucchyocean.ct.ColorTeamingAPI;
import com.github.ucchyocean.ct.Utility;
import com.github.ucchyocean.ct.config.ColorTeamingConfig;
import com.github.ucchyocean.ct.config.TeamNameSetting;
import com.github.ucchyocean.ct.event.ColorTeamingLeaderDefeatedEvent;
import com.github.ucchyocean.ct.event.ColorTeamingPlayerLeaveEvent.Reason;
import com.github.ucchyocean.ct.event.ColorTeamingTeamDefeatedEvent;
import com.github.ucchyocean.ct.event.ColorTeamingTrophyKillEvent;
import com.github.ucchyocean.ct.event.ColorTeamingTrophyKillReachEvent;
import com.github.ucchyocean.ct.event.ColorTeamingWonLeaderEvent;
import com.github.ucchyocean.ct.event.ColorTeamingWonTeamEvent;
/**
* プレイヤーが死亡したときに、通知を受け取って処理するクラス
* @author ucchy
*/
public class PlayerDeathListener implements Listener {
private static final String PRENOTICE = ChatColor.LIGHT_PURPLE.toString();
private ColorTeaming plugin;
public PlayerDeathListener(ColorTeaming plugin) {
this.plugin = plugin;
}
/**
* Playerが死亡したときに発生するイベント
* @param event
*/
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
// 倒された人を取得
Player deader = event.getEntity();
ColorTeamingConfig config = plugin.getCTConfig();
ColorTeamingAPI api = plugin.getAPI();
HashMap<String, int[]> killDeathUserCounts = api.getKillDeathUserCounts();
HashMap<String, ArrayList<String>> leaders = api.getLeaders();
TeamNameSetting tnsDeader = api.getPlayerTeamName(deader);
if ( tnsDeader != null ) {
String teamDeader = tnsDeader.getID();
// 倒したプレイヤーを取得
// 直接攻撃で倒された場合は、killerをそのまま使う
// 間接攻撃で倒された場合は、shooterを取得して使う
Player killer = deader.getKiller();
EntityDamageEvent cause = event.getEntity().getLastDamageCause();
if ( cause != null && cause instanceof EntityDamageByEntityEvent ) {
Entity damager = ((EntityDamageByEntityEvent)cause).getDamager();
if ( damager instanceof Projectile ) {
LivingEntity shooter = ((Projectile) damager).getShooter();
if ( shooter instanceof Player ) {
killer = (Player)shooter;
}
}
}
String killerName = null;
if ( killer != null ) {
killerName = killer.getName();
}
// Death数を加算
// チームへ加算
api.addTeamPoint(teamDeader, config.getCTDeathPoint());
// ユーザーへ加算
if ( !killDeathUserCounts.containsKey(deader.getName()) ) {
killDeathUserCounts.put(deader.getName(), new int[3]);
}
killDeathUserCounts.get(deader.getName())[1]++;
// 死亡したプレイヤーが、大将だった場合、倒されたことを全体に通知する。
if ( leaders.containsKey(teamDeader) &&
leaders.get(teamDeader).contains(deader.getName()) ) {
String message = String.format(PRENOTICE + "%s チームの大将、%s が倒されました!",
tnsDeader.getName(), deader.getName());
Bukkit.broadcastMessage(message);
leaders.get(teamDeader).remove(deader.getName());
if ( leaders.get(teamDeader).size() >= 1 ) {
message = String.format(PRENOTICE + "%s チームの残り大将は、あと %d 人です。",
tnsDeader.getName(), leaders.get(teamDeader).size());
Bukkit.broadcastMessage(message);
} else {
message = String.format(PRENOTICE + "%s チームの大将は全滅しました!",
tnsDeader.getName());
Bukkit.broadcastMessage(message);
leaders.remove(teamDeader);
// チームリーダー全滅イベントのコール
ColorTeamingLeaderDefeatedEvent event2 =
new ColorTeamingLeaderDefeatedEvent(tnsDeader, killerName, deader.getName());
Bukkit.getServer().getPluginManager().callEvent(event2);
// リーダーが残っているチームがあと1チームなら、勝利イベントを更にコール
if ( leaders.size() == 1 ) {
TeamNameSetting wonTeam = null;
for ( String t : leaders.keySet() ) {
wonTeam = api.getTeamNameFromID(t);
}
ColorTeamingWonLeaderEvent event3 =
new ColorTeamingWonLeaderEvent(wonTeam, event2);
Bukkit.getServer().getPluginManager().callEvent(event3);
}
}
}
// 倒したプレイヤー側の処理
TeamNameSetting tnsKiller = null;
String teamKiller = null;
if ( killer != null ) {
tnsKiller = api.getPlayerTeamName(killer);
teamKiller = tnsKiller.getID();
}
if ( tnsKiller != null ) {
// Kill数を加算
// チームへ加算
if ( teamDeader.equals(teamKiller) ) // 同じチームだった場合のペナルティ
api.addTeamPoint(teamKiller, config.getCTTKPoint());
else
api.addTeamPoint(teamKiller, config.getCTKillPoint());
// ユーザーへ加算
if ( !killDeathUserCounts.containsKey(killer.getName()) ) {
killDeathUserCounts.put(killer.getName(), new int[3]);
}
if ( teamDeader.equals(teamKiller) ) // 同じチームだった場合のペナルティ
killDeathUserCounts.get(killer.getName())[2]++;
else
killDeathUserCounts.get(killer.getName())[0]++;
// killReachTrophyが設定されていたら、超えたかどうかを判定する
HashMap<String, int[]> killDeathCounts = api.getKillDeathCounts();
if ( config.getKillReachTrophy() > 0 &&
leaders.size() == 0 ) {
if ( killDeathCounts.get(teamKiller)[0] ==
config.getKillReachTrophy() ) {
int rest = config.getKillTrophy() - config.getKillReachTrophy();
String message = String.format(
PRENOTICE + "%s チームが、%d キルまでもう少しです(あと %d キル)。",
tnsKiller.getName(), config.getKillTrophy(), rest);
Bukkit.broadcastMessage(message);
// キル数達成イベントのコール
Team killerTeam = api.getPlayerTeam(killer);
ColorTeamingTrophyKillReachEvent event2 =
new ColorTeamingTrophyKillReachEvent(killerTeam, killer);
Bukkit.getServer().getPluginManager().callEvent(event2);
}
}
// killTrophyが設定されていたら、超えたかどうかを判定する
if ( config.getKillTrophy() > 0 &&
leaders.size() == 0 ) {
if ( killDeathCounts.get(teamKiller)[0] ==
config.getKillTrophy() ) {
// 全体通知
String message = String.format(
PRENOTICE + "%s チームは、%d キルを達成しました!",
tnsKiller.getName(), config.getKillTrophy());
Bukkit.broadcastMessage(message);
// キル数リーチイベントのコール
Team killerTeam = api.getPlayerTeam(killer);
ColorTeamingTrophyKillEvent event2 =
new ColorTeamingTrophyKillEvent(killerTeam, killer);
Bukkit.getServer().getPluginManager().callEvent(event2);
}
}
}
// 色設定を削除する
if ( config.isColorRemoveOnDeath() ) {
api.leavePlayerTeam(deader, Reason.DEAD);
// チームがなくなっていたなら、チーム全滅イベントをコール
ColorTeamingTeamDefeatedEvent event2 =
new ColorTeamingTeamDefeatedEvent(tnsDeader, killerName, deader.getName());
Bukkit.getServer().getPluginManager().callEvent(event2);
// 残っているチームがあと1チームなら、勝利イベントを更にコール
ArrayList<TeamNameSetting> teamNames = api.getAllTeamNames();
if ( teamNames.size() == 1 ) {
TeamNameSetting wonTeam = null;
for ( TeamNameSetting t : teamNames ) {
wonTeam = t;
}
ColorTeamingWonTeamEvent event3 =
new ColorTeamingWonTeamEvent(wonTeam, event2);
Bukkit.getServer().getPluginManager().callEvent(event3);
}
}
// スコア表示を更新する
api.refreshSidebarScore();
api.refreshTabkeyListScore();
api.refreshBelowNameScore();
// ゲームオーバー画面をスキップする
if ( config.isSkipGameover() ) {
// NOTE: 回復するとゲームオーバー画面が表示されない
Utility.heal(deader);
// リスポーンイベントを呼び出す
Location respawnLocation = deader.getBedSpawnLocation();
if ( respawnLocation == null ) {
respawnLocation = deader.getWorld().getSpawnLocation();
// TODO: ワールドの初期設定によっては、リスポーン後に埋まることがある
}
PlayerRespawnEvent respawnEvent =
new PlayerRespawnEvent(deader, respawnLocation, true);
Bukkit.getServer().getPluginManager().callEvent(respawnEvent);
- // リスポーン場所へテレポートする
respawnLocation = respawnEvent.getRespawnLocation();
if ( respawnLocation != null ) {
// 移送する場合は、経験値やインベントリのアイテムを落とさない
event.setDroppedExp(0);
- deader.getInventory().clear();
- deader.getInventory().setHelmet(null);
- deader.getInventory().setChestplate(null);
- deader.getInventory().setLeggings(null);
- deader.getInventory().setBoots(null);
+ event.getDrops().clear();
// リスポーン場所へテレポートする
deader.teleport(respawnLocation, TeleportCause.PLUGIN);
// ノックバックの除去
deader.setVelocity(new Vector());
}
}
}
}
}
| false | true | public void onPlayerDeath(PlayerDeathEvent event) {
// 倒された人を取得
Player deader = event.getEntity();
ColorTeamingConfig config = plugin.getCTConfig();
ColorTeamingAPI api = plugin.getAPI();
HashMap<String, int[]> killDeathUserCounts = api.getKillDeathUserCounts();
HashMap<String, ArrayList<String>> leaders = api.getLeaders();
TeamNameSetting tnsDeader = api.getPlayerTeamName(deader);
if ( tnsDeader != null ) {
String teamDeader = tnsDeader.getID();
// 倒したプレイヤーを取得
// 直接攻撃で倒された場合は、killerをそのまま使う
// 間接攻撃で倒された場合は、shooterを取得して使う
Player killer = deader.getKiller();
EntityDamageEvent cause = event.getEntity().getLastDamageCause();
if ( cause != null && cause instanceof EntityDamageByEntityEvent ) {
Entity damager = ((EntityDamageByEntityEvent)cause).getDamager();
if ( damager instanceof Projectile ) {
LivingEntity shooter = ((Projectile) damager).getShooter();
if ( shooter instanceof Player ) {
killer = (Player)shooter;
}
}
}
String killerName = null;
if ( killer != null ) {
killerName = killer.getName();
}
// Death数を加算
// チームへ加算
api.addTeamPoint(teamDeader, config.getCTDeathPoint());
// ユーザーへ加算
if ( !killDeathUserCounts.containsKey(deader.getName()) ) {
killDeathUserCounts.put(deader.getName(), new int[3]);
}
killDeathUserCounts.get(deader.getName())[1]++;
// 死亡したプレイヤーが、大将だった場合、倒されたことを全体に通知する。
if ( leaders.containsKey(teamDeader) &&
leaders.get(teamDeader).contains(deader.getName()) ) {
String message = String.format(PRENOTICE + "%s チームの大将、%s が倒されました!",
tnsDeader.getName(), deader.getName());
Bukkit.broadcastMessage(message);
leaders.get(teamDeader).remove(deader.getName());
if ( leaders.get(teamDeader).size() >= 1 ) {
message = String.format(PRENOTICE + "%s チームの残り大将は、あと %d 人です。",
tnsDeader.getName(), leaders.get(teamDeader).size());
Bukkit.broadcastMessage(message);
} else {
message = String.format(PRENOTICE + "%s チームの大将は全滅しました!",
tnsDeader.getName());
Bukkit.broadcastMessage(message);
leaders.remove(teamDeader);
// チームリーダー全滅イベントのコール
ColorTeamingLeaderDefeatedEvent event2 =
new ColorTeamingLeaderDefeatedEvent(tnsDeader, killerName, deader.getName());
Bukkit.getServer().getPluginManager().callEvent(event2);
// リーダーが残っているチームがあと1チームなら、勝利イベントを更にコール
if ( leaders.size() == 1 ) {
TeamNameSetting wonTeam = null;
for ( String t : leaders.keySet() ) {
wonTeam = api.getTeamNameFromID(t);
}
ColorTeamingWonLeaderEvent event3 =
new ColorTeamingWonLeaderEvent(wonTeam, event2);
Bukkit.getServer().getPluginManager().callEvent(event3);
}
}
}
// 倒したプレイヤー側の処理
TeamNameSetting tnsKiller = null;
String teamKiller = null;
if ( killer != null ) {
tnsKiller = api.getPlayerTeamName(killer);
teamKiller = tnsKiller.getID();
}
if ( tnsKiller != null ) {
// Kill数を加算
// チームへ加算
if ( teamDeader.equals(teamKiller) ) // 同じチームだった場合のペナルティ
api.addTeamPoint(teamKiller, config.getCTTKPoint());
else
api.addTeamPoint(teamKiller, config.getCTKillPoint());
// ユーザーへ加算
if ( !killDeathUserCounts.containsKey(killer.getName()) ) {
killDeathUserCounts.put(killer.getName(), new int[3]);
}
if ( teamDeader.equals(teamKiller) ) // 同じチームだった場合のペナルティ
killDeathUserCounts.get(killer.getName())[2]++;
else
killDeathUserCounts.get(killer.getName())[0]++;
// killReachTrophyが設定されていたら、超えたかどうかを判定する
HashMap<String, int[]> killDeathCounts = api.getKillDeathCounts();
if ( config.getKillReachTrophy() > 0 &&
leaders.size() == 0 ) {
if ( killDeathCounts.get(teamKiller)[0] ==
config.getKillReachTrophy() ) {
int rest = config.getKillTrophy() - config.getKillReachTrophy();
String message = String.format(
PRENOTICE + "%s チームが、%d キルまでもう少しです(あと %d キル)。",
tnsKiller.getName(), config.getKillTrophy(), rest);
Bukkit.broadcastMessage(message);
// キル数達成イベントのコール
Team killerTeam = api.getPlayerTeam(killer);
ColorTeamingTrophyKillReachEvent event2 =
new ColorTeamingTrophyKillReachEvent(killerTeam, killer);
Bukkit.getServer().getPluginManager().callEvent(event2);
}
}
// killTrophyが設定されていたら、超えたかどうかを判定する
if ( config.getKillTrophy() > 0 &&
leaders.size() == 0 ) {
if ( killDeathCounts.get(teamKiller)[0] ==
config.getKillTrophy() ) {
// 全体通知
String message = String.format(
PRENOTICE + "%s チームは、%d キルを達成しました!",
tnsKiller.getName(), config.getKillTrophy());
Bukkit.broadcastMessage(message);
// キル数リーチイベントのコール
Team killerTeam = api.getPlayerTeam(killer);
ColorTeamingTrophyKillEvent event2 =
new ColorTeamingTrophyKillEvent(killerTeam, killer);
Bukkit.getServer().getPluginManager().callEvent(event2);
}
}
}
// 色設定を削除する
if ( config.isColorRemoveOnDeath() ) {
api.leavePlayerTeam(deader, Reason.DEAD);
// チームがなくなっていたなら、チーム全滅イベントをコール
ColorTeamingTeamDefeatedEvent event2 =
new ColorTeamingTeamDefeatedEvent(tnsDeader, killerName, deader.getName());
Bukkit.getServer().getPluginManager().callEvent(event2);
// 残っているチームがあと1チームなら、勝利イベントを更にコール
ArrayList<TeamNameSetting> teamNames = api.getAllTeamNames();
if ( teamNames.size() == 1 ) {
TeamNameSetting wonTeam = null;
for ( TeamNameSetting t : teamNames ) {
wonTeam = t;
}
ColorTeamingWonTeamEvent event3 =
new ColorTeamingWonTeamEvent(wonTeam, event2);
Bukkit.getServer().getPluginManager().callEvent(event3);
}
}
// スコア表示を更新する
api.refreshSidebarScore();
api.refreshTabkeyListScore();
api.refreshBelowNameScore();
// ゲームオーバー画面をスキップする
if ( config.isSkipGameover() ) {
// NOTE: 回復するとゲームオーバー画面が表示されない
Utility.heal(deader);
// リスポーンイベントを呼び出す
Location respawnLocation = deader.getBedSpawnLocation();
if ( respawnLocation == null ) {
respawnLocation = deader.getWorld().getSpawnLocation();
// TODO: ワールドの初期設定によっては、リスポーン後に埋まることがある
}
PlayerRespawnEvent respawnEvent =
new PlayerRespawnEvent(deader, respawnLocation, true);
Bukkit.getServer().getPluginManager().callEvent(respawnEvent);
// リスポーン場所へテレポートする
respawnLocation = respawnEvent.getRespawnLocation();
if ( respawnLocation != null ) {
// 移送する場合は、経験値やインベントリのアイテムを落とさない
event.setDroppedExp(0);
deader.getInventory().clear();
deader.getInventory().setHelmet(null);
deader.getInventory().setChestplate(null);
deader.getInventory().setLeggings(null);
deader.getInventory().setBoots(null);
// リスポーン場所へテレポートする
deader.teleport(respawnLocation, TeleportCause.PLUGIN);
// ノックバックの除去
deader.setVelocity(new Vector());
}
}
}
}
| public void onPlayerDeath(PlayerDeathEvent event) {
// 倒された人を取得
Player deader = event.getEntity();
ColorTeamingConfig config = plugin.getCTConfig();
ColorTeamingAPI api = plugin.getAPI();
HashMap<String, int[]> killDeathUserCounts = api.getKillDeathUserCounts();
HashMap<String, ArrayList<String>> leaders = api.getLeaders();
TeamNameSetting tnsDeader = api.getPlayerTeamName(deader);
if ( tnsDeader != null ) {
String teamDeader = tnsDeader.getID();
// 倒したプレイヤーを取得
// 直接攻撃で倒された場合は、killerをそのまま使う
// 間接攻撃で倒された場合は、shooterを取得して使う
Player killer = deader.getKiller();
EntityDamageEvent cause = event.getEntity().getLastDamageCause();
if ( cause != null && cause instanceof EntityDamageByEntityEvent ) {
Entity damager = ((EntityDamageByEntityEvent)cause).getDamager();
if ( damager instanceof Projectile ) {
LivingEntity shooter = ((Projectile) damager).getShooter();
if ( shooter instanceof Player ) {
killer = (Player)shooter;
}
}
}
String killerName = null;
if ( killer != null ) {
killerName = killer.getName();
}
// Death数を加算
// チームへ加算
api.addTeamPoint(teamDeader, config.getCTDeathPoint());
// ユーザーへ加算
if ( !killDeathUserCounts.containsKey(deader.getName()) ) {
killDeathUserCounts.put(deader.getName(), new int[3]);
}
killDeathUserCounts.get(deader.getName())[1]++;
// 死亡したプレイヤーが、大将だった場合、倒されたことを全体に通知する。
if ( leaders.containsKey(teamDeader) &&
leaders.get(teamDeader).contains(deader.getName()) ) {
String message = String.format(PRENOTICE + "%s チームの大将、%s が倒されました!",
tnsDeader.getName(), deader.getName());
Bukkit.broadcastMessage(message);
leaders.get(teamDeader).remove(deader.getName());
if ( leaders.get(teamDeader).size() >= 1 ) {
message = String.format(PRENOTICE + "%s チームの残り大将は、あと %d 人です。",
tnsDeader.getName(), leaders.get(teamDeader).size());
Bukkit.broadcastMessage(message);
} else {
message = String.format(PRENOTICE + "%s チームの大将は全滅しました!",
tnsDeader.getName());
Bukkit.broadcastMessage(message);
leaders.remove(teamDeader);
// チームリーダー全滅イベントのコール
ColorTeamingLeaderDefeatedEvent event2 =
new ColorTeamingLeaderDefeatedEvent(tnsDeader, killerName, deader.getName());
Bukkit.getServer().getPluginManager().callEvent(event2);
// リーダーが残っているチームがあと1チームなら、勝利イベントを更にコール
if ( leaders.size() == 1 ) {
TeamNameSetting wonTeam = null;
for ( String t : leaders.keySet() ) {
wonTeam = api.getTeamNameFromID(t);
}
ColorTeamingWonLeaderEvent event3 =
new ColorTeamingWonLeaderEvent(wonTeam, event2);
Bukkit.getServer().getPluginManager().callEvent(event3);
}
}
}
// 倒したプレイヤー側の処理
TeamNameSetting tnsKiller = null;
String teamKiller = null;
if ( killer != null ) {
tnsKiller = api.getPlayerTeamName(killer);
teamKiller = tnsKiller.getID();
}
if ( tnsKiller != null ) {
// Kill数を加算
// チームへ加算
if ( teamDeader.equals(teamKiller) ) // 同じチームだった場合のペナルティ
api.addTeamPoint(teamKiller, config.getCTTKPoint());
else
api.addTeamPoint(teamKiller, config.getCTKillPoint());
// ユーザーへ加算
if ( !killDeathUserCounts.containsKey(killer.getName()) ) {
killDeathUserCounts.put(killer.getName(), new int[3]);
}
if ( teamDeader.equals(teamKiller) ) // 同じチームだった場合のペナルティ
killDeathUserCounts.get(killer.getName())[2]++;
else
killDeathUserCounts.get(killer.getName())[0]++;
// killReachTrophyが設定されていたら、超えたかどうかを判定する
HashMap<String, int[]> killDeathCounts = api.getKillDeathCounts();
if ( config.getKillReachTrophy() > 0 &&
leaders.size() == 0 ) {
if ( killDeathCounts.get(teamKiller)[0] ==
config.getKillReachTrophy() ) {
int rest = config.getKillTrophy() - config.getKillReachTrophy();
String message = String.format(
PRENOTICE + "%s チームが、%d キルまでもう少しです(あと %d キル)。",
tnsKiller.getName(), config.getKillTrophy(), rest);
Bukkit.broadcastMessage(message);
// キル数達成イベントのコール
Team killerTeam = api.getPlayerTeam(killer);
ColorTeamingTrophyKillReachEvent event2 =
new ColorTeamingTrophyKillReachEvent(killerTeam, killer);
Bukkit.getServer().getPluginManager().callEvent(event2);
}
}
// killTrophyが設定されていたら、超えたかどうかを判定する
if ( config.getKillTrophy() > 0 &&
leaders.size() == 0 ) {
if ( killDeathCounts.get(teamKiller)[0] ==
config.getKillTrophy() ) {
// 全体通知
String message = String.format(
PRENOTICE + "%s チームは、%d キルを達成しました!",
tnsKiller.getName(), config.getKillTrophy());
Bukkit.broadcastMessage(message);
// キル数リーチイベントのコール
Team killerTeam = api.getPlayerTeam(killer);
ColorTeamingTrophyKillEvent event2 =
new ColorTeamingTrophyKillEvent(killerTeam, killer);
Bukkit.getServer().getPluginManager().callEvent(event2);
}
}
}
// 色設定を削除する
if ( config.isColorRemoveOnDeath() ) {
api.leavePlayerTeam(deader, Reason.DEAD);
// チームがなくなっていたなら、チーム全滅イベントをコール
ColorTeamingTeamDefeatedEvent event2 =
new ColorTeamingTeamDefeatedEvent(tnsDeader, killerName, deader.getName());
Bukkit.getServer().getPluginManager().callEvent(event2);
// 残っているチームがあと1チームなら、勝利イベントを更にコール
ArrayList<TeamNameSetting> teamNames = api.getAllTeamNames();
if ( teamNames.size() == 1 ) {
TeamNameSetting wonTeam = null;
for ( TeamNameSetting t : teamNames ) {
wonTeam = t;
}
ColorTeamingWonTeamEvent event3 =
new ColorTeamingWonTeamEvent(wonTeam, event2);
Bukkit.getServer().getPluginManager().callEvent(event3);
}
}
// スコア表示を更新する
api.refreshSidebarScore();
api.refreshTabkeyListScore();
api.refreshBelowNameScore();
// ゲームオーバー画面をスキップする
if ( config.isSkipGameover() ) {
// NOTE: 回復するとゲームオーバー画面が表示されない
Utility.heal(deader);
// リスポーンイベントを呼び出す
Location respawnLocation = deader.getBedSpawnLocation();
if ( respawnLocation == null ) {
respawnLocation = deader.getWorld().getSpawnLocation();
// TODO: ワールドの初期設定によっては、リスポーン後に埋まることがある
}
PlayerRespawnEvent respawnEvent =
new PlayerRespawnEvent(deader, respawnLocation, true);
Bukkit.getServer().getPluginManager().callEvent(respawnEvent);
respawnLocation = respawnEvent.getRespawnLocation();
if ( respawnLocation != null ) {
// 移送する場合は、経験値やインベントリのアイテムを落とさない
event.setDroppedExp(0);
event.getDrops().clear();
// リスポーン場所へテレポートする
deader.teleport(respawnLocation, TeleportCause.PLUGIN);
// ノックバックの除去
deader.setVelocity(new Vector());
}
}
}
}
|
diff --git a/Tricorder/src/org/hermit/tricorder/ImageAtom.java b/Tricorder/src/org/hermit/tricorder/ImageAtom.java
index 54ab388..bee0870 100644
--- a/Tricorder/src/org/hermit/tricorder/ImageAtom.java
+++ b/Tricorder/src/org/hermit/tricorder/ImageAtom.java
@@ -1,272 +1,279 @@
/**
* Tricorder: turn your phone into a tricorder.
*
* This is an Android implementation of a Star Trek tricorder, based on
* the phone's own sensors. It's also a demo project for sensor access.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* 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.
*/
package org.hermit.tricorder;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import org.hermit.android.core.SurfaceRunner;
import org.hermit.android.instruments.Gauge;
import org.hermit.android.net.CachedFile;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
/**
* An atom which draws an image from the web.
*/
class ImageAtom
extends Gauge
implements Observer
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Set up this atom.
*
* @param parent Parent surface.
* @param cache File cache which will hold the image files.
* @param urls URLs of the specific images we will want
* to display.
*/
ImageAtom(SurfaceRunner parent, CachedFile cache, URL[] urls) {
super(parent);
fileCache = cache;
imageUrls = urls;
imageCache = new HashMap<URL, Bitmap>();
currentImage = imageUrls[0];
currentBitmap = null;
statusString = parent.getRes(R.string.msgLoading);
loadHandler = new Handler();
cache.addObserver(this);
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
@Override
public void setGeometry(Rect bounds) {
super.setGeometry(bounds);
imageX = bounds.left;
imageY = bounds.top;
imageWidth = bounds.right - bounds.left;
imageHeight = bounds.bottom - bounds.top;
// Clear the image cache and the current bitmap.
imageCache.clear();
currentBitmap = null;
// Add all the URLs to the image cache. Since we may have the
// cache database already, try to get the images.
long delay = 500;
for (URL url : imageUrls) {
imageCache.put(url, null);
loadHandler.postDelayed(new Loader(url), delay);
delay += 200;
}
}
private final class Loader implements Runnable {
Loader(URL url) {
imgUrl = url;
}
@Override
public void run() {
synchronized (imageCache) {
CachedFile.Entry entry = fileCache.getFile(imgUrl);
if (entry.path != null)
imageLoaded(imgUrl, entry.path);
}
}
private final URL imgUrl;
}
// ******************************************************************** //
// Image Loading.
// ******************************************************************** //
/**
* This method is invoked when a file is loaded by the file cache.
*
* @param o The cached file that was loaded.
* @param arg The URL of the file that was loaded.
*/
public void update(Observable o, Object arg) {
if (!(o instanceof CachedFile) || !(arg instanceof URL))
return;
CachedFile cache = (CachedFile) o;
URL url = (URL) arg;
CachedFile.Entry entry = cache.getFile(url);
synchronized (imageCache) {
// Make sure it's an image we're interested in.
if (!imageCache.containsKey(url))
return;
// Get the info on the cached file. Note that the file
// may have been invalidated since the notification was sent.
if (entry.path != null)
imageLoaded(url, entry.path);
}
}
/**
* This method is invoked when a file is loaded by the file cache.
*
* @param url The URL of the file that was loaded.
* @param path The path of the local copy of the file.
*/
private void imageLoaded(URL url, File path) {
// If we don't have a size yet, forget it.
if (imageWidth == 0 || imageHeight == 0)
return;
// Load the bitmap. If if fails, tell the cache we have a
// corrupted file.
- Bitmap img = BitmapFactory.decodeFile(path.getPath());
- if (img == null) {
- // Maybe we shouldn't be so hasty...
-// Log.i(TAG, "ImageAtom: invalidate " + path.getPath());
-// fileCache.invalidate(url);
- return;
+ Bitmap img = null;
+ try {
+ img = BitmapFactory.decodeFile(path.getPath());
+ if (img == null) {
+ // Can't load it? Corrupted? Invalidate the cache.
+ // But maybe we shouldn't be so hasty...
+// Log.i(TAG, "ImageAtom: invalidate " + path.getPath());
+// fileCache.invalidate(url);
+ return;
+ }
+ } catch (OutOfMemoryError e) {
+ // Can't load it right now.
+ return;
}
// Scale the bitmap to size and cache the scaled version.
img = Bitmap.createScaledBitmap(img, imageWidth, imageHeight, true);
imageCache.put(url, img);
// Set as the current image, if it is.
if (currentImage.equals(url))
currentBitmap = img;
}
// ******************************************************************** //
// View Control.
// ******************************************************************** //
/**
* Select which image is displayed in the view.
*
* @param index Index of the image to display.
*/
public void setDisplayedImage(int index) {
synchronized (imageCache) {
currentImage = imageUrls[index];
currentBitmap = imageCache.get(currentImage);
}
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* This method is called to ask the element to draw itself.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
@Override
protected void drawBody(Canvas canvas, Paint paint, long now) {
// Drawing is easy, if the image is loaded.
if (currentBitmap != null)
canvas.drawBitmap(currentBitmap, imageX, imageY, null);
else {
paint.setColor(0xffffffff);
canvas.drawText(statusString, imageX + 4, imageY + 14, paint);
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "tricorder";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The list of URLs we're to display.
private URL[] imageUrls = null;
// Current image position and size.
private int imageX = 0;
private int imageY = 0;
private int imageWidth = 0;
private int imageHeight = 0;
// File cache our images are saved in. These are the raw images off
// the web, in whatever their original size is.
private CachedFile fileCache = null;
// Cache of displayed images. These are scaled to our current size.
private HashMap<URL, Bitmap> imageCache = null;
// Handler used to schedule loading and scaling of images, so it doesn't
// freeze the main thread.
private Handler loadHandler = null;
// The currently displayed image's URL, and its Bitmap. Bitmap
// is null if not loaded yet.
private URL currentImage = null;
private Bitmap currentBitmap = null;
// Status string displayed in place of the image.
private String statusString = null;
}
| true | true | private void imageLoaded(URL url, File path) {
// If we don't have a size yet, forget it.
if (imageWidth == 0 || imageHeight == 0)
return;
// Load the bitmap. If if fails, tell the cache we have a
// corrupted file.
Bitmap img = BitmapFactory.decodeFile(path.getPath());
if (img == null) {
// Maybe we shouldn't be so hasty...
// Log.i(TAG, "ImageAtom: invalidate " + path.getPath());
// fileCache.invalidate(url);
return;
}
// Scale the bitmap to size and cache the scaled version.
img = Bitmap.createScaledBitmap(img, imageWidth, imageHeight, true);
imageCache.put(url, img);
// Set as the current image, if it is.
if (currentImage.equals(url))
currentBitmap = img;
}
| private void imageLoaded(URL url, File path) {
// If we don't have a size yet, forget it.
if (imageWidth == 0 || imageHeight == 0)
return;
// Load the bitmap. If if fails, tell the cache we have a
// corrupted file.
Bitmap img = null;
try {
img = BitmapFactory.decodeFile(path.getPath());
if (img == null) {
// Can't load it? Corrupted? Invalidate the cache.
// But maybe we shouldn't be so hasty...
// Log.i(TAG, "ImageAtom: invalidate " + path.getPath());
// fileCache.invalidate(url);
return;
}
} catch (OutOfMemoryError e) {
// Can't load it right now.
return;
}
// Scale the bitmap to size and cache the scaled version.
img = Bitmap.createScaledBitmap(img, imageWidth, imageHeight, true);
imageCache.put(url, img);
// Set as the current image, if it is.
if (currentImage.equals(url))
currentBitmap = img;
}
|
diff --git a/src/org/openjump/core/attributeoperations/AttributeOp.java b/src/org/openjump/core/attributeoperations/AttributeOp.java
index c9656bed..0bd263d2 100644
--- a/src/org/openjump/core/attributeoperations/AttributeOp.java
+++ b/src/org/openjump/core/attributeoperations/AttributeOp.java
@@ -1,341 +1,338 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* JUMP is Copyright (C) 2003 Vivid Solutions
*
* This program implements extensions to JUMP and is
* Copyright (C) Stefan Steiniger.
*
* 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.
*
* For more information, contact:
* Stefan Steiniger
* [email protected]
*/
/***********************************************
* created on 22.06.2006
* last modified:
*
* author: sstein
*
* description:
* provides some function to calculate mathematical
* indices like mean, max, median for a set of features.
*
***********************************************/
package org.openjump.core.attributeoperations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.math.array.DoubleArray;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jump.feature.AttributeType;
import com.vividsolutions.jump.feature.Feature;
import com.vividsolutions.jump.feature.FeatureSchema;
/**
*
* description:
* provides some function to calculate mathematical
* indices like mean, max, median for a set of features.
*
* @author sstein
*
*/
public class AttributeOp {
public final static int MAJORITY = 0;
public final static int MINORITY = 1;
public final static int MEAN = 2;
public final static int MEDIAN = 3;
public final static int MIN = 4;
public final static int MAX = 5;
public final static int STD = 6;
public final static int SUM = 7;
public final static int COUNT = 8;
public static String getName(int attributeOP){
String retval = "";
if(attributeOP == 0){
retval ="major";
}
else if(attributeOP == 1){
retval ="minor";
}
else if(attributeOP == 2){
retval ="mean";
}
else if(attributeOP == 3){
retval ="median";
}
else if(attributeOP == 4){
retval ="min";
}
else if(attributeOP == 5){
retval ="max";
}
else if(attributeOP == 6){
retval ="std";
}
else if(attributeOP == 7){
retval ="sum";
}
else if(attributeOP == 8){
retval ="count";
}
return retval;
}
public static double evaluateAttributes(int attributeOp, Feature[] features, String attributeName){
ArrayList<Feature> featureL = new ArrayList<Feature>();
for (int i = 0; i < features.length; i++) {
featureL.add(features[i]);
}
return AttributeOp.evaluateAttributes(attributeOp, featureL, attributeName);
}
public static double evaluateAttributes(int attributeOp, List features, String attributeName){
double result= Double.NaN;
if (features.size() > 0){
Feature firstF = (Feature)features.get(0);
FeatureSchema fs = firstF.getSchema();
if (fs.hasAttribute(attributeName)){
boolean doEval = true;
AttributeType at = fs.getAttributeType(attributeName);
int n = features.size();
double[] vals = org.math.array.StatisticSample.fill(n,0);
//Matrix mat = MatlabSyntax.zeros(n,1);
int count=0;
for (Iterator iter = features.iterator(); iter.hasNext();) {
Feature f = (Feature) iter.next();
- if (at == AttributeType.DOUBLE){
- Double val = (Double)f.getAttribute(attributeName);
+ Object value = f.getAttribute(attributeName);
+ if (value == null) {
+ // will be counted as 0
+ }
+ else if (at == AttributeType.DOUBLE){
+ Double val = (Double)value;
//mat.set(count,0, val.doubleValue());
vals[count] = val.doubleValue();
}
else if(at == AttributeType.INTEGER){
- Integer val = (Integer)f.getAttribute(attributeName);
+ Integer val = (Integer)value;
//mat.set(count,0, val.doubleValue());
vals[count] = val.doubleValue();
}
else if(at == AttributeType.GEOMETRY){
//-- simply set to one for count
- Geometry geom = (Geometry)f.getAttribute(attributeName);
- if (geom != null){
- //mat.set(count,0, 1);
- vals[count] = 1;
- }
- else{
- //mat.set(count,0, 0);
- vals[count] = 0;
- }
+ //mat.set(count,0, 1);
+ vals[count] = 1;
}
else{
System.out.println("AttributeOp: attribute type not supported");
doEval = false;
}
count++;
}
if(doEval){
if (attributeOp == AttributeOp.MAJORITY){
result = majorityEval(vals);
}
else if(attributeOp == AttributeOp.MINORITY){
result = minorityEval(vals);
}
else if(attributeOp == AttributeOp.MAX){
result = org.math.array.DoubleArray.max(vals);
}
else if(attributeOp == AttributeOp.MIN){
result = org.math.array.DoubleArray.min(vals);
}
else if(attributeOp == AttributeOp.MEAN){
result = org.math.array.StatisticSample.mean(vals);
}
else if(attributeOp == AttributeOp.STD){
result = org.math.array.StatisticSample.stddeviation(vals);
}
else if(attributeOp == AttributeOp.MEDIAN){
double[] sortvals = DoubleArray.sort(vals);
int index = (int)Math.ceil(vals.length/2.0);
result = sortvals[index-1];
}
else if(attributeOp == AttributeOp.SUM){
result = DoubleArray.sum(vals);
}
else if(attributeOp == AttributeOp.COUNT){
result = (double)vals.length;
}
else{
System.out.println("AttributeOp: attribute operation not supported");
}
}
}
else{
System.out.println("AttributeOp: attribute does not exist");
}
}
else{
if(attributeOp == AttributeOp.COUNT){
result = 0;
}
}
return result;
}
private static double majorityEval(double[] values){
double result=0;
//-- built list of all values
ArrayList vals = new ArrayList();
for(int i=0; i < values.length; i++){
double val = values[i];
if(i==0){
//-- add first value
vals.add(new Double(val));
}
else{
boolean stop = false; int count =0;
boolean found = false;
while(stop == false){
Double d = (Double)vals.get(count);
if(val == d.doubleValue()){
stop = true;
found = true;
}
count++;
if(count == vals.size()){
//-- if last value reached stop and add
stop = true;
}
}
if(found == false){
vals.add(new Double(val));
}
}
}
//-- count number of values
int[] countVals = new int[vals.size()];
//-- set to zero
for (int i = 0; i < countVals.length; i++) {
countVals[i]=0;
}
for(int i=0; i < values.length; i++){
double val = values[i];
boolean stop = false; int count =0;
while(stop == false){
Double d = (Double)vals.get(count);
if(val == d.doubleValue()){
//-- count
int oldVal = countVals[count];
countVals[count] = oldVal +1;
//-- stop
stop = true;
}
count++;
if(count == countVals.length){
stop = true;
}
}
}
// if (mat.getRowDimension() > 15){
// String s= "Stop here for debugging";
// }
//-- get maximum
int maxcount = 0;
int pos = 0;
for (int i = 0; i < countVals.length; i++) {
if (countVals[i] > maxcount){
maxcount = countVals[i];
pos = i;
}
}
//-- assign value which appears most
result = ((Double)vals.get(pos)).doubleValue();
return result;
}
private static double minorityEval(double[] values){
double result=0;
//-- built list of all values
ArrayList vals = new ArrayList();
for(int i=0; i < values.length; i++){
double val = values[i];
if(i==0){
//-- add first value
vals.add(new Double(val));
}
else{
boolean stop = false; int count =0;
boolean found = false;
while(stop == false){
Double d = (Double)vals.get(count);
if(val == d.doubleValue()){
stop = true;
found = true;
}
count++;
if(count == vals.size()){
//-- if last value reached stop and add
stop = true;
}
}
if(found == false){
vals.add(new Double(val));
}
}
}
//-- count number of values
int[] countVals = new int[vals.size()];
//-- set to zero
for (int i = 0; i < countVals.length; i++) {
countVals[i]=0;
}
for(int i=0; i < values.length; i++){
double val = values[i];
boolean stop = false; int count =0;
while(stop == false){
Double d = (Double)vals.get(count);
if(val == d.doubleValue()){
//-- count
int oldVal = countVals[count];
countVals[count] = oldVal +1;
//-- stop
stop = true;
}
count++;
if(count == countVals.length){
stop = true;
}
}
}
//-- get minimum count
int mincount = countVals[0];
int pos = 0;
for (int i = 1; i < countVals.length; i++) {
if (countVals[i] < mincount){
mincount = countVals[i];
pos = i;
}
}
//-- assign value which appears fewest
result = ((Double)vals.get(pos)).doubleValue();
return result;
}
}
| false | true | public static double evaluateAttributes(int attributeOp, List features, String attributeName){
double result= Double.NaN;
if (features.size() > 0){
Feature firstF = (Feature)features.get(0);
FeatureSchema fs = firstF.getSchema();
if (fs.hasAttribute(attributeName)){
boolean doEval = true;
AttributeType at = fs.getAttributeType(attributeName);
int n = features.size();
double[] vals = org.math.array.StatisticSample.fill(n,0);
//Matrix mat = MatlabSyntax.zeros(n,1);
int count=0;
for (Iterator iter = features.iterator(); iter.hasNext();) {
Feature f = (Feature) iter.next();
if (at == AttributeType.DOUBLE){
Double val = (Double)f.getAttribute(attributeName);
//mat.set(count,0, val.doubleValue());
vals[count] = val.doubleValue();
}
else if(at == AttributeType.INTEGER){
Integer val = (Integer)f.getAttribute(attributeName);
//mat.set(count,0, val.doubleValue());
vals[count] = val.doubleValue();
}
else if(at == AttributeType.GEOMETRY){
//-- simply set to one for count
Geometry geom = (Geometry)f.getAttribute(attributeName);
if (geom != null){
//mat.set(count,0, 1);
vals[count] = 1;
}
else{
//mat.set(count,0, 0);
vals[count] = 0;
}
}
else{
System.out.println("AttributeOp: attribute type not supported");
doEval = false;
}
count++;
}
if(doEval){
if (attributeOp == AttributeOp.MAJORITY){
result = majorityEval(vals);
}
else if(attributeOp == AttributeOp.MINORITY){
result = minorityEval(vals);
}
else if(attributeOp == AttributeOp.MAX){
result = org.math.array.DoubleArray.max(vals);
}
else if(attributeOp == AttributeOp.MIN){
result = org.math.array.DoubleArray.min(vals);
}
else if(attributeOp == AttributeOp.MEAN){
result = org.math.array.StatisticSample.mean(vals);
}
else if(attributeOp == AttributeOp.STD){
result = org.math.array.StatisticSample.stddeviation(vals);
}
else if(attributeOp == AttributeOp.MEDIAN){
double[] sortvals = DoubleArray.sort(vals);
int index = (int)Math.ceil(vals.length/2.0);
result = sortvals[index-1];
}
else if(attributeOp == AttributeOp.SUM){
result = DoubleArray.sum(vals);
}
else if(attributeOp == AttributeOp.COUNT){
result = (double)vals.length;
}
else{
System.out.println("AttributeOp: attribute operation not supported");
}
}
}
else{
System.out.println("AttributeOp: attribute does not exist");
}
}
else{
if(attributeOp == AttributeOp.COUNT){
result = 0;
}
}
return result;
}
| public static double evaluateAttributes(int attributeOp, List features, String attributeName){
double result= Double.NaN;
if (features.size() > 0){
Feature firstF = (Feature)features.get(0);
FeatureSchema fs = firstF.getSchema();
if (fs.hasAttribute(attributeName)){
boolean doEval = true;
AttributeType at = fs.getAttributeType(attributeName);
int n = features.size();
double[] vals = org.math.array.StatisticSample.fill(n,0);
//Matrix mat = MatlabSyntax.zeros(n,1);
int count=0;
for (Iterator iter = features.iterator(); iter.hasNext();) {
Feature f = (Feature) iter.next();
Object value = f.getAttribute(attributeName);
if (value == null) {
// will be counted as 0
}
else if (at == AttributeType.DOUBLE){
Double val = (Double)value;
//mat.set(count,0, val.doubleValue());
vals[count] = val.doubleValue();
}
else if(at == AttributeType.INTEGER){
Integer val = (Integer)value;
//mat.set(count,0, val.doubleValue());
vals[count] = val.doubleValue();
}
else if(at == AttributeType.GEOMETRY){
//-- simply set to one for count
//mat.set(count,0, 1);
vals[count] = 1;
}
else{
System.out.println("AttributeOp: attribute type not supported");
doEval = false;
}
count++;
}
if(doEval){
if (attributeOp == AttributeOp.MAJORITY){
result = majorityEval(vals);
}
else if(attributeOp == AttributeOp.MINORITY){
result = minorityEval(vals);
}
else if(attributeOp == AttributeOp.MAX){
result = org.math.array.DoubleArray.max(vals);
}
else if(attributeOp == AttributeOp.MIN){
result = org.math.array.DoubleArray.min(vals);
}
else if(attributeOp == AttributeOp.MEAN){
result = org.math.array.StatisticSample.mean(vals);
}
else if(attributeOp == AttributeOp.STD){
result = org.math.array.StatisticSample.stddeviation(vals);
}
else if(attributeOp == AttributeOp.MEDIAN){
double[] sortvals = DoubleArray.sort(vals);
int index = (int)Math.ceil(vals.length/2.0);
result = sortvals[index-1];
}
else if(attributeOp == AttributeOp.SUM){
result = DoubleArray.sum(vals);
}
else if(attributeOp == AttributeOp.COUNT){
result = (double)vals.length;
}
else{
System.out.println("AttributeOp: attribute operation not supported");
}
}
}
else{
System.out.println("AttributeOp: attribute does not exist");
}
}
else{
if(attributeOp == AttributeOp.COUNT){
result = 0;
}
}
return result;
}
|
diff --git a/src/main/java/com/mojang/minecraft/SkinDownloadThread.java b/src/main/java/com/mojang/minecraft/SkinDownloadThread.java
index c741c73..a728ad9 100644
--- a/src/main/java/com/mojang/minecraft/SkinDownloadThread.java
+++ b/src/main/java/com/mojang/minecraft/SkinDownloadThread.java
@@ -1,52 +1,52 @@
package com.mojang.minecraft;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
import com.mojang.minecraft.player.Player;
public class SkinDownloadThread extends Thread {
String skinServer;
private Minecraft minecraft;
public SkinDownloadThread(Minecraft minecraft, String skinServer) {
super();
this.skinServer = skinServer;
this.minecraft = minecraft;
}
@Override
public void run() {
if (minecraft.session != null) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(skinServer + minecraft.session.username
+ ".png").openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/4.76");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() != 404) {
- Player.newTexture = ImageIO.read(connection.getInputStream());
+ Player.newTexture = ImageIO.read(connection.getInputStream()).getSubimage(0, 0, 64, 32);
return;
}
} catch (Exception var4) {
var4.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
}
| true | true | public void run() {
if (minecraft.session != null) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(skinServer + minecraft.session.username
+ ".png").openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/4.76");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() != 404) {
Player.newTexture = ImageIO.read(connection.getInputStream());
return;
}
} catch (Exception var4) {
var4.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
| public void run() {
if (minecraft.session != null) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(skinServer + minecraft.session.username
+ ".png").openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/4.76");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() != 404) {
Player.newTexture = ImageIO.read(connection.getInputStream()).getSubimage(0, 0, 64, 32);
return;
}
} catch (Exception var4) {
var4.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
|
diff --git a/src/main/java/uk/co/brotherlogic/mdb/vgadd/VGAdd.java b/src/main/java/uk/co/brotherlogic/mdb/vgadd/VGAdd.java
index 477d60c..f6dc164 100644
--- a/src/main/java/uk/co/brotherlogic/mdb/vgadd/VGAdd.java
+++ b/src/main/java/uk/co/brotherlogic/mdb/vgadd/VGAdd.java
@@ -1,91 +1,94 @@
package uk.co.brotherlogic.mdb.vgadd;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Calendar;
import uk.co.brotherlogic.mdb.Connect;
import uk.co.brotherlogic.mdb.categories.GetCategories;
import uk.co.brotherlogic.mdb.format.GetFormats;
import uk.co.brotherlogic.mdb.label.GetLabels;
import uk.co.brotherlogic.mdb.record.GetRecords;
import uk.co.brotherlogic.mdb.record.Record;
import uk.co.brotherlogic.mdb.record.Track;
public class VGAdd
{
public void run(File f) throws IOException, SQLException
{
// For testing
- Connect.setForDevMode();
+ // Connect.setForDevMode();
// Read the generic information
BufferedReader reader = new BufferedReader(new FileReader(f));
String header = reader.readLine();
String[] elems = header.trim().split("~");
String title = elems[0];
int year = Integer.parseInt(elems[1]);
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
+ if (line.trim().length() > 0)
+ {
String[] lineElems = line.trim().split("~");
String person = lineElems[0];
int tracks = Integer.parseInt(lineElems[1]);
if (GetRecords.create().getRecords(title + ": " + person).size() == 0)
{
// Build up the record
Record r = new Record();
r.setTitle(title + ": " + person);
r.setLabel(GetLabels.create().getLabel("VinylVulture"));
r.setReleaseType(2);
r.setFormat(GetFormats.create().getFormat("CD"));
r.setCatNo("VG+ XMAS " + year);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 25);
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.YEAR, year);
r.setDate(cal.getTime());
r.setYear(year);
r.setReleaseMonth(12);
r.setCategory(GetCategories.build().getCategory("VinylVulture"));
for (int i = 1; i <= tracks; i++)
{
System.err.println(i + " => " + tracks);
Track t = new Track();
t.setFormTrackNumber(i);
t.setTrackNumber(i);
t.setTitle("");
r.addTrack(t);
}
r.setOwner(1);
r.setAuthor("Various");
System.out.println("Adding: " + person);
r.save();
}
else
System.out.println("Skipping: " + person);
Connect.getConnection().commitTrans();
System.out.println(GetRecords.create().getRecords(title + ": " + person).get(0)
.getFormTrackArtist(1));
System.out.println(GetRecords.create().getRecords(title + ": " + person).get(0)
.getFormTrackTitle(1));
}
+ }
// Commit all the additions
}
}
| false | true | public void run(File f) throws IOException, SQLException
{
// For testing
Connect.setForDevMode();
// Read the generic information
BufferedReader reader = new BufferedReader(new FileReader(f));
String header = reader.readLine();
String[] elems = header.trim().split("~");
String title = elems[0];
int year = Integer.parseInt(elems[1]);
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
String[] lineElems = line.trim().split("~");
String person = lineElems[0];
int tracks = Integer.parseInt(lineElems[1]);
if (GetRecords.create().getRecords(title + ": " + person).size() == 0)
{
// Build up the record
Record r = new Record();
r.setTitle(title + ": " + person);
r.setLabel(GetLabels.create().getLabel("VinylVulture"));
r.setReleaseType(2);
r.setFormat(GetFormats.create().getFormat("CD"));
r.setCatNo("VG+ XMAS " + year);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 25);
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.YEAR, year);
r.setDate(cal.getTime());
r.setYear(year);
r.setReleaseMonth(12);
r.setCategory(GetCategories.build().getCategory("VinylVulture"));
for (int i = 1; i <= tracks; i++)
{
System.err.println(i + " => " + tracks);
Track t = new Track();
t.setFormTrackNumber(i);
t.setTrackNumber(i);
t.setTitle("");
r.addTrack(t);
}
r.setOwner(1);
r.setAuthor("Various");
System.out.println("Adding: " + person);
r.save();
}
else
System.out.println("Skipping: " + person);
Connect.getConnection().commitTrans();
System.out.println(GetRecords.create().getRecords(title + ": " + person).get(0)
.getFormTrackArtist(1));
System.out.println(GetRecords.create().getRecords(title + ": " + person).get(0)
.getFormTrackTitle(1));
}
// Commit all the additions
}
| public void run(File f) throws IOException, SQLException
{
// For testing
// Connect.setForDevMode();
// Read the generic information
BufferedReader reader = new BufferedReader(new FileReader(f));
String header = reader.readLine();
String[] elems = header.trim().split("~");
String title = elems[0];
int year = Integer.parseInt(elems[1]);
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
if (line.trim().length() > 0)
{
String[] lineElems = line.trim().split("~");
String person = lineElems[0];
int tracks = Integer.parseInt(lineElems[1]);
if (GetRecords.create().getRecords(title + ": " + person).size() == 0)
{
// Build up the record
Record r = new Record();
r.setTitle(title + ": " + person);
r.setLabel(GetLabels.create().getLabel("VinylVulture"));
r.setReleaseType(2);
r.setFormat(GetFormats.create().getFormat("CD"));
r.setCatNo("VG+ XMAS " + year);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 25);
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.YEAR, year);
r.setDate(cal.getTime());
r.setYear(year);
r.setReleaseMonth(12);
r.setCategory(GetCategories.build().getCategory("VinylVulture"));
for (int i = 1; i <= tracks; i++)
{
System.err.println(i + " => " + tracks);
Track t = new Track();
t.setFormTrackNumber(i);
t.setTrackNumber(i);
t.setTitle("");
r.addTrack(t);
}
r.setOwner(1);
r.setAuthor("Various");
System.out.println("Adding: " + person);
r.save();
}
else
System.out.println("Skipping: " + person);
Connect.getConnection().commitTrans();
System.out.println(GetRecords.create().getRecords(title + ": " + person).get(0)
.getFormTrackArtist(1));
System.out.println(GetRecords.create().getRecords(title + ": " + person).get(0)
.getFormTrackTitle(1));
}
}
// Commit all the additions
}
|
diff --git a/bundles/org.eclipse.core.runtime/src/org/eclipse/core/internal/content/XMLContentDescriber.java b/bundles/org.eclipse.core.runtime/src/org/eclipse/core/internal/content/XMLContentDescriber.java
index 64b708a51..3717afa53 100644
--- a/bundles/org.eclipse.core.runtime/src/org/eclipse/core/internal/content/XMLContentDescriber.java
+++ b/bundles/org.eclipse.core.runtime/src/org/eclipse/core/internal/content/XMLContentDescriber.java
@@ -1,117 +1,121 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.content;
import java.io.*;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.ITextContentDescriber;
/**
* A content interpreter for XML files.
* This class provides internal basis for XML-based content describers.
* <p>
* Note: do not add protected/public members to this class if you don't intend to
* make them public API.
* </p>
*
* @see org.eclipse.core.runtime.content.XMLRootElementContentDescriber
* @see "http://www.w3.org/TR/REC-xml *"
*/
public class XMLContentDescriber extends TextContentDescriber implements ITextContentDescriber {
private static final QualifiedName[] SUPPORTED_OPTIONS = new QualifiedName[] {IContentDescription.CHARSET, IContentDescription.BYTE_ORDER_MARK};
private static final String ENCODING = "encoding="; //$NON-NLS-1$
private static final String XML_PREFIX = "<?xml "; //$NON-NLS-1$
public int describe(InputStream input, IContentDescription description) throws IOException {
byte[] bom = getByteOrderMark(input);
String xmlDeclEncoding = "UTF-8"; //$NON-NLS-1$
input.reset();
if (bom != null) {
if (bom == IContentDescription.BOM_UTF_16BE)
xmlDeclEncoding = "UTF-16BE"; //$NON-NLS-1$
else if (bom == IContentDescription.BOM_UTF_16LE)
xmlDeclEncoding = "UTF-16LE"; //$NON-NLS-1$
// skip BOM to make comparison simpler
input.skip(bom.length);
// set the BOM in the description if requested
if (description != null && description.isRequested(IContentDescription.BYTE_ORDER_MARK))
description.setProperty(IContentDescription.BYTE_ORDER_MARK, bom);
}
byte[] xmlPrefixBytes = XML_PREFIX.getBytes(xmlDeclEncoding);
byte[] prefix = new byte[xmlPrefixBytes.length];
if (input.read(prefix) < prefix.length)
// there is not enough info to say anything
return INDETERMINATE;
for (int i = 0; i < prefix.length; i++)
if (prefix[i] != xmlPrefixBytes[i])
// we don't have a XMLDecl... there is not enough info to say anything
return INDETERMINATE;
if (description == null)
return VALID;
// describe charset if requested
if (description.isRequested(IContentDescription.CHARSET)) {
String fullXMLDecl = readFullXMLDecl(input, xmlDeclEncoding);
- if (fullXMLDecl != null)
- description.setProperty(IContentDescription.CHARSET, getCharset(fullXMLDecl));
+ if (fullXMLDecl != null) {
+ String charset = getCharset(fullXMLDecl);
+ if (charset != null && !"UTF-8".equalsIgnoreCase(charset)) //$NON-NLS-1$
+ // only set property if value is not default (avoid using a non-default content description)
+ description.setProperty(IContentDescription.CHARSET, getCharset(fullXMLDecl));
+ }
}
return VALID;
}
private String readFullXMLDecl(InputStream input, String unicodeEncoding) throws IOException {
byte[] xmlDecl = new byte[100];
int c = 0;
// looks for XMLDecl ending char (?)
int read = 0;
while (read < xmlDecl.length && (c = input.read()) != -1 && c != '?')
xmlDecl[read++] = (byte) c;
return c == '?' ? new String(xmlDecl, 0, read, unicodeEncoding) : null;
}
public int describe(Reader input, IContentDescription description) throws IOException {
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
// end of stream
if (line == null)
return INDETERMINATE;
// XMLDecl should be the first string (no blanks allowed)
if (!line.startsWith(XML_PREFIX))
return INDETERMINATE;
if (description == null)
return VALID;
// describe charset if requested
if ((description.isRequested(IContentDescription.CHARSET)))
description.setProperty(IContentDescription.CHARSET, getCharset(line));
return VALID;
}
private String getCharset(String firstLine) {
int encodingPos = firstLine.indexOf(ENCODING);
if (encodingPos == -1)
return null;
char quoteChar = '"';
int firstQuote = firstLine.indexOf(quoteChar, encodingPos);
if (firstQuote == -1) {
quoteChar = '\'';
firstQuote = firstLine.indexOf(quoteChar, encodingPos);
}
if (firstQuote == -1 || firstLine.length() == firstQuote - 1)
return null;
int secondQuote = firstLine.indexOf(quoteChar, firstQuote + 1);
if (secondQuote == -1)
return null;
return firstLine.substring(firstQuote + 1, secondQuote);
}
public QualifiedName[] getSupportedOptions() {
return SUPPORTED_OPTIONS;
}
}
| true | true | public int describe(InputStream input, IContentDescription description) throws IOException {
byte[] bom = getByteOrderMark(input);
String xmlDeclEncoding = "UTF-8"; //$NON-NLS-1$
input.reset();
if (bom != null) {
if (bom == IContentDescription.BOM_UTF_16BE)
xmlDeclEncoding = "UTF-16BE"; //$NON-NLS-1$
else if (bom == IContentDescription.BOM_UTF_16LE)
xmlDeclEncoding = "UTF-16LE"; //$NON-NLS-1$
// skip BOM to make comparison simpler
input.skip(bom.length);
// set the BOM in the description if requested
if (description != null && description.isRequested(IContentDescription.BYTE_ORDER_MARK))
description.setProperty(IContentDescription.BYTE_ORDER_MARK, bom);
}
byte[] xmlPrefixBytes = XML_PREFIX.getBytes(xmlDeclEncoding);
byte[] prefix = new byte[xmlPrefixBytes.length];
if (input.read(prefix) < prefix.length)
// there is not enough info to say anything
return INDETERMINATE;
for (int i = 0; i < prefix.length; i++)
if (prefix[i] != xmlPrefixBytes[i])
// we don't have a XMLDecl... there is not enough info to say anything
return INDETERMINATE;
if (description == null)
return VALID;
// describe charset if requested
if (description.isRequested(IContentDescription.CHARSET)) {
String fullXMLDecl = readFullXMLDecl(input, xmlDeclEncoding);
if (fullXMLDecl != null)
description.setProperty(IContentDescription.CHARSET, getCharset(fullXMLDecl));
}
return VALID;
}
| public int describe(InputStream input, IContentDescription description) throws IOException {
byte[] bom = getByteOrderMark(input);
String xmlDeclEncoding = "UTF-8"; //$NON-NLS-1$
input.reset();
if (bom != null) {
if (bom == IContentDescription.BOM_UTF_16BE)
xmlDeclEncoding = "UTF-16BE"; //$NON-NLS-1$
else if (bom == IContentDescription.BOM_UTF_16LE)
xmlDeclEncoding = "UTF-16LE"; //$NON-NLS-1$
// skip BOM to make comparison simpler
input.skip(bom.length);
// set the BOM in the description if requested
if (description != null && description.isRequested(IContentDescription.BYTE_ORDER_MARK))
description.setProperty(IContentDescription.BYTE_ORDER_MARK, bom);
}
byte[] xmlPrefixBytes = XML_PREFIX.getBytes(xmlDeclEncoding);
byte[] prefix = new byte[xmlPrefixBytes.length];
if (input.read(prefix) < prefix.length)
// there is not enough info to say anything
return INDETERMINATE;
for (int i = 0; i < prefix.length; i++)
if (prefix[i] != xmlPrefixBytes[i])
// we don't have a XMLDecl... there is not enough info to say anything
return INDETERMINATE;
if (description == null)
return VALID;
// describe charset if requested
if (description.isRequested(IContentDescription.CHARSET)) {
String fullXMLDecl = readFullXMLDecl(input, xmlDeclEncoding);
if (fullXMLDecl != null) {
String charset = getCharset(fullXMLDecl);
if (charset != null && !"UTF-8".equalsIgnoreCase(charset)) //$NON-NLS-1$
// only set property if value is not default (avoid using a non-default content description)
description.setProperty(IContentDescription.CHARSET, getCharset(fullXMLDecl));
}
}
return VALID;
}
|
diff --git a/src/org/eclipse/core/internal/resources/Workspace.java b/src/org/eclipse/core/internal/resources/Workspace.java
index b4ce25d6..82045483 100644
--- a/src/org/eclipse/core/internal/resources/Workspace.java
+++ b/src/org/eclipse/core/internal/resources/Workspace.java
@@ -1,2065 +1,2062 @@
/*******************************************************************************
* Copyright (c) 2000, 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.core.internal.resources;
import java.io.IOException;
import java.util.*;
import org.eclipse.core.internal.events.*;
import org.eclipse.core.internal.localstore.CoreFileSystemLibrary;
import org.eclipse.core.internal.localstore.FileSystemResourceManager;
import org.eclipse.core.internal.properties.PropertyManager;
import org.eclipse.core.internal.utils.Assert;
import org.eclipse.core.internal.utils.Policy;
import org.eclipse.core.internal.watson.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.team.IMoveDeleteHook;
import org.eclipse.core.resources.team.TeamHook;
import org.eclipse.core.runtime.*;
public class Workspace extends PlatformObject implements IWorkspace, ICoreConstants {
protected WorkspacePreferences description;
protected LocalMetaArea localMetaArea;
protected boolean openFlag = false;
protected ElementTree tree;
protected ElementTree operationTree; // tree at the start of the current operation
protected SaveManager saveManager;
protected BuildManager buildManager;
protected NatureManager natureManager;
protected NotificationManager notificationManager;
protected FileSystemResourceManager fileSystemManager;
protected PathVariableManager pathVariableManager;
protected PropertyManager propertyManager;
protected MarkerManager markerManager;
protected WorkManager workManager;
protected AliasManager aliasManager;
protected long nextNodeId = 0;
protected long nextModificationStamp = 0;
protected long nextMarkerId = 0;
protected Synchronizer synchronizer;
protected IProject[] buildOrder = null;
protected IWorkspaceRoot defaultRoot = new WorkspaceRoot(Path.ROOT, this);
protected final HashSet lifecycleListeners = new HashSet(10);
protected static final String REFRESH_ON_STARTUP = "-refresh"; //$NON-NLS-1$
/**
* File modification validation. If it is true and validator is null, we try/initialize
* validator first time through. If false, there is no validator.
*/
protected boolean shouldValidate = true;
/**
* The currently installed file modification validator.
*/
protected IFileModificationValidator validator = null;
/**
* The currently installed Move/Delete hook.
*/
protected IMoveDeleteHook moveDeleteHook = null;
/**
* The currently installed team hook.
*/
protected TeamHook teamHook = null;
// whether the resources plugin is in debug mode.
public static boolean DEBUG = false;
/**
This field is used to control the access to the workspace tree
inside operations. It is useful when calling alien code. Since
we usually are in the same thread as the alien code we are calling,
our concurrency model would allow the alien code to run operations
that could change the tree. If this field is set to true, a
beginOperation(true) fails, so the alien code would fail and be logged
in our SafeRunnable wrappers, not affecting the normal workspace operation.
*/
protected boolean treeLocked;
/** indicates if the workspace crashed in a previous session */
protected boolean crashed = false;
public Workspace() {
super();
localMetaArea = new LocalMetaArea();
tree = new ElementTree();
/* tree should only be modified during operations */
tree.immutable();
treeLocked = true;
tree.setTreeData(newElement(IResource.ROOT));
}
/**
* Adds a listener for internal workspace lifecycle events. There is no way to
* remove lifecycle listeners.
*/
public void addLifecycleListener(ILifecycleListener listener) {
lifecycleListeners.add(listener);
}
/**
* @see IWorkspace
*/
public void addResourceChangeListener(IResourceChangeListener listener) {
notificationManager.addListener(listener, IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE);
}
/**
* @see IWorkspace
*/
public void addResourceChangeListener(IResourceChangeListener listener, int eventMask) {
notificationManager.addListener(listener, eventMask);
}
/**
* @see IWorkspace
*/
public ISavedState addSaveParticipant(Plugin plugin, ISaveParticipant participant) throws CoreException {
Assert.isNotNull(plugin, "Plugin must not be null"); //$NON-NLS-1$
Assert.isNotNull(participant, "Participant must not be null"); //$NON-NLS-1$
return saveManager.addParticipant(plugin, participant);
}
public void beginOperation(boolean createNewTree) throws CoreException {
WorkManager workManager = getWorkManager();
workManager.incrementNestedOperations();
if (!workManager.isBalanced())
Assert.isTrue(false, "Operation was not prepared."); //$NON-NLS-1$
if (treeLocked && createNewTree) {
String message = Policy.bind("resources.cannotModify"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.ERROR, null, message, null);
}
if (workManager.getPreparedOperationDepth() > 1) {
if (createNewTree && tree.isImmutable())
newWorkingTree();
return;
}
if (createNewTree) {
// stash the current tree as the basis for this operation.
operationTree = tree;
newWorkingTree();
}
}
private void broadcastChanges(ElementTree currentTree, int type, boolean lockTree, boolean updateState, IProgressMonitor monitor) {
if (operationTree == null)
return;
monitor.subTask(MSG_RESOURCES_UPDATING);
notificationManager.broadcastChanges(currentTree, type, lockTree, updateState);
}
/**
* Broadcasts an internal workspace lifecycle event to interested
* internal listeners.
*/
protected void broadcastEvent(LifecycleEvent event) throws CoreException {
for (Iterator it = lifecycleListeners.iterator(); it.hasNext();) {
ILifecycleListener listener = (ILifecycleListener) it.next();
listener.handleEvent(event);
}
}
public void build(int trigger, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, Policy.opWork);
try {
prepareOperation();
beginOperation(true);
getBuildManager().build(trigger, Policy.subMonitorFor(monitor, Policy.opWork));
} finally {
getWorkManager().avoidAutoBuild();
endOperation(false, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#checkpoint
*/
public void checkpoint(boolean build) {
boolean immutable = true;
try {
/* if it was not called by the current operation, just ignore */
if (!getWorkManager().isCurrentOperation())
return;
immutable = tree.isImmutable();
broadcastChanges(tree, IResourceChangeEvent.PRE_AUTO_BUILD, false, false, Policy.monitorFor(null));
if (build && isAutoBuilding())
getBuildManager().build(IncrementalProjectBuilder.AUTO_BUILD, Policy.monitorFor(null));
broadcastChanges(tree, IResourceChangeEvent.POST_AUTO_BUILD, false, false, Policy.monitorFor(null));
broadcastChanges(tree, IResourceChangeEvent.POST_CHANGE, true, true, Policy.monitorFor(null));
getMarkerManager().resetMarkerDeltas();
} catch (CoreException e) {
// ignore any CoreException. There shouldn't be any as the buildmanager and notification manager
// should be catching and logging...
} finally {
if (!immutable)
newWorkingTree();
}
}
/**
* Deletes all the files and directories from the given root down (inclusive).
* Returns false if we could not delete some file or an exception occurred
* at any point in the deletion.
* Even if an exception occurs, a best effort is made to continue deleting.
*/
public static boolean clear(java.io.File root) {
boolean result = true;
if (root.isDirectory()) {
String[] list = root.list();
// for some unknown reason, list() can return null.
// Just skip the children If it does.
if (list != null)
for (int i = 0; i < list.length; i++)
result &= clear(new java.io.File(root, list[i]));
}
try {
if (root.exists())
result &= root.delete();
} catch (Exception e) {
result = false;
}
return result;
}
/**
* Closes this workspace; ignored if this workspace is not open.
* The state of this workspace is not saved before the workspace
* is shut down.
* <p>
* If the workspace was saved immediately prior to closing,
* it will have the same set of projects
* (open or closed) when reopened for a subsequent session.
* Otherwise, closing a workspace may lose some or all of the
* changes made since the last save or snapshot.
* </p>
* <p>
* Note that session properties are discarded when a workspace is closed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting and cancellation are not desired
* @exception CoreException if the workspace could not be shutdown.
*/
public void close(IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
String msg = Policy.bind("resources.closing.0"); //$NON-NLS-1$
int rootCount = tree.getChildCount(Path.ROOT);
monitor.beginTask(msg, rootCount + 2);
monitor.subTask(msg);
//this operation will never end because the world is going away
try {
prepareOperation();
if (isOpen()) {
beginOperation(true);
IProject[] projects = getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
//notify managers of closing so they can cleanup
broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CLOSE, projects[i]));
monitor.worked(1);
}
//empty the workspace tree so we leave in a clean state
deleteResource(getRoot());
openFlag = false;
}
// endOperation not needed here
} finally {
// Shutdown needs to be executed anyway. Doesn't matter if the workspace was not open.
shutdown(Policy.subMonitorFor(monitor, 2, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
}
} finally {
monitor.done();
}
}
/**
* Implementation of API method declared on IWorkspace.
*
* @deprecated Replaced by <code>IWorkspace.computeProjectOrder</code>, which
* produces a more usable result when there are cycles in project reference
* graph.
*/
public IProject[][] computePrerequisiteOrder(IProject[] targets) {
return computePrerequisiteOrder1(targets);
}
/*
* Compatible reimplementation of
* <code>IWorkspace.computePrerequisiteOrder</code> using
* <code>IWorkspace.computeProjectOrder</code>.
*
* @since 2.1
*/
private IProject[][] computePrerequisiteOrder1(IProject[] projects) {
IWorkspace.ProjectOrder r = computeProjectOrder(projects);
if (!r.hasCycles) {
return new IProject[][] {r.projects, new IProject[0]};
}
// when there are cycles, we need to remove all knotted projects from
// r.projects to form result[0] and merge all knots to form result[1]
// Set<IProject> bad
Set bad = new HashSet();
// Set<IProject> bad
Set keepers = new HashSet(Arrays.asList(r.projects));
for (int i = 0; i < r.knots.length; i++) {
IProject[] knot = r.knots[i];
for (int j = 0; j < knot.length; j++) {
IProject project = knot[j];
// keep only selected projects in knot
if (keepers.contains(project)) {
bad.add(project);
}
}
}
IProject[] result2 = new IProject[bad.size()];
bad.toArray(result2);
// List<IProject> p
List p = new LinkedList();
p.addAll(Arrays.asList(r.projects));
for (Iterator it = p.listIterator(); it.hasNext(); ) {
IProject project = (IProject) it.next();
if (bad.contains(project)) {
// remove knotted projects from the main answer
it.remove();
}
}
IProject[] result1 = new IProject[p.size()];
p.toArray(result1);
return new IProject[][] {result1, result2};
}
/**
* Implementation of API method declared on IWorkspace.
*
* @since 2.1
*/
public ProjectOrder computeProjectOrder(IProject[] projects) {
// compute the full project order for all accessible projects
ProjectOrder fullProjectOrder = computeFullProjectOrder();
// "fullProjectOrder.projects" contains no inaccessible projects
// but might contain accessible projects omitted from "projects"
// optimize common case where "projects" includes everything
int accessibleCount = 0;
for (int i = 0; i < projects.length; i++) {
if (projects[i].isAccessible()) {
accessibleCount++;
}
}
// no filtering required if the subset accounts for the full list
if (accessibleCount == fullProjectOrder.projects.length) {
return fullProjectOrder;
}
// otherwise we need to eliminate mention of other projects...
// ... from "fullProjectOrder.projects"...
// Set<IProject> keepers
Set keepers = new HashSet(Arrays.asList(projects));
// List<IProject> p
List reducedProjects = new ArrayList(fullProjectOrder.projects.length);
for (int i = 0; i < fullProjectOrder.projects.length; i++) {
IProject project = fullProjectOrder.projects[i];
if (keepers.contains(project)) {
// remove projects not in the initial subset
reducedProjects.add(project);
}
}
IProject[] p1 = new IProject[reducedProjects.size()];
reducedProjects.toArray(p1);
// ... and from "fullProjectOrder.knots"
// List<IProject[]> k
List reducedKnots = new ArrayList(fullProjectOrder.knots.length);
for (int i = 0; i < fullProjectOrder.knots.length; i++) {
IProject[] knot = fullProjectOrder.knots[i];
List x = new ArrayList(knot.length);
for (int j = 0; j < knot.length; j++) {
IProject project = knot[j];
if (keepers.contains(project)) {
x.add(project);
}
}
// keep knots containing 2 or more projects in the specified subset
if (x.size() > 1) {
reducedKnots.add(x.toArray(new IProject[x.size()]));
}
}
IProject[][] k1 = new IProject[reducedKnots.size()][];
// okay to use toArray here because reducedKnots elements are IProject[]
reducedKnots.toArray(k1);
return new ProjectOrder(p1, (k1.length > 0), k1);
}
/**
* Computes the global total ordering of all open projects in the
* workspace based on project references. If an existing and open project P
* references another existing and open project Q also included in the list,
* then Q should come before P in the resulting ordering. Closed and non-
* existent projects are ignored, and will not appear in the result. References
* to non-existent or closed projects are also ignored, as are any self-
* references.
* <p>
* When there are choices, the choice is made in a reasonably stable way. For
* example, given an arbitrary choice between two projects, the one with the
* lower collating project name is usually selected.
* </p>
* <p>
* When the project reference graph contains cyclic references, it is
* impossible to honor all of the relationships. In this case, the result
* ignores as few relationships as possible. For example, if P2 references P1,
* P4 references P3, and P2 and P3 reference each other, then exactly one of the
* relationships between P2 and P3 will have to be ignored. The outcome will be
* either [P1, P2, P3, P4] or [P1, P3, P2, P4]. The result also contains
* complete details of any cycles present.
* </p>
*
* @return result describing the global project order
* @since 2.1
*/
private ProjectOrder computeFullProjectOrder() {
// determine the full set of accessible projects in the workspace
// order the set in descending alphabetical order of project name
SortedSet allAccessibleProjects = new TreeSet(new Comparator() {
public int compare(Object x, Object y) {
IProject px = (IProject) x;
IProject py = (IProject) y;
return py.getName().compareTo(px.getName());
}});
IProject[] allProjects = getRoot().getProjects();
// List<IProject[]> edges
List edges = new ArrayList(allProjects.length);
for (int i = 0; i < allProjects.length; i++) {
IProject project = allProjects[i];
// ignore projects that are not accessible
if (project.isAccessible()) {
allAccessibleProjects.add(project);
IProject[] refs= null;
try {
refs = project.getReferencedProjects();
} catch (CoreException e) {
// can't happen - project is accessible
}
for (int j = 0; j < refs.length; j++) {
IProject ref = refs[j];
// ignore self references and references to projects that are
// not accessible
if (ref.isAccessible() && !ref.equals(project)) {
edges.add(new IProject[] {project, ref});
}
}
}
}
ProjectOrder fullProjectOrder =
ComputeProjectOrder.computeProjectOrder(allAccessibleProjects, edges);
return fullProjectOrder;
}
/*
* @see IWorkspace#copy
*/
public IStatus copy(IResource[] resources, IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
int opWork = Math.max(resources.length, 1);
int totalWork = Policy.totalWork * opWork / Policy.opWork;
String message = Policy.bind("resources.copying.0"); //$NON-NLS-1$
monitor.beginTask(message, totalWork);
Assert.isLegal(resources != null);
if (resources.length == 0)
return ResourceStatus.OK_STATUS;
// to avoid concurrent changes to this array
resources = (IResource[]) resources.clone();
IPath parentPath = null;
message = Policy.bind("resources.copyProblem"); //$NON-NLS-1$
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < resources.length; i++) {
Policy.checkCanceled(monitor);
IResource resource = resources[i];
if (resource == null || isDuplicate(resources, i)) {
monitor.worked(1);
continue;
}
// test siblings
if (parentPath == null)
parentPath = resource.getFullPath().removeLastSegments(1);
if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) {
// test copy requirements
try {
IPath destinationPath = destination.append(resource.getName());
IStatus requirements = ((Resource) resource).checkCopyRequirements(destinationPath, resource.getType(), updateFlags);
if (requirements.isOK()) {
try {
resource.copy(destinationPath, updateFlags, Policy.subMonitorFor(monitor, 1));
} catch (CoreException e) {
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
status.merge(requirements);
}
} catch (CoreException e) {
monitor.worked(1);
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
message = Policy.bind("resources.notChild", resources[i].getFullPath().toString(), parentPath.toString()); //$NON-NLS-1$
status.merge(new ResourceStatus(IResourceStatus.OPERATION_FAILED, resources[i].getFullPath(), message));
}
}
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork));
}
if (status.matches(IStatus.ERROR))
throw new ResourceException(status);
return status.isOK() ? ResourceStatus.OK_STATUS : (IStatus) status;
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#copy
*/
public IStatus copy(IResource[] resources, IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
return copy(resources, destination, updateFlags , monitor);
}
protected void copyTree(IResource source, IPath destination, int depth, int updateFlags, boolean keepSyncInfo) throws CoreException {
// retrieve the resource at the destination if there is one (phantoms included).
// if there isn't one, then create a new handle based on the type that we are
// trying to copy
IResource destinationResource = getRoot().findMember(destination, true);
if (destinationResource == null) {
int destinationType;
if (source.getType() == IResource.FILE)
destinationType = IResource.FILE;
else
if (destination.segmentCount() == 1)
destinationType = IResource.PROJECT;
else
destinationType = IResource.FOLDER;
destinationResource = newResource(destination, destinationType);
}
// create the resource at the destination
ResourceInfo sourceInfo = ((Resource) source).getResourceInfo(true, false);
if (destinationResource.getType() != source.getType()) {
sourceInfo = (ResourceInfo) sourceInfo.clone();
sourceInfo.setType(destinationResource.getType());
}
ResourceInfo newInfo = createResource(destinationResource, sourceInfo, false, false, keepSyncInfo);
// get/set the node id from the source's resource info so we can later put it in the
// info for the destination resource. This will help us generate the proper deltas,
// indicating a move rather than a add/delete
long nodeid = ((Resource) source).getResourceInfo(true, false).getNodeId();
newInfo.setNodeId(nodeid);
// preserve local sync info
ResourceInfo oldInfo = ((Resource) source).getResourceInfo(true, false);
newInfo.setFlags(newInfo.getFlags() | (oldInfo.getFlags() & M_LOCAL_EXISTS));
// update link locations in project descriptions
if (source.isLinked()) {
LinkDescription linkDescription;
if ((updateFlags & IResource.SHALLOW) != 0) {
//for shallow move the destination is also a linked resource
newInfo.set(ICoreConstants.M_LINK);
linkDescription = new LinkDescription(destinationResource, source.getLocation());
} else {
//for deep move the destination is not a linked resource
newInfo.clear(ICoreConstants.M_LINK);
linkDescription = null;
}
Project project = (Project)destinationResource.getProject();
project.internalGetDescription().setLinkLocation(destinationResource.getName(), linkDescription);
project.writeDescription(IResource.NONE);
}
// do the recursion. if we have a file then it has no members so return. otherwise
// recursively call this method on the container's members if the depth tells us to
if (depth == IResource.DEPTH_ZERO || source.getType() == IResource.FILE)
return;
if (depth == IResource.DEPTH_ONE)
depth = IResource.DEPTH_ZERO;
IResource[] children = ((IContainer) source).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS);
for (int i = 0; i < children.length; i++) {
IResource child = children[i];
IPath childPath = destination.append(child.getName());
copyTree(child, childPath, depth, updateFlags, keepSyncInfo);
}
}
/**
* Returns the number of resources in a subtree of the resource tree.
* @param path The subtree to count resources for
* @param depth The depth of the subtree to count
* @param phantom If true, phantoms are included, otherwise they are ignored.
*/
public int countResources(IPath root, int depth, final boolean phantom) {
if (!tree.includes(root))
return 0;
switch (depth) {
case IResource.DEPTH_ZERO:
return 1;
case IResource.DEPTH_ONE:
return 1 + tree.getChildCount(root);
case IResource.DEPTH_INFINITE:
final int[] count = new int[1];
IElementContentVisitor visitor = new IElementContentVisitor() {
public void visitElement(ElementTree tree, IPathRequestor requestor, Object elementContents) {
if (phantom || !((ResourceInfo)elementContents).isSet(M_PHANTOM))
count[0]++;
}
};
new ElementTreeIterator().iterate(tree, visitor, root);
return count[0];
}
return 0;
}
public ResourceInfo createResource(IResource resource, ResourceInfo info, boolean phantom, boolean overwrite) throws CoreException {
return createResource(resource, info, phantom, overwrite, false);
}
/*
* Creates the given resource in the tree and returns the new resource info object.
* If phantom is true, the created element is marked as a phantom.
* If there is already be an element in the tree for the given resource
* in the given state (i.e., phantom), a CoreException is thrown.
* If there is already a phantom in the tree and the phantom flag is false,
* the element is overwritten with the new element. (but the synchronization
* information is preserved) If the specified resource info is null, then create
* a new one.
*
* If keepSyncInfo is set to be true, the sync info in the given ResourceInfo is NOT
* cleared before being created and thus any sync info already existing at that namespace
* (as indicated by an already existing phantom resource) will be lost.
*/
public ResourceInfo createResource(IResource resource, ResourceInfo info, boolean phantom, boolean overwrite, boolean keepSyncInfo) throws CoreException {
info = info == null ? newElement(resource.getType()) : (ResourceInfo) info.clone();
ResourceInfo original = getResourceInfo(resource.getFullPath(), true, false);
if (phantom) {
info.set(M_PHANTOM);
info.setModificationStamp(IResource.NULL_STAMP);
}
// if nothing existed at the destination then just create the resource in the tree
if (original == null) {
// we got here from a copy/move. we don't want to copy over any sync info
// from the source so clear it.
if (!keepSyncInfo)
info.setSyncInfo(null);
tree.createElement(resource.getFullPath(), info);
} else {
// if overwrite==true then slam the new info into the tree even if one existed before
if (overwrite || (!phantom && original.isSet(M_PHANTOM))) {
// copy over the sync info and flags from the old resource info
// since we are replacing a phantom with a real resource
// DO NOT set the sync info dirty flag because we want to
// preserve the old sync info so its not dirty
// XXX: must copy over the generic sync info from the old info to the new
// XXX: do we really need to clone the sync info here?
if (!keepSyncInfo)
info.setSyncInfo(original.getSyncInfo(true));
// mark the markers bit as dirty so we snapshot an empty marker set for
// the new resource
info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY);
tree.setElementData(resource.getFullPath(), info);
} else {
String message = Policy.bind("resources.mustNotExist", resource.getFullPath().toString()); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.RESOURCE_EXISTS, resource.getFullPath(), message, null);
}
}
return info;
}
/*
* Creates the given resource in the tree and returns the new resource info object.
* If phantom is true, the created element is marked as a phantom.
* If there is already be an element in the tree for the given resource
* in the given state (i.e., phantom), a CoreException is thrown.
* If there is already a phantom in the tree and the phantom flag is false,
* the element is overwritten with the new element. (but the synchronization
* information is preserved)
*/
public ResourceInfo createResource(IResource resource, boolean phantom) throws CoreException {
return createResource(resource, null, phantom, false);
}
public ResourceInfo createResource(IResource resource, boolean phantom, boolean overwrite) throws CoreException {
return createResource(resource, null, phantom, overwrite);
}
public static WorkspaceDescription defaultWorkspaceDescription() {
return new WorkspaceDescription("Workspace"); //$NON-NLS-1$
}
/*
* @see IWorkspace#delete
*/
public IStatus delete(IResource[] resources, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
int opWork = Math.max(resources.length, 1);
int totalWork = Policy.totalWork * opWork / Policy.opWork;
String message = Policy.bind("resources.deleting.0"); //$NON-NLS-1$
monitor.beginTask(message, totalWork);
message = Policy.bind("resources.deleteProblem"); //$NON-NLS-1$
MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
if (resources.length == 0)
return result;
resources = (IResource[]) resources.clone(); // to avoid concurrent changes to this array
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < resources.length; i++) {
Policy.checkCanceled(monitor);
Resource resource = (Resource) resources[i];
if (resource == null) {
monitor.worked(1);
continue;
}
try {
resource.delete(updateFlags, Policy.subMonitorFor(monitor, 1));
} catch (CoreException e) {
// Don't really care about the exception unless the resource is still around.
ResourceInfo info = resource.getResourceInfo(false, false);
if (resource.exists(resource.getFlags(info), false)) {
message = Policy.bind("resources.couldnotDelete", resource.getFullPath().toString()); //$NON-NLS-1$
result.merge(new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, resource.getFullPath(), message));
result.merge(e.getStatus());
}
}
}
if (result.matches(IStatus.ERROR))
throw new ResourceException(result);
return result;
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork));
}
} finally {
monitor.done();
}
}
/*
* @see IWorkspace#delete
*/
public IStatus delete(IResource[] resources, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= IResource.KEEP_HISTORY;
return delete(resources, updateFlags, monitor);
}
/**
* @see IWorkspace
*/
public void deleteMarkers(IMarker[] markers) throws CoreException {
Assert.isNotNull(markers);
if (markers.length == 0)
return;
// clone to avoid outside changes
markers = (IMarker[]) markers.clone();
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < markers.length; ++i)
if (markers[i] != null && markers[i].getResource() != null)
markerManager.removeMarker(markers[i].getResource(), markers[i].getId());
} finally {
endOperation(false, null);
}
}
/**
* Delete the given resource from the current tree of the receiver.
* This method simply removes the resource from the tree. No cleanup or
* other management is done. Use IResource.delete for proper deletion.
* If the given resource is the root, all of its children (i.e., all projects) are
* deleted but the root is left.
*/
void deleteResource(IResource resource) {
IPath path = resource.getFullPath();
if (path.equals(Path.ROOT)) {
IProject[] children = getRoot().getProjects();
for (int i = 0; i < children.length; i++)
tree.deleteElement(children[i].getFullPath());
} else
tree.deleteElement(path);
}
/**
* For debugging purposes only. Dumps plugin stats to console
*/
public void dumpStats() {
EventStats.dumpStats();
}
/**
* End an operation (group of resource changes).
* Notify interested parties that some resource changes have taken place.
* This is used in the middle of batch executions to broadcast intermediate
* results. All registered resource change listeners are notified. If autobuilding
* is enabled, a build is run.
*/
public void endOperation(boolean build, IProgressMonitor monitor) throws CoreException {
WorkManager workManager = getWorkManager();
try {
workManager.setBuild(build);
// if we are not exiting a top level operation then just decrement the count and return
if (workManager.getPreparedOperationDepth() > 1)
return;
// do the following in a try/finally to ensure that the operation tree is null'd at the end
// as we are completing a top level operation.
try {
// if the tree is locked we likely got here in some finally block after a failed begin.
// Since the tree is locked, nothing could have been done so there is nothing to do.
Assert.isTrue(!(treeLocked && workManager.shouldBuild()), "The tree should not be locked."); //$NON-NLS-1$
// check for a programming error on using beginOperation/endOperation
Assert.isTrue(workManager.getPreparedOperationDepth() > 0, "Mismatched begin/endOperation"); //$NON-NLS-1$
// At this time we need to rebalance the nested operations. It is necessary because
// build() and snapshot() should not fail if they are called.
workManager.rebalanceNestedOperations();
// If autobuild is on, give each open project a chance to build. We have to tell each one
// because there is no way of knowing whether or not there is a relevant change
// for the project without computing the delta for each builder in each project relative
// to its last built state. If we have guaranteed corelation between the notification delta
// and the last time autobuild was done, then we could look at the notification delta and
// see which projects had changed and only build them. Currently there is no such
// guarantee.
// Note that building a project when there is actually nothing to do is not free but
// is should not be too expensive. The computed delta will be empty and so the builder itself
// will not actually be run. This does require however the delta computation.
//
// This is done in a try finally to ensure that we always decrement the operation count.
// The operationCount cannot be decremented before this as the build must be done
// inside an operation. Note that we only ever get here if we are at a top level operation.
// As such, the operationCount will always be 0 (zero) after this.
OperationCanceledException cancel = null;
CoreException signal = null;
monitor = Policy.monitorFor(monitor);
monitor.subTask(MSG_RESOURCES_UPDATING); //$NON-NLS-1$
broadcastChanges(tree, IResourceChangeEvent.PRE_AUTO_BUILD, false, false, Policy.monitorFor(null));
if (isAutoBuilding() && shouldBuild()) {
try {
getBuildManager().build(IncrementalProjectBuilder.AUTO_BUILD, monitor);
} catch (OperationCanceledException e) {
cancel = e;
} catch (CoreException sig) {
signal = sig;
}
}
broadcastChanges(tree, IResourceChangeEvent.POST_AUTO_BUILD, false, false, Policy.monitorFor(null));
broadcastChanges(tree, IResourceChangeEvent.POST_CHANGE, true, true, Policy.monitorFor(null));
getMarkerManager().resetMarkerDeltas();
// Perform a snapshot if we are sufficiently out of date. Be sure to make the tree immutable first
tree.immutable();
saveManager.snapshotIfNeeded();
//make sure the monitor subtask message is cleared.
monitor.subTask(""); //$NON-NLS-1$
if (cancel != null)
throw cancel;
if (signal != null)
throw signal;
} finally {
// make sure that the tree is immutable. Only do this if we are ending a top-level operation.
tree.immutable();
operationTree = null;
}
} finally {
workManager.checkOut();
}
}
/**
* Flush the build order cache for the workspace. Only needed if the
* description does not already have a build order. That is, if this
* is really a cache.
*/
protected void flushBuildOrder() {
if (description.getBuildOrder(false) == null)
buildOrder = null;
}
/**
* @see IWorkspace
*/
public void forgetSavedTree(String pluginId) {
Assert.isNotNull(pluginId, "PluginId must not be null"); //$NON-NLS-1$
saveManager.forgetSavedTree(pluginId);
}
public AliasManager getAliasManager() {
return aliasManager;
}
/**
* Returns this workspace's build manager
*/
public BuildManager getBuildManager() {
return buildManager;
}
/**
* Returns the order in which open projects in this workspace will be built.
* <p>
* The project build order is based on information specified in the workspace
* description. The projects are built in the order specified by
* <code>IWorkspaceDescription.getBuildOrder</code>; closed or non-existent
* projects are ignored and not included in the result. If
* <code>IWorkspaceDescription.getBuildOrder</code> is non-null, the default
* build order is used; again, only open projects are included in the result.
* </p>
* <p>
* The returned value is cached in the <code>buildOrder</code> field.
* </p>
*
* @return the list of currently open projects in the workspace in the order in
* which they would be built by <code>IWorkspace.build</code>.
* @see IWorkspace#build
* @see IWorkspaceDescription#getBuildOrder
* @since 2.1
*/
public IProject[] getBuildOrder() {
if (buildOrder != null) {
// return previously-computed and cached project build order
return buildOrder;
}
// see if a particular build order is specified
String[] order = description.getBuildOrder(false);
if (order != null) {
// convert from project names to project handles
// and eliminate non-existent and closed projects
List projectList = new ArrayList(order.length);
for (int i = 0; i < order.length; i++) {
IProject project = getRoot().getProject(order[i]);
//FIXME should non-accessible projects be removed?
if (project.isAccessible()) {
projectList.add(project);
}
}
buildOrder = new IProject[projectList.size()];
projectList.toArray(buildOrder);
} else {
// use default project build order
// computed for all accessible projects in workspace
buildOrder = computeFullProjectOrder().projects;
}
return buildOrder;
}
/**
* @see IWorkspace#getDanglingReferences
*/
public Map getDanglingReferences() {
IProject[] projects = getRoot().getProjects();
Map result = new HashMap(projects.length);
for (int i = 0; i < projects.length; i++) {
Project project = (Project) projects[i];
if (!project.isAccessible())
continue;
IProject[] refs = project.internalGetDescription().getReferencedProjects(false);
List dangling = new ArrayList(refs.length);
for (int j = 0; j < refs.length; j++)
if (!refs[i].exists())
dangling.add(refs[i]);
if (!dangling.isEmpty())
result.put(projects[i], dangling.toArray(new IProject[dangling.size()]));
}
return result;
}
/**
* @see IWorkspace
*/
public IWorkspaceDescription getDescription() {
WorkspaceDescription workingCopy = defaultWorkspaceDescription();
description.copyTo(workingCopy);
return workingCopy;
}
/**
* Returns the current element tree for this workspace
*/
public ElementTree getElementTree() {
return tree;
}
public FileSystemResourceManager getFileSystemManager() {
return fileSystemManager;
}
/**
* Returns the marker manager for this workspace
*/
public MarkerManager getMarkerManager() {
return markerManager;
}
public LocalMetaArea getMetaArea() {
return localMetaArea;
}
protected IMoveDeleteHook getMoveDeleteHook() {
if (moveDeleteHook == null)
initializeMoveDeleteHook();
return moveDeleteHook;
}
/**
* @see IWorkspace#getNatureDescriptor(String)
*/
public IProjectNatureDescriptor getNatureDescriptor(String natureId) {
return natureManager.getNatureDescriptor(natureId);
}
/**
* @see IWorkspace#getNatureDescriptors()
*/
public IProjectNatureDescriptor[] getNatureDescriptors() {
return natureManager.getNatureDescriptors();
}
/**
* Returns the nature manager for this workspace.
*/
public NatureManager getNatureManager() {
return natureManager;
}
public NotificationManager getNotificationManager() {
return notificationManager;
}
/**
* @see org.eclipse.core.resources.IWorkspace#getPathVariableManager()
*/
public IPathVariableManager getPathVariableManager() {
return pathVariableManager;
}
public PropertyManager getPropertyManager() {
return propertyManager;
}
/**
* Returns the resource info for the identified resource.
* null is returned if no such resource can be found.
* If the phantom flag is true, phantom resources are considered.
* If the mutable flag is true, the info is opened for change.
*
* This method DOES NOT throw an exception if the resource is not found.
*/
public ResourceInfo getResourceInfo(IPath path, boolean phantom, boolean mutable) {
try {
if (path.segmentCount() == 0) {
ResourceInfo info = (ResourceInfo)tree.getTreeData();
Assert.isNotNull(info, "Tree root info must never be null"); //$NON-NLS-1$
return info;
}
ResourceInfo result = null;
if (!tree.includes(path))
return null;
if (mutable)
result = (ResourceInfo) tree.openElementData(path);
else
result = (ResourceInfo) tree.getElementData(path);
if (result != null && (!phantom && result.isSet(M_PHANTOM)))
return null;
return result;
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* @see IWorkspace#getRoot
*/
public IWorkspaceRoot getRoot() {
return defaultRoot;
}
public SaveManager getSaveManager() {
return saveManager;
}
/**
* @see IWorkspace#getSynchronizer
*/
public ISynchronizer getSynchronizer() {
return synchronizer;
}
/**
* Returns the installed team hook. Never returns null.
*/
protected TeamHook getTeamHook() {
if (teamHook == null)
initializeTeamHook();
return teamHook;
}
/**
* We should not have direct references to this field. All references should go through
* this method.
*/
public WorkManager getWorkManager() throws CoreException {
if (workManager == null) {
String message = Policy.bind("resources.shutdown"); //$NON-NLS-1$
throw new ResourceException(new ResourceStatus(IResourceStatus.INTERNAL_ERROR, null, message));
}
return workManager;
}
/**
* A file modification validator hasn't been initialized. Check the extension point and
* try to create a new validator if a user has one defined as an extension.
*/
protected void initializeValidator() {
shouldValidate = false;
IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_FILE_MODIFICATION_VALIDATOR);
// no-one is plugged into the extension point so disable validation
if (configs == null || configs.length == 0) {
return;
}
// can only have one defined at a time. log a warning, disable validation, but continue with
// the #setContents (e.g. don't throw an exception)
if (configs.length > 1) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneValidator"), null); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
return;
}
// otherwise we have exactly one validator extension. Try to create a new instance
// from the user-specified class.
try {
IConfigurationElement config = configs[0];
validator = (IFileModificationValidator) config.createExecutableExtension("class"); //$NON-NLS-1$
shouldValidate = true;
} catch (CoreException e) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initValidator"), e); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
}
}
/**
* A move/delete hook hasn't been initialized. Check the extension point and
* try to create a new hook if a user has one defined as an extension. Otherwise
* use the Core's implementation as the default.
*/
protected void initializeMoveDeleteHook() {
try {
IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_MOVE_DELETE_HOOK);
// no-one is plugged into the extension point so disable validation
if (configs == null || configs.length == 0) {
return;
}
// can only have one defined at a time. log a warning
if (configs.length > 1) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneHook"), null); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
return;
}
// otherwise we have exactly one hook extension. Try to create a new instance
// from the user-specified class.
try {
IConfigurationElement config = configs[0];
moveDeleteHook = (IMoveDeleteHook) config.createExecutableExtension("class"); //$NON-NLS-1$
} catch (CoreException e) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initHook"), e); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
}
} finally {
// for now just use Core's implementation
if (moveDeleteHook == null)
moveDeleteHook = new MoveDeleteHook();
}
}
/**
* A team hook hasn't been initialized. Check the extension point and
* try to create a new hook if a user has one defined as an extension.
* Otherwise use the Core's implementation as the default.
*/
protected void initializeTeamHook() {
try {
IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_TEAM_HOOK);
// no-one is plugged into the extension point so disable validation
if (configs == null || configs.length == 0) {
return;
}
// can only have one defined at a time. log a warning
if (configs.length > 1) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneTeamHook"), null); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
return;
}
// otherwise we have exactly one hook extension. Try to create a new instance
// from the user-specified class.
try {
IConfigurationElement config = configs[0];
teamHook = (TeamHook) config.createExecutableExtension("class"); //$NON-NLS-1$
} catch (CoreException e) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initTeamHook"), e); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
}
} finally {
// default to use Core's implementation
if (teamHook == null)
teamHook = new TeamHook();
}
}
public WorkspaceDescription internalGetDescription() {
return description;
}
/**
* @see IWorkspace
*/
public boolean isAutoBuilding() {
return description.isAutoBuilding();
}
/**
* Returns true if the object at the specified position has any
* other copy in the given array.
*/
private static boolean isDuplicate(Object[] array, int position) {
if (array == null || position >= array.length)
return false;
for (int j = position - 1; j >= 0; j--)
if (array[j].equals(array[position]))
return true;
return false;
}
/**
* @see IWorkspace#isOpen
*/
public boolean isOpen() {
return openFlag;
}
/**
* Returns true if the given file system locations overlap (they are the same,
* or one is a proper prefix of the other), and false otherwise.
* Does the right thing with respect to case insensitive platforms.
*/
protected boolean isOverlapping(IPath location1, IPath location2) {
IPath one = location1;
IPath two = location2;
// If we are on a case-insensitive file system then convert to all lowercase.
if (!CoreFileSystemLibrary.isCaseSensitive()) {
one = new Path(location1.toOSString().toLowerCase());
two = new Path(location2.toOSString().toLowerCase());
}
return one.isPrefixOf(two) || two.isPrefixOf(one);
}
public boolean isTreeLocked() {
return treeLocked;
}
/**
* Link the given tree into the receiver's tree at the specified resource.
*/
protected void linkTrees(IPath path, ElementTree[] newTrees) throws CoreException {
tree = tree.mergeDeltaChain(path, newTrees);
}
/**
* @see IWorkspace#loadProjectDescription
* @since 2.0
*/
public IProjectDescription loadProjectDescription(IPath path) throws CoreException {
IProjectDescription result = null;
IOException e = null;
try {
result = (IProjectDescription) new ModelObjectReader().read(path);
if (result != null) {
// check to see if we are using in the default area or not. use java.io.File for
// testing equality because it knows better w.r.t. drives and case sensitivity
IPath user = path.removeLastSegments(1);
IPath platform = Platform.getLocation().append(result.getName());
if (!user.toFile().equals(platform.toFile()))
result.setLocation(user);
}
} catch (IOException ex) {
e = ex;
}
if (result == null || e != null) {
String message = Policy.bind("resources.errorReadProject", path.toOSString());//$NON-NLS1 //$NON-NLS-1$
IStatus status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message, e);
throw new ResourceException(status);
}
return result;
}
/*
* @see IWorkspace#move
*/
public IStatus move(IResource[] resources, IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
int opWork = Math.max(resources.length, 1);
int totalWork = Policy.totalWork * opWork / Policy.opWork;
String message = Policy.bind("resources.moving.0"); //$NON-NLS-1$
monitor.beginTask(message, totalWork);
Assert.isLegal(resources != null);
if (resources.length == 0)
return ResourceStatus.OK_STATUS;
resources = (IResource[]) resources.clone(); // to avoid concurrent changes to this array
IPath parentPath = null;
message = Policy.bind("resources.moveProblem"); //$NON-NLS-1$
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < resources.length; i++) {
Policy.checkCanceled(monitor);
Resource resource = (Resource) resources[i];
if (resource == null || isDuplicate(resources, i)) {
monitor.worked(1);
continue;
}
// test siblings
if (parentPath == null)
parentPath = resource.getFullPath().removeLastSegments(1);
if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) {
// test move requirements
try {
IStatus requirements = resource.checkMoveRequirements(destination.append(resource.getName()), resource.getType(), updateFlags);
if (requirements.isOK()) {
try {
resource.move(destination.append(resource.getName()), updateFlags, Policy.subMonitorFor(monitor, 1));
} catch (CoreException e) {
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
status.merge(requirements);
}
} catch (CoreException e) {
monitor.worked(1);
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
message = Policy.bind("resources.notChild", resource.getFullPath().toString(), parentPath.toString()); //$NON-NLS-1$
status.merge(new ResourceStatus(IResourceStatus.OPERATION_FAILED, resource.getFullPath(), message));
}
}
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork));
}
if (status.matches(IStatus.ERROR))
throw new ResourceException(status);
return status.isOK() ? (IStatus) ResourceStatus.OK_STATUS : (IStatus) status;
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#move
*/
public IStatus move(IResource[] resources, IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= IResource.KEEP_HISTORY;
return move(resources, destination, updateFlags, monitor);
}
/**
* Moves this resource's subtree to the destination. This operation should only be
* used by move methods. Destination must be a valid destination for this resource.
* The keepSyncInfo boolean is used to indicated whether or not the sync info should
* be moved from the source to the destination.
*/
/* package */ void move(Resource source, IPath destination, int depth, int updateFlags, boolean keepSyncInfo) throws CoreException {
// overlay the tree at the destination path, preserving any important info
// in any already existing resource infos
copyTree(source, destination, depth, updateFlags, keepSyncInfo);
source.fixupAfterMoveSource();
}
/**
* Create and return a new tree element of the given type.
*/
protected ResourceInfo newElement(int type) {
ResourceInfo result = null;
switch (type) {
case IResource.FILE :
case IResource.FOLDER :
result = new ResourceInfo();
break;
case IResource.PROJECT :
result = new ProjectInfo();
break;
case IResource.ROOT :
result = new RootInfo();
break;
}
result.setNodeId(nextNodeId());
result.setModificationStamp(nextModificationStamp());
result.setType(type);
return result;
}
/**
* @see IWorkspace#newProjectDescription
*/
public IProjectDescription newProjectDescription(String projectName) {
IProjectDescription result = new ProjectDescription();
result.setName(projectName);
return result;
}
public Resource newResource(IPath path, int type) {
String message;
switch (type) {
case IResource.FOLDER :
message = "Path must include project and resource name."; //$NON-NLS-1$
Assert.isLegal(path.segmentCount() >= ICoreConstants.MINIMUM_FOLDER_SEGMENT_LENGTH , message);
return new Folder(path.makeAbsolute(), this);
case IResource.FILE :
message = "Path must include project and resource name."; //$NON-NLS-1$
Assert.isLegal(path.segmentCount() >= ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH, message);
return new File(path.makeAbsolute(), this);
case IResource.PROJECT :
return (Resource) getRoot().getProject(path.lastSegment());
case IResource.ROOT :
return (Resource) getRoot();
}
Assert.isLegal(false);
// will never get here because of assertion.
return null;
}
/**
* Opens a new mutable element tree layer, thus allowing
* modifications to the tree.
*/
public ElementTree newWorkingTree() {
tree = tree.newEmptyDelta();
return tree;
}
/**
* Returns the next, previously unassigned, marker id.
*/
protected long nextMarkerId() {
return nextMarkerId++;
}
public long nextModificationStamp() {
return nextModificationStamp++;
}
public long nextNodeId() {
return nextNodeId++;
}
/**
* Opens this workspace using the data at its location in the local file system.
* This workspace must not be open.
* If the operation succeeds, the result will detail any serious
* (but non-fatal) problems encountered while opening the workspace.
* The status code will be <code>OK</code> if there were no problems.
* An exception is thrown if there are fatal problems opening the workspace,
* in which case the workspace is left closed.
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting and cancellation are not desired
* @return status with code <code>OK</code> if no problems;
* otherwise status describing any serious but non-fatal problems.
*
* @exception CoreException if the workspace could not be opened.
* Reasons include:
* <ul>
* <li> There is no valid workspace structure at the given location
* in the local file system.</li>
* <li> The workspace structure on disk appears to be hopelessly corrupt.</li>
* </ul>
* @see IWorkspace#getLocation
* @see ResourcePlugin#containsWorkspace
*/
public IStatus open(IProgressMonitor monitor) throws CoreException {
// This method is not inside an operation because it is the one responsible for
// creating the WorkManager object (who takes care of operations).
String message = Policy.bind("resources.workspaceOpen"); //$NON-NLS-1$
Assert.isTrue(!isOpen(), message);
if (!getMetaArea().hasSavedWorkspace()) {
message = Policy.bind("resources.readWorkspaceMeta"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.FAILED_READ_METADATA, Platform.getLocation(), message, null);
}
description = new WorkspacePreferences();
description.setDefaults(Workspace.defaultWorkspaceDescription());
// if we have an old description file, read it (getting rid of it)
WorkspaceDescription oldDescription = getMetaArea().readOldWorkspace();
if (oldDescription != null) {
description.copyFrom(oldDescription);
ResourcesPlugin.getPlugin().savePluginPreferences();
}
// create root location
localMetaArea.locationFor(getRoot()).toFile().mkdirs();
// turn off autobuilding while we open the workspace. This is in
// case an operation is triggered. We don't want to do an autobuild
// just yet. Any changes will be reported the next time we build.
boolean oldBuildFlag = description.isAutoBuilding();
try {
description.setAutoBuilding(false);
IProgressMonitor nullMonitor = Policy.monitorFor(null);
startup(nullMonitor);
//restart the notification manager so it is initialized with the right tree
notificationManager.startup(null);
openFlag = true;
if (crashed || refreshRequested()) {
try {
getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
//don't fail entire open if refresh failed, just report as minor warning
return e.getStatus();
}
}
return ResourceStatus.OK_STATUS;
} finally {
description.setAutoBuilding(oldBuildFlag);
}
}
/**
* Called before checking the pre-conditions of an operation.
*/
public void prepareOperation() throws CoreException {
getWorkManager().checkIn();
if (!isOpen()) {
String message = Policy.bind("resources.workspaceClosed"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.OPERATION_FAILED, null, message, null);
}
}
protected boolean refreshRequested() {
String[] args = Platform.getCommandLineArgs();
for (int i = 0; i < args.length; i++)
if (args[i].equalsIgnoreCase(REFRESH_ON_STARTUP))
return true;
return false;
}
/**
* @see IWorkspace
*/
public void removeResourceChangeListener(IResourceChangeListener listener) {
notificationManager.removeListener(listener);
}
/**
* @see IWorkspace
*/
public void removeSaveParticipant(Plugin plugin) {
Assert.isNotNull(plugin, "Plugin must not be null"); //$NON-NLS-1$
saveManager.removeParticipant(plugin);
}
/**
* @see IWorkspace#run
*/
public void run(IWorkspaceRunnable job, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, Policy.totalWork);
try {
prepareOperation();
beginOperation(true);
job.run(Policy.subMonitorFor(monitor, Policy.opWork, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(false, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
/**
* @see IWorkspace
*/
public IStatus save(boolean full, IProgressMonitor monitor) throws CoreException {
String message;
// if a full save was requested, and this is a top-level op, try the save. Otherwise
// fail the operation.
if (full) {
// If the workmanager thread is null or is different than this thread
// it is OK to start the save because it will wait until the other thread
// is finished. Otherwise, someone in this thread has tried to do a save
// inside of an operation (which is not allowed by the spec).
if (getWorkManager().getCurrentOperationThread() == Thread.currentThread()) {
message = Policy.bind("resources.saveOp"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.OPERATION_FAILED, null, message, null);
}
return saveManager.save(ISaveContext.FULL_SAVE, null, monitor);
}
// A snapshot was requested. Start an operation (if not already started) and
// signal that a snapshot should be done at the end.
try {
prepareOperation();
beginOperation(false);
saveManager.requestSnapshot();
message = Policy.bind("resources.snapRequest"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OK, message);
} finally {
endOperation(false, null);
}
}
public void setCrashed(boolean value) {
crashed = value;
}
/**
* @see IWorkspace
*/
public void setDescription(IWorkspaceDescription value) throws CoreException {
// if both the old and new description's build orders are null, leave the
// workspace's build order slot because it is caching the computed order.
// Otherwise, set the slot to null to force recomputation or building from the description.
WorkspaceDescription newDescription = (WorkspaceDescription) value;
String[] newOrder = newDescription.getBuildOrder(false);
if (description.getBuildOrder(false) != null || newOrder != null)
buildOrder = null;
description.copyFrom(newDescription);
Policy.setupAutoBuildProgress(description.isAutoBuilding());
ResourcesPlugin.getPlugin().savePluginPreferences();
}
public void setTreeLocked(boolean locked) {
treeLocked = locked;
}
public void setWorkspaceLock(WorkspaceLock lock) {
workManager.setWorkspaceLock(lock);
}
private boolean shouldBuild() throws CoreException {
return getWorkManager().shouldBuild() && ElementTree.hasChanges(tree, operationTree, ResourceComparator.getComparator(false), true);
}
protected void shutdown(IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
IManager[] managers = { buildManager, notificationManager, propertyManager, pathVariableManager, fileSystemManager, markerManager, saveManager, workManager, aliasManager};
monitor.beginTask(null, managers.length);
String message = Policy.bind("resources.shutdownProblems"); //$NON-NLS-1$
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
// best effort to shutdown every object and free resources
for (int i = 0; i < managers.length; i++) {
IManager manager = managers[i];
if (manager == null)
monitor.worked(1);
else {
try {
manager.shutdown(Policy.subMonitorFor(monitor, 1));
} catch (Exception e) {
message = Policy.bind("resources.shutdownProblems"); //$NON-NLS-1$
status.add(new Status(Status.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, e));
}
}
}
buildManager = null;
notificationManager = null;
propertyManager = null;
pathVariableManager = null;
fileSystemManager = null;
markerManager = null;
synchronizer = null;
saveManager = null;
workManager = null;
if (!status.isOK())
throw new CoreException(status);
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#sortNatureSet(String[])
*/
public String[] sortNatureSet(String[] natureIds) {
return natureManager.sortNatureSet(natureIds);
}
protected void startup(IProgressMonitor monitor) throws CoreException {
// ensure the tree is locked during the startup notification
workManager = new WorkManager(this);
workManager.startup(null);
fileSystemManager = new FileSystemResourceManager(this);
fileSystemManager.startup(monitor);
propertyManager = new PropertyManager(this);
propertyManager.startup(monitor);
pathVariableManager = new PathVariableManager(this);
pathVariableManager.startup(null);
natureManager = new NatureManager();
natureManager.startup(null);
buildManager = new BuildManager(this);
buildManager.startup(null);
notificationManager = new NotificationManager(this);
notificationManager.startup(null);
markerManager = new MarkerManager(this);
markerManager.startup(null);
synchronizer = new Synchronizer(this);
saveManager = new SaveManager(this);
saveManager.startup(null);
//must start after save manager, because (read) access to tree is needed
aliasManager = new AliasManager(this);
aliasManager.startup(null);
treeLocked = false; // unlock the tree.
}
/**
* Returns a string representation of this working state's
* structure suitable for debug purposes.
*/
public String toDebugString() {
final StringBuffer buffer = new StringBuffer("\nDump of " + toString() + ":\n"); //$NON-NLS-1$ //$NON-NLS-2$
buffer.append(" parent: " + tree.getParent()); //$NON-NLS-1$
ElementTreeIterator iterator = new ElementTreeIterator();
IElementPathContentVisitor visitor = new IElementPathContentVisitor() {
public void visitElement(ElementTree tree, IPath path, Object elementContents) {
buffer.append("\n " + path + ": " + elementContents); //$NON-NLS-1$ //$NON-NLS-2$
}
};
iterator.iterateWithPath(tree, visitor, Path.ROOT);
return buffer.toString();
}
public void updateModificationStamp(ResourceInfo info) {
info.setModificationStamp(nextModificationStamp());
}
/* (non-javadoc)
* Method declared on IWorkspace.
*/
public IStatus validateEdit(final IFile[] files, final Object context) {
// if validation is turned off then just return
if (!shouldValidate) {
String message = Policy.bind("resources.readOnly2"); //$NON-NLS-1$
MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.OK, message, null);
for (int i=0; i<files.length; i++) {
if (files[i].isReadOnly()) {
IPath filePath = files[i].getFullPath();
message = Policy.bind("resources.readOnly", filePath.toString()); //$NON-NLS-1$
result.add(new ResourceStatus(IResourceStatus.FAILED_WRITE_LOCAL, filePath, message));
}
}
return result.isOK() ? ResourceStatus.OK_STATUS : (IStatus) result;
}
// first time through the validator hasn't been initialized so try and create it
if (validator == null)
initializeValidator();
// we were unable to initialize the validator. Validation has been turned off and
// a warning has already been logged so just return.
if (validator == null)
return ResourceStatus.OK_STATUS;
// otherwise call the API and throw an exception if appropriate
final IStatus[] status = new IStatus[1];
ISafeRunnable body = new ISafeRunnable() {
public void run() throws Exception {
status[0] = validator.validateEdit(files, context);
}
public void handleException(Throwable exception) {
status[0] = new ResourceStatus(IResourceStatus.ERROR, null, Policy.bind("resources.errorValidator"), exception); //$NON-NLS-1$
}
};
Platform.run(body);
return status[0];
}
/* (non-javadoc)
* Method declared on IWorkspace.
*/
public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) {
//check that the resource has a project as its parent
String message;
IContainer parent = resource.getParent();
if (parent == null || parent.getType() != IResource.PROJECT) {
message = Policy.bind("links.parentNotProject", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
if (!parent.isAccessible()) {
message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
IPath location = getPathVariableManager().resolvePath(unresolvedLocation);
//check nature veto
String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds();
IStatus result = getNatureManager().validateLinkCreation(natureIds);
if (!result.isOK())
return result;
//check team provider veto
if (resource.getType() == IResource.FILE)
result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location);
else
result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location);
if (!result.isOK())
return result;
//check the standard path name restrictions
int segmentCount = location.segmentCount();
for (int i = 0; i < segmentCount; i++) {
result = validateName(location.segment(i), resource.getType());
if (!result.isOK())
return result;
}
//if the location doesn't have a device, see if the OS will assign one
if (location.getDevice() == null)
location = new Path(location.toFile().getAbsolutePath());
// test if the given location overlaps the platform metadata location
IPath testLocation = getMetaArea().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.invalidLocation", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
//test if the given path overlaps the location of the given project
testLocation = resource.getProject().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.locationOverlapsProject", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
//check that the location is absolute
//Note: this check must be done last because we tolerate this condition in createLink
if (!location.isAbsolute()) {
if (location.segmentCount() > 0)
message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$
else
message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message);
}
// Iterate over each known project and ensure that the location does not
// conflict with any project locations or linked resource locations
IProject[] projects = getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
IProject project = (IProject) projects[i];
// since we are iterating over the project in the workspace, we
// know that they have been created before and must have a description
IProjectDescription desc = ((Project) project).internalGetDescription();
testLocation = desc.getLocation();
- // if the project uses the default location then continue
- if (testLocation == null)
- continue;
- if (isOverlapping(location, testLocation)) {
+ if (testLocation != null && isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message);
}
//iterate over linked resources and check for overlap
if (!project.isOpen())
continue;
IResource[] children = null;
try {
children = project.members();
} catch (CoreException e) {
//ignore projects that cannot be accessed
}
if (children == null)
continue;
for (int j = 0; j < children.length; j++) {
if (children[j].isLinked()) {
testLocation = children[j].getLocation();
- if (isOverlapping(location, testLocation)) {
+ if (testLocation != null && isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message);
}
}
}
}
return ResourceStatus.OK_STATUS;
}
/**
* @see IWorkspace#validateName
*/
public IStatus validateName(String segment, int type) {
String message;
/* segment must not be null */
if (segment == null) {
message = Policy.bind("resources.nameNull"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
// cannot be an empty string
if (segment.length() == 0) {
message = Policy.bind("resources.nameEmpty"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* segment must not begin or end with a whitespace */
if (Character.isWhitespace(segment.charAt(0)) || Character.isWhitespace(segment.charAt(segment.length() - 1))) {
message = Policy.bind("resources.invalidWhitespace",segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* segment must not end with a dot */
if (segment.endsWith(".")) { //$NON-NLS-1$
message = Policy.bind("resources.invalidDot", segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* test invalid characters */
char[] chars = OS.INVALID_RESOURCE_CHARACTERS;
for (int i = 0; i < chars.length; i++)
if (segment.indexOf(chars[i]) != -1) {
message = Policy.bind("resources.invalidCharInName", String.valueOf(chars[i]), segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* test invalid OS names */
if (!OS.isNameValid(segment)) {
message = Policy.bind("resources.invalidName", segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
return ResourceStatus.OK_STATUS;
}
/**
* @see IWorkspace#validateNatureSet(String[])
*/
public IStatus validateNatureSet(String[] natureIds) {
return natureManager.validateNatureSet(natureIds);
}
/**
* @see IWorkspace#validatePath
*/
public IStatus validatePath(String path, int type) {
String message;
/* path must not be null */
if (path == null) {
message = Policy.bind("resources.pathNull"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* path must not have a device separator */
if (path.indexOf(IPath.DEVICE_SEPARATOR) != -1) {
message = Policy.bind("resources.invalidCharInPath", String.valueOf(IPath.DEVICE_SEPARATOR), path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* path must not be the root path */
IPath testPath = new Path(path);
if (testPath.isRoot()) {
message = Policy.bind("resources.invalidRoot"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* path must be absolute */
if (!testPath.isAbsolute()) {
message = Policy.bind("resources.mustBeAbsolute", path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* validate segments */
int numberOfSegments = testPath.segmentCount();
if ((type & IResource.PROJECT) != 0) {
if (numberOfSegments == ICoreConstants.PROJECT_SEGMENT_LENGTH) {
return validateName(testPath.segment(0), IResource.PROJECT);
} else
if (type == IResource.PROJECT) {
message = Policy.bind("resources.projectPath",path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
}
if ((type & (IResource.FILE | IResource.FOLDER)) != 0)
if (numberOfSegments >= ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH) {
IStatus status = validateName(testPath.segment(0), IResource.PROJECT);
if (!status.isOK())
return status;
int fileFolderType = type &= ~IResource.PROJECT;
int segmentCount = testPath.segmentCount();
// ignore first segment (the project)
for (int i = 1; i < segmentCount; i++) {
status = validateName(testPath.segment(i), fileFolderType);
if (!status.isOK())
return status;
}
return ResourceStatus.OK_STATUS;
} else {
message = Policy.bind("resources.resourcePath",path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
message = Policy.bind("resources.invalidPath", path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/**
* @see IWorkspace#validateProjectLocation
*/
public IStatus validateProjectLocation(IProject context, IPath unresolvedLocation) {
String message;
// the default default is ok for all projects
if (unresolvedLocation == null) {
return ResourceStatus.OK_STATUS;
}
//check the standard path name restrictions
IPath location = getPathVariableManager().resolvePath(unresolvedLocation);
int segmentCount = location.segmentCount();
for (int i = 0; i < segmentCount; i++) {
IStatus result = validateName(location.segment(i), IResource.PROJECT);
if (!result.isOK())
return result;
}
//check that the location is absolute
if (!location.isAbsolute()) {
if (location.segmentCount() > 0)
message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$
else
message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message);
}
//if the location doesn't have a device, see if the OS will assign one
if (location.getDevice() == null)
location = new Path(location.toFile().getAbsolutePath());
// test if the given location overlaps the default default location
IPath defaultDefaultLocation = Platform.getLocation();
if (isOverlapping(location, defaultDefaultLocation)) {
message = Policy.bind("resources.overlapLocal", location.toString(), defaultDefaultLocation.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
// Iterate over each known project and ensure that the location does not
// conflict with any of their already defined locations.
IProject[] projects = getRoot().getProjects();
for (int j = 0; j < projects.length; j++) {
IProject project = (IProject) projects[j];
// since we are iterating over the project in the workspace, we
// know that they have been created before and must have a description
IProjectDescription desc = ((Project) project).internalGetDescription();
IPath definedLocalLocation = desc.getLocation();
// if the project uses the default location then continue
if (definedLocalLocation == null)
continue;
//tolerate locations being the same if this is the project being tested
if (project.equals(context) && definedLocalLocation.equals(location))
continue;
if (isOverlapping(location, definedLocalLocation)) {
message = Policy.bind("resources.overlapLocal", location.toString(), definedLocalLocation.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
}
return ResourceStatus.OK_STATUS;
}
/**
* Internal method. To be called only from the following methods:
* <ul>
* <li><code>IFile#appendContents</code></li>
* <li><code>IFile#setContents(InputStream, boolean, boolean, IProgressMonitor)</code></li>
* <li><code>IFile#setContents(IFileState, boolean, boolean, IProgressMonitor)</code></li>
* </ul>
*
* @see IFileModificationValidator#validateSave
*/
protected void validateSave(final IFile file) throws CoreException {
// if validation is turned off then just return
if (!shouldValidate)
return;
// first time through the validator hasn't been initialized so try and create it
if (validator == null)
initializeValidator();
// we were unable to initialize the validator. Validation has been turned off and
// a warning has already been logged so just return.
if (validator == null)
return;
// otherwise call the API and throw an exception if appropriate
final IStatus[] status = new IStatus[1];
ISafeRunnable body = new ISafeRunnable() {
public void run() throws Exception {
status[0] = validator.validateSave(file);
}
public void handleException(Throwable exception) {
status[0] = new ResourceStatus(IResourceStatus.ERROR, null, Policy.bind("resources.errorValidator"), exception); //$NON-NLS-1$
}
};
Platform.run(body);
if (!status[0].isOK())
throw new ResourceException(status[0]);
}
}
| false | true | public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) {
//check that the resource has a project as its parent
String message;
IContainer parent = resource.getParent();
if (parent == null || parent.getType() != IResource.PROJECT) {
message = Policy.bind("links.parentNotProject", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
if (!parent.isAccessible()) {
message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
IPath location = getPathVariableManager().resolvePath(unresolvedLocation);
//check nature veto
String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds();
IStatus result = getNatureManager().validateLinkCreation(natureIds);
if (!result.isOK())
return result;
//check team provider veto
if (resource.getType() == IResource.FILE)
result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location);
else
result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location);
if (!result.isOK())
return result;
//check the standard path name restrictions
int segmentCount = location.segmentCount();
for (int i = 0; i < segmentCount; i++) {
result = validateName(location.segment(i), resource.getType());
if (!result.isOK())
return result;
}
//if the location doesn't have a device, see if the OS will assign one
if (location.getDevice() == null)
location = new Path(location.toFile().getAbsolutePath());
// test if the given location overlaps the platform metadata location
IPath testLocation = getMetaArea().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.invalidLocation", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
//test if the given path overlaps the location of the given project
testLocation = resource.getProject().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.locationOverlapsProject", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
//check that the location is absolute
//Note: this check must be done last because we tolerate this condition in createLink
if (!location.isAbsolute()) {
if (location.segmentCount() > 0)
message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$
else
message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message);
}
// Iterate over each known project and ensure that the location does not
// conflict with any project locations or linked resource locations
IProject[] projects = getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
IProject project = (IProject) projects[i];
// since we are iterating over the project in the workspace, we
// know that they have been created before and must have a description
IProjectDescription desc = ((Project) project).internalGetDescription();
testLocation = desc.getLocation();
// if the project uses the default location then continue
if (testLocation == null)
continue;
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message);
}
//iterate over linked resources and check for overlap
if (!project.isOpen())
continue;
IResource[] children = null;
try {
children = project.members();
} catch (CoreException e) {
//ignore projects that cannot be accessed
}
if (children == null)
continue;
for (int j = 0; j < children.length; j++) {
if (children[j].isLinked()) {
testLocation = children[j].getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message);
}
}
}
}
return ResourceStatus.OK_STATUS;
}
| public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) {
//check that the resource has a project as its parent
String message;
IContainer parent = resource.getParent();
if (parent == null || parent.getType() != IResource.PROJECT) {
message = Policy.bind("links.parentNotProject", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
if (!parent.isAccessible()) {
message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
IPath location = getPathVariableManager().resolvePath(unresolvedLocation);
//check nature veto
String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds();
IStatus result = getNatureManager().validateLinkCreation(natureIds);
if (!result.isOK())
return result;
//check team provider veto
if (resource.getType() == IResource.FILE)
result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location);
else
result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location);
if (!result.isOK())
return result;
//check the standard path name restrictions
int segmentCount = location.segmentCount();
for (int i = 0; i < segmentCount; i++) {
result = validateName(location.segment(i), resource.getType());
if (!result.isOK())
return result;
}
//if the location doesn't have a device, see if the OS will assign one
if (location.getDevice() == null)
location = new Path(location.toFile().getAbsolutePath());
// test if the given location overlaps the platform metadata location
IPath testLocation = getMetaArea().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.invalidLocation", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
//test if the given path overlaps the location of the given project
testLocation = resource.getProject().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.locationOverlapsProject", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
//check that the location is absolute
//Note: this check must be done last because we tolerate this condition in createLink
if (!location.isAbsolute()) {
if (location.segmentCount() > 0)
message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$
else
message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message);
}
// Iterate over each known project and ensure that the location does not
// conflict with any project locations or linked resource locations
IProject[] projects = getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
IProject project = (IProject) projects[i];
// since we are iterating over the project in the workspace, we
// know that they have been created before and must have a description
IProjectDescription desc = ((Project) project).internalGetDescription();
testLocation = desc.getLocation();
if (testLocation != null && isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message);
}
//iterate over linked resources and check for overlap
if (!project.isOpen())
continue;
IResource[] children = null;
try {
children = project.members();
} catch (CoreException e) {
//ignore projects that cannot be accessed
}
if (children == null)
continue;
for (int j = 0; j < children.length; j++) {
if (children[j].isLinked()) {
testLocation = children[j].getLocation();
if (testLocation != null && isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message);
}
}
}
}
return ResourceStatus.OK_STATUS;
}
|
diff --git a/com.aptana.rdt.ui/src/com/aptana/rdt/internal/ui/text/correction/QuickFixProcessor.java b/com.aptana.rdt.ui/src/com/aptana/rdt/internal/ui/text/correction/QuickFixProcessor.java
index 38a245af..68cefa17 100644
--- a/com.aptana.rdt.ui/src/com/aptana/rdt/internal/ui/text/correction/QuickFixProcessor.java
+++ b/com.aptana.rdt.ui/src/com/aptana/rdt/internal/ui/text/correction/QuickFixProcessor.java
@@ -1,128 +1,128 @@
package com.aptana.rdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.jruby.ast.ClassNode;
import org.jruby.ast.DefnNode;
import org.jruby.ast.ModuleNode;
import org.jruby.ast.Node;
import org.jruby.ast.visitor.rewriter.DefaultFormatHelper;
import org.jruby.ast.visitor.rewriter.FormatHelper;
import org.jruby.ast.visitor.rewriter.ReWriteVisitor;
import org.rubypeople.rdt.core.IRubyScript;
import org.rubypeople.rdt.core.compiler.IProblem;
import org.rubypeople.rdt.core.formatter.Indents;
import org.rubypeople.rdt.internal.formatter.IndentationState;
import org.rubypeople.rdt.internal.ti.util.ClosestSpanningNodeLocator;
import org.rubypeople.rdt.internal.ti.util.INodeAcceptor;
import org.rubypeople.rdt.internal.ui.rubyeditor.ASTProvider;
import org.rubypeople.rdt.refactoring.core.NodeFactory;
import org.rubypeople.rdt.ui.text.ruby.IInvocationContext;
import org.rubypeople.rdt.ui.text.ruby.IProblemLocation;
import org.rubypeople.rdt.ui.text.ruby.IQuickFixProcessor;
import org.rubypeople.rdt.ui.text.ruby.IRubyCompletionProposal;
import com.aptana.rdt.internal.parser.warnings.ConstantNamingConvention;
import com.aptana.rdt.internal.parser.warnings.MethodMissingWithoutRespondTo;
import com.aptana.rdt.internal.parser.warnings.MisspelledConstructorVisitor;
public class QuickFixProcessor implements IQuickFixProcessor {
public IRubyCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
if (locations == null || locations.length == 0) {
return null;
}
HashSet<Integer> handledProblems = new HashSet<Integer>(locations.length);
ArrayList<IRubyCompletionProposal> resultingCollections = new ArrayList<IRubyCompletionProposal>();
for (int i = 0; i < locations.length; i++) {
IProblemLocation curr = locations[i];
Integer id = new Integer(curr.getProblemId());
if (handledProblems.add(id)) {
process(context, curr, resultingCollections);
}
}
return (IRubyCompletionProposal[]) resultingCollections.toArray(new IRubyCompletionProposal[resultingCollections.size()]);
}
private void process(IInvocationContext context, IProblemLocation problem, Collection<IRubyCompletionProposal> proposals) throws CoreException {
int id = problem.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateField:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case MisspelledConstructorVisitor.PROBLEM_ID:
LocalCorrectionsSubProcessor.addReplacementProposal("initialize\n", "Rename to 'initialize'", problem, proposals);
break;
case ConstantNamingConvention.PROBLEM_ID:
IRubyScript script = context.getRubyScript();
String src = script.getSource();
String constName = src.substring(problem.getOffset(), problem.getOffset() + problem.getLength());
LocalCorrectionsSubProcessor.addReplacementProposal(constName.toUpperCase(), "Convert to all uppercase", problem, proposals);
break;
case MethodMissingWithoutRespondTo.PROBLEM_ID:
// FIXME Only do this stuff when we apply the proposal! Don't do all this work just to create the proposal...
script = context.getRubyScript();
src = script.getSource();
int offset = 0;
Node rootNode = ASTProvider.getASTProvider().getAST(script, ASTProvider.WAIT_YES, null);
Node typeNode = ClosestSpanningNodeLocator.Instance().findClosestSpanner(rootNode, problem.getOffset(), new INodeAcceptor() {
public boolean doesAccept(Node node) {
return node instanceof ClassNode || node instanceof ModuleNode;
}
});
if (typeNode instanceof ClassNode) {
ClassNode classNode = (ClassNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
} else if (typeNode instanceof ModuleNode) {
ModuleNode classNode = (ModuleNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
}
DefnNode methodNode = NodeFactory.createMethodNode("respond_to?", new String[] {"symbol", "include_private = false"}, null);
Node insert = NodeFactory.createBlockNode(true, NodeFactory.createNewLineNode(methodNode));
String text = ReWriteVisitor.createCodeFromNode(insert, src, getFormatHelper());
// Figure out indent at offset and apply that to each line of text and at end of text
String line = src.substring(0, src.indexOf("\n", offset));
line = line.substring(line.lastIndexOf("\n") + 1);
Map options = script.getRubyProject().getOptions(true);
String indent = Indents.extractIndentString(line, options);
text = indent + text;
- text = text.replaceAll("\\n", "\n" + indent);
text = text + "\n";
+ text = text.replaceAll("\\n", "\n" + indent);
LocalCorrectionsSubProcessor.addReplacementProposal(offset, 0, text, "Add respond_to? method stub", proposals);
break;
default:
}
}
protected FormatHelper getFormatHelper() {
return new DefaultFormatHelper();
}
public boolean hasCorrections(IRubyScript unit, int problemId) {
switch (problemId) {
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateField:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
case MisspelledConstructorVisitor.PROBLEM_ID:
case ConstantNamingConvention.PROBLEM_ID:
case MethodMissingWithoutRespondTo.PROBLEM_ID:
return true;
default:
return false;
}
}
}
| false | true | private void process(IInvocationContext context, IProblemLocation problem, Collection<IRubyCompletionProposal> proposals) throws CoreException {
int id = problem.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateField:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case MisspelledConstructorVisitor.PROBLEM_ID:
LocalCorrectionsSubProcessor.addReplacementProposal("initialize\n", "Rename to 'initialize'", problem, proposals);
break;
case ConstantNamingConvention.PROBLEM_ID:
IRubyScript script = context.getRubyScript();
String src = script.getSource();
String constName = src.substring(problem.getOffset(), problem.getOffset() + problem.getLength());
LocalCorrectionsSubProcessor.addReplacementProposal(constName.toUpperCase(), "Convert to all uppercase", problem, proposals);
break;
case MethodMissingWithoutRespondTo.PROBLEM_ID:
// FIXME Only do this stuff when we apply the proposal! Don't do all this work just to create the proposal...
script = context.getRubyScript();
src = script.getSource();
int offset = 0;
Node rootNode = ASTProvider.getASTProvider().getAST(script, ASTProvider.WAIT_YES, null);
Node typeNode = ClosestSpanningNodeLocator.Instance().findClosestSpanner(rootNode, problem.getOffset(), new INodeAcceptor() {
public boolean doesAccept(Node node) {
return node instanceof ClassNode || node instanceof ModuleNode;
}
});
if (typeNode instanceof ClassNode) {
ClassNode classNode = (ClassNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
} else if (typeNode instanceof ModuleNode) {
ModuleNode classNode = (ModuleNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
}
DefnNode methodNode = NodeFactory.createMethodNode("respond_to?", new String[] {"symbol", "include_private = false"}, null);
Node insert = NodeFactory.createBlockNode(true, NodeFactory.createNewLineNode(methodNode));
String text = ReWriteVisitor.createCodeFromNode(insert, src, getFormatHelper());
// Figure out indent at offset and apply that to each line of text and at end of text
String line = src.substring(0, src.indexOf("\n", offset));
line = line.substring(line.lastIndexOf("\n") + 1);
Map options = script.getRubyProject().getOptions(true);
String indent = Indents.extractIndentString(line, options);
text = indent + text;
text = text.replaceAll("\\n", "\n" + indent);
text = text + "\n";
LocalCorrectionsSubProcessor.addReplacementProposal(offset, 0, text, "Add respond_to? method stub", proposals);
break;
default:
}
| private void process(IInvocationContext context, IProblemLocation problem, Collection<IRubyCompletionProposal> proposals) throws CoreException {
int id = problem.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateField:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case MisspelledConstructorVisitor.PROBLEM_ID:
LocalCorrectionsSubProcessor.addReplacementProposal("initialize\n", "Rename to 'initialize'", problem, proposals);
break;
case ConstantNamingConvention.PROBLEM_ID:
IRubyScript script = context.getRubyScript();
String src = script.getSource();
String constName = src.substring(problem.getOffset(), problem.getOffset() + problem.getLength());
LocalCorrectionsSubProcessor.addReplacementProposal(constName.toUpperCase(), "Convert to all uppercase", problem, proposals);
break;
case MethodMissingWithoutRespondTo.PROBLEM_ID:
// FIXME Only do this stuff when we apply the proposal! Don't do all this work just to create the proposal...
script = context.getRubyScript();
src = script.getSource();
int offset = 0;
Node rootNode = ASTProvider.getASTProvider().getAST(script, ASTProvider.WAIT_YES, null);
Node typeNode = ClosestSpanningNodeLocator.Instance().findClosestSpanner(rootNode, problem.getOffset(), new INodeAcceptor() {
public boolean doesAccept(Node node) {
return node instanceof ClassNode || node instanceof ModuleNode;
}
});
if (typeNode instanceof ClassNode) {
ClassNode classNode = (ClassNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
} else if (typeNode instanceof ModuleNode) {
ModuleNode classNode = (ModuleNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
}
DefnNode methodNode = NodeFactory.createMethodNode("respond_to?", new String[] {"symbol", "include_private = false"}, null);
Node insert = NodeFactory.createBlockNode(true, NodeFactory.createNewLineNode(methodNode));
String text = ReWriteVisitor.createCodeFromNode(insert, src, getFormatHelper());
// Figure out indent at offset and apply that to each line of text and at end of text
String line = src.substring(0, src.indexOf("\n", offset));
line = line.substring(line.lastIndexOf("\n") + 1);
Map options = script.getRubyProject().getOptions(true);
String indent = Indents.extractIndentString(line, options);
text = indent + text;
text = text + "\n";
text = text.replaceAll("\\n", "\n" + indent);
LocalCorrectionsSubProcessor.addReplacementProposal(offset, 0, text, "Add respond_to? method stub", proposals);
break;
default:
}
|
diff --git a/src/com/android/email/activity/MessageListItem.java b/src/com/android/email/activity/MessageListItem.java
index d69ab18b..8d6eaea8 100644
--- a/src/com/android/email/activity/MessageListItem.java
+++ b/src/com/android/email/activity/MessageListItem.java
@@ -1,507 +1,511 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity;
import com.android.email.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.text.Layout.Alignment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.format.DateUtils;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* This custom View is the list item for the MessageList activity, and serves two purposes:
* 1. It's a container to store message metadata (e.g. the ids of the message, mailbox, & account)
* 2. It handles internal clicks such as the checkbox or the favorite star
*/
public class MessageListItem extends View {
// Note: messagesAdapter directly fiddles with these fields.
/* package */ long mMessageId;
/* package */ long mMailboxId;
/* package */ long mAccountId;
private MessagesAdapter mAdapter;
private boolean mDownEvent;
public static final String MESSAGE_LIST_ITEMS_CLIP_LABEL =
"com.android.email.MESSAGE_LIST_ITEMS";
public MessageListItem(Context context) {
super(context);
init(context);
}
public MessageListItem(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MessageListItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
// We always show two lines of subject/snippet
private static final int MAX_SUBJECT_SNIPPET_LINES = 2;
// Narrow mode shows sender/snippet and time/favorite stacked to save real estate; due to this,
// it is also somewhat taller
private static final int MODE_NARROW = 1;
// Wide mode shows sender, snippet, time, and favorite spread out across the screen
private static final int MODE_WIDE = 2;
// Sentinel indicating that the view needs layout
public static final int NEEDS_LAYOUT = -1;
private static boolean sInit = false;
private static final TextPaint sDefaultPaint = new TextPaint();
private static final TextPaint sBoldPaint = new TextPaint();
private static final TextPaint sDatePaint = new TextPaint();
private static Bitmap sAttachmentIcon;
private static Bitmap sInviteIcon;
private static Bitmap sFavoriteIconOff;
private static Bitmap sFavoriteIconOn;
private static int sFavoriteIconWidth;
private static Bitmap sSelectedIconOn;
private static Bitmap sSelectedIconOff;
private static String sSubjectSnippetDivider;
public String mSender;
public CharSequence mText;
public String mSnippet;
public String mSubject;
public boolean mRead;
public long mTimestamp;
public boolean mHasAttachment = false;
public boolean mHasInvite = true;
public boolean mIsFavorite = false;
/** {@link Paint} for account color chips. null if no chips should be drawn. */
public Paint mColorChipPaint;
private int mMode = -1;
private int mViewWidth = 0;
private int mViewHeight = 0;
private int mSenderSnippetWidth;
private int mSnippetWidth;
private int mDateFaveWidth;
private static int sCheckboxHitWidth;
private static int sDateIconWidthWide;
private static int sDateIconWidthNarrow;
private static int sFavoriteHitWidth;
private static int sFavoritePaddingRight;
private static int sSenderPaddingTopNarrow;
private static int sSenderWidth;
private static int sPaddingLarge;
private static int sPaddingVerySmall;
private static int sPaddingSmall;
private static int sPaddingMedium;
private static int sTextSize;
private static int sItemHeightWide;
private static int sItemHeightNarrow;
private static int sMinimumWidthWideMode;
private static int sColorTipWidth;
private static int sColorTipHeight;
private static int sColorTipRightMarginOnNarrow;
private static int sColorTipRightMarginOnWide;
public int mSnippetLineCount = NEEDS_LAYOUT;
private final CharSequence[] mSnippetLines = new CharSequence[MAX_SUBJECT_SNIPPET_LINES];
private CharSequence mFormattedSender;
private CharSequence mFormattedDate;
private void init(Context context) {
if (!sInit) {
Resources r = context.getResources();
sSubjectSnippetDivider = r.getString(R.string.message_list_subject_snippet_divider);
sCheckboxHitWidth =
r.getDimensionPixelSize(R.dimen.message_list_item_checkbox_hit_width);
sFavoriteHitWidth =
r.getDimensionPixelSize(R.dimen.message_list_item_favorite_hit_width);
sFavoritePaddingRight =
r.getDimensionPixelSize(R.dimen.message_list_item_favorite_padding_right);
sSenderPaddingTopNarrow =
r.getDimensionPixelSize(R.dimen.message_list_item_sender_padding_top_narrow);
sDateIconWidthWide =
r.getDimensionPixelSize(R.dimen.message_list_item_date_icon_width_wide);
sDateIconWidthNarrow =
r.getDimensionPixelSize(R.dimen.message_list_item_date_icon_width_narrow);
sSenderWidth =
r.getDimensionPixelSize(R.dimen.message_list_item_sender_width);
sPaddingLarge =
r.getDimensionPixelSize(R.dimen.message_list_item_padding_large);
sPaddingMedium =
r.getDimensionPixelSize(R.dimen.message_list_item_padding_medium);
sPaddingSmall =
r.getDimensionPixelSize(R.dimen.message_list_item_padding_small);
sPaddingVerySmall =
r.getDimensionPixelSize(R.dimen.message_list_item_padding_very_small);
sTextSize =
r.getDimensionPixelSize(R.dimen.message_list_item_text_size);
sItemHeightWide =
r.getDimensionPixelSize(R.dimen.message_list_item_height_wide);
sItemHeightNarrow =
r.getDimensionPixelSize(R.dimen.message_list_item_height_narrow);
sMinimumWidthWideMode =
r.getDimensionPixelSize(R.dimen.message_list_item_minimum_width_wide_mode);
sColorTipWidth =
r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_width);
sColorTipHeight =
r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_height);
sColorTipRightMarginOnNarrow =
r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_right_margin_on_narrow);
sColorTipRightMarginOnWide =
r.getDimensionPixelSize(R.dimen.message_list_item_color_tip_right_margin_on_wide);
sDefaultPaint.setTypeface(Typeface.DEFAULT);
sDefaultPaint.setTextSize(sTextSize);
sDefaultPaint.setAntiAlias(true);
sDatePaint.setTypeface(Typeface.DEFAULT);
sDatePaint.setTextSize(sTextSize - 1);
sDatePaint.setAntiAlias(true);
sDatePaint.setTextAlign(Align.RIGHT);
sBoldPaint.setTypeface(Typeface.DEFAULT_BOLD);
sBoldPaint.setTextSize(sTextSize);
sBoldPaint.setAntiAlias(true);
sAttachmentIcon = BitmapFactory.decodeResource(r, R.drawable.ic_mms_attachment_small);
sInviteIcon = BitmapFactory.decodeResource(r, R.drawable.ic_calendar_event_small);
sFavoriteIconOff =
BitmapFactory.decodeResource(r, R.drawable.btn_star_big_buttonless_dark_off);
sFavoriteIconOn =
BitmapFactory.decodeResource(r, R.drawable.btn_star_big_buttonless_dark_on);
sSelectedIconOff =
BitmapFactory.decodeResource(r, R.drawable.btn_check_off_normal_holo_light);
sSelectedIconOn =
BitmapFactory.decodeResource(r, R.drawable.btn_check_on_normal_holo_light);
sFavoriteIconWidth = sFavoriteIconOff.getWidth();
sInit = true;
}
}
/**
* Determine the mode of this view (WIDE or NORMAL)
*
* @param width The width of the view
* @return The mode of the view
*/
private int getViewMode(int width) {
int mode = MODE_NARROW;
if (width > sMinimumWidthWideMode) {
mode = MODE_WIDE;
}
return mode;
}
private void calculateDrawingData() {
SpannableStringBuilder ssb = new SpannableStringBuilder();
boolean hasSubject = false;
if (!TextUtils.isEmpty(mSubject)) {
SpannableString ss = new SpannableString(mSubject);
ss.setSpan(new StyleSpan(mRead ? Typeface.NORMAL : Typeface.BOLD), 0, ss.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(ss);
hasSubject = true;
}
if (!TextUtils.isEmpty(mSnippet)) {
if (hasSubject) {
ssb.append(sSubjectSnippetDivider);
}
ssb.append(mSnippet);
}
mText = ssb;
if (mMode == MODE_WIDE) {
mDateFaveWidth = sFavoriteHitWidth + sDateIconWidthWide;
} else {
mDateFaveWidth = sDateIconWidthNarrow;
}
mSenderSnippetWidth = mViewWidth - mDateFaveWidth - sCheckboxHitWidth;
// In wide mode, we use 3/4 for snippet and 1/4 for sender
mSnippetWidth = mSenderSnippetWidth;
if (mMode == MODE_WIDE) {
mSnippetWidth = mSenderSnippetWidth - sSenderWidth - sPaddingLarge;
}
// Create a StaticLayout with our snippet to get the line breaks
StaticLayout layout = new StaticLayout(mText, 0, mText.length(), sDefaultPaint,
mSnippetWidth, Alignment.ALIGN_NORMAL, 1, 0, true);
// Get the number of lines needed to render the whole snippet
mSnippetLineCount = layout.getLineCount();
// Go through our maximum number of lines, and save away what we'll end up displaying
// for those lines
for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) {
int start = layout.getLineStart(i);
if (i == MAX_SUBJECT_SNIPPET_LINES - 1) {
int end = mText.length() - 1;
if (start > end) continue;
// For the final line, ellipsize the text to our width
mSnippetLines[i] = TextUtils.ellipsize(mText.subSequence(start, end), sDefaultPaint,
mSnippetWidth, TruncateAt.END);
} else {
// Just extract from start to end
mSnippetLines[i] = mText.subSequence(start, layout.getLineEnd(i));
}
}
// Now, format the sender for its width
TextPaint senderPaint = mRead ? sDefaultPaint : sBoldPaint;
int senderWidth = (mMode == MODE_WIDE) ? sSenderWidth : mSenderSnippetWidth;
// And get the ellipsized string for the calculated width
mFormattedSender = TextUtils.ellipsize(mSender, senderPaint, senderWidth, TruncateAt.END);
// Get a nicely formatted date string (relative to today)
String date = DateUtils.getRelativeTimeSpanString(getContext(), mTimestamp).toString();
// And make it fit to our size
mFormattedDate = TextUtils.ellipsize(date, sDatePaint, sDateIconWidthWide, TruncateAt.END);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (widthMeasureSpec != 0 || mViewWidth == 0) {
mViewWidth = MeasureSpec.getSize(widthMeasureSpec);
int mode = getViewMode(mViewWidth);
if (mode != mMode) {
// If the mode has changed, set the snippet line count to indicate layout required
mMode = mode;
mSnippetLineCount = NEEDS_LAYOUT;
}
mViewHeight = measureHeight(heightMeasureSpec, mMode);
}
setMeasuredDimension(mViewWidth, mViewHeight);
}
/**
* Determine the height of this view
*
* @param measureSpec A measureSpec packed into an int
* @param mode The current mode of this view
* @return The height of the view, honoring constraints from measureSpec
*/
private int measureHeight(int measureSpec, int mode) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
if (mMode == MODE_WIDE) {
result = sItemHeightWide;
} else {
result = sItemHeightNarrow;
}
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
if (mSnippetLineCount == NEEDS_LAYOUT) {
calculateDrawingData();
}
// Snippet starts at right of checkbox
int snippetX = sCheckboxHitWidth;
int snippetY;
int lineHeight = (int)sDefaultPaint.getFontSpacing() + sPaddingVerySmall;
FontMetricsInt fontMetrics = sDefaultPaint.getFontMetricsInt();
int ascent = fontMetrics.ascent;
int descent = fontMetrics.descent;
int senderY;
if (mMode == MODE_WIDE) {
// Get the right starting point for the snippet
snippetX += sSenderWidth + sPaddingLarge;
// And center the sender and snippet
senderY = (mViewHeight - descent - ascent) / 2;
snippetY = ((mViewHeight - (2 * lineHeight)) / 2) - ascent;
} else {
senderY = -ascent + sSenderPaddingTopNarrow;
snippetY = senderY + lineHeight + sPaddingVerySmall;
}
// Draw the color chip
if (mColorChipPaint != null) {
final int rightMargin = (mMode == MODE_WIDE)
? sColorTipRightMarginOnWide : sColorTipRightMarginOnNarrow;
final int x = mViewWidth - rightMargin - sColorTipWidth;
canvas.drawRect(x, 0, x + sColorTipWidth, sColorTipHeight, mColorChipPaint);
}
// Draw the checkbox
int checkboxLeft = (sCheckboxHitWidth - sSelectedIconOff.getWidth()) / 2;
int checkboxTop = (mViewHeight - sSelectedIconOff.getHeight()) / 2;
canvas.drawBitmap(mAdapter.isSelected(this) ? sSelectedIconOn : sSelectedIconOff,
checkboxLeft, checkboxTop, sDefaultPaint);
// Draw the sender name
canvas.drawText(mFormattedSender, 0, mFormattedSender.length(), sCheckboxHitWidth, senderY,
mRead ? sDefaultPaint : sBoldPaint);
// Draw each of the snippet lines
int subjectEnd = (mSubject == null) ? 0 : mSubject.length();
int lineStart = 0;
TextPaint subjectPaint = mRead ? sDefaultPaint : sBoldPaint;
for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) {
CharSequence line = mSnippetLines[i];
int drawX = snippetX;
if (line != null) {
int defaultPaintStart = 0;
if (lineStart <= subjectEnd) {
int boldPaintEnd = subjectEnd - lineStart;
if (boldPaintEnd > line.length()) {
boldPaintEnd = line.length();
}
// From 0 to end, do in bold or default depending on the read flag
canvas.drawText(line, 0, boldPaintEnd, drawX, snippetY, subjectPaint);
defaultPaintStart = boldPaintEnd;
drawX += subjectPaint.measureText(line, 0, boldPaintEnd);
}
canvas.drawText(line, defaultPaintStart, line.length(), drawX, snippetY,
sDefaultPaint);
snippetY += lineHeight;
lineStart += line.length();
}
}
// Draw the attachment and invite icons, if necessary
int datePaddingRight;
if (mMode == MODE_WIDE) {
datePaddingRight = sFavoriteHitWidth;
} else {
datePaddingRight = sPaddingLarge;
}
int left = mViewWidth - datePaddingRight - (int)sDefaultPaint.measureText(mFormattedDate,
0, mFormattedDate.length()) - sPaddingMedium;
+ int iconTop;
if (mHasAttachment) {
left -= sAttachmentIcon.getWidth() + sPaddingSmall;
- int iconTop;
if (mMode == MODE_WIDE) {
iconTop = (mViewHeight - sAttachmentIcon.getHeight()) / 2;
} else {
iconTop = senderY - sAttachmentIcon.getHeight();
}
canvas.drawBitmap(sAttachmentIcon, left, iconTop, sDefaultPaint);
}
if (mHasInvite) {
left -= sInviteIcon.getWidth() + sPaddingSmall;
- int iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2;
+ if (mMode == MODE_WIDE) {
+ iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2;
+ } else {
+ iconTop = senderY - sInviteIcon.getHeight();
+ }
canvas.drawBitmap(sInviteIcon, left, iconTop, sDefaultPaint);
}
// Draw the date
canvas.drawText(mFormattedDate, 0, mFormattedDate.length(), mViewWidth - datePaddingRight,
senderY, sDatePaint);
// Draw the favorite icon
int faveLeft = mViewWidth - sFavoriteIconWidth;
if (mMode == MODE_WIDE) {
faveLeft -= sFavoritePaddingRight;
} else {
faveLeft -= sPaddingLarge;
}
int faveTop = (mViewHeight - sFavoriteIconOff.getHeight()) / 2;
if (mMode == MODE_NARROW) {
faveTop += sSenderPaddingTopNarrow;
}
canvas.drawBitmap(mIsFavorite ? sFavoriteIconOn : sFavoriteIconOff, faveLeft, faveTop,
sDefaultPaint);
}
/**
* Called by the adapter at bindView() time
*
* @param adapter the adapter that creates this view
*/
public void bindViewInit(MessagesAdapter adapter) {
mAdapter = adapter;
}
/**
* Overriding this method allows us to "catch" clicks in the checkbox or star
* and process them accordingly.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean handled = false;
int touchX = (int) event.getX();
int checkRight = sCheckboxHitWidth;
int starLeft = mViewWidth - sFavoriteHitWidth;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (touchX < checkRight || touchX > starLeft) {
mDownEvent = true;
if ((touchX < checkRight) || (touchX > starLeft)) {
handled = true;
}
}
break;
case MotionEvent.ACTION_CANCEL:
mDownEvent = false;
break;
case MotionEvent.ACTION_UP:
if (mDownEvent) {
if (touchX < checkRight) {
mAdapter.toggleSelected(this);
handled = true;
} else if (touchX > starLeft) {
mIsFavorite = !mIsFavorite;
mAdapter.updateFavorite(this, mIsFavorite);
handled = true;
}
}
break;
}
if (handled) {
invalidate();
} else {
handled = super.onTouchEvent(event);
}
return handled;
}
}
| false | true | protected void onDraw(Canvas canvas) {
if (mSnippetLineCount == NEEDS_LAYOUT) {
calculateDrawingData();
}
// Snippet starts at right of checkbox
int snippetX = sCheckboxHitWidth;
int snippetY;
int lineHeight = (int)sDefaultPaint.getFontSpacing() + sPaddingVerySmall;
FontMetricsInt fontMetrics = sDefaultPaint.getFontMetricsInt();
int ascent = fontMetrics.ascent;
int descent = fontMetrics.descent;
int senderY;
if (mMode == MODE_WIDE) {
// Get the right starting point for the snippet
snippetX += sSenderWidth + sPaddingLarge;
// And center the sender and snippet
senderY = (mViewHeight - descent - ascent) / 2;
snippetY = ((mViewHeight - (2 * lineHeight)) / 2) - ascent;
} else {
senderY = -ascent + sSenderPaddingTopNarrow;
snippetY = senderY + lineHeight + sPaddingVerySmall;
}
// Draw the color chip
if (mColorChipPaint != null) {
final int rightMargin = (mMode == MODE_WIDE)
? sColorTipRightMarginOnWide : sColorTipRightMarginOnNarrow;
final int x = mViewWidth - rightMargin - sColorTipWidth;
canvas.drawRect(x, 0, x + sColorTipWidth, sColorTipHeight, mColorChipPaint);
}
// Draw the checkbox
int checkboxLeft = (sCheckboxHitWidth - sSelectedIconOff.getWidth()) / 2;
int checkboxTop = (mViewHeight - sSelectedIconOff.getHeight()) / 2;
canvas.drawBitmap(mAdapter.isSelected(this) ? sSelectedIconOn : sSelectedIconOff,
checkboxLeft, checkboxTop, sDefaultPaint);
// Draw the sender name
canvas.drawText(mFormattedSender, 0, mFormattedSender.length(), sCheckboxHitWidth, senderY,
mRead ? sDefaultPaint : sBoldPaint);
// Draw each of the snippet lines
int subjectEnd = (mSubject == null) ? 0 : mSubject.length();
int lineStart = 0;
TextPaint subjectPaint = mRead ? sDefaultPaint : sBoldPaint;
for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) {
CharSequence line = mSnippetLines[i];
int drawX = snippetX;
if (line != null) {
int defaultPaintStart = 0;
if (lineStart <= subjectEnd) {
int boldPaintEnd = subjectEnd - lineStart;
if (boldPaintEnd > line.length()) {
boldPaintEnd = line.length();
}
// From 0 to end, do in bold or default depending on the read flag
canvas.drawText(line, 0, boldPaintEnd, drawX, snippetY, subjectPaint);
defaultPaintStart = boldPaintEnd;
drawX += subjectPaint.measureText(line, 0, boldPaintEnd);
}
canvas.drawText(line, defaultPaintStart, line.length(), drawX, snippetY,
sDefaultPaint);
snippetY += lineHeight;
lineStart += line.length();
}
}
// Draw the attachment and invite icons, if necessary
int datePaddingRight;
if (mMode == MODE_WIDE) {
datePaddingRight = sFavoriteHitWidth;
} else {
datePaddingRight = sPaddingLarge;
}
int left = mViewWidth - datePaddingRight - (int)sDefaultPaint.measureText(mFormattedDate,
0, mFormattedDate.length()) - sPaddingMedium;
if (mHasAttachment) {
left -= sAttachmentIcon.getWidth() + sPaddingSmall;
int iconTop;
if (mMode == MODE_WIDE) {
iconTop = (mViewHeight - sAttachmentIcon.getHeight()) / 2;
} else {
iconTop = senderY - sAttachmentIcon.getHeight();
}
canvas.drawBitmap(sAttachmentIcon, left, iconTop, sDefaultPaint);
}
if (mHasInvite) {
left -= sInviteIcon.getWidth() + sPaddingSmall;
int iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2;
canvas.drawBitmap(sInviteIcon, left, iconTop, sDefaultPaint);
}
// Draw the date
canvas.drawText(mFormattedDate, 0, mFormattedDate.length(), mViewWidth - datePaddingRight,
senderY, sDatePaint);
// Draw the favorite icon
int faveLeft = mViewWidth - sFavoriteIconWidth;
if (mMode == MODE_WIDE) {
faveLeft -= sFavoritePaddingRight;
} else {
faveLeft -= sPaddingLarge;
}
int faveTop = (mViewHeight - sFavoriteIconOff.getHeight()) / 2;
if (mMode == MODE_NARROW) {
faveTop += sSenderPaddingTopNarrow;
}
canvas.drawBitmap(mIsFavorite ? sFavoriteIconOn : sFavoriteIconOff, faveLeft, faveTop,
sDefaultPaint);
}
| protected void onDraw(Canvas canvas) {
if (mSnippetLineCount == NEEDS_LAYOUT) {
calculateDrawingData();
}
// Snippet starts at right of checkbox
int snippetX = sCheckboxHitWidth;
int snippetY;
int lineHeight = (int)sDefaultPaint.getFontSpacing() + sPaddingVerySmall;
FontMetricsInt fontMetrics = sDefaultPaint.getFontMetricsInt();
int ascent = fontMetrics.ascent;
int descent = fontMetrics.descent;
int senderY;
if (mMode == MODE_WIDE) {
// Get the right starting point for the snippet
snippetX += sSenderWidth + sPaddingLarge;
// And center the sender and snippet
senderY = (mViewHeight - descent - ascent) / 2;
snippetY = ((mViewHeight - (2 * lineHeight)) / 2) - ascent;
} else {
senderY = -ascent + sSenderPaddingTopNarrow;
snippetY = senderY + lineHeight + sPaddingVerySmall;
}
// Draw the color chip
if (mColorChipPaint != null) {
final int rightMargin = (mMode == MODE_WIDE)
? sColorTipRightMarginOnWide : sColorTipRightMarginOnNarrow;
final int x = mViewWidth - rightMargin - sColorTipWidth;
canvas.drawRect(x, 0, x + sColorTipWidth, sColorTipHeight, mColorChipPaint);
}
// Draw the checkbox
int checkboxLeft = (sCheckboxHitWidth - sSelectedIconOff.getWidth()) / 2;
int checkboxTop = (mViewHeight - sSelectedIconOff.getHeight()) / 2;
canvas.drawBitmap(mAdapter.isSelected(this) ? sSelectedIconOn : sSelectedIconOff,
checkboxLeft, checkboxTop, sDefaultPaint);
// Draw the sender name
canvas.drawText(mFormattedSender, 0, mFormattedSender.length(), sCheckboxHitWidth, senderY,
mRead ? sDefaultPaint : sBoldPaint);
// Draw each of the snippet lines
int subjectEnd = (mSubject == null) ? 0 : mSubject.length();
int lineStart = 0;
TextPaint subjectPaint = mRead ? sDefaultPaint : sBoldPaint;
for (int i = 0; i < MAX_SUBJECT_SNIPPET_LINES; i++) {
CharSequence line = mSnippetLines[i];
int drawX = snippetX;
if (line != null) {
int defaultPaintStart = 0;
if (lineStart <= subjectEnd) {
int boldPaintEnd = subjectEnd - lineStart;
if (boldPaintEnd > line.length()) {
boldPaintEnd = line.length();
}
// From 0 to end, do in bold or default depending on the read flag
canvas.drawText(line, 0, boldPaintEnd, drawX, snippetY, subjectPaint);
defaultPaintStart = boldPaintEnd;
drawX += subjectPaint.measureText(line, 0, boldPaintEnd);
}
canvas.drawText(line, defaultPaintStart, line.length(), drawX, snippetY,
sDefaultPaint);
snippetY += lineHeight;
lineStart += line.length();
}
}
// Draw the attachment and invite icons, if necessary
int datePaddingRight;
if (mMode == MODE_WIDE) {
datePaddingRight = sFavoriteHitWidth;
} else {
datePaddingRight = sPaddingLarge;
}
int left = mViewWidth - datePaddingRight - (int)sDefaultPaint.measureText(mFormattedDate,
0, mFormattedDate.length()) - sPaddingMedium;
int iconTop;
if (mHasAttachment) {
left -= sAttachmentIcon.getWidth() + sPaddingSmall;
if (mMode == MODE_WIDE) {
iconTop = (mViewHeight - sAttachmentIcon.getHeight()) / 2;
} else {
iconTop = senderY - sAttachmentIcon.getHeight();
}
canvas.drawBitmap(sAttachmentIcon, left, iconTop, sDefaultPaint);
}
if (mHasInvite) {
left -= sInviteIcon.getWidth() + sPaddingSmall;
if (mMode == MODE_WIDE) {
iconTop = (mViewHeight - sInviteIcon.getHeight()) / 2;
} else {
iconTop = senderY - sInviteIcon.getHeight();
}
canvas.drawBitmap(sInviteIcon, left, iconTop, sDefaultPaint);
}
// Draw the date
canvas.drawText(mFormattedDate, 0, mFormattedDate.length(), mViewWidth - datePaddingRight,
senderY, sDatePaint);
// Draw the favorite icon
int faveLeft = mViewWidth - sFavoriteIconWidth;
if (mMode == MODE_WIDE) {
faveLeft -= sFavoritePaddingRight;
} else {
faveLeft -= sPaddingLarge;
}
int faveTop = (mViewHeight - sFavoriteIconOff.getHeight()) / 2;
if (mMode == MODE_NARROW) {
faveTop += sSenderPaddingTopNarrow;
}
canvas.drawBitmap(mIsFavorite ? sFavoriteIconOn : sFavoriteIconOff, faveLeft, faveTop,
sDefaultPaint);
}
|
diff --git a/src/main/java/de/tudarmstadt/ukp/shibhttpclient/ShibHttpClient.java b/src/main/java/de/tudarmstadt/ukp/shibhttpclient/ShibHttpClient.java
index 020a91a..6713c46 100644
--- a/src/main/java/de/tudarmstadt/ukp/shibhttpclient/ShibHttpClient.java
+++ b/src/main/java/de/tudarmstadt/ukp/shibhttpclient/ShibHttpClient.java
@@ -1,507 +1,508 @@
/*******************************************************************************
* Copyright 2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Copyright 2013 Diamond Light Source 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 de.tudarmstadt.ukp.shibhttpclient;
import static de.tudarmstadt.ukp.shibhttpclient.Utils.unmarshallMessage;
import static de.tudarmstadt.ukp.shibhttpclient.Utils.xmlToString;
import static java.util.Arrays.asList;
import java.io.IOException;
import java.net.ProxySelector;
import java.security.GeneralSecurityException;
import java.util.List;
import javax.security.sasl.AuthenticationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.NonRepeatableRequestException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.StatusCode;
import org.opensaml.saml2.ecp.RelayState;
import org.opensaml.saml2.ecp.Response;
import org.opensaml.ws.soap.soap11.Body;
import org.opensaml.ws.soap.soap11.Envelope;
import org.opensaml.ws.soap.soap11.Header;
import org.opensaml.ws.soap.soap11.impl.EnvelopeBuilder;
import org.opensaml.ws.soap.soap11.impl.HeaderBuilder;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.parse.BasicParserPool;
import org.opensaml.xml.util.Base64;
/**
* Simple Shibbolethized {@link HttpClient} using basic HTTP username/password authentication to
* authenticate against a predefined IdP. The client indicates its ECP capability to the SP.
* Authentication happens automatically if the SP replies to any requesting using a PAOS
* authentication solicitation.
* <p>
* GET and HEAD requests work completely transparent using redirection. If another request is
* performed, the client tries a HEAD request to the specified URL first. If this results in an
* authentication request, a login is performed before the original request is executed.
*/
public class ShibHttpClient
implements HttpClient
{
private final Log log = LogFactory.getLog(getClass());
private static final String AUTH_IN_PROGRESS = ShibHttpClient.class.getName()
+ ".AUTH_IN_PROGRESS";
private static final String MIME_TYPE_PAOS = "application/vnd.paos+xml";
// private static final QName E_PAOS_REQUEST = new QName(SAMLConstants.PAOS_NS, "Request");
//
// private static final QName A_RESPONSE_CONSUMER_URL = new QName("responseConsumerURL");
private static final String HEADER_AUTHORIZATION = "Authorization";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String HEADER_ACCEPT = "Accept";
private static final String HEADER_PAOS = "PAOS";
private CloseableHttpClient client;
private BasicCookieStore cookieStore;
private String idpUrl;
private String username;
private String password;
private BasicParserPool parserPool;
private static final List<String> REDIRECTABLE = asList("HEAD", "GET");
/**
* Create a new client.
*
* @param aIdpUrl
* the URL of the IdP. Should probably by something ending in "/SAML2/SOAP/ECP"
* @param aUsername
* the user name to log into the IdP.
* @param aPassword
* the password to log in to the IdP.
* @param aAnyCert
* if {@code true} accept any certificate from any remote host. Otherwise,
* certificates need to be installed in the JRE.
*/
public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, boolean aAnyCert)
{
setIdpUrl(aIdpUrl);
setUsername(aUsername);
setPassword(aPassword);
// Use a pooling connection manager, because we'll have to do a call out to the IdP
// while still being in a connection with the SP
PoolingHttpClientConnectionManager connMgr;
if (aAnyCert) {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
PlainConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", plainsf)
.register("https", sslsf)
.build();
connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
}
catch (GeneralSecurityException e) {
// There shouldn't be any of these exceptions, because we do not use an actual
// keystore
throw new IllegalStateException(e);
}
}
else {
connMgr = new PoolingHttpClientConnectionManager();
}
connMgr.setMaxTotal(10);
connMgr.setDefaultMaxPerRoute(5);
// retrieve the JVM parameters for proxy state (do we have a proxy?)
SystemDefaultRoutePlanner sdrp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
// The client needs to remember the auth cookie
cookieStore = new BasicCookieStore();
RequestConfig globalRequestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
.build();
// Add the ECP/PAOS headers - needs to be added first so the cookie we get from
// the authentication can be handled by the RequestAddCookies interceptor later
HttpRequestPreprocessor preProcessor = new HttpRequestPreprocessor();
// Automatically log into IdP if SP requests this
HttpRequestPostprocessor postProcessor = new HttpRequestPostprocessor();
// build our client
client = HttpClients.custom()
.setConnectionManager(connMgr)
// use a proxy if one is specified for the JVM
.setRoutePlanner(sdrp)
// The client needs to remember the auth cookie
.setDefaultRequestConfig(globalRequestConfig)
.setDefaultCookieStore(cookieStore)
// Add the ECP/PAOS headers - needs to be added first so the cookie we get from
// the authentication can be handled by the RequestAddCookies interceptor later
.addInterceptorFirst(preProcessor)
// Automatically log into IdP if SP requests this
.addInterceptorFirst(postProcessor)
.build();
parserPool = new BasicParserPool();
parserPool.setNamespaceAware(true);
}
public void setIdpUrl(String aIdpUrl)
{
idpUrl = aIdpUrl;
}
public void setUsername(String aUsername)
{
username = aUsername;
}
public void setPassword(String aPassword)
{
password = aPassword;
}
@Override
public HttpParams getParams()
{
return client.getParams();
}
@Override
public ClientConnectionManager getConnectionManager()
{
return client.getConnectionManager();
}
@Override
public HttpResponse execute(HttpUriRequest aRequest)
throws IOException, ClientProtocolException
{
return client.execute(aRequest);
}
@Override
public HttpResponse execute(HttpUriRequest aRequest, HttpContext aContext)
throws IOException, ClientProtocolException
{
return client.execute(aRequest, aContext);
}
@Override
public HttpResponse execute(HttpHost aTarget, HttpRequest aRequest)
throws IOException, ClientProtocolException
{
return client.execute(aTarget, aRequest);
}
@Override
public HttpResponse execute(HttpHost aTarget, HttpRequest aRequest, HttpContext aContext)
throws IOException, ClientProtocolException
{
return client.execute(aTarget, aRequest, aContext);
}
@Override
public <T> T execute(HttpUriRequest aRequest, ResponseHandler<? extends T> aResponseHandler)
throws IOException, ClientProtocolException
{
return client.execute(aRequest, aResponseHandler);
}
@Override
public <T> T execute(HttpUriRequest aRequest, ResponseHandler<? extends T> aResponseHandler,
HttpContext aContext)
throws IOException, ClientProtocolException
{
return client.execute(aRequest, aResponseHandler, aContext);
}
@Override
public <T> T execute(HttpHost aTarget, HttpRequest aRequest,
ResponseHandler<? extends T> aResponseHandler)
throws IOException, ClientProtocolException
{
return client.execute(aTarget, aRequest, aResponseHandler);
}
@Override
public <T> T execute(HttpHost aTarget, HttpRequest aRequest,
ResponseHandler<? extends T> aResponseHandler, HttpContext aContext)
throws IOException, ClientProtocolException
{
return client.execute(aTarget, aRequest, aResponseHandler, aContext);
}
/**
* Add the ECP/PAOS headers to each outgoing request.
*/
private final class HttpRequestPreprocessor
implements HttpRequestInterceptor
{
@Override
public void process(final HttpRequest req, final HttpContext ctx)
throws HttpException, IOException
{
if (req.getRequestLine().getMethod() == "CONNECT") {
log.trace("Received CONNECT -- Likely to be a proxy request. Skipping pre-processor");
return;
}
req.addHeader(HEADER_ACCEPT, MIME_TYPE_PAOS);
req.addHeader(HEADER_PAOS, "ver=\"" + SAMLConstants.PAOS_NS + "\";\""
+ SAMLConstants.SAML20ECP_NS + "\"");
HttpRequest r = req;
if (req instanceof HttpRequestWrapper) { // does not forward request to original
r = ((HttpRequestWrapper) req).getOriginal();
}
// This request is not redirectable, so we better knock to see if authentication
// is necessary.
if (!REDIRECTABLE.contains(r.getRequestLine().getMethod())
&& r.getParams().isParameterFalse(AUTH_IN_PROGRESS)) {
// && !r.getRequestLine().getUri().startsWith(idpUrl)) {
log.trace("Unredirectable request [" + r.getRequestLine().getMethod()
+ "], trying to knock first at " + r.getRequestLine().getUri());
HttpHead knockRequest = new HttpHead(r.getRequestLine().getUri());
client.execute(knockRequest);
for (Cookie c : cookieStore.getCookies()) {
log.trace(c.toString());
}
log.trace("Knocked");
}
}
}
/**
* Analyze responses to detect POAS solicitations for an authentication. Answer these and then
* transparently proceeed with the original request.
*/
public final class HttpRequestPostprocessor
implements HttpResponseInterceptor
{
@Override
public void process(HttpResponse res, HttpContext ctx)
throws HttpException, IOException
{
HttpRequest originalRequest;
// check for RequestWrapper objects, retrieve the original request
if (ctx.getAttribute("http.request") instanceof HttpRequestWrapper) { // does not forward request to original
log.trace("RequestWrapper found");
originalRequest = (HttpRequest) ((HttpRequestWrapper) ctx.getAttribute("http.request")).getOriginal();
}
else { // use a basic HttpRequest because BasicHttpRequest objects cannot be recast to HttpUriRequest objects
originalRequest = (HttpRequest) ctx.getAttribute("http.request");
}
log.trace("Accessing [" + originalRequest.getRequestLine().getUri() + " "
+ originalRequest.getRequestLine().getMethod() + "]");
// -- Check if authentication is already in progress ----------------------------------
if (res.getParams().isParameterTrue(AUTH_IN_PROGRESS)) {
log.trace("Authentication in progress -- skipping post processor");
return;
}
// -- Check if authentication is necessary --------------------------------------------
boolean isSamlSoap = false;
if (res.getFirstHeader(HEADER_CONTENT_TYPE) != null) {
ContentType contentType = ContentType.parse(res.getFirstHeader(HEADER_CONTENT_TYPE)
.getValue());
isSamlSoap = MIME_TYPE_PAOS.equals(contentType.getMimeType());
}
if (!isSamlSoap) {
return;
}
log.trace("Detected login request");
// -- If the request was a HEAD request, we need to try again using a GET request ----
HttpResponse paosResponse = res;
if (originalRequest.getRequestLine().getMethod() == "HEAD") {
log.trace("Original request was a HEAD, restarting authenticiation with GET");
HttpGet authTriggerRequest = new HttpGet(originalRequest.getRequestLine().getUri());
authTriggerRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
paosResponse = client.execute(authTriggerRequest);
}
// -- Parse PAOS response -------------------------------------------------------------
Envelope initialLoginSoapResponse = (Envelope) unmarshallMessage(parserPool,
paosResponse.getEntity().getContent());
// -- Capture relay state (optional) --------------------------------------------------
RelayState relayState = null;
if (!initialLoginSoapResponse.getHeader()
.getUnknownXMLObjects(RelayState.DEFAULT_ELEMENT_NAME).isEmpty()) {
relayState = (RelayState) initialLoginSoapResponse.getHeader()
.getUnknownXMLObjects(RelayState.DEFAULT_ELEMENT_NAME).get(0);
relayState.detach();
log.trace("Relay state: captured");
}
// -- Capture response consumer -------------------------------------------------------
// // pick out the responseConsumerURL attribute value from the SP response so that
// // it can later be compared to the assertionConsumerURL sent from the IdP
// String responseConsumerURL = ((XSAny) initialLoginSoapResponse.getHeader()
// .getUnknownXMLObjects(E_PAOS_REQUEST).get(0)).getUnknownAttributes().get(
// A_RESPONSE_CONSUMER_URL);
// log.debug("responseConsumerURL: [" + responseConsumerURL + "]");
// -- Send log-in request to the IdP --------------------------------------------------
// Prepare the request to the IdP
log.debug("Logging in to IdP [" + idpUrl + "]");
Envelope idpLoginSoapRequest = new EnvelopeBuilder().buildObject();
Body b = initialLoginSoapResponse.getBody();
b.detach();
idpLoginSoapRequest.setBody(b);
// Try logging in to the IdP using HTTP BASIC authentication
HttpPost idpLoginRequest = new HttpPost(idpUrl);
idpLoginRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
idpLoginRequest.addHeader(HEADER_AUTHORIZATION,
"Basic " + Base64.encodeBytes((username + ":" + password).getBytes()));
idpLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapRequest)));
HttpResponse idpLoginResponse = client.execute(idpLoginRequest);
// -- Handle log-in response tfrom the IdP --------------------------------------------
log.debug("Status: " + idpLoginResponse.getStatusLine());
Envelope idpLoginSoapResponse = (Envelope) unmarshallMessage(parserPool,
idpLoginResponse.getEntity().getContent());
EntityUtils.consume(idpLoginResponse.getEntity());
String assertionConsumerServiceURL = ((Response) idpLoginSoapResponse.getHeader()
.getUnknownXMLObjects(Response.DEFAULT_ELEMENT_NAME).get(0))
.getAssertionConsumerServiceURL();
log.debug("assertionConsumerServiceURL: " + assertionConsumerServiceURL);
List<XMLObject> responses = idpLoginSoapResponse.getBody().getUnknownXMLObjects(
org.opensaml.saml2.core.Response.DEFAULT_ELEMENT_NAME);
if (!responses.isEmpty()) {
org.opensaml.saml2.core.Response response = (org.opensaml.saml2.core.Response) responses
.get(0);
// Get root code (?)
StatusCode sc = response.getStatus().getStatusCode();
while (sc.getStatusCode() != null) {
sc = sc.getStatusCode();
}
// Hm, they don't like us
if ("urn:oasis:names:tc:SAML:2.0:status:AuthnFailed".equals(sc.getValue())) {
throw new AuthenticationException(sc.getValue());
}
}
// compare the responseConsumerURL from the SP to the assertionConsumerServiceURL from
// the IdP and if they are not identical then send a SOAP fault to the SP
// if (false) {
// // Nice guys should send a fault to the SP - we are NOT nice yet
// }
// -- Forward ticket to the SP --------------------------------------------------------
// craft the package to send to the SP by copying the response from the IdP but
// removing the SOAP header sent by the IdP and instead putting in a new header that
// includes the relay state sent by the SP
Header header = new HeaderBuilder().buildObject();
header.getUnknownXMLObjects().clear();
if (relayState != null) {
header.getUnknownXMLObjects().add(relayState);
}
idpLoginSoapResponse.setHeader(header);
// push the response to the SP at the assertion consumer service URL included in
// the response from the IdP
log.debug("Logging in to SP");
HttpPost spLoginRequest = new HttpPost(assertionConsumerServiceURL);
spLoginRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
spLoginRequest.setHeader(HEADER_CONTENT_TYPE, MIME_TYPE_PAOS);
spLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapResponse)));
HttpClientParams.setRedirecting(spLoginRequest.getParams(), false);
HttpResponse spLoginResponse = client.execute(spLoginRequest);
log.debug("Status: " + spLoginResponse.getStatusLine());
log.debug("Authentication complete");
// -- Handle unredirectable cases -----------------------------------------------------
// If we get a redirection and the request is redirectable, then let the client redirect
// If the request is not redirectable, signal that the operation must be retried.
if (spLoginResponse.getStatusLine().getStatusCode() == 302
- && !REDIRECTABLE.contains(originalRequest.getRequestLine().getMethod())) {
+ && !REDIRECTABLE.contains(originalRequest.getRequestLine().getMethod())
+ && (originalRequest.getRequestLine().getMethod() != "CONNECT")) {
EntityUtils.consume(spLoginResponse.getEntity());
throw new NonRepeatableRequestException("Request of type [" +
originalRequest.getRequestLine().getMethod() + "] cannot be redirected");
}
// -- Transparently return response to original request -------------------------------
// Return response received after login as actual response to original caller
res.setEntity(spLoginResponse.getEntity());
res.setHeaders(spLoginResponse.getAllHeaders());
res.setStatusLine(spLoginResponse.getStatusLine());
}
}
}
| true | true | public void process(HttpResponse res, HttpContext ctx)
throws HttpException, IOException
{
HttpRequest originalRequest;
// check for RequestWrapper objects, retrieve the original request
if (ctx.getAttribute("http.request") instanceof HttpRequestWrapper) { // does not forward request to original
log.trace("RequestWrapper found");
originalRequest = (HttpRequest) ((HttpRequestWrapper) ctx.getAttribute("http.request")).getOriginal();
}
else { // use a basic HttpRequest because BasicHttpRequest objects cannot be recast to HttpUriRequest objects
originalRequest = (HttpRequest) ctx.getAttribute("http.request");
}
log.trace("Accessing [" + originalRequest.getRequestLine().getUri() + " "
+ originalRequest.getRequestLine().getMethod() + "]");
// -- Check if authentication is already in progress ----------------------------------
if (res.getParams().isParameterTrue(AUTH_IN_PROGRESS)) {
log.trace("Authentication in progress -- skipping post processor");
return;
}
// -- Check if authentication is necessary --------------------------------------------
boolean isSamlSoap = false;
if (res.getFirstHeader(HEADER_CONTENT_TYPE) != null) {
ContentType contentType = ContentType.parse(res.getFirstHeader(HEADER_CONTENT_TYPE)
.getValue());
isSamlSoap = MIME_TYPE_PAOS.equals(contentType.getMimeType());
}
if (!isSamlSoap) {
return;
}
log.trace("Detected login request");
// -- If the request was a HEAD request, we need to try again using a GET request ----
HttpResponse paosResponse = res;
if (originalRequest.getRequestLine().getMethod() == "HEAD") {
log.trace("Original request was a HEAD, restarting authenticiation with GET");
HttpGet authTriggerRequest = new HttpGet(originalRequest.getRequestLine().getUri());
authTriggerRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
paosResponse = client.execute(authTriggerRequest);
}
// -- Parse PAOS response -------------------------------------------------------------
Envelope initialLoginSoapResponse = (Envelope) unmarshallMessage(parserPool,
paosResponse.getEntity().getContent());
// -- Capture relay state (optional) --------------------------------------------------
RelayState relayState = null;
if (!initialLoginSoapResponse.getHeader()
.getUnknownXMLObjects(RelayState.DEFAULT_ELEMENT_NAME).isEmpty()) {
relayState = (RelayState) initialLoginSoapResponse.getHeader()
.getUnknownXMLObjects(RelayState.DEFAULT_ELEMENT_NAME).get(0);
relayState.detach();
log.trace("Relay state: captured");
}
// -- Capture response consumer -------------------------------------------------------
// // pick out the responseConsumerURL attribute value from the SP response so that
// // it can later be compared to the assertionConsumerURL sent from the IdP
// String responseConsumerURL = ((XSAny) initialLoginSoapResponse.getHeader()
// .getUnknownXMLObjects(E_PAOS_REQUEST).get(0)).getUnknownAttributes().get(
// A_RESPONSE_CONSUMER_URL);
// log.debug("responseConsumerURL: [" + responseConsumerURL + "]");
// -- Send log-in request to the IdP --------------------------------------------------
// Prepare the request to the IdP
log.debug("Logging in to IdP [" + idpUrl + "]");
Envelope idpLoginSoapRequest = new EnvelopeBuilder().buildObject();
Body b = initialLoginSoapResponse.getBody();
b.detach();
idpLoginSoapRequest.setBody(b);
// Try logging in to the IdP using HTTP BASIC authentication
HttpPost idpLoginRequest = new HttpPost(idpUrl);
idpLoginRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
idpLoginRequest.addHeader(HEADER_AUTHORIZATION,
"Basic " + Base64.encodeBytes((username + ":" + password).getBytes()));
idpLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapRequest)));
HttpResponse idpLoginResponse = client.execute(idpLoginRequest);
// -- Handle log-in response tfrom the IdP --------------------------------------------
log.debug("Status: " + idpLoginResponse.getStatusLine());
Envelope idpLoginSoapResponse = (Envelope) unmarshallMessage(parserPool,
idpLoginResponse.getEntity().getContent());
EntityUtils.consume(idpLoginResponse.getEntity());
String assertionConsumerServiceURL = ((Response) idpLoginSoapResponse.getHeader()
.getUnknownXMLObjects(Response.DEFAULT_ELEMENT_NAME).get(0))
.getAssertionConsumerServiceURL();
log.debug("assertionConsumerServiceURL: " + assertionConsumerServiceURL);
List<XMLObject> responses = idpLoginSoapResponse.getBody().getUnknownXMLObjects(
org.opensaml.saml2.core.Response.DEFAULT_ELEMENT_NAME);
if (!responses.isEmpty()) {
org.opensaml.saml2.core.Response response = (org.opensaml.saml2.core.Response) responses
.get(0);
// Get root code (?)
StatusCode sc = response.getStatus().getStatusCode();
while (sc.getStatusCode() != null) {
sc = sc.getStatusCode();
}
// Hm, they don't like us
if ("urn:oasis:names:tc:SAML:2.0:status:AuthnFailed".equals(sc.getValue())) {
throw new AuthenticationException(sc.getValue());
}
}
// compare the responseConsumerURL from the SP to the assertionConsumerServiceURL from
// the IdP and if they are not identical then send a SOAP fault to the SP
// if (false) {
// // Nice guys should send a fault to the SP - we are NOT nice yet
// }
// -- Forward ticket to the SP --------------------------------------------------------
// craft the package to send to the SP by copying the response from the IdP but
// removing the SOAP header sent by the IdP and instead putting in a new header that
// includes the relay state sent by the SP
Header header = new HeaderBuilder().buildObject();
header.getUnknownXMLObjects().clear();
if (relayState != null) {
header.getUnknownXMLObjects().add(relayState);
}
idpLoginSoapResponse.setHeader(header);
// push the response to the SP at the assertion consumer service URL included in
// the response from the IdP
log.debug("Logging in to SP");
HttpPost spLoginRequest = new HttpPost(assertionConsumerServiceURL);
spLoginRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
spLoginRequest.setHeader(HEADER_CONTENT_TYPE, MIME_TYPE_PAOS);
spLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapResponse)));
HttpClientParams.setRedirecting(spLoginRequest.getParams(), false);
HttpResponse spLoginResponse = client.execute(spLoginRequest);
log.debug("Status: " + spLoginResponse.getStatusLine());
log.debug("Authentication complete");
// -- Handle unredirectable cases -----------------------------------------------------
// If we get a redirection and the request is redirectable, then let the client redirect
// If the request is not redirectable, signal that the operation must be retried.
if (spLoginResponse.getStatusLine().getStatusCode() == 302
&& !REDIRECTABLE.contains(originalRequest.getRequestLine().getMethod())) {
EntityUtils.consume(spLoginResponse.getEntity());
throw new NonRepeatableRequestException("Request of type [" +
originalRequest.getRequestLine().getMethod() + "] cannot be redirected");
}
// -- Transparently return response to original request -------------------------------
// Return response received after login as actual response to original caller
res.setEntity(spLoginResponse.getEntity());
res.setHeaders(spLoginResponse.getAllHeaders());
res.setStatusLine(spLoginResponse.getStatusLine());
}
| public void process(HttpResponse res, HttpContext ctx)
throws HttpException, IOException
{
HttpRequest originalRequest;
// check for RequestWrapper objects, retrieve the original request
if (ctx.getAttribute("http.request") instanceof HttpRequestWrapper) { // does not forward request to original
log.trace("RequestWrapper found");
originalRequest = (HttpRequest) ((HttpRequestWrapper) ctx.getAttribute("http.request")).getOriginal();
}
else { // use a basic HttpRequest because BasicHttpRequest objects cannot be recast to HttpUriRequest objects
originalRequest = (HttpRequest) ctx.getAttribute("http.request");
}
log.trace("Accessing [" + originalRequest.getRequestLine().getUri() + " "
+ originalRequest.getRequestLine().getMethod() + "]");
// -- Check if authentication is already in progress ----------------------------------
if (res.getParams().isParameterTrue(AUTH_IN_PROGRESS)) {
log.trace("Authentication in progress -- skipping post processor");
return;
}
// -- Check if authentication is necessary --------------------------------------------
boolean isSamlSoap = false;
if (res.getFirstHeader(HEADER_CONTENT_TYPE) != null) {
ContentType contentType = ContentType.parse(res.getFirstHeader(HEADER_CONTENT_TYPE)
.getValue());
isSamlSoap = MIME_TYPE_PAOS.equals(contentType.getMimeType());
}
if (!isSamlSoap) {
return;
}
log.trace("Detected login request");
// -- If the request was a HEAD request, we need to try again using a GET request ----
HttpResponse paosResponse = res;
if (originalRequest.getRequestLine().getMethod() == "HEAD") {
log.trace("Original request was a HEAD, restarting authenticiation with GET");
HttpGet authTriggerRequest = new HttpGet(originalRequest.getRequestLine().getUri());
authTriggerRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
paosResponse = client.execute(authTriggerRequest);
}
// -- Parse PAOS response -------------------------------------------------------------
Envelope initialLoginSoapResponse = (Envelope) unmarshallMessage(parserPool,
paosResponse.getEntity().getContent());
// -- Capture relay state (optional) --------------------------------------------------
RelayState relayState = null;
if (!initialLoginSoapResponse.getHeader()
.getUnknownXMLObjects(RelayState.DEFAULT_ELEMENT_NAME).isEmpty()) {
relayState = (RelayState) initialLoginSoapResponse.getHeader()
.getUnknownXMLObjects(RelayState.DEFAULT_ELEMENT_NAME).get(0);
relayState.detach();
log.trace("Relay state: captured");
}
// -- Capture response consumer -------------------------------------------------------
// // pick out the responseConsumerURL attribute value from the SP response so that
// // it can later be compared to the assertionConsumerURL sent from the IdP
// String responseConsumerURL = ((XSAny) initialLoginSoapResponse.getHeader()
// .getUnknownXMLObjects(E_PAOS_REQUEST).get(0)).getUnknownAttributes().get(
// A_RESPONSE_CONSUMER_URL);
// log.debug("responseConsumerURL: [" + responseConsumerURL + "]");
// -- Send log-in request to the IdP --------------------------------------------------
// Prepare the request to the IdP
log.debug("Logging in to IdP [" + idpUrl + "]");
Envelope idpLoginSoapRequest = new EnvelopeBuilder().buildObject();
Body b = initialLoginSoapResponse.getBody();
b.detach();
idpLoginSoapRequest.setBody(b);
// Try logging in to the IdP using HTTP BASIC authentication
HttpPost idpLoginRequest = new HttpPost(idpUrl);
idpLoginRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
idpLoginRequest.addHeader(HEADER_AUTHORIZATION,
"Basic " + Base64.encodeBytes((username + ":" + password).getBytes()));
idpLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapRequest)));
HttpResponse idpLoginResponse = client.execute(idpLoginRequest);
// -- Handle log-in response tfrom the IdP --------------------------------------------
log.debug("Status: " + idpLoginResponse.getStatusLine());
Envelope idpLoginSoapResponse = (Envelope) unmarshallMessage(parserPool,
idpLoginResponse.getEntity().getContent());
EntityUtils.consume(idpLoginResponse.getEntity());
String assertionConsumerServiceURL = ((Response) idpLoginSoapResponse.getHeader()
.getUnknownXMLObjects(Response.DEFAULT_ELEMENT_NAME).get(0))
.getAssertionConsumerServiceURL();
log.debug("assertionConsumerServiceURL: " + assertionConsumerServiceURL);
List<XMLObject> responses = idpLoginSoapResponse.getBody().getUnknownXMLObjects(
org.opensaml.saml2.core.Response.DEFAULT_ELEMENT_NAME);
if (!responses.isEmpty()) {
org.opensaml.saml2.core.Response response = (org.opensaml.saml2.core.Response) responses
.get(0);
// Get root code (?)
StatusCode sc = response.getStatus().getStatusCode();
while (sc.getStatusCode() != null) {
sc = sc.getStatusCode();
}
// Hm, they don't like us
if ("urn:oasis:names:tc:SAML:2.0:status:AuthnFailed".equals(sc.getValue())) {
throw new AuthenticationException(sc.getValue());
}
}
// compare the responseConsumerURL from the SP to the assertionConsumerServiceURL from
// the IdP and if they are not identical then send a SOAP fault to the SP
// if (false) {
// // Nice guys should send a fault to the SP - we are NOT nice yet
// }
// -- Forward ticket to the SP --------------------------------------------------------
// craft the package to send to the SP by copying the response from the IdP but
// removing the SOAP header sent by the IdP and instead putting in a new header that
// includes the relay state sent by the SP
Header header = new HeaderBuilder().buildObject();
header.getUnknownXMLObjects().clear();
if (relayState != null) {
header.getUnknownXMLObjects().add(relayState);
}
idpLoginSoapResponse.setHeader(header);
// push the response to the SP at the assertion consumer service URL included in
// the response from the IdP
log.debug("Logging in to SP");
HttpPost spLoginRequest = new HttpPost(assertionConsumerServiceURL);
spLoginRequest.getParams().setBooleanParameter(AUTH_IN_PROGRESS, true);
spLoginRequest.setHeader(HEADER_CONTENT_TYPE, MIME_TYPE_PAOS);
spLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapResponse)));
HttpClientParams.setRedirecting(spLoginRequest.getParams(), false);
HttpResponse spLoginResponse = client.execute(spLoginRequest);
log.debug("Status: " + spLoginResponse.getStatusLine());
log.debug("Authentication complete");
// -- Handle unredirectable cases -----------------------------------------------------
// If we get a redirection and the request is redirectable, then let the client redirect
// If the request is not redirectable, signal that the operation must be retried.
if (spLoginResponse.getStatusLine().getStatusCode() == 302
&& !REDIRECTABLE.contains(originalRequest.getRequestLine().getMethod())
&& (originalRequest.getRequestLine().getMethod() != "CONNECT")) {
EntityUtils.consume(spLoginResponse.getEntity());
throw new NonRepeatableRequestException("Request of type [" +
originalRequest.getRequestLine().getMethod() + "] cannot be redirected");
}
// -- Transparently return response to original request -------------------------------
// Return response received after login as actual response to original caller
res.setEntity(spLoginResponse.getEntity());
res.setHeaders(spLoginResponse.getAllHeaders());
res.setStatusLine(spLoginResponse.getStatusLine());
}
|
diff --git a/source/RMG/RMG.java b/source/RMG/RMG.java
index ab3317e3..3ac4da42 100644
--- a/source/RMG/RMG.java
+++ b/source/RMG/RMG.java
@@ -1,235 +1,235 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;
import jing.chem.*;
import jing.chemParser.*;
import jing.param.*;
import jing.chemUtil.*;
import jing.rxn.*;
import jing.rxnSys.*;
import jing.mathTool.*;
//----------------------------------------------------------------------------
// MainRMG.java
//----------------------------------------------------------------------------
public class RMG {
//## configuration RMG::RMG
public static void main(String[] args) {
// Initialize the logger
Logger.initialize();
// Log the RMG header
Logger.logHeader();
try {
// Record the time at which RMG was started (so we can periodically
// print the elapsed time)
Global.tAtInitialization = System.currentTimeMillis();
// Initialize some properties
globalInitializeSystemProperties();
// Create the working folders for various RMG components
// Note that some of these folders are only used when their
// corresponding features are activated in the condition file
createFolder("chemkin", true);
- createFolder("Restart", true);
+ createFolder("Restart", false);
createFolder("GATPFit", true);
createFolder("ODESolver", true);
createFolder("fame", true);
createFolder("frankie", true);
createFolder("InChI", true);
createFolder("Pruning", true);
createFolder("2Dmolfiles", true); // Not sure if we should be deleting this
createFolder("3Dmolfiles", true); // Not sure if we should be deleting this
createFolder("QMfiles", false); // Preserving QM files between runs will speed things up considerably
// The only parameter should be the path to the condition file
String inputfile = args[0];
System.setProperty("jing.rxnSys.ReactionModelGenerator.conditionFile",inputfile);
// Echo the contents of the condition file into the log
logInputFile(inputfile);
// Read the "Database" keyword from the condition file
// This database supercedes the default RMG_database if present
FileReader in = new FileReader(inputfile);
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Database"))
extractAndSetDatabasePath(line);
// Generate the model!
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.modelGeneration();
// Save the resulting model to Final_Model.txt
writeFinalModel(rmg);
}
catch (Exception e) {
// Any unhandled exception will land here
// We assume that these were critical errors
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
}
// Finish the logger
Logger.finish();
}
public static void writeFinalModel(ReactionModelGenerator rmg) throws IOException {
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rmg.getReactionModel();
long tAtInitialization = Global.tAtInitialization;
BufferedWriter file = new BufferedWriter(new FileWriter("Final_Model.txt"));
LinkedList speList = new LinkedList(rmg.getReactionModel().getSpeciesSet());
//11/2/07 gmagoon: changing to loop over all reaction systems
LinkedList rsList = rmg.getReactionSystemList();
for (int i = 0; i < rsList.size(); i++) {
ReactionSystem rs = (ReactionSystem) rsList.get(i);
file.write("Reaction system " + (i + 1) + " of " + rsList.size() + "\n");//11/4/07 gmagoon: fixing "off by one" error
file.write("\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Concentration Profile Output \\\\\\\\\\\\\\\\\\\\\\\\\\");
file.write("\n" + rs.returnConcentrationProfile(speList) + "\n");
if (rmg.getError()) {//svp
file.write("\n");
file.write("Upper Bounds:" + "\n");
file.write(rs.printUpperBoundConcentrations(speList) + "\n");
file.write("Lower Bounds:" + "\n");
file.write(rs.printLowerBoundConcentrations(speList) + "\n");
}
file.write("\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Mole Fraction Profile Output \\\\\\\\\\\\\\\\\\\\\\\\\\");
file.write("\n" + rs.returnMoleFractionProfile(speList) + "\n");
file.write(rs.printOrderedReactions() + "\n");
if (rmg.getSensitivity()) {//svp
LinkedList importantSpecies = rmg.getSpeciesList();
file.write("Sensitivity Analysis:");
file.write(rs.printSensitivityCoefficients(speList, importantSpecies) + "\n");
file.write("\n");
file.write(rs.printSensitivityToThermo(speList, importantSpecies) + "\n");
file.write("\n");
file.write(rs.printMostUncertainReactions(speList, importantSpecies) + "\n\n");
}
file.write(rs.returnReactionFlux() + "\n");
}
// Write how long the simulation took, and then close the file
long end = System.currentTimeMillis();
double min = (end - tAtInitialization) / 1.0E3 / 60.0;
file.write(String.format("Running time: %.3f min", + min));
file.close();
}
public static void globalInitializeSystemProperties() {
// Set the default locale to US (since RMG is developed there)
Locale.setDefault(Locale.US);
// Get the value of the RMG environment variable; fail if not set!
String workingDir = System.getenv("RMG");
if (workingDir == null) throw new RuntimeException("The RMG environment variable is not defined.");
System.setProperty("RMG.workingDirectory", workingDir);
// Set the default database
setDatabasePaths(workingDir + "/databases/RMG_database");
}
public static void setDatabasePaths(String database_path) {
// String database_path = workingDir + "/databases/" + name
System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile", database_path +"/ForbiddenStructures.txt");
System.setProperty("jing.chem.ThermoGAGroupLibrary.pathName", database_path +"/thermo_groups");
System.setProperty("jing.chem.ThermoReferenceLibrary.pathName", database_path +"/thermo_libraries");
System.setProperty("jing.chem.FrequencyDatabase.pathName", database_path +"/frequencies_groups");
System.setProperty("jing.chem.LJDatabase.pathName", database_path +"/transport_groups");
System.setProperty("jing.chem.TransportReferenceLibrary.pathName", database_path +"/transport_libraries");
System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", database_path +"/kinetics_groups");
System.setProperty("jing.rxn.ReactionLibrary.pathName", database_path +"/kinetics_libraries");
System.setProperty("jing.chem.SolventLibrary.pathName", database_path +"/thermo_libraries");
}
/**
* Create a folder in the current (working) directory, deleting the
* existing folder and its contents if desired.
* @param name The name of the folder to create
* @param deleteExisting true to delete the existing folder (and its contents!), false to preserve it
*/
public static void createFolder(String name, boolean deleteExisting) {
File folder = new File(name);
if (deleteExisting)
ChemParser.deleteDir(folder);
if (!folder.exists())
folder.mkdir();
}
public static void extractAndSetDatabasePath(String line) {
StringTokenizer st = new StringTokenizer(line);
String next = st.nextToken();
String database_name = st.nextToken().trim();
String workingDir = System.getProperty("RMG.workingDirectory");
String database_path = workingDir + "/databases/" + database_name;
setDatabasePaths(database_path);
}
/**
* Echo the contents of the input condition file to the log.
* @param inputfile The path of the input file
*/
public static void logInputFile(String inputfile) throws FileNotFoundException, IOException {
Logger.verbose("----------------------------------------------------------------------");
Logger.verbose(" User input:");
Logger.verbose("----------------------------------------------------------------------");
Logger.verbose("");
BufferedReader minireader = new BufferedReader(new FileReader(inputfile));
String inputLine = minireader.readLine();
while (inputLine != null) {
Logger.verbose(inputLine);
inputLine = minireader.readLine();
}
minireader.close();
Logger.verbose("");
Logger.verbose("----------------------------------------------------------------------");
Logger.verbose("");
}
}
/*********************************************************************
File Path : RMG\RMG\MainRMG.java
*********************************************************************/
| true | true | public static void main(String[] args) {
// Initialize the logger
Logger.initialize();
// Log the RMG header
Logger.logHeader();
try {
// Record the time at which RMG was started (so we can periodically
// print the elapsed time)
Global.tAtInitialization = System.currentTimeMillis();
// Initialize some properties
globalInitializeSystemProperties();
// Create the working folders for various RMG components
// Note that some of these folders are only used when their
// corresponding features are activated in the condition file
createFolder("chemkin", true);
createFolder("Restart", true);
createFolder("GATPFit", true);
createFolder("ODESolver", true);
createFolder("fame", true);
createFolder("frankie", true);
createFolder("InChI", true);
createFolder("Pruning", true);
createFolder("2Dmolfiles", true); // Not sure if we should be deleting this
createFolder("3Dmolfiles", true); // Not sure if we should be deleting this
createFolder("QMfiles", false); // Preserving QM files between runs will speed things up considerably
// The only parameter should be the path to the condition file
String inputfile = args[0];
System.setProperty("jing.rxnSys.ReactionModelGenerator.conditionFile",inputfile);
// Echo the contents of the condition file into the log
logInputFile(inputfile);
// Read the "Database" keyword from the condition file
// This database supercedes the default RMG_database if present
FileReader in = new FileReader(inputfile);
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Database"))
extractAndSetDatabasePath(line);
// Generate the model!
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.modelGeneration();
// Save the resulting model to Final_Model.txt
writeFinalModel(rmg);
}
catch (Exception e) {
// Any unhandled exception will land here
// We assume that these were critical errors
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
}
// Finish the logger
Logger.finish();
}
| public static void main(String[] args) {
// Initialize the logger
Logger.initialize();
// Log the RMG header
Logger.logHeader();
try {
// Record the time at which RMG was started (so we can periodically
// print the elapsed time)
Global.tAtInitialization = System.currentTimeMillis();
// Initialize some properties
globalInitializeSystemProperties();
// Create the working folders for various RMG components
// Note that some of these folders are only used when their
// corresponding features are activated in the condition file
createFolder("chemkin", true);
createFolder("Restart", false);
createFolder("GATPFit", true);
createFolder("ODESolver", true);
createFolder("fame", true);
createFolder("frankie", true);
createFolder("InChI", true);
createFolder("Pruning", true);
createFolder("2Dmolfiles", true); // Not sure if we should be deleting this
createFolder("3Dmolfiles", true); // Not sure if we should be deleting this
createFolder("QMfiles", false); // Preserving QM files between runs will speed things up considerably
// The only parameter should be the path to the condition file
String inputfile = args[0];
System.setProperty("jing.rxnSys.ReactionModelGenerator.conditionFile",inputfile);
// Echo the contents of the condition file into the log
logInputFile(inputfile);
// Read the "Database" keyword from the condition file
// This database supercedes the default RMG_database if present
FileReader in = new FileReader(inputfile);
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Database"))
extractAndSetDatabasePath(line);
// Generate the model!
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.modelGeneration();
// Save the resulting model to Final_Model.txt
writeFinalModel(rmg);
}
catch (Exception e) {
// Any unhandled exception will land here
// We assume that these were critical errors
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
}
// Finish the logger
Logger.finish();
}
|
diff --git a/src/com/hersan/bablrr/Message.java b/src/com/hersan/bablrr/Message.java
index b01bbf7..30d678a 100644
--- a/src/com/hersan/bablrr/Message.java
+++ b/src/com/hersan/bablrr/Message.java
@@ -1,188 +1,186 @@
package com.hersan.bablrr;
import processing.core.PApplet;
import processing.core.PImage;
import processing.core.PGraphics;
import java.util.ArrayList;
/* from Processing :
* PImage : theImage
* createImage()
* copy()
* PImage : ti
* width + height
* PGraphics : theGraphics
* get()
*/
public class Message {
private final static int SUCCESS = 0;
private final static int FAIL = 1;
private ArrayList<Word> words;
private PImage theImage;
private PApplet myProcessing;
// constructor
// create array of words and an image
// msg := text message
// img := path to image file
// initw,inith := init dimensions for the final image
public Message(String msg, String img, PApplet pa, int initw, int inith) {
myProcessing = pa;
myProcessing.colorMode(PApplet.RGB);
// fill array with words from msg
MessageHelper(msg);
// add picture at the end
if((img != null)&&(!img.equals(""))){
words.add(new Picture(img,myProcessing));
}
// gen graphic
this.genImage(initw, inith);
}
// no image
public Message(String msg, PApplet pa, int initw, int inith) {
this(msg,"",pa,initw,inith);
}
// some defaut values for w and h
public Message(String msg, PApplet pa) {
this(msg,"",pa,300,200);
}
public Message(String msg, String img, PApplet pa) {
this(msg,img,pa,300,200);
}
// constructor helper to fill array with words from msg
private void MessageHelper(String msg) {
words = new ArrayList<Word>();
// fill array
String[] tWords = msg.split(" ");
for(String s : tWords){
if (s.length() > 0) {
words.add(new Word(s, myProcessing));
}
}
/*
for (int i=0; i<tWords.length; i++) {
if (tWords[i].length() > 0) {
words.add(new Word(tWords[i], myProcessing));
}
}
*/
}
private void genImage(int initw, int inith) {
int w = initw;
int h = inith;
int gcnt = 1;
System.out.println("!!!! Try "+gcnt+". Size: "+w+" x "+h);
int result = placeWords(w, h);
while (result == FAIL) {
w += (int)(0.2f*w);
if(w > (2*h)){
h += (int)(0.2f*h);
}
gcnt++;
System.out.println("!!!! Try "+gcnt+". Size: "+w+" x "+h);
result = placeWords(w, h);
}
}
private int placeWords(int width_, int height_) {
/// DEBUG
//System.out.println("!!!!!!!: from placeWords : "+width_+" x "+height_);
// init graphic
PGraphics theGraphic = myProcessing.createGraphics(width_, height_, PApplet.JAVA2D);
theGraphic.beginDraw();
theGraphic.background(0xffffffff);
// keep track of max dimensions
float maxX = 0;
float maxY = 0;
// current offsets for placing
float xoff = 0;
float yoff = 0;
// for every word w
- //for (int i=0; i<words.size(); i++) {
- //Word w = words.get(i);
for(Word w : words){
PImage ti = w.getDImage();
// DEBUG
//System.out.println("!!!! word "+i+" : "+ti.width+ " x "+ti.height);
- // special case to take care of long first words that don't fit.
- if ((xoff==0)&&(yoff==0)&&(ti.width>theGraphic.width)) {
+ // special case to take care of long words that don't fit in their own line.
+ if ((ti.width>theGraphic.width)) {
theGraphic.endDraw();
theGraphic.dispose();
theGraphic.delete();
return FAIL;
}
// if word doesn't fit in this line.
- // this doens't work when very first word doesn't fit in line.
+ // this doens't work when very first word of a line doesn't fit in the line.
if ((xoff+ti.width)>theGraphic.width) {
// reset xoffset
xoff = 0;
// bump up yoffset
yoff = maxY+2;
}
// check if out of bounds in the y direction
if ((yoff+ti.height) > theGraphic.height) {
theGraphic.endDraw();
theGraphic.dispose();
theGraphic.delete();
return FAIL;
}
// offsets should be good: place word
theGraphic.image(ti, xoff, yoff);
// bump up xoffset
xoff += ti.width+2;
// update max values
if (xoff > maxX) maxX = xoff;
if ((yoff+ti.height)>maxY) maxY = yoff+ti.height;
}
// should have image
theGraphic.endDraw();
// create, size and copy onto theImage
theImage = myProcessing.createImage((int)(maxX+2), (int)(maxY+2), PApplet.RGB);
theImage.copy(theGraphic.get(), 0, 0, (int)(maxX+2), (int)(maxY+2), 0, 0, theImage.width, theImage.height);
// clean up
theGraphic.dispose();
theGraphic.delete();
// success
return SUCCESS;
}
// get Image
public PImage getImage() {
return theImage;
}
// access words
public Word getWord(int i) {
if ((i>-1)&&(i<words.size())) {
return words.get(i);
}
else {
return words.get(0);
}
}
}
| false | true | private int placeWords(int width_, int height_) {
/// DEBUG
//System.out.println("!!!!!!!: from placeWords : "+width_+" x "+height_);
// init graphic
PGraphics theGraphic = myProcessing.createGraphics(width_, height_, PApplet.JAVA2D);
theGraphic.beginDraw();
theGraphic.background(0xffffffff);
// keep track of max dimensions
float maxX = 0;
float maxY = 0;
// current offsets for placing
float xoff = 0;
float yoff = 0;
// for every word w
//for (int i=0; i<words.size(); i++) {
//Word w = words.get(i);
for(Word w : words){
PImage ti = w.getDImage();
// DEBUG
//System.out.println("!!!! word "+i+" : "+ti.width+ " x "+ti.height);
// special case to take care of long first words that don't fit.
if ((xoff==0)&&(yoff==0)&&(ti.width>theGraphic.width)) {
theGraphic.endDraw();
theGraphic.dispose();
theGraphic.delete();
return FAIL;
}
// if word doesn't fit in this line.
// this doens't work when very first word doesn't fit in line.
if ((xoff+ti.width)>theGraphic.width) {
// reset xoffset
xoff = 0;
// bump up yoffset
yoff = maxY+2;
}
// check if out of bounds in the y direction
if ((yoff+ti.height) > theGraphic.height) {
theGraphic.endDraw();
theGraphic.dispose();
theGraphic.delete();
return FAIL;
}
// offsets should be good: place word
theGraphic.image(ti, xoff, yoff);
// bump up xoffset
xoff += ti.width+2;
// update max values
if (xoff > maxX) maxX = xoff;
if ((yoff+ti.height)>maxY) maxY = yoff+ti.height;
}
// should have image
theGraphic.endDraw();
// create, size and copy onto theImage
theImage = myProcessing.createImage((int)(maxX+2), (int)(maxY+2), PApplet.RGB);
theImage.copy(theGraphic.get(), 0, 0, (int)(maxX+2), (int)(maxY+2), 0, 0, theImage.width, theImage.height);
// clean up
theGraphic.dispose();
theGraphic.delete();
// success
return SUCCESS;
}
| private int placeWords(int width_, int height_) {
/// DEBUG
//System.out.println("!!!!!!!: from placeWords : "+width_+" x "+height_);
// init graphic
PGraphics theGraphic = myProcessing.createGraphics(width_, height_, PApplet.JAVA2D);
theGraphic.beginDraw();
theGraphic.background(0xffffffff);
// keep track of max dimensions
float maxX = 0;
float maxY = 0;
// current offsets for placing
float xoff = 0;
float yoff = 0;
// for every word w
for(Word w : words){
PImage ti = w.getDImage();
// DEBUG
//System.out.println("!!!! word "+i+" : "+ti.width+ " x "+ti.height);
// special case to take care of long words that don't fit in their own line.
if ((ti.width>theGraphic.width)) {
theGraphic.endDraw();
theGraphic.dispose();
theGraphic.delete();
return FAIL;
}
// if word doesn't fit in this line.
// this doens't work when very first word of a line doesn't fit in the line.
if ((xoff+ti.width)>theGraphic.width) {
// reset xoffset
xoff = 0;
// bump up yoffset
yoff = maxY+2;
}
// check if out of bounds in the y direction
if ((yoff+ti.height) > theGraphic.height) {
theGraphic.endDraw();
theGraphic.dispose();
theGraphic.delete();
return FAIL;
}
// offsets should be good: place word
theGraphic.image(ti, xoff, yoff);
// bump up xoffset
xoff += ti.width+2;
// update max values
if (xoff > maxX) maxX = xoff;
if ((yoff+ti.height)>maxY) maxY = yoff+ti.height;
}
// should have image
theGraphic.endDraw();
// create, size and copy onto theImage
theImage = myProcessing.createImage((int)(maxX+2), (int)(maxY+2), PApplet.RGB);
theImage.copy(theGraphic.get(), 0, 0, (int)(maxX+2), (int)(maxY+2), 0, 0, theImage.width, theImage.height);
// clean up
theGraphic.dispose();
theGraphic.delete();
// success
return SUCCESS;
}
|
diff --git a/src/jothello/Ai.java b/src/jothello/Ai.java
index c24a120..7caa901 100644
--- a/src/jothello/Ai.java
+++ b/src/jothello/Ai.java
@@ -1,60 +1,63 @@
package jothello;
import java.awt.Point;
import java.util.ArrayList;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;
public class Ai {
Globals globals;
public final static int CORNER_WEIGHT = 10;
public final static double DISC_WEIGHT = 0.01;
public final static int MONTE_CARLO_TREE_SEARCH = 0;
public final static int MINIMAX_ALPHA_BETA = 1;
public final int algo_type;
LuaValue monteCarlo = null;
LuaValue miniMax = null;
LuaTable param = null;
public Ai(int algo_type) {
String script = "lib/ai.lua";
// create an environment to run in
globals = JsePlatform.standardGlobals();
globals.load(new aif());
// Use the convenience function on the globals to load a chunk.
LuaValue chunk = globals.loadFile(script);
// Use any of the "call()" or "invoke()" functions directly on the chunk.
chunk.call( LuaValue.valueOf(script) );
this.algo_type = algo_type;
monteCarlo = globals.get("monteCarlo");
miniMax = globals.get("miniMax");
param = new LuaTable();
//param.set("time", 10);
//param.set("fixed_depth", 4);
param.set("max_depth", 4);
+ param.set("use_tt", LuaValue.valueOf(true));
+ param.set("get_pv", LuaValue.valueOf(true));
+ //param.set("no_tt_move_ordering", LuaValue.valueOf(true));
}
public Point selectMove(Jothello jothello) {
ArrayList<Point> legalMoves = jothello.getAllMoves();
LuaValue retvals = null;
if(algo_type == MONTE_CARLO_TREE_SEARCH) {
retvals = monteCarlo.call(LuaValue.valueOf(jothello.getGameStateString()), LuaValue.valueOf(jothello.getNumberOfMoves()));
}else {
retvals = miniMax.call(LuaValue.valueOf(jothello.getGameStateString()), param);
}
//System.out.println("best_move_index : " + retvals.toint());
return legalMoves.get(retvals.toint());
}
}
| true | true | public Ai(int algo_type) {
String script = "lib/ai.lua";
// create an environment to run in
globals = JsePlatform.standardGlobals();
globals.load(new aif());
// Use the convenience function on the globals to load a chunk.
LuaValue chunk = globals.loadFile(script);
// Use any of the "call()" or "invoke()" functions directly on the chunk.
chunk.call( LuaValue.valueOf(script) );
this.algo_type = algo_type;
monteCarlo = globals.get("monteCarlo");
miniMax = globals.get("miniMax");
param = new LuaTable();
//param.set("time", 10);
//param.set("fixed_depth", 4);
param.set("max_depth", 4);
}
| public Ai(int algo_type) {
String script = "lib/ai.lua";
// create an environment to run in
globals = JsePlatform.standardGlobals();
globals.load(new aif());
// Use the convenience function on the globals to load a chunk.
LuaValue chunk = globals.loadFile(script);
// Use any of the "call()" or "invoke()" functions directly on the chunk.
chunk.call( LuaValue.valueOf(script) );
this.algo_type = algo_type;
monteCarlo = globals.get("monteCarlo");
miniMax = globals.get("miniMax");
param = new LuaTable();
//param.set("time", 10);
//param.set("fixed_depth", 4);
param.set("max_depth", 4);
param.set("use_tt", LuaValue.valueOf(true));
param.set("get_pv", LuaValue.valueOf(true));
//param.set("no_tt_move_ordering", LuaValue.valueOf(true));
}
|
diff --git a/src/me/libraryaddict/Hungergames/Commands/BuyKit.java b/src/me/libraryaddict/Hungergames/Commands/BuyKit.java
index 8edab5c..a4d83b0 100644
--- a/src/me/libraryaddict/Hungergames/Commands/BuyKit.java
+++ b/src/me/libraryaddict/Hungergames/Commands/BuyKit.java
@@ -1,55 +1,55 @@
package me.libraryaddict.Hungergames.Commands;
import me.libraryaddict.Hungergames.Configs.TranslationConfig;
import me.libraryaddict.Hungergames.Managers.KitManager;
import me.libraryaddict.Hungergames.Managers.PlayerManager;
import me.libraryaddict.Hungergames.Types.HungergamesApi;
import me.libraryaddict.Hungergames.Types.Gamer;
import me.libraryaddict.Hungergames.Types.GiveKitThread;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class BuyKit implements CommandExecutor {
private TranslationConfig cm = HungergamesApi.getConfigManager().getTranslationsConfig();
public String description = "When mysql is enabled you can use this command to buy kits";
private KitManager kits = HungergamesApi.getKitManager();
private PlayerManager pm = HungergamesApi.getPlayerManager();
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Gamer gamer = pm.getGamer(sender.getName());
if (args.length > 0) {
me.libraryaddict.Hungergames.Types.Kit kit = kits.getKitByName(StringUtils.join(args, " "));
if (kit != null) {
if (gamer.getBalance() < kit.getPrice()) {
sender.sendMessage(cm.getCommandBuyKitCantAfford());
return true;
}
- if (kit.getPrice() < 0 || kit.isFree()) {
+ if (kit.getPrice() <= 0 || kit.isFree()) {
sender.sendMessage(cm.getCommandBuyKitCantBuyKit());
return true;
}
if (kits.ownsKit(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitAlreadyOwn());
return true;
}
if (!HungergamesApi.getConfigManager().getMainConfig().isMysqlEnabled()) {
sender.sendMessage(cm.getCommandBuyKitMysqlNotEnabled());
return true;
}
if (!kits.addKitToPlayer(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitKitsNotLoaded());
} else {
gamer.addBalance(-kit.getPrice());
new GiveKitThread(gamer.getName(), kit.getName()).start();
sender.sendMessage(String.format(cm.getCommandBuyKitPurchasedKit(), kit.getName()));
}
return true;
}
}
sender.sendMessage(cm.getCommandBuyKitNoArgs());
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Gamer gamer = pm.getGamer(sender.getName());
if (args.length > 0) {
me.libraryaddict.Hungergames.Types.Kit kit = kits.getKitByName(StringUtils.join(args, " "));
if (kit != null) {
if (gamer.getBalance() < kit.getPrice()) {
sender.sendMessage(cm.getCommandBuyKitCantAfford());
return true;
}
if (kit.getPrice() < 0 || kit.isFree()) {
sender.sendMessage(cm.getCommandBuyKitCantBuyKit());
return true;
}
if (kits.ownsKit(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitAlreadyOwn());
return true;
}
if (!HungergamesApi.getConfigManager().getMainConfig().isMysqlEnabled()) {
sender.sendMessage(cm.getCommandBuyKitMysqlNotEnabled());
return true;
}
if (!kits.addKitToPlayer(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitKitsNotLoaded());
} else {
gamer.addBalance(-kit.getPrice());
new GiveKitThread(gamer.getName(), kit.getName()).start();
sender.sendMessage(String.format(cm.getCommandBuyKitPurchasedKit(), kit.getName()));
}
return true;
}
}
sender.sendMessage(cm.getCommandBuyKitNoArgs());
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Gamer gamer = pm.getGamer(sender.getName());
if (args.length > 0) {
me.libraryaddict.Hungergames.Types.Kit kit = kits.getKitByName(StringUtils.join(args, " "));
if (kit != null) {
if (gamer.getBalance() < kit.getPrice()) {
sender.sendMessage(cm.getCommandBuyKitCantAfford());
return true;
}
if (kit.getPrice() <= 0 || kit.isFree()) {
sender.sendMessage(cm.getCommandBuyKitCantBuyKit());
return true;
}
if (kits.ownsKit(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitAlreadyOwn());
return true;
}
if (!HungergamesApi.getConfigManager().getMainConfig().isMysqlEnabled()) {
sender.sendMessage(cm.getCommandBuyKitMysqlNotEnabled());
return true;
}
if (!kits.addKitToPlayer(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitKitsNotLoaded());
} else {
gamer.addBalance(-kit.getPrice());
new GiveKitThread(gamer.getName(), kit.getName()).start();
sender.sendMessage(String.format(cm.getCommandBuyKitPurchasedKit(), kit.getName()));
}
return true;
}
}
sender.sendMessage(cm.getCommandBuyKitNoArgs());
return true;
}
|
diff --git a/nevernote-core/src/main/java/devoxx/core/controllers/NotesController.java b/nevernote-core/src/main/java/devoxx/core/controllers/NotesController.java
index d384130..70e916c 100644
--- a/nevernote-core/src/main/java/devoxx/core/controllers/NotesController.java
+++ b/nevernote-core/src/main/java/devoxx/core/controllers/NotesController.java
@@ -1,105 +1,108 @@
package devoxx.core.controllers;
import devoxx.api.NoteDoneEvent;
import devoxx.core.db.NotesModel;
import devoxx.core.db.NotesModel.Notes;
import devoxx.core.db.NotesModel.Note;
import devoxx.core.fwk.api.Controller;
import devoxx.core.util.F;
import devoxx.core.util.F.Unit;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.ws.rs.*;
import org.jboss.weld.environment.osgi.api.events.InterBundleEvent;
@Path("notes")
public class NotesController implements Controller {
@Inject Event<InterBundleEvent> evt;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Note> notes() {
final List<Note> notes = new ArrayList<Note>();
NotesModel.DB.withConnection(new F.Function<Connection, F.Unit>() {
@Override
public F.Unit apply(Connection _) {
notes.addAll(Notes._.findAll());
return F.Unit.unit();
}
});
return notes;
}
@GET @Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Note getNote(@PathParam("id") final Long id) {
return NotesModel.DB.withConnection(new F.Function<Connection, Note>() {
@Override
public Note apply(Connection _) {
return Notes._.findById(id).getOrNull();
}
});
}
@DELETE @Path("{id}")
public void remNote(@PathParam("id") final Long id) {
NotesModel.DB.withConnection(new F.Function<Connection, Unit>() {
@Override
public Unit apply(Connection _) {
Notes._.delete(id);
return F.Unit.unit();
}
});
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Note create(@FormParam("title") String title,
@FormParam("content") String content) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
final Note note = new Note(System.currentTimeMillis(), format.format(new Date()), title, content, Boolean.FALSE);
NotesModel.DB.withConnection(new F.Function<Connection, F.Unit>() {
@Override
public F.Unit apply(Connection _) {
Notes._.insertAll(note);
return F.Unit.unit();
}
});
return note;
}
@POST @Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Note update(@PathParam("id") final Long id,
@FormParam("title") final String title,
@FormParam("content") final String content,
@FormParam("done") final Boolean done) {
return NotesModel.DB.withConnection(new F.Function<Connection, Note>() {
@Override
public Note apply(Connection _) {
for (Note note : Notes._.findById(id)) {
+ boolean changed = false;
try {
note.title = title;
note.content = content;
- boolean changed = (note.done == done);
+ changed = (note.done == done);
note.done = done;
return Notes._.update(note);
} finally {
- evt.fire(new InterBundleEvent(new NoteDoneEvent(note.id, note.date, note.title, note.content), NoteDoneEvent.class));
+ if (changed) {
+ evt.fire(new InterBundleEvent(new NoteDoneEvent(note.id, note.date, note.title, note.content), NoteDoneEvent.class));
+ }
}
}
return null;
}
});
}
}
| false | true | public Note update(@PathParam("id") final Long id,
@FormParam("title") final String title,
@FormParam("content") final String content,
@FormParam("done") final Boolean done) {
return NotesModel.DB.withConnection(new F.Function<Connection, Note>() {
@Override
public Note apply(Connection _) {
for (Note note : Notes._.findById(id)) {
try {
note.title = title;
note.content = content;
boolean changed = (note.done == done);
note.done = done;
return Notes._.update(note);
} finally {
evt.fire(new InterBundleEvent(new NoteDoneEvent(note.id, note.date, note.title, note.content), NoteDoneEvent.class));
}
}
return null;
}
});
}
| public Note update(@PathParam("id") final Long id,
@FormParam("title") final String title,
@FormParam("content") final String content,
@FormParam("done") final Boolean done) {
return NotesModel.DB.withConnection(new F.Function<Connection, Note>() {
@Override
public Note apply(Connection _) {
for (Note note : Notes._.findById(id)) {
boolean changed = false;
try {
note.title = title;
note.content = content;
changed = (note.done == done);
note.done = done;
return Notes._.update(note);
} finally {
if (changed) {
evt.fire(new InterBundleEvent(new NoteDoneEvent(note.id, note.date, note.title, note.content), NoteDoneEvent.class));
}
}
}
return null;
}
});
}
|
diff --git a/ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java b/ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
index 504f2b927..7be16e8dd 100644
--- a/ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
+++ b/ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
@@ -1,636 +1,638 @@
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC),
* 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* AMC 01.20.2003 extended to support new AspectJ 1.1 options,
* bugzilla #29769
* ******************************************************************/
package org.aspectj.ajde.internal;
import java.io.File;
import java.util.*;
import org.aspectj.ajde.*;
import org.aspectj.ajdt.ajc.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.LangUtil;
//import org.eclipse.core.runtime.OperationCanceledException;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class CompilerAdapter {
private static final Set DEFAULT__AJDE_WARNINGS;
static {
DEFAULT__AJDE_WARNINGS = new HashSet();
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_DEPRECATION);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_UNUSED_IMPORTS);
// DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_);
// DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_);
}
// private Map optionsMap;
private AjBuildManager buildManager = null;
private IMessageHandler messageHandler = null;
private BuildNotifierAdapter currNotifier = null;
private boolean initialized = false;
private boolean structureDirty = true;
private boolean showInfoMessages = false;
// set to false in incremental mode to re-do initial build
private boolean nextBuild = false;
public CompilerAdapter() {
super();
}
public void showInfoMessages(boolean show) { // XXX surface in GUI
showInfoMessages = show;
}
public boolean getShowInfoMessages() {
return showInfoMessages;
}
public void nextBuildFresh() {
if (nextBuild) {
nextBuild = false;
}
}
public void requestCompileExit() {
if (currNotifier != null) {
currNotifier.cancelBuild();
} else {
signalText("unable to cancel build process");
}
}
public boolean isStructureDirty() {
return structureDirty;
}
public void setStructureDirty(boolean structureDirty) {
this.structureDirty = structureDirty;
}
public boolean compile(String configFile, BuildProgressMonitor progressMonitor, boolean buildModel) {
if (configFile == null) {
Ajde.getDefault().getErrorHandler().handleError("Tried to build null config file.");
}
init();
try {
AjBuildConfig buildConfig = genBuildConfig(configFile);
if (buildConfig == null) {
return false;
}
buildConfig.setGenerateModelMode(buildModel);
currNotifier = new BuildNotifierAdapter(progressMonitor, buildManager);
buildManager.setProgressListener(currNotifier);
String rtInfo = buildManager.checkRtJar(buildConfig); // !!! will get called twice
if (rtInfo != null) {
Ajde.getDefault().getErrorHandler().handleWarning(
"AspectJ Runtime error: " + rtInfo
+ " Please place a valid aspectjrt.jar on the classpath.");
return false;
}
boolean incrementalEnabled =
buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
boolean successfulBuild;
if (incrementalEnabled && nextBuild) {
successfulBuild = buildManager.incrementalBuild(buildConfig, messageHandler);
} else {
if (incrementalEnabled) {
nextBuild = incrementalEnabled;
}
successfulBuild = buildManager.batchBuild(buildConfig, messageHandler);
}
IncrementalStateManager.recordSuccessfulBuild(configFile,buildManager.getState());
return successfulBuild;
// } catch (OperationCanceledException ce) {
// Ajde.getDefault().getErrorHandler().handleWarning(
// "build cancelled by user");
// return false;
} catch (AbortException e) {
final IMessage message = e.getIMessage();
if (null == message) {
signalThrown(e);
} else if (null != message.getMessage()) {
Ajde.getDefault().getErrorHandler().handleWarning(message.getMessage());
} else if (null != message.getThrown()) {
signalThrown(message.getThrown());
} else {
signalThrown(e);
}
return false;
} catch (Throwable t) {
signalThrown(t);
return false;
}
}
/**
* Generate AjBuildConfig from the local configFile parameter
* plus global project and build options.
* Errors signalled using signal... methods.
* @param configFile
* @return null if invalid configuration,
* corresponding AjBuildConfig otherwise
*/
public AjBuildConfig genBuildConfig(String configFilePath) {
init();
File configFile = new File(configFilePath);
if (!configFile.exists()) {
Ajde.getDefault().getErrorHandler().handleError(
"Config file \"" + configFile + "\" does not exist."
);
return null;
}
String[] args = new String[] { "@" + configFile.getAbsolutePath() };
CountingMessageHandler handler
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
BuildArgParser parser = new BuildArgParser(handler);
AjBuildConfig config = new AjBuildConfig();
parser.populateBuildConfig(config, args, false, configFile);
configureBuildOptions(config,Ajde.getDefault().getBuildManager().getBuildOptions(),handler);
configureProjectOptions(config, Ajde.getDefault().getProjectProperties()); // !!! not what the API intended
// // -- get globals, treat as defaults used if no local values
// AjBuildConfig global = new AjBuildConfig();
// // AMC refactored into two methods to populate buildConfig from buildOptions and
// // project properties - bugzilla 29769.
// BuildOptionsAdapter buildOptions
// = Ajde.getDefault().getBuildManager().getBuildOptions();
// if (!configureBuildOptions(/* global */ config, buildOptions, handler)) {
// return null;
// }
// ProjectPropertiesAdapter projectOptions =
// Ajde.getDefault().getProjectProperties();
// configureProjectOptions(global, projectOptions);
// config.installGlobals(global);
ISourceLocation location = null;
if (config.getConfigFile() != null) {
location = new SourceLocation(config.getConfigFile(), 0);
}
String message = parser.getOtherMessages(true);
if (null != message) {
IMessage m = new Message(message, IMessage.ERROR, null, location);
handler.handleMessage(m);
}
// always force model generation in AJDE
config.setGenerateModelMode(true);
if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) {
config.getOptions().set(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap());
}
return config;
// return fixupBuildConfig(config);
}
// /**
// * Fix up build configuration just before using to compile.
// * This should be delegated to a BuildAdapter callback (XXX)
// * for implementation-specific value checks
// * (e.g., to force use of project classpath rather
// * than local config classpath).
// * This implementation does no checks and returns local.
// * @param local the AjBuildConfig generated to validate
// * @param global
// * @param buildOptions
// * @param projectOptions
// * @return null if unable to fix problems or fixed AjBuildConfig if no errors
// *
// */
// protected AjBuildConfig fixupBuildConfig(AjBuildConfig local) {
// if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) {
// local.getJavaOptions().putAll(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap());
// }
// return local;
// }
// /** signal error text to user */
// protected void signalError(String text) {
// }
// /** signal warning text to user */
// protected void signalWarning(String text) {
//
// }
/** signal text to user */
protected void signalText(String text) {
Ajde.getDefault().getIdeUIAdapter().displayStatusInformation(text);
}
/** signal Throwable to user (summary in GUI, trace to stdout). */
protected void signalThrown(Throwable t) { // nothing to error handler?
String text = LangUtil.unqualifiedClassName(t)
+ " thrown: "
+ t.getMessage();
Ajde.getDefault().getErrorHandler().handleError(text, t);
}
/**
* Populate options in a build configuration, using the Ajde BuildOptionsAdapter.
* Added by AMC 01.20.2003, bugzilla #29769
*/
private static boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) {
LangUtil.throwIaxIfNull(options, "options");
LangUtil.throwIaxIfNull(config, "config");
Map optionsToSet = new HashMap();
LangUtil.throwIaxIfNull(optionsToSet, "javaOptions");
if (options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_5)) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if (options.getSourceOnePointFourMode()
|| options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_4)) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
}
String enc = options.getCharacterEncoding();
if (!LangUtil.isEmpty(enc)) {
optionsToSet.put(CompilerOptions.OPTION_Encoding, enc );
}
String compliance = options.getComplianceLevel();
if (!LangUtil.isEmpty(compliance)) {
String version = CompilerOptions.VERSION_1_4;
if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) {
version = CompilerOptions.VERSION_1_3;
}
optionsToSet.put(CompilerOptions.OPTION_Compliance, version );
optionsToSet.put(CompilerOptions.OPTION_Source, version );
}
String sourceLevel = options.getSourceCompatibilityLevel();
if (!LangUtil.isEmpty(sourceLevel)) {
String slVersion = CompilerOptions.VERSION_1_4;
if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) {
slVersion = CompilerOptions.VERSION_1_3;
}
// never set a lower source level than compliance level
// Mik: prepended with 1.5 check
if (sourceLevel.equals(CompilerOptions.VERSION_1_5)) {
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else {
- String setCompliance = (String) optionsToSet.get( CompilerOptions.OPTION_Compliance);
- if ( ! (setCompliance.equals(CompilerOptions.VERSION_1_4 )
- && slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
- optionsToSet.put(CompilerOptions.OPTION_Source, slVersion);
- }
+ if (optionsToSet.containsKey(CompilerOptions.OPTION_Compliance)) {
+ String setCompliance = (String) optionsToSet.get(CompilerOptions.OPTION_Compliance);
+ if ( ! (setCompliance.equals(CompilerOptions.VERSION_1_4 )
+ && slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
+ optionsToSet.put(CompilerOptions.OPTION_Source, slVersion);
+ }
+ }
}
}
Set warnings = options.getWarnings();
if (!LangUtil.isEmpty(warnings)) {
// turn off all warnings
disableWarnings( optionsToSet );
// then selectively enable those in the set
enableWarnings( optionsToSet, warnings );
} else if (warnings == null) {
// set default warnings on...
enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS);
}
Set debugOptions = options.getDebugLevel();
if (!LangUtil.isEmpty(debugOptions)) {
// default is all options on, so just need to selectively
// disable
boolean sourceLine = false;
boolean varAttr = false;
boolean lineNo = false;
Iterator it = debugOptions.iterator();
while (it.hasNext()){
String debug = (String) it.next();
if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) {
sourceLine = true;
varAttr = true;
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) {
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) {
sourceLine = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) {
varAttr = true;
}
}
if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
}
//XXX we can't turn off import errors in 3.0 stream
// if ( options.getNoImportError() ) {
// javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.WARNING);
// }
if ( options.getPreserveAllLocals() ) {
optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.PRESERVE);
}
if ( !config.isIncrementalMode()
&& options.getIncrementalMode() ) {
config.setIncrementalMode(true);
}
Map jom = options.getJavaOptionsMap();
if (jom!=null) {
String version = (String)jom.get(CompilerOptions.OPTION_Compliance);
if (version!=null && version.equals(CompilerOptions.VERSION_1_5)) {
config.setBehaveInJava5Way(true);
}
}
config.getOptions().set(optionsToSet);
String toAdd = options.getNonStandardOptions();
return LangUtil.isEmpty(toAdd)
? true
: configureNonStandardOptions( config, toAdd, handler );
// ignored: lenient, porting, preprocess, strict, usejavac, workingdir
}
/**
* Helper method for configureBuildOptions
*/
private static void disableWarnings( Map options ) {
options.put(
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.IGNORE);
}
/**
* Helper method for configureBuildOptions
*/
private static void enableWarnings( Map options, Set warnings ) {
Iterator it = warnings.iterator();
while (it.hasNext() ) {
String thisWarning = (String) it.next();
if ( thisWarning.equals( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER )) {
options.put( CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME )) {
options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_DEPRECATION )) {
options.put( CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS )) {
options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD )) {
options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS )) {
options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS )) {
options.put( CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_IMPORTS )) {
options.put( CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_LOCALS )) {
options.put( CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_NLS )) {
options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.WARNING );
}
}
}
/** Local helper method for splitting option strings */
private static List tokenizeString(String str) {
List tokens = new ArrayList();
StringTokenizer tok = new StringTokenizer(str);
while ( tok.hasMoreTokens() ) {
tokens.add(tok.nextToken());
}
return tokens;
}
/**
* Helper method for configure build options.
* This reads all command-line options specified
* in the non-standard options text entry and
* sets any corresponding unset values in config.
* @return false if config failed
*/
private static boolean configureNonStandardOptions(
AjBuildConfig config,
String nonStdOptions,
IMessageHandler messageHandler ) {
if (LangUtil.isEmpty(nonStdOptions)) {
return true;
}
// Break a string into a string array of non-standard options.
// Allows for one option to include a ' '. i.e. assuming it has been quoted, it
// won't accidentally get treated as a pair of options (can be needed for xlint props file option)
List tokens = new ArrayList();
int ind = nonStdOptions.indexOf('\"');
int ind2 = nonStdOptions.indexOf('\"',ind+1);
if ((ind > -1) && (ind2 > -1)) { // dont tokenize within double quotes
String pre = nonStdOptions.substring(0,ind);
String quoted = nonStdOptions.substring(ind+1,ind2);
String post = nonStdOptions.substring(ind2+1,nonStdOptions.length());
tokens.addAll(tokenizeString(pre));
tokens.add(quoted);
tokens.addAll(tokenizeString(post));
} else {
tokens.addAll(tokenizeString(nonStdOptions));
}
String[] args = (String[])tokens.toArray(new String[]{});
// set the non-standard options in an alternate build config
// (we don't want to lose the settings we already have)
CountingMessageHandler counter
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
AjBuildConfig altConfig = AjdtCommand.genBuildConfig(args, counter);
if (counter.hasErrors()) {
return false;
}
// copy globals where local is not set
config.installGlobals(altConfig);
return true;
}
/**
* Add new options from the ProjectPropertiesAdapter to the configuration.
* <ul>
* <li>New list entries are added if not duplicates in,
* for classpath, aspectpath, injars, inpath and sourceroots</li>
* <li>Set only one new entry for output dir or output jar
* only if there is no output dir/jar entry in the config</li>
* </ul>
* Subsequent changes to the ProjectPropertiesAdapter will not affect
* the configuration.
* <p>Added by AMC 01.20.2003, bugzilla #29769
*/
private void configureProjectOptions( AjBuildConfig config, ProjectPropertiesAdapter properties ) {
// XXX no error handling in copying project properties
// Handle regular classpath
String propcp = properties.getClasspath();
if (!LangUtil.isEmpty(propcp)) {
StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator);
List configClasspath = config.getClasspath();
ArrayList toAdd = new ArrayList();
while (st.hasMoreTokens()) {
String entry = st.nextToken();
if (!configClasspath.contains(entry)) {
toAdd.add(entry);
}
}
if (0 < toAdd.size()) {
ArrayList both = new ArrayList(configClasspath.size() + toAdd.size());
both.addAll(configClasspath);
both.addAll(toAdd);
config.setClasspath(both);
Ajde.getDefault().logEvent("building with classpath: " + both);
}
}
// Handle boot classpath
propcp = properties.getBootClasspath();
if (!LangUtil.isEmpty(propcp)) {
StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator);
List configClasspath = config.getBootclasspath();
ArrayList toAdd = new ArrayList();
while (st.hasMoreTokens()) {
String entry = st.nextToken();
if (!configClasspath.contains(entry)) {
toAdd.add(entry);
}
}
if (0 < toAdd.size()) {
ArrayList both = new ArrayList(configClasspath.size() + toAdd.size());
both.addAll(configClasspath);
both.addAll(toAdd);
config.setBootclasspath(both);
Ajde.getDefault().logEvent("building with boot classpath: " + both);
}
}
// set outputdir and outputjar only if both not set
if ((null == config.getOutputDir() && (null == config.getOutputJar()))) {
String outPath = properties.getOutputPath();
if (!LangUtil.isEmpty(outPath)) {
config.setOutputDir(new File(outPath));
}
String outJar = properties.getOutJar();
if (!LangUtil.isEmpty(outJar)) {
config.setOutputJar(new File( outJar ) );
}
}
join(config.getSourceRoots(), properties.getSourceRoots());
join(config.getInJars(), properties.getInJars());
join(config.getInpath(),properties.getInpath());
config.setSourcePathResources(properties.getSourcePathResources());
join(config.getAspectpath(), properties.getAspectPath());
}
void join(Collection target, Collection source) { // XXX dup Util
if ((null == target) || (null == source)) {
return;
}
for (Iterator iter = source.iterator(); iter.hasNext();) {
Object next = iter.next();
if (! target.contains(next)) {
target.add(next);
}
}
}
private void init() {
if (!initialized) { // XXX plug into AJDE initialization
// Ajde.getDefault().setErrorHandler(new DebugErrorHandler());
if (Ajde.getDefault().getMessageHandler() != null) {
this.messageHandler = Ajde.getDefault().getMessageHandler();
} else {
this.messageHandler = new MessageHandlerAdapter();
}
buildManager = new AjBuildManager(messageHandler);
// XXX need to remove the properties file each time!
initialized = true;
}
}
class MessageHandlerAdapter extends MessageHandler {
private TaskListManager taskListManager;
public MessageHandlerAdapter() {
this.taskListManager = Ajde.getDefault().getTaskListManager();
}
public boolean handleMessage(IMessage message) throws AbortException {
IMessage.Kind kind = message.getKind();
if (isIgnoring(kind)
|| (!showInfoMessages && IMessage.INFO.equals(kind))) {
return true;
}
taskListManager.addSourcelineTask(message);
return super.handleMessage(message); // also store...
}
}
public void setState(AjState buildState) {
buildManager.setState(buildState);
buildManager.setStructureModel(buildState.getStructureModel());
}
}
| true | true | private static boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) {
LangUtil.throwIaxIfNull(options, "options");
LangUtil.throwIaxIfNull(config, "config");
Map optionsToSet = new HashMap();
LangUtil.throwIaxIfNull(optionsToSet, "javaOptions");
if (options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_5)) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if (options.getSourceOnePointFourMode()
|| options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_4)) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
}
String enc = options.getCharacterEncoding();
if (!LangUtil.isEmpty(enc)) {
optionsToSet.put(CompilerOptions.OPTION_Encoding, enc );
}
String compliance = options.getComplianceLevel();
if (!LangUtil.isEmpty(compliance)) {
String version = CompilerOptions.VERSION_1_4;
if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) {
version = CompilerOptions.VERSION_1_3;
}
optionsToSet.put(CompilerOptions.OPTION_Compliance, version );
optionsToSet.put(CompilerOptions.OPTION_Source, version );
}
String sourceLevel = options.getSourceCompatibilityLevel();
if (!LangUtil.isEmpty(sourceLevel)) {
String slVersion = CompilerOptions.VERSION_1_4;
if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) {
slVersion = CompilerOptions.VERSION_1_3;
}
// never set a lower source level than compliance level
// Mik: prepended with 1.5 check
if (sourceLevel.equals(CompilerOptions.VERSION_1_5)) {
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else {
String setCompliance = (String) optionsToSet.get( CompilerOptions.OPTION_Compliance);
if ( ! (setCompliance.equals(CompilerOptions.VERSION_1_4 )
&& slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
optionsToSet.put(CompilerOptions.OPTION_Source, slVersion);
}
}
}
Set warnings = options.getWarnings();
if (!LangUtil.isEmpty(warnings)) {
// turn off all warnings
disableWarnings( optionsToSet );
// then selectively enable those in the set
enableWarnings( optionsToSet, warnings );
} else if (warnings == null) {
// set default warnings on...
enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS);
}
Set debugOptions = options.getDebugLevel();
if (!LangUtil.isEmpty(debugOptions)) {
// default is all options on, so just need to selectively
// disable
boolean sourceLine = false;
boolean varAttr = false;
boolean lineNo = false;
Iterator it = debugOptions.iterator();
while (it.hasNext()){
String debug = (String) it.next();
if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) {
sourceLine = true;
varAttr = true;
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) {
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) {
sourceLine = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) {
varAttr = true;
}
}
if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
}
//XXX we can't turn off import errors in 3.0 stream
// if ( options.getNoImportError() ) {
// javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.WARNING);
// }
if ( options.getPreserveAllLocals() ) {
optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.PRESERVE);
}
if ( !config.isIncrementalMode()
&& options.getIncrementalMode() ) {
config.setIncrementalMode(true);
}
Map jom = options.getJavaOptionsMap();
if (jom!=null) {
String version = (String)jom.get(CompilerOptions.OPTION_Compliance);
if (version!=null && version.equals(CompilerOptions.VERSION_1_5)) {
config.setBehaveInJava5Way(true);
}
}
config.getOptions().set(optionsToSet);
String toAdd = options.getNonStandardOptions();
return LangUtil.isEmpty(toAdd)
? true
: configureNonStandardOptions( config, toAdd, handler );
// ignored: lenient, porting, preprocess, strict, usejavac, workingdir
}
| private static boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) {
LangUtil.throwIaxIfNull(options, "options");
LangUtil.throwIaxIfNull(config, "config");
Map optionsToSet = new HashMap();
LangUtil.throwIaxIfNull(optionsToSet, "javaOptions");
if (options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_5)) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if (options.getSourceOnePointFourMode()
|| options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_4)) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
}
String enc = options.getCharacterEncoding();
if (!LangUtil.isEmpty(enc)) {
optionsToSet.put(CompilerOptions.OPTION_Encoding, enc );
}
String compliance = options.getComplianceLevel();
if (!LangUtil.isEmpty(compliance)) {
String version = CompilerOptions.VERSION_1_4;
if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) {
version = CompilerOptions.VERSION_1_3;
}
optionsToSet.put(CompilerOptions.OPTION_Compliance, version );
optionsToSet.put(CompilerOptions.OPTION_Source, version );
}
String sourceLevel = options.getSourceCompatibilityLevel();
if (!LangUtil.isEmpty(sourceLevel)) {
String slVersion = CompilerOptions.VERSION_1_4;
if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) {
slVersion = CompilerOptions.VERSION_1_3;
}
// never set a lower source level than compliance level
// Mik: prepended with 1.5 check
if (sourceLevel.equals(CompilerOptions.VERSION_1_5)) {
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else {
if (optionsToSet.containsKey(CompilerOptions.OPTION_Compliance)) {
String setCompliance = (String) optionsToSet.get(CompilerOptions.OPTION_Compliance);
if ( ! (setCompliance.equals(CompilerOptions.VERSION_1_4 )
&& slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
optionsToSet.put(CompilerOptions.OPTION_Source, slVersion);
}
}
}
}
Set warnings = options.getWarnings();
if (!LangUtil.isEmpty(warnings)) {
// turn off all warnings
disableWarnings( optionsToSet );
// then selectively enable those in the set
enableWarnings( optionsToSet, warnings );
} else if (warnings == null) {
// set default warnings on...
enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS);
}
Set debugOptions = options.getDebugLevel();
if (!LangUtil.isEmpty(debugOptions)) {
// default is all options on, so just need to selectively
// disable
boolean sourceLine = false;
boolean varAttr = false;
boolean lineNo = false;
Iterator it = debugOptions.iterator();
while (it.hasNext()){
String debug = (String) it.next();
if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) {
sourceLine = true;
varAttr = true;
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) {
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) {
sourceLine = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) {
varAttr = true;
}
}
if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
}
//XXX we can't turn off import errors in 3.0 stream
// if ( options.getNoImportError() ) {
// javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.WARNING);
// }
if ( options.getPreserveAllLocals() ) {
optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.PRESERVE);
}
if ( !config.isIncrementalMode()
&& options.getIncrementalMode() ) {
config.setIncrementalMode(true);
}
Map jom = options.getJavaOptionsMap();
if (jom!=null) {
String version = (String)jom.get(CompilerOptions.OPTION_Compliance);
if (version!=null && version.equals(CompilerOptions.VERSION_1_5)) {
config.setBehaveInJava5Way(true);
}
}
config.getOptions().set(optionsToSet);
String toAdd = options.getNonStandardOptions();
return LangUtil.isEmpty(toAdd)
? true
: configureNonStandardOptions( config, toAdd, handler );
// ignored: lenient, porting, preprocess, strict, usejavac, workingdir
}
|
diff --git a/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/frameworks/taskwizard/internal/SubtaskHistory.java b/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/frameworks/taskwizard/internal/SubtaskHistory.java
index 8b242d7b0..0fd47a9be 100644
--- a/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/frameworks/taskwizard/internal/SubtaskHistory.java
+++ b/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/frameworks/taskwizard/internal/SubtaskHistory.java
@@ -1,352 +1,361 @@
/*******************************************************************************
* Copyright (c) 2006 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.core.ui.frameworks.taskwizard.internal;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.core.ui.frameworks.taskwizard.TreeCompoundTask;
import org.eclipse.birt.core.ui.i18n.Messages;
import org.eclipse.birt.core.ui.utils.UIHelper;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.TreeItem;
/**
* History for navigating subtasks.
*
* @since 2.2
*/
public class SubtaskHistory
{
/**
* The history toolbar.
*/
private ToolBarManager historyToolbar;
/**
* A list of history domain elements that stores the history of the visited
* preference pages.
*/
private List historyList = new ArrayList( );
/**
* Stores the current entry into <code>history</code> and
* <code>historyLabels</code>.
*/
private int historyIndex = -1;
/**
* The compound task we implement the history for.
*/
private final TreeCompoundTask parentTask;
/**
* Creates a new history for the given dialog.
*
* @param parentTask
* the parent task to create a history for
*/
public SubtaskHistory( TreeCompoundTask parentTask )
{
this.parentTask = parentTask;
}
/**
* Returns the subtask path (for now: its id) for the history at
* <code>index</code>.
*
* @param index
* the index into the history
* @return the subtask node path at <code>index</code> or
* <code>null</code> if <code>index</code> is not a valid
* history index
*/
private String getHistoryEntry( int index )
{
if ( index >= 0 && index < historyList.size( ) )
{
return (String) historyList.get( index );
}
return null;
}
/**
* Adds the subtask path to the history.
*
* @param entry
* the subtask history entry
*/
public void addHistoryEntry( String entry )
{
if ( historyIndex == -1
|| !historyList.get( historyIndex ).equals( entry ) )
{
historyList.subList( historyIndex + 1, historyList.size( ) )
.clear( );
historyList.add( entry );
historyIndex++;
updateHistoryControls( );
}
}
public void clearHistory( )
{
historyList.clear( );
historyIndex = -1;
updateHistoryControls( );
}
/**
* Sets the current page to be the one corresponding to the given index in
* the page history.
*
* @param index
* the index into the page history
*/
private void jumpToHistory( int index )
{
if ( index >= 0 && index < historyList.size( ) )
{
historyIndex = index;
parentTask.switchTo( getHistoryEntry( index ) );
}
updateHistoryControls( );
}
/**
* Updates the history controls.
*
*/
private void updateHistoryControls( )
{
if ( historyToolbar != null )
{
historyToolbar.update( false );
IContributionItem[] items = historyToolbar.getItems( );
for ( int i = 0; i < items.length; i++ )
{
items[i].update( IAction.ENABLED );
items[i].update( IAction.TOOL_TIP_TEXT );
}
}
}
/**
* Creates the history toolbar and initializes <code>historyToolbar</code>.
*
* @param historyBar
* @param manager
* @return the control of the history toolbar
*/
public ToolBar createHistoryControls( ToolBar historyBar,
ToolBarManager manager )
{
historyToolbar = manager;
/**
* Superclass of the two for-/backward actions for the history.
*/
abstract class HistoryNavigationAction extends Action
implements
IMenuCreator
{
private Menu lastMenu;
protected final static int MAX_ENTRIES = 5;
HistoryNavigationAction( )
{
super( "", IAction.AS_DROP_DOWN_MENU ); //$NON-NLS-1$
}
public IMenuCreator getMenuCreator( )
{
return this;
}
public void dispose( )
{
if ( lastMenu != null )
{
lastMenu.dispose( );
lastMenu = null;
}
}
public Menu getMenu( Control parent )
{
if ( lastMenu != null )
{
lastMenu.dispose( );
}
lastMenu = new Menu( parent );
createEntries( lastMenu );
return lastMenu;
}
public Menu getMenu( Menu parent )
{
return null;
}
protected void addActionToMenu( Menu parent, IAction action )
{
ActionContributionItem item = new ActionContributionItem( action );
item.fill( parent, -1 );
}
protected abstract void createEntries( Menu menu );
}
/**
* Menu entry for the toolbar dropdowns. Instances are direct-jump
* entries in the navigation history.
*/
class HistoryItemAction extends Action
{
private final int index;
HistoryItemAction( int index, String label )
{
super( label, IAction.AS_PUSH_BUTTON );
this.index = index;
}
public void run( )
{
if ( isCurrentEntryAvailable( index ) )
{
jumpToHistory( index );
}
}
}
HistoryNavigationAction backward = new HistoryNavigationAction( ) {
public void run( )
{
int index = historyIndex - 1;
while ( !isCurrentEntryAvailable( index ) )
{
index--;
}
jumpToHistory( index );
}
public boolean isEnabled( )
{
boolean enabled = historyIndex > 0;
if ( enabled )
{
int index = historyIndex - 1;
setToolTipText( isCurrentEntryAvailable( index )
? Messages.getFormattedString( "SubtaskHistory.Tooltip.Back", //$NON-NLS-1$
getItemText( index ) ) : "" ); //$NON-NLS-1$
}
return enabled;
}
protected void createEntries( Menu menu )
{
- int limit = Math.max( 0, historyIndex - MAX_ENTRIES );
- for ( int i = historyIndex - 1; i >= limit; i-- )
+ for ( int i = historyIndex - 1, j = 0; i >= 0
+ && j < MAX_ENTRIES; i-- )
{
- IAction action = new HistoryItemAction( i, getItemText( i ) );
- addActionToMenu( menu, action );
+ if ( isCurrentEntryAvailable( i ) )
+ {
+ IAction action = new HistoryItemAction( i,
+ getItemText( i ) );
+ addActionToMenu( menu, action );
+ j++;
+ }
}
}
};
backward.setText( Messages.getString( "SubtaskHistory.Text.Back" ) ); //$NON-NLS-1$
backward.setActionDefinitionId( "org.eclipse.ui.navigate.backwardHistory" ); //$NON-NLS-1$
backward.setImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_BACKWARD ) ) );
backward.setDisabledImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_BACKWARD_DIS ) ) );
historyToolbar.add( backward );
HistoryNavigationAction forward = new HistoryNavigationAction( ) {
public void run( )
{
int index = historyIndex + 1;
while ( !isCurrentEntryAvailable( index ) )
{
index++;
}
jumpToHistory( index );
}
public boolean isEnabled( )
{
boolean enabled = historyIndex < historyList.size( ) - 1;
if ( enabled )
{
int index = historyIndex + 1;
setToolTipText( isCurrentEntryAvailable( index )
? Messages.getFormattedString( "SubtaskHistory.Tooltip.Forward", //$NON-NLS-1$
getItemText( index ) ) : "" ); //$NON-NLS-1$
}
return enabled;
}
protected void createEntries( Menu menu )
{
- int limit = Math.min( historyList.size( ), historyIndex
- + MAX_ENTRIES + 1 );
- for ( int i = historyIndex + 1; i < limit; i++ )
+ for ( int i = historyIndex + 1, j = 0; i < historyList.size( )
+ && j < MAX_ENTRIES; i++ )
{
- IAction action = new HistoryItemAction( i, getItemText( i ) );
- addActionToMenu( menu, action );
+ if ( isCurrentEntryAvailable( i ) )
+ {
+ IAction action = new HistoryItemAction( i,
+ getItemText( i ) );
+ addActionToMenu( menu, action );
+ j++;
+ }
}
}
};
forward.setText( Messages.getString( "SubtaskHistory.Text.Forward" ) ); //$NON-NLS-1$
forward.setActionDefinitionId( "org.eclipse.ui.navigate.forwardHistory" ); //$NON-NLS-1$
forward.setImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_FORWARD ) ) );
forward.setDisabledImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_FORWARD_DIS ) ) );
historyToolbar.add( forward );
return historyBar;
}
private boolean isCurrentEntryAvailable( int index )
{
return index >= 0
&& index < historyList.size( )
&& parentTask.getNavigatorTree( )
.findTreeItem( getHistoryEntry( index ) ) != null;
}
private String getItemText( int index )
{
TreeItem item = parentTask.getNavigatorTree( )
.findTreeItem( getHistoryEntry( index ) );
if ( item != null )
{
return item.getText( );
}
return Messages.getString( "SubtaskHistory.Text.Invalid" ); //$NON-NLS-1$
}
}
| false | true | public ToolBar createHistoryControls( ToolBar historyBar,
ToolBarManager manager )
{
historyToolbar = manager;
/**
* Superclass of the two for-/backward actions for the history.
*/
abstract class HistoryNavigationAction extends Action
implements
IMenuCreator
{
private Menu lastMenu;
protected final static int MAX_ENTRIES = 5;
HistoryNavigationAction( )
{
super( "", IAction.AS_DROP_DOWN_MENU ); //$NON-NLS-1$
}
public IMenuCreator getMenuCreator( )
{
return this;
}
public void dispose( )
{
if ( lastMenu != null )
{
lastMenu.dispose( );
lastMenu = null;
}
}
public Menu getMenu( Control parent )
{
if ( lastMenu != null )
{
lastMenu.dispose( );
}
lastMenu = new Menu( parent );
createEntries( lastMenu );
return lastMenu;
}
public Menu getMenu( Menu parent )
{
return null;
}
protected void addActionToMenu( Menu parent, IAction action )
{
ActionContributionItem item = new ActionContributionItem( action );
item.fill( parent, -1 );
}
protected abstract void createEntries( Menu menu );
}
/**
* Menu entry for the toolbar dropdowns. Instances are direct-jump
* entries in the navigation history.
*/
class HistoryItemAction extends Action
{
private final int index;
HistoryItemAction( int index, String label )
{
super( label, IAction.AS_PUSH_BUTTON );
this.index = index;
}
public void run( )
{
if ( isCurrentEntryAvailable( index ) )
{
jumpToHistory( index );
}
}
}
HistoryNavigationAction backward = new HistoryNavigationAction( ) {
public void run( )
{
int index = historyIndex - 1;
while ( !isCurrentEntryAvailable( index ) )
{
index--;
}
jumpToHistory( index );
}
public boolean isEnabled( )
{
boolean enabled = historyIndex > 0;
if ( enabled )
{
int index = historyIndex - 1;
setToolTipText( isCurrentEntryAvailable( index )
? Messages.getFormattedString( "SubtaskHistory.Tooltip.Back", //$NON-NLS-1$
getItemText( index ) ) : "" ); //$NON-NLS-1$
}
return enabled;
}
protected void createEntries( Menu menu )
{
int limit = Math.max( 0, historyIndex - MAX_ENTRIES );
for ( int i = historyIndex - 1; i >= limit; i-- )
{
IAction action = new HistoryItemAction( i, getItemText( i ) );
addActionToMenu( menu, action );
}
}
};
backward.setText( Messages.getString( "SubtaskHistory.Text.Back" ) ); //$NON-NLS-1$
backward.setActionDefinitionId( "org.eclipse.ui.navigate.backwardHistory" ); //$NON-NLS-1$
backward.setImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_BACKWARD ) ) );
backward.setDisabledImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_BACKWARD_DIS ) ) );
historyToolbar.add( backward );
HistoryNavigationAction forward = new HistoryNavigationAction( ) {
public void run( )
{
int index = historyIndex + 1;
while ( !isCurrentEntryAvailable( index ) )
{
index++;
}
jumpToHistory( index );
}
public boolean isEnabled( )
{
boolean enabled = historyIndex < historyList.size( ) - 1;
if ( enabled )
{
int index = historyIndex + 1;
setToolTipText( isCurrentEntryAvailable( index )
? Messages.getFormattedString( "SubtaskHistory.Tooltip.Forward", //$NON-NLS-1$
getItemText( index ) ) : "" ); //$NON-NLS-1$
}
return enabled;
}
protected void createEntries( Menu menu )
{
int limit = Math.min( historyList.size( ), historyIndex
+ MAX_ENTRIES + 1 );
for ( int i = historyIndex + 1; i < limit; i++ )
{
IAction action = new HistoryItemAction( i, getItemText( i ) );
addActionToMenu( menu, action );
}
}
};
forward.setText( Messages.getString( "SubtaskHistory.Text.Forward" ) ); //$NON-NLS-1$
forward.setActionDefinitionId( "org.eclipse.ui.navigate.forwardHistory" ); //$NON-NLS-1$
forward.setImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_FORWARD ) ) );
forward.setDisabledImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_FORWARD_DIS ) ) );
historyToolbar.add( forward );
return historyBar;
}
| public ToolBar createHistoryControls( ToolBar historyBar,
ToolBarManager manager )
{
historyToolbar = manager;
/**
* Superclass of the two for-/backward actions for the history.
*/
abstract class HistoryNavigationAction extends Action
implements
IMenuCreator
{
private Menu lastMenu;
protected final static int MAX_ENTRIES = 5;
HistoryNavigationAction( )
{
super( "", IAction.AS_DROP_DOWN_MENU ); //$NON-NLS-1$
}
public IMenuCreator getMenuCreator( )
{
return this;
}
public void dispose( )
{
if ( lastMenu != null )
{
lastMenu.dispose( );
lastMenu = null;
}
}
public Menu getMenu( Control parent )
{
if ( lastMenu != null )
{
lastMenu.dispose( );
}
lastMenu = new Menu( parent );
createEntries( lastMenu );
return lastMenu;
}
public Menu getMenu( Menu parent )
{
return null;
}
protected void addActionToMenu( Menu parent, IAction action )
{
ActionContributionItem item = new ActionContributionItem( action );
item.fill( parent, -1 );
}
protected abstract void createEntries( Menu menu );
}
/**
* Menu entry for the toolbar dropdowns. Instances are direct-jump
* entries in the navigation history.
*/
class HistoryItemAction extends Action
{
private final int index;
HistoryItemAction( int index, String label )
{
super( label, IAction.AS_PUSH_BUTTON );
this.index = index;
}
public void run( )
{
if ( isCurrentEntryAvailable( index ) )
{
jumpToHistory( index );
}
}
}
HistoryNavigationAction backward = new HistoryNavigationAction( ) {
public void run( )
{
int index = historyIndex - 1;
while ( !isCurrentEntryAvailable( index ) )
{
index--;
}
jumpToHistory( index );
}
public boolean isEnabled( )
{
boolean enabled = historyIndex > 0;
if ( enabled )
{
int index = historyIndex - 1;
setToolTipText( isCurrentEntryAvailable( index )
? Messages.getFormattedString( "SubtaskHistory.Tooltip.Back", //$NON-NLS-1$
getItemText( index ) ) : "" ); //$NON-NLS-1$
}
return enabled;
}
protected void createEntries( Menu menu )
{
for ( int i = historyIndex - 1, j = 0; i >= 0
&& j < MAX_ENTRIES; i-- )
{
if ( isCurrentEntryAvailable( i ) )
{
IAction action = new HistoryItemAction( i,
getItemText( i ) );
addActionToMenu( menu, action );
j++;
}
}
}
};
backward.setText( Messages.getString( "SubtaskHistory.Text.Back" ) ); //$NON-NLS-1$
backward.setActionDefinitionId( "org.eclipse.ui.navigate.backwardHistory" ); //$NON-NLS-1$
backward.setImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_BACKWARD ) ) );
backward.setDisabledImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_BACKWARD_DIS ) ) );
historyToolbar.add( backward );
HistoryNavigationAction forward = new HistoryNavigationAction( ) {
public void run( )
{
int index = historyIndex + 1;
while ( !isCurrentEntryAvailable( index ) )
{
index++;
}
jumpToHistory( index );
}
public boolean isEnabled( )
{
boolean enabled = historyIndex < historyList.size( ) - 1;
if ( enabled )
{
int index = historyIndex + 1;
setToolTipText( isCurrentEntryAvailable( index )
? Messages.getFormattedString( "SubtaskHistory.Tooltip.Forward", //$NON-NLS-1$
getItemText( index ) ) : "" ); //$NON-NLS-1$
}
return enabled;
}
protected void createEntries( Menu menu )
{
for ( int i = historyIndex + 1, j = 0; i < historyList.size( )
&& j < MAX_ENTRIES; i++ )
{
if ( isCurrentEntryAvailable( i ) )
{
IAction action = new HistoryItemAction( i,
getItemText( i ) );
addActionToMenu( menu, action );
j++;
}
}
}
};
forward.setText( Messages.getString( "SubtaskHistory.Text.Forward" ) ); //$NON-NLS-1$
forward.setActionDefinitionId( "org.eclipse.ui.navigate.forwardHistory" ); //$NON-NLS-1$
forward.setImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_FORWARD ) ) );
forward.setDisabledImageDescriptor( ImageDescriptor.createFromURL( UIHelper.getURL( UIHelper.IMAGE_NAV_FORWARD_DIS ) ) );
historyToolbar.add( forward );
return historyBar;
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/DispatchTask.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/DispatchTask.java
index dcd12283b..bbb7837c3 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/DispatchTask.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/DispatchTask.java
@@ -1,69 +1,69 @@
/*
* 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.servlet.sip.core.dispatchers;
import javax.sip.ServerTransaction;
import javax.sip.SipProvider;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.message.SipServletMessageImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
/**
* Generic class that allows async execution of tasks in one of the executors depending
* on what session isolation you need. Error handling is also done here.
*
* @author Vladimir Ralev
*
*/
public abstract class DispatchTask implements Runnable {
private static final Logger logger = Logger.getLogger(DispatchTask.class);
protected SipServletMessageImpl sipServletMessage;
protected SipProvider sipProvider;
public DispatchTask(SipServletMessageImpl sipServletMessage, SipProvider sipProvider) {
this.sipProvider = sipProvider;
this.sipServletMessage = sipServletMessage;
}
abstract public void dispatch() throws DispatcherException;
public void run() {
dispatchAndHandleExceptions();
}
public void dispatchAndHandleExceptions () {
try {
dispatch();
} catch (Throwable t) {
logger.error("Unexpected exception while processing message " + sipServletMessage, t);
if(sipServletMessage instanceof SipServletRequestImpl) {
SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
- if(!Request.ACK.equalsIgnoreCase(sipServletRequest.getMethod()) ||
+ if(!Request.ACK.equalsIgnoreCase(sipServletRequest.getMethod()) &&
!Request.PRACK.equalsIgnoreCase(sipServletRequest.getMethod())) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
}
}
}
}
| true | true | public void dispatchAndHandleExceptions () {
try {
dispatch();
} catch (Throwable t) {
logger.error("Unexpected exception while processing message " + sipServletMessage, t);
if(sipServletMessage instanceof SipServletRequestImpl) {
SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(!Request.ACK.equalsIgnoreCase(sipServletRequest.getMethod()) ||
!Request.PRACK.equalsIgnoreCase(sipServletRequest.getMethod())) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
}
}
}
| public void dispatchAndHandleExceptions () {
try {
dispatch();
} catch (Throwable t) {
logger.error("Unexpected exception while processing message " + sipServletMessage, t);
if(sipServletMessage instanceof SipServletRequestImpl) {
SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(!Request.ACK.equalsIgnoreCase(sipServletRequest.getMethod()) &&
!Request.PRACK.equalsIgnoreCase(sipServletRequest.getMethod())) {
MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, (ServerTransaction) sipServletRequest.getTransaction(), (Request) sipServletRequest.getMessage(), sipProvider);
}
}
}
}
|
diff --git a/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/GenericStorage.java b/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/GenericStorage.java
index 3fdd9229..59544c49 100644
--- a/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/GenericStorage.java
+++ b/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/GenericStorage.java
@@ -1,1537 +1,1537 @@
/* Copyright 2010 University of Cambridge
* Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.chain.csp.persistence.services;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.collectionspace.chain.csp.persistence.services.connection.ConnectionException;
import org.collectionspace.chain.csp.persistence.services.connection.RequestMethod;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL;
import org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection;
import org.collectionspace.chain.csp.schema.Field;
import org.collectionspace.chain.csp.schema.FieldSet;
import org.collectionspace.chain.csp.schema.Group;
import org.collectionspace.chain.csp.schema.Record;
import org.collectionspace.chain.csp.schema.Repeat;
import org.collectionspace.chain.util.json.JSONUtils;
import org.collectionspace.csp.api.core.CSPRequestCache;
import org.collectionspace.csp.api.core.CSPRequestCredentials;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.collectionspace.csp.helper.persistence.ContextualisedStorage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GenericStorage implements ContextualisedStorage {
private static final Logger log=LoggerFactory.getLogger(GenericStorage.class);
protected ServicesConnection conn;
protected Record r;
protected Map<String,String> view_good=new HashMap<String,String>();// map of servicenames of fields to descriptors
protected Map<String,String> view_map=new HashMap<String,String>(); // map of csid to service name of field
protected Set<String> xxx_view_deurn=new HashSet<String>();
protected Map<String,List<String>> view_merge = new HashMap<String, List<String>>();
public GenericStorage(Record r,ServicesConnection conn) throws DocumentException, IOException {
this.conn=conn;
this.r=r;
}
protected void resetGlean(Record r){
view_good=new HashMap<String,String>();
view_map=new HashMap<String,String>();
xxx_view_deurn=new HashSet<String>();
view_merge = new HashMap<String, List<String>>();
initializeGlean(r);
}
protected void resetGlean(Record r,Map<String,String> reset_good, Map<String,String> reset_map, Set<String> reset_deurn, Map<String,List<String>> reset_merge, Boolean init){
view_good=reset_good;
view_map=reset_map;
xxx_view_deurn=reset_deurn;
view_merge = reset_merge;
if(init){
initializeGlean(r);
}
}
protected void initializeGlean(Record r){
// Number
if(r.getMiniNumber()!=null){
view_good.put("number",r.getMiniNumber().getID());
view_map.put(r.getMiniNumber().getServicesTag(),r.getMiniNumber().getID());
if(r.getMiniNumber().hasMergeData()){
view_merge.put("number",r.getMiniNumber().getAllMerge());
}
if(r.getMiniNumber().hasAutocompleteInstance())
xxx_view_deurn.add(r.getMiniNumber().getID());
}
// Summary
if(r.getMiniSummary() !=null){
view_good.put("summary",r.getMiniSummary().getID());
view_map.put(r.getMiniSummary().getServicesTag(),r.getMiniSummary().getID());
if(r.getMiniSummary().hasMergeData()){
view_merge.put("summary",r.getMiniSummary().getAllMerge());
}
if(r.getMiniSummary().hasAutocompleteInstance())
xxx_view_deurn.add(r.getMiniSummary().getID());
}
//complex summary list
if(r.getAllMiniDataSets().length>0){
for(String setName : r.getAllMiniDataSets()){
String prefix = setName;
if(r.getMiniDataSetByName(prefix).length>0 && !prefix.equals("")){
for(FieldSet fs : r.getMiniDataSetByName(prefix)){
view_good.put(prefix+"_"+ fs.getID(),fs.getID());
view_map.put(fs.getServicesTag(),fs.getID());
if(fs instanceof Field) {
Field f=(Field)fs;
// Single field
if(f.hasMergeData()){
view_merge.put(prefix+"_"+f.getID(),f.getAllMerge());
for(String fm : f.getAllMerge()){
if(fm!=null){
if(r.getRepeatField(fm).hasAutocompleteInstance()){
xxx_view_deurn.add(f.getID());
}
}
}
}
if(f.hasAutocompleteInstance()){
xxx_view_deurn.add(f.getID());
}
}
}
}
}
}
}
/**
* Set the csids that were retrieved in the cache
* @param cache The cache itself
* @param path The path to the object on the service layer
* @param key The key for the node in the json file
* @param value The value for the node in the json file
*/
protected void setGleanedValue(CSPRequestCache cache,String path,String key,String value) {
cache.setCached(getClass(),new String[]{"glean",path,key},value);
}
/**
* Get a value out of the cache
* @param {CSPRequestCache} cache The cache in which we store the csids
* @param {String} path The path to the record
* @param {String} key The key to recreate the unique key to retrieve the cached value
* @return {String} The csid that was stored
*/
protected String getGleanedValue(CSPRequestCache cache,String path,String key) {
return (String)cache.getCached(getClass(),new String[]{"glean",path,key});
}
/**
* Convert an XML file into a JSON string
* @param {JSONObject} out The JSON string to which the XML has been converted
* @param {Document} in The XML document that has to be converted
* @throws JSONException
*/
protected void convertToJson(JSONObject out,Document in, String permlevel, String section,String csid,String ims_base) throws JSONException {
XmlJsonConversion.convertToJson(out,r,in,permlevel,section,csid,ims_base);
}
/**
* Convert an XML file into a JSON string
* @param out
* @param in
* @param r
* @throws JSONException
*/
protected void convertToJson(JSONObject out,Document in, Record r, String permlevel, String section, String csid) throws JSONException {
XmlJsonConversion.convertToJson(out,r,in,permlevel,section,csid,conn.getIMSBase());
}
protected void getGleaned(){
}
protected String xxx_deurn(String in) throws UnderlyingStorageException {
if(!in.startsWith("urn:"))
return in;
if(!in.endsWith("'"))
return in;
in=in.substring(0,in.length()-1);
int pos=in.lastIndexOf("'");
if(pos==-1)
return in+"'";
try {
return URLDecoder.decode(in.substring(pos+1),"UTF8");
} catch (UnsupportedEncodingException e) {
throw new UnderlyingStorageException("No UTF8!");
}
}
/**
* Get a mini view of the record
* Currently used for relatedObj relatedProc Find&Edit and Search
* this needs to be refactored as the 4 areas have different data set needs
*
* @param cache
* @param creds
* @param filePath
* @param extra - used to define which subset of data to use expects related|terms|search|list
* @return
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
* @throws JSONException
*/
public JSONObject miniViewRetrieveJSON(CSPRequestCache cache,CSPRequestCredentials creds,String filePath,String extra, String cachelistitem, Record thisr) throws ExistException,UnimplementedException, UnderlyingStorageException, JSONException {
if(cachelistitem==null){
cachelistitem = thisr.getServicesURL()+"/"+filePath;
}
JSONObject out=new JSONObject();
JSONObject summarylist=new JSONObject();
String summarylistname = "summarylist_";
if(!extra.equals("")){
summarylistname = extra+"_";
}
Set<String> to_get=new HashSet<String>(view_good.keySet());
// Try to fullfil from gleaned info
//gleaned is info that everytime we read a record we cache certain parts of it
for(String fieldname : view_good.keySet()) {
//only get the info that is needed
String name = fieldname;
if(!name.startsWith(summarylistname) && !name.equals("summary") && !name.equals("number")){
to_get.remove(fieldname);
continue;
}
String gleaned = null;
String good = view_good.get(fieldname);
if(view_merge.containsKey(fieldname)){
List<String> mergeids = view_merge.get(fieldname);
for(String id : mergeids){
if(id == null)
continue;
//iterate for merged ids
gleaned=getGleanedValue(cache,cachelistitem,id);
if(gleaned!=null && gleaned !=""){
//if find value stop
break;
}
}
}
else{
gleaned=getGleanedValue(cache,cachelistitem,good);
}
if(gleaned==null)
continue;
if(xxx_view_deurn.contains(good))
gleaned=xxx_deurn(gleaned);
if(name.startsWith(summarylistname)){
name = name.substring(summarylistname.length());
summarylist.put(name, gleaned);
}
else{
out.put(fieldname,gleaned);
}
to_get.remove(fieldname);
}
// Do a full request only if values in list of fields returned != list from cspace-config
if(to_get.size()>0) {
JSONObject data=simpleRetrieveJSON(creds,cache,filePath,thisr);
for(String fieldname : to_get) {
String good = view_good.get(fieldname);
String value = null;
if(view_merge.containsKey(fieldname)){
List<String> mergeids = view_merge.get(fieldname);
for(String id : mergeids){
if(id == null)
continue;
value = JSONUtils.checkKey(data, id);
//iterate for merged ids
if(value!=null && value !=""){
//if find value stop
break;
}
}
}
else{
value = JSONUtils.checkKey(data, good);
}
//this might work with repeat objects
if(value != null){
String vkey=fieldname;
if(xxx_view_deurn.contains(good))
value=xxx_deurn(value);
if(vkey.startsWith(summarylistname)){
String name = vkey.substring(summarylistname.length());
summarylist.put(name, value);
}
else{
out.put(vkey,value);
}
}
else{
String vkey=fieldname;
if(vkey.startsWith(summarylistname)){
String name = vkey.substring(summarylistname.length());
summarylist.put(name, "");
}
else{
out.put(vkey,"");
}
}
}
}
if(summarylist.length()>0){
out.put("summarylist", summarylist);
}
return out;
}
/**
* return data just as the service layer gives it to the App layer
* no extra columns required
* @param creds
* @param cache
* @param filePath
* @return
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/
public JSONObject simpleRetrieveJSON(CSPRequestCredentials creds,CSPRequestCache cache,String filePath) throws ExistException,
UnimplementedException, UnderlyingStorageException {
JSONObject out=new JSONObject();
out = simpleRetrieveJSON(creds,cache,filePath,r);
return out;
}
/**
* return data just as the service layer gives it to the App layer
* no extra columns required
* @param creds
* @param cache
* @param filePath
* @param Record
* @return
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/
public JSONObject simpleRetrieveJSON(CSPRequestCredentials creds,CSPRequestCache cache,String filePath, Record thisr) throws ExistException,
UnimplementedException, UnderlyingStorageException {
JSONObject out=new JSONObject();
out = simpleRetrieveJSON(creds,cache,filePath,thisr.getServicesURL()+"/", thisr);
return out;
}
public JSONObject simpleRetrieveJSON(CSPRequestCredentials creds,CSPRequestCache cache,String filePath, String servicesurl, Record thisr) throws ExistException,
UnimplementedException, UnderlyingStorageException {
String csid="";
String[] path_parts = filePath.split("/");
if(path_parts.length>1)
csid = path_parts[1];
else
csid = filePath;
JSONObject out=new JSONObject();
try {
String softpath = filePath;
if(thisr.hasSoftDeleteMethod()){
softpath = softpath(filePath);
}
if(thisr.hasHierarchyUsed("screen")){
softpath = hierarchicalpath(softpath);
}
if(thisr.isMultipart()){
ReturnedMultipartDocument doc = conn.getMultipartXMLDocument(RequestMethod.GET,servicesurl+softpath,null,creds,cache);
if((doc.getStatus()<200 || doc.getStatus()>=300))
throw new UnderlyingStorageException("Does not exist ",doc.getStatus(),softpath);
for(String section : thisr.getServicesRecordPaths()) {
String path=thisr.getServicesRecordPath(section);
String[] parts=path.split(":",2);
if(doc.getDocument(parts[0]) != null ){
convertToJson(out,doc.getDocument(parts[0]), thisr, "GET",section , csid);
}
}
}
else{
ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, servicesurl+softpath,null, creds, cache);
if((doc.getStatus()<200 || doc.getStatus()>=300))
throw new UnderlyingStorageException("Does not exist ",doc.getStatus(),softpath);
convertToJson(out,doc.getDocument(), thisr, "GET", "common",csid);
}
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Service layer exception",e);
}
try{
for(FieldSet fs : thisr.getAllSubRecords("GET")){
Boolean validator = true;
Record sr = fs.usesRecordId();
if(fs.usesRecordValidator()!= null){
validator = false;
if(out.has(fs.usesRecordValidator())){
String test = out.getString(fs.usesRecordValidator());
if(test!=null && !test.equals("")){
validator = true;
}
}
}
if(validator){
String getPath = servicesurl+filePath + "/" + sr.getServicesURL();
if(null !=fs.getServicesUrl()){
getPath = fs.getServicesUrl();
}
if(fs.getWithCSID()!=null) {
getPath = getPath + "/" + out.getString(fs.getWithCSID());
}
//seems to work for media blob
//need to get update and delete working? tho not going to be used for media as handling blob seperately
if(fs instanceof Group){
JSONObject outer = simpleRetrieveJSON(creds,cache,getPath,"",sr);
JSONArray group = new JSONArray();
group.put(outer);
out.put(fs.getID(), group);
}
if(fs instanceof Repeat){
//NEED TO GET A LIST OF ALL THE THINGS
JSONArray repeat = new JSONArray();
String path = getPath;
String node = "/"+sr.getServicesListPath().split("/")[0]+"/*";
while(!path.equals("")){
JSONObject data = getListView(creds,cache,path,node,"/"+sr.getServicesListPath(),"csid",false,r);
if(data.has("listItems")){
String[] results = (String[]) data.get("listItems");
for(String result : results) {
JSONObject rout=simpleRetrieveJSON( creds, cache,getPath+"/"+result, "", sr);
rout.put("_subrecordcsid", result);//add in csid so I can do update with a modicum of confidence
repeat.put(rout);
}
}
if(data.has("pagination")){
Integer ps = Integer.valueOf(data.getJSONObject("pagination").getString("pageSize"));
Integer pn = Integer.valueOf(data.getJSONObject("pagination").getString("pageNum"));
Integer ti = Integer.valueOf(data.getJSONObject("pagination").getString("totalItems"));
if(ti > (ps * (pn +1))){
JSONObject restrictions = new JSONObject();
restrictions.put("pageSize", Integer.toString(ps));
restrictions.put("pageNum", Integer.toString(pn + 1));
path = getRestrictedPath(getPath, restrictions, sr.getServicesSearchKeyword(), "", false, "");
//need more values
}
else{
path = "";
}
}
}
//group.put(outer);
out.put(fs.getID(), repeat);
}
}
}
}
catch (Exception e) {
//ignore exceptions for sub records at the moment - make it more intellegent later
//throw new UnderlyingStorageException("Service layer exception",e);
}
return out;
}
/**
* Construct different data sets for different view needs
*
*
* @param storage
* @param creds
* @param cache
* @param filePath
* @param view - view|refs used to define what type of data is needed
* @return
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
* @throws JSONException
* @throws UnsupportedEncodingException
* @throws ConnectionException
*/
public JSONObject viewRetrieveJSON(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String filePath,String view, String extra, JSONObject restrictions) throws ExistException,UnimplementedException, UnderlyingStorageException, JSONException, UnsupportedEncodingException {
if(view.equals("view")){
//get a view of a specific item e.g. for search results
return miniViewRetrieveJSON(cache,creds,filePath, extra, null,r);
}
else if("refs".equals(view)){
String path = r.getServicesURL()+"/"+filePath+"/authorityrefs";
return refViewRetrieveJSON(storage,creds,cache,path,restrictions);
}
else if("refObjs".equals(view)){
String path = r.getServicesURL()+"/"+filePath+"/refObjs";
return refObjViewRetrieveJSON(storage,creds,cache,path);
}
else
return new JSONObject();
}
// XXX support URNs for reference
protected JSONObject miniForURI(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String refname,String uri, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
return storage.retrieveJSON(storage,creds,cache,"direct/urn/"+uri+"/"+refname, restrictions);
}
/**
* get data needed for terms Used block of a record
* @param creds
* @param cache
* @param path
* @return
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
* @throws JSONException
* @throws UnsupportedEncodingException
*/
public JSONObject refViewRetrieveJSON(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String path, JSONObject restrictions) throws ExistException,UnimplementedException, UnderlyingStorageException, JSONException, UnsupportedEncodingException {
try {
JSONObject out=new JSONObject();
//not all the records need a reference, look in cspace-config.xml for which that don't
if(r.hasTermsUsed()){
path = getRestrictedPath(path, restrictions,"kw", "", false, "");
if(r.hasSoftDeleteMethod()){//XXX completely not the right thinsg to do but a good enough hack
path = softpath(path);
}
if(r.hasHierarchyUsed("screen")){
path = hierarchicalpath(path);
}
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET,path,null,creds,cache);
if(all.getStatus()!=200)
throw new ConnectionException("Bad request during identifier cache map update: status not 200",all.getStatus(),path);
Document list=all.getDocument();
for(Object node : list.selectNodes("authority-ref-list/authority-ref-item")) {
if(!(node instanceof Element))
continue;
if(((Element) node).hasContent()){
String key=((Element)node).selectSingleNode("sourceField").getText();
String uri=((Element)node).selectSingleNode("uri").getText();
String refname=((Element)node).selectSingleNode("refName").getText();
String fieldName = key;
if(key.split(":").length>1){
fieldName = key.split(":")[1];
}
Field fieldinstance= null;
if(r.getRepeatField(fieldName) instanceof Repeat){
Repeat rp = (Repeat)r.getRepeatField(fieldName);
for(FieldSet a : rp.getChildren("GET")){
if(a instanceof Field && a.hasAutocompleteInstance()){
fieldinstance = (Field)a;
}
}
}
else{
fieldinstance = (Field)r.getRepeatField(fieldName);
}
if(fieldinstance != null){
if(uri!=null && uri.startsWith("/"))
uri=uri.substring(1);
JSONObject data=miniForURI(storage,creds,cache,refname,uri,restrictions);
data.put("sourceFieldselector", fieldinstance.getSelector());
data.put("sourceFieldName", fieldName);
data.put("sourceFieldType", r.getID());
if(out.has(key)){
JSONArray temp = out.getJSONArray(key).put(data);
out.put(key,temp);
}
else{
JSONArray temp = new JSONArray();
temp.put(data);
out.put(key,temp);
}
}
}
}
}
return out;
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection problem"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
/**
* get data needed for list of objects related to a termUsed
* @param storage
* @param creds
* @param cache
* @param path
* @return
* @throws ExistException
* @throws UnderlyingStorageException
* @throws JSONException
* @throws UnimplementedException
*/
public JSONObject refObjViewRetrieveJSON(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String path) throws ExistException, UnderlyingStorageException, JSONException, UnimplementedException {
JSONObject out=new JSONObject();
try{
Map<String,String> reset_good=new HashMap<String,String>();// map of servicenames of fields to descriptors
Map<String,String> reset_map=new HashMap<String,String>(); // map of csid to service name of field
Set<String> reset_deurn=new HashSet<String>();
Map<String,List<String>> reset_merge = new HashMap<String, List<String>>();
if(r.hasRefObjUsed()){
//XXX need a way to append the data needed from the field whcih we don't know until after we have got the information...
reset_map.put("docType", "docType");
reset_map.put("docId", "docId");
reset_map.put("docNumber", "docNumber");
reset_map.put("sourceField", "sourceField");
reset_map.put("uri", "uri");
reset_good.put("terms_docType", "docType");
reset_good.put("terms_docId", "docId");
reset_good.put("terms_docNumber", "docNumber");
reset_good.put("terms_sourceField", "sourceField");
view_good = reset_good;
view_map = reset_map;
xxx_view_deurn = reset_deurn;
view_merge = reset_merge;
String nodeName = "authority-ref-doc-list/authority-ref-doc-item";
JSONObject data = getRepeatableListView(storage,creds,cache,path,nodeName,"/authority-ref-doc-list/authority-ref-doc-item","uri", true, r);//XXX this might be the wrong record to pass to checkf or hard/soft delet listing
reset_good = view_good;
reset_map = view_map;
reset_deurn = xxx_view_deurn;
reset_merge = view_merge;
JSONArray recs = data.getJSONArray("listItems");
//String[] filepaths = (String[]) data.get("listItems");
for (int i = 0; i < recs.length(); ++i) {
String uri = recs.getJSONObject(i).getString("csid");
String filePath = recs.getJSONObject(i).getString("csid");
if(filePath!=null && filePath.startsWith("/"))
filePath=filePath.substring(1);
String[] parts=filePath.split("/");
String recordurl = parts[0];
Record thisr = r.getSpec().getRecordByServicesUrl(recordurl);
resetGlean(thisr,reset_good,reset_map,reset_deurn,reset_merge, true);// what glean info required for this one..
String csid = parts[parts.length-1];
JSONObject dataitem = miniViewRetrieveJSON(cache,creds,csid, "terms", r.getServicesURL()+"/"+uri, thisr);
dataitem.getJSONObject("summarylist").put("uri",filePath);
String key = recs.getJSONObject(i).getString("sourceField");
dataitem.getJSONObject("summarylist").put("sourceField",key);
String fieldName = "unknown";
String fieldSelector = "unknown";
if(key.contains(":")){
fieldName = key.split(":")[1];
//XXX fixCSPACE-2909 would be nice if they gave us the actual field rather than the parent
//XXX CSPACE-2586
while(thisr.getRepeatField(fieldName) instanceof Repeat || thisr.getRepeatField(fieldName) instanceof Group ){
fieldName = ((Repeat)thisr.getRepeatField(fieldName)).getChildren("GET")[0].getID();
}
Field fieldinstance = (Field)thisr.getRepeatField(fieldName);
fieldSelector = fieldinstance.getSelector();
}
dataitem.put("csid", csid);
dataitem.put("sourceFieldselector", fieldSelector);
dataitem.put("sourceFieldName", fieldName);
dataitem.put("sourceFieldType", dataitem.getJSONObject("summarylist").getString("docType"));
out.put(key,dataitem);
}
/*
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET,path,null,creds,cache);
String test = all.getDocument().asXML();
if(all.getStatus()!=200)
throw new ConnectionException("Bad request during identifier cache map update: status not 200");
Document list=all.getDocument();
for(Object node : list.selectNodes("authority-ref-doc-list/authority-ref-doc-item")) {
if(!(node instanceof Element))
continue;
String key=((Element)node).selectSingleNode("sourceField").getText();
String uri=((Element)node).selectSingleNode("uri").getText();
String docid=((Element)node).selectSingleNode("docId").getText();
String doctype=((Element)node).selectSingleNode("docType").getText();
String fieldName = key.split(":")[1];
//Field fieldinstance = (Field)r.getRepeatField(fieldName);
if(uri!=null && uri.startsWith("/"))
uri=uri.substring(1);
JSONObject data = new JSONObject();//=miniForURI(storage,creds,cache,refname,uri);
data.put("csid", docid);
// data.put("sourceFieldselector", fieldinstance.getSelector());
data.put("sourceFieldName", fieldName);
data.put("sourceFieldType", doctype);
out.put(key,data);
}
*/
}
return out;
} catch (ConnectionException e) {
log.error("failed to retrieve refObjs for "+path);
JSONObject dataitem = new JSONObject();
dataitem.put("csid", "");
dataitem.put("sourceFieldselector", "Functionality Failed");
dataitem.put("sourceFieldName", "Functionality Failed");
dataitem.put("sourceFieldType", "Functionality Failed");
dataitem.put("message", e.getMessage());
out.put("Functionality Failed",dataitem);
//return out;
throw new UnderlyingStorageException("Connection problem"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject,Record thisr, String serviceurl)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Map<String,Document> parts=new HashMap<String,Document>();
Document doc = null;
for(String section : thisr.getServicesRecordPaths()) {
String path=thisr.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
doc=XmlJsonConversion.convertToXml(thisr,jsonObject,section,"PUT");
if(doc !=null){
parts.put(record_path[0],doc);
// log.info(doc.asXML());
}
}
int status = 0;
if(thisr.isMultipart()){
ReturnedMultipartDocument docm = conn.getMultipartXMLDocument(RequestMethod.PUT,serviceurl+filePath,parts,creds,cache);
status = docm.getStatus();
}
else{
ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, serviceurl+filePath, doc, creds, cache);
status = docm.getStatus();
}
//XXX Completely untested subrecord update
- for(FieldSet fs : r.getAllSubRecords("PUT")){
+ for(FieldSet fs : thisr.getAllSubRecords("PUT")){
Record sr = fs.usesRecordId();
if(sr.isRealRecord()){//only deal with ones which are separate Records in the services
//get list of existing subrecords
JSONObject existingcsid = new JSONObject();
JSONObject updatecsid = new JSONObject();
JSONArray createcsid = new JSONArray();
String getPath = serviceurl+filePath + "/" + sr.getServicesURL();
String node = "/"+sr.getServicesListPath().split("/")[0]+"/*";
JSONObject data = getListView(creds,cache,getPath,node,"/"+sr.getServicesListPath(),"csid",false, sr);
String[] filepaths = (String[]) data.get("listItems");
for(String uri : filepaths) {
String path = uri;
if(path!=null && path.startsWith("/"))
path=path.substring(1);
existingcsid.put(path,"original");
}
//how does that compare to what we need
if(sr.isType("authority")){
//need to use configuredVocabStorage
}
else{
if(fs instanceof Field){
JSONObject subdata = new JSONObject();
//loop thr jsonObject and find the fields I need
for(FieldSet subfs: sr.getAllFields("PUT")){
String key = subfs.getID();
if(jsonObject.has(key)){
subdata.put(key, jsonObject.get(key));
}
}
if(filepaths.length ==0){
//create
createcsid.put(subdata);
}
else{
//update - there should only be one
String firstcsid = filepaths[0];
updatecsid.put(firstcsid, subdata);
existingcsid.remove(firstcsid);
}
}
else if(fs instanceof Group){//JSONObject
//do we have a csid
//subrecorddata.put(value);
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONObject){
if(((JSONObject) subdata).has("_subrecordcsid")){
String thiscsid = ((JSONObject) subdata).getString("_subrecordcsid");
//update
if(existingcsid.has(thiscsid)){
updatecsid.put(thiscsid, (JSONObject) subdata);
existingcsid.remove(thiscsid);
}
else{
//something has gone wrong... best just create it from scratch
createcsid.put(subdata);
}
}
else{
//create
createcsid.put(subdata);
}
}
}
}
else{//JSONArray Repeat
//need to find if we have csid's for each one
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
if(((JSONObject) subrecord).has("_subrecordcsid")){
String thiscsid = ((JSONObject) subrecord).getString("_subrecordcsid");
//update
if(existingcsid.has(thiscsid)){
updatecsid.put(thiscsid, (JSONObject) subrecord);
existingcsid.remove(thiscsid);
}
else{
//something has gone wrong... best just create it from scratch
createcsid.put(subrecord);
}
}
else{
//create
createcsid.put(subrecord);
}
}
}
}
}
String savePath = serviceurl+filePath + "/" + sr.getServicesURL()+"/";
//do delete JSONObject existingcsid = new JSONObject();
Iterator<String> rit=existingcsid.keys();
while(rit.hasNext()) {
String key=rit.next();
deleteJSON(root,creds,cache,key,savePath,sr);
}
//do update JSONObject updatecsid = new JSONObject();
Iterator<String> keys = updatecsid.keys();
while(keys.hasNext()) {
String key=keys.next();
JSONObject value = updatecsid.getJSONObject(key);
updateJSON( root, creds, cache, key, value, sr, savePath);
}
//do create JSONArray createcsid = new JSONArray();
for(int i=0;i<createcsid.length();i++){
JSONObject value = createcsid.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,value,savePath);
}
}
}
}
//if(status==404)
// throw new ExistException("Not found: "+serviceurl+filePath);
if(status>299 || status<200)
throw new UnderlyingStorageException("Bad response ",status,serviceurl+filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnimplementedException("JSONException",e);
}
}
public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject,Record thisr)
throws ExistException, UnimplementedException, UnderlyingStorageException {
updateJSON( root, creds, cache, filePath, jsonObject, thisr, thisr.getServicesURL()+"/");
}
public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject)
throws ExistException, UnimplementedException, UnderlyingStorageException {
updateJSON( root, creds, cache, filePath, jsonObject, r);
}
/**
* needs some tests.. just copied from ConfiguredVocabStorage
* @param root
* @param creds
* @param cache
* @param myr
* @param jsonObject
* @param savePrefix
* @return
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/
public String subautocreateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,Record myr,JSONObject jsonObject, String savePrefix)
throws ExistException, UnimplementedException, UnderlyingStorageException{
try {
ReturnedURL url = null;
Document doc = null;
//used by userroles and permroles as they have complex urls
if(myr.hasPrimaryField()){
//XXX test if works: need to delete first before create/update
// deleteJSON(root,creds,cache,filePath);
for(String section : myr.getServicesRecordPaths()) {
doc=XmlJsonConversion.convertToXml(myr,jsonObject,section,"POST");
String path = myr.getServicesURL();
path = path.replace("*", getSubCsid(jsonObject,myr.getPrimaryField()));
deleteJSON(root,creds,cache,path);
url = conn.getURL(RequestMethod.POST, path, doc, creds, cache);
}
}
else{
url = autoCreateSub(creds, cache, jsonObject, doc, savePrefix, myr);
}
// create related sub records?
for(FieldSet allfs : myr.getAllSubRecords("POST")){
Record sr = allfs.usesRecordId();
//sr.getID()
if(sr.isType("authority")){
}
else{
String savePath = url.getURL() + "/" + sr.getServicesURL();
if(jsonObject.has(sr.getID())){
Object subdata = jsonObject.get(sr.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
else if(subdata instanceof JSONObject){
JSONObject subrecord = (JSONObject)subdata;
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
}
}
return url.getURLTail();
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Connection exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Cannot parse surrounding JSON"+e.getLocalizedMessage(),e);
}
}
/**
* Convert the JSON from the UI Layer into XML for the Service layer while using the XML structure from cspace-config.xml
* Send the XML through to the Service Layer to store it in the database
* The Service Layer returns a url to the object we just stored.
* @param {ContextualisedStorage} root
* @param {CSPRequestCredentials} creds
* @param {CSPRequestCache} cache
* @param {String} filePath part of the path to the Service URL (containing the type of object)
* @param {JSONObject} jsonObject The JSON string coming in from the UI Layer, containing the object to be stored
* @return {String} csid The id of the object in the database
*/
public String autocreateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
ReturnedURL url = null;
Document doc = null;
//used by userroles and permroles as they have complex urls
if(r.hasPrimaryField()){
//XXX test if works: need to delete first before create/update
// deleteJSON(root,creds,cache,filePath);
for(String section : r.getServicesRecordPaths()) {
doc=XmlJsonConversion.convertToXml(r,jsonObject,section,"POST");
String path = r.getServicesURL();
path = path.replace("*", getSubCsid(jsonObject,r.getPrimaryField()));
deleteJSON(root,creds,cache,path);
url = conn.getURL(RequestMethod.POST, path, doc, creds, cache);
}
}
else{
url = autoCreateSub(creds, cache, jsonObject, doc, r.getServicesURL(), r);
}
// create related sub records?
//I am developing this.. it might not work...
for(FieldSet fs : r.getAllSubRecords("POST")){
Record sr = fs.usesRecordId();
//sr.getID()
if(sr.isType("authority")){
//need to use code from configuredVocabStorage
}
else{
String savePath = url.getURL() + "/" + sr.getServicesURL();
if(fs instanceof Field){//get the fields form inline XXX untested - might not work...
JSONObject subdata = new JSONObject();
//loop thr jsonObject and find the fields I need
for(FieldSet subfs: sr.getAllFields("POST")){
String key = subfs.getID();
if(jsonObject.has(key)){
subdata.put(key, jsonObject.get(key));
}
}
subautocreateJSON(root,creds,cache,sr,subdata,savePath);
}
else if(fs instanceof Group){//JSONObject
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONObject){
JSONObject subrecord = (JSONObject)subdata;
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
}
else{//JSONArray
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,subrecord,savePath);
}
}
}
}
}
}
return url.getURLTail();
} catch (ConnectionException e) {
throw new UnderlyingStorageException(e.getMessage(),e.getStatus(), e.getUrl(),e);
} catch (JSONException e) {
throw new UnimplementedException("JSONException",e);
}
}
protected ReturnedURL autoCreateSub(CSPRequestCredentials creds,
CSPRequestCache cache, JSONObject jsonObject, Document doc, String savePrefix, Record r)
throws JSONException, UnderlyingStorageException,
ConnectionException {
ReturnedURL url;
Map<String,Document> parts=new HashMap<String,Document>();
Document doc2 = doc;
for(String section : r.getServicesRecordPaths()) {
String path=r.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
doc2=XmlJsonConversion.convertToXml(r,jsonObject,section,"POST");
if(doc2!=null){
doc = doc2;
parts.put(record_path[0],doc2);
//log.info(doc.asXML());
//log.info(savePrefix);
}
}
//some records are accepted as multipart in the service layers, others arent, that's why we split up here
if(r.isMultipart())
url = conn.getMultipartURL(RequestMethod.POST,savePrefix,parts,creds,cache);
else
url = conn.getURL(RequestMethod.POST, savePrefix, doc, creds, cache);
if(url.getStatus()>299 || url.getStatus()<200)
throw new UnderlyingStorageException("Bad response ",url.getStatus(),savePrefix);
return url;
}
/**
* Gets the csid from an role or account out of the json authorization
* @param data
* @param primaryField
* @return
* @throws JSONException
*/
protected String getSubCsid(JSONObject data, String primaryField) throws JSONException{
String[] path = primaryField.split("/");
JSONObject temp = data;
int finalnum = path.length - 1;
for(int i=0;i<finalnum; i++){
if(temp.has(path[i])){
temp = temp.getJSONObject(path[i]);
}
}
String csid = temp.getString(path[finalnum]);
return csid;
}
public void createJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject)
throws ExistException, UnimplementedException, UnderlyingStorageException {
throw new UnimplementedException("Cannot post to full path");
}
//don't call direct as need to check if soft or hard delete first
public void hardDeleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, String serviceurl) throws ExistException,
UnimplementedException, UnderlyingStorageException {
try {
int status=conn.getNone(RequestMethod.DELETE,serviceurl+filePath,null,creds,cache);
if(status>299 || status<200) // XXX CSPACE-73, should be 404
throw new UnderlyingStorageException("Service layer exception",status,serviceurl+filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
public void softDeleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, String serviceurl) throws ExistException,
UnimplementedException, UnderlyingStorageException {
try {
int status = 0;
Document doc = null;
doc=XmlJsonConversion.getXMLSoftDelete();
String workflow = "/workflow";
ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, serviceurl+filePath+workflow, doc, creds, cache);
status = docm.getStatus();
if(status>299 || status<200)
throw new UnderlyingStorageException("Bad response ",status,serviceurl+filePath);
}
catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
}
}
public void deleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, Record thisr) throws ExistException,
UnimplementedException, UnderlyingStorageException {
String serviceurl = thisr.getServicesURL()+"/";
if(thisr.hasSoftDeleteMethod()){
softDeleteJSON(root,creds,cache,filePath,serviceurl);
}
else{
hardDeleteJSON(root,creds,cache,filePath,serviceurl);
}
}
public void deleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, String serviceurl, Record thisr) throws ExistException,
UnimplementedException, UnderlyingStorageException {
if(thisr.hasSoftDeleteMethod()){
softDeleteJSON(root,creds,cache,filePath,serviceurl);
}
else{
hardDeleteJSON(root,creds,cache,filePath,serviceurl);
}
}
public void deleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath) throws ExistException,
UnimplementedException, UnderlyingStorageException {
deleteJSON(root,creds,cache,filePath,r);
}
@Override
public String[] getPaths(ContextualisedStorage root,
CSPRequestCredentials creds, CSPRequestCache cache,
String rootPath, JSONObject restrictions) throws ExistException,
UnimplementedException, UnderlyingStorageException {
// TODO Auto-generated method stub
return null;
}
protected String getRestrictedPath(String basepath, JSONObject restrictions, String keywordparam, String tail, Boolean isVocab, String displayName) throws UnsupportedEncodingException, JSONException{
String postfix = "?";
if (tail.length() > 0) {
postfix += tail.substring(1) + "&";
}
String prefix=null;
Boolean queryadded = false;
if(restrictions!=null){
if(isVocab && restrictions.has(displayName)){
prefix=restrictions.getString(displayName);
}
else if(restrictions.has("keywords")) {
/* Keyword search */
String data=URLEncoder.encode(restrictions.getString("keywords"),"UTF-8");
postfix += keywordparam+"="+data+"&";
}
if(restrictions.has("sortKey")){//"summarylist.updatedAt"//movements_common:locationDate
postfix += "sortBy="+restrictions.getString("sortKey");
if(restrictions.has("sortDir")){//1" - ascending, "-1" - descending
if(restrictions.getString("sortDir").equals("-1")){
postfix += "+DESC";
}
else{
postfix += "+ASC";
}
}
postfix += "&";
}
if(restrictions.has("pageSize")){
postfix += "pgSz="+restrictions.getString("pageSize")+"&";
}
if(restrictions.has("pageNum")){
postfix += "pgNum="+restrictions.getString("pageNum")+"&";
}
if(restrictions.has("queryTerm")){
String queryString = prefix;
if(restrictions.has("queryString")){
queryString=restrictions.getString("queryString");
}
postfix+=restrictions.getString("queryTerm")+"="+URLEncoder.encode(queryString,"UTF8")+"&";
queryadded = true;
}
}
if(isVocab){
if(prefix!=null && !queryadded){
postfix+="pt="+URLEncoder.encode(prefix,"UTF8")+"&";
}
}
postfix = postfix.substring(0, postfix.length()-1);
if(postfix.length() == 0){postfix +="/";}
//log.info(postfix);
String path = basepath+postfix;
return path;
}
/**
* Gets a list of csids of a certain type of record together with the pagination info
*/
public JSONObject getPathsJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String rootPath,JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), "", false, "");
String node = "/"+r.getServicesListPath().split("/")[0]+"/*";
JSONObject data = getListView(creds,cache,path,node,"/"+r.getServicesListPath(),"csid",false,r);
return data;
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (UnsupportedEncodingException e) {
throw new UnderlyingStorageException("Service layer exception",e);
} catch (JSONException e) {
throw new UnderlyingStorageException("Service layer exception",e);
}
}
/**
* need to hack list view so it returns fuller data for those sets that might have repeating items that are varied e.g. refObjs
* @return
*/
protected JSONObject getRepeatableListView(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String path, String nodeName, String matchlistitem, String csidfield, Boolean fullcsid, Record r) throws ConnectionException, JSONException {
if(r.hasHierarchyUsed("screen")){
path = hierarchicalpath(path);
}
if(r.hasSoftDeleteMethod()){
return getRepeatableSoftListView(root,creds,cache,path,nodeName, matchlistitem, csidfield, fullcsid);
}
else{
return getRepeatableHardListView(root,creds,cache,path,nodeName, matchlistitem, csidfield, fullcsid);
}
}
protected JSONObject getListView(CSPRequestCredentials creds,CSPRequestCache cache,String path, String nodeName, String matchlistitem, String csidfield, Boolean fullcsid, Record r) throws ConnectionException, JSONException {
if(r.hasHierarchyUsed("screen")){
path = hierarchicalpath(path);
}
if(r.hasSoftDeleteMethod()){
return getSoftListView(creds,cache,path,nodeName, matchlistitem, csidfield, fullcsid);
}
else{
return getHardListView(creds,cache,path,nodeName, matchlistitem, csidfield, fullcsid);
}
}
protected String softpath(String path){
String softdeletepath = path;
//does path include a ? if so add &wf_delete else add ?wf_delete
if(path.contains("?")){
softdeletepath += "&";
}
else{
softdeletepath += "?";
}
softdeletepath += "wf_deleted=false";
return softdeletepath;
}
protected String hierarchicalpath(String path){
String hierarchicalpath = path;
//does path include a ? if so add &wf_delete else add ?wf_delete
if(path.contains("?")){
hierarchicalpath += "&";
}
else{
hierarchicalpath += "?";
}
hierarchicalpath += "showRelations=true";
return hierarchicalpath;
}
protected JSONObject getRepeatableSoftListView(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String path, String nodeName, String matchlistitem, String csidfield, Boolean fullcsid) throws ConnectionException, JSONException {
String softdeletepath = softpath(path);
return getRepeatableHardListView(root,creds,cache,softdeletepath,nodeName, matchlistitem, csidfield, fullcsid);
}
protected JSONObject getSoftListView(CSPRequestCredentials creds,CSPRequestCache cache,String path, String nodeName, String matchlistitem, String csidfield, Boolean fullcsid) throws ConnectionException, JSONException {
String softdeletepath = softpath(path);
return getHardListView(creds,cache,softdeletepath,nodeName, matchlistitem, csidfield, fullcsid);
}
protected JSONObject getRepeatableHardListView(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String path, String nodeName, String matchlistitem, String csidfield, Boolean fullcsid) throws ConnectionException, JSONException {
JSONObject out = new JSONObject();
JSONObject pagination = new JSONObject();
Document list=null;
List<JSONObject> listitems=new ArrayList<JSONObject>();
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET,path,null,creds,cache);
if(all.getStatus()!=200){
//throw new StatusException(all.getStatus(),path,"Bad request during identifier cache map update: status not 200");
throw new ConnectionException("Bad request during identifier cache map update: status not 200"+Integer.toString(all.getStatus()),all.getStatus(),path);
}
list=all.getDocument();
List<Node> nodes=list.selectNodes(nodeName);
if(matchlistitem.equals("roles_list/*") || matchlistitem.equals("permissions_list/*")){
//XXX hack to deal with roles being inconsistent
//XXX CSPACE-1887 workaround
for(Node node : nodes) {
if(node.matches(matchlistitem)){
String csid = node.valueOf( "@csid" );
JSONObject test = new JSONObject();
test.put("csid", csid);
listitems.add(test);
}
else{
pagination.put(node.getName(), node.getText());
}
}
}
else{
for(Node node : nodes) {
if(node.matches(matchlistitem)){
List<Node> fields=node.selectNodes("*");
String csid="";
if(node.selectSingleNode(csidfield)!=null){
csid=node.selectSingleNode(csidfield).getText();
}
JSONObject test = new JSONObject();
for(Node field : fields) {
if(csidfield.equals(field.getName())) {
if(!fullcsid){
int idx=csid.lastIndexOf("/");
if(idx!=-1)
csid=csid.substring(idx+1);
}
test.put("csid", csid);
} else {
String json_name=view_map.get(field.getName());
if(json_name!=null) {
String value=field.getText();
// XXX hack to cope with multi values
if(value==null || "".equals(value)) {
List<Node> inners=field.selectNodes("*");
for(Node n : inners) {
value+=n.getText();
}
}
setGleanedValue(cache,r.getServicesURL()+"/"+csid,json_name,value);
test.put(json_name, value);
}
}
}
listitems.add(test);
/* this hopefully will reduce fan out - needs more testing */
if(list.selectSingleNode(r.getServicesFieldsPath())!=null){
String myfields = list.selectSingleNode(r.getServicesFieldsPath()).getText();
String[] allfields = myfields.split("\\|");
for(String s : allfields){
String gleaned = getGleanedValue(cache,r.getServicesURL()+"/"+csid,s);
if(gleaned==null){
setGleanedValue(cache,r.getServicesURL()+"/"+csid,s,"");
}
}
}
}
else{
pagination.put(node.getName(), node.getText());
}
}
}
out.put("pagination", pagination);
out.put("listItems", listitems);
return out;
}
protected JSONObject getHardListView(CSPRequestCredentials creds,CSPRequestCache cache,String path, String nodeName, String matchlistitem, String csidfield, Boolean fullcsid) throws ConnectionException, JSONException {
JSONObject out = new JSONObject();
JSONObject pagination = new JSONObject();
Document list=null;
List<String> listitems=new ArrayList<String>();
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET,path,null,creds,cache);
if(all.getStatus()!=200){
//throw new StatusException(all.getStatus(),path,"Bad request during identifier cache map update: status not 200");
throw new ConnectionException("Bad request during identifier cache map update: status not 200"+Integer.toString(all.getStatus()),all.getStatus(),path);
}
list=all.getDocument();
List<Node> nodes=list.selectNodes(nodeName);
if(matchlistitem.equals("roles_list/*") || matchlistitem.equals("permissions_list/*")){
//XXX hack to deal with roles being inconsistent
//XXX CSPACE-1887 workaround
for(Node node : nodes) {
if(node.matches(matchlistitem)){
String csid = node.valueOf( "@csid" );
listitems.add(csid);
}
else{
pagination.put(node.getName(), node.getText());
}
}
}
else{
for(Node node : nodes) {
if(node.matches(matchlistitem)){
List<Node> fields=node.selectNodes("*");
String csid="";
if(node.selectSingleNode(csidfield)!=null){
csid=node.selectSingleNode(csidfield).getText();
}
for(Node field : fields) {
if(csidfield.equals(field.getName())) {
if(!fullcsid){
int idx=csid.lastIndexOf("/");
if(idx!=-1)
csid=csid.substring(idx+1);
}
listitems.add(csid);
} else {
String json_name=view_map.get(field.getName());
if(json_name!=null) {
String value=field.getText();
// XXX hack to cope with multi values
if(value==null || "".equals(value)) {
List<Node> inners=field.selectNodes("*");
for(Node n : inners) {
value+=n.getText();
}
}
setGleanedValue(cache,r.getServicesURL()+"/"+csid,json_name,value);
}
}
}
/* this hopefully will reduce fan out - needs more testing */
if(list.selectSingleNode(r.getServicesFieldsPath())!=null){
String myfields = list.selectSingleNode(r.getServicesFieldsPath()).getText();
String[] allfields = myfields.split("\\|");
for(String s : allfields){
String gleaned = getGleanedValue(cache,r.getServicesURL()+"/"+csid,s);
if(gleaned==null){
setGleanedValue(cache,r.getServicesURL()+"/"+csid,s,"");
}
}
}
}
else{
pagination.put(node.getName(), node.getText());
}
}
}
out.put("pagination", pagination);
out.put("listItems", listitems.toArray(new String[0]));
return out;
}
/**
* Get data about objects. If filePath is made of 2 elements then this is a specific view of the object
* e.g. for related objs, search etcn and therefore will require a different dataset returned
* @throws
*/
public JSONObject retrieveJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject restrictions) throws ExistException,
UnimplementedException, UnderlyingStorageException {
try {
String[] parts=filePath.split("/");
if(parts.length>=2) {
String extra = "";
if(parts.length==3){
extra = parts[2];
}
return viewRetrieveJSON(root,creds,cache,parts[0],parts[1],extra, restrictions);
} else
return simpleRetrieveJSON(creds,cache,filePath);
} catch(JSONException x) {
throw new UnderlyingStorageException("Error building JSON",x);
} catch (UnsupportedEncodingException x) {
throw new UnderlyingStorageException("Error UnsupportedEncodingException JSON",x);
}
}
}
| true | true | public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject,Record thisr, String serviceurl)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Map<String,Document> parts=new HashMap<String,Document>();
Document doc = null;
for(String section : thisr.getServicesRecordPaths()) {
String path=thisr.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
doc=XmlJsonConversion.convertToXml(thisr,jsonObject,section,"PUT");
if(doc !=null){
parts.put(record_path[0],doc);
// log.info(doc.asXML());
}
}
int status = 0;
if(thisr.isMultipart()){
ReturnedMultipartDocument docm = conn.getMultipartXMLDocument(RequestMethod.PUT,serviceurl+filePath,parts,creds,cache);
status = docm.getStatus();
}
else{
ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, serviceurl+filePath, doc, creds, cache);
status = docm.getStatus();
}
//XXX Completely untested subrecord update
for(FieldSet fs : r.getAllSubRecords("PUT")){
Record sr = fs.usesRecordId();
if(sr.isRealRecord()){//only deal with ones which are separate Records in the services
//get list of existing subrecords
JSONObject existingcsid = new JSONObject();
JSONObject updatecsid = new JSONObject();
JSONArray createcsid = new JSONArray();
String getPath = serviceurl+filePath + "/" + sr.getServicesURL();
String node = "/"+sr.getServicesListPath().split("/")[0]+"/*";
JSONObject data = getListView(creds,cache,getPath,node,"/"+sr.getServicesListPath(),"csid",false, sr);
String[] filepaths = (String[]) data.get("listItems");
for(String uri : filepaths) {
String path = uri;
if(path!=null && path.startsWith("/"))
path=path.substring(1);
existingcsid.put(path,"original");
}
//how does that compare to what we need
if(sr.isType("authority")){
//need to use configuredVocabStorage
}
else{
if(fs instanceof Field){
JSONObject subdata = new JSONObject();
//loop thr jsonObject and find the fields I need
for(FieldSet subfs: sr.getAllFields("PUT")){
String key = subfs.getID();
if(jsonObject.has(key)){
subdata.put(key, jsonObject.get(key));
}
}
if(filepaths.length ==0){
//create
createcsid.put(subdata);
}
else{
//update - there should only be one
String firstcsid = filepaths[0];
updatecsid.put(firstcsid, subdata);
existingcsid.remove(firstcsid);
}
}
else if(fs instanceof Group){//JSONObject
//do we have a csid
//subrecorddata.put(value);
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONObject){
if(((JSONObject) subdata).has("_subrecordcsid")){
String thiscsid = ((JSONObject) subdata).getString("_subrecordcsid");
//update
if(existingcsid.has(thiscsid)){
updatecsid.put(thiscsid, (JSONObject) subdata);
existingcsid.remove(thiscsid);
}
else{
//something has gone wrong... best just create it from scratch
createcsid.put(subdata);
}
}
else{
//create
createcsid.put(subdata);
}
}
}
}
else{//JSONArray Repeat
//need to find if we have csid's for each one
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
if(((JSONObject) subrecord).has("_subrecordcsid")){
String thiscsid = ((JSONObject) subrecord).getString("_subrecordcsid");
//update
if(existingcsid.has(thiscsid)){
updatecsid.put(thiscsid, (JSONObject) subrecord);
existingcsid.remove(thiscsid);
}
else{
//something has gone wrong... best just create it from scratch
createcsid.put(subrecord);
}
}
else{
//create
createcsid.put(subrecord);
}
}
}
}
}
String savePath = serviceurl+filePath + "/" + sr.getServicesURL()+"/";
//do delete JSONObject existingcsid = new JSONObject();
Iterator<String> rit=existingcsid.keys();
while(rit.hasNext()) {
String key=rit.next();
deleteJSON(root,creds,cache,key,savePath,sr);
}
//do update JSONObject updatecsid = new JSONObject();
Iterator<String> keys = updatecsid.keys();
while(keys.hasNext()) {
String key=keys.next();
JSONObject value = updatecsid.getJSONObject(key);
updateJSON( root, creds, cache, key, value, sr, savePath);
}
//do create JSONArray createcsid = new JSONArray();
for(int i=0;i<createcsid.length();i++){
JSONObject value = createcsid.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,value,savePath);
}
}
}
}
//if(status==404)
// throw new ExistException("Not found: "+serviceurl+filePath);
if(status>299 || status<200)
throw new UnderlyingStorageException("Bad response ",status,serviceurl+filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnimplementedException("JSONException",e);
}
}
| public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject,Record thisr, String serviceurl)
throws ExistException, UnimplementedException, UnderlyingStorageException {
try {
Map<String,Document> parts=new HashMap<String,Document>();
Document doc = null;
for(String section : thisr.getServicesRecordPaths()) {
String path=thisr.getServicesRecordPath(section);
String[] record_path=path.split(":",2);
doc=XmlJsonConversion.convertToXml(thisr,jsonObject,section,"PUT");
if(doc !=null){
parts.put(record_path[0],doc);
// log.info(doc.asXML());
}
}
int status = 0;
if(thisr.isMultipart()){
ReturnedMultipartDocument docm = conn.getMultipartXMLDocument(RequestMethod.PUT,serviceurl+filePath,parts,creds,cache);
status = docm.getStatus();
}
else{
ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, serviceurl+filePath, doc, creds, cache);
status = docm.getStatus();
}
//XXX Completely untested subrecord update
for(FieldSet fs : thisr.getAllSubRecords("PUT")){
Record sr = fs.usesRecordId();
if(sr.isRealRecord()){//only deal with ones which are separate Records in the services
//get list of existing subrecords
JSONObject existingcsid = new JSONObject();
JSONObject updatecsid = new JSONObject();
JSONArray createcsid = new JSONArray();
String getPath = serviceurl+filePath + "/" + sr.getServicesURL();
String node = "/"+sr.getServicesListPath().split("/")[0]+"/*";
JSONObject data = getListView(creds,cache,getPath,node,"/"+sr.getServicesListPath(),"csid",false, sr);
String[] filepaths = (String[]) data.get("listItems");
for(String uri : filepaths) {
String path = uri;
if(path!=null && path.startsWith("/"))
path=path.substring(1);
existingcsid.put(path,"original");
}
//how does that compare to what we need
if(sr.isType("authority")){
//need to use configuredVocabStorage
}
else{
if(fs instanceof Field){
JSONObject subdata = new JSONObject();
//loop thr jsonObject and find the fields I need
for(FieldSet subfs: sr.getAllFields("PUT")){
String key = subfs.getID();
if(jsonObject.has(key)){
subdata.put(key, jsonObject.get(key));
}
}
if(filepaths.length ==0){
//create
createcsid.put(subdata);
}
else{
//update - there should only be one
String firstcsid = filepaths[0];
updatecsid.put(firstcsid, subdata);
existingcsid.remove(firstcsid);
}
}
else if(fs instanceof Group){//JSONObject
//do we have a csid
//subrecorddata.put(value);
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONObject){
if(((JSONObject) subdata).has("_subrecordcsid")){
String thiscsid = ((JSONObject) subdata).getString("_subrecordcsid");
//update
if(existingcsid.has(thiscsid)){
updatecsid.put(thiscsid, (JSONObject) subdata);
existingcsid.remove(thiscsid);
}
else{
//something has gone wrong... best just create it from scratch
createcsid.put(subdata);
}
}
else{
//create
createcsid.put(subdata);
}
}
}
}
else{//JSONArray Repeat
//need to find if we have csid's for each one
if(jsonObject.has(fs.getID())){
Object subdata = jsonObject.get(fs.getID());
if(subdata instanceof JSONArray){
JSONArray subarray = (JSONArray)subdata;
for(int i=0;i<subarray.length();i++) {
JSONObject subrecord = subarray.getJSONObject(i);
if(((JSONObject) subrecord).has("_subrecordcsid")){
String thiscsid = ((JSONObject) subrecord).getString("_subrecordcsid");
//update
if(existingcsid.has(thiscsid)){
updatecsid.put(thiscsid, (JSONObject) subrecord);
existingcsid.remove(thiscsid);
}
else{
//something has gone wrong... best just create it from scratch
createcsid.put(subrecord);
}
}
else{
//create
createcsid.put(subrecord);
}
}
}
}
}
String savePath = serviceurl+filePath + "/" + sr.getServicesURL()+"/";
//do delete JSONObject existingcsid = new JSONObject();
Iterator<String> rit=existingcsid.keys();
while(rit.hasNext()) {
String key=rit.next();
deleteJSON(root,creds,cache,key,savePath,sr);
}
//do update JSONObject updatecsid = new JSONObject();
Iterator<String> keys = updatecsid.keys();
while(keys.hasNext()) {
String key=keys.next();
JSONObject value = updatecsid.getJSONObject(key);
updateJSON( root, creds, cache, key, value, sr, savePath);
}
//do create JSONArray createcsid = new JSONArray();
for(int i=0;i<createcsid.length();i++){
JSONObject value = createcsid.getJSONObject(i);
subautocreateJSON(root,creds,cache,sr,value,savePath);
}
}
}
}
//if(status==404)
// throw new ExistException("Not found: "+serviceurl+filePath);
if(status>299 || status<200)
throw new UnderlyingStorageException("Bad response ",status,serviceurl+filePath);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception"+e.getLocalizedMessage(),e.getStatus(),e.getUrl(),e);
} catch (JSONException e) {
throw new UnimplementedException("JSONException",e);
}
}
|
diff --git a/src/com/eteks/sweethome3d/viewcontroller/Home3DAttributesController.java b/src/com/eteks/sweethome3d/viewcontroller/Home3DAttributesController.java
index 8fd8cb03..395cdb36 100644
--- a/src/com/eteks/sweethome3d/viewcontroller/Home3DAttributesController.java
+++ b/src/com/eteks/sweethome3d/viewcontroller/Home3DAttributesController.java
@@ -1,530 +1,531 @@
/*
* Home3DAttributesController.java 25 juin 07
*
* Sweet Home 3D, Copyright (c) 2007 Emmanuel PUYBARET / eTeks <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.eteks.sweethome3d.viewcontroller;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.List;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoableEdit;
import javax.swing.undo.UndoableEditSupport;
import com.eteks.sweethome3d.model.Home;
import com.eteks.sweethome3d.model.HomeEnvironment;
import com.eteks.sweethome3d.model.HomeTexture;
import com.eteks.sweethome3d.model.Level;
import com.eteks.sweethome3d.model.ObserverCamera;
import com.eteks.sweethome3d.model.UserPreferences;
/**
* A MVC controller for home 3D attributes view.
* @author Emmanuel Puybaret
*/
public class Home3DAttributesController implements Controller {
/**
* The properties that may be edited by the view associated to this controller.
*/
public enum Property {OBSERVER_FIELD_OF_VIEW_IN_DEGREES, OBSERVER_HEIGHT, OBSERVER_CAMERA_ELEVATION, MINIMUM_ELEVATION,
GROUND_COLOR, GROUND_PAINT, SKY_COLOR, SKY_PAINT,
LIGHT_COLOR, WALLS_ALPHA}
/**
* The possible values for {@linkplain #getGroundPaint() ground paint type}.
*/
public enum EnvironmentPaint {COLORED, TEXTURED}
private final Home home;
private final UserPreferences preferences;
private final ViewFactory viewFactory;
private final ContentManager contentManager;
private final UndoableEditSupport undoSupport;
private TextureChoiceController groundTextureController;
private TextureChoiceController skyTextureController;
private final PropertyChangeSupport propertyChangeSupport;
private DialogView home3DAttributesView;
private int observerFieldOfViewInDegrees;
private float observerHeight;
private Float observerCameraElevation;
private float minimumElevation;
private int groundColor;
private EnvironmentPaint groundPaint;
private int skyColor;
private EnvironmentPaint skyPaint;
private int lightColor;
private float wallsAlpha;
/**
* Creates the controller of 3D view with undo support.
*/
public Home3DAttributesController(Home home,
UserPreferences preferences,
ViewFactory viewFactory,
ContentManager contentManager,
UndoableEditSupport undoSupport) {
this.home = home;
this.preferences = preferences;
this.viewFactory = viewFactory;
this.contentManager = contentManager;
this.undoSupport = undoSupport;
this.propertyChangeSupport = new PropertyChangeSupport(this);
updateProperties();
}
/**
* Returns the texture controller of the ground.
*/
public TextureChoiceController getGroundTextureController() {
// Create sub controller lazily only once it's needed
if (this.groundTextureController == null) {
this.groundTextureController = new TextureChoiceController(
this.preferences.getLocalizedString(Home3DAttributesController.class, "groundTextureTitle"),
this.preferences, this.viewFactory, this.contentManager);
this.groundTextureController.addPropertyChangeListener(TextureChoiceController.Property.TEXTURE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
setGroundPaint(EnvironmentPaint.TEXTURED);
}
});
}
return this.groundTextureController;
}
/**
* Returns the texture controller of the sky.
*/
public TextureChoiceController getSkyTextureController() {
// Create sub controller lazily only once it's needed
if (this.skyTextureController == null) {
this.skyTextureController = new TextureChoiceController(
this.preferences.getLocalizedString(Home3DAttributesController.class, "skyTextureTitle"),
this.preferences, this.viewFactory, this.contentManager);
this.skyTextureController.addPropertyChangeListener(TextureChoiceController.Property.TEXTURE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
setSkyPaint(EnvironmentPaint.TEXTURED);
}
});
}
return this.skyTextureController;
}
/**
* Returns the view associated with this controller.
*/
public DialogView getView() {
// Create view lazily only once it's needed
if (this.home3DAttributesView == null) {
this.home3DAttributesView = this.viewFactory.createHome3DAttributesView(
this.preferences, this);
}
return this.home3DAttributesView;
}
/**
* Displays the view controlled by this controller.
*/
public void displayView(View parentView) {
getView().displayView(parentView);
}
/**
* Adds the property change <code>listener</code> in parameter to this controller.
*/
public void addPropertyChangeListener(Property property, PropertyChangeListener listener) {
this.propertyChangeSupport.addPropertyChangeListener(property.name(), listener);
}
/**
* Removes the property change <code>listener</code> in parameter from this controller.
*/
public void removePropertyChangeListener(Property property, PropertyChangeListener listener) {
this.propertyChangeSupport.removePropertyChangeListener(property.name(), listener);
}
/**
* Updates edited properties from the 3D attributes of the home edited by this controller.
*/
protected void updateProperties() {
setObserverFieldOfViewInDegrees((int)(Math.round(Math.toDegrees(
this.home.getObserverCamera().getFieldOfView())) + 360) % 360);
setObserverHeight(this.home.getObserverCamera().getZ() * 15 / 14);
List<Level> levels = this.home.getLevels();
setMinimumElevation(levels.size() == 0 ? 10 : 10 + levels.get(0).getElevation());
setObserverCameraElevation(levels.size() == 0 || levels.get(0).getElevation() == 0 && levels.get(levels.size() - 1).getElevation() == 0
? null
: this.home.getObserverCamera().getZ());
HomeEnvironment homeEnvironment = this.home.getEnvironment();
setGroundColor(homeEnvironment.getGroundColor());
HomeTexture groundTexture = homeEnvironment.getGroundTexture();
getGroundTextureController().setTexture(groundTexture);
if (groundTexture != null) {
setGroundPaint(EnvironmentPaint.TEXTURED);
} else {
setGroundPaint(EnvironmentPaint.COLORED);
}
setSkyColor(homeEnvironment.getSkyColor());
HomeTexture skyTexture = homeEnvironment.getSkyTexture();
getSkyTextureController().setTexture(skyTexture);
if (skyTexture != null) {
setSkyPaint(EnvironmentPaint.TEXTURED);
} else {
setSkyPaint(EnvironmentPaint.COLORED);
}
setLightColor(homeEnvironment.getLightColor());
setWallsAlpha(homeEnvironment.getWallsAlpha());
}
/**
* Sets the edited observer field of view in degrees.
*/
public void setObserverFieldOfViewInDegrees(int observerFieldOfViewInDegrees) {
if (observerFieldOfViewInDegrees != this.observerFieldOfViewInDegrees) {
int oldObserverFieldOfViewInDegrees = this.observerFieldOfViewInDegrees;
this.observerFieldOfViewInDegrees = observerFieldOfViewInDegrees;
this.propertyChangeSupport.firePropertyChange(Property.OBSERVER_FIELD_OF_VIEW_IN_DEGREES.name(),
oldObserverFieldOfViewInDegrees, observerFieldOfViewInDegrees);
}
}
/**
* Returns the edited observer field of view in degrees.
*/
public int getObserverFieldOfViewInDegrees() {
return this.observerFieldOfViewInDegrees;
}
/**
* Sets the edited observer height.
*/
public void setObserverHeight(float observerHeight) {
if (observerHeight != this.observerHeight) {
float oldObserverHeight = this.observerHeight;
this.observerHeight = observerHeight;
this.propertyChangeSupport.firePropertyChange(Property.OBSERVER_HEIGHT.name(), oldObserverHeight, observerHeight);
}
}
/**
* Returns the edited observer height.
*/
public float getObserverHeight() {
return this.observerHeight;
}
/**
* Sets the edited camera elevation.
*/
public void setObserverCameraElevation(Float observerCameraElevation) {
if (observerCameraElevation != this.observerCameraElevation
|| observerCameraElevation != null && !observerCameraElevation.equals(this.observerCameraElevation)) {
Float oldObserverCameraElevation = this.observerCameraElevation;
this.observerCameraElevation = observerCameraElevation;
this.propertyChangeSupport.firePropertyChange(Property.OBSERVER_CAMERA_ELEVATION.name(), oldObserverCameraElevation, observerCameraElevation);
}
}
/**
* Returns the edited camera elevation or <code>null</code> if observer height should be preferred.
*/
public Float getObserverCameraElevation() {
return this.observerCameraElevation;
}
/**
* Sets the minimum elevation.
*/
private void setMinimumElevation(float minimumElevation) {
if (minimumElevation != this.minimumElevation) {
float oldMinimumElevation = this.minimumElevation;
this.minimumElevation = minimumElevation;
this.propertyChangeSupport.firePropertyChange(Property.MINIMUM_ELEVATION.name(), oldMinimumElevation, minimumElevation);
}
}
/**
* Returns the minimum elevation.
*/
public float getMinimumElevation() {
return this.minimumElevation;
}
/**
* Sets the edited ground color.
*/
public void setGroundColor(int groundColor) {
if (groundColor != this.groundColor) {
int oldGroundColor = this.groundColor;
this.groundColor = groundColor;
this.propertyChangeSupport.firePropertyChange(Property.GROUND_COLOR.name(), oldGroundColor, groundColor);
setGroundPaint(EnvironmentPaint.COLORED);
}
}
/**
* Returns the edited ground color.
*/
public int getGroundColor() {
return this.groundColor;
}
/**
* Sets whether the ground is colored or textured.
*/
public void setGroundPaint(EnvironmentPaint groundPaint) {
if (groundPaint != this.groundPaint) {
EnvironmentPaint oldGroundPaint = this.groundPaint;
this.groundPaint = groundPaint;
this.propertyChangeSupport.firePropertyChange(Property.GROUND_PAINT.name(), oldGroundPaint, groundPaint);
}
}
/**
* Returns whether the ground is colored or textured.
*/
public EnvironmentPaint getGroundPaint() {
return this.groundPaint;
}
/**
* Sets the edited sky color.
*/
public void setSkyColor(int skyColor) {
if (skyColor != this.skyColor) {
int oldSkyColor = this.skyColor;
this.skyColor = skyColor;
this.propertyChangeSupport.firePropertyChange(Property.SKY_COLOR.name(), oldSkyColor, skyColor);
}
}
/**
* Returns the edited sky color.
*/
public int getSkyColor() {
return this.skyColor;
}
/**
* Sets whether the sky is colored or textured.
*/
public void setSkyPaint(EnvironmentPaint skyPaint) {
if (skyPaint != this.skyPaint) {
EnvironmentPaint oldSkyPaint = this.skyPaint;
this.skyPaint = skyPaint;
this.propertyChangeSupport.firePropertyChange(Property.SKY_PAINT.name(), oldSkyPaint, skyPaint);
}
}
/**
* Returns whether the sky is colored or textured.
*/
public EnvironmentPaint getSkyPaint() {
return this.skyPaint;
}
/**
* Sets the edited light color.
*/
public void setLightColor(int lightColor) {
if (lightColor != this.lightColor) {
int oldLightColor = this.lightColor;
this.lightColor = lightColor;
this.propertyChangeSupport.firePropertyChange(Property.LIGHT_COLOR.name(), oldLightColor, lightColor);
}
}
/**
* Returns the edited light color.
*/
public int getLightColor() {
return this.lightColor;
}
/**
* Sets the edited walls transparency alpha.
*/
public void setWallsAlpha(float wallsAlpha) {
if (wallsAlpha != this.wallsAlpha) {
float oldWallsAlpha = this.wallsAlpha;
this.wallsAlpha = wallsAlpha;
this.propertyChangeSupport.firePropertyChange(Property.WALLS_ALPHA.name(), oldWallsAlpha, wallsAlpha);
}
}
/**
* Returns the edited walls transparency alpha.
*/
public float getWallsAlpha() {
return this.wallsAlpha;
}
/**
* Controls the modification of the 3D attributes of the edited home.
*/
public void modify3DAttributes() {
float observerCameraFieldOfView = (float)Math.toRadians(getObserverFieldOfViewInDegrees());
- float observerCameraZ = getObserverHeight() * 14 / 15;
Float observerCameraElevation = getObserverCameraElevation();
+ float observerCameraZ = observerCameraElevation != null
+ ? observerCameraElevation.floatValue()
+ : getObserverHeight() * 14 / 15;
int groundColor = getGroundColor();
HomeTexture groundTexture = getGroundPaint() == EnvironmentPaint.TEXTURED
? getGroundTextureController().getTexture()
: null;
int skyColor = getSkyColor();
HomeTexture skyTexture = getSkyPaint() == EnvironmentPaint.TEXTURED
? getSkyTextureController().getTexture()
: null;
int lightColor = getLightColor();
float wallsAlpha = getWallsAlpha();
float oldObserverCameraFieldOfView = this.home.getObserverCamera().getFieldOfView();
float oldObserverCameraZ = this.home.getObserverCamera().getZ();
HomeEnvironment homeEnvironment = this.home.getEnvironment();
int oldGroundColor = homeEnvironment.getGroundColor();
HomeTexture oldGroundTexture = homeEnvironment.getGroundTexture();
int oldSkyColor = homeEnvironment.getSkyColor();
HomeTexture oldSkyTexture = homeEnvironment.getSkyTexture();
int oldLightColor = homeEnvironment.getLightColor();
float oldWallsAlpha = homeEnvironment.getWallsAlpha();
// Apply modification
doModify3DAttributes(home, observerCameraFieldOfView, observerCameraZ,
groundColor, groundTexture, skyColor, skyTexture, lightColor, wallsAlpha);
if (this.undoSupport != null) {
UndoableEdit undoableEdit = new Home3DAttributesModificationUndoableEdit(
this.home, this.preferences,
oldObserverCameraFieldOfView, oldObserverCameraZ,
oldGroundColor, oldGroundTexture, oldSkyColor,
- oldSkyTexture, oldLightColor, oldWallsAlpha, observerCameraFieldOfView,
- observerCameraElevation != null ? observerCameraElevation.floatValue() : observerCameraZ,
+ oldSkyTexture, oldLightColor, oldWallsAlpha, observerCameraFieldOfView, observerCameraZ,
groundColor, groundTexture, skyColor,
skyTexture, lightColor, wallsAlpha);
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Undoable edit for 3D attributes modification. This class isn't anonymous to avoid
* being bound to controller and its view.
*/
private static class Home3DAttributesModificationUndoableEdit extends AbstractUndoableEdit {
private final Home home;
private final UserPreferences preferences;
private final float oldObserverCameraFieldOfView;
private final float oldObserverCameraZ;
private final int oldGroundColor;
private final HomeTexture oldGroundTexture;
private final int oldSkyColor;
private final HomeTexture oldSkyTexture;
private final int oldLightColor;
private final float oldWallsAlpha;
private final float observerCameraFieldOfView;
private final float observerCameraZ;
private final int groundColor;
private final HomeTexture groundTexture;
private final int skyColor;
private final HomeTexture skyTexture;
private final int lightColor;
private final float wallsAlpha;
private Home3DAttributesModificationUndoableEdit(Home home,
UserPreferences preferences,
float oldObserverCameraFieldOfView,
float oldObserverCameraZ,
int oldGroundColor,
HomeTexture oldGroundTexture,
int oldSkyColor,
HomeTexture oldSkyTexture,
int oldLightColor,
float oldWallsAlpha,
float observerCameraFieldOfView,
float observerCameraZ,
int groundColor,
HomeTexture groundTexture,
int skyColor,
HomeTexture skyTexture,
int lightColor,
float wallsAlpha) {
this.home = home;
this.preferences = preferences;
this.oldObserverCameraFieldOfView = oldObserverCameraFieldOfView;
this.oldObserverCameraZ = oldObserverCameraZ;
this.oldGroundColor = oldGroundColor;
this.oldGroundTexture = oldGroundTexture;
this.oldSkyColor = oldSkyColor;
this.oldSkyTexture = oldSkyTexture;
this.oldLightColor = oldLightColor;
this.oldWallsAlpha = oldWallsAlpha;
this.observerCameraFieldOfView = observerCameraFieldOfView;
this.observerCameraZ = observerCameraZ;
this.groundColor = groundColor;
this.groundTexture = groundTexture;
this.skyColor = skyColor;
this.skyTexture = skyTexture;
this.lightColor = lightColor;
this.wallsAlpha = wallsAlpha;
}
@Override
public void undo() throws CannotUndoException {
super.undo();
doModify3DAttributes(this.home, this.oldObserverCameraFieldOfView, this.oldObserverCameraZ,
this.oldGroundColor, this.oldGroundTexture, this.oldSkyColor, this.oldSkyTexture, this.oldLightColor, this.oldWallsAlpha);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doModify3DAttributes(this.home, this.observerCameraFieldOfView, this.observerCameraZ,
this.groundColor, this.groundTexture, this.skyColor, this.skyTexture, this.lightColor, this.wallsAlpha);
}
@Override
public String getPresentationName() {
return this.preferences.getLocalizedString(
Home3DAttributesController.class, "undoModify3DAttributesName");
}
}
/**
* Modifies the 3D attributes of the given <code>home</code>.
*/
private static void doModify3DAttributes(Home home,
float observerCameraFieldOfView,
float observerCameraZ,
int groundColor, HomeTexture groundTexture,
int skyColor, HomeTexture skyTexture,
int lightColor, float wallsAlpha) {
ObserverCamera observerCamera = home.getObserverCamera();
observerCamera.setFieldOfView(observerCameraFieldOfView);
observerCamera.setZ(observerCameraZ);
HomeEnvironment homeEnvironment = home.getEnvironment();
homeEnvironment.setGroundColor(groundColor);
homeEnvironment.setGroundTexture(groundTexture);
homeEnvironment.setSkyColor(skyColor);
homeEnvironment.setSkyTexture(skyTexture);
homeEnvironment.setLightColor(lightColor);
homeEnvironment.setWallsAlpha(wallsAlpha);
}
}
| false | true | public void modify3DAttributes() {
float observerCameraFieldOfView = (float)Math.toRadians(getObserverFieldOfViewInDegrees());
float observerCameraZ = getObserverHeight() * 14 / 15;
Float observerCameraElevation = getObserverCameraElevation();
int groundColor = getGroundColor();
HomeTexture groundTexture = getGroundPaint() == EnvironmentPaint.TEXTURED
? getGroundTextureController().getTexture()
: null;
int skyColor = getSkyColor();
HomeTexture skyTexture = getSkyPaint() == EnvironmentPaint.TEXTURED
? getSkyTextureController().getTexture()
: null;
int lightColor = getLightColor();
float wallsAlpha = getWallsAlpha();
float oldObserverCameraFieldOfView = this.home.getObserverCamera().getFieldOfView();
float oldObserverCameraZ = this.home.getObserverCamera().getZ();
HomeEnvironment homeEnvironment = this.home.getEnvironment();
int oldGroundColor = homeEnvironment.getGroundColor();
HomeTexture oldGroundTexture = homeEnvironment.getGroundTexture();
int oldSkyColor = homeEnvironment.getSkyColor();
HomeTexture oldSkyTexture = homeEnvironment.getSkyTexture();
int oldLightColor = homeEnvironment.getLightColor();
float oldWallsAlpha = homeEnvironment.getWallsAlpha();
// Apply modification
doModify3DAttributes(home, observerCameraFieldOfView, observerCameraZ,
groundColor, groundTexture, skyColor, skyTexture, lightColor, wallsAlpha);
if (this.undoSupport != null) {
UndoableEdit undoableEdit = new Home3DAttributesModificationUndoableEdit(
this.home, this.preferences,
oldObserverCameraFieldOfView, oldObserverCameraZ,
oldGroundColor, oldGroundTexture, oldSkyColor,
oldSkyTexture, oldLightColor, oldWallsAlpha, observerCameraFieldOfView,
observerCameraElevation != null ? observerCameraElevation.floatValue() : observerCameraZ,
groundColor, groundTexture, skyColor,
skyTexture, lightColor, wallsAlpha);
this.undoSupport.postEdit(undoableEdit);
}
}
| public void modify3DAttributes() {
float observerCameraFieldOfView = (float)Math.toRadians(getObserverFieldOfViewInDegrees());
Float observerCameraElevation = getObserverCameraElevation();
float observerCameraZ = observerCameraElevation != null
? observerCameraElevation.floatValue()
: getObserverHeight() * 14 / 15;
int groundColor = getGroundColor();
HomeTexture groundTexture = getGroundPaint() == EnvironmentPaint.TEXTURED
? getGroundTextureController().getTexture()
: null;
int skyColor = getSkyColor();
HomeTexture skyTexture = getSkyPaint() == EnvironmentPaint.TEXTURED
? getSkyTextureController().getTexture()
: null;
int lightColor = getLightColor();
float wallsAlpha = getWallsAlpha();
float oldObserverCameraFieldOfView = this.home.getObserverCamera().getFieldOfView();
float oldObserverCameraZ = this.home.getObserverCamera().getZ();
HomeEnvironment homeEnvironment = this.home.getEnvironment();
int oldGroundColor = homeEnvironment.getGroundColor();
HomeTexture oldGroundTexture = homeEnvironment.getGroundTexture();
int oldSkyColor = homeEnvironment.getSkyColor();
HomeTexture oldSkyTexture = homeEnvironment.getSkyTexture();
int oldLightColor = homeEnvironment.getLightColor();
float oldWallsAlpha = homeEnvironment.getWallsAlpha();
// Apply modification
doModify3DAttributes(home, observerCameraFieldOfView, observerCameraZ,
groundColor, groundTexture, skyColor, skyTexture, lightColor, wallsAlpha);
if (this.undoSupport != null) {
UndoableEdit undoableEdit = new Home3DAttributesModificationUndoableEdit(
this.home, this.preferences,
oldObserverCameraFieldOfView, oldObserverCameraZ,
oldGroundColor, oldGroundTexture, oldSkyColor,
oldSkyTexture, oldLightColor, oldWallsAlpha, observerCameraFieldOfView, observerCameraZ,
groundColor, groundTexture, skyColor,
skyTexture, lightColor, wallsAlpha);
this.undoSupport.postEdit(undoableEdit);
}
}
|
diff --git a/GAE/src/com/gallatinsystems/instancecreator/app/InstanceConfigurator.java b/GAE/src/com/gallatinsystems/instancecreator/app/InstanceConfigurator.java
index 692ba465f..9a1a58d14 100644
--- a/GAE/src/com/gallatinsystems/instancecreator/app/InstanceConfigurator.java
+++ b/GAE/src/com/gallatinsystems/instancecreator/app/InstanceConfigurator.java
@@ -1,186 +1,186 @@
package com.gallatinsystems.instancecreator.app;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import com.gallatinsystems.instancecreator.util.S3PolicySigner;
public class InstanceConfigurator {
private VelocityEngine engine = null;
private static final Logger log = Logger
.getLogger(InstanceConfigurator.class.getName());
private static String aws_secret_key = null;
public static void main(String[] args) {
InstanceConfigurator ic = new InstanceConfigurator();
String[] directories;
String s3policyFileTemplateName;
aws_secret_key = args[0];
ic.addAttribute("awsSecretKey", args[0]);
ic.addAttribute("awsIdentifier", args[1]);
ic.addAttribute("instanceName", args[2]);
ic.addAttribute("s3bucket", args[3]);
String s3bucket = args[3];
directories = args[4].split("\\|");
s3policyFileTemplateName = args[5];
ic.addAttribute("s3Id", args[1]);
ic.addAttribute("signingKey", args[6]);
ic.addAttribute("dataUploadUrl", args[7]);
ic.addAttribute("serverBase", args[8]);
ic.addAttribute("surveyS3Url", args[8] + "/surveys");
ic.addAttribute("storepass", args[9]);
ic.addAttribute("keypass", args[10]);
ic.addAttribute("alias", args[11]);
ic.addAttribute("reportsEmailAddress", args[12]);
ic.addAttribute("defaultPhotoCaption", args[13]);
ic.addAttribute("scoreAPFlag", args[14]);
ic.addAttribute("organization", args[15]);
ic.addAttribute("s3url",args[8]);
String localLocation = args[16];
ic.addAttribute("keystore",args[17]);
ic.addAttribute("mapsApiKey",args[18]);
localLocation = ic.createLocalDeployDir(localLocation, args[2]);
TreeMap<String, String[]> policyFiles = new TreeMap<String, String[]>();
S3PolicySigner s3PolicySigner = new S3PolicySigner();
try {
for (String directory : directories) {
String policyFile = ic.buildPolicyFile(s3bucket, directory,
s3policyFileTemplateName);
String[] documents = s3PolicySigner.createPolicyString(
policyFile, aws_secret_key);
log.log(Level.INFO, "bucket: " + s3bucket + " directory: "
+ directory + "\nsig: " + documents[0] + "\nkey:"
+ documents[1] + "\n" + policyFile);
if (directory.equals("reports")) {
ic.addAttribute("reportS3Sig", documents[0]);
ic.addAttribute("reportsS3Policy", documents[1]);
} else if (directory.equals("devicezip")) {
ic.addAttribute("reportS3Sig", documents[0]);
- ic.addAttribute("reportsS3Policy", documents[1]);
+ ic.addAttribute("reportS3Policy", documents[1]);
} else if (directory.equals("bootstrap")) {
ic.addAttribute("bootstrapS3Sig", documents[0]);
ic.addAttribute("bootstrapS3Policy", documents[1]);
} else if (directory.equals("helpcontent")) {
ic.addAttribute("helpcontentS3Sig", documents[0]);
ic.addAttribute("helpcontentS3Policy", documents[1]);
} else if (directory.equals("images")) {
ic.addAttribute("imagesS3Sig", documents[0]);
ic.addAttribute("imagesS3Policy", documents[1]);
} else if (directory.equals("surveys")) {
- ic.addAttribute("surveyS3Sig", documents[0]);
- ic.addAttribute("surveyS3Policy", documents[1]);
+ ic.addAttribute("surveySig", documents[0]);
+ ic.addAttribute("surveyPolicy", documents[1]);
}
policyFiles.put(directory, documents);
}
String appenginexml = ic.buildfile("war/appengine-web.vm");
ic.writeFile(localLocation, "appengine-web.xml", appenginexml);
String portalgwtxml = ic.buildfile("war/portalgwt.vm");
ic.writeFile(localLocation, "portal.gwt.xml", portalgwtxml);
String surveyentrygwtxml = ic.buildfile("war/surveyentrygwtxml.vm");
ic.writeFile(localLocation, "surveyEntry.gwt.xml", surveyentrygwtxml);
String uploadconstantproperties = ic.buildfile("war/UploadConstants.vm");
ic.writeFile(localLocation, "UploadConstants.properties", uploadconstantproperties);
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeFile(String location, String name, String contents)
throws IOException {
File file = new File(location + System.getProperty("file.separator")
+ name);
if (file.exists()) {
if (file.delete()) {
file.createNewFile();
}
}
Writer output = new BufferedWriter(new FileWriter(file));
try {
output.write(contents);
} finally {
output.close();
}
}
private String createLocalDeployDir(String dir, String instanceName) {
File f = new File(dir + instanceName);
if (!f.exists()) {
if (f.mkdir()) {
return f.getAbsolutePath();
}
} else {
return f.getAbsolutePath();
}
return null;
}
private String buildfile(String vmName) throws Exception {
VelocityContext context = new VelocityContext();
for (Entry<String, String> item : attributeMap.entrySet()) {
context.put(item.getKey(), item.getValue());
}
return mergeContext(context,vmName);
}
private HashMap<String, String> attributeMap = new HashMap<String, String>();
public void addAttribute(String attributeName, String attributeValue) {
attributeMap.put(attributeName, attributeValue);
}
public InstanceConfigurator() {
engine = new VelocityEngine();
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
try {
engine.init();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
};
private String buildPolicyFile(String s3bucket, String directory,
String templateName) throws Exception {
VelocityContext context = new VelocityContext();
context.put("s3bucket", s3bucket);
context.put("directory", directory);
return mergeContext(context, templateName);
}
/**
* merges a hydrated context with a template identified by the templateName
* passed in.
*
* @param context
* @param templateName
* @return
* @throws Exception
*/
private String mergeContext(VelocityContext context, String templateName)
throws Exception {
Template t = engine.getTemplate(templateName);
StringWriter writer = new StringWriter();
t.merge(context, writer);
context = null;
return writer.toString();
}
}
| false | true | public static void main(String[] args) {
InstanceConfigurator ic = new InstanceConfigurator();
String[] directories;
String s3policyFileTemplateName;
aws_secret_key = args[0];
ic.addAttribute("awsSecretKey", args[0]);
ic.addAttribute("awsIdentifier", args[1]);
ic.addAttribute("instanceName", args[2]);
ic.addAttribute("s3bucket", args[3]);
String s3bucket = args[3];
directories = args[4].split("\\|");
s3policyFileTemplateName = args[5];
ic.addAttribute("s3Id", args[1]);
ic.addAttribute("signingKey", args[6]);
ic.addAttribute("dataUploadUrl", args[7]);
ic.addAttribute("serverBase", args[8]);
ic.addAttribute("surveyS3Url", args[8] + "/surveys");
ic.addAttribute("storepass", args[9]);
ic.addAttribute("keypass", args[10]);
ic.addAttribute("alias", args[11]);
ic.addAttribute("reportsEmailAddress", args[12]);
ic.addAttribute("defaultPhotoCaption", args[13]);
ic.addAttribute("scoreAPFlag", args[14]);
ic.addAttribute("organization", args[15]);
ic.addAttribute("s3url",args[8]);
String localLocation = args[16];
ic.addAttribute("keystore",args[17]);
ic.addAttribute("mapsApiKey",args[18]);
localLocation = ic.createLocalDeployDir(localLocation, args[2]);
TreeMap<String, String[]> policyFiles = new TreeMap<String, String[]>();
S3PolicySigner s3PolicySigner = new S3PolicySigner();
try {
for (String directory : directories) {
String policyFile = ic.buildPolicyFile(s3bucket, directory,
s3policyFileTemplateName);
String[] documents = s3PolicySigner.createPolicyString(
policyFile, aws_secret_key);
log.log(Level.INFO, "bucket: " + s3bucket + " directory: "
+ directory + "\nsig: " + documents[0] + "\nkey:"
+ documents[1] + "\n" + policyFile);
if (directory.equals("reports")) {
ic.addAttribute("reportS3Sig", documents[0]);
ic.addAttribute("reportsS3Policy", documents[1]);
} else if (directory.equals("devicezip")) {
ic.addAttribute("reportS3Sig", documents[0]);
ic.addAttribute("reportsS3Policy", documents[1]);
} else if (directory.equals("bootstrap")) {
ic.addAttribute("bootstrapS3Sig", documents[0]);
ic.addAttribute("bootstrapS3Policy", documents[1]);
} else if (directory.equals("helpcontent")) {
ic.addAttribute("helpcontentS3Sig", documents[0]);
ic.addAttribute("helpcontentS3Policy", documents[1]);
} else if (directory.equals("images")) {
ic.addAttribute("imagesS3Sig", documents[0]);
ic.addAttribute("imagesS3Policy", documents[1]);
} else if (directory.equals("surveys")) {
ic.addAttribute("surveyS3Sig", documents[0]);
ic.addAttribute("surveyS3Policy", documents[1]);
}
policyFiles.put(directory, documents);
}
String appenginexml = ic.buildfile("war/appengine-web.vm");
ic.writeFile(localLocation, "appengine-web.xml", appenginexml);
String portalgwtxml = ic.buildfile("war/portalgwt.vm");
ic.writeFile(localLocation, "portal.gwt.xml", portalgwtxml);
String surveyentrygwtxml = ic.buildfile("war/surveyentrygwtxml.vm");
ic.writeFile(localLocation, "surveyEntry.gwt.xml", surveyentrygwtxml);
String uploadconstantproperties = ic.buildfile("war/UploadConstants.vm");
ic.writeFile(localLocation, "UploadConstants.properties", uploadconstantproperties);
} catch (Exception e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
InstanceConfigurator ic = new InstanceConfigurator();
String[] directories;
String s3policyFileTemplateName;
aws_secret_key = args[0];
ic.addAttribute("awsSecretKey", args[0]);
ic.addAttribute("awsIdentifier", args[1]);
ic.addAttribute("instanceName", args[2]);
ic.addAttribute("s3bucket", args[3]);
String s3bucket = args[3];
directories = args[4].split("\\|");
s3policyFileTemplateName = args[5];
ic.addAttribute("s3Id", args[1]);
ic.addAttribute("signingKey", args[6]);
ic.addAttribute("dataUploadUrl", args[7]);
ic.addAttribute("serverBase", args[8]);
ic.addAttribute("surveyS3Url", args[8] + "/surveys");
ic.addAttribute("storepass", args[9]);
ic.addAttribute("keypass", args[10]);
ic.addAttribute("alias", args[11]);
ic.addAttribute("reportsEmailAddress", args[12]);
ic.addAttribute("defaultPhotoCaption", args[13]);
ic.addAttribute("scoreAPFlag", args[14]);
ic.addAttribute("organization", args[15]);
ic.addAttribute("s3url",args[8]);
String localLocation = args[16];
ic.addAttribute("keystore",args[17]);
ic.addAttribute("mapsApiKey",args[18]);
localLocation = ic.createLocalDeployDir(localLocation, args[2]);
TreeMap<String, String[]> policyFiles = new TreeMap<String, String[]>();
S3PolicySigner s3PolicySigner = new S3PolicySigner();
try {
for (String directory : directories) {
String policyFile = ic.buildPolicyFile(s3bucket, directory,
s3policyFileTemplateName);
String[] documents = s3PolicySigner.createPolicyString(
policyFile, aws_secret_key);
log.log(Level.INFO, "bucket: " + s3bucket + " directory: "
+ directory + "\nsig: " + documents[0] + "\nkey:"
+ documents[1] + "\n" + policyFile);
if (directory.equals("reports")) {
ic.addAttribute("reportS3Sig", documents[0]);
ic.addAttribute("reportsS3Policy", documents[1]);
} else if (directory.equals("devicezip")) {
ic.addAttribute("reportS3Sig", documents[0]);
ic.addAttribute("reportS3Policy", documents[1]);
} else if (directory.equals("bootstrap")) {
ic.addAttribute("bootstrapS3Sig", documents[0]);
ic.addAttribute("bootstrapS3Policy", documents[1]);
} else if (directory.equals("helpcontent")) {
ic.addAttribute("helpcontentS3Sig", documents[0]);
ic.addAttribute("helpcontentS3Policy", documents[1]);
} else if (directory.equals("images")) {
ic.addAttribute("imagesS3Sig", documents[0]);
ic.addAttribute("imagesS3Policy", documents[1]);
} else if (directory.equals("surveys")) {
ic.addAttribute("surveySig", documents[0]);
ic.addAttribute("surveyPolicy", documents[1]);
}
policyFiles.put(directory, documents);
}
String appenginexml = ic.buildfile("war/appengine-web.vm");
ic.writeFile(localLocation, "appengine-web.xml", appenginexml);
String portalgwtxml = ic.buildfile("war/portalgwt.vm");
ic.writeFile(localLocation, "portal.gwt.xml", portalgwtxml);
String surveyentrygwtxml = ic.buildfile("war/surveyentrygwtxml.vm");
ic.writeFile(localLocation, "surveyEntry.gwt.xml", surveyentrygwtxml);
String uploadconstantproperties = ic.buildfile("war/UploadConstants.vm");
ic.writeFile(localLocation, "UploadConstants.properties", uploadconstantproperties);
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/tests/src/com/android/inputmethod/latin/SuggestHelper.java b/tests/src/com/android/inputmethod/latin/SuggestHelper.java
index a845acb9..ed01a753 100644
--- a/tests/src/com/android/inputmethod/latin/SuggestHelper.java
+++ b/tests/src/com/android/inputmethod/latin/SuggestHelper.java
@@ -1,158 +1,159 @@
/*
* 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.inputmethod.latin;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.KeyDetector;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.keyboard.LatinKeyboard;
import com.android.inputmethod.keyboard.ProximityKeyDetector;
import android.content.Context;
import android.text.TextUtils;
import java.io.File;
import java.util.List;
public class SuggestHelper {
protected final Suggest mSuggest;
private final LatinKeyboard mKeyboard;
private final KeyDetector mKeyDetector;
public SuggestHelper(Context context, int dictionaryId, KeyboardId keyboardId) {
mSuggest = new Suggest(context, dictionaryId);
mKeyboard = new LatinKeyboard(context, keyboardId);
mKeyDetector = new ProximityKeyDetector();
init();
}
protected SuggestHelper(Context context, File dictionaryPath, long startOffset, long length,
KeyboardId keyboardId) {
mSuggest = new Suggest(dictionaryPath, startOffset, length);
mKeyboard = new LatinKeyboard(context, keyboardId);
mKeyDetector = new ProximityKeyDetector();
init();
}
private void init() {
mSuggest.setQuickFixesEnabled(false);
mSuggest.setCorrectionMode(Suggest.CORRECTION_FULL);
mKeyDetector.setKeyboard(mKeyboard, 0, 0);
mKeyDetector.setProximityCorrectionEnabled(true);
mKeyDetector.setProximityThreshold(KeyDetector.getMostCommonKeyWidth(mKeyboard));
}
public void setCorrectionMode(int correctionMode) {
mSuggest.setCorrectionMode(correctionMode);
}
public boolean hasMainDictionary() {
return mSuggest.hasMainDictionary();
}
private void addKeyInfo(WordComposer word, char c) {
final List<Key> keys = mKeyboard.getKeys();
for (final Key key : keys) {
if (key.mCode == c) {
final int x = key.mX + key.mWidth / 2;
final int y = key.mY + key.mHeight / 2;
final int[] codes = mKeyDetector.newCodeArray();
mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes);
word.add(c, codes, x, y);
+ return;
}
}
word.add(c, new int[] { c }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
protected WordComposer createWordComposer(CharSequence s) {
WordComposer word = new WordComposer();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
addKeyInfo(word, c);
}
return word;
}
public boolean isValidWord(CharSequence typed) {
return mSuggest.isValidWord(typed);
}
// TODO: This may be slow, but is OK for test so far.
public SuggestedWords getSuggestions(CharSequence typed) {
return mSuggest.getSuggestions(null, createWordComposer(typed), null);
}
public CharSequence getFirstSuggestion(CharSequence typed) {
WordComposer word = createWordComposer(typed);
SuggestedWords suggestions = mSuggest.getSuggestions(null, word, null);
// Note that suggestions.getWord(0) is the word user typed.
return suggestions.size() > 1 ? suggestions.getWord(1) : null;
}
public CharSequence getAutoCorrection(CharSequence typed) {
WordComposer word = createWordComposer(typed);
SuggestedWords suggestions = mSuggest.getSuggestions(null, word, null);
// Note that suggestions.getWord(0) is the word user typed.
return (suggestions.size() > 1 && mSuggest.hasAutoCorrection())
? suggestions.getWord(1) : null;
}
public int getSuggestIndex(CharSequence typed, CharSequence expected) {
WordComposer word = createWordComposer(typed);
SuggestedWords suggestions = mSuggest.getSuggestions(null, word, null);
// Note that suggestions.getWord(0) is the word user typed.
for (int i = 1; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.getWord(i), expected))
return i;
}
return -1;
}
private void getBigramSuggestions(CharSequence previous, CharSequence typed) {
if (!TextUtils.isEmpty(previous) && (typed.length() > 1)) {
WordComposer firstChar = createWordComposer(Character.toString(typed.charAt(0)));
mSuggest.getSuggestions(null, firstChar, previous);
}
}
public CharSequence getBigramFirstSuggestion(CharSequence previous, CharSequence typed) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
SuggestedWords suggestions = mSuggest.getSuggestions(null, word, previous);
return suggestions.size() > 1 ? suggestions.getWord(1) : null;
}
public CharSequence getBigramAutoCorrection(CharSequence previous, CharSequence typed) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
SuggestedWords suggestions = mSuggest.getSuggestions(null, word, previous);
return (suggestions.size() > 1 && mSuggest.hasAutoCorrection())
? suggestions.getWord(1) : null;
}
public int searchBigramSuggestion(CharSequence previous, CharSequence typed,
CharSequence expected) {
WordComposer word = createWordComposer(typed);
getBigramSuggestions(previous, typed);
SuggestedWords suggestions = mSuggest.getSuggestions(null, word, previous);
for (int i = 1; i < suggestions.size(); i++) {
if (TextUtils.equals(suggestions.getWord(i), expected))
return i;
}
return -1;
}
}
| true | true | private void addKeyInfo(WordComposer word, char c) {
final List<Key> keys = mKeyboard.getKeys();
for (final Key key : keys) {
if (key.mCode == c) {
final int x = key.mX + key.mWidth / 2;
final int y = key.mY + key.mHeight / 2;
final int[] codes = mKeyDetector.newCodeArray();
mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes);
word.add(c, codes, x, y);
}
}
word.add(c, new int[] { c }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
| private void addKeyInfo(WordComposer word, char c) {
final List<Key> keys = mKeyboard.getKeys();
for (final Key key : keys) {
if (key.mCode == c) {
final int x = key.mX + key.mWidth / 2;
final int y = key.mY + key.mHeight / 2;
final int[] codes = mKeyDetector.newCodeArray();
mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes);
word.add(c, codes, x, y);
return;
}
}
word.add(c, new int[] { c }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
|
diff --git a/src/edu/common/dynamicextensions/validation/DateValidator.java b/src/edu/common/dynamicextensions/validation/DateValidator.java
index f36bb7117..e944501ef 100644
--- a/src/edu/common/dynamicextensions/validation/DateValidator.java
+++ b/src/edu/common/dynamicextensions/validation/DateValidator.java
@@ -1,145 +1,145 @@
package edu.common.dynamicextensions.validation;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import edu.common.dynamicextensions.domain.DateAttributeTypeInformation;
import edu.common.dynamicextensions.domaininterface.AttributeMetadataInterface;
import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsValidationException;
/**
* @author chetan_patil
*
*/
public class DateValidator implements ValidatorRuleInterface
{
/**
* @see edu.common.dynamicextensions.validation.ValidatorRuleInterface#validate(edu.common.dynamicextensions.domaininterface.AttributeInterface, java.lang.Object, java.util.Map)
* @throws DynamicExtensionsValidationException
*/
public boolean validate(AttributeMetadataInterface attribute, Object valueObject,
Map<String, String> parameterMap, String controlCaption)
throws DynamicExtensionsValidationException
{
boolean valid = true;
valid = validateDate(attribute, valueObject, controlCaption);
return valid;
}
/**
* Validate user input for permissible date values for date with range.
* @param attribute
* @param valueObject
* @param parameterMap
* @param controlCaption
* @param isFromDateRangeValidator
* @return
* @throws DynamicExtensionsValidationException
*/
public boolean validate(AttributeMetadataInterface attribute, Object valueObject,
Map<String, String> parameterMap, String controlCaption,
boolean isFromDateRangeValidator) throws DynamicExtensionsValidationException
{
boolean valid = true;
valid = validateDate(attribute, valueObject, controlCaption,
isFromDateRangeValidator);
return valid;
}
/**
* Validate user input for permissible date values.
* @param attribute
* @param valueObject
* @param controlCaption
* @param isFromDateRangeValidator
* @return
* @throws DynamicExtensionsValidationException
*/
private boolean validateDate(AttributeMetadataInterface attribute, Object valueObject,
String controlCaption,
boolean... isFromDateRangeValidator) throws DynamicExtensionsValidationException
{
boolean valid = true;
AttributeTypeInformationInterface attributeTypeInformation = attribute
.getAttributeTypeInformation();
if (((valueObject != null) && (!((String) valueObject).trim().equals("")))
&& ((attributeTypeInformation != null) && (attributeTypeInformation instanceof DateAttributeTypeInformation)))
{
DateAttributeTypeInformation dateAttributeTypeInformation = (DateAttributeTypeInformation) attributeTypeInformation;
String dateFormat = dateAttributeTypeInformation.getFormat();
String value = (String) valueObject;
Date tempDate = null;
try
{
- SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
- sf.setLenient(false);
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
+ simpleDateFormat.setLenient(false);
if (isFromDateRangeValidator.length == 0)
{
- tempDate = sf.parse(value);
+ tempDate = simpleDateFormat.parse(value);
}
else
{
- sf.parse(value);
+ simpleDateFormat.parse(value);
}
}
catch (ParseException parseException)
{
valid = false;
}
// Validate if year is equal to '0000' or contains '.' symbol
if (value.endsWith("0000") || value.contains("."))
{
valid = false;
}
// Validate length of entered date
if (dateFormat.length() != value.length())
{
valid = false;
}
if (valid && isFromDateRangeValidator.length == 0 && tempDate.after(new Date()))
{
reportInvalidInput(controlCaption, "today's date.",
"dynExtn.validation.Date.Max");
}
if (!valid)
{
reportInvalidInput(controlCaption, dateFormat, "dynExtn.validation.Date");
}
}
return valid;
}
/**
* Report invalid user inputs to the user.
* @param placeHolderOne
* @param placeHolderTwo
* @param errorKey
* @throws DynamicExtensionsValidationException
*/
private void reportInvalidInput(String placeHolderOne, String placeHolderTwo, String errorKey)
throws DynamicExtensionsValidationException
{
List<String> placeHolders = new ArrayList<String>();
placeHolders.add(placeHolderOne);
placeHolders.add(placeHolderTwo);
throw new DynamicExtensionsValidationException("Validation failed", null, errorKey,
placeHolders);
}
}
| false | true | private boolean validateDate(AttributeMetadataInterface attribute, Object valueObject,
String controlCaption,
boolean... isFromDateRangeValidator) throws DynamicExtensionsValidationException
{
boolean valid = true;
AttributeTypeInformationInterface attributeTypeInformation = attribute
.getAttributeTypeInformation();
if (((valueObject != null) && (!((String) valueObject).trim().equals("")))
&& ((attributeTypeInformation != null) && (attributeTypeInformation instanceof DateAttributeTypeInformation)))
{
DateAttributeTypeInformation dateAttributeTypeInformation = (DateAttributeTypeInformation) attributeTypeInformation;
String dateFormat = dateAttributeTypeInformation.getFormat();
String value = (String) valueObject;
Date tempDate = null;
try
{
SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
sf.setLenient(false);
if (isFromDateRangeValidator.length == 0)
{
tempDate = sf.parse(value);
}
else
{
sf.parse(value);
}
}
catch (ParseException parseException)
{
valid = false;
}
// Validate if year is equal to '0000' or contains '.' symbol
if (value.endsWith("0000") || value.contains("."))
{
valid = false;
}
// Validate length of entered date
if (dateFormat.length() != value.length())
{
valid = false;
}
if (valid && isFromDateRangeValidator.length == 0 && tempDate.after(new Date()))
{
reportInvalidInput(controlCaption, "today's date.",
"dynExtn.validation.Date.Max");
}
if (!valid)
{
reportInvalidInput(controlCaption, dateFormat, "dynExtn.validation.Date");
}
}
return valid;
}
| private boolean validateDate(AttributeMetadataInterface attribute, Object valueObject,
String controlCaption,
boolean... isFromDateRangeValidator) throws DynamicExtensionsValidationException
{
boolean valid = true;
AttributeTypeInformationInterface attributeTypeInformation = attribute
.getAttributeTypeInformation();
if (((valueObject != null) && (!((String) valueObject).trim().equals("")))
&& ((attributeTypeInformation != null) && (attributeTypeInformation instanceof DateAttributeTypeInformation)))
{
DateAttributeTypeInformation dateAttributeTypeInformation = (DateAttributeTypeInformation) attributeTypeInformation;
String dateFormat = dateAttributeTypeInformation.getFormat();
String value = (String) valueObject;
Date tempDate = null;
try
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
simpleDateFormat.setLenient(false);
if (isFromDateRangeValidator.length == 0)
{
tempDate = simpleDateFormat.parse(value);
}
else
{
simpleDateFormat.parse(value);
}
}
catch (ParseException parseException)
{
valid = false;
}
// Validate if year is equal to '0000' or contains '.' symbol
if (value.endsWith("0000") || value.contains("."))
{
valid = false;
}
// Validate length of entered date
if (dateFormat.length() != value.length())
{
valid = false;
}
if (valid && isFromDateRangeValidator.length == 0 && tempDate.after(new Date()))
{
reportInvalidInput(controlCaption, "today's date.",
"dynExtn.validation.Date.Max");
}
if (!valid)
{
reportInvalidInput(controlCaption, dateFormat, "dynExtn.validation.Date");
}
}
return valid;
}
|
diff --git a/src/at/mabs/model/ModelHistroy.java b/src/at/mabs/model/ModelHistroy.java
index dd2c4ca..2c8a9b6 100644
--- a/src/at/mabs/model/ModelHistroy.java
+++ b/src/at/mabs/model/ModelHistroy.java
@@ -1,754 +1,755 @@
/*
This code is licensed under the LGPL v3 or greater with the classpath exception,
with the following additions and exceptions.
packages cern.* have retained the original cern copyright notices.
packages at.mabs.cmdline and at.mabs.util.*
have the option to be licensed under a BSD(simplified) or Apache 2.0 or greater license
in addition to LGPL.
Note that you have permission to replace this license text to any of the permitted licenses.
Main text for LGPL can be found here:
http://www.opensource.org/licenses/lgpl-license.php
For BSD:
http://www.opensource.org/licenses/bsd-license.php
for Apache:
http://www.opensource.org/licenses/apache2.0.php
classpath exception:
http://www.gnu.org/software/classpath/license.html
*/
package at.mabs.model;
import java.io.PrintStream;
import java.util.*;
import at.mabs.coalescent.LineageState;
import at.mabs.model.selection.BasicFrequencyCondition;
import at.mabs.model.selection.DefaultSelectionSimulator;
import at.mabs.model.selection.FrequencyCondition;
import at.mabs.model.selection.FrequencyTrace;
import at.mabs.model.selection.SelectionData;
import at.mabs.model.selection.SuperFrequencyTrace;
import at.mabs.model.selection.SelectionEndTimeEvent;
import at.mabs.model.selection.SelectionSimulator;
import at.mabs.model.selection.SelectionStartEvent;
import at.mabs.model.selection.SelectionTimeConditionEvent;
import at.mabs.model.selection.RestartCondition;
import at.mabs.stats.ForwardStatsCollector;
/**
* the container for models and events. It describes a history of models and how to map changes
* between them. Everything has a strict order.
*
* We also provide a place for gloabal parameters. Such as mutation rate, recombination rate and
* forward/reverse benifical mutation rate.
*
* @author bob
*
*/
public class ModelHistroy {
private double recombinationRate;
private long recombinationCutSites;
// wild type to selectied
private double forwardAlleleMutationRate;
// selelted to wild type.
private double backAlleleMutationRate;
private double neutralMutationRate;
private int segSiteCount;
private double alleleLocation;
private double sAA, saA, saa;
private double N;
private SampleConfiguration sampleConfig;
private double[] lociConfiguration = { 0, 1 };
private FrequencyCondition timedCondition=new BasicFrequencyCondition(-1, -1, 1);//fixation!
private RestartCondition restartCondtion=new RestartCondition.Default();//restart on none.
/*
* each model has a set of events between it and the next model. If there is only one model the
* event set is empty. these need to be both a list and a Deque... we want constant time
* insertion and removal. Almost all changes should be done via ListIterators.
*/
private LinkedList<Model> models;
private LinkedList<ModelEvent> events;
//private LinkedList<Object> modelsAndEvents;
private boolean selection;
private SelectionSimulator selectionSimulator =new DefaultSelectionSimulator();
private ForwardStatsCollector forwardTraceOutput;
private boolean foldMutations;
private boolean unphase;
/**
* creates the models. builds up the finalised models from the events. This will not mutate the
* events list...
*
* @param N
* @param nDemes
* @param m
* @param events
*/
public ModelHistroy(int nDemes, double N, double m, List<ModelEvent> e, boolean forwardOnly) {
Model model =new Model(this, nDemes, N, m);
model.setForwardOnly(forwardOnly);
this.N =N;
events =new LinkedList<ModelEvent>(e);
Collections.sort(events);
// System.out.println("Sorted:"+events);
// find a selection event
// for (ModelEvent me : events) {
// if ((me instanceof SelectionEndTimeEvent) || (me instanceof SelectionTimeConditionEvent)) {
// selection =true;
// break;
// }
// }
List<ModelEvent> shortList =new ArrayList<ModelEvent>();
models =new LinkedList<Model>();
// so now we need to be a little smarter as not all the events can now be removed.
// we need to use iterators that don't have a "current"
Iterator<ModelEvent> iterator =events.listIterator();
double time =0;
// new version
// add the basic model.
// models.add(model);
// model.commitObject();
// model=new Model(model);
//System.out.println("modelFirst:"+Arrays.tomodel.getMigrationRatesByDeme());
while (iterator.hasNext()) {
ModelEvent event =iterator.next();
if (event.getEventTime() == time) {
// collect all events for this model break
shortList.add(event);
} else {
// we have finished this model break...
model.setEndTime(event.getEventTime());
// so end and start time are set
for (ModelEvent me : shortList) {
me.modifiyModel(model);
}
model.commitObject();
models.add(model);
// now for the next model
model =new Model(model);
model.setStartTime(event.getEventTime());
time =event.getEventTime();
shortList.clear();
shortList.add(event);
}
if (event.isModelOnly()) {
iterator.remove();
// System.out.println("RM:"+event+"\t"+event.getEventTime());
}
}
// now finish the last model
model.setEndTime(Long.MAX_VALUE);
for (ModelEvent me : shortList) {
me.modifiyModel(model);
}
model.commitObject();
models.add(model);
//System.out.println("Models:"+models);
// for (Model mm : models) {
// System.out.println("Models:" + Arrays.toString(mm.getTotalMigrationRates()) + "\t" + mm.getStartTime() + "\t" + mm.getEndTime());
// }
// for (ModelEvent me : events) {
// System.out.println("Events:" + me);
// }
// modelsAndEvents=new LinkedList<Object>();
// modelsAndEvents.addAll(events);
// modelsAndEvents.addAll(models);
// Collections.sort(modelsAndEvents,new Comparator<Object>() {
// @Override
// public int compare(Object o1, Object o2) {
// double time1=getTime(o1);
// double time2=getTime(o2);
// if(time1>time2)
// return 1;
// if(time1<time2)
// return -1;
// return 0;
// }
//
// private double getTime(Object o){
// assert o!=null;
// if(o instanceof Model)
// return ((Model)o).getStartTime();
// return ((ModelEvent)o).getEventTime();
// }
// });
//System.out.println(modelsAndEvents);
}
public int getMaxDemeCount() {
return models.getLast().getDemeCount();
}
public int getFirstModelDemeCount() {
return models.getFirst().getDemeCount();
}
public double getRecombinationRate() {
return recombinationRate;
}
public void setRecombinationRate(double recombinationRate) {
this.recombinationRate =recombinationRate;
}
public void setRecombinationCutSites(long recombinationCutSites) {
this.recombinationCutSites =recombinationCutSites;
}
public long getRecombinationCutSites() {
return recombinationCutSites;
}
public double getForwardAlleleMutationRate() {
return forwardAlleleMutationRate;
}
public void setForwardAlleleMutationRate(double alleleMutationRate) {
this.forwardAlleleMutationRate =alleleMutationRate;
}
public double getBackAlleleMutationRate() {
return backAlleleMutationRate;
}
public void setBackAlleleMutationRate(double backAlleleMutationRate) {
this.backAlleleMutationRate =backAlleleMutationRate;
}
public double getNeutralMutationRate() {
return neutralMutationRate;
}
public void setNeutralMutationRate(double neutralMutationRate) {
this.neutralMutationRate =neutralMutationRate;
}
public double getAlleleLocation() {
return alleleLocation;
}
public void setAlleleLocation(double alleleLocation) {
this.alleleLocation =alleleLocation;
}
public BackwardIterator backwardIterator() {
return new BackwardIterator();
}
public boolean isSelection() {
return selection;
}
public double getSAA() {
return sAA;
}
public double getSaA() {
return saA;
}
public double getSaa() {
return saa;
}
public void setSAA(double saa) {
sAA =saa;
}
public void setSaA(double saA) {
this.saA =saA;
}
public void setSaa(double saa) {
this.saa =saa;
}
public double getN() {
return N;
}
public List<SuperFrequencyTrace> getSelectionTraces() {
List<SuperFrequencyTrace> traces =new ArrayList<SuperFrequencyTrace>();
if (!selection)
return traces;
Iterator<Model> modIter =models.iterator();
while (modIter.hasNext()) {
Model model =modIter.next();
SelectionData sd =model.getSelectionData();
if (sd != null) {
SuperFrequencyTrace ft =sd.getFrequencys();
if (ft != null ) {
traces.add(ft);
// System.out.println("Model:"+model+"\n\t"+sd+"\n\t"+ft);
}
}
}
Collections.reverse(traces);
return traces;
}
public double simulateSelection(){
//System.err.println("MH simulation called:"+selection);
if(!selection)
return 0;
if (N == Integer.MAX_VALUE || N==Long.MAX_VALUE)//not correct...its a note for me
throw new RuntimeException("Must use the -N option with selection");
//System.err.println("Do i have any events that we give a crap about?:"+events);
// first lets clear volitoles
Iterator<ModelEvent> iterator =events.iterator();
while (iterator.hasNext()) {
ModelEvent me =iterator.next();
if (me.isVolatileSelectionEvent())
iterator.remove();
}
//init simulator
List<ModelEvent> moreEvents=getSelectionSimulator().init(this);//more FIXME we just don't have the class design right here
events.addAll(moreEvents);
Collections.sort(events);
//System.out.println(events);
//System.err.println("more evets?:"+events);
//we find the start and keep calling till we are either at the last model, or
// we hit a start selection event. then all all the new selection events...
Iterator<ModelEvent> eventIterator=events.descendingIterator();
Iterator<Model> modelIterator=models.descendingIterator();
ModelEvent startEvent=eventIterator.next();
while(!(startEvent instanceof SelectionEndTimeEvent || startEvent instanceof SelectionTimeConditionEvent) && eventIterator.hasNext()){
startEvent=eventIterator.next();
}
//System.err.println("StartEvent:"+startEvent);
//if(!(startEvent instanceof SelectionEndTimeEvent)){
// throw new RuntimeException("No Selection \"end\"!");
//}
//get to the right model... ie the first model with start time < event time.
Model model=modelIterator.next();
while(model.getStartTime()>startEvent.getEventTime() && modelIterator.hasNext()){
model=modelIterator.next();
}
if(startEvent instanceof SelectionEndTimeEvent && modelIterator.hasNext() && model.getStartTime()>=startEvent.getEventTime()){//note the =
model=modelIterator.next();
}
//System.err.println("FirstModel:"+model+"\t"+startEvent+"\t"+model.getStartTime());
//note that we have the model at and *above* the SelectionTimeConditionEvent
//now we go down the models as required with "boundry" events and the posiblity of intermediate
//events --however intermediate events do not require boundry checks.
double lastSweepTime=-1;
FrequencyState fstate=new FrequencyState(this.getMaxDemeCount(), model.getDemeCount());
//so the current "start" event
model.initSelectionData();
//System.err.println("SSim:"+model);
if(startEvent instanceof SelectionEndTimeEvent){
FrequencyState init=((SelectionEndTimeEvent)startEvent).getInitalFrequencys();
model.getSelectionData().setFrequencyToEnd(init);
}
List<ModelEvent> newEvents=model.getSelectionData().runSelectionSimulation();// side effect, uses selection simulator thats inited.
lastSweepTime=model.getSelectionData().getSweepTime();
while(modelIterator.hasNext()){
//in fact first we see if we should have stoped.
if(containtsForwardSimStopEvent(newEvents)){
break;
}
//first we find the next model
Model nextModel=modelIterator.next();
nextModel.initSelectionData();
//now we move the events to the relevent boundry... note we don't do anything with
//events that are intermediate in a model. This is because these events are for the
// coalsescent part... you can't "copy" state within a model pass... so events that
//need to do this must already be processed.
while(startEvent.getEventTime()!=nextModel.getStartTime() && eventIterator.hasNext()){
startEvent=eventIterator.next();
if(startEvent instanceof SelectionStartEvent)
break;//don't need to break to a label, since the remaining whiles will fall through to the instanceof test again
}
//now apply events. but should make sure they are not "stop" events
model.getSelectionData().getFrequencysFromStart(fstate);
while(startEvent.getEventTime()==nextModel.getStartTime() && !(startEvent instanceof SelectionStartEvent)){
startEvent.processEventSelection(model.getSelectionData(), nextModel.getSelectionData(), fstate);
if(eventIterator.hasNext()){
startEvent=eventIterator.next();
}else{
break;
}
}
//we need to consider the case where there are a bunch models between here and this "startEvent"
if(startEvent instanceof SelectionStartEvent && startEvent.getEventTime()>=nextModel.getEndTime()){
break;
}
//we are gold... we simulate the next model.
//System.out.println("SSim:"+nextModel);
SelectionData data=nextModel.getSelectionData();
data.setFrequencyToEnd(fstate);
List<ModelEvent> reallyNewEvents=data.runSelectionSimulation();
newEvents.addAll(reallyNewEvents);
lastSweepTime=data.getSweepTime();
model=nextModel;
}
+ System.out.println("newand Old:"+newEvents+"\n\t"+events);
events.addAll(newEvents);
Collections.sort(events);
//System.out.println(lastSweepTime);
return lastSweepTime;
}
private boolean containtsForwardSimStopEvent(List<ModelEvent> newEvents) {
for(ModelEvent me:newEvents){
if(me instanceof SelectionStartEvent)
return true;
}
return false;
}
/**
* this gives access to the events and models...
*
* This permits internal management of events that occur in the middle of a valid model. Such
* events are dynamic in that they occur at different times due to zeros in the selection
* simulation.
*
* Backward is in the sense of time. ie pastward.
*
* @author bob
*
*/
/*
* don't forget the case where there are no events between the models
*/
public class BackwardIterator {
private ListIterator<ModelEvent> eventIterator;
private ListIterator<Model> modelIterator;
private ModelEvent currentEvent;
private Model currentModel;
private BackwardIterator() {
eventIterator =events.listIterator();
if (eventIterator.hasNext())
currentEvent =eventIterator.next();
modelIterator =models.listIterator();
currentModel =modelIterator.next();
//System.out.println(models);
//System.out.println(events);
}
public Model getCurrentModel() {
return currentModel;
}
public long getNextEventTime() {
if (currentEvent != null)
return Math.min(currentEvent.getEventTime(), currentModel.getEndTime());
return currentModel.getEndTime();
}
/**
* moves to the next model via processing the needed events.
*
* The state must be at the current next Event Time...
*
* @param state
*/
public void nextModel(LineageState state) {
state.setCurrentTime(getNextEventTime());
double time =getNextEventTime();
if (time == Long.MAX_VALUE) {
//assert false:state.getLinagesActive();
throw new RuntimeException(
"Model does not permit full coalescent of linages.\n Check for zero migration rates or for exp population growth pastward");
}
// we have severl posible states.
// -1 we have important events at time zero.... ie newSamples
// 1 the current event is before the model end.. we increment events but not a model
// 2 the current events == the the model end. we increment events and the model
// 3 the current events are after the model. We just incremet the model
// this covers the 2 cases where the events need to be increment
//System.out.println("PreCurrentEventLoop:"+currentEvent);
while (currentEvent != null && currentEvent.getEventTime() == time) {
//System.out.println("EventsMoveLoop:"+currentEvent);
currentEvent.processEventCoalecent(state);
if (eventIterator.hasNext()) {
currentEvent =eventIterator.next();
} else {
currentEvent =null;
}
}
//
if ((time >= currentModel.getEndTime() || currentEvent == null) && modelIterator.hasNext() && time>0) {
currentModel =modelIterator.next();
}
state.setCurrentMaxTime(getNextEventTime());
state.setSelectionData(currentModel.getSelectionData());
//System.out.println("SelectionData? "+currentModel.getSelectionData()+"\t"+state.getSelectionData());
}
public void finishSelectionEvents(LineageState state) {
if(currentEvent!=null){
currentEvent.processEventCoalecent(state);
}
while(eventIterator.hasNext()){
currentEvent=eventIterator.next();
currentEvent.processEventCoalecent(state);
}
currentEvent=null;
currentModel=null;//make sure we don't call it again.
modelIterator=null;
eventIterator=null;
}
}
/**
* we relax the original assumptions and try and keep the code cleaner.
*
* In particular we relax that model boundaries and events times must coincide. ie events
* can happen in the middle of a model. And these can be selection events.
* @author greg
*
*/
private class newForwardIterator {
private Model currentModel;
private ModelEvent currentEvent;
private Iterator<ModelEvent> eventIterator =events.descendingIterator();
private Iterator<Model> modelIterator =models.descendingIterator();
private FrequencyState state;
public newForwardIterator() {
state =new FrequencyState(models.getLast().getDemeCount(), models.getLast().getDemeCount());
//find the first "selection start time event".
//however we may not have a "start event" iff we are conditioning on end time. ie that gets
//created with the forward simulator.
while(eventIterator.hasNext()){
currentEvent=eventIterator.next();
if(currentEvent instanceof SelectionEndTimeEvent){
moveToModel(currentEvent.getEventTime());
return;//we are done!
}
if(currentEvent instanceof SelectionTimeConditionEvent){// the "fixation at time 0" event
moveToModel(currentEvent.getEventTime());
return;
}
}
assert false;
}
private void moveToModel(long time){
while(currentModel.getStartTime()>time && modelIterator.hasNext()){
currentModel=modelIterator.next();
}
}
}
/*FIXME
* this class provides a similar function to the backwards iterator. the assumption will be cut
* and pasted here from the selection simulation block. That is the only thing that should use
* this.
*
* the current model is always the model *above* the currentEvent. In otherwords the first event
* to get to the "next" model is the current Event.
*
* we seek to the SelectionEndTime Event and throw exceptions if we Find a FixationTimeEvent or
* no selectionEvent...Note that the current model is the model ABOVE the SelectionEndTimeEvent
*
* @author bob
*/
private class ForwardIterator {
private Model currentModel;
private ModelEvent currentEvent;
private Iterator<ModelEvent> eventIterator =events.descendingIterator();
private Iterator<Model> modelIterator =models.descendingIterator();
private FrequencyState state;
private ForwardIterator() {
// for (Model mm : models) {
// System.out.println("Models:" + Arrays.toString(mm.getTotalMigrationRates()) + "\t" + mm.getStartTime() + "\t" + mm.getEndTime());
// }
// for (ModelEvent me : events) {
// System.out.println("Events:" + me);
// }
eventIterator =events.descendingIterator();
modelIterator =models.descendingIterator();
state =new FrequencyState(models.getLast().getDemeCount(), models.getLast().getDemeCount());// should
// //
// zero
// so now we just need to find the correct place.
while (eventIterator.hasNext()) {
currentEvent =eventIterator.next();
if (currentEvent instanceof SelectionTimeConditionEvent) {
// should never happen
throw new RuntimeException("Fixation Time Error. Perhaps your model is not time invarant.");
}
if (currentEvent instanceof SelectionEndTimeEvent) {
break;
}
}
if (!(currentEvent instanceof SelectionEndTimeEvent)) {
throw new RuntimeException("Selection must have a start or end time");
}
// we are now at the right place...
// now to get the model to the correct place.
currentModel =modelIterator.next();
while (currentModel.getStartTime() != currentEvent.getEventTime() && modelIterator.hasNext()) {
currentModel =modelIterator.next();
}
currentModel.initSelectionData();
}
/*
* this is always true...even for models with no events between them...
*/
// public double getNextEventTime() {
// return currentModel.getStartTime();
// }
/*
* Guts of the class. move to the next model --by applying the events between
*/
public void moveToNextModel() {
currentModel.getSelectionData().getFrequencysFromStart(state);
// so first we must note that the next model may need no events between.
// we know there is a next model
Model next =modelIterator.next();
//next.initSelectionData();// just cheaking
if (currentEvent == null || currentEvent.getEventTime() < currentModel.getStartTime()) {
next.getSelectionData().setFrequencyToEnd(state);
currentModel =next;
return;
}
while (currentEvent != null && currentEvent.getEventTime() == currentModel.getStartTime()) {
currentEvent.processEventSelection(currentModel.getSelectionData(), next.getSelectionData(), state);
if (eventIterator.hasNext()) {
currentEvent =eventIterator.next();
} else {
currentEvent =null;
}
}
// now apply the state.
next.getSelectionData().setFrequencyToEnd(state);
currentModel =next;
}
public boolean hasNextModel() {
return modelIterator.hasNext();
}
public Model getCurrentModel() {
return currentModel;
}
public ModelEvent getCurrentEvent() {
return currentEvent;
}
}
public SampleConfiguration getSampleConfiguration() {
return sampleConfig;
}
public void setSampleConfiguration(SampleConfiguration sampleConfiguration) {
this.sampleConfig =sampleConfiguration;
}
public double[] getLociConfiguration() {
return lociConfiguration;
}
public void setLociConfiguration(double[] lociConfiguration) {
this.lociConfiguration =lociConfiguration;
}
public int getSegSiteCount() {
return segSiteCount;
}
public void setSegSiteCount(int segSiteCount) {
this.segSiteCount =segSiteCount;
}
public FrequencyCondition getTimedCondition() {
return timedCondition;
}
public void setTimedCondition(FrequencyCondition timedCondition) {
this.timedCondition =timedCondition;
// System.out.println("TimedCondtions:"+this.timedCondition);
}
public SelectionSimulator getSelectionSimulator() {
return selectionSimulator;
}
public void setSelectionSimulator(SelectionSimulator selectionSimulator) {
this.selectionSimulator =selectionSimulator;
}
public ForwardStatsCollector getForwardTraceOutput() {
return forwardTraceOutput;
}
public void setForwardTraceOutput(ForwardStatsCollector forwardTraceOutput) {
this.forwardTraceOutput =forwardTraceOutput;
}
public void setSelection(boolean selection) {
this.selection =selection;
}
public RestartCondition getRestartCondtion() {
return restartCondtion;
}
public void setRestartCondtion(RestartCondition restartCondtion) {
this.restartCondtion =restartCondtion;
}
public void setFoldMutations(boolean foldMutations) {
this.foldMutations=foldMutations;
}
public boolean isFoldMutations() {
return foldMutations;
}
public boolean isUnphase() {
return unphase;
}
public void setUnphase(boolean unphase) {
this.unphase = unphase;
}
}
| true | true | public double simulateSelection(){
//System.err.println("MH simulation called:"+selection);
if(!selection)
return 0;
if (N == Integer.MAX_VALUE || N==Long.MAX_VALUE)//not correct...its a note for me
throw new RuntimeException("Must use the -N option with selection");
//System.err.println("Do i have any events that we give a crap about?:"+events);
// first lets clear volitoles
Iterator<ModelEvent> iterator =events.iterator();
while (iterator.hasNext()) {
ModelEvent me =iterator.next();
if (me.isVolatileSelectionEvent())
iterator.remove();
}
//init simulator
List<ModelEvent> moreEvents=getSelectionSimulator().init(this);//more FIXME we just don't have the class design right here
events.addAll(moreEvents);
Collections.sort(events);
//System.out.println(events);
//System.err.println("more evets?:"+events);
//we find the start and keep calling till we are either at the last model, or
// we hit a start selection event. then all all the new selection events...
Iterator<ModelEvent> eventIterator=events.descendingIterator();
Iterator<Model> modelIterator=models.descendingIterator();
ModelEvent startEvent=eventIterator.next();
while(!(startEvent instanceof SelectionEndTimeEvent || startEvent instanceof SelectionTimeConditionEvent) && eventIterator.hasNext()){
startEvent=eventIterator.next();
}
//System.err.println("StartEvent:"+startEvent);
//if(!(startEvent instanceof SelectionEndTimeEvent)){
// throw new RuntimeException("No Selection \"end\"!");
//}
//get to the right model... ie the first model with start time < event time.
Model model=modelIterator.next();
while(model.getStartTime()>startEvent.getEventTime() && modelIterator.hasNext()){
model=modelIterator.next();
}
if(startEvent instanceof SelectionEndTimeEvent && modelIterator.hasNext() && model.getStartTime()>=startEvent.getEventTime()){//note the =
model=modelIterator.next();
}
//System.err.println("FirstModel:"+model+"\t"+startEvent+"\t"+model.getStartTime());
//note that we have the model at and *above* the SelectionTimeConditionEvent
//now we go down the models as required with "boundry" events and the posiblity of intermediate
//events --however intermediate events do not require boundry checks.
double lastSweepTime=-1;
FrequencyState fstate=new FrequencyState(this.getMaxDemeCount(), model.getDemeCount());
//so the current "start" event
model.initSelectionData();
//System.err.println("SSim:"+model);
if(startEvent instanceof SelectionEndTimeEvent){
FrequencyState init=((SelectionEndTimeEvent)startEvent).getInitalFrequencys();
model.getSelectionData().setFrequencyToEnd(init);
}
List<ModelEvent> newEvents=model.getSelectionData().runSelectionSimulation();// side effect, uses selection simulator thats inited.
lastSweepTime=model.getSelectionData().getSweepTime();
while(modelIterator.hasNext()){
//in fact first we see if we should have stoped.
if(containtsForwardSimStopEvent(newEvents)){
break;
}
//first we find the next model
Model nextModel=modelIterator.next();
nextModel.initSelectionData();
//now we move the events to the relevent boundry... note we don't do anything with
//events that are intermediate in a model. This is because these events are for the
// coalsescent part... you can't "copy" state within a model pass... so events that
//need to do this must already be processed.
while(startEvent.getEventTime()!=nextModel.getStartTime() && eventIterator.hasNext()){
startEvent=eventIterator.next();
if(startEvent instanceof SelectionStartEvent)
break;//don't need to break to a label, since the remaining whiles will fall through to the instanceof test again
}
//now apply events. but should make sure they are not "stop" events
model.getSelectionData().getFrequencysFromStart(fstate);
while(startEvent.getEventTime()==nextModel.getStartTime() && !(startEvent instanceof SelectionStartEvent)){
startEvent.processEventSelection(model.getSelectionData(), nextModel.getSelectionData(), fstate);
if(eventIterator.hasNext()){
startEvent=eventIterator.next();
}else{
break;
}
}
//we need to consider the case where there are a bunch models between here and this "startEvent"
if(startEvent instanceof SelectionStartEvent && startEvent.getEventTime()>=nextModel.getEndTime()){
break;
}
//we are gold... we simulate the next model.
//System.out.println("SSim:"+nextModel);
SelectionData data=nextModel.getSelectionData();
data.setFrequencyToEnd(fstate);
List<ModelEvent> reallyNewEvents=data.runSelectionSimulation();
newEvents.addAll(reallyNewEvents);
lastSweepTime=data.getSweepTime();
model=nextModel;
}
events.addAll(newEvents);
Collections.sort(events);
//System.out.println(lastSweepTime);
return lastSweepTime;
}
| public double simulateSelection(){
//System.err.println("MH simulation called:"+selection);
if(!selection)
return 0;
if (N == Integer.MAX_VALUE || N==Long.MAX_VALUE)//not correct...its a note for me
throw new RuntimeException("Must use the -N option with selection");
//System.err.println("Do i have any events that we give a crap about?:"+events);
// first lets clear volitoles
Iterator<ModelEvent> iterator =events.iterator();
while (iterator.hasNext()) {
ModelEvent me =iterator.next();
if (me.isVolatileSelectionEvent())
iterator.remove();
}
//init simulator
List<ModelEvent> moreEvents=getSelectionSimulator().init(this);//more FIXME we just don't have the class design right here
events.addAll(moreEvents);
Collections.sort(events);
//System.out.println(events);
//System.err.println("more evets?:"+events);
//we find the start and keep calling till we are either at the last model, or
// we hit a start selection event. then all all the new selection events...
Iterator<ModelEvent> eventIterator=events.descendingIterator();
Iterator<Model> modelIterator=models.descendingIterator();
ModelEvent startEvent=eventIterator.next();
while(!(startEvent instanceof SelectionEndTimeEvent || startEvent instanceof SelectionTimeConditionEvent) && eventIterator.hasNext()){
startEvent=eventIterator.next();
}
//System.err.println("StartEvent:"+startEvent);
//if(!(startEvent instanceof SelectionEndTimeEvent)){
// throw new RuntimeException("No Selection \"end\"!");
//}
//get to the right model... ie the first model with start time < event time.
Model model=modelIterator.next();
while(model.getStartTime()>startEvent.getEventTime() && modelIterator.hasNext()){
model=modelIterator.next();
}
if(startEvent instanceof SelectionEndTimeEvent && modelIterator.hasNext() && model.getStartTime()>=startEvent.getEventTime()){//note the =
model=modelIterator.next();
}
//System.err.println("FirstModel:"+model+"\t"+startEvent+"\t"+model.getStartTime());
//note that we have the model at and *above* the SelectionTimeConditionEvent
//now we go down the models as required with "boundry" events and the posiblity of intermediate
//events --however intermediate events do not require boundry checks.
double lastSweepTime=-1;
FrequencyState fstate=new FrequencyState(this.getMaxDemeCount(), model.getDemeCount());
//so the current "start" event
model.initSelectionData();
//System.err.println("SSim:"+model);
if(startEvent instanceof SelectionEndTimeEvent){
FrequencyState init=((SelectionEndTimeEvent)startEvent).getInitalFrequencys();
model.getSelectionData().setFrequencyToEnd(init);
}
List<ModelEvent> newEvents=model.getSelectionData().runSelectionSimulation();// side effect, uses selection simulator thats inited.
lastSweepTime=model.getSelectionData().getSweepTime();
while(modelIterator.hasNext()){
//in fact first we see if we should have stoped.
if(containtsForwardSimStopEvent(newEvents)){
break;
}
//first we find the next model
Model nextModel=modelIterator.next();
nextModel.initSelectionData();
//now we move the events to the relevent boundry... note we don't do anything with
//events that are intermediate in a model. This is because these events are for the
// coalsescent part... you can't "copy" state within a model pass... so events that
//need to do this must already be processed.
while(startEvent.getEventTime()!=nextModel.getStartTime() && eventIterator.hasNext()){
startEvent=eventIterator.next();
if(startEvent instanceof SelectionStartEvent)
break;//don't need to break to a label, since the remaining whiles will fall through to the instanceof test again
}
//now apply events. but should make sure they are not "stop" events
model.getSelectionData().getFrequencysFromStart(fstate);
while(startEvent.getEventTime()==nextModel.getStartTime() && !(startEvent instanceof SelectionStartEvent)){
startEvent.processEventSelection(model.getSelectionData(), nextModel.getSelectionData(), fstate);
if(eventIterator.hasNext()){
startEvent=eventIterator.next();
}else{
break;
}
}
//we need to consider the case where there are a bunch models between here and this "startEvent"
if(startEvent instanceof SelectionStartEvent && startEvent.getEventTime()>=nextModel.getEndTime()){
break;
}
//we are gold... we simulate the next model.
//System.out.println("SSim:"+nextModel);
SelectionData data=nextModel.getSelectionData();
data.setFrequencyToEnd(fstate);
List<ModelEvent> reallyNewEvents=data.runSelectionSimulation();
newEvents.addAll(reallyNewEvents);
lastSweepTime=data.getSweepTime();
model=nextModel;
}
System.out.println("newand Old:"+newEvents+"\n\t"+events);
events.addAll(newEvents);
Collections.sort(events);
//System.out.println(lastSweepTime);
return lastSweepTime;
}
|
diff --git a/TODO_Example_Xtext2/tests/org.eclipse.xtext.todo.ui.tests/src/org/xtext/example/mydsl/XtextTodoTest.java b/TODO_Example_Xtext2/tests/org.eclipse.xtext.todo.ui.tests/src/org/xtext/example/mydsl/XtextTodoTest.java
index d06f566..2744969 100644
--- a/TODO_Example_Xtext2/tests/org.eclipse.xtext.todo.ui.tests/src/org/xtext/example/mydsl/XtextTodoTest.java
+++ b/TODO_Example_Xtext2/tests/org.eclipse.xtext.todo.ui.tests/src/org/xtext/example/mydsl/XtextTodoTest.java
@@ -1,44 +1,45 @@
package org.xtext.example.mydsl;
import org.eclipse.core.resources.IMarker;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEclipseEditor;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.waits.Conditions;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xtext.example.mydsl.testutils.AbstractUITest;
@RunWith(SWTBotJunit4ClassRunner.class)
public class XtextTodoTest extends AbstractUITest {
final String projectName = "Test";
@Test
public void testCreateSimpleDsl() {
String sourceFolder = "model";
String dslFile = "test.mydsl";
+ getBot().perspectiveByLabel("Java").activate();
createNewProject();
selectFolderNode(getProjectName()).select();
createFolder(getProjectName(), sourceFolder);
createFirstXtextFile(getProjectName(), sourceFolder, dslFile);
SWTBotEclipseEditor dslEditor = getBot().activeEditor().toTextEditor();
dslEditor.setText("// TODO change name!\nHello Joerg!");
dslEditor.save();
openView("Tasks", "General");
SWTBotView view = getBot().viewById("org.eclipse.ui.views.TaskList");
view.show();
SWTBotTree tree = getBot().tree();
getBot().waitUntil(Conditions.treeHasRows(tree, 1));
// TODO assert TODO Highlighting
// TODO assert Marker Existence
// TODO assert Marker Hyper Linking
}
@Override
protected String getProjectName() {
return projectName;
}
}
| true | true | public void testCreateSimpleDsl() {
String sourceFolder = "model";
String dslFile = "test.mydsl";
createNewProject();
selectFolderNode(getProjectName()).select();
createFolder(getProjectName(), sourceFolder);
createFirstXtextFile(getProjectName(), sourceFolder, dslFile);
SWTBotEclipseEditor dslEditor = getBot().activeEditor().toTextEditor();
dslEditor.setText("// TODO change name!\nHello Joerg!");
dslEditor.save();
openView("Tasks", "General");
SWTBotView view = getBot().viewById("org.eclipse.ui.views.TaskList");
view.show();
SWTBotTree tree = getBot().tree();
getBot().waitUntil(Conditions.treeHasRows(tree, 1));
// TODO assert TODO Highlighting
// TODO assert Marker Existence
// TODO assert Marker Hyper Linking
}
| public void testCreateSimpleDsl() {
String sourceFolder = "model";
String dslFile = "test.mydsl";
getBot().perspectiveByLabel("Java").activate();
createNewProject();
selectFolderNode(getProjectName()).select();
createFolder(getProjectName(), sourceFolder);
createFirstXtextFile(getProjectName(), sourceFolder, dslFile);
SWTBotEclipseEditor dslEditor = getBot().activeEditor().toTextEditor();
dslEditor.setText("// TODO change name!\nHello Joerg!");
dslEditor.save();
openView("Tasks", "General");
SWTBotView view = getBot().viewById("org.eclipse.ui.views.TaskList");
view.show();
SWTBotTree tree = getBot().tree();
getBot().waitUntil(Conditions.treeHasRows(tree, 1));
// TODO assert TODO Highlighting
// TODO assert Marker Existence
// TODO assert Marker Hyper Linking
}
|
diff --git a/src/main/java/edu/ohsu/sonmezsysbio/cloudbreak/mapper/SingleEndAlignmentsToReadPairInfoMapper.java b/src/main/java/edu/ohsu/sonmezsysbio/cloudbreak/mapper/SingleEndAlignmentsToReadPairInfoMapper.java
index f3c4543..6af0e84 100644
--- a/src/main/java/edu/ohsu/sonmezsysbio/cloudbreak/mapper/SingleEndAlignmentsToReadPairInfoMapper.java
+++ b/src/main/java/edu/ohsu/sonmezsysbio/cloudbreak/mapper/SingleEndAlignmentsToReadPairInfoMapper.java
@@ -1,394 +1,394 @@
package edu.ohsu.sonmezsysbio.cloudbreak.mapper;
import edu.ohsu.sonmezsysbio.cloudbreak.*;
import edu.ohsu.sonmezsysbio.cloudbreak.file.BigWigFileHelper;
import edu.ohsu.sonmezsysbio.cloudbreak.file.FaidxFileHelper;
import edu.ohsu.sonmezsysbio.cloudbreak.file.GFFFileHelper;
import edu.ohsu.sonmezsysbio.cloudbreak.io.AlignmentRecordFilter;
import edu.ohsu.sonmezsysbio.cloudbreak.io.GenomicLocation;
import edu.ohsu.sonmezsysbio.cloudbreak.io.GenomicLocationWithQuality;
import edu.ohsu.sonmezsysbio.cloudbreak.io.ReadPairInfo;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: cwhelan
* Date: 4/6/12
* Time: 1:03 PM
*/
public class SingleEndAlignmentsToReadPairInfoMapper extends SingleEndAlignmentsMapper
implements Mapper<Text, Text, GenomicLocationWithQuality, ReadPairInfo>, AlignmentRecordFilter {
private static org.apache.log4j.Logger logger = Logger.getLogger(SingleEndAlignmentsToReadPairInfoMapper.class);
{ logger.setLevel(Level.INFO); }
private PairedAlignmentScorer scorer;
private String faidxFileName;
FaidxFileHelper faix;
// for debugging, restrict output to a particular region
private String chromosomeFilter;
private Long startFilter;
private Long endFilter;
private GFFFileHelper exclusionRegions;
private BigWigFileHelper mapabilityWeighting;
private int minScore = -1;
private int maxMismatches = -1;
public int getMaxMismatches() {
return maxMismatches;
}
public void setMaxMismatches(int maxMismatches) {
this.maxMismatches = maxMismatches;
}
public int getMinScore() {
return minScore;
}
public void setMinScore(int minScore) {
this.minScore = minScore;
}
public FaidxFileHelper getFaix() {
return faix;
}
public void setFaix(FaidxFileHelper faix) {
this.faix = faix;
}
public String getChromosomeFilter() {
return chromosomeFilter;
}
public void setChromosomeFilter(String chromosomeFilter) {
this.chromosomeFilter = chromosomeFilter;
}
public Long getStartFilter() {
return startFilter;
}
public void setStartFilter(Long startFilter) {
this.startFilter = startFilter;
}
public Long getEndFilter() {
return endFilter;
}
public void setEndFilter(Long endFilter) {
this.endFilter = endFilter;
}
public Integer getMaxInsertSize() {
return maxInsertSize;
}
public void setMaxInsertSize(Integer maxInsertSize) {
this.maxInsertSize = maxInsertSize;
}
public PairedAlignmentScorer getScorer() {
return scorer;
}
public void setScorer(PairedAlignmentScorer scorer) {
this.scorer = scorer;
}
public GFFFileHelper getExclusionRegions() {
return exclusionRegions;
}
public void setExclusionRegions(GFFFileHelper exclusionRegions) {
this.exclusionRegions = exclusionRegions;
}
public void map(Text key, Text value, OutputCollector<GenomicLocationWithQuality, ReadPairInfo> output, Reporter reporter) throws IOException {
String line = value.toString();
ReadPairAlignments readPairAlignments = alignmentReader.parsePairAlignmentLine(line, this);
// ignoring OEA for now
if (readPairAlignments.getRead1Alignments().size() == 0 || readPairAlignments.getRead2Alignments().size() == 0) {
return;
}
Set<AlignmentRecord> recordsInExcludedAreas = new HashSet<AlignmentRecord>();
try {
if (exclusionRegions != null) {
for (AlignmentRecord record : readPairAlignments.getRead1Alignments()) {
if (exclusionRegions.doesLocationOverlap(record.getChromosomeName(), record.getPosition(), record.getPosition() + record.getSequenceLength())) {
logger.debug("excluding record " + record);
recordsInExcludedAreas.add(record);
}
}
for (AlignmentRecord record : readPairAlignments.getRead2Alignments()) {
if (exclusionRegions.doesLocationOverlap(record.getChromosomeName(), record.getPosition(), record.getPosition() + record.getSequenceLength())) {
logger.debug("excluding record " + record);
recordsInExcludedAreas.add(record);
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
try {
Map<GenomicLocation, ReadPairInfo> bestScoresForGL = emitReadPairInfoForAllPairs(readPairAlignments, output, recordsInExcludedAreas);
for (GenomicLocation genomicLocation : bestScoresForGL.keySet()) {
ReadPairInfo bestRpi = bestScoresForGL.get(genomicLocation);
GenomicLocationWithQuality genomicLocationWithQuality =
new GenomicLocationWithQuality(genomicLocation.chromosome, genomicLocation.pos, bestRpi.pMappingCorrect);
output.collect(genomicLocationWithQuality, bestRpi);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private Map<GenomicLocation, ReadPairInfo> emitReadPairInfoForAllPairs(ReadPairAlignments readPairAlignments,
OutputCollector<GenomicLocationWithQuality, ReadPairInfo> output,
Set<AlignmentRecord> recordsInExcludedAreas) throws Exception {
Map<GenomicLocation, ReadPairInfo> bestScoresForGL = new HashMap<GenomicLocation, ReadPairInfo>();
if (!emitConcordantAlignmentIfFound(readPairAlignments, output, bestScoresForGL)) {
for (String chrom : readPairAlignments.getRead1AlignmentsByChromosome().keySet()) {
if (! readPairAlignments.getRead2AlignmentsByChromosome().containsKey(chrom))
continue;
if (getChromosomeFilter() != null && ! chrom.equals(getChromosomeFilter()))
continue;
for (AlignmentRecord record1 : readPairAlignments.getRead1AlignmentsByChromosome().get(chrom)) {
if (getMinScore() != -1) {
if (record1.getAlignmentScore() < getMinScore()) {
continue;
}
}
for (AlignmentRecord record2 : readPairAlignments.getRead2AlignmentsByChromosome().get(chrom)) {
if (getMinScore() != -1) {
if (record2.getAlignmentScore() < getMinScore()) {
continue;
}
}
if (recordsInExcludedAreas.contains(record1) || recordsInExcludedAreas.contains(record2)) continue;
emitReadPairInfoForPair(record1, record2, readPairAlignments, output, bestScoresForGL);
}
}
}
}
return bestScoresForGL;
}
private boolean emitConcordantAlignmentIfFound(ReadPairAlignments readPairAlignments,
OutputCollector<GenomicLocationWithQuality, ReadPairInfo> output,
Map<GenomicLocation, ReadPairInfo> bestScoresForGL) throws IOException {
boolean foundConcordant = false;
for (String chrom : readPairAlignments.getRead1AlignmentsByChromosome().keySet()) {
if (getChromosomeFilter() != null && ! chrom.equals(getChromosomeFilter()))
continue;
if (! readPairAlignments.getRead2AlignmentsByChromosome().containsKey(chrom))
continue;
for (AlignmentRecord record1 : readPairAlignments.getRead1AlignmentsByChromosome().get(chrom)) {
for (AlignmentRecord record2 : readPairAlignments.getRead2AlignmentsByChromosome().get(chrom)) {
if (!scorer.validateMappingOrientations(record1, record2, isMatePairs())) continue;
AlignmentRecord leftRead = record1.getPosition() < record2.getPosition() ?
record1 : record2;
AlignmentRecord rightRead = record1.getPosition() < record2.getPosition() ?
record2 : record1;
int insertSize = rightRead.getPosition() + rightRead.getSequenceLength() - leftRead.getPosition();
if (Math.abs(insertSize - getTargetIsize()) < 3 * getTargetIsizeSD()) {
emitReadPairInfoForPair(record1, record2, readPairAlignments, output, bestScoresForGL);
foundConcordant = true;
}
}
}
}
return foundConcordant;
}
private void emitReadPairInfoForPair(AlignmentRecord record1, AlignmentRecord record2, ReadPairAlignments readPairAlignments,
OutputCollector<GenomicLocationWithQuality, ReadPairInfo> output,
Map<GenomicLocation, ReadPairInfo> bestScoresForGL) throws IOException {
try {
// todo: not handling translocations for now
if (! record1.getChromosomeName().equals(record2.getChromosomeName())) {
if (logger.isDebugEnabled()) {
logger.debug("translocation: r1 = " + record1 + "; r2 = " + record2);
}
return;
}
if (getChromosomeFilter() != null) {
if (! record1.getChromosomeName().equals(getChromosomeFilter())) {
return;
}
}
int insertSize;
AlignmentRecord leftRead = record1.getPosition() < record2.getPosition() ?
record1 : record2;
AlignmentRecord rightRead = record1.getPosition() < record2.getPosition() ?
record2 : record1;
// todo: not handling inversions for now
if (!scorer.validateMappingOrientations(record1, record2, isMatePairs())) {
if (logger.isDebugEnabled()) {
logger.debug("failed mapping orientation check: r1 = " + record1 + "; r2 = " + record2 + ", matepair = " + isMatePairs());
}
return;
}
insertSize = rightRead.getPosition() + rightRead.getSequenceLength() - leftRead.getPosition();
if (! scorer.validateInsertSize(insertSize, record1.getReadId(), maxInsertSize)) {
return;
}
int leftReadEnd = leftRead.getPosition() + leftRead.getSequenceLength();
int genomeOffset = leftReadEnd - leftReadEnd % resolution;
int internalIsize = rightRead.getPosition() - leftReadEnd;
int genomicWindow = internalIsize +
leftReadEnd % resolution +
(resolution - rightRead.getPosition() % resolution);
double pMappingCorrect = alignmentReader.probabilityMappingIsCorrect(record1, record2, readPairAlignments);
if (mapabilityWeighting != null) {
if (insertSize > getTargetIsize() + 6 * getTargetIsizeSD()) {
String chrom = record1.getChromosomeName();
int leftReadStart = leftRead.getPosition();
double leftReadMapability = mapabilityWeighting.getMinValueForRegion(chrom, leftReadStart, leftReadEnd);
logger.debug("left read mapability from " + leftRead.getPosition() + " to " + leftReadEnd + " = " + leftReadMapability);
- int rightReadStart = rightRead.getPosition() - rightRead.getSequenceLength();
- int rightReadEnd = rightRead.getPosition();
+ int rightReadStart = rightRead.getPosition();
+ int rightReadEnd = rightRead.getPosition() + rightRead.getSequenceLength();
double rightReadMapability = mapabilityWeighting.getMinValueForRegion(chrom, rightReadStart, rightReadEnd);
logger.debug("right read mapability from " + (rightRead.getPosition() - rightRead.getSequenceLength()) + " to " + rightRead.getPosition() + " = " + rightReadMapability);
logger.debug("old pmc: " + pMappingCorrect);
pMappingCorrect = pMappingCorrect + Math.log(leftReadMapability) + Math.log(rightReadMapability);
logger.debug("new pmc: " + pMappingCorrect);
}
}
ReadPairInfo readPairInfo = new ReadPairInfo(insertSize, pMappingCorrect, getReadGroupId());
for (int i = 0; i <= genomicWindow; i += resolution) {
Short chromosome = faix.getKeyForChromName(record1.getChromosomeName());
if (chromosome == null) {
throw new RuntimeException("Bad chromosome in record: " + record1.getChromosomeName());
}
int pos = genomeOffset + i;
if (getChromosomeFilter() != null) {
if (! record1.getChromosomeName().equals(getChromosomeFilter()) ||
pos < getStartFilter() || pos > getEndFilter()) {
continue;
}
}
logger.debug("Emitting insert size " + insertSize);
GenomicLocationWithQuality genomicLocationWithQuality = new GenomicLocationWithQuality(chromosome, pos, readPairInfo.pMappingCorrect);
GenomicLocation genomicLocation = new GenomicLocation(genomicLocationWithQuality.chromosome, genomicLocationWithQuality.pos);
if (bestScoresForGL.containsKey(genomicLocation) && bestScoresForGL.get(genomicLocation).pMappingCorrect >= readPairInfo.pMappingCorrect) {
continue;
} else {
bestScoresForGL.put(genomicLocation, readPairInfo);
}
}
} catch (BadAlignmentRecordException e) {
logger.error(e);
logger.error("skipping bad record pair: "+ record1 + ", " + record2);
}
}
public void configure(JobConf job) {
super.configure(job);
configureReadGroups(job);
scorer = new ProbabilisticPairedAlignmentScorer();
faidxFileName = job.get("alignment.faidx");
faix = new FaidxFileHelper(faidxFileName);
if (job.get("alignments.filterchr") != null) {
setChromosomeFilter(job.get("alignments.filterchr"));
setStartFilter(Long.parseLong(job.get("alignments.filterstart")));
setEndFilter(Long.parseLong(job.get("alignments.filterend")));
logger.debug("Configured filter");
}
if (job.get("alignment.exclusionRegions") != null) {
String exclusionRegionsFileName = job.get("alignment.exclusionRegions");
try {
exclusionRegions = new GFFFileHelper(exclusionRegionsFileName);
} catch (IOException e) {
e.printStackTrace();
}
logger.debug("configured exclusion regions with " + exclusionRegionsFileName);
}
if (job.get("alignment.mapabilityWeighting") != null) {
String mapabilityWeightingFileName = job.get("alignment.mapabilityWeighting");
mapabilityWeighting = new BigWigFileHelper();
try {
mapabilityWeighting.open(mapabilityWeightingFileName);
} catch (IOException e) {
e.printStackTrace();
}
logger.debug("configured mapability with " + mapabilityWeightingFileName);
}
if (job.get("pileupDeletionScore.maxInsertSize") != null) {
maxInsertSize = Integer.parseInt(job.get("pileupDeletionScore.maxInsertSize"));
logger.debug("configured max insert to " + maxInsertSize);
}
minScore = Integer.parseInt(job.get("pileupDeletionScore.minScore"));
maxMismatches = Integer.parseInt(job.get("pileupDeletionScore.maxMismatches"));
logger.debug("done with configuration");
}
public boolean passes(AlignmentRecord record) {
if (maxMismatches != -1 && getAlignerName().equals(Cloudbreak.ALIGNER_GENERIC_SAM)) {
return ((SAMRecord) record).getMismatches() < maxMismatches;
}
return true;
}
}
| true | true | private void emitReadPairInfoForPair(AlignmentRecord record1, AlignmentRecord record2, ReadPairAlignments readPairAlignments,
OutputCollector<GenomicLocationWithQuality, ReadPairInfo> output,
Map<GenomicLocation, ReadPairInfo> bestScoresForGL) throws IOException {
try {
// todo: not handling translocations for now
if (! record1.getChromosomeName().equals(record2.getChromosomeName())) {
if (logger.isDebugEnabled()) {
logger.debug("translocation: r1 = " + record1 + "; r2 = " + record2);
}
return;
}
if (getChromosomeFilter() != null) {
if (! record1.getChromosomeName().equals(getChromosomeFilter())) {
return;
}
}
int insertSize;
AlignmentRecord leftRead = record1.getPosition() < record2.getPosition() ?
record1 : record2;
AlignmentRecord rightRead = record1.getPosition() < record2.getPosition() ?
record2 : record1;
// todo: not handling inversions for now
if (!scorer.validateMappingOrientations(record1, record2, isMatePairs())) {
if (logger.isDebugEnabled()) {
logger.debug("failed mapping orientation check: r1 = " + record1 + "; r2 = " + record2 + ", matepair = " + isMatePairs());
}
return;
}
insertSize = rightRead.getPosition() + rightRead.getSequenceLength() - leftRead.getPosition();
if (! scorer.validateInsertSize(insertSize, record1.getReadId(), maxInsertSize)) {
return;
}
int leftReadEnd = leftRead.getPosition() + leftRead.getSequenceLength();
int genomeOffset = leftReadEnd - leftReadEnd % resolution;
int internalIsize = rightRead.getPosition() - leftReadEnd;
int genomicWindow = internalIsize +
leftReadEnd % resolution +
(resolution - rightRead.getPosition() % resolution);
double pMappingCorrect = alignmentReader.probabilityMappingIsCorrect(record1, record2, readPairAlignments);
if (mapabilityWeighting != null) {
if (insertSize > getTargetIsize() + 6 * getTargetIsizeSD()) {
String chrom = record1.getChromosomeName();
int leftReadStart = leftRead.getPosition();
double leftReadMapability = mapabilityWeighting.getMinValueForRegion(chrom, leftReadStart, leftReadEnd);
logger.debug("left read mapability from " + leftRead.getPosition() + " to " + leftReadEnd + " = " + leftReadMapability);
int rightReadStart = rightRead.getPosition() - rightRead.getSequenceLength();
int rightReadEnd = rightRead.getPosition();
double rightReadMapability = mapabilityWeighting.getMinValueForRegion(chrom, rightReadStart, rightReadEnd);
logger.debug("right read mapability from " + (rightRead.getPosition() - rightRead.getSequenceLength()) + " to " + rightRead.getPosition() + " = " + rightReadMapability);
logger.debug("old pmc: " + pMappingCorrect);
pMappingCorrect = pMappingCorrect + Math.log(leftReadMapability) + Math.log(rightReadMapability);
logger.debug("new pmc: " + pMappingCorrect);
}
}
ReadPairInfo readPairInfo = new ReadPairInfo(insertSize, pMappingCorrect, getReadGroupId());
for (int i = 0; i <= genomicWindow; i += resolution) {
Short chromosome = faix.getKeyForChromName(record1.getChromosomeName());
if (chromosome == null) {
throw new RuntimeException("Bad chromosome in record: " + record1.getChromosomeName());
}
int pos = genomeOffset + i;
if (getChromosomeFilter() != null) {
if (! record1.getChromosomeName().equals(getChromosomeFilter()) ||
pos < getStartFilter() || pos > getEndFilter()) {
continue;
}
}
logger.debug("Emitting insert size " + insertSize);
GenomicLocationWithQuality genomicLocationWithQuality = new GenomicLocationWithQuality(chromosome, pos, readPairInfo.pMappingCorrect);
GenomicLocation genomicLocation = new GenomicLocation(genomicLocationWithQuality.chromosome, genomicLocationWithQuality.pos);
if (bestScoresForGL.containsKey(genomicLocation) && bestScoresForGL.get(genomicLocation).pMappingCorrect >= readPairInfo.pMappingCorrect) {
continue;
} else {
bestScoresForGL.put(genomicLocation, readPairInfo);
}
}
} catch (BadAlignmentRecordException e) {
logger.error(e);
logger.error("skipping bad record pair: "+ record1 + ", " + record2);
}
}
| private void emitReadPairInfoForPair(AlignmentRecord record1, AlignmentRecord record2, ReadPairAlignments readPairAlignments,
OutputCollector<GenomicLocationWithQuality, ReadPairInfo> output,
Map<GenomicLocation, ReadPairInfo> bestScoresForGL) throws IOException {
try {
// todo: not handling translocations for now
if (! record1.getChromosomeName().equals(record2.getChromosomeName())) {
if (logger.isDebugEnabled()) {
logger.debug("translocation: r1 = " + record1 + "; r2 = " + record2);
}
return;
}
if (getChromosomeFilter() != null) {
if (! record1.getChromosomeName().equals(getChromosomeFilter())) {
return;
}
}
int insertSize;
AlignmentRecord leftRead = record1.getPosition() < record2.getPosition() ?
record1 : record2;
AlignmentRecord rightRead = record1.getPosition() < record2.getPosition() ?
record2 : record1;
// todo: not handling inversions for now
if (!scorer.validateMappingOrientations(record1, record2, isMatePairs())) {
if (logger.isDebugEnabled()) {
logger.debug("failed mapping orientation check: r1 = " + record1 + "; r2 = " + record2 + ", matepair = " + isMatePairs());
}
return;
}
insertSize = rightRead.getPosition() + rightRead.getSequenceLength() - leftRead.getPosition();
if (! scorer.validateInsertSize(insertSize, record1.getReadId(), maxInsertSize)) {
return;
}
int leftReadEnd = leftRead.getPosition() + leftRead.getSequenceLength();
int genomeOffset = leftReadEnd - leftReadEnd % resolution;
int internalIsize = rightRead.getPosition() - leftReadEnd;
int genomicWindow = internalIsize +
leftReadEnd % resolution +
(resolution - rightRead.getPosition() % resolution);
double pMappingCorrect = alignmentReader.probabilityMappingIsCorrect(record1, record2, readPairAlignments);
if (mapabilityWeighting != null) {
if (insertSize > getTargetIsize() + 6 * getTargetIsizeSD()) {
String chrom = record1.getChromosomeName();
int leftReadStart = leftRead.getPosition();
double leftReadMapability = mapabilityWeighting.getMinValueForRegion(chrom, leftReadStart, leftReadEnd);
logger.debug("left read mapability from " + leftRead.getPosition() + " to " + leftReadEnd + " = " + leftReadMapability);
int rightReadStart = rightRead.getPosition();
int rightReadEnd = rightRead.getPosition() + rightRead.getSequenceLength();
double rightReadMapability = mapabilityWeighting.getMinValueForRegion(chrom, rightReadStart, rightReadEnd);
logger.debug("right read mapability from " + (rightRead.getPosition() - rightRead.getSequenceLength()) + " to " + rightRead.getPosition() + " = " + rightReadMapability);
logger.debug("old pmc: " + pMappingCorrect);
pMappingCorrect = pMappingCorrect + Math.log(leftReadMapability) + Math.log(rightReadMapability);
logger.debug("new pmc: " + pMappingCorrect);
}
}
ReadPairInfo readPairInfo = new ReadPairInfo(insertSize, pMappingCorrect, getReadGroupId());
for (int i = 0; i <= genomicWindow; i += resolution) {
Short chromosome = faix.getKeyForChromName(record1.getChromosomeName());
if (chromosome == null) {
throw new RuntimeException("Bad chromosome in record: " + record1.getChromosomeName());
}
int pos = genomeOffset + i;
if (getChromosomeFilter() != null) {
if (! record1.getChromosomeName().equals(getChromosomeFilter()) ||
pos < getStartFilter() || pos > getEndFilter()) {
continue;
}
}
logger.debug("Emitting insert size " + insertSize);
GenomicLocationWithQuality genomicLocationWithQuality = new GenomicLocationWithQuality(chromosome, pos, readPairInfo.pMappingCorrect);
GenomicLocation genomicLocation = new GenomicLocation(genomicLocationWithQuality.chromosome, genomicLocationWithQuality.pos);
if (bestScoresForGL.containsKey(genomicLocation) && bestScoresForGL.get(genomicLocation).pMappingCorrect >= readPairInfo.pMappingCorrect) {
continue;
} else {
bestScoresForGL.put(genomicLocation, readPairInfo);
}
}
} catch (BadAlignmentRecordException e) {
logger.error(e);
logger.error("skipping bad record pair: "+ record1 + ", " + record2);
}
}
|
diff --git a/src/me/neatmonster/spacertk/SpaceRTK.java b/src/me/neatmonster/spacertk/SpaceRTK.java
index 12d2618..c67cd57 100644
--- a/src/me/neatmonster/spacertk/SpaceRTK.java
+++ b/src/me/neatmonster/spacertk/SpaceRTK.java
@@ -1,158 +1,158 @@
/*
* This file is part of SpaceRTK (http://spacebukkit.xereo.net/).
*
* SpaceRTK is free software: you can redistribute it and/or modify it under the terms of the
* Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative
* Common organization, either version 3.0 of the license, or (at your option) any later version.
*
* SpaceRTK 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
* Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license for more details.
*
* You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA)
* license along with this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>.
*/
package me.neatmonster.spacertk;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Handler;
import java.util.logging.Logger;
import com.drdanick.rtoolkit.EventDispatcher;
import com.drdanick.rtoolkit.event.ToolkitEventPriority;
import me.neatmonster.spacemodule.SpaceModule;
import me.neatmonster.spacemodule.api.ActionsManager;
import me.neatmonster.spacertk.actions.FileActions;
import me.neatmonster.spacertk.actions.PluginActions;
import me.neatmonster.spacertk.actions.SchedulerActions;
import me.neatmonster.spacertk.actions.ServerActions;
import me.neatmonster.spacertk.event.BackupEvent;
import me.neatmonster.spacertk.plugins.PluginsManager;
import me.neatmonster.spacertk.scheduler.Scheduler;
import me.neatmonster.spacertk.utilities.BackupManager;
import me.neatmonster.spacertk.utilities.Format;
import org.bukkit.configuration.file.YamlConfiguration;
/**
* Main class of SpaceRTK
*/
public class SpaceRTK {
private static SpaceRTK spaceRTK;
/**
* Gets the RTK Instance
* @return RTK Instance
*/
public static SpaceRTK getInstance() {
return spaceRTK;
}
public ActionsManager actionsManager;
public PanelListener panelListener;
public PluginsManager pluginsManager;
public String type = null;
public int port;
public int rPort;
public String salt;
public File worldContainer;
public String backupDirName;
public boolean backupLogs;
private BackupManager backupManager;
private PingListener pingListener;
public static final File baseDir = new File(System.getProperty("user.dir"));
/**
* Creates a new RTK
*/
public SpaceRTK() {
try {
final Logger rootlog = Logger.getLogger("");
for (final Handler h : rootlog.getHandlers())
h.setFormatter(new Format());
EventDispatcher edt = SpaceModule.getInstance().getEdt();
edt.registerListener(new BackupListener(), SpaceModule.getInstance().getEventHandler(), ToolkitEventPriority.SYSTEM, BackupEvent.class);
} catch (final Exception e) {
e.printStackTrace();
}
}
/**
* Called when the RTK is disabled
*/
public void onDisable() {
try {
panelListener.stopServer();
pingListener.shutdown();
} catch (final Exception e) {
e.printStackTrace();
}
}
/**
* Called when the RTK is enabled
*/
public void onEnable() {
spaceRTK = this;
final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION);
- type = configuration.getString("SpaceModule.Type", "Bukkit");
- configuration.set("SpaceModule.Type", type = "Bukkit");
- salt = configuration.getString("General.Salt", "<default>");
+ type = configuration.getString("SpaceModule.type", "Bukkit");
+ configuration.set("SpaceModule.type", type = "Bukkit");
+ salt = configuration.getString("General.salt", "<default>");
if (salt.equals("<default>")) {
salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
- configuration.set("General.Salt", salt);
+ configuration.set("General.salt", salt);
}
- worldContainer = new File(configuration.getString("General.WorldContainer", "."));
+ worldContainer = new File(configuration.getString("General.worldContainer", "."));
if (type.equals("Bukkit"))
- port = configuration.getInt("SpaceBukkit.Port", 2011);
- rPort = configuration.getInt("SpaceRTK.Port", 2012);
- backupDirName = configuration.getString("General.BackupDirectory", "Backups");
- backupLogs = configuration.getBoolean("General.BackupLogs", true);
+ port = configuration.getInt("SpaceBukkit.port", 2011);
+ rPort = configuration.getInt("SpaceRTK.port", 2012);
+ backupDirName = configuration.getString("General.backupDirectory", "Backups");
+ backupLogs = configuration.getBoolean("General.backupLogs", true);
try {
configuration.save(SpaceModule.CONFIGURATION);
} catch (IOException e) {
e.printStackTrace();
}
if(backupManager == null)
backupManager = BackupManager.getInstance();
try {
pingListener = new PingListener();
pingListener.startup();
} catch (IOException e) {
e.printStackTrace();
}
File backupDir = new File(SpaceRTK.getInstance().worldContainer.getPath() + File.separator + SpaceRTK.getInstance().backupDirName);
for(File f : baseDir.listFiles()) {
if(f.isDirectory()) {
if(f.getName().equalsIgnoreCase(backupDirName) && !f.getName().equals(backupDirName)) {
f.renameTo(backupDir);
}
}
}
pluginsManager = new PluginsManager();
actionsManager = new ActionsManager();
actionsManager.register(FileActions.class);
actionsManager.register(PluginActions.class);
actionsManager.register(SchedulerActions.class);
actionsManager.register(ServerActions.class);
panelListener = new PanelListener();
Scheduler.loadJobs();
}
/**
* Gets the Backup Manager
* @return Backup Manager
*/
public BackupManager getBackupManager() {
return backupManager;
}
}
| false | true | public void onEnable() {
spaceRTK = this;
final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION);
type = configuration.getString("SpaceModule.Type", "Bukkit");
configuration.set("SpaceModule.Type", type = "Bukkit");
salt = configuration.getString("General.Salt", "<default>");
if (salt.equals("<default>")) {
salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
configuration.set("General.Salt", salt);
}
worldContainer = new File(configuration.getString("General.WorldContainer", "."));
if (type.equals("Bukkit"))
port = configuration.getInt("SpaceBukkit.Port", 2011);
rPort = configuration.getInt("SpaceRTK.Port", 2012);
backupDirName = configuration.getString("General.BackupDirectory", "Backups");
backupLogs = configuration.getBoolean("General.BackupLogs", true);
try {
configuration.save(SpaceModule.CONFIGURATION);
} catch (IOException e) {
e.printStackTrace();
}
if(backupManager == null)
backupManager = BackupManager.getInstance();
try {
pingListener = new PingListener();
pingListener.startup();
} catch (IOException e) {
e.printStackTrace();
}
File backupDir = new File(SpaceRTK.getInstance().worldContainer.getPath() + File.separator + SpaceRTK.getInstance().backupDirName);
for(File f : baseDir.listFiles()) {
if(f.isDirectory()) {
if(f.getName().equalsIgnoreCase(backupDirName) && !f.getName().equals(backupDirName)) {
f.renameTo(backupDir);
}
}
}
pluginsManager = new PluginsManager();
actionsManager = new ActionsManager();
actionsManager.register(FileActions.class);
actionsManager.register(PluginActions.class);
actionsManager.register(SchedulerActions.class);
actionsManager.register(ServerActions.class);
panelListener = new PanelListener();
Scheduler.loadJobs();
}
| public void onEnable() {
spaceRTK = this;
final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION);
type = configuration.getString("SpaceModule.type", "Bukkit");
configuration.set("SpaceModule.type", type = "Bukkit");
salt = configuration.getString("General.salt", "<default>");
if (salt.equals("<default>")) {
salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
configuration.set("General.salt", salt);
}
worldContainer = new File(configuration.getString("General.worldContainer", "."));
if (type.equals("Bukkit"))
port = configuration.getInt("SpaceBukkit.port", 2011);
rPort = configuration.getInt("SpaceRTK.port", 2012);
backupDirName = configuration.getString("General.backupDirectory", "Backups");
backupLogs = configuration.getBoolean("General.backupLogs", true);
try {
configuration.save(SpaceModule.CONFIGURATION);
} catch (IOException e) {
e.printStackTrace();
}
if(backupManager == null)
backupManager = BackupManager.getInstance();
try {
pingListener = new PingListener();
pingListener.startup();
} catch (IOException e) {
e.printStackTrace();
}
File backupDir = new File(SpaceRTK.getInstance().worldContainer.getPath() + File.separator + SpaceRTK.getInstance().backupDirName);
for(File f : baseDir.listFiles()) {
if(f.isDirectory()) {
if(f.getName().equalsIgnoreCase(backupDirName) && !f.getName().equals(backupDirName)) {
f.renameTo(backupDir);
}
}
}
pluginsManager = new PluginsManager();
actionsManager = new ActionsManager();
actionsManager.register(FileActions.class);
actionsManager.register(PluginActions.class);
actionsManager.register(SchedulerActions.class);
actionsManager.register(ServerActions.class);
panelListener = new PanelListener();
Scheduler.loadJobs();
}
|
diff --git a/src/org/pixmob/freemobile/netstat/DatabaseCleanup.java b/src/org/pixmob/freemobile/netstat/DatabaseCleanup.java
index cf5e7000..ff3f32c6 100644
--- a/src/org/pixmob/freemobile/netstat/DatabaseCleanup.java
+++ b/src/org/pixmob/freemobile/netstat/DatabaseCleanup.java
@@ -1,79 +1,79 @@
/*
* Copyright (C) 2012 Pixmob (http://github.com/pixmob)
*
* 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.pixmob.freemobile.netstat;
import static org.pixmob.freemobile.netstat.Constants.TAG;
import java.util.Calendar;
import org.pixmob.freemobile.netstat.content.NetstatContract.Events;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Process;
import android.util.Log;
/**
* This broadcast receiver removes old data from the database.
* @author Pixmob
*/
public class DatabaseCleanup extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// The database cleanup is done in a background thread so that the main
// thread is not blocked.
new DatabaseCleanupTask(context.getApplicationContext()).start();
}
/**
* Internal thread for executing database cleanup.
* @author Pixmob
*/
private static class DatabaseCleanupTask extends Thread {
private final Context context;
public DatabaseCleanupTask(final Context context) {
this.context = context;
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
cleanupDatabase();
} catch (Exception e) {
Log.e(TAG, "Failed to cleanup database", e);
}
}
private void cleanupDatabase() throws Exception {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Log.i(TAG, "Deleting events older than " + cal.getTime());
// Delete oldest events.
final long timestampLimit = cal.getTimeInMillis();
- final int deletedEvents = context.getContentResolver().update(
- Events.CONTENT_URI, null, Events.TIMESTAMP + "<?",
+ final int deletedEvents = context.getContentResolver().delete(
+ Events.CONTENT_URI, Events.TIMESTAMP + "<?",
new String[] { String.valueOf(timestampLimit) });
Log.i(TAG, deletedEvents + " events deleted");
}
}
}
| true | true | private void cleanupDatabase() throws Exception {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Log.i(TAG, "Deleting events older than " + cal.getTime());
// Delete oldest events.
final long timestampLimit = cal.getTimeInMillis();
final int deletedEvents = context.getContentResolver().update(
Events.CONTENT_URI, null, Events.TIMESTAMP + "<?",
new String[] { String.valueOf(timestampLimit) });
Log.i(TAG, deletedEvents + " events deleted");
}
| private void cleanupDatabase() throws Exception {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Log.i(TAG, "Deleting events older than " + cal.getTime());
// Delete oldest events.
final long timestampLimit = cal.getTimeInMillis();
final int deletedEvents = context.getContentResolver().delete(
Events.CONTENT_URI, Events.TIMESTAMP + "<?",
new String[] { String.valueOf(timestampLimit) });
Log.i(TAG, deletedEvents + " events deleted");
}
|
diff --git a/src/edu/uwm/cs552/HexEdge.java b/src/edu/uwm/cs552/HexEdge.java
index d95adce..41d50be 100644
--- a/src/edu/uwm/cs552/HexEdge.java
+++ b/src/edu/uwm/cs552/HexEdge.java
@@ -1,141 +1,142 @@
package edu.uwm.cs552;
import java.awt.Point;
import edu.uwm.cs552.util.Pair;
public class HexEdge {
private HexCoordinate coor;
private HexDirection dir;
public HexEdge(HexCoordinate h, HexDirection d) {
coor = h;
dir = d;
}
public double a() {
HexCoordinate h = coor.move(dir);
double hp = h.a();
double cp = coor.a();
return (hp + cp) / 2;
}
public double b() {
HexCoordinate h = coor.move(dir);
double hp = h.b();
double cp = coor.b();
return (hp + cp) / 2;
}
public static HexEdge fromString(String string) {
String[] s = string.split("@");
return new HexEdge(HexCoordinate.fromString(s[0]),
HexDirection.valueOf(s[1]));
}
public Pair<Point, Point> toLineSegment(double s) {
HexCoordinate h = coor.move(dir);
Point hp = h.toPoint(s);
Point cp = coor.toPoint(s);
Point mid = new Point((int) Math.round((hp.getX() + cp.getX()) / 2),
(int) Math.round((hp.getY() + cp.getY()) / 2));
Pair<Point, Point> p = new Pair<Point, Point>(new Point(mid.x,
(int) Math.round(mid.getY() + (s * SQRT32) / 3)), new Point(mid.x,
(int) Math.round(mid.getY() - (s * SQRT32) / 3)));
switch (dir) {
case NORTHEAST:
case SOUTHWEST:
p = rotateLineSegment(p, mid, -120);
+ p.fst = new Point(p.fst.x-1, p.fst.y-1); // Fix
break;
case EAST:
case WEST:
break;
case SOUTHEAST:
case NORTHWEST:
p = rotateLineSegment(p, mid, 120);
break;
}
return p;
}
public static HexEdge fromPoint(Point p, double scale) {
HexCoordinate on = HexCoordinate.fromPoint(p, scale);
double distance = Double.MAX_VALUE;
HexDirection direction = null;
for (HexDirection d : HexDirection.values()) {
Point n = on.move(d).toPoint(scale);
if (p.distance(n.x, n.y) < distance) {
distance = p.distance(n.x, n.y);
direction = d;
}
}
return new HexEdge(on, direction);
}
@Override
public String toString() {
return coor.toString() + "@" + dir.name();
}
public boolean equals(Object o) {
if (!(o instanceof HexEdge))
return false;
HexEdge h = (HexEdge) o;
HexCoordinate c1 = coor, c2 = h.coor;
HexDirection d1 = dir, d2 = h.dir;
if (dir == HexDirection.WEST || dir == HexDirection.SOUTHWEST
|| dir == HexDirection.NORTHWEST) {
c1 = c1.move(dir);
d1 = d1.reverse();
}
if (h.dir == HexDirection.WEST || h.dir == HexDirection.SOUTHWEST
|| h.dir == HexDirection.NORTHWEST) {
c2 = c2.move(h.dir);
d2 = d2.reverse();
}
return c1.equals(c2) && d1 == d2;
}
public int hashCode() {
HexDirection d = dir;
HexCoordinate c = coor;
if (dir == HexDirection.WEST || dir == HexDirection.SOUTHWEST
|| dir == HexDirection.NORTHWEST) {
c = c.move(dir);
d = d.reverse();
}
return c.hashCode() + (d.ordinal() * 1001);
}
private Pair<Point, Point> rotateLineSegment(Pair<Point, Point> points,
Point mid, double angle) {
angle = Math.toRadians(angle);
double sin = Math.sin(angle);
double cos = Math.cos(angle);
int nx1 = (int) Math.round(mid.x + (points.fst.x - mid.x) * cos
- (points.fst.y - mid.y) * sin);
int ny1 = (int) Math.round(mid.y + (points.fst.x - mid.x) * sin
- (points.fst.y - mid.y) * cos);
int nx2 = (int) Math.round(mid.x + (points.snd.x - mid.x) * cos
- (points.snd.y - mid.y) * sin);
int ny2 = (int) Math.round(mid.y + (points.snd.x - mid.x) * sin
- (points.snd.y - mid.y) * cos);
return new Pair<Point, Point>(new Point(nx1, ny1), new Point(nx2, ny2));
}
private static final double SQRT32 = Math.sqrt(3.0) / 2.0;
}
| true | true | public Pair<Point, Point> toLineSegment(double s) {
HexCoordinate h = coor.move(dir);
Point hp = h.toPoint(s);
Point cp = coor.toPoint(s);
Point mid = new Point((int) Math.round((hp.getX() + cp.getX()) / 2),
(int) Math.round((hp.getY() + cp.getY()) / 2));
Pair<Point, Point> p = new Pair<Point, Point>(new Point(mid.x,
(int) Math.round(mid.getY() + (s * SQRT32) / 3)), new Point(mid.x,
(int) Math.round(mid.getY() - (s * SQRT32) / 3)));
switch (dir) {
case NORTHEAST:
case SOUTHWEST:
p = rotateLineSegment(p, mid, -120);
break;
case EAST:
case WEST:
break;
case SOUTHEAST:
case NORTHWEST:
p = rotateLineSegment(p, mid, 120);
break;
}
return p;
}
| public Pair<Point, Point> toLineSegment(double s) {
HexCoordinate h = coor.move(dir);
Point hp = h.toPoint(s);
Point cp = coor.toPoint(s);
Point mid = new Point((int) Math.round((hp.getX() + cp.getX()) / 2),
(int) Math.round((hp.getY() + cp.getY()) / 2));
Pair<Point, Point> p = new Pair<Point, Point>(new Point(mid.x,
(int) Math.round(mid.getY() + (s * SQRT32) / 3)), new Point(mid.x,
(int) Math.round(mid.getY() - (s * SQRT32) / 3)));
switch (dir) {
case NORTHEAST:
case SOUTHWEST:
p = rotateLineSegment(p, mid, -120);
p.fst = new Point(p.fst.x-1, p.fst.y-1); // Fix
break;
case EAST:
case WEST:
break;
case SOUTHEAST:
case NORTHWEST:
p = rotateLineSegment(p, mid, 120);
break;
}
return p;
}
|
diff --git a/pmd/src/net/sourceforge/pmd/rules/basic/BigIntegerInstantiation.java b/pmd/src/net/sourceforge/pmd/rules/basic/BigIntegerInstantiation.java
index 1ab554a50..463d981a6 100644
--- a/pmd/src/net/sourceforge/pmd/rules/basic/BigIntegerInstantiation.java
+++ b/pmd/src/net/sourceforge/pmd/rules/basic/BigIntegerInstantiation.java
@@ -1,50 +1,53 @@
package net.sourceforge.pmd.rules.basic;
import net.sourceforge.pmd.AbstractRule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.SourceType;
import net.sourceforge.pmd.ast.ASTAllocationExpression;
import net.sourceforge.pmd.ast.ASTArguments;
import net.sourceforge.pmd.ast.ASTArrayDimsAndInits;
import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.ast.ASTLiteral;
import net.sourceforge.pmd.ast.Node;
public class BigIntegerInstantiation extends AbstractRule {
public Object visit(ASTAllocationExpression node, Object data) {
Node type = node.jjtGetChild(0);
if (!(type instanceof ASTClassOrInterfaceType)) {
return super.visit(node, data);
}
String img = ((ASTClassOrInterfaceType) type).getImage();
if (img.startsWith("java.math.")) {
img = img.substring(10);
}
boolean jdk15 = ((RuleContext) data).getSourceType().compareTo(SourceType.JAVA_15) >= 0;
if (("BigInteger".equals(img) || (jdk15 && "BigDecimal".equals(img))) &&
(node.getFirstChildOfType(ASTArrayDimsAndInits.class) == null)
) {
ASTArguments args = (ASTArguments) node.getFirstChildOfType(ASTArguments.class);
if (args.getArgumentCount() == 1) {
ASTLiteral literal = (ASTLiteral) node.getFirstChildOfType(ASTLiteral.class);
+ if (literal == null || literal.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() != args) {
+ return super.visit(node, data);
+ }
img = literal.getImage();
if ((img.length() > 2 && img.charAt(0) == '"')) {
img = img.substring(1, img.length() - 1);
}
if ("0".equals(img) || "1".equals(img) || (jdk15 && "10".equals(img))) {
addViolation(data, node);
return data;
}
}
}
return super.visit(node, data);
}
}
| true | true | public Object visit(ASTAllocationExpression node, Object data) {
Node type = node.jjtGetChild(0);
if (!(type instanceof ASTClassOrInterfaceType)) {
return super.visit(node, data);
}
String img = ((ASTClassOrInterfaceType) type).getImage();
if (img.startsWith("java.math.")) {
img = img.substring(10);
}
boolean jdk15 = ((RuleContext) data).getSourceType().compareTo(SourceType.JAVA_15) >= 0;
if (("BigInteger".equals(img) || (jdk15 && "BigDecimal".equals(img))) &&
(node.getFirstChildOfType(ASTArrayDimsAndInits.class) == null)
) {
ASTArguments args = (ASTArguments) node.getFirstChildOfType(ASTArguments.class);
if (args.getArgumentCount() == 1) {
ASTLiteral literal = (ASTLiteral) node.getFirstChildOfType(ASTLiteral.class);
img = literal.getImage();
if ((img.length() > 2 && img.charAt(0) == '"')) {
img = img.substring(1, img.length() - 1);
}
if ("0".equals(img) || "1".equals(img) || (jdk15 && "10".equals(img))) {
addViolation(data, node);
return data;
}
}
}
return super.visit(node, data);
}
| public Object visit(ASTAllocationExpression node, Object data) {
Node type = node.jjtGetChild(0);
if (!(type instanceof ASTClassOrInterfaceType)) {
return super.visit(node, data);
}
String img = ((ASTClassOrInterfaceType) type).getImage();
if (img.startsWith("java.math.")) {
img = img.substring(10);
}
boolean jdk15 = ((RuleContext) data).getSourceType().compareTo(SourceType.JAVA_15) >= 0;
if (("BigInteger".equals(img) || (jdk15 && "BigDecimal".equals(img))) &&
(node.getFirstChildOfType(ASTArrayDimsAndInits.class) == null)
) {
ASTArguments args = (ASTArguments) node.getFirstChildOfType(ASTArguments.class);
if (args.getArgumentCount() == 1) {
ASTLiteral literal = (ASTLiteral) node.getFirstChildOfType(ASTLiteral.class);
if (literal == null || literal.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() != args) {
return super.visit(node, data);
}
img = literal.getImage();
if ((img.length() > 2 && img.charAt(0) == '"')) {
img = img.substring(1, img.length() - 1);
}
if ("0".equals(img) || "1".equals(img) || (jdk15 && "10".equals(img))) {
addViolation(data, node);
return data;
}
}
}
return super.visit(node, data);
}
|
diff --git a/Dashboard/src/dashboard/servlet/RegistrationServlet.java b/Dashboard/src/dashboard/servlet/RegistrationServlet.java
index 5a87503..a4ff5ff 100644
--- a/Dashboard/src/dashboard/servlet/RegistrationServlet.java
+++ b/Dashboard/src/dashboard/servlet/RegistrationServlet.java
@@ -1,43 +1,43 @@
package dashboard.servlet;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dashboard.error.*;
import dashboard.registry.StudentRegistry;
import dashboard.model.Student;
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = -5081331444892620046L;
/**
* Called when a user is trying to register
* @param req
* @param resp
* @throws IOException
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String email = req.getParameter("mail");
String firstName = req.getParameter("firstname");
String lastName = req.getParameter("lastname");
String password = req.getParameter("password");
try{
StudentRegistry.addUser(new Student(firstName,lastName,username,email,password));//add the user to the list of existing users
resp.sendRedirect("/login.jsp?msg=Registration succes!");
} catch (UserNameInUseException e){
- resp.sendRedirect("/error.jsp");
+ resp.sendRedirect("/error.jsp?msg=username is already in use!");
} catch (InvalidUserNameException e){
- resp.sendRedirect("/error.jsp");
+ resp.sendRedirect("/error.jsp?msg=username is not valid!");
} catch (EmailInUseException e){
- resp.sendRedirect("/error.jsp");
+ resp.sendRedirect("/error.jsp?msg=Email is already in use!");
} catch (InvalidEmailException e){
- resp.sendRedirect("/error.jsp");
+ resp.sendRedirect("/error.jsp?msg=email is not valid!");
} catch (InvalidPasswordException e){
- resp.sendRedirect("/error.jsp");
+ resp.sendRedirect("/error.jsp?password is not valid!");
}
}
}
| false | true | public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String email = req.getParameter("mail");
String firstName = req.getParameter("firstname");
String lastName = req.getParameter("lastname");
String password = req.getParameter("password");
try{
StudentRegistry.addUser(new Student(firstName,lastName,username,email,password));//add the user to the list of existing users
resp.sendRedirect("/login.jsp?msg=Registration succes!");
} catch (UserNameInUseException e){
resp.sendRedirect("/error.jsp");
} catch (InvalidUserNameException e){
resp.sendRedirect("/error.jsp");
} catch (EmailInUseException e){
resp.sendRedirect("/error.jsp");
} catch (InvalidEmailException e){
resp.sendRedirect("/error.jsp");
} catch (InvalidPasswordException e){
resp.sendRedirect("/error.jsp");
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String email = req.getParameter("mail");
String firstName = req.getParameter("firstname");
String lastName = req.getParameter("lastname");
String password = req.getParameter("password");
try{
StudentRegistry.addUser(new Student(firstName,lastName,username,email,password));//add the user to the list of existing users
resp.sendRedirect("/login.jsp?msg=Registration succes!");
} catch (UserNameInUseException e){
resp.sendRedirect("/error.jsp?msg=username is already in use!");
} catch (InvalidUserNameException e){
resp.sendRedirect("/error.jsp?msg=username is not valid!");
} catch (EmailInUseException e){
resp.sendRedirect("/error.jsp?msg=Email is already in use!");
} catch (InvalidEmailException e){
resp.sendRedirect("/error.jsp?msg=email is not valid!");
} catch (InvalidPasswordException e){
resp.sendRedirect("/error.jsp?password is not valid!");
}
}
|
diff --git a/src/me/HariboPenguin/PermissionFinder/DumpCommand.java b/src/me/HariboPenguin/PermissionFinder/DumpCommand.java
index eee5e5b..805d421 100644
--- a/src/me/HariboPenguin/PermissionFinder/DumpCommand.java
+++ b/src/me/HariboPenguin/PermissionFinder/DumpCommand.java
@@ -1,81 +1,81 @@
package me.HariboPenguin.PermissionFinder;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
public class DumpCommand implements CommandExecutor {
public PermissionFinder plugin;
public DumpCommand(PermissionFinder instance) {
this.plugin = instance;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args) {
- if (args.length >= 1) {
+ if (args.length == 1) {
if (Bukkit.getPluginManager().getPlugin(args[0]) != null) {
Plugin enteredPlugin = Bukkit.getPluginManager().getPlugin(args[0]);
List permList = enteredPlugin.getDescription().getPermissions();
if (permList.isEmpty()) {
sender.sendMessage(plugin.prefix + ChatColor.RED + "No permission nodes were found for that plugin");
} else {
int listSize = permList.size();
int counter = 0;
plugin.getDataFolder().mkdir();
File dumpFile = new File(plugin.getDataFolder().getPath() + File.separatorChar + enteredPlugin.getName() + "-perms.txt");
try {
dumpFile.createNewFile();
BufferedWriter dumpOut = new BufferedWriter(new FileWriter(dumpFile));
dumpOut.write("---------- Permission nodes for " + enteredPlugin.getName() + " ----------");
while (counter < listSize) {
Permission permissionNode = (Permission) permList.get(counter);
if (args.length == 1) {
dumpOut.newLine();
dumpOut.write(permissionNode.getName() + " - " + permissionNode.getDescription());
counter++;
}
}
dumpOut.close();
sender.sendMessage(plugin.prefix + ChatColor.GREEN + "Permission nodes successfully dumped to: " + dumpFile.getPath());
} catch (IOException ex) {
Logger.getLogger(DumpCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
sender.sendMessage(plugin.prefix + ChatColor.RED + "Plugin is not enabled!");
}
} else {
sender.sendMessage(plugin.prefix + ChatColor.RED + "Command usage is: /dumpperms [Plugin]");
}
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args) {
if (args.length >= 1) {
if (Bukkit.getPluginManager().getPlugin(args[0]) != null) {
Plugin enteredPlugin = Bukkit.getPluginManager().getPlugin(args[0]);
List permList = enteredPlugin.getDescription().getPermissions();
if (permList.isEmpty()) {
sender.sendMessage(plugin.prefix + ChatColor.RED + "No permission nodes were found for that plugin");
} else {
int listSize = permList.size();
int counter = 0;
plugin.getDataFolder().mkdir();
File dumpFile = new File(plugin.getDataFolder().getPath() + File.separatorChar + enteredPlugin.getName() + "-perms.txt");
try {
dumpFile.createNewFile();
BufferedWriter dumpOut = new BufferedWriter(new FileWriter(dumpFile));
dumpOut.write("---------- Permission nodes for " + enteredPlugin.getName() + " ----------");
while (counter < listSize) {
Permission permissionNode = (Permission) permList.get(counter);
if (args.length == 1) {
dumpOut.newLine();
dumpOut.write(permissionNode.getName() + " - " + permissionNode.getDescription());
counter++;
}
}
dumpOut.close();
sender.sendMessage(plugin.prefix + ChatColor.GREEN + "Permission nodes successfully dumped to: " + dumpFile.getPath());
} catch (IOException ex) {
Logger.getLogger(DumpCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
sender.sendMessage(plugin.prefix + ChatColor.RED + "Plugin is not enabled!");
}
} else {
sender.sendMessage(plugin.prefix + ChatColor.RED + "Command usage is: /dumpperms [Plugin]");
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args) {
if (args.length == 1) {
if (Bukkit.getPluginManager().getPlugin(args[0]) != null) {
Plugin enteredPlugin = Bukkit.getPluginManager().getPlugin(args[0]);
List permList = enteredPlugin.getDescription().getPermissions();
if (permList.isEmpty()) {
sender.sendMessage(plugin.prefix + ChatColor.RED + "No permission nodes were found for that plugin");
} else {
int listSize = permList.size();
int counter = 0;
plugin.getDataFolder().mkdir();
File dumpFile = new File(plugin.getDataFolder().getPath() + File.separatorChar + enteredPlugin.getName() + "-perms.txt");
try {
dumpFile.createNewFile();
BufferedWriter dumpOut = new BufferedWriter(new FileWriter(dumpFile));
dumpOut.write("---------- Permission nodes for " + enteredPlugin.getName() + " ----------");
while (counter < listSize) {
Permission permissionNode = (Permission) permList.get(counter);
if (args.length == 1) {
dumpOut.newLine();
dumpOut.write(permissionNode.getName() + " - " + permissionNode.getDescription());
counter++;
}
}
dumpOut.close();
sender.sendMessage(plugin.prefix + ChatColor.GREEN + "Permission nodes successfully dumped to: " + dumpFile.getPath());
} catch (IOException ex) {
Logger.getLogger(DumpCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
sender.sendMessage(plugin.prefix + ChatColor.RED + "Plugin is not enabled!");
}
} else {
sender.sendMessage(plugin.prefix + ChatColor.RED + "Command usage is: /dumpperms [Plugin]");
}
return true;
}
|
diff --git a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Net/JacksonManager.java b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Net/JacksonManager.java
index 12528c2..18f83e3 100644
--- a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Net/JacksonManager.java
+++ b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Net/JacksonManager.java
@@ -1,55 +1,57 @@
package de.uni.stuttgart.informatik.ToureNPlaner.Net;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.smile.SmileFactory;
public class JacksonManager {
static ObjectMapper jsonMapper;
static ObjectMapper smileMapper;
public static ObjectMapper getJsonMapper() {
if (jsonMapper == null)
jsonMapper = new ObjectMapper(new JsonFactory());
return jsonMapper;
}
public static ObjectMapper getSmileMapper() {
if (smileMapper == null)
smileMapper = new ObjectMapper(new SmileFactory());
return smileMapper;
}
public static ObjectMapper getMapper(ContentType type) {
switch (type) {
case SMILE:
return getSmileMapper();
case JSON:
default:
return getJsonMapper();
}
}
public enum ContentType {
JSON("application/json"), SMILE("application/x-jackson-smile");
public final String identifier;
private ContentType(String s) {
identifier = s;
}
public static ContentType parse(String header) {
+ if (header == null)
+ throw new IllegalArgumentException("No Content-Type Header.");
String[] s = header.split(";");
if (s.length < 0)
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Wrong Content-Type Header. Was: \"" + header + "\".");
for (ContentType t : ContentType.values()) {
if (s[0].toLowerCase().equals(t.identifier))
return t;
}
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Wrong Content-Type Header. Was: \"" + header + "\".");
}
}
}
| false | true | public static ContentType parse(String header) {
String[] s = header.split(";");
if (s.length < 0)
throw new IllegalArgumentException();
for (ContentType t : ContentType.values()) {
if (s[0].toLowerCase().equals(t.identifier))
return t;
}
throw new IllegalArgumentException();
}
| public static ContentType parse(String header) {
if (header == null)
throw new IllegalArgumentException("No Content-Type Header.");
String[] s = header.split(";");
if (s.length < 0)
throw new IllegalArgumentException("Wrong Content-Type Header. Was: \"" + header + "\".");
for (ContentType t : ContentType.values()) {
if (s[0].toLowerCase().equals(t.identifier))
return t;
}
throw new IllegalArgumentException("Wrong Content-Type Header. Was: \"" + header + "\".");
}
|
diff --git a/src/main/java/local/radioschedulers/ScheduleSpace.java b/src/main/java/local/radioschedulers/ScheduleSpace.java
index 6258eb2..8acc86a 100644
--- a/src/main/java/local/radioschedulers/ScheduleSpace.java
+++ b/src/main/java/local/radioschedulers/ScheduleSpace.java
@@ -1,97 +1,97 @@
package local.radioschedulers;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
/**
* A schedule space is a timeline that, for each time slot, defines a list of
* JobCombinations that could be executed.
*
* @author Johannes Buchner
*/
public class ScheduleSpace implements Iterable<Entry<LSTTime, Set<JobCombination>>> {
public static final int LST_SLOTS_MINUTES = 15;
public static final int LST_SLOTS_PER_DAY = 60 * 24 / LST_SLOTS_MINUTES;
private Map<LSTTime, Set<JobCombination>> schedule = new TreeMap<LSTTime, Set<JobCombination>>();
private void createIfNeeded(LSTTime t) {
if (!schedule.containsKey(t)) {
schedule.put(t, new HashSet<JobCombination>());
}
}
public void clear(LSTTime t) {
schedule.remove(t);
}
public void add(LSTTime t, JobCombination jc) {
createIfNeeded(t);
schedule.get(t).add(jc);
}
public boolean isEmpty(LSTTime t) {
if (schedule.containsKey(t))
return schedule.get(t).isEmpty();
else
return true;
}
public Set<JobCombination> get(LSTTime t) {
createIfNeeded(t);
return schedule.get(t);
}
public LSTTime findLastEntry() {
return Collections.max(schedule.keySet());
}
public Map<LSTTime, Set<JobCombination>> getSchedule() {
return schedule;
}
public void setSchedule(Map<LSTTime, Set<JobCombination>> schedule) {
this.schedule = schedule;
}
@Override
public Iterator<Entry<LSTTime, Set<JobCombination>>> iterator() {
return new Iterator<Entry<LSTTime, Set<JobCombination>>>() {
LSTTime t = new LSTTime(0L, 0L);
LSTTime lastEntry = findLastEntry();
@Override
public boolean hasNext() {
- if (t.day <= lastEntry.day)
+ if (t.compareTo(lastEntry) <= 0)
return true;
else
return false;
}
@Override
public Entry<LSTTime, Set<JobCombination>> next() {
Set<JobCombination> jc = get(new LSTTime(t.day, t.minute));
Entry<LSTTime, Set<JobCombination>> entry = new SimpleEntry<LSTTime, Set<JobCombination>>(
new LSTTime(t.day, t.minute), jc);
t.minute += LST_SLOTS_MINUTES;
if (t.minute >= 24 * 60) {
t.day++;
t.minute = 0L;
}
return entry;
}
@Override
public void remove() {
throw new Error("Not implemented.");
}
};
}
}
| true | true | public Iterator<Entry<LSTTime, Set<JobCombination>>> iterator() {
return new Iterator<Entry<LSTTime, Set<JobCombination>>>() {
LSTTime t = new LSTTime(0L, 0L);
LSTTime lastEntry = findLastEntry();
@Override
public boolean hasNext() {
if (t.day <= lastEntry.day)
return true;
else
return false;
}
@Override
public Entry<LSTTime, Set<JobCombination>> next() {
Set<JobCombination> jc = get(new LSTTime(t.day, t.minute));
Entry<LSTTime, Set<JobCombination>> entry = new SimpleEntry<LSTTime, Set<JobCombination>>(
new LSTTime(t.day, t.minute), jc);
t.minute += LST_SLOTS_MINUTES;
if (t.minute >= 24 * 60) {
t.day++;
t.minute = 0L;
}
return entry;
}
@Override
public void remove() {
throw new Error("Not implemented.");
}
};
}
| public Iterator<Entry<LSTTime, Set<JobCombination>>> iterator() {
return new Iterator<Entry<LSTTime, Set<JobCombination>>>() {
LSTTime t = new LSTTime(0L, 0L);
LSTTime lastEntry = findLastEntry();
@Override
public boolean hasNext() {
if (t.compareTo(lastEntry) <= 0)
return true;
else
return false;
}
@Override
public Entry<LSTTime, Set<JobCombination>> next() {
Set<JobCombination> jc = get(new LSTTime(t.day, t.minute));
Entry<LSTTime, Set<JobCombination>> entry = new SimpleEntry<LSTTime, Set<JobCombination>>(
new LSTTime(t.day, t.minute), jc);
t.minute += LST_SLOTS_MINUTES;
if (t.minute >= 24 * 60) {
t.day++;
t.minute = 0L;
}
return entry;
}
@Override
public void remove() {
throw new Error("Not implemented.");
}
};
}
|
diff --git a/src/org/objectweb/proactive/core/descriptor/xml/ProActiveDescriptorHandler.java b/src/org/objectweb/proactive/core/descriptor/xml/ProActiveDescriptorHandler.java
index 5c6be76c1..35e47dba0 100644
--- a/src/org/objectweb/proactive/core/descriptor/xml/ProActiveDescriptorHandler.java
+++ b/src/org/objectweb/proactive/core/descriptor/xml/ProActiveDescriptorHandler.java
@@ -1,475 +1,475 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2006 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.descriptor.xml;
import java.net.URL;
import java.util.Enumeration;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptorImpl;
import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl;
import org.objectweb.proactive.core.xml.VariableContract;
import org.objectweb.proactive.core.xml.handler.AbstractUnmarshallerDecorator;
import org.objectweb.proactive.core.xml.handler.BasicUnmarshaller;
import org.objectweb.proactive.core.xml.handler.PassiveCompositeUnmarshaller;
import org.objectweb.proactive.core.xml.handler.UnmarshallerHandler;
import org.objectweb.proactive.core.xml.io.Attributes;
import org.objectweb.proactive.core.xml.io.SAXParserErrorHandlerTerminating;
import org.objectweb.proactive.scheduler.Scheduler;
/**
* This class receives deployment events
*
* @author ProActive Team
* @version 1.0, 2002/09/20
* @since ProActive 0.9.3
*/
public class ProActiveDescriptorHandler extends AbstractUnmarshallerDecorator
implements ProActiveDescriptorConstants {
protected ProActiveDescriptor proActiveDescriptor;
private Scheduler scheduler;
private String jobID;
//
// -- CONSTRUCTORS -----------------------------------------------
//
public ProActiveDescriptorHandler(String xmlDescriptorUrl,
VariableContract variableContract) {
super(false);
proActiveDescriptor = new ProActiveDescriptorImpl(xmlDescriptorUrl);
// keep a reference of the variable contract for future use
proActiveDescriptor.setVariableContract(variableContract);
addHandler(MAIN_DEFINITION_TAG, new MainDefinitionHandler(
proActiveDescriptor));
addHandler(DEPLOYMENT_TAG, new DeploymentHandler(proActiveDescriptor));
addHandler(INFRASTRUCTURE_TAG, new InfrastructureHandler(
proActiveDescriptor));
addHandler(FILE_TRANSFER_DEFINITIONS_TAG,
new FileTransferDefinitionsHandler(proActiveDescriptor));
addHandler(TECHNICAL_SERVICES_TAG, new TechnicalServicesHandler(
proActiveDescriptor));
addHandler(SECURITY_TAG, new SecurityHandler(proActiveDescriptor));
{
PassiveCompositeUnmarshaller compDefHandler = new PassiveCompositeUnmarshaller();
PassiveCompositeUnmarshaller vNodesDefHandler = new PassiveCompositeUnmarshaller();
PassiveCompositeUnmarshaller vNodesAcqHandler = new PassiveCompositeUnmarshaller();
vNodesDefHandler.addHandler(VIRTUAL_NODE_TAG,
new VirtualNodeHandler(proActiveDescriptor));
vNodesAcqHandler.addHandler(VIRTUAL_NODE_TAG,
new VirtualNodeLookupHandler());
compDefHandler.addHandler(VIRTUAL_NODES_DEFINITION_TAG,
vNodesDefHandler);
compDefHandler.addHandler(VIRTUAL_NODES_ACQUISITION_TAG,
vNodesAcqHandler);
this.addHandler(COMPONENT_DEFINITION_TAG, compDefHandler);
}
this.addHandler(VARIABLES_TAG, new VariablesHandler(variableContract));
}
public ProActiveDescriptorHandler(Scheduler scheduler, String jobId,
String xmlDescriptorUrl) {
super(false);
this.proActiveDescriptor = new ProActiveDescriptorImpl(xmlDescriptorUrl);
this.scheduler = scheduler;
this.jobID = jobId;
addHandler(MAIN_DEFINITION_TAG, new MainDefinitionHandler(scheduler,
jobId, this.proActiveDescriptor));
addHandler(INFRASTRUCTURE_TAG, new InfrastructureHandler(scheduler,
jobId, this.proActiveDescriptor));
addHandler(DEPLOYMENT_TAG, new DeploymentHandler(proActiveDescriptor,
false));
addHandler(FILE_TRANSFER_DEFINITIONS_TAG,
new FileTransferDefinitionsHandler(proActiveDescriptor));
addHandler(TECHNICAL_SERVICES_TAG, new TechnicalServicesHandler(
proActiveDescriptor));
addHandler(SECURITY_TAG, new SecurityHandler(proActiveDescriptor));
{
PassiveCompositeUnmarshaller compDefHandler = new PassiveCompositeUnmarshaller();
PassiveCompositeUnmarshaller vNodesDefHandler = new PassiveCompositeUnmarshaller();
PassiveCompositeUnmarshaller vNodesAcqHandler = new PassiveCompositeUnmarshaller();
vNodesDefHandler.addHandler(VIRTUAL_NODE_TAG,
new VirtualNodeHandler(proActiveDescriptor));
vNodesAcqHandler.addHandler(VIRTUAL_NODE_TAG,
new VirtualNodeLookupHandler());
compDefHandler.addHandler(VIRTUAL_NODES_DEFINITION_TAG,
vNodesDefHandler);
compDefHandler.addHandler(VIRTUAL_NODES_ACQUISITION_TAG,
vNodesAcqHandler);
this.addHandler(COMPONENT_DEFINITION_TAG, compDefHandler);
}
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
// public static void main(String[] args) throws java.io.IOException, org.xml.sax.SAXException {
// // String uri =
// // "Z:\\ProActive\\descriptors\\C3D_Dispatcher_Renderer.xml";
// String uri = "/user/cjarjouh/home/ProActive/descriptors/C3D_Dispatcher_Renderer.xml";
// InitialHandler h = new InitialHandler(uri, new VariableContract());
//
// // String uri =
// // "file:/net/home/rquilici/ProActive/descriptors/C3D_Dispatcher_Renderer.xml";
// org.objectweb.proactive.core.xml.io.StreamReader sr;
//
// if ("enable".equals(ProActiveConfiguration.getSchemaValidationState())) {
// sr = new org.objectweb.proactive.core.xml.io.StreamReader(
// new org.xml.sax.InputSource(uri), h, null,
// new SAXParserErrorHandlerTerminating());
// } else {
// sr = new org.objectweb.proactive.core.xml.io.StreamReader(
// new org.xml.sax.InputSource(uri), h);
// }
//
// sr.read();
// }
/**
* Creates ProActiveDescriptor object from XML Descriptor
*
* @param xmlDescriptorUrl
* the URL of XML Descriptor
*/
public static ProActiveDescriptorHandler createProActiveDescriptor(
String xmlDescriptorUrl, VariableContract variableContract)
throws java.io.IOException, org.xml.sax.SAXException {
// static method added to replace main method
InitialHandler h = new InitialHandler(xmlDescriptorUrl,
variableContract);
String uri = xmlDescriptorUrl;
// we get the schema from the class location
ClassLoader classLoader = ProActiveDescriptorHandler.class
.getClassLoader();
Enumeration<URL> schemaURLs = classLoader
.getResources("org/objectweb/proactive/core/descriptor/xml/DescriptorSchema.xsd");
// among the various descriptor schema that we may find, we will always
// favor the one that is in the jar file
URL schemaURLcandidate = null;
while (schemaURLs.hasMoreElements()) {
URL schemaURL = schemaURLs.nextElement();
if (schemaURL.getProtocol().equals("jar")) {
schemaURLcandidate = schemaURL;
} else if (schemaURLcandidate == null) {
schemaURLcandidate = schemaURL;
}
}
if (schemaURLcandidate == null) {
// In case the application is executed neither via the ant
// script, nor via the jar file, we need to find the schema
// manually
// we locate the proactive code
Enumeration<URL> classURLs = ProActiveDescriptorHandler.class
.getClassLoader().getResources(
"org/objectweb/proactive/core/descriptor/xml/");
// we make sure that we found a file structure (and not a jar)
URL classURLcandidate = null;
while (classURLs.hasMoreElements()) {
URL classURL = classURLs.nextElement();
if (classURL.getProtocol().equals("file")) {
classURLcandidate = classURL;
}
}
try {
if (classURLcandidate != null) {
java.net.URI uriSchema;
uriSchema = classURLcandidate.toURI();
// we navigate to the descriptor schema
uriSchema = uriSchema.resolve(".." + java.io.File.separator
+ ".." + java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + java.io.File.separator
+ "descriptors" + java.io.File.separator
+ "DescriptorSchema.xsd");
java.io.File test = new java.io.File(uriSchema);
// we make sure that we have found the right file
if (test.isFile()
&& test.getName().equals("DescriptorSchema.xsd")) {
schemaURLcandidate = uriSchema.toURL();
} else {
logger
.error("The Proactive.jar file doesn't contain the Descriptor Schema.");
schemaURLcandidate = null;
}
} else {
logger
.error("The descriptor schema could not be located in your environment.");
schemaURLcandidate = null;
}
} catch (Exception e) {
logger
.error("The descriptor schema could not be located in your environment.");
schemaURLcandidate = null;
}
}
- logger.debug("Using XML shema: " + schemaURLcandidate);
+ logger.debug("Using XML schema: " + schemaURLcandidate);
org.objectweb.proactive.core.xml.io.StreamReader sr = null;
if ("enable".equals(ProActiveConfiguration.getSchemaValidationState())) {
sr = new org.objectweb.proactive.core.xml.io.StreamReader(
new org.xml.sax.InputSource(uri), h, schemaURLcandidate,
new SAXParserErrorHandlerTerminating());
} else {
sr = new org.objectweb.proactive.core.xml.io.StreamReader(
new org.xml.sax.InputSource(uri), h);
}
sr.read();
return (ProActiveDescriptorHandler) h.getResultObject();
}
//
// -- implements XMLUnmarshaller
// ------------------------------------------------------
//
public Object getResultObject() throws org.xml.sax.SAXException {
// copy xmlproperties into the pad
// proActiveDescriptor.setVariableContract(XMLProperties.xmlproperties.duplicate());
// Release lock on static global variable XMLProperties
// XMLProperties.xmlproperties.clear();
// XMLProperties.xmlproperties.releaseLock();
return proActiveDescriptor;
}
public void startContextElement(String name, Attributes attributes)
throws org.xml.sax.SAXException {
}
//
// -- PROTECTED METHODS
// ------------------------------------------------------
//
protected void notifyEndActiveHandler(String name,
UnmarshallerHandler activeHandler) throws org.xml.sax.SAXException {
/*
* if(name.equals(VARIABLES_TAG)){ //Check XMLProperties Runtime
* if(!org.objectweb.proactive.core.xml.XMLProperties.xmlproperties.checkContract())
* throw new SAXException("Variable contract breached"); }
*/
}
//
// -- PRIVATE METHODS ------------------------------------------------------
//
//
// -- INNER CLASSES ------------------------------------------------------
//
/**
* Receives deployment events
*/
private static class InitialHandler extends AbstractUnmarshallerDecorator {
// line added to return a ProactiveDescriptorHandler object
private ProActiveDescriptorHandler proActiveDescriptorHandler;
private InitialHandler(String xmlDescriptorUrl,
VariableContract variableContract) {
super();
proActiveDescriptorHandler = new ProActiveDescriptorHandler(
xmlDescriptorUrl, variableContract);
this.addHandler(PROACTIVE_DESCRIPTOR_TAG,
proActiveDescriptorHandler);
}
public Object getResultObject() throws org.xml.sax.SAXException {
return proActiveDescriptorHandler;
}
public void startContextElement(String name, Attributes attributes)
throws org.xml.sax.SAXException {
}
protected void notifyEndActiveHandler(String name,
UnmarshallerHandler activeHandler)
throws org.xml.sax.SAXException {
}
}
/**
* This class receives virtualNode events
*/
private class VirtualNodeHandler extends BasicUnmarshaller {
private ProActiveDescriptor pad;
private VirtualNodeHandler(ProActiveDescriptor pad) {
this.pad = pad;
}
public void startContextElement(String name, Attributes attributes)
throws org.xml.sax.SAXException {
// create and register a VirtualNode
String vnName = attributes.getValue("name");
if (!checkNonEmpty(vnName)) {
throw new org.xml.sax.SAXException(
"VirtualNode defined without name");
}
// underneath, we know that it is a VirtualNodeImpl, since the
// bollean in the method is false
VirtualNodeImpl vn = (VirtualNodeImpl) proActiveDescriptor
.createVirtualNode(vnName, false);
// property
String property = attributes.getValue("property");
if (checkNonEmpty(property)) {
vn.setProperty(property);
}
String timeout = attributes.getValue("timeout");
String waitForTimeoutAsString = attributes
.getValue("waitForTimeout");
boolean waitForTimeout = false;
if (checkNonEmpty(waitForTimeoutAsString)) {
waitForTimeout = new Boolean(waitForTimeoutAsString)
.booleanValue();
}
if (checkNonEmpty(timeout)) {
vn.setTimeout(new Integer(timeout).longValue(), waitForTimeout);
}
String minNodeNumber = attributes.getValue("minNodeNumber");
if (checkNonEmpty(minNodeNumber)) {
vn.setMinNumberOfNodes((new Integer(minNodeNumber).intValue()));
}
String serviceId = attributes.getValue("ftServiceId");
if (checkNonEmpty(serviceId)) {
pad.registerService(vn, serviceId);
}
String fileTransferDeployName = attributes
.getValue(FILE_TRANSFER_DEPLOY_TAG);
if (checkNonEmpty(fileTransferDeployName)) {
vn.addFileTransferDeploy(pad
.getFileTransfer(fileTransferDeployName));
}
String fileTransferRetrieveName = attributes
.getValue(FILE_TRANSFER_RETRIEVE_TAG);
if (checkNonEmpty(fileTransferRetrieveName)) {
vn.addFileTransferRetrieve(pad
.getFileTransfer(fileTransferRetrieveName));
}
String technicalServiceId = attributes
.getValue(TECHNICAL_SERVICE_ID);
if (checkNonEmpty(technicalServiceId)) {
vn.addTechnicalService(pad
.getTechnicalService(technicalServiceId));
}
}
} // end inner class VirtualNodeHandler
/**
* This class receives virtualNode events
*/
private class VirtualNodeLookupHandler extends BasicUnmarshaller {
private VirtualNodeLookupHandler() {
}
public void startContextElement(String name, Attributes attributes)
throws org.xml.sax.SAXException {
// create and register a VirtualNode
String vnName = attributes.getValue("name");
if (!checkNonEmpty(vnName)) {
throw new org.xml.sax.SAXException(
"VirtualNode defined without name");
}
proActiveDescriptor.createVirtualNode(vnName, true);
}
} // end inner class VirtualNodeLookupHandler
// SECURITY
/**
* This class receives Security events
*/
private class SecurityHandler extends BasicUnmarshaller {
private ProActiveDescriptor proActiveDescriptor;
public SecurityHandler(ProActiveDescriptor proActiveDescriptor) {
super();
this.proActiveDescriptor = proActiveDescriptor;
}
public void startContextElement(String name, Attributes attributes)
throws org.xml.sax.SAXException {
// create and register a VirtualNode
String file = attributes.getValue("file");
if (!checkNonEmpty(file)) {
throw new org.xml.sax.SAXException("Empty security file");
}
logger.debug("creating ProActiveSecurityManager : " + file);
proActiveDescriptor.createProActiveSecurityManager(file);
}
}
// end inner class SecurityHandler
}
| true | true | public static ProActiveDescriptorHandler createProActiveDescriptor(
String xmlDescriptorUrl, VariableContract variableContract)
throws java.io.IOException, org.xml.sax.SAXException {
// static method added to replace main method
InitialHandler h = new InitialHandler(xmlDescriptorUrl,
variableContract);
String uri = xmlDescriptorUrl;
// we get the schema from the class location
ClassLoader classLoader = ProActiveDescriptorHandler.class
.getClassLoader();
Enumeration<URL> schemaURLs = classLoader
.getResources("org/objectweb/proactive/core/descriptor/xml/DescriptorSchema.xsd");
// among the various descriptor schema that we may find, we will always
// favor the one that is in the jar file
URL schemaURLcandidate = null;
while (schemaURLs.hasMoreElements()) {
URL schemaURL = schemaURLs.nextElement();
if (schemaURL.getProtocol().equals("jar")) {
schemaURLcandidate = schemaURL;
} else if (schemaURLcandidate == null) {
schemaURLcandidate = schemaURL;
}
}
if (schemaURLcandidate == null) {
// In case the application is executed neither via the ant
// script, nor via the jar file, we need to find the schema
// manually
// we locate the proactive code
Enumeration<URL> classURLs = ProActiveDescriptorHandler.class
.getClassLoader().getResources(
"org/objectweb/proactive/core/descriptor/xml/");
// we make sure that we found a file structure (and not a jar)
URL classURLcandidate = null;
while (classURLs.hasMoreElements()) {
URL classURL = classURLs.nextElement();
if (classURL.getProtocol().equals("file")) {
classURLcandidate = classURL;
}
}
try {
if (classURLcandidate != null) {
java.net.URI uriSchema;
uriSchema = classURLcandidate.toURI();
// we navigate to the descriptor schema
uriSchema = uriSchema.resolve(".." + java.io.File.separator
+ ".." + java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + java.io.File.separator
+ "descriptors" + java.io.File.separator
+ "DescriptorSchema.xsd");
java.io.File test = new java.io.File(uriSchema);
// we make sure that we have found the right file
if (test.isFile()
&& test.getName().equals("DescriptorSchema.xsd")) {
schemaURLcandidate = uriSchema.toURL();
} else {
logger
.error("The Proactive.jar file doesn't contain the Descriptor Schema.");
schemaURLcandidate = null;
}
} else {
logger
.error("The descriptor schema could not be located in your environment.");
schemaURLcandidate = null;
}
} catch (Exception e) {
logger
.error("The descriptor schema could not be located in your environment.");
schemaURLcandidate = null;
}
}
logger.debug("Using XML shema: " + schemaURLcandidate);
org.objectweb.proactive.core.xml.io.StreamReader sr = null;
if ("enable".equals(ProActiveConfiguration.getSchemaValidationState())) {
sr = new org.objectweb.proactive.core.xml.io.StreamReader(
new org.xml.sax.InputSource(uri), h, schemaURLcandidate,
new SAXParserErrorHandlerTerminating());
} else {
sr = new org.objectweb.proactive.core.xml.io.StreamReader(
new org.xml.sax.InputSource(uri), h);
}
sr.read();
return (ProActiveDescriptorHandler) h.getResultObject();
}
| public static ProActiveDescriptorHandler createProActiveDescriptor(
String xmlDescriptorUrl, VariableContract variableContract)
throws java.io.IOException, org.xml.sax.SAXException {
// static method added to replace main method
InitialHandler h = new InitialHandler(xmlDescriptorUrl,
variableContract);
String uri = xmlDescriptorUrl;
// we get the schema from the class location
ClassLoader classLoader = ProActiveDescriptorHandler.class
.getClassLoader();
Enumeration<URL> schemaURLs = classLoader
.getResources("org/objectweb/proactive/core/descriptor/xml/DescriptorSchema.xsd");
// among the various descriptor schema that we may find, we will always
// favor the one that is in the jar file
URL schemaURLcandidate = null;
while (schemaURLs.hasMoreElements()) {
URL schemaURL = schemaURLs.nextElement();
if (schemaURL.getProtocol().equals("jar")) {
schemaURLcandidate = schemaURL;
} else if (schemaURLcandidate == null) {
schemaURLcandidate = schemaURL;
}
}
if (schemaURLcandidate == null) {
// In case the application is executed neither via the ant
// script, nor via the jar file, we need to find the schema
// manually
// we locate the proactive code
Enumeration<URL> classURLs = ProActiveDescriptorHandler.class
.getClassLoader().getResources(
"org/objectweb/proactive/core/descriptor/xml/");
// we make sure that we found a file structure (and not a jar)
URL classURLcandidate = null;
while (classURLs.hasMoreElements()) {
URL classURL = classURLs.nextElement();
if (classURL.getProtocol().equals("file")) {
classURLcandidate = classURL;
}
}
try {
if (classURLcandidate != null) {
java.net.URI uriSchema;
uriSchema = classURLcandidate.toURI();
// we navigate to the descriptor schema
uriSchema = uriSchema.resolve(".." + java.io.File.separator
+ ".." + java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + ".."
+ java.io.File.separator + java.io.File.separator
+ "descriptors" + java.io.File.separator
+ "DescriptorSchema.xsd");
java.io.File test = new java.io.File(uriSchema);
// we make sure that we have found the right file
if (test.isFile()
&& test.getName().equals("DescriptorSchema.xsd")) {
schemaURLcandidate = uriSchema.toURL();
} else {
logger
.error("The Proactive.jar file doesn't contain the Descriptor Schema.");
schemaURLcandidate = null;
}
} else {
logger
.error("The descriptor schema could not be located in your environment.");
schemaURLcandidate = null;
}
} catch (Exception e) {
logger
.error("The descriptor schema could not be located in your environment.");
schemaURLcandidate = null;
}
}
logger.debug("Using XML schema: " + schemaURLcandidate);
org.objectweb.proactive.core.xml.io.StreamReader sr = null;
if ("enable".equals(ProActiveConfiguration.getSchemaValidationState())) {
sr = new org.objectweb.proactive.core.xml.io.StreamReader(
new org.xml.sax.InputSource(uri), h, schemaURLcandidate,
new SAXParserErrorHandlerTerminating());
} else {
sr = new org.objectweb.proactive.core.xml.io.StreamReader(
new org.xml.sax.InputSource(uri), h);
}
sr.read();
return (ProActiveDescriptorHandler) h.getResultObject();
}
|
diff --git a/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java b/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java
index e8288f359..9e028ce7d 100644
--- a/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java
+++ b/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java
@@ -1,414 +1,415 @@
package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.IndexDocValuesField;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter; // javadoc
import org.apache.lucene.index.codecs.CodecProvider;
import org.apache.lucene.index.values.ValueType;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.Version;
import org.apache.lucene.util._TestUtil;
/** Silly class that randomizes the indexing experience. EG
* it may swap in a different merge policy/scheduler; may
* commit periodically; may or may not optimize in the end,
* may flush by doc count instead of RAM, etc.
*/
public class RandomIndexWriter implements Closeable {
public IndexWriter w;
private final Random r;
int docCount;
int flushAt;
private double flushAtFactor = 1.0;
private boolean getReaderCalled;
private final int fixedBytesLength;
private final long docValuesFieldPrefix;
private volatile boolean doDocValues;
private CodecProvider codecProvider;
// Randomly calls Thread.yield so we mixup thread scheduling
private static final class MockIndexWriter extends IndexWriter {
private final Random r;
public MockIndexWriter(Random r, Directory dir, IndexWriterConfig conf) throws IOException {
super(dir, conf);
// must make a private random since our methods are
// called from different threads; else test failures may
// not be reproducible from the original seed
this.r = new Random(r.nextInt());
}
@Override
boolean testPoint(String name) {
if (r.nextInt(4) == 2)
Thread.yield();
return true;
}
}
/** create a RandomIndexWriter with a random config: Uses TEST_VERSION_CURRENT and MockAnalyzer */
public RandomIndexWriter(Random r, Directory dir) throws IOException {
this(r, dir, LuceneTestCase.newIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(r)));
}
/** create a RandomIndexWriter with a random config: Uses TEST_VERSION_CURRENT */
public RandomIndexWriter(Random r, Directory dir, Analyzer a) throws IOException {
this(r, dir, LuceneTestCase.newIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, a));
}
/** create a RandomIndexWriter with a random config */
public RandomIndexWriter(Random r, Directory dir, Version v, Analyzer a) throws IOException {
this(r, dir, LuceneTestCase.newIndexWriterConfig(r, v, a));
}
/** create a RandomIndexWriter with the provided config */
public RandomIndexWriter(Random r, Directory dir, IndexWriterConfig c) throws IOException {
this.r = r;
w = new MockIndexWriter(r, dir, c);
flushAt = _TestUtil.nextInt(r, 10, 1000);
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW config=" + w.getConfig());
System.out.println("codec default=" + w.getConfig().getCodecProvider().getDefaultFieldCodec());
w.setInfoStream(System.out);
}
/* TODO: find some what to make that random...
* This must be fixed across all fixed bytes
* fields in one index. so if you open another writer
* this might change if I use r.nextInt(x)
* maybe we can peek at the existing files here?
*/
fixedBytesLength = 37;
docValuesFieldPrefix = r.nextLong();
codecProvider = w.getConfig().getCodecProvider();
switchDoDocValues();
}
private void switchDoDocValues() {
// randomly enable / disable docValues
doDocValues = LuceneTestCase.rarely(r);
}
/**
* Adds a Document.
* @see IndexWriter#addDocument(Iterable)
*/
public <T extends IndexableField> void addDocument(final Iterable<T> doc) throws IOException {
if (doDocValues && doc instanceof Document) {
randomPerDocFieldValues(r, (Document) doc);
}
if (r.nextInt(5) == 3) {
// TODO: maybe, we should simply buffer up added docs
// (but we need to clone them), and only when
// getReader, commit, etc. are called, we do an
// addDocuments? Would be better testing.
w.addDocuments(new Iterable<Iterable<T>>() {
@Override
public Iterator<Iterable<T>> iterator() {
return new Iterator<Iterable<T>>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterable<T> next() {
if (done) {
throw new IllegalStateException();
}
done = true;
return doc;
}
};
}
});
} else {
w.addDocument(doc);
}
maybeCommit();
}
private void randomPerDocFieldValues(Random random, Document doc) {
ValueType[] values = ValueType.values();
ValueType type = values[random.nextInt(values.length)];
String name = "random_" + type.name() + "" + docValuesFieldPrefix;
if ("PreFlex".equals(codecProvider.getFieldCodec(name)) || doc.getField(name) != null)
return;
IndexDocValuesField docValuesField = new IndexDocValuesField(name);
switch (type) {
case BYTES_FIXED_DEREF:
case BYTES_FIXED_STRAIGHT:
case BYTES_FIXED_SORTED:
- final String randomUnicodeString = _TestUtil.randomUnicodeString(random, fixedBytesLength);
+ //make sure we use a valid unicode string with a fixed size byte length
+ final String randomUnicodeString = _TestUtil.randomFixedByteLengthUnicodeString(random, fixedBytesLength);
BytesRef fixedRef = new BytesRef(randomUnicodeString);
if (fixedRef.length > fixedBytesLength) {
fixedRef = new BytesRef(fixedRef.bytes, 0, fixedBytesLength);
} else {
fixedRef.grow(fixedBytesLength);
fixedRef.length = fixedBytesLength;
}
docValuesField.setBytes(fixedRef, type);
break;
case BYTES_VAR_DEREF:
case BYTES_VAR_STRAIGHT:
case BYTES_VAR_SORTED:
BytesRef ref = new BytesRef(_TestUtil.randomUnicodeString(random, 200));
docValuesField.setBytes(ref, type);
break;
case FLOAT_32:
docValuesField.setFloat(random.nextFloat());
break;
case FLOAT_64:
docValuesField.setFloat(random.nextDouble());
break;
case VAR_INTS:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_16:
docValuesField.setInt(random.nextInt(Short.MAX_VALUE));
break;
case FIXED_INTS_32:
docValuesField.setInt(random.nextInt());
break;
case FIXED_INTS_64:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_8:
docValuesField.setInt(random.nextInt(128));
break;
default:
throw new IllegalArgumentException("no such type: " + type);
}
doc.add(docValuesField);
}
private void maybeCommit() throws IOException {
if (docCount++ == flushAt) {
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW.add/updateDocument: now doing a commit at docCount=" + docCount);
}
w.commit();
flushAt += _TestUtil.nextInt(r, (int) (flushAtFactor * 10), (int) (flushAtFactor * 1000));
if (flushAtFactor < 2e6) {
// gradually but exponentially increase time b/w flushes
flushAtFactor *= 1.05;
}
switchDoDocValues();
}
}
public void addDocuments(Iterable<? extends Iterable<? extends IndexableField>> docs) throws IOException {
w.addDocuments(docs);
maybeCommit();
}
public void updateDocuments(Term delTerm, Iterable<? extends Iterable<? extends IndexableField>> docs) throws IOException {
w.updateDocuments(delTerm, docs);
maybeCommit();
}
/**
* Updates a document.
* @see IndexWriter#updateDocument(Term, Iterable)
*/
public <T extends IndexableField> void updateDocument(Term t, final Iterable<T> doc) throws IOException {
if (doDocValues) {
randomPerDocFieldValues(r, (Document) doc);
}
if (r.nextInt(5) == 3) {
w.updateDocuments(t, new Iterable<Iterable<T>>() {
@Override
public Iterator<Iterable<T>> iterator() {
return new Iterator<Iterable<T>>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterable<T> next() {
if (done) {
throw new IllegalStateException();
}
done = true;
return doc;
}
};
}
});
} else {
w.updateDocument(t, doc);
}
maybeCommit();
}
public void addIndexes(Directory... dirs) throws CorruptIndexException, IOException {
w.addIndexes(dirs);
}
public void deleteDocuments(Term term) throws CorruptIndexException, IOException {
w.deleteDocuments(term);
}
public void deleteDocuments(Query q) throws CorruptIndexException, IOException {
w.deleteDocuments(q);
}
public void commit() throws CorruptIndexException, IOException {
w.commit();
switchDoDocValues();
}
public int numDocs() throws IOException {
return w.numDocs();
}
public int maxDoc() {
return w.maxDoc();
}
public void deleteAll() throws IOException {
w.deleteAll();
}
public IndexReader getReader() throws IOException {
return getReader(true);
}
private boolean doRandomOptimize = true;
private boolean doRandomOptimizeAssert = true;
public void expungeDeletes(boolean doWait) throws IOException {
w.expungeDeletes(doWait);
}
public void expungeDeletes() throws IOException {
w.expungeDeletes();
}
public void setDoRandomOptimize(boolean v) {
doRandomOptimize = v;
}
public void setDoRandomOptimizeAssert(boolean v) {
doRandomOptimizeAssert = v;
}
private void doRandomOptimize() throws IOException {
if (doRandomOptimize) {
final int segCount = w.getSegmentCount();
if (r.nextBoolean() || segCount == 0) {
// full optimize
w.optimize();
} else {
// partial optimize
final int limit = _TestUtil.nextInt(r, 1, segCount);
w.optimize(limit);
assert !doRandomOptimizeAssert || w.getSegmentCount() <= limit: "limit=" + limit + " actual=" + w.getSegmentCount();
}
}
switchDoDocValues();
}
public IndexReader getReader(boolean applyDeletions) throws IOException {
getReaderCalled = true;
if (r.nextInt(4) == 2) {
doRandomOptimize();
}
// If we are writing with PreFlexRW, force a full
// IndexReader.open so terms are sorted in codepoint
// order during searching:
if (!applyDeletions || !w.codecs.getDefaultFieldCodec().equals("PreFlex") && r.nextBoolean()) {
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW.getReader: use NRT reader");
}
if (r.nextInt(5) == 1) {
w.commit();
}
return w.getReader(applyDeletions);
} else {
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW.getReader: open new reader");
}
w.commit();
switchDoDocValues();
if (r.nextBoolean()) {
return IndexReader.open(w.getDirectory(), new KeepOnlyLastCommitDeletionPolicy(), r.nextBoolean(), _TestUtil.nextInt(r, 1, 10), w.getConfig().getCodecProvider());
} else {
return w.getReader(applyDeletions);
}
}
}
/**
* Close this writer.
* @see IndexWriter#close()
*/
public void close() throws IOException {
// if someone isn't using getReader() API, we want to be sure to
// maybeOptimize since presumably they might open a reader on the dir.
if (getReaderCalled == false && r.nextInt(8) == 2) {
doRandomOptimize();
}
w.close();
}
/**
* Forces an optimize.
* <p>
* NOTE: this should be avoided in tests unless absolutely necessary,
* as it will result in less test coverage.
* @see IndexWriter#optimize()
*/
public void optimize() throws IOException {
w.optimize();
}
}
| true | true | private void randomPerDocFieldValues(Random random, Document doc) {
ValueType[] values = ValueType.values();
ValueType type = values[random.nextInt(values.length)];
String name = "random_" + type.name() + "" + docValuesFieldPrefix;
if ("PreFlex".equals(codecProvider.getFieldCodec(name)) || doc.getField(name) != null)
return;
IndexDocValuesField docValuesField = new IndexDocValuesField(name);
switch (type) {
case BYTES_FIXED_DEREF:
case BYTES_FIXED_STRAIGHT:
case BYTES_FIXED_SORTED:
final String randomUnicodeString = _TestUtil.randomUnicodeString(random, fixedBytesLength);
BytesRef fixedRef = new BytesRef(randomUnicodeString);
if (fixedRef.length > fixedBytesLength) {
fixedRef = new BytesRef(fixedRef.bytes, 0, fixedBytesLength);
} else {
fixedRef.grow(fixedBytesLength);
fixedRef.length = fixedBytesLength;
}
docValuesField.setBytes(fixedRef, type);
break;
case BYTES_VAR_DEREF:
case BYTES_VAR_STRAIGHT:
case BYTES_VAR_SORTED:
BytesRef ref = new BytesRef(_TestUtil.randomUnicodeString(random, 200));
docValuesField.setBytes(ref, type);
break;
case FLOAT_32:
docValuesField.setFloat(random.nextFloat());
break;
case FLOAT_64:
docValuesField.setFloat(random.nextDouble());
break;
case VAR_INTS:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_16:
docValuesField.setInt(random.nextInt(Short.MAX_VALUE));
break;
case FIXED_INTS_32:
docValuesField.setInt(random.nextInt());
break;
case FIXED_INTS_64:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_8:
docValuesField.setInt(random.nextInt(128));
break;
default:
throw new IllegalArgumentException("no such type: " + type);
}
doc.add(docValuesField);
}
| private void randomPerDocFieldValues(Random random, Document doc) {
ValueType[] values = ValueType.values();
ValueType type = values[random.nextInt(values.length)];
String name = "random_" + type.name() + "" + docValuesFieldPrefix;
if ("PreFlex".equals(codecProvider.getFieldCodec(name)) || doc.getField(name) != null)
return;
IndexDocValuesField docValuesField = new IndexDocValuesField(name);
switch (type) {
case BYTES_FIXED_DEREF:
case BYTES_FIXED_STRAIGHT:
case BYTES_FIXED_SORTED:
//make sure we use a valid unicode string with a fixed size byte length
final String randomUnicodeString = _TestUtil.randomFixedByteLengthUnicodeString(random, fixedBytesLength);
BytesRef fixedRef = new BytesRef(randomUnicodeString);
if (fixedRef.length > fixedBytesLength) {
fixedRef = new BytesRef(fixedRef.bytes, 0, fixedBytesLength);
} else {
fixedRef.grow(fixedBytesLength);
fixedRef.length = fixedBytesLength;
}
docValuesField.setBytes(fixedRef, type);
break;
case BYTES_VAR_DEREF:
case BYTES_VAR_STRAIGHT:
case BYTES_VAR_SORTED:
BytesRef ref = new BytesRef(_TestUtil.randomUnicodeString(random, 200));
docValuesField.setBytes(ref, type);
break;
case FLOAT_32:
docValuesField.setFloat(random.nextFloat());
break;
case FLOAT_64:
docValuesField.setFloat(random.nextDouble());
break;
case VAR_INTS:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_16:
docValuesField.setInt(random.nextInt(Short.MAX_VALUE));
break;
case FIXED_INTS_32:
docValuesField.setInt(random.nextInt());
break;
case FIXED_INTS_64:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_8:
docValuesField.setInt(random.nextInt(128));
break;
default:
throw new IllegalArgumentException("no such type: " + type);
}
doc.add(docValuesField);
}
|
diff --git a/rdt/org.eclipse.ptp.rdt.core/miners/org/eclipse/ptp/internal/rdt/core/miners/RemoteCHQueries.java b/rdt/org.eclipse.ptp.rdt.core/miners/org/eclipse/ptp/internal/rdt/core/miners/RemoteCHQueries.java
index e1ef1f6ee..e6b8f193a 100644
--- a/rdt/org.eclipse.ptp.rdt.core/miners/org/eclipse/ptp/internal/rdt/core/miners/RemoteCHQueries.java
+++ b/rdt/org.eclipse.ptp.rdt.core/miners/org/eclipse/ptp/internal/rdt/core/miners/RemoteCHQueries.java
@@ -1,308 +1,308 @@
/*******************************************************************************
* Copyright (c) 2006, 2011 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.ptp.internal.rdt.core.miners;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IEnumerator;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.dom.ast.c.ICExternalBinding;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.index.IIndexLocationConverter;
import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IMethod;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.ptp.internal.rdt.core.callhierarchy.CalledByResult;
import org.eclipse.ptp.internal.rdt.core.callhierarchy.CallsToResult;
import org.eclipse.ptp.internal.rdt.core.index.DummyName;
import org.eclipse.ptp.internal.rdt.core.index.IndexQueries;
import org.eclipse.ptp.internal.rdt.core.model.ICProjectFactory;
import org.eclipse.ptp.internal.rdt.core.model.IIndexLocationConverterFactory;
import org.eclipse.ptp.internal.rdt.core.model.RemoteCProjectFactory;
import org.eclipse.rse.dstore.universal.miners.UniversalServerUtilities;
public class RemoteCHQueries {
public static final String LOG_TAG = "RemoteCHQueries"; //$NON-NLS-1$
/* -- ST-Origin --
* Source folder: org.eclipse.cdt.ui/src
* Class: org.eclipse.cdt.internal.ui.callhierarchy.CHQueries
* Version: 1.20
*/
//copied from private static void findCalledBy(ICElement callee, int linkageID, IIndex index, CalledByResult result)
public static CalledByResult findCalledBy(ICElement callee, String path, IIndex project_index, IIndex serach_scope_index, String scheme, String hostName, CalledByResult result, DataStore _dataStore, IIndexLocationConverterFactory converter, DataElement status)
throws CoreException, URISyntaxException, InterruptedException {
final ICProject project = callee.getCProject();
IBinding calleeBinding = null;
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.acquireReadLock();
try {
calleeBinding=IndexQueries.elementToBinding(project_index, callee, path);
} finally {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Releasing read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.releaseReadLock();
}
if (calleeBinding != null) {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for serach_scope_index", _dataStore); //$NON-NLS-1$
serach_scope_index.acquireReadLock();
try{
findCalledBy1(serach_scope_index, calleeBinding, true, project, scheme, hostName, result, _dataStore, converter, status);
if (calleeBinding instanceof ICPPMethod) {
IBinding[] overriddenBindings= ClassTypeHelper.findOverridden((ICPPMethod) calleeBinding, null);
for (IBinding overriddenBinding : overriddenBindings) {
if(CDTMiner.isCancelled(status)) {
break;
}
findCalledBy1(serach_scope_index, overriddenBinding, false, project, scheme, hostName, result, _dataStore, converter, status);
}
}
} finally{
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Releasing read lock for serach_scope_index", _dataStore); //$NON-NLS-1$
serach_scope_index.releaseReadLock();
}
}
return result;
}
private static void findCalledBy1(IIndex index, IBinding callee, boolean includeOrdinaryCalls,
ICProject project, String scheme, String hostName, CalledByResult result, DataStore _dataStore, IIndexLocationConverterFactory converter, DataElement status) throws CoreException, URISyntaxException {
findCalledBy2(index, callee, includeOrdinaryCalls, project, scheme, hostName, result, _dataStore, converter, status);
List<? extends IBinding> specializations = IndexQueries.findSpecializations(callee);
for (IBinding spec : specializations) {
if(CDTMiner.isCancelled(status)) {
break;
}
findCalledBy2(index, spec, includeOrdinaryCalls, project, scheme, hostName, result, _dataStore, converter, status);
}
}
private static void findCalledBy2(IIndex index, IBinding callee, boolean includeOrdinaryCalls, ICProject project, String scheme, String hostName, CalledByResult result, DataStore _dataStore, IIndexLocationConverterFactory converter, DataElement status)
throws CoreException, URISyntaxException {
IIndexName[] names= index.findNames(callee, IIndex.FIND_REFERENCES | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES);
for (IIndexName rname : names) {
if(CDTMiner.isCancelled(status)) {
break;
}
if (includeOrdinaryCalls || rname.couldBePolymorphicMethodCall()) {
IIndexName caller= rname.getEnclosingDefinition();
if (caller != null) {
ICElement elem= IndexQueries.getCElementForName(project, index, caller, converter, new RemoteCProjectFactory());
if (elem != null) {
IIndexFileLocation indexLocation = createLocation(scheme, hostName, rname.getFile().getLocation(), _dataStore);
IIndexName reference = new DummyName(rname, rname.getFileLocation(), indexLocation);
result.add(elem, reference);
}
}
}
}
}
/**
* Searches for all calls that are made within a given range.
* @param status
* @throws InterruptedException
* @throws URISyntaxException
*/
public static CallsToResult findCalls(ICElement caller, String path, IIndex project_index, IIndex workspace_scope_index, String scheme, String hostName, DataStore _dataStore, IIndexLocationConverterFactory converter, DataElement status)
throws CoreException, InterruptedException, URISyntaxException {
CallsToResult result = new CallsToResult();
IIndexName callerName = null;
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.acquireReadLock();
try {
callerName= IndexQueries.remoteElementToName(project_index, caller, path);
}
finally {
UniversalServerUtilities.logDebugMessage(CDTMiner.LOG_TAG, "Releasing read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.releaseReadLock();
}
if (callerName != null) {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for workspace_scope_index", _dataStore); //$NON-NLS-1$
workspace_scope_index.acquireReadLock();
try{
IIndexName[] refs= callerName.getEnclosedNames();
final ICProject project = caller.getCProject();
ICProjectFactory projectFactory = new RemoteCProjectFactory();
for (IIndexName name : refs) {
if (CDTMiner.isCancelled(status)) {
break;
}
IBinding binding= workspace_scope_index.findBinding(name);
if (isRelevantForCallHierarchy(binding)) {
for(;;) {
if (CDTMiner.isCancelled(status)) {
break;
}
ICElement[] defs= null;
- if (binding instanceof ICPPMethod) {
+ if (binding instanceof ICPPMethod && name.couldBePolymorphicMethodCall()) {
defs = findOverriders(workspace_scope_index, (ICPPMethod) binding, converter, project, projectFactory);
}
if (defs == null) {
defs= IndexQueries.findRepresentative(workspace_scope_index, binding, converter, project, projectFactory);
}
if (defs != null && defs.length > 0) {
IIndexFileLocation indexLocation = createLocation(scheme, hostName, name.getFile().getLocation(), _dataStore);
IIndexName reference = new DummyName(name, name.getFileLocation(), indexLocation);
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Found a callee: " + defs[0].getElementName() + "\n", _dataStore); //$NON-NLS-1$ //$NON-NLS-2$
result.add(defs, reference);
} else if (binding instanceof ICPPSpecialization) {
binding= ((ICPPSpecialization) binding).getSpecializedBinding();
if (binding != null)
continue;
}
break;
}
}
}
}finally {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Releasing read lock for workspace_scope_index", _dataStore); //$NON-NLS-1$
workspace_scope_index.releaseReadLock();
}
}
return result;
}
/**
* Searches for overriders of method and converts them to ICElement, returns null, if there are none.
*/
private static ICElement[] findOverriders(IIndex index, ICPPMethod binding, IIndexLocationConverterFactory converter, ICProject project, ICProjectFactory projectFactory) throws CoreException {
IBinding[] virtualOverriders= ClassTypeHelper.findOverriders(index, binding);
if (virtualOverriders.length > 0) {
ArrayList<ICElement> list= new ArrayList<ICElement>();
list.addAll(Arrays.asList(IndexQueries.findRepresentative(index, binding, converter, project, projectFactory)));
for (IBinding overrider : virtualOverriders) {
list.addAll(Arrays.asList(IndexQueries.findRepresentative(index, overrider, converter, project, projectFactory)));
}
return list.toArray(new ICElement[list.size()]);
}
return null;
}
/* -- ST-Origin --
* Source folder: org.eclipse.cdt.ui/src
* Class: org.eclipse.cdt.internal.ui.callhierarchy.CallHierarchyUI
* Version: 1.25
*/
public static boolean isRelevantForCallHierarchy(IBinding binding) {
if (binding instanceof ICExternalBinding ||
binding instanceof IEnumerator ||
binding instanceof IFunction ||
binding instanceof IVariable) {
return true;
}
return false;
}
private static IIndexFileLocation createLocation(String scheme, String hostName, IIndexFileLocation location, DataStore _dataStore) throws URISyntaxException {
URI uri = location.getURI();
String path = uri.getPath();
URI newURI = null;
if(scheme == null || scheme.equals("")) { //$NON-NLS-1$
scheme = ScopeManager.getInstance().getSchemeForFile(path);
}
// create the URI
newURI = URICreatorManager.getDefault(_dataStore).createURI(scheme, hostName, path);
return new RemoteIndexFileLocation(null, newURI);
}
/* -- ST-Origin --
* Source folder: org.eclipse.cdt.ui/src
* Class: org.eclipse.cdt.internal.ui.callhierarchy.CHContentProvider
* Version: 1.21
*/
public static Map<String, ICElement[]> handleGetOverriders(IIndex project_index, ICElement subject, String path, DataStore _dataStore, IIndexLocationConverterFactory converter) throws InterruptedException, CoreException {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock", _dataStore); //$NON-NLS-1$
project_index.acquireReadLock();
Map<String, ICElement[]> result = new HashMap<String, ICElement[]>();
try {
if (subject instanceof IMethod) {
IIndexName methodName= IndexQueries.remoteElementToName(project_index, subject, path);
if (methodName != null) {
IBinding methodBinding= project_index.findBinding(methodName);
if (methodBinding instanceof ICPPMethod) {
final ICProject project = subject.getCProject();
ICProjectFactory projectFactory = new RemoteCProjectFactory();
ICElement[] defs= findOverriders(project_index, (ICPPMethod) methodBinding, converter, project, projectFactory);
if (defs != null && defs.length > 0) {
result.put(methodBinding.getLinkage().getLinkageID()+"", defs); //$NON-NLS-1$
}
}
}
}
}
finally {
project_index.releaseReadLock();
}
return result;
}
}
| true | true | public static CallsToResult findCalls(ICElement caller, String path, IIndex project_index, IIndex workspace_scope_index, String scheme, String hostName, DataStore _dataStore, IIndexLocationConverterFactory converter, DataElement status)
throws CoreException, InterruptedException, URISyntaxException {
CallsToResult result = new CallsToResult();
IIndexName callerName = null;
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.acquireReadLock();
try {
callerName= IndexQueries.remoteElementToName(project_index, caller, path);
}
finally {
UniversalServerUtilities.logDebugMessage(CDTMiner.LOG_TAG, "Releasing read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.releaseReadLock();
}
if (callerName != null) {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for workspace_scope_index", _dataStore); //$NON-NLS-1$
workspace_scope_index.acquireReadLock();
try{
IIndexName[] refs= callerName.getEnclosedNames();
final ICProject project = caller.getCProject();
ICProjectFactory projectFactory = new RemoteCProjectFactory();
for (IIndexName name : refs) {
if (CDTMiner.isCancelled(status)) {
break;
}
IBinding binding= workspace_scope_index.findBinding(name);
if (isRelevantForCallHierarchy(binding)) {
for(;;) {
if (CDTMiner.isCancelled(status)) {
break;
}
ICElement[] defs= null;
if (binding instanceof ICPPMethod) {
defs = findOverriders(workspace_scope_index, (ICPPMethod) binding, converter, project, projectFactory);
}
if (defs == null) {
defs= IndexQueries.findRepresentative(workspace_scope_index, binding, converter, project, projectFactory);
}
if (defs != null && defs.length > 0) {
IIndexFileLocation indexLocation = createLocation(scheme, hostName, name.getFile().getLocation(), _dataStore);
IIndexName reference = new DummyName(name, name.getFileLocation(), indexLocation);
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Found a callee: " + defs[0].getElementName() + "\n", _dataStore); //$NON-NLS-1$ //$NON-NLS-2$
result.add(defs, reference);
} else if (binding instanceof ICPPSpecialization) {
binding= ((ICPPSpecialization) binding).getSpecializedBinding();
if (binding != null)
continue;
}
break;
}
}
}
}finally {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Releasing read lock for workspace_scope_index", _dataStore); //$NON-NLS-1$
workspace_scope_index.releaseReadLock();
}
}
return result;
}
| public static CallsToResult findCalls(ICElement caller, String path, IIndex project_index, IIndex workspace_scope_index, String scheme, String hostName, DataStore _dataStore, IIndexLocationConverterFactory converter, DataElement status)
throws CoreException, InterruptedException, URISyntaxException {
CallsToResult result = new CallsToResult();
IIndexName callerName = null;
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.acquireReadLock();
try {
callerName= IndexQueries.remoteElementToName(project_index, caller, path);
}
finally {
UniversalServerUtilities.logDebugMessage(CDTMiner.LOG_TAG, "Releasing read lock for project_index", _dataStore); //$NON-NLS-1$
project_index.releaseReadLock();
}
if (callerName != null) {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Acquiring read lock for workspace_scope_index", _dataStore); //$NON-NLS-1$
workspace_scope_index.acquireReadLock();
try{
IIndexName[] refs= callerName.getEnclosedNames();
final ICProject project = caller.getCProject();
ICProjectFactory projectFactory = new RemoteCProjectFactory();
for (IIndexName name : refs) {
if (CDTMiner.isCancelled(status)) {
break;
}
IBinding binding= workspace_scope_index.findBinding(name);
if (isRelevantForCallHierarchy(binding)) {
for(;;) {
if (CDTMiner.isCancelled(status)) {
break;
}
ICElement[] defs= null;
if (binding instanceof ICPPMethod && name.couldBePolymorphicMethodCall()) {
defs = findOverriders(workspace_scope_index, (ICPPMethod) binding, converter, project, projectFactory);
}
if (defs == null) {
defs= IndexQueries.findRepresentative(workspace_scope_index, binding, converter, project, projectFactory);
}
if (defs != null && defs.length > 0) {
IIndexFileLocation indexLocation = createLocation(scheme, hostName, name.getFile().getLocation(), _dataStore);
IIndexName reference = new DummyName(name, name.getFileLocation(), indexLocation);
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Found a callee: " + defs[0].getElementName() + "\n", _dataStore); //$NON-NLS-1$ //$NON-NLS-2$
result.add(defs, reference);
} else if (binding instanceof ICPPSpecialization) {
binding= ((ICPPSpecialization) binding).getSpecializedBinding();
if (binding != null)
continue;
}
break;
}
}
}
}finally {
UniversalServerUtilities.logDebugMessage(LOG_TAG, "Releasing read lock for workspace_scope_index", _dataStore); //$NON-NLS-1$
workspace_scope_index.releaseReadLock();
}
}
return result;
}
|
diff --git a/deegree-layers/deegree-layers-feature/src/main/java/org/deegree/layer/persistence/feature/FeatureLayer.java b/deegree-layers/deegree-layers-feature/src/main/java/org/deegree/layer/persistence/feature/FeatureLayer.java
index aee7324ce1..da92299236 100644
--- a/deegree-layers/deegree-layers-feature/src/main/java/org/deegree/layer/persistence/feature/FeatureLayer.java
+++ b/deegree-layers/deegree-layers-feature/src/main/java/org/deegree/layer/persistence/feature/FeatureLayer.java
@@ -1,191 +1,192 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
Occam Labs Schmitz & Schneider GbR
Godesberger Allee 139, 53175 Bonn
Germany
http://www.occamlabs.de/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.layer.persistence.feature;
import static org.deegree.layer.persistence.feature.FilterBuilder.buildFilterForMap;
import static org.deegree.style.utils.Styles.getStyleFilters;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import org.deegree.commons.ows.exception.OWSException;
import org.deegree.feature.persistence.FeatureStore;
import org.deegree.feature.persistence.query.Query;
import org.deegree.feature.types.AppSchemas;
import org.deegree.filter.Expression;
import org.deegree.filter.Filters;
import org.deegree.filter.OperatorFilter;
import org.deegree.filter.expression.ValueReference;
import org.deegree.filter.sort.SortProperty;
import org.deegree.geometry.Envelope;
import org.deegree.layer.AbstractLayer;
import org.deegree.layer.LayerQuery;
import org.deegree.layer.metadata.LayerMetadata;
import org.deegree.style.StyleRef;
import org.deegree.style.se.unevaluated.Style;
import org.deegree.style.utils.Styles;
import org.slf4j.Logger;
/**
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author: stranger $
*
* @version $Revision: $, $Date: $
*/
public class FeatureLayer extends AbstractLayer {
private static final Logger LOG = getLogger( FeatureLayer.class );
private FeatureStore featureStore;
private OperatorFilter filter;
private final QName featureType;
SortProperty[] sortBy, sortByFeatureInfo;
private DimensionFilterBuilder dimFilterBuilder;
public FeatureLayer( LayerMetadata md, FeatureStore featureStore, QName featureType, OperatorFilter filter,
List<SortProperty> sortBy, List<SortProperty> sortByFeatureInfo ) {
super( md );
this.featureStore = featureStore;
this.featureType = featureType;
this.filter = filter;
if ( sortBy != null ) {
this.sortBy = sortBy.toArray( new SortProperty[sortBy.size()] );
}
if ( sortByFeatureInfo != null ) {
this.sortByFeatureInfo = sortByFeatureInfo.toArray( new SortProperty[sortByFeatureInfo.size()] );
}
dimFilterBuilder = new DimensionFilterBuilder( md.getDimensions() );
}
@Override
public FeatureLayerData mapQuery( final LayerQuery query, List<String> headers )
throws OWSException {
StyleRef ref = query.getStyle();
if ( !ref.isResolved() ) {
ref.resolve( getMetadata().getStyles().get( ref.getName() ) );
}
Style style = ref.getStyle();
if ( style == null ) {
throw new OWSException( "The style " + ref.getName() + " is not defined for layer "
+ getMetadata().getName() + ".", "StyleNotDefined", "styles" );
}
+ style = style.filter( query.getScale() );
OperatorFilter filter = buildFilterForMap( this.filter, style, query, dimFilterBuilder, headers );
final Envelope bbox = query.getQueryBox();
Set<Expression> exprs = new HashSet<Expression>( Styles.getGeometryExpressions( style ) );
final ValueReference geomProp;
if ( exprs.size() == 1 && exprs.iterator().next() instanceof ValueReference ) {
geomProp = (ValueReference) exprs.iterator().next();
} else {
geomProp = null;
}
QName ftName = featureType == null ? style.getFeatureType() : featureType;
if ( ftName != null && featureStore.getSchema().getFeatureType( ftName ) == null ) {
LOG.warn( "FeatureType '" + ftName + "' is not known to the FeatureStore." );
return null;
}
filter = Filters.repair( filter, AppSchemas.collectProperyNames( featureStore.getSchema(), ftName ) );
QueryBuilder builder = new QueryBuilder( featureStore, filter, ftName, bbox, query, geomProp, sortBy,
getMetadata().getName() );
List<Query> queries = builder.buildMapQueries();
if ( queries.isEmpty() ) {
LOG.warn( "No queries were generated. Is the configuration correct?" );
return null;
}
Integer maxFeats = query.getRenderingOptions().getMaxFeatures( getMetadata().getName() );
final int maxFeatures = maxFeats == null ? -1 : maxFeats;
return new FeatureLayerData( queries, featureStore, maxFeatures, style, ftName );
}
@Override
public FeatureLayerData infoQuery( final LayerQuery query, List<String> headers )
throws OWSException {
OperatorFilter filter = this.filter;
filter = Filters.and( filter, dimFilterBuilder.getDimensionFilter( query.getDimensions(), headers ) );
StyleRef ref = query.getStyle();
if ( !ref.isResolved() ) {
ref.resolve( getMetadata().getStyles().get( ref.getName() ) );
}
Style style = ref.getStyle();
style = style.filter( query.getScale() );
filter = Filters.and( filter, getStyleFilters( style, query.getScale() ) );
filter = Filters.and( filter, query.getFilter() );
final Envelope clickBox = query.calcClickBox( query.getRenderingOptions().getFeatureInfoRadius( getMetadata().getName() ) );
filter = (OperatorFilter) Filters.addBBoxConstraint( clickBox, filter, null );
QName featureType = this.featureType == null ? style.getFeatureType() : this.featureType;
filter = Filters.repair( filter, AppSchemas.collectProperyNames( featureStore.getSchema(), featureType ) );
LOG.debug( "Querying the feature store(s)..." );
QueryBuilder builder = new QueryBuilder( featureStore, filter, featureType, clickBox, query, null,
sortByFeatureInfo, getMetadata().getName() );
List<Query> queries = builder.buildInfoQueries();
LOG.debug( "Finished querying the feature store(s)." );
return new FeatureLayerData( queries, featureStore, query.getFeatureCount(), style, featureType );
}
}
| true | true | public FeatureLayerData mapQuery( final LayerQuery query, List<String> headers )
throws OWSException {
StyleRef ref = query.getStyle();
if ( !ref.isResolved() ) {
ref.resolve( getMetadata().getStyles().get( ref.getName() ) );
}
Style style = ref.getStyle();
if ( style == null ) {
throw new OWSException( "The style " + ref.getName() + " is not defined for layer "
+ getMetadata().getName() + ".", "StyleNotDefined", "styles" );
}
OperatorFilter filter = buildFilterForMap( this.filter, style, query, dimFilterBuilder, headers );
final Envelope bbox = query.getQueryBox();
Set<Expression> exprs = new HashSet<Expression>( Styles.getGeometryExpressions( style ) );
final ValueReference geomProp;
if ( exprs.size() == 1 && exprs.iterator().next() instanceof ValueReference ) {
geomProp = (ValueReference) exprs.iterator().next();
} else {
geomProp = null;
}
QName ftName = featureType == null ? style.getFeatureType() : featureType;
if ( ftName != null && featureStore.getSchema().getFeatureType( ftName ) == null ) {
LOG.warn( "FeatureType '" + ftName + "' is not known to the FeatureStore." );
return null;
}
filter = Filters.repair( filter, AppSchemas.collectProperyNames( featureStore.getSchema(), ftName ) );
QueryBuilder builder = new QueryBuilder( featureStore, filter, ftName, bbox, query, geomProp, sortBy,
getMetadata().getName() );
List<Query> queries = builder.buildMapQueries();
if ( queries.isEmpty() ) {
LOG.warn( "No queries were generated. Is the configuration correct?" );
return null;
}
Integer maxFeats = query.getRenderingOptions().getMaxFeatures( getMetadata().getName() );
final int maxFeatures = maxFeats == null ? -1 : maxFeats;
return new FeatureLayerData( queries, featureStore, maxFeatures, style, ftName );
}
| public FeatureLayerData mapQuery( final LayerQuery query, List<String> headers )
throws OWSException {
StyleRef ref = query.getStyle();
if ( !ref.isResolved() ) {
ref.resolve( getMetadata().getStyles().get( ref.getName() ) );
}
Style style = ref.getStyle();
if ( style == null ) {
throw new OWSException( "The style " + ref.getName() + " is not defined for layer "
+ getMetadata().getName() + ".", "StyleNotDefined", "styles" );
}
style = style.filter( query.getScale() );
OperatorFilter filter = buildFilterForMap( this.filter, style, query, dimFilterBuilder, headers );
final Envelope bbox = query.getQueryBox();
Set<Expression> exprs = new HashSet<Expression>( Styles.getGeometryExpressions( style ) );
final ValueReference geomProp;
if ( exprs.size() == 1 && exprs.iterator().next() instanceof ValueReference ) {
geomProp = (ValueReference) exprs.iterator().next();
} else {
geomProp = null;
}
QName ftName = featureType == null ? style.getFeatureType() : featureType;
if ( ftName != null && featureStore.getSchema().getFeatureType( ftName ) == null ) {
LOG.warn( "FeatureType '" + ftName + "' is not known to the FeatureStore." );
return null;
}
filter = Filters.repair( filter, AppSchemas.collectProperyNames( featureStore.getSchema(), ftName ) );
QueryBuilder builder = new QueryBuilder( featureStore, filter, ftName, bbox, query, geomProp, sortBy,
getMetadata().getName() );
List<Query> queries = builder.buildMapQueries();
if ( queries.isEmpty() ) {
LOG.warn( "No queries were generated. Is the configuration correct?" );
return null;
}
Integer maxFeats = query.getRenderingOptions().getMaxFeatures( getMetadata().getName() );
final int maxFeatures = maxFeats == null ? -1 : maxFeats;
return new FeatureLayerData( queries, featureStore, maxFeatures, style, ftName );
}
|
diff --git a/src/entities/players/abilities/ForwardTeleportAbility.java b/src/entities/players/abilities/ForwardTeleportAbility.java
index 6e5bd9b..d67ede5 100644
--- a/src/entities/players/abilities/ForwardTeleportAbility.java
+++ b/src/entities/players/abilities/ForwardTeleportAbility.java
@@ -1,35 +1,35 @@
package entities.players.abilities;
import map.MapLoader;
import map.tileproperties.TileProperty;
import entities.players.Player;
import game.config.Config;
class ForwardTeleportAbility extends AbstractPlayerAbility {
private static float distance = 5f;
ForwardTeleportAbility() {
super("Forward teleport","Press Q to teleport forward");
}
public void use(Player p){
if (p.getDirection() == 1 && (p.getX() - 1 + distance < Config.getScreenWidth()/Config.getTileSize())){
- if (MapLoader.getCurrentCell().getTile((int) p.getX() + (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
+ if (!MapLoader.getCurrentCell().getTile((int) p.getX() + (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
p.accelerate(distance,0);
}
} else if (p.getDirection() == -1 && (p.getX() - 1 - distance > 0)) {
- if (MapLoader.getCurrentCell().getTile((int) p.getX() - (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
+ if (!MapLoader.getCurrentCell().getTile((int) p.getX() - (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
p.accelerate(-distance,0);
}
}
}
public static float getDistance() {
return distance;
}
public static void setDistance(float distance) {
ForwardTeleportAbility.distance = distance;
}
}
| false | true | public void use(Player p){
if (p.getDirection() == 1 && (p.getX() - 1 + distance < Config.getScreenWidth()/Config.getTileSize())){
if (MapLoader.getCurrentCell().getTile((int) p.getX() + (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
p.accelerate(distance,0);
}
} else if (p.getDirection() == -1 && (p.getX() - 1 - distance > 0)) {
if (MapLoader.getCurrentCell().getTile((int) p.getX() - (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
p.accelerate(-distance,0);
}
}
}
| public void use(Player p){
if (p.getDirection() == 1 && (p.getX() - 1 + distance < Config.getScreenWidth()/Config.getTileSize())){
if (!MapLoader.getCurrentCell().getTile((int) p.getX() + (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
p.accelerate(distance,0);
}
} else if (p.getDirection() == -1 && (p.getX() - 1 - distance > 0)) {
if (!MapLoader.getCurrentCell().getTile((int) p.getX() - (int) distance, (int) p.getY()).lookup(TileProperty.BLOCKED)){
p.accelerate(-distance,0);
}
}
}
|
diff --git a/example/src/test/java/org/apache/mina/example/echoserver/ConnectorTest.java b/example/src/test/java/org/apache/mina/example/echoserver/ConnectorTest.java
index 2ef65bc9..e77faae4 100644
--- a/example/src/test/java/org/apache/mina/example/echoserver/ConnectorTest.java
+++ b/example/src/test/java/org/apache/mina/example/echoserver/ConnectorTest.java
@@ -1,269 +1,269 @@
/*
* 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.mina.example.echoserver;
import java.net.InetSocketAddress;
import junit.framework.Assert;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.RuntimeIOException;
import org.apache.mina.common.WriteFuture;
import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory;
import org.apache.mina.filter.SSLFilter;
import org.apache.mina.transport.socket.nio.DatagramConnector;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.util.AvailablePortFinder;
import org.apache.mina.util.SessionLog;
/**
* Tests echo server example.
*
* @author The Apache Directory Project ([email protected])
* @version $Rev:448075 $, $Date:2006-09-20 05:26:53Z $
*/
public class ConnectorTest extends AbstractTest
{
private static final int TIMEOUT = 10000; // 10 seconds
private final int COUNT = 10;
private final int DATA_SIZE = 16;
private SSLFilter connectorSSLFilter;
public ConnectorTest()
{
}
protected void setUp() throws Exception
{
super.setUp();
connectorSSLFilter =
new SSLFilter( BogusSSLContextFactory.getInstance( false ) );
connectorSSLFilter.setUseClientMode( true ); // set client mode
}
public void testTCP() throws Exception
{
IoConnector connector = new SocketConnector();
testConnector( connector );
}
public void testTCPWithSSL() throws Exception
{
useSSL = true;
// Create a connector
IoConnector connector = new SocketConnector();
// Add an SSL filter to connector
connector.getFilterChain().addLast( "SSL", connectorSSLFilter );
testConnector( connector );
}
public void testUDP() throws Exception
{
IoConnector connector = new DatagramConnector();
testConnector( connector );
}
private void testConnector( IoConnector connector ) throws Exception
{
System.out.println("* Without localAddress");
testConnector( connector, false );
System.out.println("* With localAddress");
testConnector( connector, true );
}
private void testConnector( IoConnector connector, boolean useLocalAddress ) throws Exception
{
EchoConnectorHandler handler = new EchoConnectorHandler();
IoSession session = null;
if( !useLocalAddress )
{
connector.setHandler( handler );
ConnectFuture future = connector.connect(
new InetSocketAddress( "localhost", port ) );
future.join();
session = future.getSession();
}
else
{
int clientPort = port;
for( int i = 0; i < 65536; i ++ )
{
clientPort = AvailablePortFinder.getNextAvailable( clientPort + 1 );
try
{
connector.setHandler( handler );
ConnectFuture future = connector.connect(
- new InetSocketAddress( clientPort ),
- new InetSocketAddress( "localhost", port ) );
+ new InetSocketAddress( "localhost", port ),
+ new InetSocketAddress( clientPort ) );
future.join();
session = future.getSession();
break;
}
catch( RuntimeIOException e )
{
// Try again until we succeed to bind.
}
}
if( session == null )
{
Assert.fail( "Failed to find out an appropriate local address." );
}
}
// Run a basic connector test.
testConnector0( session );
// Send closeNotify to test TLS closure if it is TLS connection.
if( useSSL )
{
connectorSSLFilter.stopSSL( session ).join();
System.out.println( "-------------------------------------------------------------------------------" );
// Test again after we finished TLS session.
testConnector0( session );
System.out.println( "-------------------------------------------------------------------------------" );
// Test if we can enter TLS mode again.
//// Send StartTLS request.
handler.readBuf.clear();
ByteBuffer buf = ByteBuffer.allocate( 1 );
buf.put( ( byte ) '.' );
buf.flip();
session.write( buf ).join();
//// Wait for StartTLS response.
waitForResponse( handler, 1 );
handler.readBuf.flip();
Assert.assertEquals( 1, handler.readBuf.remaining() );
Assert.assertEquals( ( byte ) '.', handler.readBuf.get() );
// Now start TLS connection
Assert.assertTrue( connectorSSLFilter.startSSL( session ) );
testConnector0( session );
}
session.close().join();
}
private void testConnector0( IoSession session ) throws InterruptedException
{
EchoConnectorHandler handler = ( EchoConnectorHandler ) session.getHandler();
ByteBuffer readBuf = handler.readBuf;
readBuf.clear();
WriteFuture writeFuture = null;
for( int i = 0; i < COUNT; i ++ )
{
ByteBuffer buf = ByteBuffer.allocate( DATA_SIZE );
buf.limit( DATA_SIZE );
fillWriteBuffer( buf, i );
buf.flip();
writeFuture = session.write( buf );
if( session.getTransportType().isConnectionless() )
{
// This will align message arrival order in connectionless transport types
waitForResponse( handler, ( i + 1 ) * DATA_SIZE );
}
}
writeFuture.join();
waitForResponse( handler, DATA_SIZE * COUNT );
// Assert data
//// Please note that BufferOverflowException can be thrown
//// in SocketIoProcessor if there was a read timeout because
//// we share readBuf.
readBuf.flip();
SessionLog.info( session, "readBuf: " + readBuf );
Assert.assertEquals( DATA_SIZE * COUNT, readBuf.remaining() );
ByteBuffer expectedBuf = ByteBuffer.allocate( DATA_SIZE * COUNT );
for( int i = 0; i < COUNT; i ++ ) {
expectedBuf.limit( ( i + 1 ) * DATA_SIZE );
fillWriteBuffer( expectedBuf, i );
}
expectedBuf.position( 0 );
assertEquals(expectedBuf, readBuf);
}
private void waitForResponse( EchoConnectorHandler handler, int bytes ) throws InterruptedException
{
for( int j = 0; j < TIMEOUT / 10; j ++ )
{
if( handler.readBuf.position() >= bytes )
{
break;
}
Thread.sleep( 10 );
}
Assert.assertEquals( bytes, handler.readBuf.position() );
}
private void fillWriteBuffer( ByteBuffer writeBuf, int i )
{
while( writeBuf.remaining() > 0 )
{
writeBuf.put( ( byte ) ( i ++ ) );
}
}
public static void main( String[] args )
{
junit.textui.TestRunner.run( ConnectorTest.class );
}
private static class EchoConnectorHandler extends IoHandlerAdapter
{
private ByteBuffer readBuf = ByteBuffer.allocate( 1024 );
private EchoConnectorHandler()
{
readBuf.setAutoExpand( true );
}
public void messageReceived( IoSession session, Object message )
{
readBuf.put( ( ByteBuffer ) message );
}
public void messageSent( IoSession session, Object message )
{
}
public void exceptionCaught( IoSession session, Throwable cause )
{
cause.printStackTrace();
}
}
}
| true | true | private void testConnector( IoConnector connector, boolean useLocalAddress ) throws Exception
{
EchoConnectorHandler handler = new EchoConnectorHandler();
IoSession session = null;
if( !useLocalAddress )
{
connector.setHandler( handler );
ConnectFuture future = connector.connect(
new InetSocketAddress( "localhost", port ) );
future.join();
session = future.getSession();
}
else
{
int clientPort = port;
for( int i = 0; i < 65536; i ++ )
{
clientPort = AvailablePortFinder.getNextAvailable( clientPort + 1 );
try
{
connector.setHandler( handler );
ConnectFuture future = connector.connect(
new InetSocketAddress( clientPort ),
new InetSocketAddress( "localhost", port ) );
future.join();
session = future.getSession();
break;
}
catch( RuntimeIOException e )
{
// Try again until we succeed to bind.
}
}
if( session == null )
{
Assert.fail( "Failed to find out an appropriate local address." );
}
}
// Run a basic connector test.
testConnector0( session );
// Send closeNotify to test TLS closure if it is TLS connection.
if( useSSL )
{
connectorSSLFilter.stopSSL( session ).join();
System.out.println( "-------------------------------------------------------------------------------" );
// Test again after we finished TLS session.
testConnector0( session );
System.out.println( "-------------------------------------------------------------------------------" );
// Test if we can enter TLS mode again.
//// Send StartTLS request.
handler.readBuf.clear();
ByteBuffer buf = ByteBuffer.allocate( 1 );
buf.put( ( byte ) '.' );
buf.flip();
session.write( buf ).join();
//// Wait for StartTLS response.
waitForResponse( handler, 1 );
handler.readBuf.flip();
Assert.assertEquals( 1, handler.readBuf.remaining() );
Assert.assertEquals( ( byte ) '.', handler.readBuf.get() );
// Now start TLS connection
Assert.assertTrue( connectorSSLFilter.startSSL( session ) );
testConnector0( session );
}
session.close().join();
}
| private void testConnector( IoConnector connector, boolean useLocalAddress ) throws Exception
{
EchoConnectorHandler handler = new EchoConnectorHandler();
IoSession session = null;
if( !useLocalAddress )
{
connector.setHandler( handler );
ConnectFuture future = connector.connect(
new InetSocketAddress( "localhost", port ) );
future.join();
session = future.getSession();
}
else
{
int clientPort = port;
for( int i = 0; i < 65536; i ++ )
{
clientPort = AvailablePortFinder.getNextAvailable( clientPort + 1 );
try
{
connector.setHandler( handler );
ConnectFuture future = connector.connect(
new InetSocketAddress( "localhost", port ),
new InetSocketAddress( clientPort ) );
future.join();
session = future.getSession();
break;
}
catch( RuntimeIOException e )
{
// Try again until we succeed to bind.
}
}
if( session == null )
{
Assert.fail( "Failed to find out an appropriate local address." );
}
}
// Run a basic connector test.
testConnector0( session );
// Send closeNotify to test TLS closure if it is TLS connection.
if( useSSL )
{
connectorSSLFilter.stopSSL( session ).join();
System.out.println( "-------------------------------------------------------------------------------" );
// Test again after we finished TLS session.
testConnector0( session );
System.out.println( "-------------------------------------------------------------------------------" );
// Test if we can enter TLS mode again.
//// Send StartTLS request.
handler.readBuf.clear();
ByteBuffer buf = ByteBuffer.allocate( 1 );
buf.put( ( byte ) '.' );
buf.flip();
session.write( buf ).join();
//// Wait for StartTLS response.
waitForResponse( handler, 1 );
handler.readBuf.flip();
Assert.assertEquals( 1, handler.readBuf.remaining() );
Assert.assertEquals( ( byte ) '.', handler.readBuf.get() );
// Now start TLS connection
Assert.assertTrue( connectorSSLFilter.startSSL( session ) );
testConnector0( session );
}
session.close().join();
}
|
diff --git a/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java b/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java
index 6d0dceb..3553725 100644
--- a/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java
+++ b/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java
@@ -1,74 +1,73 @@
package org.opentripplanner.graph_builder.impl.shapefile;
import java.io.File;
import junit.framework.TestCase;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
public class TestShapefileStreetGraphBuilderImpl extends TestCase {
public void testBasic() throws Exception {
Graph gg = new Graph();
File file = new File("src/test/resources/nyc_streets/streets.shp");
- file = new File("/Users/bdferris/oba/data/opentripplanner-data/nyc/streets/nyc_streets/streets.shp");
if (!file.exists()) {
System.out.println("No New York City basemap; skipping; see comment here for details");
/*
* This test requires the New York City base map, available at:
* http://www.nyc.gov/html/dcp/html/bytes/dwnlion.shtml Download the MapInfo file. This
* must be converted to a ShapeFile. unzip nyc_lion09ami.zip ogr2ogr -f 'ESRI Shapefile'
* nyc_streets/streets.shp lion/MNLION1.tab ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/SILION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/QNLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BKLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BXLION1.tab -nln streets
*
* It also requires the NYC Subway data in GTFS: cd src/test/resources wget
* http://data.topplabs.org/data/mta_nyct_subway/subway.zip
*/
return;
}
ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
ShapefileStreetSchema schema = new ShapefileStreetSchema();
schema.setIdAttribute("StreetCode");
schema.setNameAttribute("Street");
CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
forward.addPermission("W", StreetTraversalPermission.ALL);
reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY);
forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY);
reverse.addPermission("A", StreetTraversalPermission.ALL);
forward.addPermission("T", StreetTraversalPermission.ALL);
reverse.addPermission("T", StreetTraversalPermission.ALL);
schema.setForwardPermissionConverter(forward);
schema.setReversePermissionConverter(reverse);
ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl();
loader.setFeatureSourceFactory(factory);
loader.setSchema(schema);
loader.buildGraph(gg);
assertEquals(104910,gg.getVertices().size());
Vertex start = gg.getVertex("PARK PL at VANDERBILT AV");
Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST");
assertNotNull(start);
assertNotNull(end);
}
}
| true | true | public void testBasic() throws Exception {
Graph gg = new Graph();
File file = new File("src/test/resources/nyc_streets/streets.shp");
file = new File("/Users/bdferris/oba/data/opentripplanner-data/nyc/streets/nyc_streets/streets.shp");
if (!file.exists()) {
System.out.println("No New York City basemap; skipping; see comment here for details");
/*
* This test requires the New York City base map, available at:
* http://www.nyc.gov/html/dcp/html/bytes/dwnlion.shtml Download the MapInfo file. This
* must be converted to a ShapeFile. unzip nyc_lion09ami.zip ogr2ogr -f 'ESRI Shapefile'
* nyc_streets/streets.shp lion/MNLION1.tab ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/SILION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/QNLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BKLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BXLION1.tab -nln streets
*
* It also requires the NYC Subway data in GTFS: cd src/test/resources wget
* http://data.topplabs.org/data/mta_nyct_subway/subway.zip
*/
return;
}
ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
ShapefileStreetSchema schema = new ShapefileStreetSchema();
schema.setIdAttribute("StreetCode");
schema.setNameAttribute("Street");
CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
forward.addPermission("W", StreetTraversalPermission.ALL);
reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY);
forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY);
reverse.addPermission("A", StreetTraversalPermission.ALL);
forward.addPermission("T", StreetTraversalPermission.ALL);
reverse.addPermission("T", StreetTraversalPermission.ALL);
schema.setForwardPermissionConverter(forward);
schema.setReversePermissionConverter(reverse);
ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl();
loader.setFeatureSourceFactory(factory);
loader.setSchema(schema);
loader.buildGraph(gg);
assertEquals(104910,gg.getVertices().size());
Vertex start = gg.getVertex("PARK PL at VANDERBILT AV");
Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST");
assertNotNull(start);
assertNotNull(end);
}
| public void testBasic() throws Exception {
Graph gg = new Graph();
File file = new File("src/test/resources/nyc_streets/streets.shp");
if (!file.exists()) {
System.out.println("No New York City basemap; skipping; see comment here for details");
/*
* This test requires the New York City base map, available at:
* http://www.nyc.gov/html/dcp/html/bytes/dwnlion.shtml Download the MapInfo file. This
* must be converted to a ShapeFile. unzip nyc_lion09ami.zip ogr2ogr -f 'ESRI Shapefile'
* nyc_streets/streets.shp lion/MNLION1.tab ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/SILION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/QNLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BKLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BXLION1.tab -nln streets
*
* It also requires the NYC Subway data in GTFS: cd src/test/resources wget
* http://data.topplabs.org/data/mta_nyct_subway/subway.zip
*/
return;
}
ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
ShapefileStreetSchema schema = new ShapefileStreetSchema();
schema.setIdAttribute("StreetCode");
schema.setNameAttribute("Street");
CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
forward.addPermission("W", StreetTraversalPermission.ALL);
reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY);
forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY);
reverse.addPermission("A", StreetTraversalPermission.ALL);
forward.addPermission("T", StreetTraversalPermission.ALL);
reverse.addPermission("T", StreetTraversalPermission.ALL);
schema.setForwardPermissionConverter(forward);
schema.setReversePermissionConverter(reverse);
ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl();
loader.setFeatureSourceFactory(factory);
loader.setSchema(schema);
loader.buildGraph(gg);
assertEquals(104910,gg.getVertices().size());
Vertex start = gg.getVertex("PARK PL at VANDERBILT AV");
Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST");
assertNotNull(start);
assertNotNull(end);
}
|
diff --git a/src/com/android/phone/BluetoothHeadsetService.java b/src/com/android/phone/BluetoothHeadsetService.java
index 941f66ec..77e0c58c 100755
--- a/src/com/android/phone/BluetoothHeadsetService.java
+++ b/src/com/android/phone/BluetoothHeadsetService.java
@@ -1,923 +1,929 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAudioGateway;
import android.bluetooth.BluetoothAudioGateway.IncomingConnectionInfo;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothUuid;
import android.bluetooth.HeadsetBase;
import android.bluetooth.IBluetooth;
import android.bluetooth.IBluetoothHeadset;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelUuid;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Provides Bluetooth Headset and Handsfree profile, as a service in
* the Phone application.
* @hide
*/
public class BluetoothHeadsetService extends Service {
private static final String TAG = "Bluetooth HSHFP";
private static final boolean DBG = true;
private static final String PREF_NAME = BluetoothHeadsetService.class.getSimpleName();
private static final String PREF_LAST_HEADSET = "lastHeadsetAddress";
private static final int PHONE_STATE_CHANGED = 1;
private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
private static boolean sHasStarted = false;
private BluetoothDevice mDeviceSdpQuery;
private BluetoothAdapter mAdapter;
private IBluetooth mBluetoothService;
private PowerManager mPowerManager;
private BluetoothAudioGateway mAg;
private BluetoothHandsfree mBtHandsfree;
private HashMap<BluetoothDevice, BluetoothRemoteHeadset> mRemoteHeadsets;
private BluetoothDevice mAudioConnectedDevice;
@Override
public void onCreate() {
super.onCreate();
mAdapter = BluetoothAdapter.getDefaultAdapter();
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mBtHandsfree = PhoneApp.getInstance().getBluetoothHandsfree();
mAg = new BluetoothAudioGateway(mAdapter);
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(AudioManager.VOLUME_CHANGED_ACTION);
filter.addAction(BluetoothDevice.ACTION_UUID);
registerReceiver(mBluetoothReceiver, filter);
IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE);
if (b == null) {
throw new RuntimeException("Bluetooth service not available");
}
mBluetoothService = IBluetooth.Stub.asInterface(b);
mRemoteHeadsets = new HashMap<BluetoothDevice, BluetoothRemoteHeadset>();
}
private class BluetoothRemoteHeadset {
private int mState;
private int mAudioState;
private int mHeadsetType;
private HeadsetBase mHeadset;
private IncomingConnectionInfo mIncomingInfo;
BluetoothRemoteHeadset() {
mState = BluetoothProfile.STATE_DISCONNECTED;
mHeadsetType = BluetoothHandsfree.TYPE_UNKNOWN;
mHeadset = null;
mIncomingInfo = null;
mAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
}
BluetoothRemoteHeadset(int headsetType, IncomingConnectionInfo incomingInfo) {
mState = BluetoothProfile.STATE_DISCONNECTED;
mHeadsetType = headsetType;
mHeadset = null;
mIncomingInfo = incomingInfo;
mAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
}
}
synchronized private BluetoothDevice getCurrentDevice() {
for (BluetoothDevice device : mRemoteHeadsets.keySet()) {
int state = mRemoteHeadsets.get(device).mState;
if (state == BluetoothProfile.STATE_CONNECTING ||
state == BluetoothProfile.STATE_CONNECTED) {
return device;
}
}
return null;
}
@Override
public void onStart(Intent intent, int startId) {
if (mAdapter == null) {
Log.w(TAG, "Stopping BluetoothHeadsetService: device does not have BT");
stopSelf();
} else {
if (!sHasStarted) {
if (DBG) log("Starting BluetoothHeadsetService");
if (mAdapter.isEnabled()) {
mAg.start(mIncomingConnectionHandler);
mBtHandsfree.onBluetoothEnabled();
}
sHasStarted = true;
}
}
}
private final Handler mIncomingConnectionHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized(BluetoothHeadsetService.this) {
IncomingConnectionInfo info = (IncomingConnectionInfo)msg.obj;
int type = BluetoothHandsfree.TYPE_UNKNOWN;
switch(msg.what) {
case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION:
type = BluetoothHandsfree.TYPE_HEADSET;
break;
case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION:
type = BluetoothHandsfree.TYPE_HANDSFREE;
break;
}
Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) +
") connection from " + info.mRemoteDevice + "on channel " +
info.mRfcommChan);
int priority = BluetoothProfile.PRIORITY_OFF;
HeadsetBase headset;
priority = getPriority(info.mRemoteDevice);
if (priority <= BluetoothProfile.PRIORITY_OFF) {
Log.i(TAG, "Rejecting incoming connection because priority = " + priority);
headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan,
null);
headset.disconnect();
+ try {
+ mBluetoothService.notifyIncomingConnection(info.mRemoteDevice.getAddress(),
+ true);
+ } catch (RemoteException e) {
+ Log.e(TAG, "notifyIncomingConnection", e);
+ }
return;
}
BluetoothRemoteHeadset remoteHeadset;
BluetoothDevice device = getCurrentDevice();
int state = BluetoothProfile.STATE_DISCONNECTED;
if (device != null) {
state = mRemoteHeadsets.get(device).mState;
}
switch (state) {
case BluetoothProfile.STATE_DISCONNECTED:
// headset connecting us, lets join
remoteHeadset = new BluetoothRemoteHeadset(type, info);
mRemoteHeadsets.put(info.mRemoteDevice, remoteHeadset);
try {
mBluetoothService.notifyIncomingConnection(
- info.mRemoteDevice.getAddress());
+ info.mRemoteDevice.getAddress(), false);
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection");
}
break;
case BluetoothProfile.STATE_CONNECTING:
if (!info.mRemoteDevice.equals(device)) {
// different headset, ignoring
Log.i(TAG, "Already attempting connect to " + device +
", disconnecting " + info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan,
null);
headset.disconnect();
break;
}
// Incoming and Outgoing connections to the same headset.
// The state machine manager will cancel outgoing and accept the incoming one.
// Update the state
mRemoteHeadsets.get(info.mRemoteDevice).mHeadsetType = type;
mRemoteHeadsets.get(info.mRemoteDevice).mIncomingInfo = info;
try {
mBluetoothService.notifyIncomingConnection(
- info.mRemoteDevice.getAddress());
+ info.mRemoteDevice.getAddress(), false);
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection");
}
break;
case BluetoothProfile.STATE_CONNECTED:
Log.i(TAG, "Already connected to " + device + ", disconnecting " +
info.mRemoteDevice);
rejectIncomingConnection(info);
break;
}
}
}
};
private void rejectIncomingConnection(IncomingConnectionInfo info) {
HeadsetBase headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
}
private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BluetoothDevice currDevice = getCurrentDevice();
int state = BluetoothProfile.STATE_DISCONNECTED;
if (currDevice != null) {
state = mRemoteHeadsets.get(currDevice).mState;
}
if ((state == BluetoothProfile.STATE_CONNECTED ||
state == BluetoothProfile.STATE_CONNECTING) &&
action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED) &&
device.equals(currDevice)) {
try {
mBinder.disconnect(currDevice);
} catch (RemoteException e) {}
} else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
switch (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR)) {
case BluetoothAdapter.STATE_ON:
mAg.start(mIncomingConnectionHandler);
mBtHandsfree.onBluetoothEnabled();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
mBtHandsfree.onBluetoothDisabled();
mAg.stop();
if (currDevice != null) {
try {
mBinder.disconnect(currDevice);
} catch (RemoteException e) {}
}
break;
}
} else if (action.equals(AudioManager.VOLUME_CHANGED_ACTION)) {
int streamType = intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, -1);
if (streamType == AudioManager.STREAM_BLUETOOTH_SCO) {
mBtHandsfree.sendScoGainUpdate(intent.getIntExtra(
AudioManager.EXTRA_VOLUME_STREAM_VALUE, 0));
}
} else if (action.equals(BluetoothDevice.ACTION_UUID)) {
if (device.equals(mDeviceSdpQuery) && device.equals(currDevice)) {
// We have got SDP records for the device we are interested in.
getSdpRecordsAndConnect(device);
}
}
}
};
private static final int CONNECT_HEADSET_DELAYED = 1;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case CONNECT_HEADSET_DELAYED:
BluetoothDevice device = (BluetoothDevice) msg.obj;
getSdpRecordsAndConnect(device);
break;
}
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// ------------------------------------------------------------------
// Bluetooth Headset Connect
// ------------------------------------------------------------------
private static final int RFCOMM_CONNECTED = 1;
private static final int RFCOMM_ERROR = 2;
private long mTimestamp;
/**
* Thread for RFCOMM connection
* Messages are sent to mConnectingStatusHandler as connection progresses.
*/
private RfcommConnectThread mConnectThread;
private class RfcommConnectThread extends Thread {
private BluetoothDevice device;
private int channel;
private int type;
private static final int EINTERRUPT = -1000;
private static final int ECONNREFUSED = -111;
public RfcommConnectThread(BluetoothDevice device, int channel, int type) {
super();
this.device = device;
this.channel = channel;
this.type = type;
}
private int waitForConnect(HeadsetBase headset) {
// Try to connect for 20 seconds
int result = 0;
for (int i=0; i < 40 && result == 0; i++) {
// waitForAsyncConnect returns 0 on timeout, 1 on success, < 0 on error.
result = headset.waitForAsyncConnect(500, mConnectedStatusHandler);
if (isInterrupted()) {
headset.disconnect();
return EINTERRUPT;
}
}
return result;
}
@Override
public void run() {
long timestamp;
timestamp = System.currentTimeMillis();
HeadsetBase headset = new HeadsetBase(mPowerManager, mAdapter,
device, channel);
int result = waitForConnect(headset);
if (result != EINTERRUPT && result != 1) {
if (result == ECONNREFUSED && mDeviceSdpQuery == null) {
// The rfcomm channel number might have changed, do SDP
// query and try to connect again.
mDeviceSdpQuery = getCurrentDevice();
device.fetchUuidsWithSdp();
mConnectThread = null;
return;
} else {
Log.i(TAG, "Trying to connect to rfcomm socket again after 1 sec");
try {
sleep(1000); // 1 second
} catch (InterruptedException e) {
return;
}
}
result = waitForConnect(headset);
}
mDeviceSdpQuery = null;
if (result == EINTERRUPT) return;
if (DBG) log("RFCOMM connection attempt took " +
(System.currentTimeMillis() - timestamp) + " ms");
if (isInterrupted()) {
headset.disconnect();
return;
}
if (result < 0) {
Log.w(TAG, "headset.waitForAsyncConnect() error: " + result);
mConnectingStatusHandler.obtainMessage(RFCOMM_ERROR).sendToTarget();
return;
} else if (result == 0) {
mConnectingStatusHandler.obtainMessage(RFCOMM_ERROR).sendToTarget();
Log.w(TAG, "mHeadset.waitForAsyncConnect() error: " + result + "(timeout)");
return;
} else {
mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget();
}
}
}
/**
* Receives events from mConnectThread back in the main thread.
*/
private final Handler mConnectingStatusHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
BluetoothDevice device = getCurrentDevice();
if (device == null ||
mRemoteHeadsets.get(device).mState != BluetoothProfile.STATE_CONNECTING) {
return; // stale events
}
switch (msg.what) {
case RFCOMM_ERROR:
if (DBG) log("Rfcomm error");
mConnectThread = null;
setState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
case RFCOMM_CONNECTED:
if (DBG) log("Rfcomm connected");
mConnectThread = null;
HeadsetBase headset = (HeadsetBase)msg.obj;
setState(device, BluetoothProfile.STATE_CONNECTED);
mRemoteHeadsets.get(device).mHeadset = headset;
mBtHandsfree.connectHeadset(headset, mRemoteHeadsets.get(device).mHeadsetType);
break;
}
}
};
/**
* Receives events from a connected RFCOMM socket back in the main thread.
*/
private final Handler mConnectedStatusHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HeadsetBase.RFCOMM_DISCONNECTED:
mBtHandsfree.resetAtState();
mBtHandsfree.setVirtualCallInProgress(false);
BluetoothDevice device = getCurrentDevice();
if (device != null) {
setState(device, BluetoothProfile.STATE_DISCONNECTED);
}
break;
}
}
};
private synchronized void setState(BluetoothDevice device, int state) {
int prevState = mRemoteHeadsets.get(device).mState;
if (state != prevState) {
if (DBG) log("Device: " + device +
" Headset state" + prevState + " -> " + state);
if (prevState == BluetoothProfile.STATE_CONNECTED) {
// Headset is disconnecting, stop the parser.
mBtHandsfree.disconnectHeadset();
}
Intent intent = new Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothProfile.EXTRA_STATE, state);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
if (state == BluetoothProfile.STATE_DISCONNECTED) {
mRemoteHeadsets.get(device).mHeadset = null;
mRemoteHeadsets.get(device).mHeadsetType = BluetoothHandsfree.TYPE_UNKNOWN;
}
mRemoteHeadsets.get(device).mState = state;
sendBroadcast(intent, BLUETOOTH_PERM);
if (state == BluetoothHeadset.STATE_CONNECTED) {
// Set the priority to AUTO_CONNECT
setPriority(device, BluetoothHeadset.PRIORITY_AUTO_CONNECT);
adjustOtherHeadsetPriorities(device);
}
try {
mBluetoothService.sendConnectionStateChange(device, BluetoothProfile.HEADSET,
state, prevState);
} catch (RemoteException e) {
Log.e(TAG, "sendConnectionStateChange: exception");
}
}
}
private void adjustOtherHeadsetPriorities(BluetoothDevice connectedDevice) {
for (BluetoothDevice device : mAdapter.getBondedDevices()) {
if (getPriority(device) >= BluetoothHeadset.PRIORITY_AUTO_CONNECT &&
!device.equals(connectedDevice)) {
setPriority(device, BluetoothHeadset.PRIORITY_ON);
}
}
}
private void setPriority(BluetoothDevice device, int priority) {
try {
mBinder.setPriority(device, priority);
} catch (RemoteException e) {
Log.e(TAG, "Error while setting priority for: " + device);
}
}
private int getPriority(BluetoothDevice device) {
try {
return mBinder.getPriority(device);
} catch (RemoteException e) {
Log.e(TAG, "Error while getting priority for: " + device);
}
return BluetoothProfile.PRIORITY_UNDEFINED;
}
private synchronized void getSdpRecordsAndConnect(BluetoothDevice device) {
if (!device.equals(getCurrentDevice())) {
// stale
return;
}
// Check if incoming connection has already connected.
if (mRemoteHeadsets.get(device).mState == BluetoothProfile.STATE_CONNECTED) {
return;
}
ParcelUuid[] uuids = device.getUuids();
ParcelUuid[] localUuids = mAdapter.getUuids();
int type = BluetoothHandsfree.TYPE_UNKNOWN;
if (uuids != null) {
if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Handsfree) &&
BluetoothUuid.isUuidPresent(localUuids, BluetoothUuid.Handsfree_AG)) {
log("SDP UUID: TYPE_HANDSFREE");
type = BluetoothHandsfree.TYPE_HANDSFREE;
mRemoteHeadsets.get(device).mHeadsetType = type;
int channel = device.getServiceChannel(BluetoothUuid.Handsfree);
mConnectThread = new RfcommConnectThread(device, channel, type);
if (mAdapter.isDiscovering()) {
mAdapter.cancelDiscovery();
}
mConnectThread.start();
if (getPriority(device) < BluetoothHeadset.PRIORITY_AUTO_CONNECT) {
setPriority(device, BluetoothHeadset.PRIORITY_AUTO_CONNECT);
}
return;
} else if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.HSP) &&
BluetoothUuid.isUuidPresent(localUuids, BluetoothUuid.HSP_AG)) {
log("SDP UUID: TYPE_HEADSET");
type = BluetoothHandsfree.TYPE_HEADSET;
mRemoteHeadsets.get(device).mHeadsetType = type;
int channel = device.getServiceChannel(BluetoothUuid.HSP);
mConnectThread = new RfcommConnectThread(device, channel, type);
if (mAdapter.isDiscovering()) {
mAdapter.cancelDiscovery();
}
mConnectThread.start();
if (getPriority(device) < BluetoothHeadset.PRIORITY_AUTO_CONNECT) {
setPriority(device, BluetoothHeadset.PRIORITY_AUTO_CONNECT);
}
return;
}
}
log("SDP UUID: TYPE_UNKNOWN");
mRemoteHeadsets.get(device).mHeadsetType = type;
setState(device, BluetoothProfile.STATE_DISCONNECTED);
return;
}
/**
* Handlers for incoming service calls
*/
private final IBluetoothHeadset.Stub mBinder = new IBluetoothHeadset.Stub() {
public int getConnectionState(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
BluetoothRemoteHeadset headset = mRemoteHeadsets.get(device);
if (headset == null) {
return BluetoothProfile.STATE_DISCONNECTED;
}
return headset.mState;
}
public List<BluetoothDevice> getConnectedDevices() {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
return getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED});
}
public boolean connect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
synchronized (BluetoothHeadsetService.this) {
BluetoothDevice currDevice = getCurrentDevice();
if (currDevice == device ||
getPriority(device) == BluetoothProfile.PRIORITY_OFF) {
return false;
}
if (currDevice != null) {
disconnect(currDevice);
}
try {
return mBluetoothService.connectHeadset(device.getAddress());
} catch (RemoteException e) {
Log.e(TAG, "connectHeadset");
return false;
}
}
}
public boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
synchronized (BluetoothHeadsetService.this) {
BluetoothRemoteHeadset headset = mRemoteHeadsets.get(device);
if (headset == null ||
headset.mState == BluetoothProfile.STATE_DISCONNECTED ||
headset.mState == BluetoothProfile.STATE_DISCONNECTING) {
return false;
}
try {
return mBluetoothService.disconnectHeadset(device.getAddress());
} catch (RemoteException e) {
Log.e(TAG, "disconnectHeadset");
return false;
}
}
}
public synchronized boolean isAudioConnected(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
if (device.equals(mAudioConnectedDevice)) return true;
return false;
}
public synchronized List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
List<BluetoothDevice> headsets = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device: mRemoteHeadsets.keySet()) {
int headsetState = getConnectionState(device);
for (int state : states) {
if (state == headsetState) {
headsets.add(device);
break;
}
}
}
return headsets;
}
public boolean startVoiceRecognition(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
synchronized (BluetoothHeadsetService.this) {
if (device == null ||
mRemoteHeadsets.get(device) == null ||
mRemoteHeadsets.get(device).mState != BluetoothProfile.STATE_CONNECTED) {
return false;
}
return mBtHandsfree.startVoiceRecognition();
}
}
public boolean stopVoiceRecognition(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
synchronized (BluetoothHeadsetService.this) {
if (device == null ||
mRemoteHeadsets.get(device) == null ||
mRemoteHeadsets.get(device).mState != BluetoothProfile.STATE_CONNECTED) {
return false;
}
return mBtHandsfree.stopVoiceRecognition();
}
}
public int getBatteryUsageHint(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
return HeadsetBase.getAtInputCount();
}
public int getPriority(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
synchronized (BluetoothHeadsetService.this) {
int priority = Settings.Secure.getInt(getContentResolver(),
Settings.Secure.getBluetoothHeadsetPriorityKey(device.getAddress()),
BluetoothProfile.PRIORITY_UNDEFINED);
return priority;
}
}
public boolean setPriority(BluetoothDevice device, int priority) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
synchronized (BluetoothHeadsetService.this) {
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.getBluetoothHeadsetPriorityKey(device.getAddress()),
priority);
if (DBG) log("Saved priority " + device + " = " + priority);
return true;
}
}
public boolean createIncomingConnect(BluetoothDevice device) {
synchronized (BluetoothHeadsetService.this) {
HeadsetBase headset;
setState(device, BluetoothProfile.STATE_CONNECTING);
IncomingConnectionInfo info = mRemoteHeadsets.get(device).mIncomingInfo;
headset = new HeadsetBase(mPowerManager, mAdapter,
device,
info.mSocketFd, info.mRfcommChan,
mConnectedStatusHandler);
mRemoteHeadsets.get(device).mHeadset = headset;
mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget();
return true;
}
}
public boolean startScoUsingVirtualVoiceCall(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
synchronized (BluetoothHeadsetService.this) {
if (device == null ||
mRemoteHeadsets.get(device) == null ||
mRemoteHeadsets.get(device).mState != BluetoothProfile.STATE_CONNECTED ||
getAudioState(device) != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
return false;
}
return mBtHandsfree.initiateScoUsingVirtualVoiceCall();
}
}
public boolean stopScoUsingVirtualVoiceCall(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
synchronized (BluetoothHeadsetService.this) {
if (device == null ||
mRemoteHeadsets.get(device) == null ||
mRemoteHeadsets.get(device).mState != BluetoothProfile.STATE_CONNECTED ||
getAudioState(device) == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
return false;
}
return mBtHandsfree.terminateScoUsingVirtualVoiceCall();
}
}
public boolean rejectIncomingConnect(BluetoothDevice device) {
synchronized (BluetoothHeadsetService.this) {
BluetoothRemoteHeadset headset = mRemoteHeadsets.get(device);
if (headset != null) {
IncomingConnectionInfo info = headset.mIncomingInfo;
rejectIncomingConnection(info);
} else {
Log.e(TAG, "Error no record of remote headset");
}
return true;
}
}
public boolean acceptIncomingConnect(BluetoothDevice device) {
synchronized (BluetoothHeadsetService.this) {
HeadsetBase headset;
BluetoothRemoteHeadset cachedHeadset = mRemoteHeadsets.get(device);
if (cachedHeadset == null) {
Log.e(TAG, "Cached Headset is Null in acceptIncomingConnect");
return false;
}
IncomingConnectionInfo info = cachedHeadset.mIncomingInfo;
headset = new HeadsetBase(mPowerManager, mAdapter,
device,
info.mSocketFd, info.mRfcommChan,
mConnectedStatusHandler);
setState(device, BluetoothProfile.STATE_CONNECTED);
cachedHeadset.mHeadset = headset;
mBtHandsfree.connectHeadset(headset, cachedHeadset.mHeadsetType);
if (DBG) log("Successfully used incoming connection");
return true;
}
}
public boolean cancelConnectThread() {
synchronized (BluetoothHeadsetService.this) {
if (mConnectThread != null) {
// cancel the connection thread
mConnectThread.interrupt();
try {
mConnectThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Connection cancelled twice?", e);
}
mConnectThread = null;
}
return true;
}
}
public boolean connectHeadsetInternal(BluetoothDevice device) {
synchronized (BluetoothHeadsetService.this) {
BluetoothDevice currDevice = getCurrentDevice();
if (currDevice == null) {
BluetoothRemoteHeadset headset = new BluetoothRemoteHeadset();
mRemoteHeadsets.put(device, headset);
setState(device, BluetoothProfile.STATE_CONNECTING);
if (device.getUuids() == null) {
// We might not have got the UUID change notification from
// Bluez yet, if we have just paired. Try after 1.5 secs.
Message msg = new Message();
msg.what = CONNECT_HEADSET_DELAYED;
msg.obj = device;
mHandler.sendMessageDelayed(msg, 1500);
} else {
getSdpRecordsAndConnect(device);
}
return true;
} else {
Log.w(TAG, "connectHeadset(" + device + "): failed: already in state " +
mRemoteHeadsets.get(currDevice).mState +
" with headset " + currDevice);
}
return false;
}
}
public boolean disconnectHeadsetInternal(BluetoothDevice device) {
synchronized (BluetoothHeadsetService.this) {
BluetoothRemoteHeadset remoteHeadset = mRemoteHeadsets.get(device);
if (remoteHeadset == null) return false;
if (remoteHeadset.mState == BluetoothProfile.STATE_CONNECTED) {
// Send a dummy battery level message to force headset
// out of sniff mode so that it will immediately notice
// the disconnection. We are currently sending it for
// handsfree only.
// TODO: Call hci_conn_enter_active_mode() from
// rfcomm_send_disc() in the kernel instead.
// See http://b/1716887
setState(device, BluetoothProfile.STATE_DISCONNECTING);
HeadsetBase headset = remoteHeadset.mHeadset;
if (remoteHeadset.mHeadsetType == BluetoothHandsfree.TYPE_HANDSFREE) {
headset.sendURC("+CIEV: 7,3");
}
if (headset != null) {
headset.disconnect();
headset = null;
}
setState(device, BluetoothProfile.STATE_DISCONNECTED);
return true;
} else if (remoteHeadset.mState == BluetoothProfile.STATE_CONNECTING) {
// The state machine would have canceled the connect thread.
// Just set the state here.
setState(device, BluetoothProfile.STATE_DISCONNECTED);
return true;
}
return false;
}
}
public boolean setAudioState(BluetoothDevice device, int state) {
synchronized (BluetoothHeadsetService.this) {
int prevState = mRemoteHeadsets.get(device).mAudioState;
mRemoteHeadsets.get(device).mAudioState = state;
if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
mAudioConnectedDevice = device;
} else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
mAudioConnectedDevice = null;
}
Intent intent = new Intent(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
intent.putExtra(BluetoothHeadset.EXTRA_STATE, state);
intent.putExtra(BluetoothHeadset.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
sendBroadcast(intent, android.Manifest.permission.BLUETOOTH);
if (DBG) log("AudioStateIntent: " + device + " State: " + state
+ " PrevState: " + prevState);
return true;
}
}
public int getAudioState(BluetoothDevice device) {
synchronized (BluetoothHeadsetService.this) {
BluetoothRemoteHeadset headset = mRemoteHeadsets.get(device);
if (headset == null) return BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
return headset.mAudioState;
}
}
};
@Override
public void onDestroy() {
super.onDestroy();
if (DBG) log("Stopping BluetoothHeadsetService");
unregisterReceiver(mBluetoothReceiver);
mBtHandsfree.onBluetoothDisabled();
mAg.stop();
sHasStarted = false;
BluetoothDevice device = getCurrentDevice();
if (device != null) {
setState(device, BluetoothProfile.STATE_DISCONNECTED);
}
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
| false | true | public void handleMessage(Message msg) {
synchronized(BluetoothHeadsetService.this) {
IncomingConnectionInfo info = (IncomingConnectionInfo)msg.obj;
int type = BluetoothHandsfree.TYPE_UNKNOWN;
switch(msg.what) {
case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION:
type = BluetoothHandsfree.TYPE_HEADSET;
break;
case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION:
type = BluetoothHandsfree.TYPE_HANDSFREE;
break;
}
Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) +
") connection from " + info.mRemoteDevice + "on channel " +
info.mRfcommChan);
int priority = BluetoothProfile.PRIORITY_OFF;
HeadsetBase headset;
priority = getPriority(info.mRemoteDevice);
if (priority <= BluetoothProfile.PRIORITY_OFF) {
Log.i(TAG, "Rejecting incoming connection because priority = " + priority);
headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan,
null);
headset.disconnect();
return;
}
BluetoothRemoteHeadset remoteHeadset;
BluetoothDevice device = getCurrentDevice();
int state = BluetoothProfile.STATE_DISCONNECTED;
if (device != null) {
state = mRemoteHeadsets.get(device).mState;
}
switch (state) {
case BluetoothProfile.STATE_DISCONNECTED:
// headset connecting us, lets join
remoteHeadset = new BluetoothRemoteHeadset(type, info);
mRemoteHeadsets.put(info.mRemoteDevice, remoteHeadset);
try {
mBluetoothService.notifyIncomingConnection(
info.mRemoteDevice.getAddress());
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection");
}
break;
case BluetoothProfile.STATE_CONNECTING:
if (!info.mRemoteDevice.equals(device)) {
// different headset, ignoring
Log.i(TAG, "Already attempting connect to " + device +
", disconnecting " + info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan,
null);
headset.disconnect();
break;
}
// Incoming and Outgoing connections to the same headset.
// The state machine manager will cancel outgoing and accept the incoming one.
// Update the state
mRemoteHeadsets.get(info.mRemoteDevice).mHeadsetType = type;
mRemoteHeadsets.get(info.mRemoteDevice).mIncomingInfo = info;
try {
mBluetoothService.notifyIncomingConnection(
info.mRemoteDevice.getAddress());
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection");
}
break;
case BluetoothProfile.STATE_CONNECTED:
Log.i(TAG, "Already connected to " + device + ", disconnecting " +
info.mRemoteDevice);
rejectIncomingConnection(info);
break;
}
}
}
| public void handleMessage(Message msg) {
synchronized(BluetoothHeadsetService.this) {
IncomingConnectionInfo info = (IncomingConnectionInfo)msg.obj;
int type = BluetoothHandsfree.TYPE_UNKNOWN;
switch(msg.what) {
case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION:
type = BluetoothHandsfree.TYPE_HEADSET;
break;
case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION:
type = BluetoothHandsfree.TYPE_HANDSFREE;
break;
}
Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) +
") connection from " + info.mRemoteDevice + "on channel " +
info.mRfcommChan);
int priority = BluetoothProfile.PRIORITY_OFF;
HeadsetBase headset;
priority = getPriority(info.mRemoteDevice);
if (priority <= BluetoothProfile.PRIORITY_OFF) {
Log.i(TAG, "Rejecting incoming connection because priority = " + priority);
headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan,
null);
headset.disconnect();
try {
mBluetoothService.notifyIncomingConnection(info.mRemoteDevice.getAddress(),
true);
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection", e);
}
return;
}
BluetoothRemoteHeadset remoteHeadset;
BluetoothDevice device = getCurrentDevice();
int state = BluetoothProfile.STATE_DISCONNECTED;
if (device != null) {
state = mRemoteHeadsets.get(device).mState;
}
switch (state) {
case BluetoothProfile.STATE_DISCONNECTED:
// headset connecting us, lets join
remoteHeadset = new BluetoothRemoteHeadset(type, info);
mRemoteHeadsets.put(info.mRemoteDevice, remoteHeadset);
try {
mBluetoothService.notifyIncomingConnection(
info.mRemoteDevice.getAddress(), false);
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection");
}
break;
case BluetoothProfile.STATE_CONNECTING:
if (!info.mRemoteDevice.equals(device)) {
// different headset, ignoring
Log.i(TAG, "Already attempting connect to " + device +
", disconnecting " + info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter,
info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan,
null);
headset.disconnect();
break;
}
// Incoming and Outgoing connections to the same headset.
// The state machine manager will cancel outgoing and accept the incoming one.
// Update the state
mRemoteHeadsets.get(info.mRemoteDevice).mHeadsetType = type;
mRemoteHeadsets.get(info.mRemoteDevice).mIncomingInfo = info;
try {
mBluetoothService.notifyIncomingConnection(
info.mRemoteDevice.getAddress(), false);
} catch (RemoteException e) {
Log.e(TAG, "notifyIncomingConnection");
}
break;
case BluetoothProfile.STATE_CONNECTED:
Log.i(TAG, "Already connected to " + device + ", disconnecting " +
info.mRemoteDevice);
rejectIncomingConnection(info);
break;
}
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/FrequencyAlight.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/FrequencyAlight.java
index f914f61dc..0d1a7844b 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/FrequencyAlight.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/FrequencyAlight.java
@@ -1,247 +1,247 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.Trip;
import org.opentripplanner.gtfs.GtfsLibrary;
import org.opentripplanner.routing.core.EdgeNarrative;
import org.opentripplanner.routing.core.RouteSpec;
import org.opentripplanner.routing.core.RoutingContext;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.ServiceDay;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.StateEditor;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.TraverseModeSet;
import org.opentripplanner.routing.graph.AbstractEdge;
import org.opentripplanner.routing.vertextype.TransitVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Geometry;
public class FrequencyAlight extends AbstractEdge implements OnBoardReverseEdge {
private static final long serialVersionUID = 3388162982920747289L;
private static final Logger _log = LoggerFactory.getLogger(FrequencyAlight.class);
private int stopIndex;
private FrequencyBasedTripPattern pattern;
private int modeMask;
public FrequencyAlight(TransitVertex from, TransitVertex to,
FrequencyBasedTripPattern pattern, int stopIndex, TraverseMode mode) {
super(from, to);
this.pattern = pattern;
this.stopIndex = stopIndex;
this.modeMask = new TraverseModeSet(mode).getMask();
}
public String getDirection() {
return null;
}
public double getDistance() {
return 0;
}
public Geometry getGeometry() {
return null;
}
public TraverseMode getMode() {
return TraverseMode.ALIGHTING;
}
public String getName() {
return "leave street network for transit network";
}
public State traverse(State state0) {
RoutingContext rctx = state0.getContext();
RoutingRequest options = state0.getOptions();
Trip trip = pattern.getTrip();
if (options.isArriveBy()) {
/* backward traversal: find a transit trip on this pattern */
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding time */
/*
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to
* initial state) if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long currentTime = state0.getTime();
int bestWait = -1;
int bestPatternIndex = -1;
TraverseMode mode = state0.getNonTransitMode(options);
if (options.bannedTrips.contains(trip.getId())) {
//This behaves a little differently than with ordinary trip patterns,
//because trips don't really have strong identities in frequency-based
//plans. I expect that reasonable plans will still be produced, since
//we used to use route banning and that was not so bad.
return null;
}
AgencyAndId serviceId = trip.getServiceId();
for (ServiceDay sd : rctx.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(currentTime);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
if (secondsSinceMidnight < 0)
continue;
if (sd.serviceIdRunning(serviceId)) {
int startTime = pattern.getPreviousArrivalTime(stopIndex, secondsSinceMidnight,
options.wheelchairAccessible, mode == TraverseMode.BICYCLE, true);
if (startTime >= 0) {
// a trip was found, wait will be non-negative
- int wait = (int) (sd.time(startTime) - currentTime);
+ int wait = (int) (currentTime - sd.time(startTime));
if (wait < 0)
- _log.error("negative wait time on board");
+ _log.error("negative wait time on alight");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
}
}
}
}
if (bestWait < 0) {
return null;
}
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan */
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
int type = pattern.getBoardType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTrip(bestPatternIndex);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(pattern.getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
long wait_cost = bestWait;
if (state0.getNumBoardings() == 0) {
wait_cost *= options.waitAtBeginningFactor;
} else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
s1.incrementWeight(wait_cost + options.getBoardCost(mode));
return s1.makeState();
} else {
/* forward traversal: not so much to do */
// do not alight immediately when arrive-depart dwell has been eliminated
// this affects multi-itinerary searches
if (state0.getBackEdge() instanceof FrequencyAlight) {
return null;
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
int type = pattern.getBoardType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(fromv);
return s1.makeState();
}
}
public State optimisticTraverse(State state0) {
StateEditor s1 = state0.edit(this);
// no cost (see patternalight)
return s1.makeState();
}
/* See weightLowerBound comment. */
public double timeLowerBound(RoutingContext rctx) {
if (rctx.opt.isArriveBy()) {
if (! rctx.opt.getModes().get(modeMask)) {
return Double.POSITIVE_INFINITY;
}
AgencyAndId serviceId = pattern.getTrip().getServiceId();
for (ServiceDay sd : rctx.serviceDays)
if (sd.serviceIdRunning(serviceId))
return 0;
return Double.POSITIVE_INFINITY;
} else {
return 0;
}
}
/*
* If the main search is proceeding backward, the lower bound search is proceeding forward.
* Check the mode or serviceIds of this pattern at board time to see whether this pattern is
* worth exploring. If the main search is proceeding forward, board cost is added at board
* edges. The lower bound search is proceeding backward, and if it has reached a board edge the
* pattern was already deemed useful.
*/
public double weightLowerBound(RoutingRequest options) {
if (options.isArriveBy())
return timeLowerBound(options);
else
return options.getBoardCostLowerBound();
}
public int getStopIndex() {
return stopIndex;
}
public String toString() {
return "PatternBoard(" + getFromVertex() + ", " + getToVertex() + ")";
}
}
| false | true | public State traverse(State state0) {
RoutingContext rctx = state0.getContext();
RoutingRequest options = state0.getOptions();
Trip trip = pattern.getTrip();
if (options.isArriveBy()) {
/* backward traversal: find a transit trip on this pattern */
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding time */
/*
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to
* initial state) if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long currentTime = state0.getTime();
int bestWait = -1;
int bestPatternIndex = -1;
TraverseMode mode = state0.getNonTransitMode(options);
if (options.bannedTrips.contains(trip.getId())) {
//This behaves a little differently than with ordinary trip patterns,
//because trips don't really have strong identities in frequency-based
//plans. I expect that reasonable plans will still be produced, since
//we used to use route banning and that was not so bad.
return null;
}
AgencyAndId serviceId = trip.getServiceId();
for (ServiceDay sd : rctx.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(currentTime);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
if (secondsSinceMidnight < 0)
continue;
if (sd.serviceIdRunning(serviceId)) {
int startTime = pattern.getPreviousArrivalTime(stopIndex, secondsSinceMidnight,
options.wheelchairAccessible, mode == TraverseMode.BICYCLE, true);
if (startTime >= 0) {
// a trip was found, wait will be non-negative
int wait = (int) (sd.time(startTime) - currentTime);
if (wait < 0)
_log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
}
}
}
}
if (bestWait < 0) {
return null;
}
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan */
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
int type = pattern.getBoardType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTrip(bestPatternIndex);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(pattern.getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
long wait_cost = bestWait;
if (state0.getNumBoardings() == 0) {
wait_cost *= options.waitAtBeginningFactor;
} else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
s1.incrementWeight(wait_cost + options.getBoardCost(mode));
return s1.makeState();
} else {
/* forward traversal: not so much to do */
// do not alight immediately when arrive-depart dwell has been eliminated
// this affects multi-itinerary searches
if (state0.getBackEdge() instanceof FrequencyAlight) {
return null;
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
int type = pattern.getBoardType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(fromv);
return s1.makeState();
}
}
| public State traverse(State state0) {
RoutingContext rctx = state0.getContext();
RoutingRequest options = state0.getOptions();
Trip trip = pattern.getTrip();
if (options.isArriveBy()) {
/* backward traversal: find a transit trip on this pattern */
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding time */
/*
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to
* initial state) if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long currentTime = state0.getTime();
int bestWait = -1;
int bestPatternIndex = -1;
TraverseMode mode = state0.getNonTransitMode(options);
if (options.bannedTrips.contains(trip.getId())) {
//This behaves a little differently than with ordinary trip patterns,
//because trips don't really have strong identities in frequency-based
//plans. I expect that reasonable plans will still be produced, since
//we used to use route banning and that was not so bad.
return null;
}
AgencyAndId serviceId = trip.getServiceId();
for (ServiceDay sd : rctx.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(currentTime);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
if (secondsSinceMidnight < 0)
continue;
if (sd.serviceIdRunning(serviceId)) {
int startTime = pattern.getPreviousArrivalTime(stopIndex, secondsSinceMidnight,
options.wheelchairAccessible, mode == TraverseMode.BICYCLE, true);
if (startTime >= 0) {
// a trip was found, wait will be non-negative
int wait = (int) (currentTime - sd.time(startTime));
if (wait < 0)
_log.error("negative wait time on alight");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
}
}
}
}
if (bestWait < 0) {
return null;
}
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan */
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
int type = pattern.getBoardType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTrip(bestPatternIndex);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(pattern.getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
long wait_cost = bestWait;
if (state0.getNumBoardings() == 0) {
wait_cost *= options.waitAtBeginningFactor;
} else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
s1.incrementWeight(wait_cost + options.getBoardCost(mode));
return s1.makeState();
} else {
/* forward traversal: not so much to do */
// do not alight immediately when arrive-depart dwell has been eliminated
// this affects multi-itinerary searches
if (state0.getBackEdge() instanceof FrequencyAlight) {
return null;
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
int type = pattern.getBoardType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(fromv);
return s1.makeState();
}
}
|
diff --git a/src/main/java/fnug/ResourceServlet.java b/src/main/java/fnug/ResourceServlet.java
index f85a74c..8e196c6 100644
--- a/src/main/java/fnug/ResourceServlet.java
+++ b/src/main/java/fnug/ResourceServlet.java
@@ -1,442 +1,445 @@
package fnug;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import fnug.resource.Bundle;
import fnug.resource.DefaultResource;
import fnug.resource.Resource;
import fnug.resource.ResourceResolver;
import fnug.servlet.BadArg;
import fnug.servlet.Bootstrap;
import fnug.servlet.BundleNames;
import fnug.servlet.ToServe;
import fnug.servlet.ToServeBundle;
import fnug.servlet.ToServeResource;
/*
Copyright 2010 Martin Algesten
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.
*/
/**
* Servlet serving resources.
*
* @author Martin Algesten
*
*/
@SuppressWarnings("serial")
public class ResourceServlet extends HttpServlet {
private static final String PARAM_CALLBACK = "callback";
public static final String UTF_8 = "utf-8";
public static final String CONTENT_TYPE_JSON = "application/json; charset=utf-8";
public static final String CONTENT_TYPE_JS = "text/javascript; charset=utf8";
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
private static final String HEADER_LAST_MODIFIED = "Last-Modified";
private static final String HEADER_EXPIRES = "Expires";
private static final String HEADER_DATE = "Date";
private static final String HEADER_CACHE_CONTROL = "Cache-Control";
private static final String VALUE_GZIP = "gzip";
private static final long ONE_YEAR = 365l * 24l * 60l * 60l * 1000l;
private static final String PATH_IE_CSS = "/ie.css";
private static final String CHAR_SLASH = "/";
private static ThreadLocal<RequestEntry> reqEntry = new ThreadLocal<RequestEntry>();
private ResourceResolver resolver;
private ObjectMapper mapper = new ObjectMapper();
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
initResolver(config);
}
private void initResolver(ServletConfig config) throws ServletException {
String configStr = config.getInitParameter("config");
if (configStr == null) {
throw new ServletException("Missing config parameter 'config'");
}
String contextKey = ResourceResolver.class.getName() + "_" + configStr.hashCode();
resolver = (ResourceResolver) config.getServletContext().getAttribute(contextKey);
if (resolver == null) {
String[] configs = configStr.split("\\s*,\\s*");
LinkedList<Resource> resources = new LinkedList<Resource>();
// add internal config resources first.
resources.add(new DefaultResource("/fnug/", "bundles.js"));
for (String s : configs) {
// normalize windowz strings in config to only use forward slashes.
if (File.separatorChar == '\\') {
s = s.replace(File.separatorChar, '/');
}
String basePath = s.substring(0, s.lastIndexOf(CHAR_SLASH) + 1);
String path = s.substring(s.lastIndexOf(CHAR_SLASH) + 1);
resources.add(new DefaultResource(basePath, path));
}
resolver = new ResourceResolver(resources);
config.getServletContext().setAttribute(contextKey, resolver);
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String prefix = req.getContextPath() + req.getServletPath();
prefix = prefix.endsWith(CHAR_SLASH) ?
prefix.substring(0, prefix.length() - 1) : prefix;
if (req.getPathInfo().equals(PATH_IE_CSS)) {
serviceIeIncludeCss(prefix, req, resp);
return;
}
resolver.setThreadLocal();
resolver.checkModified();
String path = req.getPathInfo();
+ if (path == null) {
+ path = "";
+ }
String gzipHeader = req.getHeader(HEADER_ACCEPT_ENCODING);
boolean gzip = gzipHeader != null && gzipHeader.indexOf(VALUE_GZIP) >= 0;
String jsonp = req.getParameter(PARAM_CALLBACK);
if (jsonp != null && jsonp.trim().equals("")) {
jsonp = null;
}
RequestEntry entry = new RequestEntry(prefix, path, gzip, jsonp);
reqEntry.set(entry);
super.service(req, resp);
// when the servlet container does a 304 not modified, Content-Type is
// set to null, this often results in the Content-Type being set to a
// default by the servlet container or a web server/cache in front of
// the servlet container. Such deafult content type is often wrong about the
// original resource (text/plain or similar). By always setting the
// "correct" content type, we ensure to not pollute caches etc.
// according to the HTTP spec, it's okay to set any meta header about the
// content in a 304 as long as they are true for the original resource.
if (resp.getContentType() == null && !resp.isCommitted()) {
entry.setHeaders(resp);
}
reqEntry.remove();
}
private void serviceIeIncludeCss(String prefix, HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String f = req.getParameter("f");
if (f == null || f.equals("")) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing req param 'f'");
return;
}
String[] files = f.split(",");
resp.setContentType("text/css");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
for (String file : files) {
// this also serves as a protection against injecting strange
// stuff into the resulting style sheet.
Resource r = resolver.resolve(file);
if (r != null && r.isCss() && r.getLastModified() > 0) {
writer.println("@import url(" + prefix + "/" + file + ");");
}
}
}
@Override
protected long getLastModified(HttpServletRequest req) {
return reqEntry.get().getLastModified();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
reqEntry.get().serve(resp, false);
}
@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
reqEntry.get().serve(resp, true);
}
private class RequestEntry {
private static final String SUFFIX_JS = "js";
private static final String SUFFIX_ADD_JS = "add.js";
private static final String CHAR_DOT = ".";
private String prefix;
/**
* Full path: /some/path/to/file.js
*/
private String path;
/**
* The filename without suffix: file
*/
private String file;
/**
* The suffix: js
*/
private String suffix;
private Object toServe;
private byte[] toServeBytes;
private String jsonp;
private boolean gzip;
public RequestEntry(String prefix, String path, boolean gzip, String jsonp) {
this.prefix = prefix;
this.gzip = gzip;
this.jsonp = jsonp;
initPathFileSuffix(path);
initToServe();
initToServeBytes();
}
private void initPathFileSuffix(String inpath) {
if (inpath == null) {
inpath = "";
}
inpath = normalizePath(inpath);
int lastDot = inpath.lastIndexOf(CHAR_DOT);
path = inpath;
if (inpath.endsWith(SUFFIX_ADD_JS)) {
file = inpath.substring(0, inpath.length() - SUFFIX_ADD_JS.length() - 1);
suffix = SUFFIX_ADD_JS;
} else if (lastDot > inpath.lastIndexOf(CHAR_SLASH)) {
file = inpath.substring(0, lastDot);
suffix = inpath.substring(lastDot + 1);
} else {
file = inpath;
suffix = "";
}
}
private String normalizePath(String path) {
if (path.startsWith(CHAR_SLASH)) {
path = path.substring(1);
}
if (path.endsWith(CHAR_SLASH)) {
path = path.substring(0, path.length() - 1);
}
return path;
}
private void initToServe() {
try {
if (path.equals("")) {
toServe = new BundleNames(mapper, jsonp);
} else if (Bundle.BUNDLE_ALLOWED_CHARS.matcher(file).matches()) {
Bundle bundle = resolver.getBundle(file);
if (bundle != null) {
bundle.checkModified();
if (suffix.equals("")) {
toServe = new ToServeBundle(mapper, bundle, jsonp);
} else if (suffix.equals(SUFFIX_ADD_JS)) {
toServe = new Bootstrap(mapper, prefix, bundle, true);
} else if (suffix.equals(SUFFIX_JS)) {
toServe = new Bootstrap(mapper, prefix, bundle, false);
} else {
toServe = null;
}
}
}
if (toServe == null) {
Resource r = resolver.resolve(path);
if (r != null) {
r.checkModified();
}
toServe = r == null || r.getLastModified() == -1 ? null : new ToServeResource(r, jsonp);
}
} catch (IllegalArgumentException iae) {
toServe = new BadArg(iae.getMessage());
} catch (IllegalStateException ise) {
toServe = new BadArg(ise.getMessage());
}
}
private void initToServeBytes() {
if (toServe != null && toServe instanceof ToServe) {
toServeBytes = ((ToServe) toServe).getBytes();
if (gzip) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream os = new GZIPOutputStream(baos);
os.write(toServeBytes);
os.close();
toServeBytes = baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Failed to comress gzip", e);
}
}
}
}
public void serve(HttpServletResponse resp, boolean head) throws IOException {
if (head) {
// affects headers
gzip = false;
}
if (toServe == null) {
serve404(resp);
} else if (toServe instanceof BadArg) {
serve400(resp, ((BadArg) toServe).getMessage());
} else if (toServe instanceof ToServe) {
serveDefault(resp, head, (ToServe) toServe);
}
}
private void serve404(HttpServletResponse resp) throws IOException {
resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
}
private void serve400(HttpServletResponse resp, String msg) throws IOException {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
private void serveDefault(HttpServletResponse resp, boolean head, ToServe toServe) throws IOException {
setHeaders(resp);
if (gzip) {
resp.setHeader(HEADER_CONTENT_ENCODING, VALUE_GZIP);
}
if (!head) {
OutputStream os = resp.getOutputStream();
os.write(toServeBytes);
}
}
public void setHeaders(HttpServletResponse resp) {
if (toServe != null && toServe instanceof ToServe) {
ToServe t = (ToServe) toServe;
resp.setDateHeader(HEADER_DATE, System.currentTimeMillis());
resp.setContentType(t.getContentType());
resp.setContentLength(toServeBytes.length);
resp.setDateHeader(HEADER_LAST_MODIFIED, t.getLastModified());
// some web caches are buggy and can't handle compressed
// resources, in which
// case we must avoid polluting that cache.
String cacheControl = gzip ? "private" : "";
if (t.futureExpires()) {
resp.setDateHeader(HEADER_EXPIRES, System.currentTimeMillis() + ONE_YEAR);
cacheControl += ", max-age=" + (ONE_YEAR / 1000);
} else {
// by setting an expiration in the past, we make extra sure
// all caches and browsers are treating this object as not
// cacheable. This will however not interfere with
// Last-Modified magic.
resp.setDateHeader(HEADER_EXPIRES, t.getLastModified());
cacheControl += ", max-age=0";
}
if (cacheControl.startsWith(", ")) {
cacheControl = cacheControl.substring(2);
}
resp.setHeader(HEADER_CACHE_CONTROL, cacheControl);
}
}
public long getLastModified() {
if (toServe != null && toServe instanceof ToServe) {
return ((ToServe) toServe).getLastModified();
}
return -1;
}
}
}
| true | true | protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String prefix = req.getContextPath() + req.getServletPath();
prefix = prefix.endsWith(CHAR_SLASH) ?
prefix.substring(0, prefix.length() - 1) : prefix;
if (req.getPathInfo().equals(PATH_IE_CSS)) {
serviceIeIncludeCss(prefix, req, resp);
return;
}
resolver.setThreadLocal();
resolver.checkModified();
String path = req.getPathInfo();
String gzipHeader = req.getHeader(HEADER_ACCEPT_ENCODING);
boolean gzip = gzipHeader != null && gzipHeader.indexOf(VALUE_GZIP) >= 0;
String jsonp = req.getParameter(PARAM_CALLBACK);
if (jsonp != null && jsonp.trim().equals("")) {
jsonp = null;
}
RequestEntry entry = new RequestEntry(prefix, path, gzip, jsonp);
reqEntry.set(entry);
super.service(req, resp);
// when the servlet container does a 304 not modified, Content-Type is
// set to null, this often results in the Content-Type being set to a
// default by the servlet container or a web server/cache in front of
// the servlet container. Such deafult content type is often wrong about the
// original resource (text/plain or similar). By always setting the
// "correct" content type, we ensure to not pollute caches etc.
// according to the HTTP spec, it's okay to set any meta header about the
// content in a 304 as long as they are true for the original resource.
if (resp.getContentType() == null && !resp.isCommitted()) {
entry.setHeaders(resp);
}
reqEntry.remove();
}
| protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String prefix = req.getContextPath() + req.getServletPath();
prefix = prefix.endsWith(CHAR_SLASH) ?
prefix.substring(0, prefix.length() - 1) : prefix;
if (req.getPathInfo().equals(PATH_IE_CSS)) {
serviceIeIncludeCss(prefix, req, resp);
return;
}
resolver.setThreadLocal();
resolver.checkModified();
String path = req.getPathInfo();
if (path == null) {
path = "";
}
String gzipHeader = req.getHeader(HEADER_ACCEPT_ENCODING);
boolean gzip = gzipHeader != null && gzipHeader.indexOf(VALUE_GZIP) >= 0;
String jsonp = req.getParameter(PARAM_CALLBACK);
if (jsonp != null && jsonp.trim().equals("")) {
jsonp = null;
}
RequestEntry entry = new RequestEntry(prefix, path, gzip, jsonp);
reqEntry.set(entry);
super.service(req, resp);
// when the servlet container does a 304 not modified, Content-Type is
// set to null, this often results in the Content-Type being set to a
// default by the servlet container or a web server/cache in front of
// the servlet container. Such deafult content type is often wrong about the
// original resource (text/plain or similar). By always setting the
// "correct" content type, we ensure to not pollute caches etc.
// according to the HTTP spec, it's okay to set any meta header about the
// content in a 304 as long as they are true for the original resource.
if (resp.getContentType() == null && !resp.isCommitted()) {
entry.setHeaders(resp);
}
reqEntry.remove();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.