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/org/dasein/cloud/cloudstack/compute/VirtualMachines.java b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
index f12c7d0..de5e74f 100644
--- a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
+++ b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
@@ -1,1484 +1,1485 @@
/**
* Copyright (C) 2009-2013 enstratius, 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.dasein.cloud.cloudstack.compute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.Tag;
import org.dasein.cloud.cloudstack.CSCloud;
import org.dasein.cloud.cloudstack.CSException;
import org.dasein.cloud.cloudstack.CSMethod;
import org.dasein.cloud.cloudstack.CSServiceProvider;
import org.dasein.cloud.cloudstack.CSTopology;
import org.dasein.cloud.cloudstack.CSVersion;
import org.dasein.cloud.cloudstack.Param;
import org.dasein.cloud.cloudstack.network.Network;
import org.dasein.cloud.cloudstack.network.SecurityGroup;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.network.RawAddress;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.logicblaze.lingo.util.DefaultTimeoutMap;
public class VirtualMachines extends AbstractVMSupport {
static public final Logger logger = Logger.getLogger(VirtualMachines.class);
static private final String DEPLOY_VIRTUAL_MACHINE = "deployVirtualMachine";
static private final String DESTROY_VIRTUAL_MACHINE = "destroyVirtualMachine";
static private final String GET_VIRTUAL_MACHINE_PASSWORD = "getVMPassword";
static private final String LIST_VIRTUAL_MACHINES = "listVirtualMachines";
static private final String LIST_SERVICE_OFFERINGS = "listServiceOfferings";
static private final String REBOOT_VIRTUAL_MACHINE = "rebootVirtualMachine";
static private final String RESET_VIRTUAL_MACHINE_PASSWORD = "resetPasswordForVirtualMachine";
static private final String RESIZE_VIRTUAL_MACHINE = "scaleVirtualMachine";
static private final String START_VIRTUAL_MACHINE = "startVirtualMachine";
static private final String STOP_VIRTUAL_MACHINE = "stopVirtualMachine";
static private Properties cloudMappings;
static private Map<String,Map<String,String>> customNetworkMappings;
static private Map<String,Map<String,Set<String>>> customServiceMappings;
static private DefaultTimeoutMap productCache = new DefaultTimeoutMap();
private CSCloud provider;
public VirtualMachines(CSCloud provider) {
super(provider);
this.provider = provider;
}
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.alterVM");
try {
String productId = options.getProviderProductId();
if (vmId == null || options.getProviderProductId() == null) {
throw new CloudException("No vmid and/or product id set for this operation");
}
CSMethod method = new CSMethod(provider);
VirtualMachine vm = getVirtualMachine(vmId);
if (vm.getProductId().equals(productId)) {
return vm;
}
boolean restart = false;
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
restart = true;
stop(vmId, true);
}
long timeout = System.currentTimeMillis()+(CalendarWrapper.MINUTE*20L);
while (System.currentTimeMillis() < timeout) {
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
try {
Thread.sleep(15000L);
vm = getVirtualMachine(vmId);
}
catch (InterruptedException ignore) {}
}
else {
break;
}
}
vm = getVirtualMachine(vmId);
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
throw new CloudException("Unable to stop vm for scaling");
}
Document doc = method.get(method.buildUrl(RESIZE_VIRTUAL_MACHINE, new Param("id", vmId), new Param("serviceOfferingId", productId)), RESIZE_VIRTUAL_MACHINE);
NodeList matches = doc.getElementsByTagName("scalevirtualmachineresponse");
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
}
if( jobId == null ) {
throw new CloudException("Could not scale server");
}
Document responseDoc = provider.waitForJob(doc, "Scale Server");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
if (restart) {
start(vmId);
}
return vm;
}
}
}
if (restart) {
start(vmId);
}
return getVirtualMachine(vmId);
}
finally {
APITrace.end();
}
}
@Nullable
@Override
public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException {
return VMScalingCapabilities.getInstance(false,true,Requirement.NONE,Requirement.NONE);
}
@Override
public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException {
return 100;
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getProduct");
try {
for( Architecture architecture : Architecture.values() ) {
for( VirtualMachineProduct product : listProducts(architecture) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
}
if( logger.isDebugEnabled() ) {
logger.debug("Unknown product ID for cloud.com: " + productId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "virtual machine";
}
private String getRootPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.getPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(GET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), GET_VIRTUAL_MACHINE_PASSWORD);
if (doc != null){
NodeList matches = doc.getElementsByTagName("getvmpasswordresponse");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
NodeList nodes = attribute.getChildNodes();
for( int k=0; k<nodes.getLength(); k++ ) {
Node password = nodes.item(k);
name = password.getNodeName().toLowerCase();
if( password.getChildNodes().getLength() > 0 ) {
value = password.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("encryptedpassword") ) {
return value;
}
}
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
catch (CSException e) {
if (e.getHttpCode() == 431) {
logger.warn("No password found for vm "+serverId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getVirtualMachine");
try {
CSMethod method = new CSMethod(provider);
try {
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("id", serverId)), LIST_VIRTUAL_MACHINES);
NodeList matches = doc.getElementsByTagName("virtualmachine");
if( matches.getLength() < 1 ) {
return null;
}
for( int i=0; i<matches.getLength(); i++ ) {
VirtualMachine s = toVirtualMachine(matches.item(i));
if( s != null && s.getProviderVirtualMachineId().equals(serverId) ) {
return s;
}
}
}
catch( CloudException e ) {
if( e.getMessage().contains("does not exist") ) {
return null;
}
throw e;
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.OPTIONAL;
}
@Override
public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.identifyVlanRequirement");
try {
if( provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) ) {
return Requirement.NONE;
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request");
}
return (provider.getDataCenterServices().requiresNetwork(regionId) ? Requirement.REQUIRED : Requirement.OPTIONAL);
}
return Requirement.OPTIONAL;
}
finally {
APITrace.end();
}
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.isSubscribed");
try {
CSMethod method = new CSMethod(provider);
try {
method.get(method.buildUrl(CSTopology.LIST_ZONES, new Param("available", "true")), CSTopology.LIST_ZONES);
return true;
}
catch( CSException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == 401 || code == 531 ) {
return false;
}
throw e;
}
catch( CloudException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED ) {
return false;
}
throw e;
}
}
finally {
APITrace.end();
}
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return true;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.launch");
try {
String id = withLaunchOptions.getStandardProductId();
VirtualMachineProduct product = getProduct(id);
if( product == null ) {
throw new CloudException("Invalid product ID: " + id);
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
return launch22(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName(), withLaunchOptions.getBootstrapKey(), withLaunchOptions.getVlanId(), withLaunchOptions.getFirewallIds(), withLaunchOptions.getUserData());
}
else {
return launch21(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName());
}
}
finally {
APITrace.end();
}
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public @Nonnull VirtualMachine launch(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nonnull String inZoneId, @Nonnull String name, @Nonnull String description, @Nullable String usingKey, @Nullable String withVlanId, boolean withMonitoring, boolean asSandbox, @Nullable String[] protectedByFirewalls, @Nullable Tag ... tags) throws InternalException, CloudException {
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
StringBuilder userData = new StringBuilder();
if( tags != null && tags.length > 0 ) {
for( Tag tag : tags ) {
userData.append(tag.getKey());
userData.append("=");
userData.append(tag.getValue());
userData.append("\n");
}
}
else {
userData.append("created=Dasein Cloud\n");
}
return launch22(imageId, product, inZoneId, name, usingKey, withVlanId, protectedByFirewalls, userData.toString());
}
else {
return launch21(imageId, product, inZoneId, name);
}
}
private VirtualMachine launch21(String imageId, VirtualMachineProduct product, String inZoneId, String name) throws InternalException, CloudException {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, new Param("zoneId", getContext().getRegionId()), new Param("serviceOfferingId", product.getProviderProductId()), new Param("templateId", imageId), new Param("displayName", name) ), DEPLOY_VIRTUAL_MACHINE));
}
private void load() {
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/cloudMappings.cfg");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
Properties properties = new Properties();
String line;
while( (line = reader.readLine()) != null ) {
if( line.startsWith("#") ) {
continue;
}
int idx = line.indexOf('=');
if( idx < 0 || line.endsWith("=") ) {
continue;
}
String cloudUrl = line.substring(0, idx);
String cloudId = line.substring(idx+1);
properties.put(cloudUrl, cloudId);
}
cloudMappings = properties;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customNetworkMappings.cfg");
HashMap<String,Map<String,String>> mapping = new HashMap<String,Map<String,String>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String[] trueKey = ((String)key).split(",");
Map<String,String> current = mapping.get(trueKey[0]);
if( current == null ) {
current = new HashMap<String,String>();
mapping.put(trueKey[0], current);
}
current.put(trueKey[1], (String)properties.get(key));
}
customNetworkMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customServiceMappings.cfg");
HashMap<String,Map<String,Set<String>>> mapping = new HashMap<String,Map<String,Set<String>>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String value = (String)properties.get(key);
if( value != null ) {
String[] trueKey = ((String)key).split(",");
Map<String,Set<String>> tmp = mapping.get(trueKey[0]);
if( tmp == null ) {
tmp =new HashMap<String,Set<String>>();
mapping.put(trueKey[0], tmp);
}
TreeSet<String> m = new TreeSet<String>();
String[] offerings = value.split(",");
if( offerings == null || offerings.length < 1 ) {
m.add(value);
}
else {
Collections.addAll(m, offerings);
}
tmp.put(trueKey[1], m);
}
}
customServiceMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
}
private @Nonnull VirtualMachine launch22(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nullable String inZoneId, @Nonnull String name, @Nullable String withKeypair, @Nullable String targetVlanId, @Nullable String[] protectedByFirewalls, @Nullable String userData) throws InternalException, CloudException {
ProviderContext ctx = provider.getContext();
List<String> vlans = null;
if( ctx == null ) {
throw new InternalException("No context was provided for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new InternalException("No region is established for this request");
}
String prdId = product.getProviderProductId();
if( customNetworkMappings == null ) {
load();
}
if( customNetworkMappings != null ) {
String cloudId = cloudMappings.getProperty(ctx.getEndpoint());
if( cloudId != null ) {
Map<String,String> map = customNetworkMappings.get(cloudId);
if( map != null ) {
String id = map.get(prdId);
if( id != null ) {
targetVlanId = id;
}
}
}
}
if( targetVlanId != null && targetVlanId.length() < 1 ) {
targetVlanId = null;
}
if( userData == null ) {
userData = "";
}
String securityGroupIds = null;
Param[] params;
if( protectedByFirewalls != null && protectedByFirewalls.length > 0 ) {
StringBuilder str = new StringBuilder();
int idx = 0;
for( String fw : protectedByFirewalls ) {
fw = fw.trim();
if( !fw.equals("") ) {
str.append(fw);
if( (idx++) < protectedByFirewalls.length-1 ) {
str.append(",");
}
}
}
securityGroupIds = str.toString();
}
int count = 4;
if( userData != null && userData.length() > 0 ) {
count++;
}
if( withKeypair != null ) {
count++;
}
if( targetVlanId == null ) {
Network vlan = provider.getNetworkServices().getVlanSupport();
if( vlan != null && vlan.isSubscribed() ) {
if( provider.getDataCenterServices().requiresNetwork(regionId) ) {
vlans = vlan.findFreeNetworks();
}
}
}
else {
vlans = new ArrayList<String>();
vlans.add(targetVlanId);
}
if( vlans != null && vlans.size() > 0 ) {
count++;
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
if( !provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) && !provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
securityGroupIds = null;
}
else {
count++;
}
}
else if( provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
/*
String sgId = null;
if( withVlanId == null ) {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( fw.getName().equalsIgnoreCase("default") && fw.getProviderVlanId() == null ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().create("default", "Default security group");
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
if( sgId != null ) {
securityGroupIds = sgId;
}
}
else {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( (fw.getName().equalsIgnoreCase("default") || fw.getName().equalsIgnoreCase("default-" + withVlanId)) && withVlanId.equals(fw.getProviderVlanId()) ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().createInVLAN("default-" + withVlanId, "Default " + withVlanId + " security group", withVlanId);
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
}
if( sgId != null ) {
securityGroupIds = sgId;
count++;
}
*/
}
params = new Param[count];
params[0] = new Param("zoneId", getContext().getRegionId());
params[1] = new Param("serviceOfferingId", prdId);
params[2] = new Param("templateId", imageId);
params[3] = new Param("displayName", name);
int i = 4;
if( userData != null && userData.length() > 0 ) {
try {
params[i++] = new Param("userdata", new String(Base64.encodeBase64(userData.getBytes("utf-8")), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
e.printStackTrace();
}
}
if( withKeypair != null ) {
params[i++] = new Param("keypair", withKeypair);
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
params[i++] = new Param("securitygroupids", securityGroupIds);
}
if( vlans != null && vlans.size() > 0 ) {
CloudException lastError = null;
for( String withVlanId : vlans ) {
params[i] = new Param("networkIds", withVlanId);
try {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
catch( CloudException e ) {
if( e.getMessage().contains("sufficient address capacity") ) {
lastError = e;
continue;
}
throw e;
}
}
if( lastError == null ) {
throw lastError;
}
throw new CloudException("Unable to identify a network into which a VM can be launched");
}
else {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
}
private @Nonnull VirtualMachine launch(@Nonnull Document doc) throws InternalException, CloudException {
NodeList matches = doc.getElementsByTagName("deployvirtualmachineresponse");
String serverId = null;
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if( node != null && (node.getNodeName().equalsIgnoreCase("virtualmachineid") || node.getNodeName().equalsIgnoreCase("id")) ) {
serverId = node.getFirstChild().getNodeValue();
break;
}
else if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
if( serverId != null ) {
break;
}
}
if( serverId == null && jobId == null ) {
throw new CloudException("Could not launch server");
}
// TODO: very odd logic below; figure out what it thinks it is doing
VirtualMachine vm = null;
// have to wait on jobs as sometimes they fail and we need to bubble error message up
Document responseDoc = provider.waitForJob(doc, "Launch Server");
//parse vm from job completion response to capture vm passwords on initial launch.
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
return vm;
}
}
}
if (vm == null){
vm = getVirtualMachine(serverId);
}
if( vm == null ) {
throw new CloudException("No virtual machine provided: " + serverId);
}
return vm;
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return Collections.emptyList();
}
return support.listFirewallsForVM(vmId);
}
finally {
APITrace.end();
}
}
private void setFirewalls(@Nonnull VirtualMachine vm) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.setFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return;
}
ArrayList<String> ids = new ArrayList<String>();
Iterable<String> firewalls;
try {
firewalls = support.listFirewallsForVM(vm.getProviderVirtualMachineId());
} catch (Throwable t) {
logger.error("Problem listing firewalls (listSecurityGroups) for '" + vm.getProviderVirtualMachineId() + "': " + t.getMessage());
return;
}
for( String id : firewalls ) {
ids.add(id);
}
vm.setProviderFirewallIds(ids.toArray(new String[ids.size()]));
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listProducts");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was configured for this request");
}
Map<Architecture,Collection<VirtualMachineProduct>> cached;
String endpoint = provider.getContext().getEndpoint();
String accountId = provider.getContext().getAccountNumber();
String regionId = provider.getContext().getRegionId();
productCache.purge();
cached = (HashMap<Architecture, Collection<VirtualMachineProduct>>) productCache.get(endpoint+"_"+accountId+"_"+regionId);
if (cached != null && !cached.isEmpty()) {
if( cached.containsKey(architecture) ) {
Collection<VirtualMachineProduct> products = cached.get(architecture);
if( products != null ) {
return products;
}
}
}
else {
cached = new HashMap<Architecture, Collection<VirtualMachineProduct>>();
productCache.put(endpoint+"_"+accountId+"_"+regionId, cached, CalendarWrapper.HOUR * 4);
}
List<VirtualMachineProduct> products;
Set<String> mapping = null;
if( customServiceMappings == null ) {
load();
}
if( customServiceMappings != null ) {
String cloudId = cloudMappings.getProperty(provider.getContext().getEndpoint());
if( cloudId != null ) {
Map<String,Set<String>> map = customServiceMappings.get(cloudId);
if( map != null ) {
mapping = map.get(provider.getContext().getRegionId());
}
}
}
products = new ArrayList<VirtualMachineProduct>();
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_SERVICE_OFFERINGS, new Param("zoneId", ctx.getRegionId())), LIST_SERVICE_OFFERINGS);
NodeList matches = doc.getElementsByTagName("serviceoffering");
for( int i=0; i<matches.getLength(); i++ ) {
String id = null, name = null;
Node node = matches.item(i);
NodeList attributes;
int memory = 0;
int cpu = 0;
attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node n = attributes.item(j);
String value;
if( n.getChildNodes().getLength() > 0 ) {
value = n.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( n.getNodeName().equals("id") ) {
id = value;
}
else if( n.getNodeName().equals("name") ) {
name = value;
}
else if( n.getNodeName().equals("cpunumber") ) {
cpu = Integer.parseInt(value);
}
else if( n.getNodeName().equals("memory") ) {
memory = Integer.parseInt(value);
}
if( id != null && name != null && cpu > 0 && memory > 0 ) {
break;
}
}
if( id != null ) {
if( mapping == null || mapping.contains(id) ) {
VirtualMachineProduct product;
product = new VirtualMachineProduct();
product.setProviderProductId(id);
product.setName(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setDescription(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setRamSize(new Storage<Megabyte>(memory, Storage.MEGABYTE));
product.setCpuCount(cpu);
product.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
products.add(product);
}
}
}
cached.put(architecture, products);
return products;
}
finally {
APITrace.end();
}
}
private transient Collection<Architecture> architectures;
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
if( architectures == null ) {
ArrayList<Architecture> a = new ArrayList<Architecture>();
a.add(Architecture.I32);
a.add(Architecture.I64);
architectures = Collections.unmodifiableList(a);
}
return architectures;
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachineStatus");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
ResourceStatus vm = toStatus(node);
if( vm != null ) {
servers.add(vm);
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachines");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
try {
VirtualMachine vm = toVirtualMachine(node);
if( vm != null ) {
servers.add(vm);
}
} catch (Throwable t) {
logger.error("Problem discovering a virtual machine: " + t.getMessage());
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
private String resetPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.resetPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(RESET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), RESET_VIRTUAL_MACHINE_PASSWORD);
Document responseDoc = provider.waitForJob(doc, "reset vm password");
if (responseDoc != null){
NodeList matches = responseDoc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
return value;
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.reboot");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(REBOOT_VIRTUAL_MACHINE, new Param("id", serverId)), REBOOT_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.start");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(START_VIRTUAL_MACHINE, new Param("id", serverId)), START_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.stop");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(STOP_VIRTUAL_MACHINE, new Param("id", vmId), new Param("forced", String.valueOf(force))), STOP_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return true;
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public void terminate(@Nonnull String serverId, @Nullable String explanation) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.terminate");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(DESTROY_VIRTUAL_MACHINE, new Param("id", serverId)), DESTROY_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
NodeList attributes = node.getChildNodes();
VmState state = null;
String serverId = null;
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
serverId = value;
}
else if( name.equals("state") ) {
if( value == null ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
}
if( serverId != null && state != null ) {
break;
}
}
if( serverId == null ) {
return null;
}
if( state == null ) {
state = VmState.PENDING;
}
return new ResourceStatus(serverId, state);
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
+ server.setArchitecture(Architecture.I64);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN) || server.getArchitecture() == null){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
if (server.getPlatform().equals(Platform.UNKNOWN)) {
server.setPlatform(image.getPlatform());
}
if (server.getArchitecture() == null) {
server.setArchitecture(image.getArchitecture());
}
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
server.setTags(properties);
return server;
}
private Platform guessForWindows(String name){
if (name == null){
return Platform.UNKNOWN;
}
String platform = name.toLowerCase();
if (platform.contains("windows") || platform.contains("win") ){
return Platform.WINDOWS;
}
return Platform.UNKNOWN;
}
}
| true | true | private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN) || server.getArchitecture() == null){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
if (server.getPlatform().equals(Platform.UNKNOWN)) {
server.setPlatform(image.getPlatform());
}
if (server.getArchitecture() == null) {
server.setArchitecture(image.getArchitecture());
}
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
server.setTags(properties);
return server;
}
| private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
server.setArchitecture(Architecture.I64);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN) || server.getArchitecture() == null){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
if (server.getPlatform().equals(Platform.UNKNOWN)) {
server.setPlatform(image.getPlatform());
}
if (server.getArchitecture() == null) {
server.setArchitecture(image.getArchitecture());
}
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
server.setTags(properties);
return server;
}
|
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java
index 5a13db80..b9e5e6aa 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java
@@ -1,689 +1,689 @@
/*******************************************************************************
* Copyright (c) 2003, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.common.componentcore;
import java.util.EventObject;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jem.internal.util.emf.workbench.nls.EMFWorkbenchResourceHandler;
import org.eclipse.jem.util.UIContextDetermination;
import org.eclipse.wst.common.componentcore.internal.ArtifactEditModel;
import org.eclipse.wst.common.componentcore.internal.BinaryComponentHelper;
import org.eclipse.wst.common.componentcore.internal.impl.ModuleURIUtil;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.frameworks.internal.operations.IOperationHandler;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModel;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModelListener;
import org.eclipse.wst.common.internal.emfworkbench.validateedit.IValidateEditContext;
/**
* Provides a Facade pattern for accessing Module Content Metamodels for Web Tools Platform flexible
* modules.
* <p>
* ArtifactEdit hides the management of accessing edit models ({@see ArtifactEditModel})
* correctly. Each project may have multiple ({@see ArtifactEditModel})s depending on the number
* of modules contained by the project. Clients should use ArtifactEdit or an appropriate subclass
* when working with the content models of WTP modules.
* </p>
*
* <p>
* Each ArtifactEdit facade is designed to manage the EditModel lifecycle for clients. However,
* while each ArtifactEdit is designed to be passed around as needed, clients must enforce the
* ArtifactEdit lifecycle. The most common method of acquiring a ArtifactEdit instance facade is to
* use {@see #getArtifactEditForRead(WorkbenchComponent)} or
* {@see #getArtifactEditForWrite(WorkbenchComponent)}.
* </p>
* <p>
* When clients have concluded their use of the instance, <b>clients must call {@see #dispose()}
* </b>.
* </p>
* <p>
* This class is experimental until fully documented.
* </p>
*
* @see ModuleCoreNature
* @see ArtifactEditModel
* @plannedfor 1.0
*/
public class ArtifactEdit implements IEditModelHandler, IAdaptable{
public static final Class ADAPTER_TYPE = ArtifactEdit.class;
private final ArtifactEditModel artifactEditModel;
private boolean isReadOnly;
private boolean isArtifactEditModelSelfManaged;
private boolean isBinary;
private BinaryComponentHelper binaryComponentHelper;
private final IProject project;
/**
*
*/
protected ArtifactEdit() {
super();
artifactEditModel = null;
project = null;
}
/**
* <p>
* Returns an instance facade to manage the underlying edit model for the given
* {@see WorkbenchComponent}. Instances of ArtifactEdit that are returned through this method
* must be {@see #dispose()}ed of when no longer in use.
* </p>
* <p>
* Use to acquire an ArtifactEdit facade for a specific {@see WorkbenchComponent} that
* will not be used for editing. Invocations of any save*() API on an instance returned from
* this method will throw exceptions.
* </p>
* <p>
* <b>The following method may return null. </b>
* </p>
* <p>Note: This method is for internal use only. Clients should not call this method.</p>
* @param aModule
* A valid {@see WorkbenchComponent} with a handle that resolves to an
* accessible project in the workspace
* @return An instance of ArtifactEdit that may only be used to read the underlying content
* model
*/
public static ArtifactEdit getArtifactEditForRead(IVirtualComponent aModule) {
if(aModule.isBinary()){
return new ArtifactEdit(aModule);
}
if (isValidEditableModule(aModule)) {
IProject project = aModule.getProject();
ModuleCoreNature nature = ModuleCoreNature.getModuleCoreNature(project);
return new ArtifactEdit(nature, aModule, true);
}
return null;
}
/**
* <p>
* Returns an instance facade to manage the underlying edit model for the given
* {@see WorkbenchComponent}. Instances of ArtifactEdit that are returned through this method
* must be {@see #dispose()}ed of when no longer in use.
* </p>
* <p>
* Use to acquire an ArtifactEdit facade for a specific {@see WorkbenchComponent} that
* will be used for editing.
* </p>
* <p>
* <b>The following method may return null. </b>
* </p>
* <p>Note: This method is for internal use only. Clients should not call this method.</p>
* @param aModule
* A valid {@see WorkbenchComponent} with a handle that resolves to an
* accessible project in the workspace
* @return An instance of ArtifactEdit that may be used to modify and persist changes to the
* underlying content model
*/
public static ArtifactEdit getArtifactEditForWrite(IVirtualComponent aModule) {
if (!aModule.isBinary() && isValidEditableModule(aModule)) {
IProject project = aModule.getProject();
ModuleCoreNature nature = ModuleCoreNature.getModuleCoreNature(project);
return new ArtifactEdit(nature, aModule, false);
}
return null;
}
/**
* <p>
* Returns an instance facade to manage the underlying edit model for the given
* {@see WorkbenchComponent}. Instances of ArtifactEdit that are returned through this method
* must be {@see #dispose()}ed of when no longer in use.
* </p>
* <p>
* Use to acquire an ArtifactEdit facade for a specific {@see WorkbenchComponent} that
* will not be used for editing. Invocations of any save*() API on an instance returned from
* this method will throw exceptions.
* </p>
* <p>
* <b>The following method may return null. </b>
* </p>
*
* @param aModule
* A valid {@see WorkbenchComponent} with a handle that resolves to an
* accessible project in the workspace
* @return An instance of ArtifactEdit that may only be used to read the underlying content
* model
*/
public static ArtifactEdit getArtifactEditForRead(IProject aProject) {
ArtifactEdit artifactEdit = null;
try {
artifactEdit = new ArtifactEdit(aProject, true);
} catch (IllegalArgumentException iae) {
artifactEdit = null;
}
return artifactEdit;
}
/**
* <p>
* Returns an instance facade to manage the underlying edit model for the given
* {@see WorkbenchComponent}. Instances of ArtifactEdit that are returned through this method
* must be {@see #dispose()}ed of when no longer in use.
* </p>
* <p>
* Use to acquire an ArtifactEdit facade for a specific {@see WorkbenchComponent} that
* will be used for editing.
* </p>
* <p>
* <b>The following method may return null. </b>
* </p>
*
* @param aModule
* A valid {@see WorkbenchComponent} with a handle that resolves to an
* accessible project in the workspace
* @return An instance of ArtifactEdit that may be used to modify and persist changes to the
* underlying content model
*/
public static ArtifactEdit getArtifactEditForWrite(IProject aProject) {
ArtifactEdit artifactEdit = null;
try {
artifactEdit = new ArtifactEdit(aProject, false);
} catch (IllegalArgumentException iae) {
artifactEdit = null;
}
return artifactEdit;
}
/**
* <p>Note: This method is for internal use only. Clients should not call this method.</p>
* @param module
* A {@see WorkbenchComponent}
* @return True if the supplied module has a moduleTypeId which has a defined
* {@see IEditModelFactory} and is contained by an accessible project
*/
public static boolean isValidEditableModule(IVirtualComponent aModule) {
if (aModule == null)
return false;
if (ModuleURIUtil.fullyQualifyURI(aModule.getProject()) == null)
return false;
/* and the containing project must be resolveable and accessible */
IProject project = aModule.getProject();
if (project == null || !project.isAccessible())
return false;
return true;
}
/**
* <p>
* Creates an instance facade for the given {@see ArtifactEditModel}.
* </p>
*
* @param anArtifactEditModel
*/
public ArtifactEdit(ArtifactEditModel anArtifactEditModel) {
artifactEditModel = anArtifactEditModel;
isReadOnly = artifactEditModel.isReadOnly();
isArtifactEditModelSelfManaged = false;
project = anArtifactEditModel.getProject();
}
protected ArtifactEdit(IVirtualComponent aBinaryModule){
if(!aBinaryModule.isBinary()){
throw new RuntimeException("This constructor is only for binary components.");
}
binaryComponentHelper = initBinaryComponentHelper(aBinaryModule);
artifactEditModel = null;
isReadOnly = true;
isBinary = true;
isArtifactEditModelSelfManaged = true;
project = null;
}
protected BinaryComponentHelper initBinaryComponentHelper(IVirtualComponent binaryModule) {
return null;
}
/**
* <p>
* Creates an instance facade for the given {@see WorkbenchComponent}.
* </p>
* <p>Note: This method is for internal use only. Clients should not call this method.</p>
* @param aNature
* A non-null {@see ModuleCoreNature} for an accessible project
* @param aModule
* A non-null {@see WorkbenchComponent} pointing to a module from the given
* {@see ModuleCoreNature}
*/
protected ArtifactEdit(ModuleCoreNature aNature, IVirtualComponent aModule, boolean toAccessAsReadOnly) {
if (toAccessAsReadOnly)
artifactEditModel = aNature.getArtifactEditModelForRead(ModuleURIUtil.fullyQualifyURI(aModule.getProject()), this);
else
artifactEditModel = aNature.getArtifactEditModelForWrite(ModuleURIUtil.fullyQualifyURI(aModule.getProject()), this);
isReadOnly = toAccessAsReadOnly;
isArtifactEditModelSelfManaged = true;
project = aNature.getProject();
}
/**
* <p>
* Creates an instance facade for the given {@see WorkbenchComponent}.
* </p>
*
* @param aNature
* A non-null {@see ModuleCoreNature} for an accessible project
* @param aModule
* A non-null {@see WorkbenchComponent} pointing to a module from the given
* {@see ModuleCoreNature}
*/
public ArtifactEdit(IProject aProject, boolean toAccessAsReadOnly) throws IllegalArgumentException {
this(aProject,toAccessAsReadOnly,false,null);
}
/**
* <p>
* Creates an instance facade for the given {@see WorkbenchComponent}.
* </p>
*
* @param aProject
* @param toAccessAsReadOnly
* @param forCreate
* @param projectType
* @throws IllegalArgumentException
*/
protected ArtifactEdit(IProject aProject, boolean toAccessAsReadOnly, boolean forCreate, String projectType) throws IllegalArgumentException {
this(aProject,toAccessAsReadOnly,forCreate,projectType,null);
}
protected void verifyOperationSupported() {
if(!validArtifactEdit){
throw new RuntimeException("Invalid Artifact Edit access (model version not supported)");
}
}
private boolean validArtifactEdit = true;
public boolean isValid() {
return validArtifactEdit;
}
protected void markInvalid(){
Logger.global.log(Level.WARNING, "Invalid Artifact Edit access (model version not supported)");
validArtifactEdit = false;
}
/**
* <p>
* Creates an instance facade for the given {@see WorkbenchComponent}.
* </p>
*
* @param aProject
* @param toAccessAsReadOnly
* @param forCreate
* @param projectType - Used to pass specific editModel edit (Used to lookup factory)
* @param editModelParams - Properties that can be used to create cacheKey on editModelFactory
* @throws IllegalArgumentException
*/
protected ArtifactEdit(IProject aProject, boolean toAccessAsReadOnly, boolean forCreate, String projectType, Map editModelParams) throws IllegalArgumentException {
if (aProject == null || !aProject.isAccessible())
throw new IllegalArgumentException("Invalid project: " + aProject);
ModuleCoreNature nature = ModuleCoreNature.getModuleCoreNature(aProject);
if (nature == null)
throw new IllegalArgumentException("Project does not have ModuleCoreNature: " + aProject);
if (!validProjectVersion(aProject)){
markInvalid();
}
IVirtualComponent component = ComponentCore.createComponent(aProject);
if (component == null)
throw new IllegalArgumentException("Invalid component handle: " + aProject);
if (!forCreate && !isValidEditableModule(component))
throw new IllegalArgumentException("Invalid component handle: " + aProject);
URI componentURI = null;
- if (forCreate)
+ if (forCreate && getContentTypeDescriber() != null)
componentURI = ModuleURIUtil.fullyQualifyURI(aProject,getContentTypeDescriber());
else
componentURI = ModuleURIUtil.fullyQualifyURI(aProject);
if (toAccessAsReadOnly)
artifactEditModel = nature.getArtifactEditModelForRead(componentURI, this, projectType, editModelParams);
else
artifactEditModel = nature.getArtifactEditModelForWrite(componentURI, this, projectType, editModelParams);
isReadOnly = toAccessAsReadOnly;
isArtifactEditModelSelfManaged = true;
project = aProject;
}
/**
* Used to optionally define an associated content type for XML file creation
* @return
*/
protected String getContentTypeDescriber() {
return null;
}
protected boolean validProjectVersion(IProject project2) {
return true;
}
/**
* <p>
* Force a save of the underlying model. The following method should be used with care. Unless
* required, use {@see #saveIfNecessary(IProgressMonitor)} instead.
* </p>
*
* @see org.eclipse.wst.common.componentcore.IEditModelHandler#save()
* @throws IllegalStateException
* If the ModuleCore object was created as read-only
*/
public void save(IProgressMonitor aMonitor) {
if (isReadOnly())
throwAttemptedReadOnlyModification();
else if (validateEdit().isOK())
artifactEditModel.save(aMonitor, this);
}
/**
* <p>
* Save the underlying model only if no other clients are currently using the model. If the
* model is not shared, it will be saved. If it is shared, the save will be deferred.
* </p>
*
* @see org.eclipse.wst.common.componentcore.IEditModelHandler#saveIfNecessary()
* @throws IllegalStateException
* If the ModuleCore object was created as read-only
*/
public void saveIfNecessary(IProgressMonitor aMonitor) {
if (isReadOnly())
throwAttemptedReadOnlyModification();
else if (validateEdit().isOK())
artifactEditModel.saveIfNecessary(aMonitor, this);
}
/**
* Validate edit for resource state
*/
public IStatus validateEdit() {
IValidateEditContext validator = (IValidateEditContext) UIContextDetermination.createInstance(IValidateEditContext.CLASS_KEY);
return validator.validateState(getArtifactEditModel());
}
/**
* Save only if necessary. If typically a save would not occur because this edit model is
* shared, the user will be prompted using the @operationHandler.
* If the prompt returns true (the user wants to save) and the model is not shared,
* the entire edit model will be saved. You may pass in a boolean <code>wasDirty</code> to
* indicate whether this edit model was dirty prior to making any changes and
* calling this method. {@link EditModel#isDirty()}
*/
public void saveIfNecessaryWithPrompt(IProgressMonitor monitor, IOperationHandler operationHandler, boolean wasDirty) {
if (shouldSave(operationHandler, wasDirty))
saveIfNecessary(monitor);
else
handleSaveIfNecessaryDidNotSave(monitor);
}
/**
* Default is to do nothing. This method is called if a saveIfNecessary or
* saveIfNecessaryWithPrompt determines not to save. This provides subclasses with an
* opportunity to do some other action.
*/
private void handleSaveIfNecessaryDidNotSave(IProgressMonitor monitor) {
// do nothing
}
/**
* Should the resources be saved.
*/
private boolean shouldSave(IOperationHandler operationHandler, boolean wasDirty) {
return !wasDirty ? shouldSave() : shouldSave(operationHandler);
}
/**
* Prompt for a save.
*/
private boolean promptToSave(IOperationHandler operationHandler) {
if (operationHandler == null)
return false;
return operationHandler.canContinue(EMFWorkbenchResourceHandler.getString("The_following_resources_ne_UI_"), getArtifactEditModel().getResourceURIs(true)); //$NON-NLS-1$ = "The following resources need to be saved but are currently shared, do you want to save now?"
}
/**
* Should the resources be saved.
*/
private boolean shouldSave(IOperationHandler operationHandler) {
return shouldSave() || promptToSave(operationHandler);
}
/**
* Should the resources be saved.
*/
private boolean shouldSave() {
return !isReadOnly() && isArtifactEditModelSelfManaged;
}
/**
* <p>
* Clients must call the following method when they have finished using the model, even if the
* ArtifactEdit instance facade was created as read-only.
* </p>
*
* @see org.eclipse.wst.common.componentcore.IEditModelHandler#dispose()
*/
public void dispose() {
if(isBinary()){
binaryComponentHelper.releaseAccess(this);
} else if (isArtifactEditModelSelfManaged && artifactEditModel != null)
artifactEditModel.releaseAccess(this);
}
/**
* <p>
* Returns the root object for read or write access (depending on how the current ArtifactEdit
* was loaded).
* </p>
*
* @return The root object of the underlying model
*/
public EObject getContentModelRoot() {
if(isBinary())
return binaryComponentHelper.getPrimaryRootObject();
if (artifactEditModel!=null)
return artifactEditModel.getPrimaryRootObject();
return null;
}
/**
* <p>
* Add a listener to track lifecylce events from the underlying EditModel.
* </p>
*
* @param listener
* A non-null EditModelListener
*/
public void addListener(EditModelListener listener) {
if(isBinary()){
} else {
if (artifactEditModel!=null && listener!=null)
artifactEditModel.addListener(listener);
}
}
/**
* <p>
* Remove the supplied listener
* </p>
*
* @param listener
* A non-null EditModelListener
*
*/
public void removeListener(EditModelListener listener) {
if(isBinary()){
} else if (artifactEditModel!=null && !artifactEditModel.isDisposed()) {
artifactEditModel.removeListener(listener);
}
}
/**
* <p>
* This method may be removed soon. Avoid adding dependencies to it.
* </p>
* <p>
* This method is considered internal and not published as API.
* </p>
* @param editModel
* @return
*/
public boolean hasEditModel(EditModel editModel) {
if(isBinary()){
return false;
}
return artifactEditModel == editModel;
}
/**
*
* @return IProject - returns the project of the underlying workbench component.
*/
public IProject getProject() {
if(isBinary()){
return null;
}
return project;
}
/**
*
* @return IVirtualComponent - returns the underlying workbench component.
*/
public IVirtualComponent getComponent() {
if(isBinary()){
return binaryComponentHelper.getComponent();
}
return getArtifactEditModel().getVirtualComponent();
}
/**
* @return The underlying managed edit model
*/
protected ArtifactEditModel getArtifactEditModel() {
if(isBinary()){
throwAttemptedBinaryEditModelAccess();
}
return artifactEditModel;
}
protected BinaryComponentHelper getBinaryComponentHelper() {
return binaryComponentHelper;
}
/**
* @return The EMF command stack managed by the underlying editmodel
*/
public CommandStack getCommandStack() {
if(isBinary()){
return new BasicCommandStack();
}
return artifactEditModel.getCommandStack();
}
/**
*
* @deprecated Use ((ArtifactEditModel)getAdapter(ArtifactEditModel.ADAPTER_TYPE)).deleteResource(aResource);
*/
public void deleteResource(Resource aResource) {
if(isBinary()){
throwAttemptedBinaryEditModelAccess();
}
artifactEditModel.deleteResource(aResource);
}
/**
* @return The isDirty flag based the underlying editmodel's list of resources.
*/
public boolean isDirty() {
if(isBinary()){
return false;
}
return artifactEditModel.isDirty();
}
private void throwAttemptedReadOnlyModification() {
throw new IllegalStateException("Attempt to modify an ArtifactEdit instance facade that was loaded as read-only.");
}
protected void throwAttemptedBinaryEditModelAccess() {
throw new IllegalStateException("Attempt to modify an ArtifactEdit instance facade that was loaded as binary.");
}
public boolean isReadOnly() {
return isReadOnly;
}
public boolean isBinary() {
return isBinary;
}
/**
* Force all of the known resource URIs to be loaded
* if they are not already.
*/
public void forceLoadKnownResources() {
if(isBinary()){
} else {
List uris = getArtifactEditModel().getKnownResourceUris();
URI uri = null;
for (int i = 0; i < uris.size(); i++) {
uri = (URI) uris.get(i);
getArtifactEditModel().getResource(uri);
}
}
}
/**
* Return a Resource for @aUri.
* @deprecated Use ((ArtifactEditModel)getAdapter(ArtifactEditModel.ADAPTER_TYPE)).getResource(aResource);
*/
public Resource getResource(URI aUri) {
if(isBinary()){
return binaryComponentHelper.getResource(aUri);
}
return getArtifactEditModel().getResource(aUri);
}
public Object getAdapter(Class adapterType) {
if (adapterType == ArtifactEditModel.class)
return getArtifactEditModel();
return Platform.getAdapterManager().getAdapter(this, adapterType);
}
public void commandStackChanged(EventObject event) {
getArtifactEditModel().commandStackChanged(event);
}
}
| true | true | protected ArtifactEdit(IProject aProject, boolean toAccessAsReadOnly, boolean forCreate, String projectType, Map editModelParams) throws IllegalArgumentException {
if (aProject == null || !aProject.isAccessible())
throw new IllegalArgumentException("Invalid project: " + aProject);
ModuleCoreNature nature = ModuleCoreNature.getModuleCoreNature(aProject);
if (nature == null)
throw new IllegalArgumentException("Project does not have ModuleCoreNature: " + aProject);
if (!validProjectVersion(aProject)){
markInvalid();
}
IVirtualComponent component = ComponentCore.createComponent(aProject);
if (component == null)
throw new IllegalArgumentException("Invalid component handle: " + aProject);
if (!forCreate && !isValidEditableModule(component))
throw new IllegalArgumentException("Invalid component handle: " + aProject);
URI componentURI = null;
if (forCreate)
componentURI = ModuleURIUtil.fullyQualifyURI(aProject,getContentTypeDescriber());
else
componentURI = ModuleURIUtil.fullyQualifyURI(aProject);
if (toAccessAsReadOnly)
artifactEditModel = nature.getArtifactEditModelForRead(componentURI, this, projectType, editModelParams);
else
artifactEditModel = nature.getArtifactEditModelForWrite(componentURI, this, projectType, editModelParams);
isReadOnly = toAccessAsReadOnly;
isArtifactEditModelSelfManaged = true;
project = aProject;
}
| protected ArtifactEdit(IProject aProject, boolean toAccessAsReadOnly, boolean forCreate, String projectType, Map editModelParams) throws IllegalArgumentException {
if (aProject == null || !aProject.isAccessible())
throw new IllegalArgumentException("Invalid project: " + aProject);
ModuleCoreNature nature = ModuleCoreNature.getModuleCoreNature(aProject);
if (nature == null)
throw new IllegalArgumentException("Project does not have ModuleCoreNature: " + aProject);
if (!validProjectVersion(aProject)){
markInvalid();
}
IVirtualComponent component = ComponentCore.createComponent(aProject);
if (component == null)
throw new IllegalArgumentException("Invalid component handle: " + aProject);
if (!forCreate && !isValidEditableModule(component))
throw new IllegalArgumentException("Invalid component handle: " + aProject);
URI componentURI = null;
if (forCreate && getContentTypeDescriber() != null)
componentURI = ModuleURIUtil.fullyQualifyURI(aProject,getContentTypeDescriber());
else
componentURI = ModuleURIUtil.fullyQualifyURI(aProject);
if (toAccessAsReadOnly)
artifactEditModel = nature.getArtifactEditModelForRead(componentURI, this, projectType, editModelParams);
else
artifactEditModel = nature.getArtifactEditModelForWrite(componentURI, this, projectType, editModelParams);
isReadOnly = toAccessAsReadOnly;
isArtifactEditModelSelfManaged = true;
project = aProject;
}
|
diff --git a/modules/library/jdbc/src/test/java/org/geotools/jdbc/EscapeSqlTest.java b/modules/library/jdbc/src/test/java/org/geotools/jdbc/EscapeSqlTest.java
index 291be9da87..54f1d48c16 100644
--- a/modules/library/jdbc/src/test/java/org/geotools/jdbc/EscapeSqlTest.java
+++ b/modules/library/jdbc/src/test/java/org/geotools/jdbc/EscapeSqlTest.java
@@ -1,45 +1,45 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2013, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.jdbc;
import java.util.Collections;
import junit.framework.TestCase;
import org.geotools.factory.Hints;
/**
* Check that SQL escape code generates the correct strings
*/
public class EscapeSqlTest extends TestCase {
public void testSqlEscaping() throws Exception {
VirtualTable vt = new VirtualTable("test", "%param1%");
vt.setEscapeSql(true);
vt.addParameter(new VirtualTableParameter("param1", "default_value", new RegexpValidator(".*")));
String singleQuote = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "o'shea")));
- assertEquals("single quotes should be doubled", "o''shea", singleQuote);
+ assertEquals("single quotes should be doubled", "o''shea\n", singleQuote);
String doubleQuote = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "If you hear a voice within you say \"you cannot paint,\" then by all means paint, and that voice will be silenced.")));
- assertEquals("double quotes should be doubled", "If you hear a voice within you say \"\"you cannot paint,\"\" then by all means paint, and that voice will be silenced.",
+ assertEquals("double quotes should be doubled", "If you hear a voice within you say \"\"you cannot paint,\"\" then by all means paint, and that voice will be silenced.\n",
doubleQuote);
String backslash = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "abc\\n")));
- assertEquals("backslashes should be removed", "abcn", backslash);
+ assertEquals("backslashes should be removed", "abcn\n", backslash);
}
}
| false | true | public void testSqlEscaping() throws Exception {
VirtualTable vt = new VirtualTable("test", "%param1%");
vt.setEscapeSql(true);
vt.addParameter(new VirtualTableParameter("param1", "default_value", new RegexpValidator(".*")));
String singleQuote = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "o'shea")));
assertEquals("single quotes should be doubled", "o''shea", singleQuote);
String doubleQuote = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "If you hear a voice within you say \"you cannot paint,\" then by all means paint, and that voice will be silenced.")));
assertEquals("double quotes should be doubled", "If you hear a voice within you say \"\"you cannot paint,\"\" then by all means paint, and that voice will be silenced.",
doubleQuote);
String backslash = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "abc\\n")));
assertEquals("backslashes should be removed", "abcn", backslash);
}
| public void testSqlEscaping() throws Exception {
VirtualTable vt = new VirtualTable("test", "%param1%");
vt.setEscapeSql(true);
vt.addParameter(new VirtualTableParameter("param1", "default_value", new RegexpValidator(".*")));
String singleQuote = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "o'shea")));
assertEquals("single quotes should be doubled", "o''shea\n", singleQuote);
String doubleQuote = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "If you hear a voice within you say \"you cannot paint,\" then by all means paint, and that voice will be silenced.")));
assertEquals("double quotes should be doubled", "If you hear a voice within you say \"\"you cannot paint,\"\" then by all means paint, and that voice will be silenced.\n",
doubleQuote);
String backslash = vt.expandParameters(new Hints(
Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "abc\\n")));
assertEquals("backslashes should be removed", "abcn\n", backslash);
}
|
diff --git a/examples/stanfordBlacklight/test/src/edu/stanford/ItemInfoTests.java b/examples/stanfordBlacklight/test/src/edu/stanford/ItemInfoTests.java
index b467736..7fc69d1 100644
--- a/examples/stanfordBlacklight/test/src/edu/stanford/ItemInfoTests.java
+++ b/examples/stanfordBlacklight/test/src/edu/stanford/ItemInfoTests.java
@@ -1,1145 +1,1145 @@
package edu.stanford;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.xml.sax.SAXException;
/**
* junit4 tests for Stanford University's fields derived from item info in
* 999 other than call number (building_facet, access_facet, location, barcode,
* etc.)
* @author Naomi Dushay
*/
public class ItemInfoTests extends AbstractStanfordBlacklightTest {
/**
* Test building facet values. Skipped building values are in a separate test
*/
@Test
public final void testBuildingFacet()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "building_facet";
createIxInitVars("buildingTests.mrc");
assertFacetFieldProperties(fldName);
assertFieldMultiValued(fldName);
assertSingleResult("229800", fldName, "\"Archive of Recorded Sound\"");
assertSingleResult("345228", fldName, "\"Art & Architecture\"");
assertSingleResult("460947", fldName, "\"Falconer (Biology)\"");
assertSingleResult("804724", fldName, "\"SAL Newark (Off-campus)\"");
assertSingleResult("919006", fldName, "\"Swain (Chemistry & Chem. Engineering)\"");
assertSingleResult("1147269", fldName, "\"Classics\"");
assertSingleResult("1505065", fldName, "\"Branner (Earth Sciences & Maps)\"");
assertSingleResult("1618836", fldName, "\"Cubberley (Education)\"");
assertSingleResult("1732616", fldName, "\"Math & Computer Science\"");
assertSingleResult("1849258", fldName, "Engineering");
assertSingleResult("2099904", fldName, "\"Jonsson (Government Documents)\"");
assertSingleResult("2678655", fldName, "\"Jackson (Business)\"");
assertSingleResult("3027805", fldName, "\"Miller (Hopkins Marine Station)\"");
assertSingleResult("3142611", fldName, "Physics");
assertSingleResult("4258089", fldName, "\"Special Collections & Archives\"");
assertSingleResult("4428936", fldName, "\"Tanner (Philosophy Dept.)\"");
assertSingleResult("4823592", fldName, "\"Crown (Law)\"");
assertSingleResult("5666387", fldName, "Music");
assertSingleResult("6676531", fldName, "\"East Asia\"");
assertSingleResult("2797607", fldName, "Meyer");
// hoover tests are a separate method below
Set<String> docIds = new HashSet<String>();
docIds.add("1033119");
docIds.add("1261173");
docIds.add("2557826");
docIds.add("3941911");
docIds.add("4114632");
// checked out
docIds.add("575946");
// NOT 3277173 (withdrawn)
assertSearchResults(fldName, "\"Green (Humanities & Social Sciences)\"", docIds);
docIds.clear();
docIds.add("1033119");
docIds.add("1962398");
docIds.add("2328381");
docIds.add("2913114");
assertSearchResults(fldName, "\"Stanford Auxiliary Library (On-campus)\"", docIds);
docIds.clear();
docIds.add("690002");
docIds.add("2328381");
docIds.add("3941911");
docIds.add("7651581");
// education - withdrawn; SAL3 stacks
docIds.add("2214009");
assertSearchResults(fldName, "\"SAL3 (Off-campus)\"", docIds);
docIds.clear();
docIds.add("7370014");
// ask@lane
docIds.add("7233951");
assertSearchResults(fldName, "\"Lane (Medical)\"", docIds);
}
/**
* ensure that there are no building facet values for items that are in
* buildings without translations in the library_map
*/
@Test
public void testSkipBuildingFacet()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "building_facet";
createIxInitVars("buildingTests.mrc");
// APPLIEDPHY (Applied Physics Department is no longer a valid building)
// assertSingleResult("115472", fldName, "\"Applied Physics Department\"");
assertZeroResults(fldName, "\"Applied Physics Department\"");
assertZeroResults(fldName, "\"APPLIEDPHY\"");
// CPM not a valid building
// assertSingleResult("1391080", fldName, "\"Green - Current Periodicals & Microtext\"");
assertZeroResults(fldName, "\"Green - Current Periodicals & Microtext\"");
assertZeroResults(fldName, "\"CPM\"");
// GRN-REF Green - Reference - Obsolete
// assertSingleResult("2442876", fldName, "\"Green - Reference\"");
assertZeroResults(fldName, "\"Green - Reference\"");
assertZeroResults(fldName, "\"GRN-REF\"");
// ILB Inter-Library Borrowing - Obsolete
// assertSingleResult("1111", fldName, "\"Inter-Library Borrowing\"");
assertZeroResults(fldName, "\"Inter-Library Borrowing\"");
assertZeroResults(fldName, "\"ILB\"");
// SPEC-DESK Green (Humanities & Social Sciences) not a valid building
// assertSingleResult("2222", fldName, "Green (Humanities & Social Sciences)");
assertZeroResults(fldName, "Green (Humanities & Social Sciences)");
assertZeroResults(fldName, "SPEC-DESK");
// SUL Stanford University Libraries not a valid building
// assertSingleResult("6493823", fldName, "Stanford University Libraries");
// assertSingleResult("7117119", fldName, "Stanford University Libraries");
assertZeroResults(fldName, "\"Stanford University Libraries\"");
assertZeroResults(fldName, "\"SUL\"");
}
/**
* ensure that the two hoover library codes have separate values for the
* building facet
*/
@Test
public void testHoover2Locs()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "building_facet";
createIxInitVars("buildingTests.mrc");
assertSingleResult("3743949", fldName, "\"Hoover Library\"");
assertSingleResult("3400092", fldName, "\"Hoover Archives\"");
}
/**
* test if barcode_search field is populated correctly
*/
@Test
public final void testBarcodeSearch()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "barcode_search";
createIxInitVars("locationTests.mrc");
assertTextFieldProperties(fldName);
assertFieldOmitsNorms(fldName);
assertFieldIndexed(fldName);
assertFieldNotStored(fldName);
assertFieldMultiValued(fldName);
// single barcode in the record
assertSingleResult("115472", fldName, "36105033811451");
// multiple barcodes in the record
assertSingleResult("1033119", fldName, "36105037439663");
assertSingleResult("1033119", fldName, "36105001623284");
}
String sep = " -|- ";
boolean isSerial = true;
/**
* test if item_display field is populated correctly, focusing on building/library
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayBuildings()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
assertDisplayFieldProperties(fldName);
assertFieldMultiValued(fldName);
// APPLIEDPHY ignored for building facet, but not here
String callnum = "HC241.25 .I4 D47";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("115472", fldName, "36105033811451 -|- APPLIEDPHY -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ARS
callnum = "HG6046 .V28 1986";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("229800", fldName, "36105034181003 -|- ARS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ART
callnum = "D764.7 .K72 1990";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("345228", fldName, "36105043140537 -|- Art -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// BIOLOGY
callnum = "E184.S75 R47A V.1 1980";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CHEMCHMENG
callnum = "PA3998 .H2 O5 1977";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("919006", fldName, "36105036688153 -|- Swain -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CLASSICS
callnum = "PR9184.6 .M3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1147269", fldName, "36105037871261 -|- Classics -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CPM
callnum = "PQ6653.A646.V5";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1391080", fldName, "36105038701285 -|- CPM -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EARTH-SCI
callnum = "TD811.5 .G76 1983";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1505065", fldName, "36105039395095 -|- Branner -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EAST-ASIA
callnum = "RD35 .H34 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6676531", fldName, "36105095758004 -|- East Asia -|- Japanese Collection -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EDUCATION
callnum = "PQ6666.E7484 B4 1983";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1618836", fldName, "36105040261765 -|- Cubberley -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ENG
callnum = "352.042 .C594 ED.2";
lopped = CallNumUtils.removeDeweyVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1849258", fldName, "36105047516096 -|- Engineering -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GOV-DOCS
callnum = "DK43 .B63";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2099904", fldName, "36105041442281 -|- Government Docs -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GREEN
callnum = "MFILM N.S. 1350 REEL 230 NO. 3741";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1261173", fldName, "001AFX2969 -|- Green -|- Media-Microtext Collection (Lower Level) -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GRN-REF
callnum = "PQ2678.I26 P54 1992";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2442876", fldName, "36105043436257 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HOOVER
callnum = "PQ6613 .A73 G44";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3743949", fldName, "3743949-1001 -|- Hoover Library -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HOPKINS
callnum = "DG579 .A5 A5 1995";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3027805", fldName, "36105016935392 -|- Hopkins -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HV-ARCHIVE
callnum = "DC34.5 .A78 L4 1996";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3400092", fldName, "36105020376997 -|- Hoover Archives -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ILB
callnum = "Z666 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1111", fldName, "36105129694373 -|- ILB -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// JACKSON
callnum = "GA 1.13:RCED-85-88";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2678655", fldName, "001ANE5736 -|- Jackson -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// LANE-MED
callnum = "X578 .S64 1851";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum, "LC", "7233951");
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7233951", fldName, "LL124341 -|- Lane -|- Check Lane catalog for status -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// LAW
callnum = "Y 4.G 74/7:G 21/10";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4823592", fldName, "36105063104488 -|- Crown -|- Basement -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MATH-CS
callnum = "QA273 .C83 1962";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1732616", fldName, "36105033142303 -|- Math/CS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
- // MEYER - ignored for building facet, but not here
+ // MEYER
callnum = "B781 .A33 I55 1993";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2797607", fldName, "36105004381195 -|- Meyer -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MUSIC
callnum = "ML410 .S54 I58 2000";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("5666387", fldName, "36105114964369 -|- Music -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// PHYSICS
callnum = "PS3553 .L337 F76 1978";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3142611", fldName, "36105017175519 -|- Physics -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL
callnum = "DS135 .P6 I65";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2913114", fldName, "36105082973251 -|- SAL -|- Temporary Shelving -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL3
callnum = "159.32 .W211";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("690002", fldName, "36105046693508 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL-NEWARK
callnum = "Z7164.T23.W45";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("804724", fldName, "36105035887392 -|- SAL Newark -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SPEC-COLL
callnum = "NAS 1.26:205100";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4258089", fldName, "4258089-1001 -|- Special Collections -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SPEC-DESK
callnum = "S666 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2222", fldName, "36105129694373 -|- SPEC-DESK -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// TANNER
callnum = "PN1993.5 .I88 C5618 2000";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4428936", fldName, "36105021909747 -|- Tanner -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SUL
callnum = "F1356 .M464 2005";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6493823", fldName, "36105122224160 -|- SUL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items in single record, diff buildings
callnum = "BX4659.E85 W44";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1033119", fldName, "36105037439663 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "BX4659 .E85 W44 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1033119", fldName, "36105001623284 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// same build, same loc, same callnum, one in another building
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
tearDown();
createIxInitVars("itemDisplayTests.mrc");
// Lane example with actual values
callnum = "Z3871.Z8 V.22 1945";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6661112", fldName, "36105082101390 -|- Lane -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// mult items same build, diff loc
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- Green -|- Bindery (Off-Campus) -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly, focusing on locations
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayLocations()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// stacks
String callnum = "HG6046 .V28 1986";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("229800", fldName, "36105034181003 -|- ARS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PS3557 .O5829 K3 1998";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3941911", fldName, "36105019748495 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PS3557 .O5829 K3 1998";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3941911", fldName, "36105025373064 -|- Green -|- Bender Room: Non-circulating -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "RD35 .H34 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6676531", fldName, "36105095758004 -|- East Asia -|- Japanese Collection -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "MFILM N.S. 1350 REEL 230 NO. 3741";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1261173", fldName, "001AFX2969 -|- Green -|- Media-Microtext Collection (Lower Level) -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// inquire
callnum = "X578 .S64 1851";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum, "LC", "7233951");
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7233951", fldName, "LL124341 -|- Lane -|- Check Lane catalog for status -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// in transit
callnum = "Z3871.Z8";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1962398", fldName, "36105082101390 -|- SAL -|- Temporary Shelving -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "DS135 .P6 I65";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2913114", fldName, "36105082973251 -|- SAL -|- Temporary Shelving -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// in process
callnum = "PQ9661 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7651581", fldName, "36105129694373 -|- SAL3 -|- In process -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// gov docs
callnum = "E 1.28:COO-4274-1";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2557826", fldName, "001AMR5851 -|- Green -|- US Federal Documents -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "ITC 1.15/3:";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4114632", fldName, "4114632-1001 -|- Green -|- US Federal Documents -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// one withdrawn location, one valid
callnum = "370.1 .S655";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasNoFieldValue("2214009", fldName, "36105033336798 -|- Cubberley -|- Withdrawn -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("2214009", fldName, "36105033336780 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// online locations: ELECTR-LOC INTERNET ONLINE-TXT RESV-URL
assertDocHasNoField("7117119", fldName);
tearDown();
createIxInitVars("itemDisplayTests.mrc");
// on order locations
callnum = "E184.S75 R47A V.1 1980";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Green -|- On order -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// reserve locations
callnum = "159.32 .W211";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("690002", fldName, "36105046693508 -|- Branner -|- Reserves -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// mult items same build, diff loc
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- Green -|- Bindery (Off-Campus) -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items for single bib with same library / location, diff callnum
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("666", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2 V.1";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("666", fldName, "36105003934424 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2 V.2";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("666", fldName, "36105048104132 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly when location is online
*/
@Test
public final void testItemDisplayOnlineLocs()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("locationTests.mrc");
// online locations do not appear as items in the search results, but
// they do appear in nearby on shelf
// ELECTR-LOC
String callnum = "HC241.25 .I4 D47";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("115472", fldName, "36105033811451 -|- Online -|- Online -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// INTERNET
callnum = "HG6046 .V28 1986";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("229800", fldName, "36105034181003 -|- Online -|- Online -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ONLINE-TXT
callnum = "E184.S75 R47A V.1 1980";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Online -|- Online -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// RESV-URL is skipped
assertDocHasNoField("690002", fldName);
}
// display home location
/**
* test if item_display field is populated correctly when there is a current
* location that should be ignored in favor of the home location
*/
@Test
public final void testItemDisplayIgnoreCurrentLocs()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// these locations should only appear as "current" locations, and they
// should be ignored in favor of "home" locations. The status of the
// item (e.g. checked out) will be displayed elsewhere.
// CHECKEDOUT as current location, Stacks as home location
String callnum = "CB3 .A6 SUPPL. V.31";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("575946", fldName, "36105035087092 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// WITHDRAWN as current location implies item is skipped
assertDocHasNoField("3277173", fldName);
}
/**
* test if item_display field is populated correctly when location implies
* item is shelved by title (SHELBYTITL SHELBYSER STORBYTITL)
*/
@Test
public final void testItemDisplayShelbyLocs()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("callNumberLCSortTests.mrc");
// callnum for all three is PQ9661 .P31 C6 VOL 1 1946"
// SHELBYTITL
String callnum = "Shelved by title";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum, "LC", "1111");
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String show_view_callnum = callnum + " VOL 1 1946";
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(show_view_callnum, callnum, isSerial);
assertDocHasFieldValue("1111", fldName, "36105129694373 -|- Swain -|- Serials -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + show_view_callnum + sep + volSort);
// STORBYTITL
assertDocHasFieldValue("3311", fldName, "36105129694375 -|- Swain -|- Storage area -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + show_view_callnum + sep + volSort);
// SHELBYSER
callnum = "Shelved by Series title";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum, "LC", "1111");
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
show_view_callnum = callnum + " VOL 1 1946";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(show_view_callnum, callnum, isSerial);
assertDocHasFieldValue("2211", fldName, "36105129694374 -|- Swain -|- Serials -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + show_view_callnum + sep + volSort);
}
/**
* test if item_display field is missing when the location shouldn't be
* displayed
*/
@Test
public final void testItemDisplaySkipLocs()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("locationTests.mrc");
// TODO: the record should not be INDEXED if all items are skipped
// DISCARD-NS
assertDocHasNoField("345228", fldName);
// WITHDRAWN
assertDocHasNoField("575946", fldName);
// FED-DOCS-S (shadow)
assertDocHasNoField("804724", fldName);
// CDPSHADOW and TECHSHADOW
assertDocHasNoField("1033119", fldName);
// LOST
assertDocHasNoField("1505065", fldName);
// INPROCESS - keep it
String callnum = "PQ9661 .P31 C6 1946";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7651581", fldName, "36105129694373 -|- SAL3 -|- In process -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly when location is to
* be left "as is" (no translation in map, but don't skip)
*/
@Test
public final void testAsIsLocations()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("mediaLocTest.mrc");
String callnum = "G70.212 .A73934 2008";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7652182", fldName, "36105130436541 -|- Branner -|- Permanent Reserve: Inquire at loan desk -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("7652182", fldName, "36105130436848 -|- Branner -|- Reference: Non-circulating -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("7652182", fldName, "36105130437192 -|- Branner -|- MEDIA -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly, focused on lopped callnums
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayLoppedCallnums()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// LC
String callnum = "E184.S75 R47A V.1 1980";
String lopped = "E184.S75 R47A";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "CB3 .A6 SUPPL. V.31";
// NOTE: it finds V.31, so it doesn't look for SUPPL. preceding it.
lopped = "CB3 .A6 SUPPL.";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("575946", fldName, "36105035087092 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// DEWEY (no vol)
callnum = "159.32 .W211";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("690002", fldName, "36105046693508 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SUDOC (no vol)
callnum = "E 1.28:COO-4274-1";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2557826", fldName, "001AMR5851 -|- Green -|- US Federal Documents -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
tearDown();
createIxInitVars("itemDisplayTests.mrc");
// LCPER
callnum = "E184.S75 R47A V.1 1980";
lopped = "E184.S75 R47A";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Green -|- On order -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// DEWEYPER (no vol)
callnum = "666.27 .F22";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("446688", fldName, "36105007402873 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ALPHANUM-SUSEL (no vol)
callnum = "SUSEL-69048";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4578538", fldName, "36105046377987 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ALPHANUM - MFILM
callnum = "MFILM N.S. 1350 REEL 230 NO. 3741";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1261173", fldName, "001AFX2969 -|- Green -|- Media-Microtext Collection (Lower Level) -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ALPHANUM - MCD
callnum = "MCD Brendel Plays Beethoven's Eroica variations";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1234673", fldName, "001AFX2969 -|- Green -|- Media-Microtext Collection (Lower Level) -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items with same call number
callnum = "PS3557 .O5829 K3 1998";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3941911", fldName, "36105025373064 -|- Green -|- Bender Room: Non-circulating -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("3941911", fldName, "36105019748495 -|- Green -|- Bender Room: Non-circulating -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items with same call number due to vol lopping
callnum = "PR3724.T3 A2 V.12";
lopped = "PR3724.T3 A2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("111", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2 V.1";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("111", fldName, "36105003934424 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2 V.2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("111", fldName, "36105048104132 -|- Green -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items with same call number due to mult buildings
callnum = "PR3724.T3 V2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("222", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("222", fldName, "36105003934424 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// invalid LC call number
callnum = "Y 4.G 74/7:G 21/10";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped, "LC", "4823592");
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4823592", fldName, "36105063104488 -|- Crown -|- Basement -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly, focused on forward sorting callnums
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayCallnumSort()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// are we getting the shelfkey for the lopped call number?
String callnum = "E184.S75 R47A V.1 1980";
String lopped = "E184.S75 R47A";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly, focused on backward sorting callnums
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayCallnumReverseSort()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// are we getting the reverse shelfkey for the lopped call number?
String callnum = "E184.S75 R47A V.1 1980";
String lopped = "E184.S75 R47A";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly, focused on full call numbers
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayFullCallnum()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// are we getting the full call number as expected
String callnum = "E184.S75 R47A V.1 1980";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* test if item_display field is populated correctly, focused on sorting call numbers for show view
* item_display contains: (separator is " -|- ")
* barcode -|- library(short version) -|- location -|-
* lopped call number (no volume/part info) -|-
* callnum_sort (from lopped call num) -|-
* callnum_reverse_sort (from lopped call num) -|-
* full callnum -|- callnum sortable for show view
*/
@Test
public final void testItemDisplayCallnumVolumeSort()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
// are we getting the volume sortable call number we expect?
String callnum = "E184.S75 R47A V.1 1980";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
/**
* Assert that multiple copies of an item each have a separate field
*/
//@Test
public final void testMultipleCopies()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
String fileName = "multipleCopies.mrc";
createIxInitVars(fileName);
mappingTestInit();
String testFilePath = testDataParentPath + File.separator + fileName;
String callnum = "PR3724.T2";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
String rest = " -|- SAL3 -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort;
String item1 = "36105003934432" + rest;
String item2 = "36105003934424" + rest;
solrFldMapTest.assertSolrFldValue(testFilePath, "1", fldName, item1);
solrFldMapTest.assertSolrFldValue(testFilePath, "1", fldName, item2);
assertDocHasFieldValue("1", fldName, item1);
assertDocHasFieldValue("1", fldName, item2);
}
}
| true | true | public final void testItemDisplayBuildings()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
assertDisplayFieldProperties(fldName);
assertFieldMultiValued(fldName);
// APPLIEDPHY ignored for building facet, but not here
String callnum = "HC241.25 .I4 D47";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("115472", fldName, "36105033811451 -|- APPLIEDPHY -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ARS
callnum = "HG6046 .V28 1986";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("229800", fldName, "36105034181003 -|- ARS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ART
callnum = "D764.7 .K72 1990";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("345228", fldName, "36105043140537 -|- Art -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// BIOLOGY
callnum = "E184.S75 R47A V.1 1980";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CHEMCHMENG
callnum = "PA3998 .H2 O5 1977";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("919006", fldName, "36105036688153 -|- Swain -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CLASSICS
callnum = "PR9184.6 .M3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1147269", fldName, "36105037871261 -|- Classics -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CPM
callnum = "PQ6653.A646.V5";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1391080", fldName, "36105038701285 -|- CPM -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EARTH-SCI
callnum = "TD811.5 .G76 1983";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1505065", fldName, "36105039395095 -|- Branner -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EAST-ASIA
callnum = "RD35 .H34 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6676531", fldName, "36105095758004 -|- East Asia -|- Japanese Collection -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EDUCATION
callnum = "PQ6666.E7484 B4 1983";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1618836", fldName, "36105040261765 -|- Cubberley -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ENG
callnum = "352.042 .C594 ED.2";
lopped = CallNumUtils.removeDeweyVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1849258", fldName, "36105047516096 -|- Engineering -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GOV-DOCS
callnum = "DK43 .B63";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2099904", fldName, "36105041442281 -|- Government Docs -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GREEN
callnum = "MFILM N.S. 1350 REEL 230 NO. 3741";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1261173", fldName, "001AFX2969 -|- Green -|- Media-Microtext Collection (Lower Level) -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GRN-REF
callnum = "PQ2678.I26 P54 1992";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2442876", fldName, "36105043436257 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HOOVER
callnum = "PQ6613 .A73 G44";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3743949", fldName, "3743949-1001 -|- Hoover Library -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HOPKINS
callnum = "DG579 .A5 A5 1995";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3027805", fldName, "36105016935392 -|- Hopkins -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HV-ARCHIVE
callnum = "DC34.5 .A78 L4 1996";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3400092", fldName, "36105020376997 -|- Hoover Archives -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ILB
callnum = "Z666 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1111", fldName, "36105129694373 -|- ILB -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// JACKSON
callnum = "GA 1.13:RCED-85-88";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2678655", fldName, "001ANE5736 -|- Jackson -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// LANE-MED
callnum = "X578 .S64 1851";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum, "LC", "7233951");
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7233951", fldName, "LL124341 -|- Lane -|- Check Lane catalog for status -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// LAW
callnum = "Y 4.G 74/7:G 21/10";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4823592", fldName, "36105063104488 -|- Crown -|- Basement -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MATH-CS
callnum = "QA273 .C83 1962";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1732616", fldName, "36105033142303 -|- Math/CS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MEYER - ignored for building facet, but not here
callnum = "B781 .A33 I55 1993";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2797607", fldName, "36105004381195 -|- Meyer -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MUSIC
callnum = "ML410 .S54 I58 2000";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("5666387", fldName, "36105114964369 -|- Music -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// PHYSICS
callnum = "PS3553 .L337 F76 1978";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3142611", fldName, "36105017175519 -|- Physics -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL
callnum = "DS135 .P6 I65";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2913114", fldName, "36105082973251 -|- SAL -|- Temporary Shelving -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL3
callnum = "159.32 .W211";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("690002", fldName, "36105046693508 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL-NEWARK
callnum = "Z7164.T23.W45";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("804724", fldName, "36105035887392 -|- SAL Newark -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SPEC-COLL
callnum = "NAS 1.26:205100";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4258089", fldName, "4258089-1001 -|- Special Collections -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SPEC-DESK
callnum = "S666 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2222", fldName, "36105129694373 -|- SPEC-DESK -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// TANNER
callnum = "PN1993.5 .I88 C5618 2000";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4428936", fldName, "36105021909747 -|- Tanner -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SUL
callnum = "F1356 .M464 2005";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6493823", fldName, "36105122224160 -|- SUL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items in single record, diff buildings
callnum = "BX4659.E85 W44";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1033119", fldName, "36105037439663 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "BX4659 .E85 W44 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1033119", fldName, "36105001623284 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// same build, same loc, same callnum, one in another building
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
tearDown();
createIxInitVars("itemDisplayTests.mrc");
// Lane example with actual values
callnum = "Z3871.Z8 V.22 1945";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6661112", fldName, "36105082101390 -|- Lane -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// mult items same build, diff loc
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- Green -|- Bindery (Off-Campus) -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
| public final void testItemDisplayBuildings()
throws ParserConfigurationException, IOException, SAXException
{
String fldName = "item_display";
createIxInitVars("buildingTests.mrc");
assertDisplayFieldProperties(fldName);
assertFieldMultiValued(fldName);
// APPLIEDPHY ignored for building facet, but not here
String callnum = "HC241.25 .I4 D47";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("115472", fldName, "36105033811451 -|- APPLIEDPHY -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ARS
callnum = "HG6046 .V28 1986";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("229800", fldName, "36105034181003 -|- ARS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ART
callnum = "D764.7 .K72 1990";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("345228", fldName, "36105043140537 -|- Art -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// BIOLOGY
callnum = "E184.S75 R47A V.1 1980";
String lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, isSerial);
assertDocHasFieldValue("460947", fldName, "36105007402873 -|- Falconer -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CHEMCHMENG
callnum = "PA3998 .H2 O5 1977";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("919006", fldName, "36105036688153 -|- Swain -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CLASSICS
callnum = "PR9184.6 .M3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1147269", fldName, "36105037871261 -|- Classics -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// CPM
callnum = "PQ6653.A646.V5";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1391080", fldName, "36105038701285 -|- CPM -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EARTH-SCI
callnum = "TD811.5 .G76 1983";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1505065", fldName, "36105039395095 -|- Branner -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EAST-ASIA
callnum = "RD35 .H34 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6676531", fldName, "36105095758004 -|- East Asia -|- Japanese Collection -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// EDUCATION
callnum = "PQ6666.E7484 B4 1983";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1618836", fldName, "36105040261765 -|- Cubberley -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ENG
callnum = "352.042 .C594 ED.2";
lopped = CallNumUtils.removeDeweyVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1849258", fldName, "36105047516096 -|- Engineering -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GOV-DOCS
callnum = "DK43 .B63";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2099904", fldName, "36105041442281 -|- Government Docs -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GREEN
callnum = "MFILM N.S. 1350 REEL 230 NO. 3741";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1261173", fldName, "001AFX2969 -|- Green -|- Media-Microtext Collection (Lower Level) -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// GRN-REF
callnum = "PQ2678.I26 P54 1992";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2442876", fldName, "36105043436257 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HOOVER
callnum = "PQ6613 .A73 G44";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3743949", fldName, "3743949-1001 -|- Hoover Library -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HOPKINS
callnum = "DG579 .A5 A5 1995";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3027805", fldName, "36105016935392 -|- Hopkins -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// HV-ARCHIVE
callnum = "DC34.5 .A78 L4 1996";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3400092", fldName, "36105020376997 -|- Hoover Archives -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// ILB
callnum = "Z666 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1111", fldName, "36105129694373 -|- ILB -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// JACKSON
callnum = "GA 1.13:RCED-85-88";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2678655", fldName, "001ANE5736 -|- Jackson -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// LANE-MED
callnum = "X578 .S64 1851";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum, "LC", "7233951");
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("7233951", fldName, "LL124341 -|- Lane -|- Check Lane catalog for status -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// LAW
callnum = "Y 4.G 74/7:G 21/10";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4823592", fldName, "36105063104488 -|- Crown -|- Basement -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MATH-CS
callnum = "QA273 .C83 1962";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1732616", fldName, "36105033142303 -|- Math/CS -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MEYER
callnum = "B781 .A33 I55 1993";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2797607", fldName, "36105004381195 -|- Meyer -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// MUSIC
callnum = "ML410 .S54 I58 2000";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("5666387", fldName, "36105114964369 -|- Music -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// PHYSICS
callnum = "PS3553 .L337 F76 1978";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("3142611", fldName, "36105017175519 -|- Physics -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL
callnum = "DS135 .P6 I65";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2913114", fldName, "36105082973251 -|- SAL -|- Temporary Shelving -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL3
callnum = "159.32 .W211";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("690002", fldName, "36105046693508 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SAL-NEWARK
callnum = "Z7164.T23.W45";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("804724", fldName, "36105035887392 -|- SAL Newark -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SPEC-COLL
callnum = "NAS 1.26:205100";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4258089", fldName, "4258089-1001 -|- Special Collections -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SPEC-DESK
callnum = "S666 .P31 C6 1946";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2222", fldName, "36105129694373 -|- SPEC-DESK -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// TANNER
callnum = "PN1993.5 .I88 C5618 2000";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("4428936", fldName, "36105021909747 -|- Tanner -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// SUL
callnum = "F1356 .M464 2005";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6493823", fldName, "36105122224160 -|- SUL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// multiple items in single record, diff buildings
callnum = "BX4659.E85 W44";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1033119", fldName, "36105037439663 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "BX4659 .E85 W44 1982";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("1033119", fldName, "36105001623284 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// same build, same loc, same callnum, one in another building
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- SAL -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- SAL3 -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
tearDown();
createIxInitVars("itemDisplayTests.mrc");
// Lane example with actual values
callnum = "Z3871.Z8 V.22 1945";
lopped = CallNumUtils.removeLCVolSuffix(callnum);
shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("6661112", fldName, "36105082101390 -|- Lane -|- Stacks -|- " +
lopped + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
// mult items same build, diff loc
callnum = "PR3724.T3";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934432 -|- Green -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "PR3724.T3 A2";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105003934424 -|- Green -|- Bindery (Off-Campus) -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
callnum = "827.5 .S97TG";
shelfkey = edu.stanford.CallNumUtils.getShelfKey(callnum);
reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey);
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, callnum, !isSerial);
assertDocHasFieldValue("2328381", fldName, "36105048104132 -|- GRN-REF -|- Stacks -|- " +
callnum + sep + shelfkey + sep + reversekey + sep + callnum + sep + volSort);
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java
index 35c9018..3455e2a 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java
@@ -1,54 +1,54 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.mylar.bugzilla.tests.AllBugzillaTests;
import org.eclipse.mylar.core.tests.AllCoreTests;
import org.eclipse.mylar.core.util.ErrorLogger;
import org.eclipse.mylar.ide.MylarIdePlugin;
import org.eclipse.mylar.ide.tests.AllIdeTests;
import org.eclipse.mylar.java.tests.AllJavaTests;
import org.eclipse.mylar.monitor.tests.AllMonitorTests;
import org.eclipse.mylar.tasklist.tests.AllTasklistTests;
import org.eclipse.mylar.tests.integration.AllIntegrationTests;
import org.eclipse.mylar.tests.misc.AllMiscTests;
import org.eclipse.mylar.xml.tests.AllXmlTests;
/**
* @author Mik Kersten
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
ErrorLogger.setDumpErrors(true);
MylarIdePlugin.getDefault().setResourceMonitoringEnabled(false);
// TODO: the order of these tests matters, but shouldn't
//$JUnit-BEGIN$
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllIntegrationTests.suite());
- suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
+ suite.addTest(AllCoreTests.suite());
suite.addTest(AllIdeTests.suite());
suite.addTest(AllJavaTests.suite());
- suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
+ suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllBugzillaTests.suite());
suite.addTest(AllMiscTests.suite());
//$JUnit-END$
return suite;
}
}
| false | true | public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
ErrorLogger.setDumpErrors(true);
MylarIdePlugin.getDefault().setResourceMonitoringEnabled(false);
// TODO: the order of these tests matters, but shouldn't
//$JUnit-BEGIN$
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllIntegrationTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllIdeTests.suite());
suite.addTest(AllJavaTests.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(AllBugzillaTests.suite());
suite.addTest(AllMiscTests.suite());
//$JUnit-END$
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
ErrorLogger.setDumpErrors(true);
MylarIdePlugin.getDefault().setResourceMonitoringEnabled(false);
// TODO: the order of these tests matters, but shouldn't
//$JUnit-BEGIN$
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllIntegrationTests.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(AllIdeTests.suite());
suite.addTest(AllJavaTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllBugzillaTests.suite());
suite.addTest(AllMiscTests.suite());
//$JUnit-END$
return suite;
}
|
diff --git a/src/main/java/org/basex/io/serial/Serializer.java b/src/main/java/org/basex/io/serial/Serializer.java
index e3d618a40..368aa9926 100644
--- a/src/main/java/org/basex/io/serial/Serializer.java
+++ b/src/main/java/org/basex/io/serial/Serializer.java
@@ -1,484 +1,485 @@
package org.basex.io.serial;
import static org.basex.data.DataText.*;
import static org.basex.io.serial.SerializerProp.*;
import static org.basex.query.QueryText.*;
import static org.basex.query.util.Err.*;
import static org.basex.util.Token.*;
import java.io.*;
import org.basex.data.*;
import org.basex.query.iter.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;
/**
* This is an interface for serializing XQuery values.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public abstract class Serializer {
/** Default serialization parameters. */
public static final SerializerProp PROPS = new SerializerProp();
/** Stack with opened tag names. */
protected final TokenList tags = new TokenList();
/** Current level. */
protected int level;
/** Current tag. */
protected byte[] elem;
/** Undeclare prefixes. */
protected boolean undecl;
/** Indentation flag. */
protected boolean indent;
/** Stack with currently available namespaces. */
private final Atts nspaces = new Atts(XML, XMLURI).add(EMPTY, EMPTY);
/** Stack with namespace size pointers. */
private final IntList nstack = new IntList();
/** Indicates if an element is currently being opened. */
private boolean opening;
/**
* Returns an XML serializer.
* @param os output stream reference
* @return serializer
* @throws IOException I/O exception
*/
public static XMLSerializer get(final OutputStream os) throws IOException {
return new XMLSerializer(os, PROPS);
}
/**
* Returns a specific serializer.
* @param os output stream reference
* @param props serialization properties (can be {@code null})
* @return serializer
* @throws IOException I/O exception
*/
public static Serializer get(final OutputStream os, final SerializerProp props)
throws IOException {
if(props == null) return get(os);
final String m = props.check(S_METHOD, METHODS);
if(M_XHTML.equals(m)) return new XHTMLSerializer(os, props);
if(M_HTML.equals(m)) return new HTMLSerializer(os, props);
if(M_TEXT.equals(m)) return new TextSerializer(os, props);
if(M_JSON.equals(m)) return new JSONSerializer(os, props);
if(M_JSONML.equals(m)) return new JsonMLSerializer(os, props);
if(M_RAW.equals(m)) return new RawSerializer(os, props);
return new XMLSerializer(os, props);
}
// PUBLIC METHODS =====================================================================
/**
* Serializes the specified item, which may be a node or an atomic value.
* @param item item to be serialized
* @throws IOException I/O exception
*/
public final void serialize(final Item item) throws IOException {
openResult();
if(item instanceof ANode) {
final Type type = item.type;
if(type == NodeType.ATT) SERATTR.thrwSerial(item);
if(type == NodeType.NSP) SERNS.thrwSerial(item);
serialize((ANode) item);
} else if(item instanceof FItem) {
SERFUNC.thrwSerial(item.description());
} else {
finishElement();
atomic(item);
}
closeResult();
}
/**
* Closes the serializer.
* @throws IOException I/O exception
*/
@SuppressWarnings("unused")
public void close() throws IOException { }
/**
* Tests if the serialization was interrupted.
* @return result of check
*/
public boolean finished() {
return false;
}
/**
* Resets the serializer (indentation, etc).
*/
public void reset() { }
// PROTECTED METHODS ==================================================================
/**
* Opens an element.
* @param name element name
* @throws IOException I/O exception
*/
protected final void startElement(final byte[] name) throws IOException {
finishElement();
nstack.push(nspaces.size());
opening = true;
elem = name;
startOpen(name);
}
/**
* Closes an element.
* @throws IOException I/O exception
*/
protected final void closeElement() throws IOException {
nspaces.size(nstack.pop());
if(opening) {
finishEmpty();
opening = false;
} else {
elem = tags.pop();
level--;
finishClose();
}
}
/**
* Serializes a text.
* @param value value
* @param ftp full-text positions, used for visualization highlighting
* @throws IOException I/O exception
*/
@SuppressWarnings("unused")
protected void finishText(final byte[] value, final FTPos ftp) throws IOException {
text(value);
}
/**
* Gets the namespace URI currently bound by the given prefix.
* @param pref namespace prefix
* @return URI if found, {@code null} otherwise
*/
protected final byte[] nsUri(final byte[] pref) {
for(int n = nspaces.size() - 1; n >= 0; n--) {
if(eq(nspaces.name(n), pref)) return nspaces.value(n);
}
return null;
}
/**
* Serializes a namespace if it has not been serialized by an ancestor yet.
* @param pref prefix
* @param uri URI
* @throws IOException I/O exception
*/
protected void namespace(final byte[] pref, final byte[] uri) throws IOException {
if(!undecl && pref.length != 0 && uri.length == 0) return;
final byte[] u = nsUri(pref);
if(u == null || !eq(u, uri)) {
attribute(pref.length == 0 ? XMLNS : concat(XMLNSC, pref), uri);
nspaces.add(pref, uri);
}
}
/**
* Starts a result.
* @throws IOException I/O exception
*/
@SuppressWarnings("unused")
protected void openResult() throws IOException { }
/**
* Closes a result.
* @throws IOException I/O exception
*/
@SuppressWarnings("unused")
protected void closeResult() throws IOException { }
/**
* Opens a document.
* @param name name
* @throws IOException I/O exception
*/
@SuppressWarnings("unused")
protected void openDoc(final byte[] name) throws IOException { }
/**
* Closes a document.
* @throws IOException I/O exception
*/
@SuppressWarnings("unused")
protected void closeDoc() throws IOException { }
/**
* Serializes an attribute.
* @param name name
* @param value value
* @throws IOException I/O exception
*/
protected abstract void attribute(final byte[] name, final byte[] value)
throws IOException;
/**
* Starts an element.
* @param name tag name
* @throws IOException I/O exception
*/
protected abstract void startOpen(final byte[] name) throws IOException;
/**
* Finishes an opening element node.
* @throws IOException I/O exception
*/
protected abstract void finishOpen() throws IOException;
/**
* Closes an empty element.
* @throws IOException I/O exception
*/
protected abstract void finishEmpty() throws IOException;
/**
* Closes an element.
* @throws IOException I/O exception
*/
protected abstract void finishClose() throws IOException;
/**
* Serializes a text.
* @param value value
* @throws IOException I/O exception
*/
protected abstract void finishText(final byte[] value) throws IOException;
/**
* Serializes a comment.
* @param value value
* @throws IOException I/O exception
*/
protected abstract void finishComment(final byte[] value) throws IOException;
/**
* Serializes a processing instruction.
* @param name name
* @param value value
* @throws IOException I/O exception
*/
protected abstract void finishPi(final byte[] name, final byte[] value)
throws IOException;
/**
* Serializes an atomic value.
* @param item item
* @throws IOException I/O exception
*/
protected abstract void atomic(final Item item) throws IOException;
// PRIVATE METHODS ==========================================================
/**
* Serializes the specified node.
* @param node node to be serialized
* @throws IOException I/O exception
*/
private void serialize(final ANode node) throws IOException {
if(node instanceof DBNode) {
serialize((DBNode) node);
} else {
final Type type = node.type;
if(type == NodeType.COM) {
comment(node.string());
} else if(type == NodeType.TXT) {
text(node.string());
} else if(type == NodeType.PI) {
pi(node.name(), node.string());
} else if(type == NodeType.NSP) {
namespace(node.name(), node.string());
} else if(type == NodeType.DOC) {
openDoc(node.baseURI());
for(final ANode n : node.children()) serialize(n);
closeDoc();
} else {
// serialize elements (code will never be called for attributes)
final QNm name = node.qname();
startElement(name.string());
// serialize declared namespaces
final Atts nsp = node.namespaces();
for(int p = nsp.size() - 1; p >= 0; p--) {
namespace(nsp.name(p), nsp.value(p));
}
// add new or updated namespace
namespace(name.prefix(), name.uri());
// serialize attributes
final boolean i = indent;
AxisMoreIter ai = node.attributes();
for(ANode nd; (nd = ai.next()) != null;) {
final byte[] n = nd.name();
final byte[] v = nd.string();
attribute(n, v);
if(eq(n, XML_SPACE)) indent &= eq(v, DataText.DEFAULT);
}
// serialize children
ai = node.children();
for(ANode n; (n = ai.next()) != null;) serialize(n);
indent = i;
closeElement();
}
}
}
/**
* Serializes a node of the specified data reference.
* @param node database node
* @throws IOException I/O exception
*/
private void serialize(final DBNode node) throws IOException {
final FTPosData ft = node instanceof FTPosNode ? ((FTPosNode) node).ft : null;
final Data data = node.data;
int p = node.pre;
int k = data.kind(p);
if(k == Data.ATTR) SERATTR.thrwSerial(node);
boolean doc = false;
final TokenSet nsp = data.nspaces.size() != 0 ? new TokenSet() : null;
final IntList pars = new IntList();
final BoolList indt = new BoolList();
// loop through all table entries
final int s = p + data.size(p, k);
while(p < s && !finished()) {
k = data.kind(p);
final int r = data.parent(p, k);
// close opened elements...
while(!pars.isEmpty() && pars.peek() >= r) {
closeElement();
indent = indt.pop();
pars.pop();
}
if(k == Data.DOC) {
if(doc) closeDoc();
openDoc(data.text(p++, true));
doc = true;
} else if(k == Data.TEXT) {
final FTPos ftd = ft != null ? ft.get(data, p) : null;
if(ftd != null) text(data.text(p++, true), ftd);
else text(data.text(p++, true));
} else if(k == Data.COMM) {
comment(data.text(p++, true));
} else if(k == Data.PI) {
pi(data.name(p, k), data.atom(p++));
} else {
// add element node
final byte[] name = data.name(p, k);
startElement(name);
// add namespace definitions
if(nsp != null) {
// add namespaces from database
nsp.clear();
int pp = p;
// check namespace of current element
final byte[] u = data.nspaces.uri(data.uri(p, k));
namespace(prefix(name), u == null ? EMPTY : u);
do {
final Atts ns = data.ns(pp);
for(int n = 0; n < ns.size(); ++n) {
final byte[] pref = ns.name(n);
if(nsp.add(pref)) namespace(pref, ns.value(n));
}
// check ancestors only on top level
if(level != 0) break;
pp = data.parent(pp, data.kind(pp));
} while(pp >= 0 && data.kind(pp) == Data.ELEM);
}
// serialize attributes
indt.push(indent);
final int as = p + data.attSize(p, k);
while(++p != as) {
final byte[] n = data.name(p, Data.ATTR);
final byte[] v = data.text(p, false);
attribute(n, v);
if(eq(n, XML_SPACE)) indent &= eq(v, DataText.DEFAULT);
}
pars.push(r);
}
}
// process remaining elements...
while(!pars.isEmpty()) {
closeElement();
+ indent = indt.pop();
pars.pop();
}
if(doc) closeDoc();
}
/**
* Serializes a text.
* @param v text bytes
* @param ftp full-text positions, used for visualization highlighting
* @throws IOException I/O exception
*/
private void text(final byte[] v, final FTPos ftp) throws IOException {
finishElement();
finishText(v, ftp);
}
/**
* Serializes a comment.
* @param value value
* @throws IOException I/O exception
*/
private void comment(final byte[] value) throws IOException {
finishElement();
finishComment(value);
}
/**
* Serializes a text.
* @param value text bytes
* @throws IOException I/O exception
*/
private void text(final byte[] value) throws IOException {
finishElement();
finishText(value);
}
/**
* Serializes a processing instruction.
* @param name name
* @param value value
* @throws IOException I/O exception
*/
private void pi(final byte[] name, final byte[] value) throws IOException {
finishElement();
finishPi(name, value);
}
/**
* Finishes an opening element node if necessary.
* @throws IOException I/O exception
*/
private void finishElement() throws IOException {
if(!opening) return;
opening = false;
finishOpen();
tags.push(elem);
level++;
}
}
| true | true | private void serialize(final DBNode node) throws IOException {
final FTPosData ft = node instanceof FTPosNode ? ((FTPosNode) node).ft : null;
final Data data = node.data;
int p = node.pre;
int k = data.kind(p);
if(k == Data.ATTR) SERATTR.thrwSerial(node);
boolean doc = false;
final TokenSet nsp = data.nspaces.size() != 0 ? new TokenSet() : null;
final IntList pars = new IntList();
final BoolList indt = new BoolList();
// loop through all table entries
final int s = p + data.size(p, k);
while(p < s && !finished()) {
k = data.kind(p);
final int r = data.parent(p, k);
// close opened elements...
while(!pars.isEmpty() && pars.peek() >= r) {
closeElement();
indent = indt.pop();
pars.pop();
}
if(k == Data.DOC) {
if(doc) closeDoc();
openDoc(data.text(p++, true));
doc = true;
} else if(k == Data.TEXT) {
final FTPos ftd = ft != null ? ft.get(data, p) : null;
if(ftd != null) text(data.text(p++, true), ftd);
else text(data.text(p++, true));
} else if(k == Data.COMM) {
comment(data.text(p++, true));
} else if(k == Data.PI) {
pi(data.name(p, k), data.atom(p++));
} else {
// add element node
final byte[] name = data.name(p, k);
startElement(name);
// add namespace definitions
if(nsp != null) {
// add namespaces from database
nsp.clear();
int pp = p;
// check namespace of current element
final byte[] u = data.nspaces.uri(data.uri(p, k));
namespace(prefix(name), u == null ? EMPTY : u);
do {
final Atts ns = data.ns(pp);
for(int n = 0; n < ns.size(); ++n) {
final byte[] pref = ns.name(n);
if(nsp.add(pref)) namespace(pref, ns.value(n));
}
// check ancestors only on top level
if(level != 0) break;
pp = data.parent(pp, data.kind(pp));
} while(pp >= 0 && data.kind(pp) == Data.ELEM);
}
// serialize attributes
indt.push(indent);
final int as = p + data.attSize(p, k);
while(++p != as) {
final byte[] n = data.name(p, Data.ATTR);
final byte[] v = data.text(p, false);
attribute(n, v);
if(eq(n, XML_SPACE)) indent &= eq(v, DataText.DEFAULT);
}
pars.push(r);
}
}
// process remaining elements...
while(!pars.isEmpty()) {
closeElement();
pars.pop();
}
if(doc) closeDoc();
}
| private void serialize(final DBNode node) throws IOException {
final FTPosData ft = node instanceof FTPosNode ? ((FTPosNode) node).ft : null;
final Data data = node.data;
int p = node.pre;
int k = data.kind(p);
if(k == Data.ATTR) SERATTR.thrwSerial(node);
boolean doc = false;
final TokenSet nsp = data.nspaces.size() != 0 ? new TokenSet() : null;
final IntList pars = new IntList();
final BoolList indt = new BoolList();
// loop through all table entries
final int s = p + data.size(p, k);
while(p < s && !finished()) {
k = data.kind(p);
final int r = data.parent(p, k);
// close opened elements...
while(!pars.isEmpty() && pars.peek() >= r) {
closeElement();
indent = indt.pop();
pars.pop();
}
if(k == Data.DOC) {
if(doc) closeDoc();
openDoc(data.text(p++, true));
doc = true;
} else if(k == Data.TEXT) {
final FTPos ftd = ft != null ? ft.get(data, p) : null;
if(ftd != null) text(data.text(p++, true), ftd);
else text(data.text(p++, true));
} else if(k == Data.COMM) {
comment(data.text(p++, true));
} else if(k == Data.PI) {
pi(data.name(p, k), data.atom(p++));
} else {
// add element node
final byte[] name = data.name(p, k);
startElement(name);
// add namespace definitions
if(nsp != null) {
// add namespaces from database
nsp.clear();
int pp = p;
// check namespace of current element
final byte[] u = data.nspaces.uri(data.uri(p, k));
namespace(prefix(name), u == null ? EMPTY : u);
do {
final Atts ns = data.ns(pp);
for(int n = 0; n < ns.size(); ++n) {
final byte[] pref = ns.name(n);
if(nsp.add(pref)) namespace(pref, ns.value(n));
}
// check ancestors only on top level
if(level != 0) break;
pp = data.parent(pp, data.kind(pp));
} while(pp >= 0 && data.kind(pp) == Data.ELEM);
}
// serialize attributes
indt.push(indent);
final int as = p + data.attSize(p, k);
while(++p != as) {
final byte[] n = data.name(p, Data.ATTR);
final byte[] v = data.text(p, false);
attribute(n, v);
if(eq(n, XML_SPACE)) indent &= eq(v, DataText.DEFAULT);
}
pars.push(r);
}
}
// process remaining elements...
while(!pars.isEmpty()) {
closeElement();
indent = indt.pop();
pars.pop();
}
if(doc) closeDoc();
}
|
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/configuration/security/DefaultNexusSecurityConfiguration.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/configuration/security/DefaultNexusSecurityConfiguration.java
index 7594ff470..64495ca27 100644
--- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/configuration/security/DefaultNexusSecurityConfiguration.java
+++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/configuration/security/DefaultNexusSecurityConfiguration.java
@@ -1,886 +1,886 @@
/*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.configuration.security;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException;
import org.codehaus.plexus.util.StringUtils;
import org.sonatype.nexus.configuration.ConfigurationChangeEvent;
import org.sonatype.nexus.configuration.ConfigurationChangeListener;
import org.sonatype.nexus.configuration.ConfigurationException;
import org.sonatype.nexus.configuration.application.NexusConfiguration;
import org.sonatype.nexus.configuration.model.CRepository;
import org.sonatype.nexus.configuration.model.CRepositoryTarget;
import org.sonatype.nexus.configuration.security.model.CApplicationPrivilege;
import org.sonatype.nexus.configuration.security.model.CPrivilege;
import org.sonatype.nexus.configuration.security.model.CRepoTargetPrivilege;
import org.sonatype.nexus.configuration.security.model.CRole;
import org.sonatype.nexus.configuration.security.model.CUser;
import org.sonatype.nexus.configuration.security.model.Configuration;
import org.sonatype.nexus.configuration.security.runtime.SecurityRuntimeConfigurationBuilder;
import org.sonatype.nexus.configuration.security.source.FileConfigurationSource;
import org.sonatype.nexus.configuration.security.source.SecurityConfigurationSource;
import org.sonatype.nexus.configuration.security.validator.SecurityConfigurationValidator;
import org.sonatype.nexus.configuration.security.validator.SecurityValidationContext;
import org.sonatype.nexus.configuration.security.validator.SecurityValidationResponse;
import org.sonatype.nexus.configuration.validator.InvalidConfigurationException;
import org.sonatype.nexus.configuration.validator.ValidationMessage;
import org.sonatype.nexus.configuration.validator.ValidationResponse;
import org.sonatype.nexus.proxy.NoSuchRepositoryException;
import org.sonatype.nexus.proxy.NoSuchRepositoryGroupException;
import org.sonatype.nexus.proxy.registry.ContentClass;
import org.sonatype.nexus.proxy.registry.RepositoryRegistry;
import org.sonatype.nexus.smtp.SmtpClient;
import org.sonatype.nexus.smtp.SmtpClientException;
/**
* The class DefaultNexusSecurityConfiguration is responsible for config management. It actually keeps in sync Nexus internal
* state with persisted user configuration. All changes incoming thru its iface is reflect/maintained in Nexus current
* state and Nexus user config.
*
* @author cstamas
* @plexus.component
*/
public class DefaultNexusSecurityConfiguration
extends AbstractLogEnabled
implements
NexusSecurityConfiguration,
ConfigurationChangeListener
{
/**
* The nexus configuration. Used to initialize the list of repo targets
*
* @plexus.requirement
*/
private NexusConfiguration nexusConfiguration;
/**
* The repository registry.
*
* @plexus.requirement
*/
private RepositoryRegistry repositoryRegistry;
/**
* The configuration source.
*
* @plexus.requirement role-hint="file"
*/
private SecurityConfigurationSource configurationSource;
/**
* The smtp client for sending mails.
*
* @plexus.requirement
*/
private SmtpClient smtpClient;
/**
* The config validator.
*
* @plexus.requirement
*/
private SecurityConfigurationValidator configurationValidator;
/**
* @plexus.requirement
*/
private PasswordGenerator pwGenerator;
/**
* The runtime configuration builder.
*
* @plexus.requirement
*/
private SecurityRuntimeConfigurationBuilder runtimeConfigurationBuilder;
/** The config event listeners. */
private CopyOnWriteArrayList<ConfigurationChangeListener> configurationChangeListeners =
new CopyOnWriteArrayList<ConfigurationChangeListener>();
public void onConfigurationChange( ConfigurationChangeEvent evt )
{
getLogger().debug( "Nexus Configuration Loaded, now loading Security Configuration" );
try
{
if ( FileConfigurationSource.class.isAssignableFrom( configurationSource.getClass() ) )
{
( ( FileConfigurationSource ) configurationSource ).setConfigurationFile( new File( nexusConfiguration.readSecurityConfigurationFile() ) );
}
loadConfiguration( true );
notifyConfigurationChangeListeners();
}
catch ( ConfigurationException e )
{
getLogger().error( "Could not start Nexus Security, user configuration exception!", e );
}
catch ( IOException e )
{
getLogger().error( "Could not start Nexus Security, bad IO exception!", e );
}
}
public void startService()
throws StartingException
{
nexusConfiguration.addConfigurationChangeListener( this );
getLogger().info( "Started Nexus Security" );
}
public void stopService()
throws StoppingException
{
getLogger().info( "Stopped Nexus Security" );
}
public void loadConfiguration()
throws ConfigurationException,
IOException
{
loadConfiguration( false );
}
public void loadConfiguration( boolean force )
throws ConfigurationException,
IOException
{
if ( force || configurationSource.getConfiguration() == null )
{
getLogger().debug( "Loading Nexus Security Configuration..." );
configurationSource.loadConfiguration();
// and register things
runtimeConfigurationBuilder.initialize( this );
notifyConfigurationChangeListeners();
}
}
public void applyConfiguration()
throws IOException
{
getLogger().debug( "Applying Nexus Security Configuration..." );
notifyConfigurationChangeListeners();
}
public void saveConfiguration()
throws IOException
{
configurationSource.storeConfiguration();
}
protected void applyAndSaveConfiguration()
throws IOException
{
applyConfiguration();
saveConfiguration();
}
public void addConfigurationChangeListener( ConfigurationChangeListener listener )
{
configurationChangeListeners.add( listener );
}
public void removeConfigurationChangeListener( ConfigurationChangeListener listener )
{
configurationChangeListeners.remove( listener );
}
public void notifyConfigurationChangeListeners()
{
notifyConfigurationChangeListeners( new ConfigurationChangeEvent( this ) );
}
public void notifyConfigurationChangeListeners( ConfigurationChangeEvent evt )
{
for ( ConfigurationChangeListener l : configurationChangeListeners )
{
try
{
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "Notifying component about config change: " + l.getClass().getName() );
}
l.onConfigurationChange( evt );
}
catch ( Exception e )
{
getLogger().info( "Unexpected exception in listener", e );
}
}
}
public Configuration getConfiguration()
{
return configurationSource.getConfiguration();
}
public SecurityConfigurationSource getConfigurationSource()
{
return configurationSource;
}
public InputStream getConfigurationAsStream()
throws IOException
{
return configurationSource.getConfigurationAsStream();
}
public boolean isInstanceUpgraded()
{
// TODO: this is not quite true: we might keep model ver but upgrade JARs of Nexus only in a release
// we should store the nexus version somewhere in working storage and trigger some household stuff
// if version changes.
return configurationSource.isConfigurationUpgraded();
}
public boolean isConfigurationUpgraded()
{
return configurationSource.isConfigurationUpgraded();
}
public boolean isConfigurationDefaulted()
{
return configurationSource.isConfigurationDefaulted();
}
/**
* User CRUD
*/
public Collection<CUser> listUsers()
{
return new ArrayList<CUser>( getConfiguration().getUsers() );
}
private String generateNewPassword( CUser settings )
{
String password = pwGenerator.generatePassword( 10, 10 );
settings.setPassword( pwGenerator.hashPassword( password ) );
settings.setStatus( CUser.STATUS_EXPIRED );
return password;
}
public void createUser( CUser settings )
throws ConfigurationException,
IOException
{
//On create we need to generate a new password, and email the user their new password
String password = generateNewPassword( settings );
ValidationResponse vr = configurationValidator.validateUser( initializeContext(), settings, false );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getUsers().add( settings );
applyAndSaveConfiguration();
try
{
smtpClient.sendEmail( settings.getEmail(), null, "Nexus: New user account created.", "User Account " + settings.getUserId() + " has been created. Another email will be sent shortly containing your password." );
smtpClient.sendEmail( settings.getEmail(), null, "Nexus: New user account created.", "Your new password is " + password );
}
catch ( SmtpClientException e )
{
getLogger().error( "Unable to notify user by email for new user creation", e );
}
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CUser readUser( String id )
throws NoSuchUserException
{
List<CUser> users = getConfiguration().getUsers();
for ( CUser user : users )
{
if ( user.getUserId().equals( id ) )
{
return user;
}
}
throw new NoSuchUserException( id );
}
public void updateUser( CUser settings )
throws NoSuchUserException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateUser( initializeContext(), settings, true );
if ( vr.isValid() )
{
List<CUser> users = getConfiguration().getUsers();
for ( int i = 0; i < users.size(); i++ )
{
CUser user = users.get( i );
if ( user.getUserId().equals( settings.getUserId() ) )
{
users.remove( i );
users.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchUserException( settings.getUserId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteUser( String id )
throws NoSuchUserException,
IOException
{
List<CUser> users = getConfiguration().getUsers();
for ( Iterator<CUser> i = users.iterator(); i.hasNext(); )
{
CUser user = i.next();
if ( user.getUserId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchUserException( id );
}
public void resetPassword( String id )
throws IOException,
NoSuchUserException
{
CUser user = readUser( id );
String password = generateNewPassword( user );
applyAndSaveConfiguration();
try
{
smtpClient.sendEmail( user.getEmail(), null, "Nexus: User account notification.", "Your password has been reset. Your new password is: " + password );
}
catch ( SmtpClientException e )
{
getLogger().error( "Unable to notify user by email password reset", e );
}
}
public void forgotPassword( String userId, String email )
throws IOException,
NoSuchUserException
{
CUser user = readUser( userId );
if ( user.getEmail().equals( email ) )
{
resetPassword( userId );
}
}
public void forgotUserId( String email )
throws IOException,
NoSuchUserException
{
List<CUser> users = getConfiguration().getUsers();
for ( Iterator<CUser> i = users.iterator(); i.hasNext(); )
{
CUser user = i.next();
if ( user.getEmail().equals( email ) )
{
try
{
smtpClient.sendEmail( user.getEmail(), null, "Nexus: User account notification.", " Your User ID is: " + user.getUserId() );
}
catch ( SmtpClientException e )
{
getLogger().error( "Unable to notify user by email for username reminder", e );
}
return;
}
}
throw new NoSuchUserException();
}
/**
* Role CRUD
*/
public Collection<CRole> listRoles()
{
return new ArrayList<CRole>( getConfiguration().getRoles() );
}
public void createRole( CRole settings )
throws ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRole( initializeContext(), settings, false );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getRoles().add( settings );
applyAndSaveConfiguration();
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CRole readRole( String id )
throws NoSuchRoleException
{
List<CRole> roles = getConfiguration().getRoles();
for ( CRole role : roles )
{
if ( role.getId().equals( id ) )
{
return role;
}
}
throw new NoSuchRoleException( id );
}
public void updateRole( CRole settings )
throws NoSuchRoleException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRole( initializeContext(), settings, true );
if ( vr.isValid() )
{
List<CRole> roles = getConfiguration().getRoles();
for ( int i = 0; i < roles.size(); i++ )
{
CRole role = roles.get( i );
if ( role.getId().equals( settings.getId() ) )
{
roles.remove( i );
roles.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchRoleException( settings.getId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteRole( String id )
throws NoSuchRoleException,
IOException
{
List<CRole> roles = getConfiguration().getRoles();
for ( Iterator<CRole> i = roles.iterator(); i.hasNext(); )
{
CRole role = i.next();
if ( role.getId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchRoleException( id );
}
/**
* Application Privilege CRUD
*/
public Collection<CApplicationPrivilege> listApplicationPrivileges()
{
return new ArrayList<CApplicationPrivilege>( getConfiguration().getApplicationPrivileges() );
}
public void createApplicationPrivilege( CApplicationPrivilege settings )
throws ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateApplicationPrivilege( initializeContext(), settings, false );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getApplicationPrivileges().add( settings );
applyAndSaveConfiguration();
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CApplicationPrivilege readApplicationPrivilege( String id )
throws NoSuchPrivilegeException
{
List<CApplicationPrivilege> privs = getConfiguration().getApplicationPrivileges();
for ( CApplicationPrivilege priv : privs )
{
if ( priv.getId().equals( id ) )
{
return priv;
}
}
throw new NoSuchPrivilegeException( id );
}
public void updateApplicationPrivilege( CApplicationPrivilege settings )
throws NoSuchPrivilegeException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateApplicationPrivilege( initializeContext(), settings, true );
if ( vr.isValid() )
{
List<CApplicationPrivilege> privs = getConfiguration().getApplicationPrivileges();
for ( int i = 0; i < privs.size(); i++ )
{
CApplicationPrivilege priv = privs.get( i );
if ( priv.getId().equals( settings.getId() ) )
{
privs.remove( i );
privs.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( settings.getId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteApplicationPrivilege( String id )
throws NoSuchPrivilegeException,
IOException
{
List<CApplicationPrivilege> privs = getConfiguration().getApplicationPrivileges();
for ( Iterator<CApplicationPrivilege> i = privs.iterator(); i.hasNext(); )
{
CApplicationPrivilege priv = i.next();
if ( priv.getId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( id );
}
/**
* Repository Target Privilege CRUD
*/
public Collection<CRepoTargetPrivilege> listRepoTargetPrivileges()
{
return new ArrayList<CRepoTargetPrivilege>( getConfiguration().getRepositoryTargetPrivileges() );
}
private ValidationResponse crossValidateRepoTargetPrivilege( CRepoTargetPrivilege settings )
{
ValidationResponse vr = new SecurityValidationResponse();
CRepositoryTarget target = nexusConfiguration.readRepositoryTarget( settings.getRepositoryTargetId() );
// Invalid target ID
if ( target == null )
{
ValidationMessage error = new ValidationMessage( "repositoryTargetId", "Privilege ID '" + settings.getId()
+ "' has invalid repository target ID '" + settings.getRepositoryTargetId() + "'",
"Repository Target doesn't exist" );
vr.addValidationError( error );
}
else
{
if ( !StringUtils.isEmpty( settings.getRepositoryId() ) )
{
try
{
CRepository repo = nexusConfiguration.readRepository( settings.getRepositoryId() );
// Invalid Repo/Target content types
- if ( !repo.getRepositoryPolicy().equals( target.getContentClass() ) )
+ if ( !repo.getType().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has repository and repository target of different types",
"Content type differs between repository and target.");
vr.addValidationError( error );
}
}
// Invalid repo selection
catch ( NoSuchRepositoryException e )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has invalid repository ID '" + settings.getRepositoryId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else if ( !StringUtils.isEmpty( settings.getGroupId() ) )
{
try
{
ContentClass content = repositoryRegistry.getRepositoryGroupContentClass( settings.getGroupId() );
// Invalid group/target content types
if ( !content.getId().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has repository group and repository target of different types",
"Content type differs between repository group and target.");
vr.addValidationError( error );
}
}
// Invalid group selection
catch ( NoSuchRepositoryGroupException e )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has invalid repository group ID '" + settings.getGroupId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else
{
//All is well
}
}
return vr;
}
public void createRepoTargetPrivilege( CRepoTargetPrivilege settings )
throws ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRepoTargetPrivilege( initializeContext(), settings, false );
vr.append( crossValidateRepoTargetPrivilege( settings ) );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getRepositoryTargetPrivileges().add( settings );
applyAndSaveConfiguration();
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CRepoTargetPrivilege readRepoTargetPrivilege( String id )
throws NoSuchPrivilegeException
{
List<CRepoTargetPrivilege> privs = getConfiguration().getRepositoryTargetPrivileges();
for ( CRepoTargetPrivilege priv : privs )
{
if ( priv.getId().equals( id ) )
{
return priv;
}
}
throw new NoSuchPrivilegeException( id );
}
public void updateRepoTargetPrivilege( CRepoTargetPrivilege settings )
throws NoSuchPrivilegeException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRepoTargetPrivilege( initializeContext(), settings, true );
vr.append( crossValidateRepoTargetPrivilege( settings ) );
if ( vr.isValid() )
{
List<CRepoTargetPrivilege> privs = getConfiguration().getRepositoryTargetPrivileges();
for ( int i = 0; i < privs.size(); i++ )
{
CRepoTargetPrivilege priv = privs.get( i );
if ( priv.getId().equals( settings.getId() ) )
{
privs.remove( i );
privs.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( settings.getId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteRepoTargetPrivilege( String id )
throws NoSuchPrivilegeException,
IOException
{
List<CRepoTargetPrivilege> privs = getConfiguration().getRepositoryTargetPrivileges();
for ( Iterator<CRepoTargetPrivilege> i = privs.iterator(); i.hasNext(); )
{
CRepoTargetPrivilege priv = i.next();
if ( priv.getId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( id );
}
private SecurityValidationContext initializeContext()
{
SecurityValidationContext context = new SecurityValidationContext();
context.addExistingUserIds();
context.addExistingRoleIds();
context.addExistingPrivilegeIds();
for ( CUser user : listUsers() )
{
context.getExistingUserIds().add( user.getUserId() );
context.getExistingEmailMap().put( user.getUserId(), user.getEmail() );
}
for ( CRole role : listRoles() )
{
context.getExistingRoleIds().add( role.getId() );
ArrayList<String> containedRoles = new ArrayList<String>();
containedRoles.addAll( role.getRoles() );
context.getRoleContainmentMap().put( role.getId(), containedRoles );
}
for ( CPrivilege priv : listApplicationPrivileges() )
{
context.getExistingPrivilegeIds().add( priv.getId() );
}
for ( CPrivilege priv : listRepoTargetPrivileges() )
{
context.getExistingPrivilegeIds().add( priv.getId() );
}
return context;
}
}
| true | true | private ValidationResponse crossValidateRepoTargetPrivilege( CRepoTargetPrivilege settings )
{
ValidationResponse vr = new SecurityValidationResponse();
CRepositoryTarget target = nexusConfiguration.readRepositoryTarget( settings.getRepositoryTargetId() );
// Invalid target ID
if ( target == null )
{
ValidationMessage error = new ValidationMessage( "repositoryTargetId", "Privilege ID '" + settings.getId()
+ "' has invalid repository target ID '" + settings.getRepositoryTargetId() + "'",
"Repository Target doesn't exist" );
vr.addValidationError( error );
}
else
{
if ( !StringUtils.isEmpty( settings.getRepositoryId() ) )
{
try
{
CRepository repo = nexusConfiguration.readRepository( settings.getRepositoryId() );
// Invalid Repo/Target content types
if ( !repo.getRepositoryPolicy().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has repository and repository target of different types",
"Content type differs between repository and target.");
vr.addValidationError( error );
}
}
// Invalid repo selection
catch ( NoSuchRepositoryException e )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has invalid repository ID '" + settings.getRepositoryId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else if ( !StringUtils.isEmpty( settings.getGroupId() ) )
{
try
{
ContentClass content = repositoryRegistry.getRepositoryGroupContentClass( settings.getGroupId() );
// Invalid group/target content types
if ( !content.getId().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has repository group and repository target of different types",
"Content type differs between repository group and target.");
vr.addValidationError( error );
}
}
// Invalid group selection
catch ( NoSuchRepositoryGroupException e )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has invalid repository group ID '" + settings.getGroupId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else
{
//All is well
}
}
return vr;
}
| private ValidationResponse crossValidateRepoTargetPrivilege( CRepoTargetPrivilege settings )
{
ValidationResponse vr = new SecurityValidationResponse();
CRepositoryTarget target = nexusConfiguration.readRepositoryTarget( settings.getRepositoryTargetId() );
// Invalid target ID
if ( target == null )
{
ValidationMessage error = new ValidationMessage( "repositoryTargetId", "Privilege ID '" + settings.getId()
+ "' has invalid repository target ID '" + settings.getRepositoryTargetId() + "'",
"Repository Target doesn't exist" );
vr.addValidationError( error );
}
else
{
if ( !StringUtils.isEmpty( settings.getRepositoryId() ) )
{
try
{
CRepository repo = nexusConfiguration.readRepository( settings.getRepositoryId() );
// Invalid Repo/Target content types
if ( !repo.getType().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has repository and repository target of different types",
"Content type differs between repository and target.");
vr.addValidationError( error );
}
}
// Invalid repo selection
catch ( NoSuchRepositoryException e )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has invalid repository ID '" + settings.getRepositoryId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else if ( !StringUtils.isEmpty( settings.getGroupId() ) )
{
try
{
ContentClass content = repositoryRegistry.getRepositoryGroupContentClass( settings.getGroupId() );
// Invalid group/target content types
if ( !content.getId().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has repository group and repository target of different types",
"Content type differs between repository group and target.");
vr.addValidationError( error );
}
}
// Invalid group selection
catch ( NoSuchRepositoryGroupException e )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has invalid repository group ID '" + settings.getGroupId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else
{
//All is well
}
}
return vr;
}
|
diff --git a/src/lobos/andrew/cuptagclient/CheckCup.java b/src/lobos/andrew/cuptagclient/CheckCup.java
index 6234be2..bbe584f 100644
--- a/src/lobos/andrew/cuptagclient/CheckCup.java
+++ b/src/lobos/andrew/cuptagclient/CheckCup.java
@@ -1,68 +1,68 @@
package lobos.andrew.cuptagclient;
import java.io.ByteArrayOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class CheckCup extends android.os.AsyncTask<String, Integer, String> {
Context context;
public CheckCup(Context context)
{
super();
this.context = context;
}
@Override
protected String doInBackground(String... input) {
try
{
if ( input.length != 2 )
return "Bad request";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("http://andrew.lobos.me/cans/check.php?data="+input[0]+"&name="+input[1]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
- return out.toString();
+ return out.toString();
}
else
{
return "Request Failed";
}
} catch (Exception e)
{
return "Request Failed "+e.getMessage();
}
}
protected void onPostExecute(String result)
{
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Result").setMessage(result);
alert.setCancelable(false);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
}
}
| true | true | protected String doInBackground(String... input) {
try
{
if ( input.length != 2 )
return "Bad request";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("http://andrew.lobos.me/cans/check.php?data="+input[0]+"&name="+input[1]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return out.toString();
}
else
{
return "Request Failed";
}
} catch (Exception e)
{
return "Request Failed "+e.getMessage();
}
}
| protected String doInBackground(String... input) {
try
{
if ( input.length != 2 )
return "Bad request";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("http://andrew.lobos.me/cans/check.php?data="+input[0]+"&name="+input[1]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return out.toString();
}
else
{
return "Request Failed";
}
} catch (Exception e)
{
return "Request Failed "+e.getMessage();
}
}
|
diff --git a/src/tconstruct/library/TConstructRegistry.java b/src/tconstruct/library/TConstructRegistry.java
index 301d5bc4c..43228caca 100644
--- a/src/tconstruct/library/TConstructRegistry.java
+++ b/src/tconstruct/library/TConstructRegistry.java
@@ -1,705 +1,707 @@
package tconstruct.library;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import tconstruct.library.crafting.Detailing;
import tconstruct.library.crafting.LiquidCasting;
import tconstruct.library.crafting.ToolBuilder;
import tconstruct.library.tools.ArrowMaterial;
import tconstruct.library.tools.BowMaterial;
import tconstruct.library.tools.BowstringMaterial;
import tconstruct.library.tools.CustomMaterial;
import tconstruct.library.tools.FletchingMaterial;
import tconstruct.library.tools.ToolCore;
import tconstruct.library.tools.ToolMaterial;
import tconstruct.library.util.TabTools;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/** A registry to store any relevant API work
*
* @author mDiyo
*/
public class TConstructRegistry
{
public static TConstructRegistry instance = new TConstructRegistry();
/* Creative tabs */
public static TabTools toolTab;
public static TabTools materialTab;
public static TabTools blockTab;
/* Items */
/** A directory of crafting items and tools used by the mod.
*
* Tools:
* pickaxe, shovel, hatchet, broadsword, longsword, rapier, dagger, cutlass
* frypan, battlesign, mattock, chisel
* lumberaxe, cleaver, scythe, excavator, hammer, battleaxe
*
* Patterns:
* blankPattern, woodPattern, metalPattern
*
* Tool crafting parts:
* toolRod, toolShard, binding, toughBinding, toughRod, heavyPlate
* pickaxeHead, shovelhead, hatchetHead, swordBlade, wideguard, handGuard, crossbar, knifeBlade,
* fullGuard, frypanHead, signHead, chiselHead
* scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead
* bowstring, fletching, arrowhead
*/
public static HashMap<String, Item> itemDirectory = new HashMap<String, Item>();
/** Adds an item to the directory
*
* @param name Associates the name with the stack
* @param itemstack The stack to add to the directory
*/
public static void addItemToDirectory (String name, Item itemstack)
{
Item add = itemDirectory.get(name);
if (add != null)
System.out.println("[TCon API] " + name + " is already present in the Item directory");
itemDirectory.put(name, itemstack);
}
/** Retrieves an itemstack from the directory
*
* @param name The name of the item to get
* @return Item associated with the name, or null if not present.
*/
public static Item getItem (String name)
{
Item ret = itemDirectory.get(name);
if (ret == null)
System.out.println("[TCon API] Could not find " + name + " in the Item directory");
return ret;
}
/** A directory of ItemStacks. Contains mostly crafting items
*
* Materials:
* paperStack, greenSlimeCrystal, blueSlimeCrystal, searedBrick, mossBall, lavaCrystal, necroticBone, silkyCloth, silkyJewel
* ingotCobalt, ingotArdite, ingotManyullyn, ingotCopper, ingotTin, ingotAluminum, rawAluminum,
* ingotBronze, ingotAluminumBrass, ingotAlumite, ingotSteel, ingotObsidian
* nuggetIron, nuggetCopper, nuggetTin, nuggetAluminum, nuggetSilver, nuggetAluminumBrass
* oreberryIron, oreberryGold, oreberryCopper, oreberryTin, oreberryTin, oreberrySilver,
* diamondApple, blueSlimeFood, canisterEmpty, miniRedHeart, canisterRedHeart
*
* Patterns - These have a suffix of Pattern or Cast. ex: hatchetHeadPattern
* ingot, toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead,
* knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheHead, excavatorHead, largeBlade, hammerHead, fullGuard, bowstring
*/
static HashMap<String, ItemStack> itemstackDirectory = new HashMap<String, ItemStack>();
/** Adds an itemstack to the directory
*
* @param name Associates the name with the stack
* @param itemstack The stack to add to the directory
*/
public static void addItemStackToDirectory (String name, ItemStack itemstack)
{
ItemStack add = itemstackDirectory.get(name);
if (add != null)
System.out.println("[TCon API] " + name + " is already present in the ItemStack directory");
itemstackDirectory.put(name, itemstack);
}
/** Retrieves an itemstack from the directory
*
* @param name The name of the item to get
* @return Item associated with the name, or null if not present.
*/
public static ItemStack getItemStack (String name)
{
ItemStack ret = itemstackDirectory.get(name);
if (ret == null)
System.out.println("[TCon API] Could not find " + name + " in the ItemStack directory");
return ret;
}
public static ArrayList<ToolCore> tools = new ArrayList<ToolCore>(20);
//Parts
/** List: Item ID, metadata, material ID
* ItemStack: Output. Ex: Cactus Binding
*/
public static HashMap<List, ItemStack> patternPartMapping = new HashMap<List, ItemStack>();
/** Maps an item and a material ID to an output part
*
* @param patternID ID to check against
* @param patternMeta Metadata to check against
* @param materialID Material that goes with the item
* @param output The resulting part
*/
public static void addPartMapping (int patternID, int patternMeta, int materialID, ItemStack output)
{
patternPartMapping.put(Arrays.asList(patternID, patternMeta, materialID), output);
}
public static ItemStack getPartMapping (int itemID, int metadata, int materialID)
{
ItemStack stack = patternPartMapping.get(Arrays.asList(itemID, metadata, materialID));
if (stack != null)
return stack.copy();
return null;
}
//Tools
/** Internal tool mapping, used for adding textures
*
* @param tool
*/
public static void addToolMapping (ToolCore tool)
{
tools.add(tool);
}
/** Internal tool mapping, used for adding textures
*
* @return List of tools
*/
public static ArrayList<ToolCore> getToolMapping ()
{
return tools;
}
/** Registers a tool to its crafting parts.
* If an output is registered multiple times the parts are added to the recipe's input list
* Valid part amounts are 1, 2, and 4. Part counts of 1 and 2 assume a Tool Rod as a handle.
* Null items are valid as placeholders. ex: Hatchet
*
* @see ToolBuidler
* @param output The ToolCore to craft
* @param parts Pieces to make the tool with
*/
public static void addToolRecipe (ToolCore output, Item... parts)
{
ToolBuilder tb = ToolBuilder.instance;
if (parts.length < 1 || parts.length > 4 || parts.length == 3)
System.out.println("[TCon API] Wrong amount of items to craft into a tool");
tb.addToolRecipe(output, parts);
}
//Materials
public static HashMap<Integer, ToolMaterial> toolMaterials = new HashMap<Integer, ToolMaterial>(40);
public static HashMap<String, ToolMaterial> toolMaterialStrings = new HashMap<String, ToolMaterial>(40);
/** Adds a tool material to the registry
*
* @param materialID Unique ID, stored for each part
* @exception materialID must be unique
* @param materialName Unique name for data lookup purposes
* @param harvestLevel The materials which the tool can harvest. Pickaxe levels - 0: Wood, 1: Stone, 2: Redstone/Diamond, 3: Obsidian, 4: Cobalt/Ardite, 5: Manyullyn
* @param durability Base durability of the tool, affects tool heads.
* @param miningspeed Base mining speed, divided by 100 in use
* @param attack Base attack
* @param handleModifier Durability multiplier on the tool
* @param reinforced Reinforced level
* @param stonebound Amount of Stonebound to put on the tool. Negative numbers are Spiny.
*/
public static void addToolMaterial (int materialID, String materialName, int harvestLevel, int durability, int miningspeed, int attack, float handleModifier, int reinforced, float stonebound,
String style, String ability)
{
ToolMaterial mat = toolMaterials.get(materialID);
if (mat == null)
{
mat = new ToolMaterial(materialName, harvestLevel, durability, miningspeed, attack, handleModifier, reinforced, stonebound, style, ability);
toolMaterials.put(materialID, mat);
toolMaterialStrings.put(materialName, mat);
}
else
throw new IllegalArgumentException("[TCon API] Material ID " + materialID + " is already occupied by " + mat.materialName);
}
/** Adds a tool material to the registry
*
* @param materialID Unique ID, stored for each part
* @exception materialID must be unique
* @param materialName Unique name for data lookup purposes
* @param displayName Prefix for creative mode tools
* @param harvestLevel The materials which the tool can harvest. Pickaxe levels - 0: Wood, 1: Stone, 2: Redstone/Diamond, 3: Obsidian, 4: Cobalt/Ardite, 5: Manyullyn
* @param durability Base durability of the tool, affects tool heads.
* @param miningspeed Base mining speed, divided by 100 in use
* @param attack Base attack
* @param handleModifier Durability multiplier on the tool
* @param reinforced Reinforced level
* @param stonebound Amount of Stonebound to put on the tool. Negative numbers are Spiny.
*/
public static void addToolMaterial (int materialID, String materialName, String displayName, int harvestLevel, int durability, int miningspeed, int attack, float handleModifier, int reinforced,
float stonebound, String style, String ability)
{
ToolMaterial mat = toolMaterials.get(materialID);
if (mat == null)
{
mat = new ToolMaterial(materialName, displayName, harvestLevel, durability, miningspeed, attack, handleModifier, reinforced, stonebound, style, ability);
toolMaterials.put(materialID, mat);
toolMaterialStrings.put(materialName, mat);
}
else
throw new IllegalArgumentException("[TCon API] Material ID " + materialID + " is already occupied by " + mat.materialName);
}
/** Adds a tool material to the registry
*
* @param materialID Unique ID, stored for each part
* @exception materialID must be unique
* @param material Complete tool material to add. Uses the name in the material for lookup purposes.
*/
public static void addtoolMaterial (int materialID, ToolMaterial material)
{
ToolMaterial mat = toolMaterials.get(materialID);
if (mat == null)
{
toolMaterials.put(materialID, mat);
toolMaterialStrings.put(material.name(), mat);
}
else
throw new IllegalArgumentException("[TCon API] Material ID " + materialID + " is already occupied by " + mat.materialName);
}
/** Looks up a tool material by ID
*
* @param key The ID to look up
* @return Tool Material
*/
public static ToolMaterial getMaterial (int key)
{
return (toolMaterials.get(key));
}
/** Looks up a tool material by name
*
* @param key the name to look up
* @return Tool Material
*/
public static ToolMaterial getMaterial (String key)
{
return (toolMaterialStrings.get(key));
}
//Bow materials
public static HashMap<Integer, BowMaterial> bowMaterials = new HashMap<Integer, BowMaterial>(40);
public static void addBowMaterial (int materialID, int durability, int drawSpeed, float speedMax)
{
BowMaterial mat = bowMaterials.get(materialID);
if (mat == null)
{
mat = new BowMaterial(durability, drawSpeed, speedMax);
bowMaterials.put(materialID, mat);
}
else
throw new IllegalArgumentException("[TCon API] Bow Material ID " + materialID + " is already occupied");
}
public static boolean validBowMaterial (int materialID)
{
return bowMaterials.containsKey(materialID);
}
public static BowMaterial getBowMaterial (int materialID)
{
return bowMaterials.get(materialID);
}
public static HashMap<Integer, ArrowMaterial> arrowMaterials = new HashMap<Integer, ArrowMaterial>(40);
public static void addArrowMaterial (int materialID, float mass, float breakChance, float accuracy)
{
ArrowMaterial mat = arrowMaterials.get(materialID);
if (mat == null)
{
mat = new ArrowMaterial(mass, breakChance, accuracy);
arrowMaterials.put(materialID, mat);
}
else
throw new IllegalArgumentException("[TCon API] Arrow Material ID " + materialID + " is already occupied");
}
public static boolean validArrowMaterial (int materialID)
{
return arrowMaterials.containsKey(materialID);
}
public static ArrowMaterial getArrowMaterial (int materialID)
{
return arrowMaterials.get(materialID);
}
//Custom materials - bowstrings, fletching, etc
public static ArrayList<CustomMaterial> customMaterials = new ArrayList<CustomMaterial>();
public static void addCustomMaterial (CustomMaterial mat)
{
if (mat != null)
customMaterials.add(mat);
}
public static void addBowstringMaterial (int materialID, int value, ItemStack input, ItemStack craftingMaterial, float durability, float drawSpeed, float flightSpeed)
{
BowstringMaterial mat = new BowstringMaterial(materialID, value, input, craftingMaterial, durability, drawSpeed, flightSpeed);
customMaterials.add(mat);
}
public static void addFletchingMaterial (int materialID, int value, ItemStack input, ItemStack craftingMaterial, float accuracy, float breakChance, float mass)
{
FletchingMaterial mat = new FletchingMaterial(materialID, value, input, craftingMaterial, accuracy, breakChance, mass);
customMaterials.add(mat);
}
public static CustomMaterial getCustomMaterial (int materialID, Class<? extends CustomMaterial> clazz)
{
for (CustomMaterial mat : customMaterials)
{
if (mat.getClass().equals(clazz) && mat.materialID == materialID)
return mat;
}
return null;
}
public static CustomMaterial getCustomMaterial (ItemStack input, Class<? extends CustomMaterial> clazz)
{
for (CustomMaterial mat : customMaterials)
{
if (mat.getClass().equals(clazz) && input.isItemEqual(mat.input))
return mat;
}
return null;
}
/*public static CustomMaterial getCustomMaterial(ItemStack input, ItemStack pattern)
{
for (CustomMaterial mat : customMaterials)
{
if (mat.matches(input, pattern))
return mat;
}
return null;
}*/
/*public static ItemStack craftBowString(ItemStack stack)
{
if (stack.stackSize < 3)
return null;
for (BowstringMaterial mat : bowstringMaterials)
{
if (stack.isItemEqual(mat.input))
return mat.craftingItem.copy();
}
return null;
}
public static BowstringMaterial getBowstringMaterial(ItemStack stack)
{
if (stack.stackSize < 3)
return null;
for (BowstringMaterial mat : bowstringMaterials)
{
if (stack.isItemEqual(mat.input))
return mat;
}
return null;
}*/
public static LiquidCasting getTableCasting ()
{
return instance.tableCasting();
}
LiquidCasting tableCasting ()
{
try
{
Class clazz = Class.forName("tconstruct.TConstruct");
Method method = clazz.getMethod("getTableCasting");
LiquidCasting lc = (LiquidCasting) method.invoke(this);
return lc;
}
catch (Exception e)
{
System.out.println("[TCon API] Could not find casting table recipes.");
return null;
}
}
public static LiquidCasting getBasinCasting ()
{
return instance.basinCasting();
}
LiquidCasting basinCasting ()
{
try
{
Class clazz = Class.forName("tconstruct.TConstruct");
Method method = clazz.getMethod("getBasinCasting");
LiquidCasting lc = (LiquidCasting) method.invoke(this);
return lc;
}
catch (Exception e)
{
System.out.println("[TCon API] Could not find casting basin recipes.");
return null;
}
}
public static Detailing getChiselDetailing ()
{
return instance.chiselDetailing();
}
Detailing chiselDetailing ()
{
try
{
Class clazz = Class.forName("tconstruct.TConstruct");
Method method = clazz.getMethod("getChiselDetailing");
Detailing lc = (Detailing) method.invoke(this);
return lc;
}
catch (Exception e)
{
System.out.println("[TCon API] Could not find chisel detailing recipes.");
return null;
}
}
public static ArrayList<ActiveToolMod> activeModifiers = new ArrayList<ActiveToolMod>();
public static void registerActiveToolMod (ActiveToolMod mod)
{
activeModifiers.add(mod);
}
/* Used to determine how blocks are laid out in the drawbridge
* 0: Metadata has to match
* 1: Metadata has no meaning
* 2: Should not be placed
* 3: Has rotational metadata
* 4: Rails
* 5: Has rotational TileEntity data
* 6: Custom placement logic
*/
public static int[] drawbridgeState = new int[Block.blocksList.length];
/** Blocks that are interchangable with each other. Ex: Still and flowing water */
public static int[] interchangableBlockMapping = new int[Block.blocksList.length];
/** Blocks that place items, and vice versa */
public static int[] blockToItemMapping = new int[Item.itemsList.length];
static void initializeDrawbridgeState ()
{
drawbridgeState[Block.stone.blockID] = 1;
drawbridgeState[Block.grass.blockID] = 1;
drawbridgeState[Block.dirt.blockID] = 1;
drawbridgeState[Block.cobblestone.blockID] = 1;
drawbridgeState[Block.bedrock.blockID] = 2;
drawbridgeState[Block.waterMoving.blockID] = 1;
drawbridgeState[Block.waterStill.blockID] = 1;
interchangableBlockMapping[Block.waterStill.blockID] = Block.waterMoving.blockID;
interchangableBlockMapping[Block.waterMoving.blockID] = Block.waterStill.blockID;
drawbridgeState[Block.lavaMoving.blockID] = 1;
drawbridgeState[Block.lavaStill.blockID] = 1;
interchangableBlockMapping[Block.lavaStill.blockID] = Block.lavaMoving.blockID;
interchangableBlockMapping[Block.lavaMoving.blockID] = Block.lavaStill.blockID;
drawbridgeState[Block.sand.blockID] = 1;
drawbridgeState[Block.gravel.blockID] = 1;
drawbridgeState[Block.oreGold.blockID] = 1;
drawbridgeState[Block.oreIron.blockID] = 1;
drawbridgeState[Block.oreCoal.blockID] = 1;
drawbridgeState[Block.sponge.blockID] = 1;
drawbridgeState[Block.oreLapis.blockID] = 1;
drawbridgeState[Block.blockLapis.blockID] = 1;
drawbridgeState[Block.dispenser.blockID] = 3;
drawbridgeState[Block.music.blockID] = 1;
drawbridgeState[Block.bed.blockID] = 2;
drawbridgeState[Block.railPowered.blockID] = 4;
drawbridgeState[Block.railDetector.blockID] = 4;
drawbridgeState[Block.pistonStickyBase.blockID] = 3;
drawbridgeState[Block.web.blockID] = 1;
drawbridgeState[Block.pistonBase.blockID] = 3;
drawbridgeState[Block.pistonExtension.blockID] = 2;
drawbridgeState[Block.plantYellow.blockID] = 1;
drawbridgeState[Block.plantRed.blockID] = 1;
drawbridgeState[Block.mushroomBrown.blockID] = 1;
drawbridgeState[Block.mushroomRed.blockID] = 1;
drawbridgeState[Block.blockGold.blockID] = 1;
drawbridgeState[Block.blockIron.blockID] = 1;
drawbridgeState[Block.brick.blockID] = 1;
drawbridgeState[Block.tnt.blockID] = 1;
drawbridgeState[Block.bookShelf.blockID] = 1;
drawbridgeState[Block.cobblestoneMossy.blockID] = 1;
drawbridgeState[Block.obsidian.blockID] = 1;
drawbridgeState[Block.torchWood.blockID] = 1;
drawbridgeState[Block.fire.blockID] = 1;
drawbridgeState[Block.mobSpawner.blockID] = 2;
drawbridgeState[Block.stairsWoodOak.blockID] = 3;
drawbridgeState[Block.chest.blockID] = 5;
drawbridgeState[Block.redstoneWire.blockID] = 1;
blockToItemMapping[Block.redstoneWire.blockID] = Item.redstone.itemID;
blockToItemMapping[Item.redstone.itemID] = Block.redstoneWire.blockID;
drawbridgeState[Block.oreDiamond.blockID] = 1;
drawbridgeState[Block.blockDiamond.blockID] = 1;
drawbridgeState[Block.workbench.blockID] = 1;
drawbridgeState[Block.crops.blockID] = 2;
drawbridgeState[Block.tilledField.blockID] = 1;
drawbridgeState[Block.furnaceIdle.blockID] = 3;
drawbridgeState[Block.furnaceBurning.blockID] = 3;
interchangableBlockMapping[Block.furnaceIdle.blockID] = Block.furnaceBurning.blockID;
interchangableBlockMapping[Block.furnaceBurning.blockID] = Block.furnaceIdle.blockID;
drawbridgeState[Block.tilledField.blockID] = 1;
drawbridgeState[Block.signPost.blockID] = 3;
drawbridgeState[Block.doorWood.blockID] = 2;
drawbridgeState[Block.ladder.blockID] = 1;
drawbridgeState[Block.rail.blockID] = 4;
drawbridgeState[Block.stairsCobblestone.blockID] = 3;
drawbridgeState[Block.signWall.blockID] = 3;
drawbridgeState[Block.lever.blockID] = 3;
drawbridgeState[Block.pressurePlateStone.blockID] = 1;
drawbridgeState[Block.doorIron.blockID] = 2;
drawbridgeState[Block.pressurePlatePlanks.blockID] = 1;
drawbridgeState[Block.oreRedstone.blockID] = 1;
drawbridgeState[Block.oreRedstoneGlowing.blockID] = 1;
drawbridgeState[Block.torchRedstoneIdle.blockID] = 1;
drawbridgeState[Block.torchRedstoneActive.blockID] = 1;
drawbridgeState[Block.stoneButton.blockID] = 3;
drawbridgeState[Block.snow.blockID] = 1;
drawbridgeState[Block.ice.blockID] = 1;
drawbridgeState[Block.blockSnow.blockID] = 1;
drawbridgeState[Block.cactus.blockID] = 2;
drawbridgeState[Block.blockClay.blockID] = 1;
drawbridgeState[Block.reed.blockID] = 1;
drawbridgeState[Block.jukebox.blockID] = 1;
drawbridgeState[Block.fence.blockID] = 1;
drawbridgeState[Block.pumpkin.blockID] = 1;
drawbridgeState[Block.netherrack.blockID] = 1;
drawbridgeState[Block.slowSand.blockID] = 1;
drawbridgeState[Block.glowStone.blockID] = 1;
drawbridgeState[Block.portal.blockID] = 2;
drawbridgeState[Block.pumpkinLantern.blockID] = 1;
drawbridgeState[Block.cake.blockID] = 2;
drawbridgeState[Block.redstoneRepeaterIdle.blockID] = 3;
drawbridgeState[Block.redstoneRepeaterActive.blockID] = 3;
interchangableBlockMapping[Block.redstoneRepeaterIdle.blockID] = Block.redstoneRepeaterActive.blockID;
interchangableBlockMapping[Block.redstoneRepeaterActive.blockID] = Block.redstoneRepeaterIdle.blockID;
blockToItemMapping[Block.redstoneRepeaterIdle.blockID] = Item.redstoneRepeater.itemID;
blockToItemMapping[Block.redstoneRepeaterActive.blockID] = Item.redstoneRepeater.itemID;
blockToItemMapping[Item.redstoneRepeater.itemID] = Block.redstoneRepeaterIdle.blockID;
drawbridgeState[Block.lockedChest.blockID] = 5;
drawbridgeState[Block.trapdoor.blockID] = 3;
drawbridgeState[Block.mushroomCapBrown.blockID] = 1;
drawbridgeState[Block.mushroomCapRed.blockID] = 1;
drawbridgeState[Block.fenceIron.blockID] = 1;
drawbridgeState[Block.thinGlass.blockID] = 1;
drawbridgeState[Block.melon.blockID] = 1;
drawbridgeState[Block.pumpkinStem.blockID] = 2;
drawbridgeState[Block.melonStem.blockID] = 2;
drawbridgeState[Block.vine.blockID] = 3;
drawbridgeState[Block.fenceGate.blockID] = 3;
drawbridgeState[Block.stairsBrick.blockID] = 3;
drawbridgeState[Block.stairsStoneBrick.blockID] = 3;
drawbridgeState[Block.mycelium.blockID] = 1;
drawbridgeState[Block.waterlily.blockID] = 1;
drawbridgeState[Block.netherBrick.blockID] = 1;
drawbridgeState[Block.netherFence.blockID] = 1;
drawbridgeState[Block.netherFence.blockID] = 3;
drawbridgeState[Block.netherStalk.blockID] = 2;
drawbridgeState[Block.enchantmentTable.blockID] = 1;
drawbridgeState[Block.brewingStand.blockID] = 1;
drawbridgeState[Block.cauldron.blockID] = 1;
drawbridgeState[Block.endPortal.blockID] = 2;
drawbridgeState[Block.dragonEgg.blockID] = 1;
drawbridgeState[Block.redstoneLampIdle.blockID] = 1;
drawbridgeState[Block.redstoneLampActive.blockID] = 1;
drawbridgeState[Block.cocoaPlant.blockID] = 2;
drawbridgeState[Block.stairsSandStone.blockID] = 3;
drawbridgeState[Block.oreEmerald.blockID] = 1;
drawbridgeState[Block.enderChest.blockID] = 5;
drawbridgeState[Block.tripWireSource.blockID] = 1;
drawbridgeState[Block.tripWire.blockID] = 1;
drawbridgeState[Block.blockEmerald.blockID] = 1;
drawbridgeState[Block.stairsWoodSpruce.blockID] = 3;
drawbridgeState[Block.stairsWoodBirch.blockID] = 3;
drawbridgeState[Block.stairsWoodJungle.blockID] = 3;
drawbridgeState[Block.commandBlock.blockID] = 1;
drawbridgeState[Block.beacon.blockID] = 1;
drawbridgeState[Block.cobblestoneWall.blockID] = 1;
drawbridgeState[Block.flowerPot.blockID] = 1;
drawbridgeState[Block.carrot.blockID] = 2;
drawbridgeState[Block.potato.blockID] = 1;
drawbridgeState[Block.woodenButton.blockID] = 3;
drawbridgeState[Block.skull.blockID] = 2;
drawbridgeState[Block.chestTrapped.blockID] = 5;
drawbridgeState[Block.pressurePlateGold.blockID] = 1;
drawbridgeState[Block.pressurePlateIron.blockID] = 1;
drawbridgeState[Block.redstoneComparatorIdle.blockID] = 1;
drawbridgeState[Block.redstoneComparatorActive.blockID] = 1;
interchangableBlockMapping[Block.redstoneComparatorIdle.blockID] = Block.redstoneComparatorActive.blockID;
interchangableBlockMapping[Block.redstoneComparatorActive.blockID] = Block.redstoneComparatorIdle.blockID;
blockToItemMapping[Block.redstoneComparatorIdle.blockID] = Item.comparator.itemID;
blockToItemMapping[Block.redstoneComparatorActive.blockID] = Item.comparator.itemID;
blockToItemMapping[Item.comparator.itemID] = Block.redstoneComparatorIdle.blockID;
drawbridgeState[Block.daylightSensor.blockID] = 1;
drawbridgeState[Block.blockRedstone.blockID] = 1;
drawbridgeState[Block.oreNetherQuartz.blockID] = 1;
drawbridgeState[Block.hopperBlock.blockID] = 3;
drawbridgeState[Block.blockNetherQuartz.blockID] = 1;
drawbridgeState[Block.stairsNetherQuartz.blockID] = 3;
drawbridgeState[Block.railActivator.blockID] = 4;
drawbridgeState[Block.dropper.blockID] = 3;
+ interchangableBlockMapping[Block.dirt.blockID] = Block.grass.blockID;
+ interchangableBlockMapping[Block.grass.blockID] = Block.dirt.blockID;
}
static
{
initializeDrawbridgeState();
}
/** Default Material Index
* 0: Wood
* 1: Stone
* 2: Iron
* 3: Flint
* 4: Cactus
* 5: Bone
* 6: Obsidian
* 7: Netherrack
* 8: Green Slime
* 9: Paper
* 10: Cobalt
* 11: Ardite
* 12: Manyullyn
* 13: Copper
* 14: Bronze
* 15: Alumite
* 16: Steel
* 17: Blue Slime
*/
}
| true | true | static void initializeDrawbridgeState ()
{
drawbridgeState[Block.stone.blockID] = 1;
drawbridgeState[Block.grass.blockID] = 1;
drawbridgeState[Block.dirt.blockID] = 1;
drawbridgeState[Block.cobblestone.blockID] = 1;
drawbridgeState[Block.bedrock.blockID] = 2;
drawbridgeState[Block.waterMoving.blockID] = 1;
drawbridgeState[Block.waterStill.blockID] = 1;
interchangableBlockMapping[Block.waterStill.blockID] = Block.waterMoving.blockID;
interchangableBlockMapping[Block.waterMoving.blockID] = Block.waterStill.blockID;
drawbridgeState[Block.lavaMoving.blockID] = 1;
drawbridgeState[Block.lavaStill.blockID] = 1;
interchangableBlockMapping[Block.lavaStill.blockID] = Block.lavaMoving.blockID;
interchangableBlockMapping[Block.lavaMoving.blockID] = Block.lavaStill.blockID;
drawbridgeState[Block.sand.blockID] = 1;
drawbridgeState[Block.gravel.blockID] = 1;
drawbridgeState[Block.oreGold.blockID] = 1;
drawbridgeState[Block.oreIron.blockID] = 1;
drawbridgeState[Block.oreCoal.blockID] = 1;
drawbridgeState[Block.sponge.blockID] = 1;
drawbridgeState[Block.oreLapis.blockID] = 1;
drawbridgeState[Block.blockLapis.blockID] = 1;
drawbridgeState[Block.dispenser.blockID] = 3;
drawbridgeState[Block.music.blockID] = 1;
drawbridgeState[Block.bed.blockID] = 2;
drawbridgeState[Block.railPowered.blockID] = 4;
drawbridgeState[Block.railDetector.blockID] = 4;
drawbridgeState[Block.pistonStickyBase.blockID] = 3;
drawbridgeState[Block.web.blockID] = 1;
drawbridgeState[Block.pistonBase.blockID] = 3;
drawbridgeState[Block.pistonExtension.blockID] = 2;
drawbridgeState[Block.plantYellow.blockID] = 1;
drawbridgeState[Block.plantRed.blockID] = 1;
drawbridgeState[Block.mushroomBrown.blockID] = 1;
drawbridgeState[Block.mushroomRed.blockID] = 1;
drawbridgeState[Block.blockGold.blockID] = 1;
drawbridgeState[Block.blockIron.blockID] = 1;
drawbridgeState[Block.brick.blockID] = 1;
drawbridgeState[Block.tnt.blockID] = 1;
drawbridgeState[Block.bookShelf.blockID] = 1;
drawbridgeState[Block.cobblestoneMossy.blockID] = 1;
drawbridgeState[Block.obsidian.blockID] = 1;
drawbridgeState[Block.torchWood.blockID] = 1;
drawbridgeState[Block.fire.blockID] = 1;
drawbridgeState[Block.mobSpawner.blockID] = 2;
drawbridgeState[Block.stairsWoodOak.blockID] = 3;
drawbridgeState[Block.chest.blockID] = 5;
drawbridgeState[Block.redstoneWire.blockID] = 1;
blockToItemMapping[Block.redstoneWire.blockID] = Item.redstone.itemID;
blockToItemMapping[Item.redstone.itemID] = Block.redstoneWire.blockID;
drawbridgeState[Block.oreDiamond.blockID] = 1;
drawbridgeState[Block.blockDiamond.blockID] = 1;
drawbridgeState[Block.workbench.blockID] = 1;
drawbridgeState[Block.crops.blockID] = 2;
drawbridgeState[Block.tilledField.blockID] = 1;
drawbridgeState[Block.furnaceIdle.blockID] = 3;
drawbridgeState[Block.furnaceBurning.blockID] = 3;
interchangableBlockMapping[Block.furnaceIdle.blockID] = Block.furnaceBurning.blockID;
interchangableBlockMapping[Block.furnaceBurning.blockID] = Block.furnaceIdle.blockID;
drawbridgeState[Block.tilledField.blockID] = 1;
drawbridgeState[Block.signPost.blockID] = 3;
drawbridgeState[Block.doorWood.blockID] = 2;
drawbridgeState[Block.ladder.blockID] = 1;
drawbridgeState[Block.rail.blockID] = 4;
drawbridgeState[Block.stairsCobblestone.blockID] = 3;
drawbridgeState[Block.signWall.blockID] = 3;
drawbridgeState[Block.lever.blockID] = 3;
drawbridgeState[Block.pressurePlateStone.blockID] = 1;
drawbridgeState[Block.doorIron.blockID] = 2;
drawbridgeState[Block.pressurePlatePlanks.blockID] = 1;
drawbridgeState[Block.oreRedstone.blockID] = 1;
drawbridgeState[Block.oreRedstoneGlowing.blockID] = 1;
drawbridgeState[Block.torchRedstoneIdle.blockID] = 1;
drawbridgeState[Block.torchRedstoneActive.blockID] = 1;
drawbridgeState[Block.stoneButton.blockID] = 3;
drawbridgeState[Block.snow.blockID] = 1;
drawbridgeState[Block.ice.blockID] = 1;
drawbridgeState[Block.blockSnow.blockID] = 1;
drawbridgeState[Block.cactus.blockID] = 2;
drawbridgeState[Block.blockClay.blockID] = 1;
drawbridgeState[Block.reed.blockID] = 1;
drawbridgeState[Block.jukebox.blockID] = 1;
drawbridgeState[Block.fence.blockID] = 1;
drawbridgeState[Block.pumpkin.blockID] = 1;
drawbridgeState[Block.netherrack.blockID] = 1;
drawbridgeState[Block.slowSand.blockID] = 1;
drawbridgeState[Block.glowStone.blockID] = 1;
drawbridgeState[Block.portal.blockID] = 2;
drawbridgeState[Block.pumpkinLantern.blockID] = 1;
drawbridgeState[Block.cake.blockID] = 2;
drawbridgeState[Block.redstoneRepeaterIdle.blockID] = 3;
drawbridgeState[Block.redstoneRepeaterActive.blockID] = 3;
interchangableBlockMapping[Block.redstoneRepeaterIdle.blockID] = Block.redstoneRepeaterActive.blockID;
interchangableBlockMapping[Block.redstoneRepeaterActive.blockID] = Block.redstoneRepeaterIdle.blockID;
blockToItemMapping[Block.redstoneRepeaterIdle.blockID] = Item.redstoneRepeater.itemID;
blockToItemMapping[Block.redstoneRepeaterActive.blockID] = Item.redstoneRepeater.itemID;
blockToItemMapping[Item.redstoneRepeater.itemID] = Block.redstoneRepeaterIdle.blockID;
drawbridgeState[Block.lockedChest.blockID] = 5;
drawbridgeState[Block.trapdoor.blockID] = 3;
drawbridgeState[Block.mushroomCapBrown.blockID] = 1;
drawbridgeState[Block.mushroomCapRed.blockID] = 1;
drawbridgeState[Block.fenceIron.blockID] = 1;
drawbridgeState[Block.thinGlass.blockID] = 1;
drawbridgeState[Block.melon.blockID] = 1;
drawbridgeState[Block.pumpkinStem.blockID] = 2;
drawbridgeState[Block.melonStem.blockID] = 2;
drawbridgeState[Block.vine.blockID] = 3;
drawbridgeState[Block.fenceGate.blockID] = 3;
drawbridgeState[Block.stairsBrick.blockID] = 3;
drawbridgeState[Block.stairsStoneBrick.blockID] = 3;
drawbridgeState[Block.mycelium.blockID] = 1;
drawbridgeState[Block.waterlily.blockID] = 1;
drawbridgeState[Block.netherBrick.blockID] = 1;
drawbridgeState[Block.netherFence.blockID] = 1;
drawbridgeState[Block.netherFence.blockID] = 3;
drawbridgeState[Block.netherStalk.blockID] = 2;
drawbridgeState[Block.enchantmentTable.blockID] = 1;
drawbridgeState[Block.brewingStand.blockID] = 1;
drawbridgeState[Block.cauldron.blockID] = 1;
drawbridgeState[Block.endPortal.blockID] = 2;
drawbridgeState[Block.dragonEgg.blockID] = 1;
drawbridgeState[Block.redstoneLampIdle.blockID] = 1;
drawbridgeState[Block.redstoneLampActive.blockID] = 1;
drawbridgeState[Block.cocoaPlant.blockID] = 2;
drawbridgeState[Block.stairsSandStone.blockID] = 3;
drawbridgeState[Block.oreEmerald.blockID] = 1;
drawbridgeState[Block.enderChest.blockID] = 5;
drawbridgeState[Block.tripWireSource.blockID] = 1;
drawbridgeState[Block.tripWire.blockID] = 1;
drawbridgeState[Block.blockEmerald.blockID] = 1;
drawbridgeState[Block.stairsWoodSpruce.blockID] = 3;
drawbridgeState[Block.stairsWoodBirch.blockID] = 3;
drawbridgeState[Block.stairsWoodJungle.blockID] = 3;
drawbridgeState[Block.commandBlock.blockID] = 1;
drawbridgeState[Block.beacon.blockID] = 1;
drawbridgeState[Block.cobblestoneWall.blockID] = 1;
drawbridgeState[Block.flowerPot.blockID] = 1;
drawbridgeState[Block.carrot.blockID] = 2;
drawbridgeState[Block.potato.blockID] = 1;
drawbridgeState[Block.woodenButton.blockID] = 3;
drawbridgeState[Block.skull.blockID] = 2;
drawbridgeState[Block.chestTrapped.blockID] = 5;
drawbridgeState[Block.pressurePlateGold.blockID] = 1;
drawbridgeState[Block.pressurePlateIron.blockID] = 1;
drawbridgeState[Block.redstoneComparatorIdle.blockID] = 1;
drawbridgeState[Block.redstoneComparatorActive.blockID] = 1;
interchangableBlockMapping[Block.redstoneComparatorIdle.blockID] = Block.redstoneComparatorActive.blockID;
interchangableBlockMapping[Block.redstoneComparatorActive.blockID] = Block.redstoneComparatorIdle.blockID;
blockToItemMapping[Block.redstoneComparatorIdle.blockID] = Item.comparator.itemID;
blockToItemMapping[Block.redstoneComparatorActive.blockID] = Item.comparator.itemID;
blockToItemMapping[Item.comparator.itemID] = Block.redstoneComparatorIdle.blockID;
drawbridgeState[Block.daylightSensor.blockID] = 1;
drawbridgeState[Block.blockRedstone.blockID] = 1;
drawbridgeState[Block.oreNetherQuartz.blockID] = 1;
drawbridgeState[Block.hopperBlock.blockID] = 3;
drawbridgeState[Block.blockNetherQuartz.blockID] = 1;
drawbridgeState[Block.stairsNetherQuartz.blockID] = 3;
drawbridgeState[Block.railActivator.blockID] = 4;
drawbridgeState[Block.dropper.blockID] = 3;
}
| static void initializeDrawbridgeState ()
{
drawbridgeState[Block.stone.blockID] = 1;
drawbridgeState[Block.grass.blockID] = 1;
drawbridgeState[Block.dirt.blockID] = 1;
drawbridgeState[Block.cobblestone.blockID] = 1;
drawbridgeState[Block.bedrock.blockID] = 2;
drawbridgeState[Block.waterMoving.blockID] = 1;
drawbridgeState[Block.waterStill.blockID] = 1;
interchangableBlockMapping[Block.waterStill.blockID] = Block.waterMoving.blockID;
interchangableBlockMapping[Block.waterMoving.blockID] = Block.waterStill.blockID;
drawbridgeState[Block.lavaMoving.blockID] = 1;
drawbridgeState[Block.lavaStill.blockID] = 1;
interchangableBlockMapping[Block.lavaStill.blockID] = Block.lavaMoving.blockID;
interchangableBlockMapping[Block.lavaMoving.blockID] = Block.lavaStill.blockID;
drawbridgeState[Block.sand.blockID] = 1;
drawbridgeState[Block.gravel.blockID] = 1;
drawbridgeState[Block.oreGold.blockID] = 1;
drawbridgeState[Block.oreIron.blockID] = 1;
drawbridgeState[Block.oreCoal.blockID] = 1;
drawbridgeState[Block.sponge.blockID] = 1;
drawbridgeState[Block.oreLapis.blockID] = 1;
drawbridgeState[Block.blockLapis.blockID] = 1;
drawbridgeState[Block.dispenser.blockID] = 3;
drawbridgeState[Block.music.blockID] = 1;
drawbridgeState[Block.bed.blockID] = 2;
drawbridgeState[Block.railPowered.blockID] = 4;
drawbridgeState[Block.railDetector.blockID] = 4;
drawbridgeState[Block.pistonStickyBase.blockID] = 3;
drawbridgeState[Block.web.blockID] = 1;
drawbridgeState[Block.pistonBase.blockID] = 3;
drawbridgeState[Block.pistonExtension.blockID] = 2;
drawbridgeState[Block.plantYellow.blockID] = 1;
drawbridgeState[Block.plantRed.blockID] = 1;
drawbridgeState[Block.mushroomBrown.blockID] = 1;
drawbridgeState[Block.mushroomRed.blockID] = 1;
drawbridgeState[Block.blockGold.blockID] = 1;
drawbridgeState[Block.blockIron.blockID] = 1;
drawbridgeState[Block.brick.blockID] = 1;
drawbridgeState[Block.tnt.blockID] = 1;
drawbridgeState[Block.bookShelf.blockID] = 1;
drawbridgeState[Block.cobblestoneMossy.blockID] = 1;
drawbridgeState[Block.obsidian.blockID] = 1;
drawbridgeState[Block.torchWood.blockID] = 1;
drawbridgeState[Block.fire.blockID] = 1;
drawbridgeState[Block.mobSpawner.blockID] = 2;
drawbridgeState[Block.stairsWoodOak.blockID] = 3;
drawbridgeState[Block.chest.blockID] = 5;
drawbridgeState[Block.redstoneWire.blockID] = 1;
blockToItemMapping[Block.redstoneWire.blockID] = Item.redstone.itemID;
blockToItemMapping[Item.redstone.itemID] = Block.redstoneWire.blockID;
drawbridgeState[Block.oreDiamond.blockID] = 1;
drawbridgeState[Block.blockDiamond.blockID] = 1;
drawbridgeState[Block.workbench.blockID] = 1;
drawbridgeState[Block.crops.blockID] = 2;
drawbridgeState[Block.tilledField.blockID] = 1;
drawbridgeState[Block.furnaceIdle.blockID] = 3;
drawbridgeState[Block.furnaceBurning.blockID] = 3;
interchangableBlockMapping[Block.furnaceIdle.blockID] = Block.furnaceBurning.blockID;
interchangableBlockMapping[Block.furnaceBurning.blockID] = Block.furnaceIdle.blockID;
drawbridgeState[Block.tilledField.blockID] = 1;
drawbridgeState[Block.signPost.blockID] = 3;
drawbridgeState[Block.doorWood.blockID] = 2;
drawbridgeState[Block.ladder.blockID] = 1;
drawbridgeState[Block.rail.blockID] = 4;
drawbridgeState[Block.stairsCobblestone.blockID] = 3;
drawbridgeState[Block.signWall.blockID] = 3;
drawbridgeState[Block.lever.blockID] = 3;
drawbridgeState[Block.pressurePlateStone.blockID] = 1;
drawbridgeState[Block.doorIron.blockID] = 2;
drawbridgeState[Block.pressurePlatePlanks.blockID] = 1;
drawbridgeState[Block.oreRedstone.blockID] = 1;
drawbridgeState[Block.oreRedstoneGlowing.blockID] = 1;
drawbridgeState[Block.torchRedstoneIdle.blockID] = 1;
drawbridgeState[Block.torchRedstoneActive.blockID] = 1;
drawbridgeState[Block.stoneButton.blockID] = 3;
drawbridgeState[Block.snow.blockID] = 1;
drawbridgeState[Block.ice.blockID] = 1;
drawbridgeState[Block.blockSnow.blockID] = 1;
drawbridgeState[Block.cactus.blockID] = 2;
drawbridgeState[Block.blockClay.blockID] = 1;
drawbridgeState[Block.reed.blockID] = 1;
drawbridgeState[Block.jukebox.blockID] = 1;
drawbridgeState[Block.fence.blockID] = 1;
drawbridgeState[Block.pumpkin.blockID] = 1;
drawbridgeState[Block.netherrack.blockID] = 1;
drawbridgeState[Block.slowSand.blockID] = 1;
drawbridgeState[Block.glowStone.blockID] = 1;
drawbridgeState[Block.portal.blockID] = 2;
drawbridgeState[Block.pumpkinLantern.blockID] = 1;
drawbridgeState[Block.cake.blockID] = 2;
drawbridgeState[Block.redstoneRepeaterIdle.blockID] = 3;
drawbridgeState[Block.redstoneRepeaterActive.blockID] = 3;
interchangableBlockMapping[Block.redstoneRepeaterIdle.blockID] = Block.redstoneRepeaterActive.blockID;
interchangableBlockMapping[Block.redstoneRepeaterActive.blockID] = Block.redstoneRepeaterIdle.blockID;
blockToItemMapping[Block.redstoneRepeaterIdle.blockID] = Item.redstoneRepeater.itemID;
blockToItemMapping[Block.redstoneRepeaterActive.blockID] = Item.redstoneRepeater.itemID;
blockToItemMapping[Item.redstoneRepeater.itemID] = Block.redstoneRepeaterIdle.blockID;
drawbridgeState[Block.lockedChest.blockID] = 5;
drawbridgeState[Block.trapdoor.blockID] = 3;
drawbridgeState[Block.mushroomCapBrown.blockID] = 1;
drawbridgeState[Block.mushroomCapRed.blockID] = 1;
drawbridgeState[Block.fenceIron.blockID] = 1;
drawbridgeState[Block.thinGlass.blockID] = 1;
drawbridgeState[Block.melon.blockID] = 1;
drawbridgeState[Block.pumpkinStem.blockID] = 2;
drawbridgeState[Block.melonStem.blockID] = 2;
drawbridgeState[Block.vine.blockID] = 3;
drawbridgeState[Block.fenceGate.blockID] = 3;
drawbridgeState[Block.stairsBrick.blockID] = 3;
drawbridgeState[Block.stairsStoneBrick.blockID] = 3;
drawbridgeState[Block.mycelium.blockID] = 1;
drawbridgeState[Block.waterlily.blockID] = 1;
drawbridgeState[Block.netherBrick.blockID] = 1;
drawbridgeState[Block.netherFence.blockID] = 1;
drawbridgeState[Block.netherFence.blockID] = 3;
drawbridgeState[Block.netherStalk.blockID] = 2;
drawbridgeState[Block.enchantmentTable.blockID] = 1;
drawbridgeState[Block.brewingStand.blockID] = 1;
drawbridgeState[Block.cauldron.blockID] = 1;
drawbridgeState[Block.endPortal.blockID] = 2;
drawbridgeState[Block.dragonEgg.blockID] = 1;
drawbridgeState[Block.redstoneLampIdle.blockID] = 1;
drawbridgeState[Block.redstoneLampActive.blockID] = 1;
drawbridgeState[Block.cocoaPlant.blockID] = 2;
drawbridgeState[Block.stairsSandStone.blockID] = 3;
drawbridgeState[Block.oreEmerald.blockID] = 1;
drawbridgeState[Block.enderChest.blockID] = 5;
drawbridgeState[Block.tripWireSource.blockID] = 1;
drawbridgeState[Block.tripWire.blockID] = 1;
drawbridgeState[Block.blockEmerald.blockID] = 1;
drawbridgeState[Block.stairsWoodSpruce.blockID] = 3;
drawbridgeState[Block.stairsWoodBirch.blockID] = 3;
drawbridgeState[Block.stairsWoodJungle.blockID] = 3;
drawbridgeState[Block.commandBlock.blockID] = 1;
drawbridgeState[Block.beacon.blockID] = 1;
drawbridgeState[Block.cobblestoneWall.blockID] = 1;
drawbridgeState[Block.flowerPot.blockID] = 1;
drawbridgeState[Block.carrot.blockID] = 2;
drawbridgeState[Block.potato.blockID] = 1;
drawbridgeState[Block.woodenButton.blockID] = 3;
drawbridgeState[Block.skull.blockID] = 2;
drawbridgeState[Block.chestTrapped.blockID] = 5;
drawbridgeState[Block.pressurePlateGold.blockID] = 1;
drawbridgeState[Block.pressurePlateIron.blockID] = 1;
drawbridgeState[Block.redstoneComparatorIdle.blockID] = 1;
drawbridgeState[Block.redstoneComparatorActive.blockID] = 1;
interchangableBlockMapping[Block.redstoneComparatorIdle.blockID] = Block.redstoneComparatorActive.blockID;
interchangableBlockMapping[Block.redstoneComparatorActive.blockID] = Block.redstoneComparatorIdle.blockID;
blockToItemMapping[Block.redstoneComparatorIdle.blockID] = Item.comparator.itemID;
blockToItemMapping[Block.redstoneComparatorActive.blockID] = Item.comparator.itemID;
blockToItemMapping[Item.comparator.itemID] = Block.redstoneComparatorIdle.blockID;
drawbridgeState[Block.daylightSensor.blockID] = 1;
drawbridgeState[Block.blockRedstone.blockID] = 1;
drawbridgeState[Block.oreNetherQuartz.blockID] = 1;
drawbridgeState[Block.hopperBlock.blockID] = 3;
drawbridgeState[Block.blockNetherQuartz.blockID] = 1;
drawbridgeState[Block.stairsNetherQuartz.blockID] = 3;
drawbridgeState[Block.railActivator.blockID] = 4;
drawbridgeState[Block.dropper.blockID] = 3;
interchangableBlockMapping[Block.dirt.blockID] = Block.grass.blockID;
interchangableBlockMapping[Block.grass.blockID] = Block.dirt.blockID;
}
|
diff --git a/infrastructure/tools/java/repository-manager/src/edu/uci/ics/sourcerer/repo/extracted/ExtractedRepository.java b/infrastructure/tools/java/repository-manager/src/edu/uci/ics/sourcerer/repo/extracted/ExtractedRepository.java
index 14b1f960..e61a2bea 100755
--- a/infrastructure/tools/java/repository-manager/src/edu/uci/ics/sourcerer/repo/extracted/ExtractedRepository.java
+++ b/infrastructure/tools/java/repository-manager/src/edu/uci/ics/sourcerer/repo/extracted/ExtractedRepository.java
@@ -1,563 +1,563 @@
/*
* Sourcerer: an infrastructure for large-scale source code analysis.
* Copyright (C) by contributors. See CONTRIBUTORS.txt for full list.
*
* 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 edu.uci.ics.sourcerer.repo.extracted;
import static edu.uci.ics.sourcerer.util.io.Logging.logger;
import java.io.File;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.logging.Level;
import edu.uci.ics.sourcerer.repo.general.AbstractExtractedProperties;
import edu.uci.ics.sourcerer.repo.general.AbstractRepository;
import edu.uci.ics.sourcerer.repo.general.IndexedJar;
import edu.uci.ics.sourcerer.repo.general.JarIndex;
import edu.uci.ics.sourcerer.repo.general.RepoFile;
import edu.uci.ics.sourcerer.repo.general.JarIndex.MavenFilter;
import edu.uci.ics.sourcerer.repo.general.JarIndex.ProjectFilter;
import edu.uci.ics.sourcerer.util.Averager;
import edu.uci.ics.sourcerer.util.Helper;
import edu.uci.ics.sourcerer.util.io.FileUtils;
import edu.uci.ics.sourcerer.util.io.Property;
import edu.uci.ics.sourcerer.util.io.TablePrettyPrinter;
import edu.uci.ics.sourcerer.util.io.properties.StringProperty;
/**
* @author Joel Ossher (jossher@uci.edu)
*/
public class ExtractedRepository extends AbstractRepository {
public static final Property<String> EXTRACTION_STATS_FILE = new StringProperty("extraction-stats-file", "extraction-stats.txt", "Output file for the extraction stats.");
private boolean includeNotExtracted = false;
private Collection<ExtractedLibrary> libraries;
private Collection<ExtractedJar> jars;
private Collection<ExtractedProject> projects;
private ExtractedRepository(File repoRoot) {
super(repoRoot);
}
public static ExtractedRepository getRepository(File repoRoot) {
return new ExtractedRepository(repoRoot);
}
public static ExtractedRepository makeJarRepository(File repoRoot, AbstractRepository repo) {
ExtractedRepository extracted = new ExtractedRepository(repoRoot);
extracted.copyJarIndex(repo);
return extracted;
}
@Override
protected void addProject(RepoFile file) {
ExtractedProject extracted = new ExtractedProject(file);
if (includeNotExtracted || extracted.extracted()) {
projects.add(extracted);
} else {
// I think that was introduced because of an error, can be safely removed
extracted = new ExtractedProject(file.getChild("content"));
if (includeNotExtracted || extracted.extracted()) {
projects.add(extracted);
}
}
}
@Override
protected void addLibrary(RepoFile file) {
ExtractedLibrary extracted = new ExtractedLibrary(file);
if (includeNotExtracted || extracted.extracted()) {
libraries.add(extracted);
}
}
private void populateJars() {
final Set<String> filter = JAR_FILTER.hasValue() ? FileUtils.getFileAsSet(JAR_FILTER.getValue()) : null;
final JarIndex index = getJarIndex();
if (index == null) {
jars = Collections.emptyList();
} else {
jars = new AbstractCollection<ExtractedJar>() {
@Override
public int size() {
if (filter == null) {
return index.getIndexSize();
} else {
return filter.size();
}
}
@Override
public Iterator<ExtractedJar> iterator() {
return new Iterator<ExtractedJar>() {
private Iterator<IndexedJar> iter = (filter == null ? index.getJars() : index.getJars(MavenFilter.ALL, ProjectFilter.ALL, filter)).iterator();
private ExtractedJar next = null;
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public ExtractedJar next() {
if (hasNext()) {
ExtractedJar retval = next;
next = null;
return retval;
} else {
throw new NoSuchElementException();
}
}
@Override
public boolean hasNext() {
if (next == null) {
while (iter.hasNext() && next == null) {
next = iter.next().getExtractedJar();
if (!next.extracted()) {
next = null;
}
}
return next != null;
}
return iter.hasNext();
}
};
}
};
}
}
private void loadProjects() {
if (projects == null) {
projects = Helper.newLinkedList();
if (PROJECT_FILTER.hasValue()) {
Set<String> filter = FileUtils.getFileAsSet(PROJECT_FILTER.getValue());
if (filter.isEmpty()) {
logger.log(Level.SEVERE, "Empty project filter!");
}
populateFilteredRepository(filter);
} else {
populateRepository();
}
}
}
public Collection<ExtractedLibrary> getLibraries() {
if (libraries == null) {
libraries = Helper.newLinkedList();
populateLibraries();
}
return libraries;
}
/**
* This method loads the jar listing, if necessary. The
* jar listing is loaded only once. The JAR_FILTER property
* dictates which jars are loaded.
*
* @see AbstractRepository#JAR_FILTER
*/
public Collection<ExtractedJar> getJars() {
if (jars == null) {
populateJars();
}
return jars;
}
/**
* This method loads the project listing, if necessary. The project
* listing is loaded only once. The PROJECT_FILTER property
* dictates which projects are loaded.
*
* @see AbstractRepository#PROJECT_FILTER
*/
public Collection<ExtractedProject> getProjects() {
if (projects == null) {
loadProjects();
}
return projects;
}
public ExtractedLibrary getExtractedLibrary(String name) {
return new ExtractedLibrary(libsRoot.getChild(name));
}
public File getJavaLibrary(String path) {
return new File(repoRoot.toDir(), path + "/lib.jar");
}
public File getJavaLibrarySource(String path) {
return new File(repoRoot.toDir(), path + "/source.jar");
}
public void cloneProperties(ExtractedRepository target) {
logger.info("Cloning extracted library properties...");
{
int count = 0;
for (ExtractedLibrary lib : getLibraries()) {
lib.clonePropertiesFile(target);
count++;
}
logger.info(" " + count + " libraries cloned.");
}
logger.info("Cloning extracted jar properties...");
{
int count = 0;
for (ExtractedJar jar : getJars()) {
jar.clonePropertiesFile(target);
count++;
}
logger.info(" " + count + " jars cloned.");
}
logger.info("Cloning extracted project properties...");
{
int count = 0;
for (ExtractedProject project : getProjects()) {
project.clonePropertiesFile(target);
count++;
}
logger.info(" " + count + " projects cloned.");
}
}
public void computeExtractionStats() {
includeNotExtracted = true;
TablePrettyPrinter printer = TablePrettyPrinter.getTablePrettyPrinter(EXTRACTION_STATS_FILE);
if (libraries == null) {
logger.info("Loading libraries...");
populateLibraries();
}
logger.info("Computing stats for " + libraries.size() + " libraries.");
{
int libsExtracted = 0;
int libsNonEmpty = 0;
int libsWithMissingTypes = 0;
int extractedLibsWithMissingTypes = 0;
int totalBinaryExtracted = 0;
int libsWithBinaryExceptions = 0;
int totalBinaryExceptions = 0;
int libsWithSource = 0;
int totalSourceExtracted = 0;
int libsWithSourceExceptions = 0;
int totalSourceExceptions = 0;
for (ExtractedLibrary lib : libraries) {
if (lib.extracted()) {
libsExtracted++;
if (!lib.empty()) {
libsNonEmpty++;
totalBinaryExtracted += lib.getExtractedFromBinary();
if (lib.hasBinaryExceptions()) {
libsWithBinaryExceptions++;
totalBinaryExceptions += lib.getBinaryExceptions();
}
if (lib.hasSource()) {
libsWithSource++;
totalSourceExtracted += lib.getExtractedFromSource();
if (lib.hasSourceExceptions()) {
libsWithSourceExceptions++;
totalSourceExceptions += lib.getSourceExceptions();
}
}
}
if (lib.hasMissingTypes()) {
extractedLibsWithMissingTypes++;
}
} else if (lib.hasMissingTypes()) {
libsWithMissingTypes++;
}
}
printer.addHeader("Extracted Library Statistics");
printer.beginTable(2);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted libraries");
printer.addCell(libsExtracted);
printer.beginRow();
printer.addCell("Non-empty libraries");
printer.addCell(libsNonEmpty);
printer.beginRow();
printer.addCell("Extracted libraries with missing types");
printer.addCell(libsExtracted);
printer.beginRow();
printer.addCell("Non-extracted libraries with missing types");
printer.addCell(libsExtracted);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(totalBinaryExtracted);
printer.beginRow();
printer.addCell("Libs with binary file exceptions");
printer.addCell(libsWithBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files with exceptions");
printer.addCell(totalBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(totalBinaryExtracted);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Libs with source files");
printer.addCell(libsWithSource);
printer.beginRow();
printer.addCell("Source files extracted");
printer.addCell(totalSourceExtracted);
printer.beginRow();
printer.addCell("Libs with source file exceptions");
printer.addCell(libsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(totalSourceExceptions);
printer.addDividerRow();
printer.endTable();
}
if (jars == null) {
logger.info("Loading jars...");
populateJars();
}
logger.info("Computing stats for " + jars.size() + " jars.");
{
int extracted = 0;
int nonEmpty = 0;
int withMissingTypes = 0;
int jarsWithMissingTypes = 0;
int binaryExtracted = 0;
int jarsWithBinaryExceptions = 0;
int binaryExceptions = 0;
int sourceSkipped = 0;
int withSource = 0;
int sourceExtracted = 0;
int jarsWithSourceExceptions = 0;
int sourceExceptions = 0;
int usingJars = 0;
int usedJars = 0;
int firstOrderJars = 0;
for (ExtractedJar jar : jars) {
if (jar.extracted()) {
extracted++;
if (!jar.empty()) {
nonEmpty++;
binaryExtracted += jar.getExtractedFromBinary();
if (jar.hasBinaryExceptions()) {
jarsWithBinaryExceptions++;
binaryExceptions += jar.getBinaryExceptions();
}
if (jar.sourceSkipped()) {
sourceSkipped++;
}
if (jar.hasSource()) {
withSource++;
sourceExtracted += jar.getExtractedFromSource();
if (jar.hasSourceExceptions()) {
jarsWithSourceExceptions++;
sourceExceptions += jar.getSourceExceptions();
}
}
// if (jar.getFirstOrderJars() == 0 && jar.getJars() > 0) {
// logger.info(jar.getName() + " " + jar.getFirstOrderJars() + " " + jar.getJars());
// } else if (jar.getFirstOrderJars() < 0 || jar.getJars() < 0) {
// logger.info(jar.getName() + " " + jar.getFirstOrderJars() + " " + jar.getJars());
// }
if (jar.getFirstOrderJars() > 0) {
firstOrderJars += jar.getFirstOrderJars();
int usedCount = jar.getJars();
if (usedCount > 0) {
usingJars++;
usedJars += usedCount;
}
}
}
if (jar.hasMissingTypes()) {
jarsWithMissingTypes++;
}
} else if (jar.hasMissingTypes()) {
withMissingTypes++;
}
}
printer.addHeader("Extracted Jar Statistics");
printer.beginTable(2);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted jars");
printer.addCell(extracted);
printer.beginRow();
printer.addCell("Non-empty jars");
printer.addCell(nonEmpty);
printer.beginRow();
printer.addCell("Extracted jars with missing types");
printer.addCell(jarsWithMissingTypes);
printer.beginRow();
printer.addCell("Non-extracted jars with missing types");
printer.addCell(withMissingTypes);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(binaryExtracted);
printer.beginRow();
printer.addCell("Jars with binary file exceptions");
printer.addCell(jarsWithBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files with exceptions");
printer.addCell(binaryExceptions);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Jars with source skipped");
printer.addCell(sourceSkipped);
printer.beginRow();
printer.addCell("Jars with source files");
printer.addCell(withSource);
printer.beginRow();
printer.addCell("Source files extracted");
printer.addCell(sourceExtracted);
printer.beginRow();
printer.addCell("Jars with source file exceptions");
printer.addCell(jarsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(sourceExceptions);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Jars using other jars");
printer.addCell(usingJars);
printer.beginRow();
printer.addCell("Jars used by other jars");
printer.addCell(usedJars);
printer.beginRow();
printer.addCell("First order jars uses");
printer.addCell(firstOrderJars);
printer.addDividerRow();
printer.endTable();
}
getProjects();
logger.info("Computing stats for " + projects.size() + " projects.");
{
int extracted = 0;
int nonEmpty = 0;
int withMissingTypes = 0;
int projectsWithMissingTypes = 0;
int projectsWithSourceExceptions = 0;
int sourceExceptions = 0;
int correctUsingJars = 0;
int missingUsingJars = 0;
Averager<Integer> correctSource = new Averager<Integer>();
Averager<Integer> missingSource = new Averager<Integer>();
Averager<Integer> correctJars = new Averager<Integer>();
Averager<Integer> missingJars = new Averager<Integer>();
for (ExtractedProject project : projects) {
if (project.extracted()) {
extracted++;
if (!project.empty()) {
nonEmpty++;
if (project.hasSourceExceptions()) {
projectsWithSourceExceptions++;
sourceExceptions += project.getSourceExceptions();
}
if (project.hasMissingTypes()) {
projectsWithMissingTypes++;
missingSource.addValue(project.getExtractedFromSource());
int usedCount = project.getJars();
if (usedCount > 0) {
missingUsingJars++;
missingJars.addValue(usedCount);
}
logger.log(Level.SEVERE, "MISSING - " + project);
} else {
correctSource.addValue(project.getExtractedFromSource());
int usedCount = project.getJars();
if (usedCount > 0) {
correctUsingJars++;
correctJars.addValue(usedCount);
}
}
} else {
if (project.hasMissingTypes()) {
logger.info("MISSING + EMPTY: " + project);
}
}
} else if (project.hasMissingTypes()) {
withMissingTypes++;
} else {
logger.info(project.toString());
}
}
printer.addHeader("Extracted Project Statistics");
printer.beginTable(6);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted projects");
printer.addCell(extracted);
printer.beginRow();
printer.addCell("Non-empty projects");
printer.addCell(nonEmpty);
printer.beginRow();
printer.addCell("Extracted projects with missing types");
printer.addCell(projectsWithMissingTypes);
printer.beginRow();
printer.addCell("Non-extracted projects with missing types");
printer.addCell(withMissingTypes);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Correct Projects", 6, TablePrettyPrinter.Alignment.CENTER);
printer.addRow("", "Sum", "Mean", "Dev", "Min", "Max");
- printer.addRow("Source files extracted", correctSource.getSum(), correctSource.getMean(), correctSource.getStandardDeviation(), correctSource.getMin(), correctSource.getMax());
+ printer.addRow("Source files extracted", "" + correctSource.getSum(), "" + correctSource.getMean(), "" + correctSource.getStandardDeviation(), "" + correctSource.getMin(), "" + correctSource.getMax());
printer.addRow("Using jars", "" + correctUsingJars);
- printer.addRow("Used jars", correctJars.getSum(), correctJars.getMean(), correctJars.getStandardDeviation(), correctJars.getMin(), correctJars.getMax());
+ printer.addRow("Used jars", "" + correctJars.getSum(), "" + correctJars.getMean(), "" + correctJars.getStandardDeviation(), "" + correctJars.getMin(), "" + correctJars.getMax());
printer.addDividerRow();
printer.beginRow();
printer.addCell("Missing Type Projects", 6, TablePrettyPrinter.Alignment.CENTER);
printer.addRow("", "Sum", "Mean", "Dev", "Min", "Max");
- printer.addRow("Source files extracted", missingSource.getSum(), missingSource.getMean(), missingSource.getStandardDeviation(), missingSource.getMin(), missingSource.getMax());
+ printer.addRow("Source files extracted", "" + missingSource.getSum(), "" + missingSource.getMean(), "" + missingSource.getStandardDeviation(), "" + missingSource.getMin(), "" + missingSource.getMax());
printer.addRow("Using jars", "" + missingUsingJars);
- printer.addRow("Used jars", missingJars.getSum(), missingJars.getMean(), missingJars.getStandardDeviation(), missingJars.getMin(), missingJars.getMax());
+ printer.addRow("Used jars", "" + missingJars.getSum(), "" + missingJars.getMean(), "" + missingJars.getStandardDeviation(), "" + missingJars.getMin(), "" + missingJars.getMax());
printer.addDividerRow();
printer.beginRow();
printer.addCell("Projects with source file exceptions");
printer.addCell(projectsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(sourceExceptions);
printer.addDividerRow();
printer.endTable();
}
printer.close();
}
}
| false | true | public void computeExtractionStats() {
includeNotExtracted = true;
TablePrettyPrinter printer = TablePrettyPrinter.getTablePrettyPrinter(EXTRACTION_STATS_FILE);
if (libraries == null) {
logger.info("Loading libraries...");
populateLibraries();
}
logger.info("Computing stats for " + libraries.size() + " libraries.");
{
int libsExtracted = 0;
int libsNonEmpty = 0;
int libsWithMissingTypes = 0;
int extractedLibsWithMissingTypes = 0;
int totalBinaryExtracted = 0;
int libsWithBinaryExceptions = 0;
int totalBinaryExceptions = 0;
int libsWithSource = 0;
int totalSourceExtracted = 0;
int libsWithSourceExceptions = 0;
int totalSourceExceptions = 0;
for (ExtractedLibrary lib : libraries) {
if (lib.extracted()) {
libsExtracted++;
if (!lib.empty()) {
libsNonEmpty++;
totalBinaryExtracted += lib.getExtractedFromBinary();
if (lib.hasBinaryExceptions()) {
libsWithBinaryExceptions++;
totalBinaryExceptions += lib.getBinaryExceptions();
}
if (lib.hasSource()) {
libsWithSource++;
totalSourceExtracted += lib.getExtractedFromSource();
if (lib.hasSourceExceptions()) {
libsWithSourceExceptions++;
totalSourceExceptions += lib.getSourceExceptions();
}
}
}
if (lib.hasMissingTypes()) {
extractedLibsWithMissingTypes++;
}
} else if (lib.hasMissingTypes()) {
libsWithMissingTypes++;
}
}
printer.addHeader("Extracted Library Statistics");
printer.beginTable(2);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted libraries");
printer.addCell(libsExtracted);
printer.beginRow();
printer.addCell("Non-empty libraries");
printer.addCell(libsNonEmpty);
printer.beginRow();
printer.addCell("Extracted libraries with missing types");
printer.addCell(libsExtracted);
printer.beginRow();
printer.addCell("Non-extracted libraries with missing types");
printer.addCell(libsExtracted);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(totalBinaryExtracted);
printer.beginRow();
printer.addCell("Libs with binary file exceptions");
printer.addCell(libsWithBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files with exceptions");
printer.addCell(totalBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(totalBinaryExtracted);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Libs with source files");
printer.addCell(libsWithSource);
printer.beginRow();
printer.addCell("Source files extracted");
printer.addCell(totalSourceExtracted);
printer.beginRow();
printer.addCell("Libs with source file exceptions");
printer.addCell(libsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(totalSourceExceptions);
printer.addDividerRow();
printer.endTable();
}
if (jars == null) {
logger.info("Loading jars...");
populateJars();
}
logger.info("Computing stats for " + jars.size() + " jars.");
{
int extracted = 0;
int nonEmpty = 0;
int withMissingTypes = 0;
int jarsWithMissingTypes = 0;
int binaryExtracted = 0;
int jarsWithBinaryExceptions = 0;
int binaryExceptions = 0;
int sourceSkipped = 0;
int withSource = 0;
int sourceExtracted = 0;
int jarsWithSourceExceptions = 0;
int sourceExceptions = 0;
int usingJars = 0;
int usedJars = 0;
int firstOrderJars = 0;
for (ExtractedJar jar : jars) {
if (jar.extracted()) {
extracted++;
if (!jar.empty()) {
nonEmpty++;
binaryExtracted += jar.getExtractedFromBinary();
if (jar.hasBinaryExceptions()) {
jarsWithBinaryExceptions++;
binaryExceptions += jar.getBinaryExceptions();
}
if (jar.sourceSkipped()) {
sourceSkipped++;
}
if (jar.hasSource()) {
withSource++;
sourceExtracted += jar.getExtractedFromSource();
if (jar.hasSourceExceptions()) {
jarsWithSourceExceptions++;
sourceExceptions += jar.getSourceExceptions();
}
}
// if (jar.getFirstOrderJars() == 0 && jar.getJars() > 0) {
// logger.info(jar.getName() + " " + jar.getFirstOrderJars() + " " + jar.getJars());
// } else if (jar.getFirstOrderJars() < 0 || jar.getJars() < 0) {
// logger.info(jar.getName() + " " + jar.getFirstOrderJars() + " " + jar.getJars());
// }
if (jar.getFirstOrderJars() > 0) {
firstOrderJars += jar.getFirstOrderJars();
int usedCount = jar.getJars();
if (usedCount > 0) {
usingJars++;
usedJars += usedCount;
}
}
}
if (jar.hasMissingTypes()) {
jarsWithMissingTypes++;
}
} else if (jar.hasMissingTypes()) {
withMissingTypes++;
}
}
printer.addHeader("Extracted Jar Statistics");
printer.beginTable(2);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted jars");
printer.addCell(extracted);
printer.beginRow();
printer.addCell("Non-empty jars");
printer.addCell(nonEmpty);
printer.beginRow();
printer.addCell("Extracted jars with missing types");
printer.addCell(jarsWithMissingTypes);
printer.beginRow();
printer.addCell("Non-extracted jars with missing types");
printer.addCell(withMissingTypes);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(binaryExtracted);
printer.beginRow();
printer.addCell("Jars with binary file exceptions");
printer.addCell(jarsWithBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files with exceptions");
printer.addCell(binaryExceptions);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Jars with source skipped");
printer.addCell(sourceSkipped);
printer.beginRow();
printer.addCell("Jars with source files");
printer.addCell(withSource);
printer.beginRow();
printer.addCell("Source files extracted");
printer.addCell(sourceExtracted);
printer.beginRow();
printer.addCell("Jars with source file exceptions");
printer.addCell(jarsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(sourceExceptions);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Jars using other jars");
printer.addCell(usingJars);
printer.beginRow();
printer.addCell("Jars used by other jars");
printer.addCell(usedJars);
printer.beginRow();
printer.addCell("First order jars uses");
printer.addCell(firstOrderJars);
printer.addDividerRow();
printer.endTable();
}
getProjects();
logger.info("Computing stats for " + projects.size() + " projects.");
{
int extracted = 0;
int nonEmpty = 0;
int withMissingTypes = 0;
int projectsWithMissingTypes = 0;
int projectsWithSourceExceptions = 0;
int sourceExceptions = 0;
int correctUsingJars = 0;
int missingUsingJars = 0;
Averager<Integer> correctSource = new Averager<Integer>();
Averager<Integer> missingSource = new Averager<Integer>();
Averager<Integer> correctJars = new Averager<Integer>();
Averager<Integer> missingJars = new Averager<Integer>();
for (ExtractedProject project : projects) {
if (project.extracted()) {
extracted++;
if (!project.empty()) {
nonEmpty++;
if (project.hasSourceExceptions()) {
projectsWithSourceExceptions++;
sourceExceptions += project.getSourceExceptions();
}
if (project.hasMissingTypes()) {
projectsWithMissingTypes++;
missingSource.addValue(project.getExtractedFromSource());
int usedCount = project.getJars();
if (usedCount > 0) {
missingUsingJars++;
missingJars.addValue(usedCount);
}
logger.log(Level.SEVERE, "MISSING - " + project);
} else {
correctSource.addValue(project.getExtractedFromSource());
int usedCount = project.getJars();
if (usedCount > 0) {
correctUsingJars++;
correctJars.addValue(usedCount);
}
}
} else {
if (project.hasMissingTypes()) {
logger.info("MISSING + EMPTY: " + project);
}
}
} else if (project.hasMissingTypes()) {
withMissingTypes++;
} else {
logger.info(project.toString());
}
}
printer.addHeader("Extracted Project Statistics");
printer.beginTable(6);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted projects");
printer.addCell(extracted);
printer.beginRow();
printer.addCell("Non-empty projects");
printer.addCell(nonEmpty);
printer.beginRow();
printer.addCell("Extracted projects with missing types");
printer.addCell(projectsWithMissingTypes);
printer.beginRow();
printer.addCell("Non-extracted projects with missing types");
printer.addCell(withMissingTypes);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Correct Projects", 6, TablePrettyPrinter.Alignment.CENTER);
printer.addRow("", "Sum", "Mean", "Dev", "Min", "Max");
printer.addRow("Source files extracted", correctSource.getSum(), correctSource.getMean(), correctSource.getStandardDeviation(), correctSource.getMin(), correctSource.getMax());
printer.addRow("Using jars", "" + correctUsingJars);
printer.addRow("Used jars", correctJars.getSum(), correctJars.getMean(), correctJars.getStandardDeviation(), correctJars.getMin(), correctJars.getMax());
printer.addDividerRow();
printer.beginRow();
printer.addCell("Missing Type Projects", 6, TablePrettyPrinter.Alignment.CENTER);
printer.addRow("", "Sum", "Mean", "Dev", "Min", "Max");
printer.addRow("Source files extracted", missingSource.getSum(), missingSource.getMean(), missingSource.getStandardDeviation(), missingSource.getMin(), missingSource.getMax());
printer.addRow("Using jars", "" + missingUsingJars);
printer.addRow("Used jars", missingJars.getSum(), missingJars.getMean(), missingJars.getStandardDeviation(), missingJars.getMin(), missingJars.getMax());
printer.addDividerRow();
printer.beginRow();
printer.addCell("Projects with source file exceptions");
printer.addCell(projectsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(sourceExceptions);
printer.addDividerRow();
printer.endTable();
}
printer.close();
}
| public void computeExtractionStats() {
includeNotExtracted = true;
TablePrettyPrinter printer = TablePrettyPrinter.getTablePrettyPrinter(EXTRACTION_STATS_FILE);
if (libraries == null) {
logger.info("Loading libraries...");
populateLibraries();
}
logger.info("Computing stats for " + libraries.size() + " libraries.");
{
int libsExtracted = 0;
int libsNonEmpty = 0;
int libsWithMissingTypes = 0;
int extractedLibsWithMissingTypes = 0;
int totalBinaryExtracted = 0;
int libsWithBinaryExceptions = 0;
int totalBinaryExceptions = 0;
int libsWithSource = 0;
int totalSourceExtracted = 0;
int libsWithSourceExceptions = 0;
int totalSourceExceptions = 0;
for (ExtractedLibrary lib : libraries) {
if (lib.extracted()) {
libsExtracted++;
if (!lib.empty()) {
libsNonEmpty++;
totalBinaryExtracted += lib.getExtractedFromBinary();
if (lib.hasBinaryExceptions()) {
libsWithBinaryExceptions++;
totalBinaryExceptions += lib.getBinaryExceptions();
}
if (lib.hasSource()) {
libsWithSource++;
totalSourceExtracted += lib.getExtractedFromSource();
if (lib.hasSourceExceptions()) {
libsWithSourceExceptions++;
totalSourceExceptions += lib.getSourceExceptions();
}
}
}
if (lib.hasMissingTypes()) {
extractedLibsWithMissingTypes++;
}
} else if (lib.hasMissingTypes()) {
libsWithMissingTypes++;
}
}
printer.addHeader("Extracted Library Statistics");
printer.beginTable(2);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted libraries");
printer.addCell(libsExtracted);
printer.beginRow();
printer.addCell("Non-empty libraries");
printer.addCell(libsNonEmpty);
printer.beginRow();
printer.addCell("Extracted libraries with missing types");
printer.addCell(libsExtracted);
printer.beginRow();
printer.addCell("Non-extracted libraries with missing types");
printer.addCell(libsExtracted);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(totalBinaryExtracted);
printer.beginRow();
printer.addCell("Libs with binary file exceptions");
printer.addCell(libsWithBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files with exceptions");
printer.addCell(totalBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(totalBinaryExtracted);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Libs with source files");
printer.addCell(libsWithSource);
printer.beginRow();
printer.addCell("Source files extracted");
printer.addCell(totalSourceExtracted);
printer.beginRow();
printer.addCell("Libs with source file exceptions");
printer.addCell(libsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(totalSourceExceptions);
printer.addDividerRow();
printer.endTable();
}
if (jars == null) {
logger.info("Loading jars...");
populateJars();
}
logger.info("Computing stats for " + jars.size() + " jars.");
{
int extracted = 0;
int nonEmpty = 0;
int withMissingTypes = 0;
int jarsWithMissingTypes = 0;
int binaryExtracted = 0;
int jarsWithBinaryExceptions = 0;
int binaryExceptions = 0;
int sourceSkipped = 0;
int withSource = 0;
int sourceExtracted = 0;
int jarsWithSourceExceptions = 0;
int sourceExceptions = 0;
int usingJars = 0;
int usedJars = 0;
int firstOrderJars = 0;
for (ExtractedJar jar : jars) {
if (jar.extracted()) {
extracted++;
if (!jar.empty()) {
nonEmpty++;
binaryExtracted += jar.getExtractedFromBinary();
if (jar.hasBinaryExceptions()) {
jarsWithBinaryExceptions++;
binaryExceptions += jar.getBinaryExceptions();
}
if (jar.sourceSkipped()) {
sourceSkipped++;
}
if (jar.hasSource()) {
withSource++;
sourceExtracted += jar.getExtractedFromSource();
if (jar.hasSourceExceptions()) {
jarsWithSourceExceptions++;
sourceExceptions += jar.getSourceExceptions();
}
}
// if (jar.getFirstOrderJars() == 0 && jar.getJars() > 0) {
// logger.info(jar.getName() + " " + jar.getFirstOrderJars() + " " + jar.getJars());
// } else if (jar.getFirstOrderJars() < 0 || jar.getJars() < 0) {
// logger.info(jar.getName() + " " + jar.getFirstOrderJars() + " " + jar.getJars());
// }
if (jar.getFirstOrderJars() > 0) {
firstOrderJars += jar.getFirstOrderJars();
int usedCount = jar.getJars();
if (usedCount > 0) {
usingJars++;
usedJars += usedCount;
}
}
}
if (jar.hasMissingTypes()) {
jarsWithMissingTypes++;
}
} else if (jar.hasMissingTypes()) {
withMissingTypes++;
}
}
printer.addHeader("Extracted Jar Statistics");
printer.beginTable(2);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted jars");
printer.addCell(extracted);
printer.beginRow();
printer.addCell("Non-empty jars");
printer.addCell(nonEmpty);
printer.beginRow();
printer.addCell("Extracted jars with missing types");
printer.addCell(jarsWithMissingTypes);
printer.beginRow();
printer.addCell("Non-extracted jars with missing types");
printer.addCell(withMissingTypes);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Binary files extracted");
printer.addCell(binaryExtracted);
printer.beginRow();
printer.addCell("Jars with binary file exceptions");
printer.addCell(jarsWithBinaryExceptions);
printer.beginRow();
printer.addCell("Binary files with exceptions");
printer.addCell(binaryExceptions);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Jars with source skipped");
printer.addCell(sourceSkipped);
printer.beginRow();
printer.addCell("Jars with source files");
printer.addCell(withSource);
printer.beginRow();
printer.addCell("Source files extracted");
printer.addCell(sourceExtracted);
printer.beginRow();
printer.addCell("Jars with source file exceptions");
printer.addCell(jarsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(sourceExceptions);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Jars using other jars");
printer.addCell(usingJars);
printer.beginRow();
printer.addCell("Jars used by other jars");
printer.addCell(usedJars);
printer.beginRow();
printer.addCell("First order jars uses");
printer.addCell(firstOrderJars);
printer.addDividerRow();
printer.endTable();
}
getProjects();
logger.info("Computing stats for " + projects.size() + " projects.");
{
int extracted = 0;
int nonEmpty = 0;
int withMissingTypes = 0;
int projectsWithMissingTypes = 0;
int projectsWithSourceExceptions = 0;
int sourceExceptions = 0;
int correctUsingJars = 0;
int missingUsingJars = 0;
Averager<Integer> correctSource = new Averager<Integer>();
Averager<Integer> missingSource = new Averager<Integer>();
Averager<Integer> correctJars = new Averager<Integer>();
Averager<Integer> missingJars = new Averager<Integer>();
for (ExtractedProject project : projects) {
if (project.extracted()) {
extracted++;
if (!project.empty()) {
nonEmpty++;
if (project.hasSourceExceptions()) {
projectsWithSourceExceptions++;
sourceExceptions += project.getSourceExceptions();
}
if (project.hasMissingTypes()) {
projectsWithMissingTypes++;
missingSource.addValue(project.getExtractedFromSource());
int usedCount = project.getJars();
if (usedCount > 0) {
missingUsingJars++;
missingJars.addValue(usedCount);
}
logger.log(Level.SEVERE, "MISSING - " + project);
} else {
correctSource.addValue(project.getExtractedFromSource());
int usedCount = project.getJars();
if (usedCount > 0) {
correctUsingJars++;
correctJars.addValue(usedCount);
}
}
} else {
if (project.hasMissingTypes()) {
logger.info("MISSING + EMPTY: " + project);
}
}
} else if (project.hasMissingTypes()) {
withMissingTypes++;
} else {
logger.info(project.toString());
}
}
printer.addHeader("Extracted Project Statistics");
printer.beginTable(6);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Extracted projects");
printer.addCell(extracted);
printer.beginRow();
printer.addCell("Non-empty projects");
printer.addCell(nonEmpty);
printer.beginRow();
printer.addCell("Extracted projects with missing types");
printer.addCell(projectsWithMissingTypes);
printer.beginRow();
printer.addCell("Non-extracted projects with missing types");
printer.addCell(withMissingTypes);
printer.addDividerRow();
printer.beginRow();
printer.addCell("Correct Projects", 6, TablePrettyPrinter.Alignment.CENTER);
printer.addRow("", "Sum", "Mean", "Dev", "Min", "Max");
printer.addRow("Source files extracted", "" + correctSource.getSum(), "" + correctSource.getMean(), "" + correctSource.getStandardDeviation(), "" + correctSource.getMin(), "" + correctSource.getMax());
printer.addRow("Using jars", "" + correctUsingJars);
printer.addRow("Used jars", "" + correctJars.getSum(), "" + correctJars.getMean(), "" + correctJars.getStandardDeviation(), "" + correctJars.getMin(), "" + correctJars.getMax());
printer.addDividerRow();
printer.beginRow();
printer.addCell("Missing Type Projects", 6, TablePrettyPrinter.Alignment.CENTER);
printer.addRow("", "Sum", "Mean", "Dev", "Min", "Max");
printer.addRow("Source files extracted", "" + missingSource.getSum(), "" + missingSource.getMean(), "" + missingSource.getStandardDeviation(), "" + missingSource.getMin(), "" + missingSource.getMax());
printer.addRow("Using jars", "" + missingUsingJars);
printer.addRow("Used jars", "" + missingJars.getSum(), "" + missingJars.getMean(), "" + missingJars.getStandardDeviation(), "" + missingJars.getMin(), "" + missingJars.getMax());
printer.addDividerRow();
printer.beginRow();
printer.addCell("Projects with source file exceptions");
printer.addCell(projectsWithSourceExceptions);
printer.beginRow();
printer.addCell("Source files with exceptions");
printer.addCell(sourceExceptions);
printer.addDividerRow();
printer.endTable();
}
printer.close();
}
|
diff --git a/src/com/gradugation/MainGameScreen.java b/src/com/gradugation/MainGameScreen.java
index 76237ec..88e8787 100644
--- a/src/com/gradugation/MainGameScreen.java
+++ b/src/com/gradugation/MainGameScreen.java
@@ -1,972 +1,972 @@
package com.gradugation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import org.andengine.audio.music.Music;
import org.andengine.audio.music.MusicFactory;
import org.andengine.engine.camera.BoundCamera;
import org.andengine.engine.camera.SmoothCamera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.CameraScene;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.util.FPSLogger;
import org.andengine.extension.tmx.TMXLayer;
import org.andengine.extension.tmx.TMXLoader;
import org.andengine.extension.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.andengine.extension.tmx.TMXProperties;
import org.andengine.extension.tmx.TMXTile;
import org.andengine.extension.tmx.TMXTileProperty;
import org.andengine.extension.tmx.TMXTiledMap;
import org.andengine.extension.tmx.util.exception.TMXLoadException;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.StrokeFont;
import org.andengine.opengl.texture.EmptyTexture;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.bitmap.AssetBitmapTexture;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.Constants;
import org.andengine.util.debug.Debug;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.coordinates.MapCoordinate;
import com.coordinates.SpriteCoordinate;
public class MainGameScreen extends SimpleBaseGameActivity implements
IOnSceneTouchListener {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
//private static final int MAX_CHARACTER_MOVEMENT = 3;
public static final int CHARACTER_WIDTH = 32;
private static final String MAP_NAME = "map_text_file.txt";
// ===========================================================
// Fields
// ===========================================================
// Need handler for callbacks to the UI thread
final Handler mHandler = new Handler();
private AlertDialog.Builder alertDialogBuilder;
private AlertDialog alertDialog;
private BoundCamera mCamera;
private ITexture mPlayerTexture;
private TiledTextureRegion mPlayerTextureRegion;
private TMXTiledMap mTMXTiledMap;
protected int mCactusCount;
private int CREDITS_NEEDED_GRADUATE = 15;
private BitmapTextureAtlas[] characterTextureAtlas;
private ITextureRegion[] character;
private Sprite[] spriteList;
private BitmapTextureAtlas diceTextureAtlas;
private TextureRegion diceTextureRegion;
private BitmapTextureAtlas finishTurnTextureAtlas;
private TextureRegion finishTurnTextureRegion;
private BitmapTextureAtlas musicTextureAtlas;
private ITextureRegion mMusicTextureRegion;
private BitmapTextureAtlas rightArrowTextureAtlas;
private ITextureRegion rightArrowRegion;
private BitmapTextureAtlas leftArrowTextureAtlas;
private ITextureRegion leftArrowRegion;
private BitmapTextureAtlas downArrowTextureAtlas;
private ITextureRegion downArrowRegion;
private BitmapTextureAtlas upArrowTextureAtlas;
private ITextureRegion upArrowRegion;
private ITexture mFaceTexture;
private ITextureRegion mFaceTextureRegion;
private ITexture mPausedTexture, mResumeTexture, mMainMenuTexture, mSaveTexture;
private ITextureRegion mPausedTextureRegion, mResumeTextureRegion,
mMainMenuTextureRegion, mSaveTextureRegion;
private CameraScene mPauseScene;
private Scene scene;
private Event mainMapEvent;
private HUD mHUD;
private Font mFont;
private StrokeFont mStrokeFont, mStrokeFontLarge;
private Music mMusic;
private ArrayList<Character> thePlayers;
private Text[] textStrokes;
final private SpriteCoordinate[] textStrokeCoordinates = {
new SpriteCoordinate(60,280), new SpriteCoordinate(420,280),
new SpriteCoordinate(60,40), new SpriteCoordinate(420,40) };
private boolean turnDone;
private boolean eventCompleted;
private boolean moving;
public int turnNum;
public int currentCharacter;
public int currentCharacterYear;
public int movesLeft;
private int numCharacters;
private int movementCount;
private Text textStroke5;
private Random random;
private int diceRoll = 0;
private int maxRoll;
private boolean gameDone = false;
private boolean hasGraduated = false;
float initX;
float initY;
float finalX;
float finalY;
float variable;
private boolean finishTurn = false;
private boolean diceDone = false;
private boolean music;
boolean swipeDone = false;
private DbHelper dbhelper;
@Override
public EngineOptions onCreateEngineOptions() {
final float maxVelocityX = 150;
final float maxVelocityY = 150;
final float maxZoomFactorChange = 5;
this.mCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT,
maxVelocityX, maxVelocityY, maxZoomFactorChange);
this.mCamera.setBoundsEnabled(false);
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);
engineOptions.getAudioOptions().setNeedsMusic(true);
return engineOptions;
}
@Override
public void onCreateResources() throws IOException {
mainMapEvent = new Event(this, R.raw.map_text_file);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
thePlayers = (ArrayList<Character>) bundle.getSerializable(ChooseCharacterActivity.THE_PLAYERS);
numCharacters = thePlayers.size();
//Create all four character sprites
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
characterTextureAtlas = new BitmapTextureAtlas[numCharacters];
character = new ITextureRegion[numCharacters];
for (int i = 0; i < numCharacters; i++) {
characterTextureAtlas[i] = new BitmapTextureAtlas(
this.getTextureManager(), 1000, 1000, TextureOptions.BILINEAR);
character[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(characterTextureAtlas[i],
this, thePlayers.get(i).getCharacterImage(), 0 , 0); //NameToImageName(characterTypes[i]), 0, 0);
characterTextureAtlas[i].load();
}
this.diceTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 170, 90, TextureOptions.BILINEAR);
this.diceTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(diceTextureAtlas, this, "dice.png",
0, 0);
this.diceTextureAtlas.load();
this.finishTurnTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 170, 90, TextureOptions.BILINEAR);
this.finishTurnTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(finishTurnTextureAtlas, this, "finish_button.png",
0, 0);
this.finishTurnTextureAtlas.load();
// Pause Assets
this.mFaceTexture = new AssetBitmapTexture(this.getTextureManager(),
this.getAssets(), "gfx/menu.png", TextureOptions.BILINEAR);
this.mFaceTextureRegion = TextureRegionFactory
.extractFromTexture(this.mFaceTexture);
this.mFaceTexture.load();
this.mPausedTexture = new AssetBitmapTexture(this.getTextureManager(),
this.getAssets(), "gfx/paused.png", TextureOptions.BILINEAR);
this.mPausedTextureRegion = TextureRegionFactory
.extractFromTexture(this.mPausedTexture);
this.mPausedTexture.load();
this.mResumeTexture = new AssetBitmapTexture(this.getTextureManager(),
this.getAssets(), "gfx/resume.png", TextureOptions.BILINEAR);
this.mResumeTextureRegion = TextureRegionFactory
.extractFromTexture(this.mResumeTexture);
this.mResumeTexture.load();
this.mMainMenuTexture = new AssetBitmapTexture(
this.getTextureManager(), this.getAssets(), "gfx/mainmenu.png",
TextureOptions.BILINEAR);
this.mMainMenuTextureRegion = TextureRegionFactory
.extractFromTexture(this.mMainMenuTexture);
this.mMainMenuTexture.load();
this.mSaveTexture = new AssetBitmapTexture(this.getTextureManager(),
this.getAssets(), "gfx/savegame.png", TextureOptions.BILINEAR);
this.mSaveTextureRegion = TextureRegionFactory
.extractFromTexture(this.mSaveTexture);
this.mSaveTexture.load();
// UI Fonts
final ITexture fontTexture = new EmptyTexture(this.getTextureManager(),
256, 256, TextureOptions.BILINEAR);
final ITexture strokeFontTexture = new EmptyTexture(
this.getTextureManager(), 256, 256, TextureOptions.BILINEAR);
this.mFont = new Font(this.getFontManager(), fontTexture,
Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 18, true,
Color.BLACK);
this.mFont.load();
this.mStrokeFont = new StrokeFont(this.getFontManager(),
strokeFontTexture, Typeface.create(Typeface.DEFAULT,
Typeface.BOLD), 18, true, Color.WHITE, 1, Color.BLACK);
this.mStrokeFont.load();
this.mStrokeFontLarge = new StrokeFont(this.getFontManager(),
strokeFontTexture, Typeface.create(Typeface.DEFAULT,
Typeface.BOLD), 32, true, Color.WHITE, 1, Color.BLACK);
this.mStrokeFontLarge.load();
this.musicTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 128, 128, TextureOptions.BILINEAR);
this.mMusicTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.musicTextureAtlas, this, "notes.png", 0, 0);
this.musicTextureAtlas.load();
MusicFactory.setAssetBasePath("mfx/");
try {
this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "DST-TowerDefenseTheme.mp3");
this.mMusic.setLooping(true);
} catch (final IOException e) {
Debug.e(e);
}
}
@Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
/*
* User Interface HUD At each corner of the screen, will display
* player's information Include number of credits There will be a button
* to roll dice and turn number will be displayed.
*/
VertexBufferObjectManager vertexBufferObjectManager = this
.getVertexBufferObjectManager();
textStrokes = new Text[numCharacters];
/*
* To update text, use [text].setText("blah blah"); In which "blah blah"
* is whatever you want to change the text to. You can use variables.
*/
for (int i = 0; i < numCharacters; i++) {
SpriteCoordinate coord = textStrokeCoordinates[i];
textStrokes[i] = new Text(coord.getX(), coord.getY(), this.mStrokeFont,
thePlayers.get(i).getName() +"\nCredits: " + thePlayers.get(i).getCredits()
+ "\nCoins: " + thePlayers.get(i).getCoins(), vertexBufferObjectManager);
}
textStroke5 = new Text(180, 20, this.mStrokeFont,
" " + diceRoll, vertexBufferObjectManager);
textStroke5.setScale((float) .7 );
mHUD = new HUD();
mHUD.attachChild(scene);
final Sprite diceButton = new Sprite(180, CAMERA_HEIGHT/10, this.diceTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
//generate random number [1,3]
currentCharacterYear = (thePlayers.get(currentCharacter).getCredits()/3) + 1;
switch(currentCharacterYear) {
case 0: maxRoll = 3;
break;
case 1: maxRoll = 3;
break;
case 2: maxRoll = 4;
break;
case 3: maxRoll = 4;
break;
case 4: maxRoll = 5;
break;
case 5: maxRoll = 6;
break;
default: maxRoll = 3;
break;
}
random = new Random();
diceRoll = random.nextInt(maxRoll) + 1;
if (diceDone == false) {
swipeDone = false;
if (touchEvent.isActionUp()) {
this.setColor(Color.GRAY);
textStroke5.setText(" " + diceRoll);
movesLeft = diceRoll;
eventCompleted = false;
diceDone = true;
move = false;
gameDone = false;
}
if (touchEvent.isActionDown()) {
this.setColor(Color.WHITE);
}
}
return true;
};
};
diceButton.setScale((float) .5);
this.rightArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.rightArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(rightArrowTextureAtlas, this, "right_arrow.png",
0, 0);
this.rightArrowTextureAtlas.load();
final Sprite rightArrowButton = new Sprite(CAMERA_WIDTH-CHARACTER_WIDTH, CAMERA_HEIGHT/2, this.rightArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(CHARACTER_WIDTH,0));
} else {
return false;
}
}
};
rightArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(rightArrowButton);
this.mHUD.attachChild(rightArrowButton);
this.leftArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.leftArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(leftArrowTextureAtlas, this, "left_arrow.png",
0, 0);
this.leftArrowTextureAtlas.load();
final Sprite leftArrowButton = new Sprite(CHARACTER_WIDTH, CAMERA_HEIGHT/2, this.leftArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(-CHARACTER_WIDTH,0));
} else {
return false;
}
}
return true;
}
};
leftArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(leftArrowButton);
this.mHUD.attachChild(leftArrowButton);
this.downArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.downArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(downArrowTextureAtlas, this, "down_arrow.png",
0, 0);
this.downArrowTextureAtlas.load();
final Sprite downArrowButton = new Sprite(CAMERA_WIDTH/2, CHARACTER_WIDTH, this.downArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(0, -CHARACTER_WIDTH));
} else {
return false;
}
}
return true;
}
};
downArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(downArrowButton);
this.mHUD.attachChild(downArrowButton);
this.upArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.upArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(upArrowTextureAtlas, this, "up_arrow.png",
0, 0);
this.upArrowTextureAtlas.load();
final Sprite upArrowButton = new Sprite(CAMERA_WIDTH/2, CAMERA_HEIGHT-CHARACTER_WIDTH, this.upArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(0,CHARACTER_WIDTH));
} else {
return false;
}
}
return true;
}
};
upArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(upArrowButton);
this.mHUD.attachChild(upArrowButton);
final Sprite finishTurnButton = new Sprite(310, CAMERA_HEIGHT/10, this.finishTurnTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (movesLeft == 0) {
if (touchEvent.isActionUp()) {
this.setColor(Color.GRAY);
finishTurn = true;
}
if (touchEvent.isActionDown()) {
this.setColor(Color.GRAY);
}
return true;
} else {
return false;
}
};
};
finishTurnButton.setScale((float) .5);
finishTurnButton.setColor(Color.GRAY);
// Load the Pause Scene
this.mPauseScene = new CameraScene(this.mCamera);
final float cX = (CAMERA_WIDTH - this.mPausedTextureRegion.getWidth())
/ 2 + (this.mPausedTextureRegion.getWidth() / 3);
final float cY = (CAMERA_HEIGHT - this.mPausedTextureRegion.getHeight()) / 5;
// Music Button
// Default - Music on.
mMusic.play();
final Sprite musicButton = new Sprite(CAMERA_WIDTH / 12, cY - (CAMERA_HEIGHT / 13), this.mMusicTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
if (mMusic.isPlaying()) {
mMusic.pause();
music = false;
} else {
mMusic.play();
music = true;
}
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(musicButton);
this.mPauseScene.attachChild(musicButton);
// Resume Button
final Sprite resumeButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 2), this.mResumeTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
mHUD.clearChildScene();
scene.setIgnoreUpdate(false);
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(resumeButton);
this.mPauseScene.attachChild(resumeButton);
// Return to main menu button
final Sprite mainMenuButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 3), this.mMainMenuTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
scene.detachChildren();
scene.clearEntityModifiers();
scene.clearTouchAreas();
scene.clearUpdateHandlers();
mHUD.detachChildren();
mPauseScene.detachChildren();
this.detachSelf();
onClick(mRenderSurfaceView);
finish();
break;
default:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(mainMenuButton);
this.mPauseScene.attachChild(mainMenuButton);
//save game button
final Sprite saveButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 6), this.mSaveTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
//update database here
saveGame();
mHUD.clearChildScene();
scene.setIgnoreUpdate(false);
//save to database
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(saveButton);
this.mPauseScene.attachChild(saveButton);
/* Makes the paused Game look through. */
this.mPauseScene.setBackgroundEnabled(false);
// Main Menu Button on HUD
- final Sprite pauseSprite = new Sprite(mCamera.getWidth() / 2 + CHARACTER_WIDTH, 300, this.mFaceTextureRegion,
+ final Sprite pauseSprite = new Sprite(mCamera.getWidth() / 2 + CHARACTER_WIDTH + 50 , 300, this.mFaceTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
scene.setIgnoreUpdate(true);
mHUD.setChildScene(mPauseScene, false, true, true);
break;
default:
break;
}
return true;
};
};
for (int i = 0; i < numCharacters; i++) {
mHUD.attachChild(textStrokes[i]);
}
mHUD.registerTouchArea(diceButton);
mHUD.attachChild(diceButton);
mHUD.registerTouchArea(finishTurnButton);
mHUD.attachChild(finishTurnButton);
mHUD.attachChild(textStroke5);
mHUD.registerTouchArea(pauseSprite);
mHUD.attachChild(pauseSprite);
mCamera.setHUD(mHUD);
/* Main Map Scene */
scene.setOnSceneTouchListener(this);
try {
final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
this.mEngine.getTextureManager(),
TextureOptions.BILINEAR_PREMULTIPLYALPHA,
this.getVertexBufferObjectManager(),
new ITMXTilePropertiesListener() {
@Override
public void onTMXTileWithPropertiesCreated(
final TMXTiledMap pTMXTiledMap,
final TMXLayer pTMXLayer,
final TMXTile pTMXTile,
final TMXProperties<TMXTileProperty> pTMXTileProperties) {
}
});
this.mTMXTiledMap = tmxLoader
.loadFromAsset("tmx/MultiGator14Layers.tmx");
this.mTMXTiledMap.setOffsetCenter(0, 0);
// this.toastOnUiThread("Cactus count in this TMXTiledMap: " +
// MainGameScreen.this.mCactusCount, Toast.LENGTH_LONG);
} catch (final TMXLoadException e) {
Debug.e(e);
}
moving = false;
turnDone = false;
turnNum = 1;
scene.attachChild(this.mTMXTiledMap);
/* Make the camera not exceed the bounds of the TMXEntity. */
this.mCamera.setBoundsEnabled(false);
this.mCamera.setBounds(0, 0, this.mTMXTiledMap.getWidth(),
this.mTMXTiledMap.getHeight());
this.mCamera.setBoundsEnabled(true);
spriteList = new Sprite[numCharacters];
for (int i = 0; i < numCharacters; i++) {
SpriteCoordinate loc = thePlayers.get(i).getSpriteLocation();
spriteList[i] = new Sprite(loc.getX(), loc.getY(), character[i],
this.getVertexBufferObjectManager());
}
//Open Database
dbhelper = new DbHelper(this);
SQLiteDatabase db = dbhelper.openDB();
Log.d("TEST", "Database has been opened");
Log.d("TEST2", Integer.toString(thePlayers.get(0).gameId));
String[] gameKey = { Integer.toString(thePlayers.get(0).gameId) };
//Grab Game info
ArrayList gameList = dbhelper.getRow(1, gameKey);
if (gameList.size()>0){
currentCharacter = Integer.valueOf((String)gameList.get(3));
}
dbhelper.close();
this.mCamera.setChaseEntity(spriteList[currentCharacter]);
/* The layer for the player to walk on. */
final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
scene.registerUpdateHandler(new IUpdateHandler() {
@Override
public void reset() {
}
@Override
public void onUpdate(final float pSecondsElapsed) {
// /* Get the scene-coordinates of the players feet. */
float[] localCoord = new float[2];
localCoord[0] = spriteList[currentCharacter].getWidth() * .5f;
localCoord[1] = spriteList[currentCharacter].getHeight() * .5f;
final float[] playerFootCordinates = spriteList[currentCharacter]
.convertLocalCoordinatesToSceneCoordinates(localCoord);
/* Get the tile the feet of the player are currently waking on. */
final TMXTile tmxTile = tmxLayer.getTMXTileAt(
playerFootCordinates[Constants.VERTEX_INDEX_X],
playerFootCordinates[Constants.VERTEX_INDEX_Y]);
if (movesLeft == 0 && diceDone) {
MainGameScreen.this.mCamera.updateChaseEntity();
finishTurnButton.setColor(Color.WHITE);
}
if (turnDone && finishTurn) { //&& swipeDone == false
moving = false;
move = false;
turnDone = false;
diceDone = false;
currentCharacter = (currentCharacter + 1) % (numCharacters);
saveGame();
// consider a delay here so the camera doesn't switch back and forth so fast
MainGameScreen.this.mCamera
.setChaseEntity(spriteList[currentCharacter]);
finishTurn = false;
diceButton.setColor(Color.WHITE);
finishTurnButton.setColor(Color.GRAY);
checkCredits(currentCharacter);
}
}
});
for (int i = (numCharacters-1); i>=0 ; i--) {
spriteList[i].setScale(.1f);
scene.attachChild(spriteList[i]);
}
return scene;
}
boolean move = false;
public boolean movement(SpriteCoordinate offset) {
if (movesLeft > 0) {
moving = true;
SpriteCoordinate characterLocation = thePlayers.get(currentCharacter).getSpriteLocation();
SpriteCoordinate newPosition = offset.add(characterLocation);
if (!mainMapEvent.checkBoundaries(newPosition)) {
return false;
}
movesLeft--;
textStroke5.setText(" " + movesLeft);
if (movesLeft == 0) {
swipeDone = false;
turnDone = true;
moving = false;
}
moveSprite(newPosition, spriteList[currentCharacter]);
}
return true;
}
public void moveSprite(final SpriteCoordinate newPosition,
final Sprite mySprite) {
SpriteCoordinate characterLocation = thePlayers.get(currentCharacter).getSpriteLocation();
mySprite.registerEntityModifier(new MoveModifier(0.5f,
characterLocation.getX(), characterLocation.getY(),
newPosition.getX(), newPosition.getY()) {
@Override
protected void onModifierStarted(IEntity pItem) {
super.onModifierStarted(pItem);
}
@Override
protected void onModifierFinished(IEntity pItem) {
thePlayers.get(currentCharacter).setLocation(mySprite.getX(), mySprite.getY());
super.onModifierFinished(pItem);
if (!eventCompleted) {
checkMiniGameHotSpots(currentCharacter);
eventCompleted = true;
}
}
});
}
// Checks the hot spots for the minigames
protected void checkMiniGameHotSpots(int current) {
Event.getEvent(thePlayers.get(current).getSpriteLocation(), this, thePlayers.get(current).getName(), thePlayers.get(current).getGraduated(), current, thePlayers);
if (!(move || gameDone)) {
gameDone = true;
}
swipeDone = false;
turnDone = true;
}
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
return false;
}
public void onClick(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
@Override
public synchronized void onResumeGame() {
if (this.mEngine != null)
super.onResumeGame();
}
// ===========================================================
// Methods
// ===========================================================
public void onActivityResult (int requestCode, int resultCode, Intent data) {
this.eventCompleted = true;
if (!(move || gameDone)) {
gameDone = true;
}
swipeDone = false;
turnDone = true;
if (resultCode != RESULT_OK || data == null) {
return;
}
int result = data.getIntExtra(requestCode+"", 0);
addCredits(currentCharacter, result);
Log.d("MINIGAME", result+", "+resultCode);
checkCredits(currentCharacter);
}
private void addCredits(int character, int creditsToAdd) {
thePlayers.get(character).addCredits(creditsToAdd);
textStrokes[character].setText(thePlayers.get(character).getName()
+ "\nCredits: " + thePlayers.get(character).getCredits()
+ "\nCoins: " + thePlayers.get(character).getCoins());
}
private void checkCredits(final int character) {
if (thePlayers.get(character).getCredits() >= CREDITS_NEEDED_GRADUATE) {
runOnUiThread(new Runnable() {
public void run() {
if (thePlayers.get(character).getGraduated() == false) {
Builder alert = new AlertDialog.Builder(MainGameScreen.this);
alert.setTitle("You have graduated!");
alert.setMessage("Please head to the O'Connoll Center.");
alert.setPositiveButton("OK", null);
alert.show();
}
thePlayers.get(character).setGraduated(true);
/*Toast.makeText(getApplicationContext(), getString(R.string.ready_to_graduate, thePlayers.get(character).getName(), thePlayers.get(character).getCredits()),
Toast.LENGTH_SHORT).show();*/
}
});
}
}
private void addCoins(int character, int coinsToAdd) {
thePlayers.get(character).addCoins(coinsToAdd);
textStrokes[character].setText(thePlayers.get(character).getName()
+ "\nCredits: " + thePlayers.get(character).getCredits()
+ "\nCoins: " + thePlayers.get(character).getCoins());
}
public void saveGame(){
int numPlayers = thePlayers.size();
DbHelper dbhelper = new DbHelper(this);
SQLiteDatabase db = dbhelper.openDB();
Calendar time_date = Calendar.getInstance();
int year = time_date.get(Calendar.YEAR);
int month = time_date.get(Calendar.MONTH)+ 1;
int day = time_date.get(Calendar.DATE);
int hour = time_date.get(Calendar.HOUR_OF_DAY);
int minute = time_date.get(Calendar.MINUTE);
String timeDate = Integer.toString(month) + "/" + Integer.toString(day) + "/" + Integer.toString(year) + " " + Integer.toString(hour) + ":" +Integer.toString(minute);
int gameId = thePlayers.get(0).getGameId();
String[] table1Values = {Integer.toString(gameId), timeDate, Integer.toString(numCharacters), Integer.toString(currentCharacter)};
Log.d("debug,",Integer.toString(gameId) + "0" + Integer.toString(numCharacters) + Integer.toString(currentCharacter));
String[] table1Key = {Integer.toString(gameId)};
dbhelper.updateRow(1, table1Key, table1Values); //Update game table
//insert numPlayers rows into table 3
for (int i = 0; i < numPlayers; i++)
{
String[] characterKey = {Integer.toString((gameId<<2) + i)};
String[] newCharacter = {characterKey[0], thePlayers.get(i).getType(), thePlayers.get(i).getName(), Float.toString(thePlayers.get(i).getMapLocation().getX()), Float.toString(thePlayers.get(i).getMapLocation().getY()), Integer.toString(thePlayers.get(i).getCredits()), Integer.toString(thePlayers.get(i).getCoins()), Integer.toString(i)};
Log.d("debug,", characterKey[0]+ thePlayers.get(i).getType()+thePlayers.get(i).getName()+Float.toString(thePlayers.get(i).getMapLocation().getX())+Float.toString(thePlayers.get(i).getMapLocation().getY())+Integer.toString(thePlayers.get(i).getCredits())+Integer.toString(thePlayers.get(i).getCoins())+Integer.toString(i+1));
dbhelper.updateRow(2, characterKey, newCharacter);
}
dbhelper.close();
}
public void deleteGame(){
int numPlayers = thePlayers.size();
DbHelper dbhelper = new DbHelper(this);
SQLiteDatabase db = dbhelper.openDB();
int gameId = thePlayers.get(0).getGameId();
String[] table1Key = {Integer.toString(gameId)};
dbhelper.deleteRow(1, table1Key); //Delete game table
//delete numPlayers rows from table 3
for (int i = 0; i < numPlayers; i++)
{
String[] characterKey = {Integer.toString((gameId<<2) + i)};
dbhelper.deleteRow(2, characterKey);
}
dbhelper.deleteRow(4, table1Key); //Delete minigame table
dbhelper.close();
}
@Override
public void onPause() {
super.onPause();
if (mMusic.isPlaying()) {
mMusic.pause();
}
}
@Override
public void onResume() {
super.onResume();
if (music) {
mMusic.resume();
}
}
}
| true | true | public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
/*
* User Interface HUD At each corner of the screen, will display
* player's information Include number of credits There will be a button
* to roll dice and turn number will be displayed.
*/
VertexBufferObjectManager vertexBufferObjectManager = this
.getVertexBufferObjectManager();
textStrokes = new Text[numCharacters];
/*
* To update text, use [text].setText("blah blah"); In which "blah blah"
* is whatever you want to change the text to. You can use variables.
*/
for (int i = 0; i < numCharacters; i++) {
SpriteCoordinate coord = textStrokeCoordinates[i];
textStrokes[i] = new Text(coord.getX(), coord.getY(), this.mStrokeFont,
thePlayers.get(i).getName() +"\nCredits: " + thePlayers.get(i).getCredits()
+ "\nCoins: " + thePlayers.get(i).getCoins(), vertexBufferObjectManager);
}
textStroke5 = new Text(180, 20, this.mStrokeFont,
" " + diceRoll, vertexBufferObjectManager);
textStroke5.setScale((float) .7 );
mHUD = new HUD();
mHUD.attachChild(scene);
final Sprite diceButton = new Sprite(180, CAMERA_HEIGHT/10, this.diceTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
//generate random number [1,3]
currentCharacterYear = (thePlayers.get(currentCharacter).getCredits()/3) + 1;
switch(currentCharacterYear) {
case 0: maxRoll = 3;
break;
case 1: maxRoll = 3;
break;
case 2: maxRoll = 4;
break;
case 3: maxRoll = 4;
break;
case 4: maxRoll = 5;
break;
case 5: maxRoll = 6;
break;
default: maxRoll = 3;
break;
}
random = new Random();
diceRoll = random.nextInt(maxRoll) + 1;
if (diceDone == false) {
swipeDone = false;
if (touchEvent.isActionUp()) {
this.setColor(Color.GRAY);
textStroke5.setText(" " + diceRoll);
movesLeft = diceRoll;
eventCompleted = false;
diceDone = true;
move = false;
gameDone = false;
}
if (touchEvent.isActionDown()) {
this.setColor(Color.WHITE);
}
}
return true;
};
};
diceButton.setScale((float) .5);
this.rightArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.rightArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(rightArrowTextureAtlas, this, "right_arrow.png",
0, 0);
this.rightArrowTextureAtlas.load();
final Sprite rightArrowButton = new Sprite(CAMERA_WIDTH-CHARACTER_WIDTH, CAMERA_HEIGHT/2, this.rightArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(CHARACTER_WIDTH,0));
} else {
return false;
}
}
};
rightArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(rightArrowButton);
this.mHUD.attachChild(rightArrowButton);
this.leftArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.leftArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(leftArrowTextureAtlas, this, "left_arrow.png",
0, 0);
this.leftArrowTextureAtlas.load();
final Sprite leftArrowButton = new Sprite(CHARACTER_WIDTH, CAMERA_HEIGHT/2, this.leftArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(-CHARACTER_WIDTH,0));
} else {
return false;
}
}
return true;
}
};
leftArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(leftArrowButton);
this.mHUD.attachChild(leftArrowButton);
this.downArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.downArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(downArrowTextureAtlas, this, "down_arrow.png",
0, 0);
this.downArrowTextureAtlas.load();
final Sprite downArrowButton = new Sprite(CAMERA_WIDTH/2, CHARACTER_WIDTH, this.downArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(0, -CHARACTER_WIDTH));
} else {
return false;
}
}
return true;
}
};
downArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(downArrowButton);
this.mHUD.attachChild(downArrowButton);
this.upArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.upArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(upArrowTextureAtlas, this, "up_arrow.png",
0, 0);
this.upArrowTextureAtlas.load();
final Sprite upArrowButton = new Sprite(CAMERA_WIDTH/2, CAMERA_HEIGHT-CHARACTER_WIDTH, this.upArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(0,CHARACTER_WIDTH));
} else {
return false;
}
}
return true;
}
};
upArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(upArrowButton);
this.mHUD.attachChild(upArrowButton);
final Sprite finishTurnButton = new Sprite(310, CAMERA_HEIGHT/10, this.finishTurnTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (movesLeft == 0) {
if (touchEvent.isActionUp()) {
this.setColor(Color.GRAY);
finishTurn = true;
}
if (touchEvent.isActionDown()) {
this.setColor(Color.GRAY);
}
return true;
} else {
return false;
}
};
};
finishTurnButton.setScale((float) .5);
finishTurnButton.setColor(Color.GRAY);
// Load the Pause Scene
this.mPauseScene = new CameraScene(this.mCamera);
final float cX = (CAMERA_WIDTH - this.mPausedTextureRegion.getWidth())
/ 2 + (this.mPausedTextureRegion.getWidth() / 3);
final float cY = (CAMERA_HEIGHT - this.mPausedTextureRegion.getHeight()) / 5;
// Music Button
// Default - Music on.
mMusic.play();
final Sprite musicButton = new Sprite(CAMERA_WIDTH / 12, cY - (CAMERA_HEIGHT / 13), this.mMusicTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
if (mMusic.isPlaying()) {
mMusic.pause();
music = false;
} else {
mMusic.play();
music = true;
}
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(musicButton);
this.mPauseScene.attachChild(musicButton);
// Resume Button
final Sprite resumeButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 2), this.mResumeTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
mHUD.clearChildScene();
scene.setIgnoreUpdate(false);
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(resumeButton);
this.mPauseScene.attachChild(resumeButton);
// Return to main menu button
final Sprite mainMenuButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 3), this.mMainMenuTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
scene.detachChildren();
scene.clearEntityModifiers();
scene.clearTouchAreas();
scene.clearUpdateHandlers();
mHUD.detachChildren();
mPauseScene.detachChildren();
this.detachSelf();
onClick(mRenderSurfaceView);
finish();
break;
default:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(mainMenuButton);
this.mPauseScene.attachChild(mainMenuButton);
//save game button
final Sprite saveButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 6), this.mSaveTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
//update database here
saveGame();
mHUD.clearChildScene();
scene.setIgnoreUpdate(false);
//save to database
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(saveButton);
this.mPauseScene.attachChild(saveButton);
/* Makes the paused Game look through. */
this.mPauseScene.setBackgroundEnabled(false);
// Main Menu Button on HUD
final Sprite pauseSprite = new Sprite(mCamera.getWidth() / 2 + CHARACTER_WIDTH, 300, this.mFaceTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
scene.setIgnoreUpdate(true);
mHUD.setChildScene(mPauseScene, false, true, true);
break;
default:
break;
}
return true;
};
};
for (int i = 0; i < numCharacters; i++) {
mHUD.attachChild(textStrokes[i]);
}
mHUD.registerTouchArea(diceButton);
mHUD.attachChild(diceButton);
mHUD.registerTouchArea(finishTurnButton);
mHUD.attachChild(finishTurnButton);
mHUD.attachChild(textStroke5);
mHUD.registerTouchArea(pauseSprite);
mHUD.attachChild(pauseSprite);
mCamera.setHUD(mHUD);
/* Main Map Scene */
scene.setOnSceneTouchListener(this);
try {
final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
this.mEngine.getTextureManager(),
TextureOptions.BILINEAR_PREMULTIPLYALPHA,
this.getVertexBufferObjectManager(),
new ITMXTilePropertiesListener() {
@Override
public void onTMXTileWithPropertiesCreated(
final TMXTiledMap pTMXTiledMap,
final TMXLayer pTMXLayer,
final TMXTile pTMXTile,
final TMXProperties<TMXTileProperty> pTMXTileProperties) {
}
});
this.mTMXTiledMap = tmxLoader
.loadFromAsset("tmx/MultiGator14Layers.tmx");
this.mTMXTiledMap.setOffsetCenter(0, 0);
// this.toastOnUiThread("Cactus count in this TMXTiledMap: " +
// MainGameScreen.this.mCactusCount, Toast.LENGTH_LONG);
} catch (final TMXLoadException e) {
Debug.e(e);
}
moving = false;
turnDone = false;
turnNum = 1;
scene.attachChild(this.mTMXTiledMap);
/* Make the camera not exceed the bounds of the TMXEntity. */
this.mCamera.setBoundsEnabled(false);
this.mCamera.setBounds(0, 0, this.mTMXTiledMap.getWidth(),
this.mTMXTiledMap.getHeight());
this.mCamera.setBoundsEnabled(true);
spriteList = new Sprite[numCharacters];
for (int i = 0; i < numCharacters; i++) {
SpriteCoordinate loc = thePlayers.get(i).getSpriteLocation();
spriteList[i] = new Sprite(loc.getX(), loc.getY(), character[i],
this.getVertexBufferObjectManager());
}
//Open Database
dbhelper = new DbHelper(this);
SQLiteDatabase db = dbhelper.openDB();
Log.d("TEST", "Database has been opened");
Log.d("TEST2", Integer.toString(thePlayers.get(0).gameId));
String[] gameKey = { Integer.toString(thePlayers.get(0).gameId) };
//Grab Game info
ArrayList gameList = dbhelper.getRow(1, gameKey);
if (gameList.size()>0){
currentCharacter = Integer.valueOf((String)gameList.get(3));
}
dbhelper.close();
this.mCamera.setChaseEntity(spriteList[currentCharacter]);
/* The layer for the player to walk on. */
final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
scene.registerUpdateHandler(new IUpdateHandler() {
@Override
public void reset() {
}
@Override
public void onUpdate(final float pSecondsElapsed) {
// /* Get the scene-coordinates of the players feet. */
float[] localCoord = new float[2];
localCoord[0] = spriteList[currentCharacter].getWidth() * .5f;
localCoord[1] = spriteList[currentCharacter].getHeight() * .5f;
final float[] playerFootCordinates = spriteList[currentCharacter]
.convertLocalCoordinatesToSceneCoordinates(localCoord);
/* Get the tile the feet of the player are currently waking on. */
final TMXTile tmxTile = tmxLayer.getTMXTileAt(
playerFootCordinates[Constants.VERTEX_INDEX_X],
playerFootCordinates[Constants.VERTEX_INDEX_Y]);
if (movesLeft == 0 && diceDone) {
MainGameScreen.this.mCamera.updateChaseEntity();
finishTurnButton.setColor(Color.WHITE);
}
if (turnDone && finishTurn) { //&& swipeDone == false
moving = false;
move = false;
turnDone = false;
diceDone = false;
currentCharacter = (currentCharacter + 1) % (numCharacters);
saveGame();
// consider a delay here so the camera doesn't switch back and forth so fast
MainGameScreen.this.mCamera
.setChaseEntity(spriteList[currentCharacter]);
finishTurn = false;
diceButton.setColor(Color.WHITE);
finishTurnButton.setColor(Color.GRAY);
checkCredits(currentCharacter);
}
}
});
for (int i = (numCharacters-1); i>=0 ; i--) {
spriteList[i].setScale(.1f);
scene.attachChild(spriteList[i]);
}
return scene;
}
| public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
/*
* User Interface HUD At each corner of the screen, will display
* player's information Include number of credits There will be a button
* to roll dice and turn number will be displayed.
*/
VertexBufferObjectManager vertexBufferObjectManager = this
.getVertexBufferObjectManager();
textStrokes = new Text[numCharacters];
/*
* To update text, use [text].setText("blah blah"); In which "blah blah"
* is whatever you want to change the text to. You can use variables.
*/
for (int i = 0; i < numCharacters; i++) {
SpriteCoordinate coord = textStrokeCoordinates[i];
textStrokes[i] = new Text(coord.getX(), coord.getY(), this.mStrokeFont,
thePlayers.get(i).getName() +"\nCredits: " + thePlayers.get(i).getCredits()
+ "\nCoins: " + thePlayers.get(i).getCoins(), vertexBufferObjectManager);
}
textStroke5 = new Text(180, 20, this.mStrokeFont,
" " + diceRoll, vertexBufferObjectManager);
textStroke5.setScale((float) .7 );
mHUD = new HUD();
mHUD.attachChild(scene);
final Sprite diceButton = new Sprite(180, CAMERA_HEIGHT/10, this.diceTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
//generate random number [1,3]
currentCharacterYear = (thePlayers.get(currentCharacter).getCredits()/3) + 1;
switch(currentCharacterYear) {
case 0: maxRoll = 3;
break;
case 1: maxRoll = 3;
break;
case 2: maxRoll = 4;
break;
case 3: maxRoll = 4;
break;
case 4: maxRoll = 5;
break;
case 5: maxRoll = 6;
break;
default: maxRoll = 3;
break;
}
random = new Random();
diceRoll = random.nextInt(maxRoll) + 1;
if (diceDone == false) {
swipeDone = false;
if (touchEvent.isActionUp()) {
this.setColor(Color.GRAY);
textStroke5.setText(" " + diceRoll);
movesLeft = diceRoll;
eventCompleted = false;
diceDone = true;
move = false;
gameDone = false;
}
if (touchEvent.isActionDown()) {
this.setColor(Color.WHITE);
}
}
return true;
};
};
diceButton.setScale((float) .5);
this.rightArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.rightArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(rightArrowTextureAtlas, this, "right_arrow.png",
0, 0);
this.rightArrowTextureAtlas.load();
final Sprite rightArrowButton = new Sprite(CAMERA_WIDTH-CHARACTER_WIDTH, CAMERA_HEIGHT/2, this.rightArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(CHARACTER_WIDTH,0));
} else {
return false;
}
}
};
rightArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(rightArrowButton);
this.mHUD.attachChild(rightArrowButton);
this.leftArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.leftArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(leftArrowTextureAtlas, this, "left_arrow.png",
0, 0);
this.leftArrowTextureAtlas.load();
final Sprite leftArrowButton = new Sprite(CHARACTER_WIDTH, CAMERA_HEIGHT/2, this.leftArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(-CHARACTER_WIDTH,0));
} else {
return false;
}
}
return true;
}
};
leftArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(leftArrowButton);
this.mHUD.attachChild(leftArrowButton);
this.downArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.downArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(downArrowTextureAtlas, this, "down_arrow.png",
0, 0);
this.downArrowTextureAtlas.load();
final Sprite downArrowButton = new Sprite(CAMERA_WIDTH/2, CHARACTER_WIDTH, this.downArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(0, -CHARACTER_WIDTH));
} else {
return false;
}
}
return true;
}
};
downArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(downArrowButton);
this.mHUD.attachChild(downArrowButton);
this.upArrowTextureAtlas = new BitmapTextureAtlas(
this.getTextureManager(), 120, 120, TextureOptions.BILINEAR);
this.upArrowRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(upArrowTextureAtlas, this, "up_arrow.png",
0, 0);
this.upArrowTextureAtlas.load();
final Sprite upArrowButton = new Sprite(CAMERA_WIDTH/2, CAMERA_HEIGHT-CHARACTER_WIDTH, this.upArrowRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (touchEvent.isActionDown()) {
if (touchEvent.isActionDown()) {
return movement(new SpriteCoordinate(0,CHARACTER_WIDTH));
} else {
return false;
}
}
return true;
}
};
upArrowButton.setScale(.5f);
this.mHUD.registerTouchArea(upArrowButton);
this.mHUD.attachChild(upArrowButton);
final Sprite finishTurnButton = new Sprite(310, CAMERA_HEIGHT/10, this.finishTurnTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
if (movesLeft == 0) {
if (touchEvent.isActionUp()) {
this.setColor(Color.GRAY);
finishTurn = true;
}
if (touchEvent.isActionDown()) {
this.setColor(Color.GRAY);
}
return true;
} else {
return false;
}
};
};
finishTurnButton.setScale((float) .5);
finishTurnButton.setColor(Color.GRAY);
// Load the Pause Scene
this.mPauseScene = new CameraScene(this.mCamera);
final float cX = (CAMERA_WIDTH - this.mPausedTextureRegion.getWidth())
/ 2 + (this.mPausedTextureRegion.getWidth() / 3);
final float cY = (CAMERA_HEIGHT - this.mPausedTextureRegion.getHeight()) / 5;
// Music Button
// Default - Music on.
mMusic.play();
final Sprite musicButton = new Sprite(CAMERA_WIDTH / 12, cY - (CAMERA_HEIGHT / 13), this.mMusicTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
if (mMusic.isPlaying()) {
mMusic.pause();
music = false;
} else {
mMusic.play();
music = true;
}
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(musicButton);
this.mPauseScene.attachChild(musicButton);
// Resume Button
final Sprite resumeButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 2), this.mResumeTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
mHUD.clearChildScene();
scene.setIgnoreUpdate(false);
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(resumeButton);
this.mPauseScene.attachChild(resumeButton);
// Return to main menu button
final Sprite mainMenuButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 3), this.mMainMenuTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
scene.detachChildren();
scene.clearEntityModifiers();
scene.clearTouchAreas();
scene.clearUpdateHandlers();
mHUD.detachChildren();
mPauseScene.detachChildren();
this.detachSelf();
onClick(mRenderSurfaceView);
finish();
break;
default:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(mainMenuButton);
this.mPauseScene.attachChild(mainMenuButton);
//save game button
final Sprite saveButton = new Sprite(cX + (CAMERA_WIDTH / 10), cY
+ (CAMERA_HEIGHT / 6), this.mSaveTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
//update database here
saveGame();
mHUD.clearChildScene();
scene.setIgnoreUpdate(false);
//save to database
break;
case TouchEvent.ACTION_MOVE:
break;
case TouchEvent.ACTION_UP:
break;
}
return true;
};
};
this.mPauseScene.registerTouchArea(saveButton);
this.mPauseScene.attachChild(saveButton);
/* Makes the paused Game look through. */
this.mPauseScene.setBackgroundEnabled(false);
// Main Menu Button on HUD
final Sprite pauseSprite = new Sprite(mCamera.getWidth() / 2 + CHARACTER_WIDTH + 50 , 300, this.mFaceTextureRegion,
this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(TouchEvent touchEvent, float X, float Y) {
switch (touchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
scene.setIgnoreUpdate(true);
mHUD.setChildScene(mPauseScene, false, true, true);
break;
default:
break;
}
return true;
};
};
for (int i = 0; i < numCharacters; i++) {
mHUD.attachChild(textStrokes[i]);
}
mHUD.registerTouchArea(diceButton);
mHUD.attachChild(diceButton);
mHUD.registerTouchArea(finishTurnButton);
mHUD.attachChild(finishTurnButton);
mHUD.attachChild(textStroke5);
mHUD.registerTouchArea(pauseSprite);
mHUD.attachChild(pauseSprite);
mCamera.setHUD(mHUD);
/* Main Map Scene */
scene.setOnSceneTouchListener(this);
try {
final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
this.mEngine.getTextureManager(),
TextureOptions.BILINEAR_PREMULTIPLYALPHA,
this.getVertexBufferObjectManager(),
new ITMXTilePropertiesListener() {
@Override
public void onTMXTileWithPropertiesCreated(
final TMXTiledMap pTMXTiledMap,
final TMXLayer pTMXLayer,
final TMXTile pTMXTile,
final TMXProperties<TMXTileProperty> pTMXTileProperties) {
}
});
this.mTMXTiledMap = tmxLoader
.loadFromAsset("tmx/MultiGator14Layers.tmx");
this.mTMXTiledMap.setOffsetCenter(0, 0);
// this.toastOnUiThread("Cactus count in this TMXTiledMap: " +
// MainGameScreen.this.mCactusCount, Toast.LENGTH_LONG);
} catch (final TMXLoadException e) {
Debug.e(e);
}
moving = false;
turnDone = false;
turnNum = 1;
scene.attachChild(this.mTMXTiledMap);
/* Make the camera not exceed the bounds of the TMXEntity. */
this.mCamera.setBoundsEnabled(false);
this.mCamera.setBounds(0, 0, this.mTMXTiledMap.getWidth(),
this.mTMXTiledMap.getHeight());
this.mCamera.setBoundsEnabled(true);
spriteList = new Sprite[numCharacters];
for (int i = 0; i < numCharacters; i++) {
SpriteCoordinate loc = thePlayers.get(i).getSpriteLocation();
spriteList[i] = new Sprite(loc.getX(), loc.getY(), character[i],
this.getVertexBufferObjectManager());
}
//Open Database
dbhelper = new DbHelper(this);
SQLiteDatabase db = dbhelper.openDB();
Log.d("TEST", "Database has been opened");
Log.d("TEST2", Integer.toString(thePlayers.get(0).gameId));
String[] gameKey = { Integer.toString(thePlayers.get(0).gameId) };
//Grab Game info
ArrayList gameList = dbhelper.getRow(1, gameKey);
if (gameList.size()>0){
currentCharacter = Integer.valueOf((String)gameList.get(3));
}
dbhelper.close();
this.mCamera.setChaseEntity(spriteList[currentCharacter]);
/* The layer for the player to walk on. */
final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
scene.registerUpdateHandler(new IUpdateHandler() {
@Override
public void reset() {
}
@Override
public void onUpdate(final float pSecondsElapsed) {
// /* Get the scene-coordinates of the players feet. */
float[] localCoord = new float[2];
localCoord[0] = spriteList[currentCharacter].getWidth() * .5f;
localCoord[1] = spriteList[currentCharacter].getHeight() * .5f;
final float[] playerFootCordinates = spriteList[currentCharacter]
.convertLocalCoordinatesToSceneCoordinates(localCoord);
/* Get the tile the feet of the player are currently waking on. */
final TMXTile tmxTile = tmxLayer.getTMXTileAt(
playerFootCordinates[Constants.VERTEX_INDEX_X],
playerFootCordinates[Constants.VERTEX_INDEX_Y]);
if (movesLeft == 0 && diceDone) {
MainGameScreen.this.mCamera.updateChaseEntity();
finishTurnButton.setColor(Color.WHITE);
}
if (turnDone && finishTurn) { //&& swipeDone == false
moving = false;
move = false;
turnDone = false;
diceDone = false;
currentCharacter = (currentCharacter + 1) % (numCharacters);
saveGame();
// consider a delay here so the camera doesn't switch back and forth so fast
MainGameScreen.this.mCamera
.setChaseEntity(spriteList[currentCharacter]);
finishTurn = false;
diceButton.setColor(Color.WHITE);
finishTurnButton.setColor(Color.GRAY);
checkCredits(currentCharacter);
}
}
});
for (int i = (numCharacters-1); i>=0 ; i--) {
spriteList[i].setScale(.1f);
scene.attachChild(spriteList[i]);
}
return scene;
}
|
diff --git a/online-local/src/net/myrrix/online/generation/InputFilesReader.java b/online-local/src/net/myrrix/online/generation/InputFilesReader.java
index 06479ce..836364f 100644
--- a/online-local/src/net/myrrix/online/generation/InputFilesReader.java
+++ b/online-local/src/net/myrrix/online/generation/InputFilesReader.java
@@ -1,165 +1,166 @@
/*
* Copyright Myrrix 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 net.myrrix.online.generation;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.google.common.base.Splitter;
import com.google.common.io.PatternFilenameFilter;
import org.apache.commons.math3.util.FastMath;
import org.apache.mahout.common.iterator.FileLineIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.myrrix.common.LangUtils;
import net.myrrix.common.collection.FastByIDFloatMap;
import net.myrrix.common.collection.FastByIDMap;
import net.myrrix.common.collection.FastIDSet;
import net.myrrix.common.io.InvertedFilenameFilter;
import net.myrrix.common.math.MatrixUtils;
/**
* @author Sean Owen
*/
final class InputFilesReader {
private static final Logger log = LoggerFactory.getLogger(InputFilesReader.class);
private static final Splitter COMMA = Splitter.on(',');
/**
* Values with absolute value less than this in the input are considered 0.
* Values are generally assumed to be > 1, actually,
* and usually not negative, though they need not be.
*/
private static final float ZERO_THRESHOLD =
Float.parseFloat(System.getProperty("model.decay.zeroThreshold", "0.0001"));
private InputFilesReader() {
}
static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs,
FastByIDMap<FastByIDFloatMap> rbyRow,
FastByIDMap<FastByIDFloatMap> rbyColumn,
File inputDir) throws IOException {
FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?");
File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter));
if (otherFiles != null) {
for (File otherFile : otherFiles) {
log.info("Skipping file {}", otherFile.getName());
}
}
File[] inputFiles = inputDir.listFiles(csvFilter);
if (inputFiles == null) {
log.info("No input files in {}", inputDir);
return;
}
Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE);
int lines = 0;
int badLines = 0;
for (File inputFile : inputFiles) {
log.info("Reading {}", inputFile);
for (CharSequence line : new FileLineIterable(inputFile)) {
+ lines++;
Iterator<String> it = COMMA.split(line).iterator();
long userID;
long itemID;
float value;
try {
userID = Long.parseLong(it.next());
itemID = Long.parseLong(it.next());
if (it.hasNext()) {
String valueToken = it.next().trim();
value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken);
} else {
value = 1.0f;
}
} catch (NoSuchElementException nsee) {
log.warn("Ignoring line with too few columns: '{}'", line);
if (++badLines > 100) { // Crude check
throw new IOException("Too many bad lines; aborting");
}
continue;
} catch (IllegalArgumentException iae) { // includes NumberFormatException
- if (lines == 0) {
+ if (lines == 1) {
log.info("Ignoring header line");
} else {
log.warn("Ignoring unparseable line: '{}'", line);
if (++badLines > 100) { // Crude check
throw new IOException("Too many bad lines; aborting");
}
}
continue;
}
if (Float.isNaN(value)) {
// Remove, not set
MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn);
} else {
MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn);
}
if (knownItemIDs != null) {
FastIDSet itemIDs = knownItemIDs.get(userID);
if (Float.isNaN(value)) {
// Remove, not set
if (itemIDs != null) {
itemIDs.remove(itemID);
if (itemIDs.isEmpty()) {
knownItemIDs.remove(userID);
}
}
} else {
if (itemIDs == null) {
itemIDs = new FastIDSet();
knownItemIDs.put(userID, itemIDs);
}
itemIDs.add(itemID);
}
}
- if (++lines % 1000000 == 0) {
+ if (lines % 1000000 == 0) {
log.info("Finished {} lines", lines);
}
}
}
removeSmall(rbyRow);
removeSmall(rbyColumn);
}
private static void removeSmall(FastByIDMap<FastByIDFloatMap> matrix) {
for (FastByIDMap.MapEntry<FastByIDFloatMap> entry : matrix.entrySet()) {
for (Iterator<FastByIDFloatMap.MapEntry> it = entry.getValue().entrySet().iterator(); it.hasNext();) {
FastByIDFloatMap.MapEntry entry2 = it.next();
if (FastMath.abs(entry2.getValue()) < ZERO_THRESHOLD) {
it.remove();
}
}
}
}
}
| false | true | static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs,
FastByIDMap<FastByIDFloatMap> rbyRow,
FastByIDMap<FastByIDFloatMap> rbyColumn,
File inputDir) throws IOException {
FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?");
File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter));
if (otherFiles != null) {
for (File otherFile : otherFiles) {
log.info("Skipping file {}", otherFile.getName());
}
}
File[] inputFiles = inputDir.listFiles(csvFilter);
if (inputFiles == null) {
log.info("No input files in {}", inputDir);
return;
}
Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE);
int lines = 0;
int badLines = 0;
for (File inputFile : inputFiles) {
log.info("Reading {}", inputFile);
for (CharSequence line : new FileLineIterable(inputFile)) {
Iterator<String> it = COMMA.split(line).iterator();
long userID;
long itemID;
float value;
try {
userID = Long.parseLong(it.next());
itemID = Long.parseLong(it.next());
if (it.hasNext()) {
String valueToken = it.next().trim();
value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken);
} else {
value = 1.0f;
}
} catch (NoSuchElementException nsee) {
log.warn("Ignoring line with too few columns: '{}'", line);
if (++badLines > 100) { // Crude check
throw new IOException("Too many bad lines; aborting");
}
continue;
} catch (IllegalArgumentException iae) { // includes NumberFormatException
if (lines == 0) {
log.info("Ignoring header line");
} else {
log.warn("Ignoring unparseable line: '{}'", line);
if (++badLines > 100) { // Crude check
throw new IOException("Too many bad lines; aborting");
}
}
continue;
}
if (Float.isNaN(value)) {
// Remove, not set
MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn);
} else {
MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn);
}
if (knownItemIDs != null) {
FastIDSet itemIDs = knownItemIDs.get(userID);
if (Float.isNaN(value)) {
// Remove, not set
if (itemIDs != null) {
itemIDs.remove(itemID);
if (itemIDs.isEmpty()) {
knownItemIDs.remove(userID);
}
}
} else {
if (itemIDs == null) {
itemIDs = new FastIDSet();
knownItemIDs.put(userID, itemIDs);
}
itemIDs.add(itemID);
}
}
if (++lines % 1000000 == 0) {
log.info("Finished {} lines", lines);
}
}
}
removeSmall(rbyRow);
removeSmall(rbyColumn);
}
| static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs,
FastByIDMap<FastByIDFloatMap> rbyRow,
FastByIDMap<FastByIDFloatMap> rbyColumn,
File inputDir) throws IOException {
FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?");
File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter));
if (otherFiles != null) {
for (File otherFile : otherFiles) {
log.info("Skipping file {}", otherFile.getName());
}
}
File[] inputFiles = inputDir.listFiles(csvFilter);
if (inputFiles == null) {
log.info("No input files in {}", inputDir);
return;
}
Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE);
int lines = 0;
int badLines = 0;
for (File inputFile : inputFiles) {
log.info("Reading {}", inputFile);
for (CharSequence line : new FileLineIterable(inputFile)) {
lines++;
Iterator<String> it = COMMA.split(line).iterator();
long userID;
long itemID;
float value;
try {
userID = Long.parseLong(it.next());
itemID = Long.parseLong(it.next());
if (it.hasNext()) {
String valueToken = it.next().trim();
value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken);
} else {
value = 1.0f;
}
} catch (NoSuchElementException nsee) {
log.warn("Ignoring line with too few columns: '{}'", line);
if (++badLines > 100) { // Crude check
throw new IOException("Too many bad lines; aborting");
}
continue;
} catch (IllegalArgumentException iae) { // includes NumberFormatException
if (lines == 1) {
log.info("Ignoring header line");
} else {
log.warn("Ignoring unparseable line: '{}'", line);
if (++badLines > 100) { // Crude check
throw new IOException("Too many bad lines; aborting");
}
}
continue;
}
if (Float.isNaN(value)) {
// Remove, not set
MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn);
} else {
MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn);
}
if (knownItemIDs != null) {
FastIDSet itemIDs = knownItemIDs.get(userID);
if (Float.isNaN(value)) {
// Remove, not set
if (itemIDs != null) {
itemIDs.remove(itemID);
if (itemIDs.isEmpty()) {
knownItemIDs.remove(userID);
}
}
} else {
if (itemIDs == null) {
itemIDs = new FastIDSet();
knownItemIDs.put(userID, itemIDs);
}
itemIDs.add(itemID);
}
}
if (lines % 1000000 == 0) {
log.info("Finished {} lines", lines);
}
}
}
removeSmall(rbyRow);
removeSmall(rbyColumn);
}
|
diff --git a/src/loci/visbio/ome/ImageUploader.java b/src/loci/visbio/ome/ImageUploader.java
index 486448a..0d6ee13 100644
--- a/src/loci/visbio/ome/ImageUploader.java
+++ b/src/loci/visbio/ome/ImageUploader.java
@@ -1,139 +1,139 @@
//
// ImageUploader.java
//
/*
VisBio application for visualization of multidimensional biological
image data. Copyright (C) 2002-@year@ Curtis Rueden and Abraham Sorber.
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 loci.visbio.ome;
import java.util.Vector;
import loci.common.services.ServiceFactory;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.gui.BufferedImageWriter;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.services.OMEXMLService;
import loci.ome.io.OMEWriter;
import loci.visbio.StatusEvent;
import loci.visbio.StatusListener;
/**
* ImageUploader is a helper class for uploading VisBio datasets
* (OME images) to the Open Microscopy Environment.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/visbio/src/loci/visbio/ome/ImageUploader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/visbio/src/loci/visbio/ome/ImageUploader.java">SVN</a></dd></dl>
*/
public class ImageUploader {
// -- Fields --
/** List of objects listening for updates to upload tasks. */
protected Vector listeners;
// -- Constructor --
/** Constructs a new OME image uploader. */
public ImageUploader() { listeners = new Vector(); }
// -- ImageUploader API methods --
/**
* Uploads the given VisBio dataset (OME image) to the specified
* OME server, using the given username and password.
*/
public void upload(loci.visbio.data.Dataset data,
String server, String username, String password)
{
try {
OMEWriter writer = new OMEWriter();
BufferedImageWriter biWriter = new BufferedImageWriter(writer);
ServiceFactory factory = new ServiceFactory();
OMEXMLService service =
(OMEXMLService) factory.getInstance(OMEXMLService.class);
MetadataStore store = service.createOMEXMLMetadata();
store.setRoot(data.getOMEXMLRoot());
MetadataRetrieve retrieve = (MetadataRetrieve) store;
writer.setMetadataRetrieve(retrieve);
String id = server + "?user=" + username + "&password=" + password;
writer.setId(id);
- String order = retrieve.getPixelsDimensionOrder(0, 0);
- int sizeZ = retrieve.getPixelsSizeZ(0, 0).intValue();
- int sizeC = retrieve.getPixelsSizeZ(0, 0).intValue();
- int sizeT = retrieve.getPixelsSizeZ(0, 0).intValue();
+ String order = retrieve.getPixelsDimensionOrder(0).toString();
+ int sizeZ = ((Integer) retrieve.getPixelsSizeZ(0).getValue()).intValue();
+ int sizeC = ((Integer) retrieve.getPixelsSizeC(0).getValue()).intValue();
+ int sizeT = ((Integer) retrieve.getPixelsSizeT(0).getValue()).intValue();
int[] len = data.getLengths();
int total = FormatTools.getRasterLength(len);
int[] cLen = new int[len.length - 2];
System.arraycopy(len, 2, cLen, 0, cLen.length);
for (int i=0; i<total; i++) {
int[] zct = FormatTools.getZCTCoords(order,
sizeZ, sizeC, sizeT, total, i);
int[] cPos = FormatTools.rasterToPosition(cLen, zct[1]);
int[] pos = new int[2 + cPos.length];
pos[0] = zct[2];
pos[1] = zct[0];
System.arraycopy(cPos, 0, pos, 2, cPos.length);
biWriter.saveImage(data.getImage(pos), i == total - 1);
}
writer.close();
}
catch (Exception exc) {
notifyListeners(new StatusEvent(1, 1,
"Error uploading (see error console for details)"));
exc.printStackTrace();
}
}
/** Adds an upload task listener. */
public void addStatusListener(StatusListener l) {
synchronized (listeners) { listeners.addElement(l); }
}
/** Removes an upload task listener. */
public void removeStatusListener(StatusListener l) {
synchronized (listeners) { listeners.removeElement(l); }
}
/** Removes all upload task listeners. */
public void removeAllStatusListeners() {
synchronized (listeners) { listeners.removeAllElements(); }
}
/** Notifies listeners of an upload task update. */
protected void notifyListeners(StatusEvent e) {
synchronized (listeners) {
for (int i=0; i<listeners.size(); i++) {
StatusListener l = (StatusListener) listeners.elementAt(i);
l.statusUpdated(e);
}
}
}
}
| true | true | public void upload(loci.visbio.data.Dataset data,
String server, String username, String password)
{
try {
OMEWriter writer = new OMEWriter();
BufferedImageWriter biWriter = new BufferedImageWriter(writer);
ServiceFactory factory = new ServiceFactory();
OMEXMLService service =
(OMEXMLService) factory.getInstance(OMEXMLService.class);
MetadataStore store = service.createOMEXMLMetadata();
store.setRoot(data.getOMEXMLRoot());
MetadataRetrieve retrieve = (MetadataRetrieve) store;
writer.setMetadataRetrieve(retrieve);
String id = server + "?user=" + username + "&password=" + password;
writer.setId(id);
String order = retrieve.getPixelsDimensionOrder(0, 0);
int sizeZ = retrieve.getPixelsSizeZ(0, 0).intValue();
int sizeC = retrieve.getPixelsSizeZ(0, 0).intValue();
int sizeT = retrieve.getPixelsSizeZ(0, 0).intValue();
int[] len = data.getLengths();
int total = FormatTools.getRasterLength(len);
int[] cLen = new int[len.length - 2];
System.arraycopy(len, 2, cLen, 0, cLen.length);
for (int i=0; i<total; i++) {
int[] zct = FormatTools.getZCTCoords(order,
sizeZ, sizeC, sizeT, total, i);
int[] cPos = FormatTools.rasterToPosition(cLen, zct[1]);
int[] pos = new int[2 + cPos.length];
pos[0] = zct[2];
pos[1] = zct[0];
System.arraycopy(cPos, 0, pos, 2, cPos.length);
biWriter.saveImage(data.getImage(pos), i == total - 1);
}
writer.close();
}
catch (Exception exc) {
notifyListeners(new StatusEvent(1, 1,
"Error uploading (see error console for details)"));
exc.printStackTrace();
}
}
| public void upload(loci.visbio.data.Dataset data,
String server, String username, String password)
{
try {
OMEWriter writer = new OMEWriter();
BufferedImageWriter biWriter = new BufferedImageWriter(writer);
ServiceFactory factory = new ServiceFactory();
OMEXMLService service =
(OMEXMLService) factory.getInstance(OMEXMLService.class);
MetadataStore store = service.createOMEXMLMetadata();
store.setRoot(data.getOMEXMLRoot());
MetadataRetrieve retrieve = (MetadataRetrieve) store;
writer.setMetadataRetrieve(retrieve);
String id = server + "?user=" + username + "&password=" + password;
writer.setId(id);
String order = retrieve.getPixelsDimensionOrder(0).toString();
int sizeZ = ((Integer) retrieve.getPixelsSizeZ(0).getValue()).intValue();
int sizeC = ((Integer) retrieve.getPixelsSizeC(0).getValue()).intValue();
int sizeT = ((Integer) retrieve.getPixelsSizeT(0).getValue()).intValue();
int[] len = data.getLengths();
int total = FormatTools.getRasterLength(len);
int[] cLen = new int[len.length - 2];
System.arraycopy(len, 2, cLen, 0, cLen.length);
for (int i=0; i<total; i++) {
int[] zct = FormatTools.getZCTCoords(order,
sizeZ, sizeC, sizeT, total, i);
int[] cPos = FormatTools.rasterToPosition(cLen, zct[1]);
int[] pos = new int[2 + cPos.length];
pos[0] = zct[2];
pos[1] = zct[0];
System.arraycopy(cPos, 0, pos, 2, cPos.length);
biWriter.saveImage(data.getImage(pos), i == total - 1);
}
writer.close();
}
catch (Exception exc) {
notifyListeners(new StatusEvent(1, 1,
"Error uploading (see error console for details)"));
exc.printStackTrace();
}
}
|
diff --git a/src/main/java/thredds/server/sos/service/MetadataParser.java b/src/main/java/thredds/server/sos/service/MetadataParser.java
index d6c6331..c2b80e9 100644
--- a/src/main/java/thredds/server/sos/service/MetadataParser.java
+++ b/src/main/java/thredds/server/sos/service/MetadataParser.java
@@ -1,244 +1,245 @@
/*
*
*/
package thredds.server.sos.service;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import thredds.server.sos.bean.Extent;
import thredds.server.sos.util.ThreddsExtentUtil;
import ucar.nc2.dataset.NetcdfDataset;
import java.io.Writer;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import thredds.server.sos.getObs.MockGetObservationParser;
import thredds.server.sos.getCaps.MockGetCapabilitiesParser;
import thredds.server.sos.util.XMLDomUtils;
/**
* MetadataParser based on EnhancedMetadataService
* @author: Andrew Bird
* Date: 2011
*/
public class MetadataParser {
private static final Logger _log = Logger.getLogger(MetadataParser.class);
private static String xmlString;
private static MockGetCapabilitiesParser MockGetCapP;
private static String service;
private static String version;
private static String request;
private static String observedProperty;
private static MockGetObservationParser MockGetObsP;
private static String offering;
private static String singleEventTime;
//true if multiple props are used
private static boolean isMultiObsProperties;
//used for the cases where multiple props are selected
private static String[] observedProperties;
//true is multiple times are used
private static boolean isMultiTime;
//used for the cases where muliple event times are selected
private static String[] EventTime;
/**
* Enhance NCML with Data Discovery conventions elements if not already in place in the metadata.
*
* @param dataset NetcdfDataset to enhance the NCML
* @param writer writer to send enhanced NCML to
*/
public static void enhance(final NetcdfDataset dataset, final Writer writer, final String query) {
MockGetCapP = null;
xmlString = null;
EventTime =null;
isMultiTime = false;
isMultiObsProperties = false;
//get the extent of the Netcdf file Lat/lon/time
Extent ext = null;
try {
//get basic information
ext = ThreddsExtentUtil.getExtent(dataset);
DatasetMetaData dst = new DatasetMetaData(ext, dataset);
dst.extractData();
if (query != null) {
//if query is not empty
//set the query params then call on the fly
splitQuery(query);
//if all the fields are valid ie not null
if ((service != null) && (request != null) && (version != null)) {
//get caps
if (request.equalsIgnoreCase("GetCapabilities")) {
createGetCapsResults(dst, writer);
} else if (request.equalsIgnoreCase("DescribeSensor")) {
+ writeErrorXMLCode(writer);
} else if (request.equalsIgnoreCase("GetObservation")) {
if (EventTime !=null){
dst.setSearchTimes(EventTime,isMultiTime);
}
dst.setRequestedStationName(MetadataParser.offering);
dst.setDatasetArrayValues(observedProperties);
createGetObsResults(dst, writer);
} else {
writeErrorXMLCode(writer);
}
} //else if the above is not true print invalid xml text
else {
writeErrorXMLCode(writer);
}
} else if (query == null) {
//if the entry is null just print out the get caps xml
_log.info("Null query string/params: using get caps");
createGetCapsResults(dst, writer);
}
//finally close the dataset
dst.closeDataSet();
//catch
} catch (Exception e) {
_log.error(e);
}
}
private static void writeErrorXMLCode(final Writer writer) throws IOException, TransformerException {
Document doc = XMLDomUtils.getExceptionDom();
createStringFromDom(doc, writer);
}
private static void createGetCapsResults(DatasetMetaData dst, final Writer writer) throws IOException, TransformerException {
MockGetCapP = new MockGetCapabilitiesParser(dst);
MockGetCapP.parseTemplateXML();
MockGetCapP.parseServiceIdentification();
MockGetCapP.parseServiceDescription();
MockGetCapP.parseOperationsMetaData();
MockGetCapP.parseObservationList();
//create string output
createStringFromDom(MockGetCapP.getDom(), writer);
}
public static void createStringFromDom(Document dom, final Writer writer) throws TransformerException, IOException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(dom);
transformer.transform(source, result);
xmlString = result.getWriter().toString();
writer.append(xmlString);
}
public static String getxmlString() {
return xmlString;
}
public static MockGetCapabilitiesParser getGetCapsParser() {
return MockGetCapP;
}
public static void splitQuery(String query) {
String[] splitQuery = query.split("&");
service = null;
version = null;
request = null;
observedProperty = null;
if (splitQuery.length > 2) {
for (int i = 0; i < splitQuery.length; i++) {
String parsedString = splitQuery[i];
String[] splitServiceStr = parsedString.split("=");
if (splitServiceStr[0].equalsIgnoreCase("service")) {
MetadataParser.service = splitServiceStr[1];
} else if (splitServiceStr[0].equalsIgnoreCase("version")) {
MetadataParser.version = splitServiceStr[1];
} else if (splitServiceStr[0].equalsIgnoreCase("request")) {
MetadataParser.request = splitServiceStr[1];
} else if (splitServiceStr[0].equalsIgnoreCase("observedProperty")) {
MetadataParser.observedProperty = splitServiceStr[1];
if (observedProperty.contains(",")) {
isMultiObsProperties = true;
MetadataParser.observedProperties = observedProperty.split(",");
} else {
MetadataParser.observedProperties = new String[]{MetadataParser.observedProperty};
}
} else if (splitServiceStr[0].equalsIgnoreCase("offering")) {
//replace all the eccaped : with real ones
String temp = splitServiceStr[1];
MetadataParser.offering = temp.replaceAll("%3A", ":");
} else if (splitServiceStr[0].equalsIgnoreCase("eventtime")) {
MetadataParser.singleEventTime = splitServiceStr[1];
if (singleEventTime.contains("/")) {
isMultiTime = true;
MetadataParser.EventTime = singleEventTime.split("/");
} else {
isMultiTime = false;
MetadataParser.EventTime = new String[]{MetadataParser.singleEventTime};
}
}
}
}
}
public static String getService() {
return service;
}
public static String getVersion() {
return version;
}
public static String getRequest() {
return request;
}
@Deprecated
public static String getObservedProperty() {
return observedProperty;
}
public static String[] getEventTime() {
return EventTime;
}
public static String getOffering() {
return offering;
}
public static String[] getObservedProperties() {
return observedProperties;
}
@Deprecated
public static boolean isMultiEventTime() {
return isMultiTime;
}
private static void createGetObsResults(DatasetMetaData dst, Writer writer) throws IOException, TransformerException {
MockGetObsP = new MockGetObservationParser(dst);
//check the obs property
boolean check = MockGetObsP.parseObsListForRequestedProperty(observedProperties);
if (check == true) {
MockGetObsP.parseTemplateXML();
MockGetObsP.parseObservations(observedProperties);
//create string output
createStringFromDom(MockGetObsP.getDom(), writer);
} else {
writeErrorXMLCode(writer);
}
}
}
| true | true | public static void enhance(final NetcdfDataset dataset, final Writer writer, final String query) {
MockGetCapP = null;
xmlString = null;
EventTime =null;
isMultiTime = false;
isMultiObsProperties = false;
//get the extent of the Netcdf file Lat/lon/time
Extent ext = null;
try {
//get basic information
ext = ThreddsExtentUtil.getExtent(dataset);
DatasetMetaData dst = new DatasetMetaData(ext, dataset);
dst.extractData();
if (query != null) {
//if query is not empty
//set the query params then call on the fly
splitQuery(query);
//if all the fields are valid ie not null
if ((service != null) && (request != null) && (version != null)) {
//get caps
if (request.equalsIgnoreCase("GetCapabilities")) {
createGetCapsResults(dst, writer);
} else if (request.equalsIgnoreCase("DescribeSensor")) {
} else if (request.equalsIgnoreCase("GetObservation")) {
if (EventTime !=null){
dst.setSearchTimes(EventTime,isMultiTime);
}
dst.setRequestedStationName(MetadataParser.offering);
dst.setDatasetArrayValues(observedProperties);
createGetObsResults(dst, writer);
} else {
writeErrorXMLCode(writer);
}
} //else if the above is not true print invalid xml text
else {
writeErrorXMLCode(writer);
}
} else if (query == null) {
//if the entry is null just print out the get caps xml
_log.info("Null query string/params: using get caps");
createGetCapsResults(dst, writer);
}
//finally close the dataset
dst.closeDataSet();
//catch
} catch (Exception e) {
_log.error(e);
}
}
| public static void enhance(final NetcdfDataset dataset, final Writer writer, final String query) {
MockGetCapP = null;
xmlString = null;
EventTime =null;
isMultiTime = false;
isMultiObsProperties = false;
//get the extent of the Netcdf file Lat/lon/time
Extent ext = null;
try {
//get basic information
ext = ThreddsExtentUtil.getExtent(dataset);
DatasetMetaData dst = new DatasetMetaData(ext, dataset);
dst.extractData();
if (query != null) {
//if query is not empty
//set the query params then call on the fly
splitQuery(query);
//if all the fields are valid ie not null
if ((service != null) && (request != null) && (version != null)) {
//get caps
if (request.equalsIgnoreCase("GetCapabilities")) {
createGetCapsResults(dst, writer);
} else if (request.equalsIgnoreCase("DescribeSensor")) {
writeErrorXMLCode(writer);
} else if (request.equalsIgnoreCase("GetObservation")) {
if (EventTime !=null){
dst.setSearchTimes(EventTime,isMultiTime);
}
dst.setRequestedStationName(MetadataParser.offering);
dst.setDatasetArrayValues(observedProperties);
createGetObsResults(dst, writer);
} else {
writeErrorXMLCode(writer);
}
} //else if the above is not true print invalid xml text
else {
writeErrorXMLCode(writer);
}
} else if (query == null) {
//if the entry is null just print out the get caps xml
_log.info("Null query string/params: using get caps");
createGetCapsResults(dst, writer);
}
//finally close the dataset
dst.closeDataSet();
//catch
} catch (Exception e) {
_log.error(e);
}
}
|
diff --git a/src/cytoscape/actions/ExportVizmapAction.java b/src/cytoscape/actions/ExportVizmapAction.java
index dddec6a0c..c21a4b059 100644
--- a/src/cytoscape/actions/ExportVizmapAction.java
+++ b/src/cytoscape/actions/ExportVizmapAction.java
@@ -1,156 +1,156 @@
/*
Copyright (c) 2006, 2007, The Cytoscape Consortium (www.cytoscape.org)
The Cytoscape Consortium is:
- Institute for Systems Biology
- University of California San Diego
- Memorial Sloan-Kettering Cancer Center
- Institut Pasteur
- Agilent Technologies
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package cytoscape.actions;
import cytoscape.Cytoscape;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;
import cytoscape.util.CyFileFilter;
import cytoscape.util.CytoscapeAction;
import cytoscape.util.FileUtil;
import java.awt.event.ActionEvent;
/**
* Export visual styles as a vizmap.props file<br>
*
* @version 0.8
* @since 2.3
* @author kono
*
*/
public class ExportVizmapAction extends CytoscapeAction {
/**
* Creates a new ExportVizmapAction object.
*/
public ExportVizmapAction() {
super("Vizmap Property File");
setPreferredMenu("File.Export");
}
/**
* Get file name and execute the saving task<br>
*/
public void actionPerformed(ActionEvent e) {
String name;
try {
- name = FileUtil.getFile("Export Vizmaper as property file", FileUtil.SAVE,
+ name = FileUtil.getFile("Export Vizmap property file", FileUtil.SAVE,
new CyFileFilter[] { }).toString();
} catch (Exception exp) {
// this is because the selection was canceled
return;
}
if (!name.endsWith(".props"))
name = name + ".props";
// Create Task
ExportVizmapTask task = new ExportVizmapTask(name);
// Configure JTask Dialog Pop-Up Box
JTaskConfig jTaskConfig = new JTaskConfig();
jTaskConfig.setOwner(Cytoscape.getDesktop());
jTaskConfig.displayCloseButton(true);
jTaskConfig.displayStatus(true);
jTaskConfig.displayCancelButton(false);
jTaskConfig.setAutoDispose(false);
// Execute Task in New Thread; pop open JTask Dialog Box.
TaskManager.executeTask(task, jTaskConfig);
}
}
/**
* Task to Save Graph Data to GML Format.
*/
class ExportVizmapTask implements Task {
private String fileName;
private TaskMonitor taskMonitor;
/**
* Constructor.
*/
ExportVizmapTask(String fileName) {
this.fileName = fileName;
}
/**
* Executes Task
*/
public void run() {
taskMonitor.setStatus("Saving Visual Styles...");
taskMonitor.setPercentCompleted(-1);
Cytoscape.firePropertyChange(Cytoscape.SAVE_VIZMAP_PROPS, null, fileName);
taskMonitor.setPercentCompleted(100);
taskMonitor.setStatus("Vizmaps successfully saved to: " + fileName);
}
/**
* Halts the Task: Not Currently Implemented.
*/
public void halt() {
// Task can not currently be halted.
}
/**
* Sets the Task Monitor.
*
* @param taskMonitor
* TaskMonitor Object.
*/
public void setTaskMonitor(TaskMonitor taskMonitor) throws IllegalThreadStateException {
this.taskMonitor = taskMonitor;
}
/**
* Gets the Task Title.
*
* @return Task Title.
*/
public String getTitle() {
return new String("Saving Vizmap");
}
}
| true | true | public void actionPerformed(ActionEvent e) {
String name;
try {
name = FileUtil.getFile("Export Vizmaper as property file", FileUtil.SAVE,
new CyFileFilter[] { }).toString();
} catch (Exception exp) {
// this is because the selection was canceled
return;
}
if (!name.endsWith(".props"))
name = name + ".props";
// Create Task
ExportVizmapTask task = new ExportVizmapTask(name);
// Configure JTask Dialog Pop-Up Box
JTaskConfig jTaskConfig = new JTaskConfig();
jTaskConfig.setOwner(Cytoscape.getDesktop());
jTaskConfig.displayCloseButton(true);
jTaskConfig.displayStatus(true);
jTaskConfig.displayCancelButton(false);
jTaskConfig.setAutoDispose(false);
// Execute Task in New Thread; pop open JTask Dialog Box.
TaskManager.executeTask(task, jTaskConfig);
}
| public void actionPerformed(ActionEvent e) {
String name;
try {
name = FileUtil.getFile("Export Vizmap property file", FileUtil.SAVE,
new CyFileFilter[] { }).toString();
} catch (Exception exp) {
// this is because the selection was canceled
return;
}
if (!name.endsWith(".props"))
name = name + ".props";
// Create Task
ExportVizmapTask task = new ExportVizmapTask(name);
// Configure JTask Dialog Pop-Up Box
JTaskConfig jTaskConfig = new JTaskConfig();
jTaskConfig.setOwner(Cytoscape.getDesktop());
jTaskConfig.displayCloseButton(true);
jTaskConfig.displayStatus(true);
jTaskConfig.displayCancelButton(false);
jTaskConfig.setAutoDispose(false);
// Execute Task in New Thread; pop open JTask Dialog Box.
TaskManager.executeTask(task, jTaskConfig);
}
|
diff --git a/src/main/java/fr/ybo/ybotv/android/activity/ProgrammeActivity.java b/src/main/java/fr/ybo/ybotv/android/activity/ProgrammeActivity.java
index c06586f..3f11ce0 100644
--- a/src/main/java/fr/ybo/ybotv/android/activity/ProgrammeActivity.java
+++ b/src/main/java/fr/ybo/ybotv/android/activity/ProgrammeActivity.java
@@ -1,422 +1,422 @@
package fr.ybo.ybotv.android.activity;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import fr.ybo.ybotv.android.R;
import fr.ybo.ybotv.android.YboTvApplication;
import fr.ybo.ybotv.android.adapter.ProgrammeAdapter;
import fr.ybo.ybotv.android.adapter.ProgrammeViewFlowAdapter;
import fr.ybo.ybotv.android.exception.YboTvErreurReseau;
import fr.ybo.ybotv.android.exception.YboTvException;
import fr.ybo.ybotv.android.lasylist.RatingLoader;
import fr.ybo.ybotv.android.lasylist.ImageLoader;
import fr.ybo.ybotv.android.modele.Channel;
import fr.ybo.ybotv.android.modele.Programme;
import fr.ybo.ybotv.android.receiver.AlertReceiver;
import fr.ybo.ybotv.android.service.YouTubeService;
import fr.ybo.ybotv.android.util.AdMobUtil;
import fr.ybo.ybotv.android.util.CalendarUtil;
import fr.ybo.ybotv.android.util.GetView;
import fr.ybo.ybotv.android.util.TacheAvecGestionErreurReseau;
import org.taptwo.android.widget.TitleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ProgrammeActivity extends SherlockActivity implements GetView {
private Programme programme;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
programme = getIntent().getParcelableExtra("programme");
getSupportActionBar().setTitle(programme.getTitle());
if (((YboTvApplication) getApplication()).isTablet()) {
createViewForTablet(programme);
} else {
createViewForPhone(programme);
}
AdMobUtil.manageAds(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem itemAgenda = menu.add(Menu.NONE, R.id.menu_calendar, Menu.NONE, R.string.menu_calendar);
itemAgenda.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
itemAgenda.setIcon(android.R.drawable.ic_menu_agenda);
MenuItem itemShare = menu.add(Menu.NONE, R.id.menu_share, Menu.NONE, R.string.menu_share);
itemShare.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
itemShare.setIcon(android.R.drawable.ic_menu_share);
String currentDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
if (currentDate.compareTo(programme.getStart()) < 0) {
MenuItem item = menu.add(Menu.NONE, R.id.menu_alert, Menu.NONE, R.string.menu_alert);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
setMenuAlertIcon(item);
}
return true;
}
private void setMenuAlertIcon(MenuItem item) {
if (programme.hasAlert(getApplication())) {
item.setIcon(R.drawable.ic_menu_alert_on);
} else {
item.setIcon(R.drawable.ic_menu_alert_off);
}
}
private Channel channel = null;
private Channel getChannel() {
if (channel == null) {
Channel channelSelect = new Channel();
channelSelect.setId(programme.getChannel());
channel = ((YboTvApplication) getApplication()).getDatabase().selectSingle(channelSelect);
}
return channel;
}
private void createNotification() {
long timeToNotif;
try {
// The notification is 3 minutes before programme start.
timeToNotif = new SimpleDateFormat("yyyyMMddHHmmss").parse(programme.getStart()).getTime() - (3 * 60 * 1000);
} catch (ParseException e) {
throw new YboTvException(e);
}
Intent alert = new Intent(this, AlertReceiver.class);
alert.putExtra("programme", (Parcelable) programme);
alert.putExtra("channel", (Parcelable) getChannel());
int notificationId = Integer.parseInt(programme.getStart().substring(8));
PendingIntent pendingAlert = PendingIntent.getBroadcast(this, notificationId, alert, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.set(AlarmManager.RTC_WAKEUP, timeToNotif, pendingAlert);
}
private void cancelNotification() {
Intent alert = new Intent(this, AlertReceiver.class);
alert.putExtra("programme", (Parcelable) programme);
alert.putExtra("channel", (Parcelable) getChannel());
int notificationId = Integer.parseInt(programme.getStart().substring(8));
PendingIntent pendingAlert = PendingIntent.getBroadcast(this, notificationId, alert, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.cancel(pendingAlert);
}
private void addProgrammeToAgenda() {
Map<Integer, String> calendars = CalendarUtil.getCalendars(getContentResolver());
if (calendars.size() > 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final int[] calenderIds = new int[calendars.size()];
CharSequence[] calenderNames = new String[calendars.size()];
int index = 0;
for (Map.Entry<Integer, String> entry : calendars.entrySet()) {
calenderIds[index] = entry.getKey();
calenderNames[index] = entry.getValue();
index++;
}
builder.setItems(calenderNames, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addInCalendar(calenderIds[which]);
}
});
builder.show();
} else if (calendars.size() == 1) {
addInCalendar(calendars.entrySet().iterator().next().getKey());
} else {
Toast.makeText(this, R.string.noCalendarError, Toast.LENGTH_LONG).show();
}
}
private void addInCalendar(int calendarId) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
long startTime = sdf.parse(programme.getStart()).getTime();
long stopTime = sdf.parse(programme.getStop()).getTime();
CalendarUtil.addToCalendar(this, getChannel().getDisplayName() + " - " + programme.getTitle(), programme.getDesc(), calendarId, startTime, stopTime);
Toast.makeText(this, R.string.eventAdded, Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
throw new YboTvException(e);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_calendar) {
addProgrammeToAgenda();
} else if (item.getItemId() == R.id.menu_share) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shareSubject, programme.getTitle()));
intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shareText, programme.getTitle()));
startActivity(Intent.createChooser(intent, getString(R.string.app_name)));
} else if (item.getItemId() == R.id.menu_alert) {
programme.setHasAlert(getApplication(), !programme.hasAlert(getApplication()));
if (programme.hasAlert(getApplication())) {
createNotification();
} else {
cancelNotification();
}
setMenuAlertIcon(item);
}
return super.onOptionsItemSelected(item);
}
private void createViewForPhone(Programme programme) {
setContentView(R.layout.flow);
ViewFlow viewFlow = (ViewFlow) findViewById(R.id.viewflow);
ProgrammeViewFlowAdapter adapter = new ProgrammeViewFlowAdapter(this, programme);
viewFlow.setAdapter(adapter);
TitleFlowIndicator indicator = (TitleFlowIndicator) findViewById(R.id.viewflowindic);
indicator.setTitleProvider(adapter);
viewFlow.setFlowIndicator(indicator);
}
private void createViewForTablet(Programme programme) {
setContentView(R.layout.programme_for_tablet);
contructResumeView(this, this, programme);
contructDetailView(this, this, programme);
if (programme.isMovie()) {
contructTrailerView(this, this, programme);
} else {
findViewById(R.id.programme_trailer_loading).setVisibility(View.GONE);
}
}
public static void contructTrailerView(final Context context, GetView getView, final Programme programme) {
if (programme == null || programme.getTitle() == null) {
return;
}
final Button trailerButton = (Button) getView.findViewById(R.id.programme_trailer_button);
final TextView trailerLoading = (TextView) getView.findViewById(R.id.programme_trailer_loading);
trailerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String videoId = (String) v.getTag();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + videoId));
intent.putExtra("VIDEO_ID", videoId);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException ignore) {
Toast.makeText(context, R.string.youtubeNotFound, Toast.LENGTH_LONG).show();
}
}
});
new TacheAvecGestionErreurReseau(context) {
private String videoId;
@Override
protected void myDoBackground() throws YboTvErreurReseau {
videoId = YouTubeService.getInstance().getFirstResult("Bande annonce " + programme.getTitle());
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (videoId == null) {
trailerLoading.setText(R.string.no_trailer_found);
} else {
trailerLoading.setVisibility(View.INVISIBLE);
trailerButton.setVisibility(View.VISIBLE);
trailerButton.setTag(videoId);
}
}
}.execute();
}
public static void contructDetailView(Context context, GetView getView, Programme programme) {
TextView duree = (TextView) getView.findViewById(R.id.programme_detail_duree);
TextView date = (TextView) getView.findViewById(R.id.programme_detail_date);
TextView credits = (TextView) getView.findViewById(R.id.programme_detail_credits);
duree.setText(context.getString(R.string.duree, programme.getDuree()));
if (programme.getDate() == null) {
date.setVisibility(View.GONE);
} else {
date.setVisibility(View.VISIBLE);
date.setText(context.getString(R.string.date, programme.getDate()));
}
StringBuilder builderCredits = new StringBuilder();
for (String director : programme.getDirectors()) {
builderCredits.append(context.getString(R.string.director, director));
builderCredits.append('\n');
}
for (String actor : programme.getActors()) {
builderCredits.append(context.getString(R.string.actor, actor));
builderCredits.append('\n');
}
for (String writer : programme.getWriters()) {
builderCredits.append(context.getString(R.string.writer, writer));
builderCredits.append('\n');
}
for (String presenter : programme.getPresenters()) {
builderCredits.append(context.getString(R.string.presenter, presenter));
builderCredits.append('\n');
}
credits.setText(builderCredits.toString());
credits.setMovementMethod(new ScrollingMovementMethod());
}
private static String formatterMots(String motsAFormatter) {
StringBuilder motsFormattes = new StringBuilder();
motsFormattes.append(motsAFormatter.substring(0, 1).toUpperCase());
motsFormattes.append(motsAFormatter.substring(1));
return motsFormattes.toString();
}
private final static Map<String, Integer> mapOfCsaRatings = new HashMap<String, Integer>() {{
put("-18", R.drawable.moins18);
put("-16", R.drawable.moins16);
put("-12", R.drawable.moins12);
put("-10", R.drawable.moins10);
}};
public static void contructResumeView(Activity context, GetView getView, Programme programme) {
ImageLoader imageLoader = new ImageLoader(context.getApplicationContext());
ImageView icon = (ImageView) getView.findViewById(R.id.programme_resume_icon);
ImageView rating = (ImageView) getView.findViewById(R.id.programme_resume_rating);
ImageView csaRating = (ImageView) getView.findViewById(R.id.programme_resume_csa_rating);
TextView categories = (TextView) getView.findViewById(R.id.programme_resume_categories);
TextView description = (TextView) getView.findViewById(R.id.programme_resume_description);
- if (programme.getIcon() != null && !programme.getIcon().isEmpty()) {
+ if (programme.getIcon() != null && programme.getIcon().length() != 0) {
imageLoader.DisplayImage(programme.getIcon(), icon);
icon.setVisibility(View.VISIBLE);
} else {
icon.setVisibility(View.GONE);
}
if (programme.isMovie() || programme.isTvShow()) {
if (programme.getRatingResource() == null) {
new Thread(new RatingLoader(programme, new RunChangeRatingImageOnUiThread(context, rating, programme))).start();
} else {
rating.setImageResource(programme.getRatingResource());
rating.setVisibility(View.VISIBLE);
}
} else {
rating.setVisibility(View.GONE);
}
Log.d(YboTvApplication.TAG, "CsaRating : " + programme.getCsaRating());
if (programme.getCsaRating() != null
&& mapOfCsaRatings.containsKey(programme.getCsaRating())) {
csaRating.setImageResource(mapOfCsaRatings.get(programme.getCsaRating()));
csaRating.setVisibility(View.VISIBLE);
} else {
csaRating.setVisibility(View.GONE);
}
if (programme.getCategories().isEmpty()) {
categories.setVisibility(View.GONE);
} else {
categories.setVisibility(View.VISIBLE);
String categorie = null;
for (String oneCategorie : programme.getCategories()) {
categorie = oneCategorie;
}
categories.setText(formatterMots(categorie));
}
if (programme.getDesc() != null) {
description.setText(Html.fromHtml(programme.getDesc()));
description.setVisibility(View.VISIBLE);
} else {
description.setVisibility(View.GONE);
}
description.setMovementMethod(new ScrollingMovementMethod());
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
private static class ChangeRatingImage implements Runnable {
private ImageView rating;
private Programme programme;
private ChangeRatingImage(ImageView rating, Programme programme) {
this.rating = rating;
this.programme = programme;
}
@Override
public void run() {
if (programme.getRatingResource() != null) {
rating.setImageResource(programme.getRatingResource());
rating.setVisibility(View.VISIBLE);
}
}
}
private static class RunChangeRatingImageOnUiThread implements Runnable {
private Activity context;
private ImageView rating;
private Programme programme;
private RunChangeRatingImageOnUiThread(Activity context, ImageView rating, Programme programme) {
this.context = context;
this.rating = rating;
this.programme = programme;
}
@Override
public void run() {
context.runOnUiThread(new ChangeRatingImage(rating, programme));
}
}
}
| true | true | public static void contructResumeView(Activity context, GetView getView, Programme programme) {
ImageLoader imageLoader = new ImageLoader(context.getApplicationContext());
ImageView icon = (ImageView) getView.findViewById(R.id.programme_resume_icon);
ImageView rating = (ImageView) getView.findViewById(R.id.programme_resume_rating);
ImageView csaRating = (ImageView) getView.findViewById(R.id.programme_resume_csa_rating);
TextView categories = (TextView) getView.findViewById(R.id.programme_resume_categories);
TextView description = (TextView) getView.findViewById(R.id.programme_resume_description);
if (programme.getIcon() != null && !programme.getIcon().isEmpty()) {
imageLoader.DisplayImage(programme.getIcon(), icon);
icon.setVisibility(View.VISIBLE);
} else {
icon.setVisibility(View.GONE);
}
if (programme.isMovie() || programme.isTvShow()) {
if (programme.getRatingResource() == null) {
new Thread(new RatingLoader(programme, new RunChangeRatingImageOnUiThread(context, rating, programme))).start();
} else {
rating.setImageResource(programme.getRatingResource());
rating.setVisibility(View.VISIBLE);
}
} else {
rating.setVisibility(View.GONE);
}
Log.d(YboTvApplication.TAG, "CsaRating : " + programme.getCsaRating());
if (programme.getCsaRating() != null
&& mapOfCsaRatings.containsKey(programme.getCsaRating())) {
csaRating.setImageResource(mapOfCsaRatings.get(programme.getCsaRating()));
csaRating.setVisibility(View.VISIBLE);
} else {
csaRating.setVisibility(View.GONE);
}
if (programme.getCategories().isEmpty()) {
categories.setVisibility(View.GONE);
} else {
categories.setVisibility(View.VISIBLE);
String categorie = null;
for (String oneCategorie : programme.getCategories()) {
categorie = oneCategorie;
}
categories.setText(formatterMots(categorie));
}
if (programme.getDesc() != null) {
description.setText(Html.fromHtml(programme.getDesc()));
description.setVisibility(View.VISIBLE);
} else {
description.setVisibility(View.GONE);
}
description.setMovementMethod(new ScrollingMovementMethod());
}
| public static void contructResumeView(Activity context, GetView getView, Programme programme) {
ImageLoader imageLoader = new ImageLoader(context.getApplicationContext());
ImageView icon = (ImageView) getView.findViewById(R.id.programme_resume_icon);
ImageView rating = (ImageView) getView.findViewById(R.id.programme_resume_rating);
ImageView csaRating = (ImageView) getView.findViewById(R.id.programme_resume_csa_rating);
TextView categories = (TextView) getView.findViewById(R.id.programme_resume_categories);
TextView description = (TextView) getView.findViewById(R.id.programme_resume_description);
if (programme.getIcon() != null && programme.getIcon().length() != 0) {
imageLoader.DisplayImage(programme.getIcon(), icon);
icon.setVisibility(View.VISIBLE);
} else {
icon.setVisibility(View.GONE);
}
if (programme.isMovie() || programme.isTvShow()) {
if (programme.getRatingResource() == null) {
new Thread(new RatingLoader(programme, new RunChangeRatingImageOnUiThread(context, rating, programme))).start();
} else {
rating.setImageResource(programme.getRatingResource());
rating.setVisibility(View.VISIBLE);
}
} else {
rating.setVisibility(View.GONE);
}
Log.d(YboTvApplication.TAG, "CsaRating : " + programme.getCsaRating());
if (programme.getCsaRating() != null
&& mapOfCsaRatings.containsKey(programme.getCsaRating())) {
csaRating.setImageResource(mapOfCsaRatings.get(programme.getCsaRating()));
csaRating.setVisibility(View.VISIBLE);
} else {
csaRating.setVisibility(View.GONE);
}
if (programme.getCategories().isEmpty()) {
categories.setVisibility(View.GONE);
} else {
categories.setVisibility(View.VISIBLE);
String categorie = null;
for (String oneCategorie : programme.getCategories()) {
categorie = oneCategorie;
}
categories.setText(formatterMots(categorie));
}
if (programme.getDesc() != null) {
description.setText(Html.fromHtml(programme.getDesc()));
description.setVisibility(View.VISIBLE);
} else {
description.setVisibility(View.GONE);
}
description.setMovementMethod(new ScrollingMovementMethod());
}
|
diff --git a/JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java b/JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java
index 7eb084f7..a27c3a31 100644
--- a/JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java
+++ b/JavaSource/org/unitime/timetable/onlinesectioning/OnlineSectioningLogger.java
@@ -1,184 +1,179 @@
/*
* UniTime 3.2 (University Timetabling Application)
* Copyright (C) 2011, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.onlinesectioning;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.Student;
import org.unitime.timetable.model.dao.OnlineSectioningLogDAO;
import org.unitime.timetable.model.dao.SessionDAO;
import org.unitime.timetable.model.dao.StudentDAO;
/**
* @author Tomas Muller
*/
public class OnlineSectioningLogger extends Thread {
private static Log sLog = LogFactory.getLog(OnlineSectioningLogger.class);
private List<OnlineSectioningLog.Action> iActions = new Vector<OnlineSectioningLog.Action>();
private boolean iActive = false;
private boolean iEnabled = false;
private int iLogLimit = -1;
private PrintWriter iOut = null;
private static OnlineSectioningLogger sInstance = null;
public static OnlineSectioningLogger getInstance() {
if (sInstance == null) startLogger();
return sInstance;
}
public static void startLogger() {
if (sInstance == null) {
sInstance = new OnlineSectioningLogger();
sInstance.start();
}
}
public static void stopLogger() {
if (sInstance != null) {
sInstance.iActive = false;
sInstance.interrupt();
try {
sInstance.join();
} catch (InterruptedException e) {}
sInstance = null;
}
}
private OnlineSectioningLogger() {
super("OnlineSectioningLogger");
setDaemon(true);
iEnabled = "true".equals(ApplicationProperties.getProperty("unitime.sectioning.log", "true"));
iLogLimit = Integer.parseInt(ApplicationProperties.getProperty("unitime.sectioning.log.limit", "5000"));
try {
if (ApplicationProperties.getProperty("unitime.sectioning.log.file") != null)
iOut = new PrintWriter(new FileWriter(new File(ApplicationProperties.getProperty("unitime.sectioning.log.file")), true));
} catch (IOException e) {
sLog.warn("Unable to create sectioning log: " + e.getMessage(), e);
}
}
public boolean isEnabled() { return iEnabled; }
public void setEnabled(boolean enabled) { iEnabled = enabled; }
public boolean isActive() { return iActive; }
public void record(OnlineSectioningLog.Log log) {
if (log == null || !isEnabled() || !isActive()) return;
for (OnlineSectioningLog.Action action: log.getActionList()) {
if (action.hasStartTime() && action.hasStudent() && action.hasOperation() && action.hasSession()) {
synchronized (iActions) {
if (iLogLimit <= 0 || iActions.size() < iLogLimit)
iActions.add(action);
}
if (iOut != null) {
synchronized (iOut) {
iOut.print(OnlineSectioningLog.Log.newBuilder().addAction(action).build().toString());
iOut.flush();
}
}
}
}
}
public void run() {
sLog.info("Online Sectioning Logger is up.");
try {
iActive = true;
- try {
- iOut = new PrintWriter(new FileWriter(new File(ApplicationProperties.getDataFolder(), "sectioning.log"), true));
- } catch (IOException e) {
- sLog.warn("Unable to create sectioning log: " + e.getMessage(), e);
- }
while (true) {
try {
sleep(60000);
} catch (InterruptedException e) {
}
List<OnlineSectioningLog.Action> actionsToSave = null;
synchronized (iActions) {
if (!iActions.isEmpty()) {
actionsToSave = new ArrayList<OnlineSectioningLog.Action>(iActions);
iActions.clear();
}
}
try {
if (actionsToSave != null) {
sLog.debug("Persisting " + actionsToSave.size() + " actions...");
if (iLogLimit > 0 && actionsToSave.size() >= iLogLimit)
sLog.warn("The limit of " + iLogLimit + " unpersisted log messages was reached, some messages have been dropped.");
org.hibernate.Session hibSession = OnlineSectioningLogDAO.getInstance().createNewSession();
try {
Hashtable<Long, Session> sessions = new Hashtable<Long, Session>();
for (OnlineSectioningLog.Action q: actionsToSave) {
org.unitime.timetable.model.OnlineSectioningLog log = new org.unitime.timetable.model.OnlineSectioningLog();
log.setAction(q.toByteArray());
log.setOperation(q.getOperation());
String studentExternalId = (q.getStudent().hasExternalId() ? q.getStudent().getExternalId() : null);
if (studentExternalId == null || studentExternalId.isEmpty()) {
Student student = StudentDAO.getInstance().get(q.getStudent().getUniqueId(), hibSession);
if (student == null) continue;
studentExternalId = student.getExternalUniqueId();
}
log.setStudent(studentExternalId);
log.setTimeStamp(new Date(q.getStartTime()));
if (q.hasResult())
log.setResult(q.getResult().getNumber());
if (q.hasUser() && q.getUser().hasExternalId())
log.setUser(q.getUser().getExternalId());
Long sessionId = q.getSession().getUniqueId();
Session session = sessions.get(sessionId);
if (session == null) {
session = SessionDAO.getInstance().get(sessionId, hibSession);
sessions.put(sessionId, session);
}
log.setSession(session);
hibSession.save(log);
}
hibSession.flush();
} finally {
hibSession.close();
}
}
} catch (Throwable t) {
sLog.warn("Failed to save " + actionsToSave.size() + " log actions: " + t.getMessage(), t);
}
if (!iActive) break;
}
} catch (Throwable t) {
sLog.error("Online Sectioning Logger failed: " + t.getMessage(), t);
} finally {
iActive = false;
- if (iOut != null) iOut.flush(); iOut.close();
+ if (iOut != null) { iOut.flush(); iOut.close(); }
}
sLog.info("Online Sectioning Logger is down."); }
}
| false | true | public void run() {
sLog.info("Online Sectioning Logger is up.");
try {
iActive = true;
try {
iOut = new PrintWriter(new FileWriter(new File(ApplicationProperties.getDataFolder(), "sectioning.log"), true));
} catch (IOException e) {
sLog.warn("Unable to create sectioning log: " + e.getMessage(), e);
}
while (true) {
try {
sleep(60000);
} catch (InterruptedException e) {
}
List<OnlineSectioningLog.Action> actionsToSave = null;
synchronized (iActions) {
if (!iActions.isEmpty()) {
actionsToSave = new ArrayList<OnlineSectioningLog.Action>(iActions);
iActions.clear();
}
}
try {
if (actionsToSave != null) {
sLog.debug("Persisting " + actionsToSave.size() + " actions...");
if (iLogLimit > 0 && actionsToSave.size() >= iLogLimit)
sLog.warn("The limit of " + iLogLimit + " unpersisted log messages was reached, some messages have been dropped.");
org.hibernate.Session hibSession = OnlineSectioningLogDAO.getInstance().createNewSession();
try {
Hashtable<Long, Session> sessions = new Hashtable<Long, Session>();
for (OnlineSectioningLog.Action q: actionsToSave) {
org.unitime.timetable.model.OnlineSectioningLog log = new org.unitime.timetable.model.OnlineSectioningLog();
log.setAction(q.toByteArray());
log.setOperation(q.getOperation());
String studentExternalId = (q.getStudent().hasExternalId() ? q.getStudent().getExternalId() : null);
if (studentExternalId == null || studentExternalId.isEmpty()) {
Student student = StudentDAO.getInstance().get(q.getStudent().getUniqueId(), hibSession);
if (student == null) continue;
studentExternalId = student.getExternalUniqueId();
}
log.setStudent(studentExternalId);
log.setTimeStamp(new Date(q.getStartTime()));
if (q.hasResult())
log.setResult(q.getResult().getNumber());
if (q.hasUser() && q.getUser().hasExternalId())
log.setUser(q.getUser().getExternalId());
Long sessionId = q.getSession().getUniqueId();
Session session = sessions.get(sessionId);
if (session == null) {
session = SessionDAO.getInstance().get(sessionId, hibSession);
sessions.put(sessionId, session);
}
log.setSession(session);
hibSession.save(log);
}
hibSession.flush();
} finally {
hibSession.close();
}
}
} catch (Throwable t) {
sLog.warn("Failed to save " + actionsToSave.size() + " log actions: " + t.getMessage(), t);
}
if (!iActive) break;
}
} catch (Throwable t) {
sLog.error("Online Sectioning Logger failed: " + t.getMessage(), t);
} finally {
iActive = false;
if (iOut != null) iOut.flush(); iOut.close();
}
sLog.info("Online Sectioning Logger is down."); }
| public void run() {
sLog.info("Online Sectioning Logger is up.");
try {
iActive = true;
while (true) {
try {
sleep(60000);
} catch (InterruptedException e) {
}
List<OnlineSectioningLog.Action> actionsToSave = null;
synchronized (iActions) {
if (!iActions.isEmpty()) {
actionsToSave = new ArrayList<OnlineSectioningLog.Action>(iActions);
iActions.clear();
}
}
try {
if (actionsToSave != null) {
sLog.debug("Persisting " + actionsToSave.size() + " actions...");
if (iLogLimit > 0 && actionsToSave.size() >= iLogLimit)
sLog.warn("The limit of " + iLogLimit + " unpersisted log messages was reached, some messages have been dropped.");
org.hibernate.Session hibSession = OnlineSectioningLogDAO.getInstance().createNewSession();
try {
Hashtable<Long, Session> sessions = new Hashtable<Long, Session>();
for (OnlineSectioningLog.Action q: actionsToSave) {
org.unitime.timetable.model.OnlineSectioningLog log = new org.unitime.timetable.model.OnlineSectioningLog();
log.setAction(q.toByteArray());
log.setOperation(q.getOperation());
String studentExternalId = (q.getStudent().hasExternalId() ? q.getStudent().getExternalId() : null);
if (studentExternalId == null || studentExternalId.isEmpty()) {
Student student = StudentDAO.getInstance().get(q.getStudent().getUniqueId(), hibSession);
if (student == null) continue;
studentExternalId = student.getExternalUniqueId();
}
log.setStudent(studentExternalId);
log.setTimeStamp(new Date(q.getStartTime()));
if (q.hasResult())
log.setResult(q.getResult().getNumber());
if (q.hasUser() && q.getUser().hasExternalId())
log.setUser(q.getUser().getExternalId());
Long sessionId = q.getSession().getUniqueId();
Session session = sessions.get(sessionId);
if (session == null) {
session = SessionDAO.getInstance().get(sessionId, hibSession);
sessions.put(sessionId, session);
}
log.setSession(session);
hibSession.save(log);
}
hibSession.flush();
} finally {
hibSession.close();
}
}
} catch (Throwable t) {
sLog.warn("Failed to save " + actionsToSave.size() + " log actions: " + t.getMessage(), t);
}
if (!iActive) break;
}
} catch (Throwable t) {
sLog.error("Online Sectioning Logger failed: " + t.getMessage(), t);
} finally {
iActive = false;
if (iOut != null) { iOut.flush(); iOut.close(); }
}
sLog.info("Online Sectioning Logger is down."); }
|
diff --git a/src/ch9k/chat/AddContactController.java b/src/ch9k/chat/AddContactController.java
index 4507a83..fc41807 100644
--- a/src/ch9k/chat/AddContactController.java
+++ b/src/ch9k/chat/AddContactController.java
@@ -1,62 +1,63 @@
package ch9k.chat;
import ch9k.chat.gui.AddContactPanel;
import ch9k.core.ChatApplication;
import ch9k.core.I18n;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* Shows a dialog to enter
* @author Pieter De Baets
*/
public class AddContactController {
private AddContactPanel view;
public AddContactController(Window window) {
JDialog dialog = new JDialog(window,
I18n.get("ch9k.chat", "add_contact"),
ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setLocationRelativeTo(window);
dialog.setResizable(false);
view = new AddContactPanel(this, dialog);
dialog.setVisible(true);
}
public boolean addContact(String username, String inetAddress) {
InetAddress ip = null;
boolean hasErrors = true;
// do some validation
if(username.isEmpty() || inetAddress.isEmpty()) {
view.setError(I18n.get("ch9k.core", "error_fill_all_fields"));
} else {
try {
ip = InetAddress.getByName(inetAddress);
if(InetAddress.getLocalHost().equals(ip)) {
view.setError(I18n.get("ch9k.chat", "error_own_ip"));
} else {
hasErrors = false;
}
} catch(UnknownHostException ex) {
view.setError(I18n.get("ch9k.chat", "error_invalid_ip"));
}
}
ContactList list = ChatApplication.getInstance().
getAccount().getContactList();
if(!hasErrors && list.getContact(ip, username) != null) {
list.addContact(new Contact(username, ip), true);
} else {
+ hasErrors = true;
view.setError(I18n.get("ch9k.chat", "error_contact_already_added"));
}
return !hasErrors;
}
}
| true | true | public boolean addContact(String username, String inetAddress) {
InetAddress ip = null;
boolean hasErrors = true;
// do some validation
if(username.isEmpty() || inetAddress.isEmpty()) {
view.setError(I18n.get("ch9k.core", "error_fill_all_fields"));
} else {
try {
ip = InetAddress.getByName(inetAddress);
if(InetAddress.getLocalHost().equals(ip)) {
view.setError(I18n.get("ch9k.chat", "error_own_ip"));
} else {
hasErrors = false;
}
} catch(UnknownHostException ex) {
view.setError(I18n.get("ch9k.chat", "error_invalid_ip"));
}
}
ContactList list = ChatApplication.getInstance().
getAccount().getContactList();
if(!hasErrors && list.getContact(ip, username) != null) {
list.addContact(new Contact(username, ip), true);
} else {
view.setError(I18n.get("ch9k.chat", "error_contact_already_added"));
}
return !hasErrors;
}
| public boolean addContact(String username, String inetAddress) {
InetAddress ip = null;
boolean hasErrors = true;
// do some validation
if(username.isEmpty() || inetAddress.isEmpty()) {
view.setError(I18n.get("ch9k.core", "error_fill_all_fields"));
} else {
try {
ip = InetAddress.getByName(inetAddress);
if(InetAddress.getLocalHost().equals(ip)) {
view.setError(I18n.get("ch9k.chat", "error_own_ip"));
} else {
hasErrors = false;
}
} catch(UnknownHostException ex) {
view.setError(I18n.get("ch9k.chat", "error_invalid_ip"));
}
}
ContactList list = ChatApplication.getInstance().
getAccount().getContactList();
if(!hasErrors && list.getContact(ip, username) != null) {
list.addContact(new Contact(username, ip), true);
} else {
hasErrors = true;
view.setError(I18n.get("ch9k.chat", "error_contact_already_added"));
}
return !hasErrors;
}
|
diff --git a/src/org/eclipse/jface/action/ToolBarContributionItem.java b/src/org/eclipse/jface/action/ToolBarContributionItem.java
index 5522a21f..f20e5a80 100644
--- a/src/org/eclipse/jface/action/ToolBarContributionItem.java
+++ b/src/org/eclipse/jface/action/ToolBarContributionItem.java
@@ -1,637 +1,637 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.action;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.jface.util.Assert;
/**
* The <code>ToolBarContributionItem</code> class provides a wrapper for tool
* bar managers when used in cool bar managers. It extends <code>ContributionItem</code>
* but and provides some additional methods to customize the size of the cool
* item and to retrieve the underlying tool bar manager.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 3.0
*/
public class ToolBarContributionItem extends ContributionItem {
/**
* A constant used by <code>setMinimumItemsToShow</code> and <code>getMinimumItemsToShow</code>
* to indicate that all tool items should be shown in the cool item.
*/
public static final int SHOW_ALL_ITEMS = -1;
/**
* The pull down menu used to list all hidden tool items if the current
* size is less than the preffered size.
*/
private MenuManager chevronMenuManager = null;
/**
* The widget created for this item; <code>null</code> before creation
* and after disposal.
*/
private CoolItem coolItem = null;
/**
* Current height of cool item
*/
private int currentHeight = -1;
/**
* Current width of cool item.
*/
private int currentWidth = -1;
/**
* A flag indicating that this item has been disposed. This prevents future
* method invocations from doing things they shouldn't.
*/
private boolean disposed = false;
/**
* Mininum number of tool items to show in the cool item widget.
*/
private int minimumItemsToShow = SHOW_ALL_ITEMS;
/**
* The tool bar manager used to manage the tool items contained in the cool
* item widget.
*/
private ToolBarManager toolBarManager = null;
/**
* Enable/disable chevron support.
*/
private boolean useChevron = true;
/**
* Convenience method equivalent to <code>ToolBarContributionItem(new ToolBarManager(), null)</code>.
*/
public ToolBarContributionItem() {
this(new ToolBarManager(), null);
}
/**
* Convenience method equivalent to <code>ToolBarContributionItem(toolBarManager, null)</code>.
*
* @param toolBarManager
* the tool bar manager
*/
public ToolBarContributionItem(IToolBarManager toolBarManager) {
this(toolBarManager, null);
}
/**
* Creates a tool bar contribution item.
*
* @param toolBarManager
* the tool bar manager to wrap
* @param id
* the contribution item id, or <code>null</code> if none
*/
public ToolBarContributionItem(IToolBarManager toolBarManager, String id) {
super(id);
Assert.isTrue(toolBarManager instanceof ToolBarManager);
this.toolBarManager = (ToolBarManager) toolBarManager;
}
/**
* Checks whether this contribution item has been disposed. If it has, and
* the tracing options are active, then it prints some debugging
* information.
*
* @return <code>true</code> if the item is disposed; <code>false</code>
* otherwise.
*
*/
private final boolean checkDisposed() {
if (disposed) {
if ("true".equalsIgnoreCase(Platform //$NON-NLS-1$
.getDebugOption("org.eclipse.jface/trace/toolbarDisposal"))) { //$NON-NLS-1$
System.out
.println("Method invocation on a disposed tool bar contribution item."); //$NON-NLS-1$
new Exception().printStackTrace(System.out);
}
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IContributionItem#dispose()
*/
public void dispose() {
// Dispose of the ToolBar and all its contributions
if (toolBarManager != null) {
toolBarManager.dispose();
toolBarManager = null;
}
/*
* We need to dispose the cool item or we might be left holding a cool
* item with a disposed control.
*/
if ((coolItem != null) && (!coolItem.isDisposed())) {
coolItem.dispose();
coolItem = null;
}
// Mark this item as disposed.
disposed = true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IContributionItem#fill(org.eclipse.swt.widgets.CoolBar,
* int)
*/
public void fill(CoolBar coolBar, int index) {
if (checkDisposed()) { return; }
if (coolItem == null && coolBar != null) {
ToolBar oldToolBar = toolBarManager.getControl();
ToolBar toolBar = toolBarManager.createControl(coolBar);
- if ((oldToolBar != null) && (!oldToolBar.equals(toolBar))) {
- // We are using a new tool bar, so we need to update.
+ if ((oldToolBar != null) && (oldToolBar.equals(toolBar))) {
+ // We are using an old tool bar, so we need to update.
toolBarManager.update(true);
}
// Do not create a coolItem if the toolbar is empty
if (toolBar.getItemCount() < 1) return;
int flags = SWT.DROP_DOWN;
if (index >= 0) {
coolItem = new CoolItem(coolBar, flags, index);
} else {
coolItem = new CoolItem(coolBar, flags);
}
// sets the back reference
coolItem.setData(this);
// Add the toolbar to the CoolItem widget
coolItem.setControl(toolBar);
// Handle Context Menu
toolBar.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
// if the toolbar does not have its own context menu then
// handle the event
if (toolBarManager.getContextMenuManager() == null) {
handleContextMenu(event);
}
}
});
// Handle for chevron clicking
if (getUseChevron()) {
// Chevron Support
coolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (event.detail == SWT.ARROW) {
handleChevron(event);
}
}
});
}
// Handle for disposal
coolItem.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
handleWidgetDispose(event);
}
});
// Sets the size of the coolItem
updateSize(true);
}
}
/**
* Returns a consistent set of wrap indices. The return value will always
* include at least one entry and the first entry will always be zero.
* CoolBar.getWrapIndices() is inconsistent in whether or not it returns an
* index for the first row.
*/
private int[] getAdjustedWrapIndices(int[] wraps) {
int[] adjustedWrapIndices;
if (wraps.length == 0) {
adjustedWrapIndices = new int[] { 0};
} else {
if (wraps[0] != 0) {
adjustedWrapIndices = new int[wraps.length + 1];
adjustedWrapIndices[0] = 0;
for (int i = 0; i < wraps.length; i++) {
adjustedWrapIndices[i + 1] = wraps[i];
}
} else {
adjustedWrapIndices = wraps;
}
}
return adjustedWrapIndices;
}
/**
* Returns the current height of the corresponding cool item.
*
* @return the current height
*/
public int getCurrentHeight() {
if (checkDisposed()) { return -1; }
return currentHeight;
}
/**
* Returns the current width of the corresponding cool item.
*
* @return the current size
*/
public int getCurrentWidth() {
if (checkDisposed()) { return -1; }
return currentWidth;
}
/**
* Returns the minimum number of tool items to show in the cool item.
*
* @return the minimum number of tool items to show, or <code>SHOW_ALL_ITEMS</code>
* if a value was not set
* @see #setMinimumItemsToShow(int)
*/
public int getMinimumItemsToShow() {
if (checkDisposed()) { return -1; }
return minimumItemsToShow;
}
/**
* Returns the internal tool bar manager of the contribution item.
*
* @return the tool bar manager, or <code>null</code> if one is not
* defined.
* @see IToolBarManager
*/
public IToolBarManager getToolBarManager() {
if (checkDisposed()) { return null; }
return toolBarManager;
}
/**
* Returns whether chevron support is enabled.
*
* @return <code>true</code> if chevron support is enabled, <code>false</code>
* otherwise
*/
public boolean getUseChevron() {
if (checkDisposed()) { return false; }
return useChevron;
}
/**
* Create and display the chevron menu.
*/
private void handleChevron(SelectionEvent event) {
CoolItem item = (CoolItem) event.widget;
Control control = item.getControl();
if ((control instanceof ToolBar) == false) { return; }
CoolBar coolBar = item.getParent();
Point chevronPosition = coolBar.toDisplay(new Point(event.x, event.y));
ToolBar toolBar = (ToolBar) control;
ToolItem[] tools = toolBar.getItems();
int toolCount = tools.length;
int visibleItemCount = 0;
while (visibleItemCount < toolCount) {
Rectangle toolBounds = tools[visibleItemCount].getBounds();
Point point = toolBar.toDisplay(new Point(toolBounds.x,
toolBounds.y));
toolBounds.x = point.x;
toolBounds.y = point.y;
// stop if the tool is at least partially hidden by the drop down
// chevron
if (chevronPosition.x >= toolBounds.x
&& chevronPosition.x - toolBounds.x <= toolBounds.width) {
break;
}
visibleItemCount++;
}
// Create a pop-up menu with items for each of the hidden buttons.
if (chevronMenuManager != null) {
chevronMenuManager.dispose();
}
chevronMenuManager = new MenuManager();
for (int i = visibleItemCount; i < toolCount; i++) {
IContributionItem data = (IContributionItem) tools[i].getData();
if (data instanceof ActionContributionItem) {
ActionContributionItem contribution = new ActionContributionItem(
((ActionContributionItem) data).getAction());
chevronMenuManager.add(contribution);
} else if (data instanceof SubContributionItem) {
IContributionItem innerData = ((SubContributionItem) data)
.getInnerItem();
if (innerData instanceof ActionContributionItem) {
ActionContributionItem contribution = new ActionContributionItem(
((ActionContributionItem) innerData).getAction());
chevronMenuManager.add(contribution);
}
} else if (data.isSeparator()) {
chevronMenuManager.add(new Separator());
}
}
Menu popup = chevronMenuManager.createContextMenu(coolBar);
popup.setLocation(chevronPosition.x, chevronPosition.y);
popup.setVisible(true);
}
/**
* Handles the event when the toobar item does not have its own context
* menu.
*
* @param event
* the event object
*/
private void handleContextMenu(Event event) {
ToolBar toolBar = toolBarManager.getControl();
// If parent has a menu then use that one
Menu parentMenu = toolBar.getParent().getMenu();
if ((parentMenu != null) && (!parentMenu.isDisposed())) {
toolBar.setMenu(parentMenu);
// Hook listener to remove menu once it has disapeared
parentMenu.addListener(SWT.Hide, new Listener() {
public void handleEvent(Event innerEvent) {
ToolBar innerToolBar = toolBarManager.getControl();
if (innerToolBar != null) {
innerToolBar.setMenu(null);
Menu innerParentMenu = innerToolBar.getParent()
.getMenu();
if (innerParentMenu != null) {
innerParentMenu.removeListener(SWT.Hide, this);
}
}
}
});
}
}
/**
* Handles the disposal of the widget.
*
* @param event
* the event object
*/
private void handleWidgetDispose(DisposeEvent event) {
coolItem = null;
}
/**
* A contribution item is visible iff its internal state is visible <em>or</em>
* the tool bar manager contains something other than group markers and
* separators.
*
* @return <code>true</code> if the tool bar manager contains something
* other than group marks and separators, and the internal state is
* set to be visible.
*/
public boolean isVisible() {
if (checkDisposed()) { return false; }
boolean visibleItem = false;
if (toolBarManager != null) {
IContributionItem[] contributionItems = toolBarManager.getItems();
for (int i = 0; i < contributionItems.length; i++) {
IContributionItem contributionItem = contributionItems[i];
if ((!contributionItem.isGroupMarker())
&& (!contributionItem.isSeparator())) {
visibleItem = true;
break;
}
}
}
return (visibleItem || super.isVisible());
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IContributionItem#saveWidgetState()
*/
public void saveWidgetState() {
if (checkDisposed()) { return; }
if (coolItem == null) return;
//1. Save current size
CoolBar coolBar = coolItem.getParent();
boolean isLastOnRow = false;
int lastIndex = coolBar.getItemCount() - 1;
int coolItemIndex = coolBar.indexOf(coolItem);
int[] wrapIndicies = getAdjustedWrapIndices(coolBar.getWrapIndices());
// Traverse through all wrap indicies backwards
for (int row = wrapIndicies.length - 1; row >= 0; row--) {
if (wrapIndicies[row] <= coolItemIndex) {
int nextRow = row + 1;
int nextRowStartIndex;
if (nextRow > (wrapIndicies.length - 1)) {
nextRowStartIndex = lastIndex + 1;
} else {
nextRowStartIndex = wrapIndicies[nextRow];
}
// Check to see if its the last item on the row
if (coolItemIndex == (nextRowStartIndex - 1)) {
isLastOnRow = true;
}
break;
}
}
// Save the preferred size as actual size for the last item on a row
int nCurrentWidth;
if (isLastOnRow) {
nCurrentWidth = coolItem.getPreferredSize().x;
} else {
nCurrentWidth = coolItem.getSize().x;
}
setCurrentWidth(nCurrentWidth);
setCurrentHeight(coolItem.getSize().y);
}
/**
* Sets the current height of the cool item. Update(SIZE) should be called
* to adjust the widget.
*
* @param currentHeight
* the current height to set
*/
public void setCurrentHeight(int currentHeight) {
if (checkDisposed()) { return; }
this.currentHeight = currentHeight;
}
/**
* Sets the current width of the cool item. Update(SIZE) should be called
* to adjust the widget.
*
* @param currentWidth
* the current width to set
*/
public void setCurrentWidth(int currentWidth) {
if (checkDisposed()) { return; }
this.currentWidth = currentWidth;
}
/**
* Sets the minimum number of tool items to show in the cool item. If this
* number is less than the total tool items, a chevron will appear and the
* hidden tool items appear in a drop down menu. By default, all the tool
* items are shown in the cool item.
*
* @param minimumItemsToShow
* the minimum number of tool items to show.
* @see #getMinimumItemsToShow()
* @see #setUseChevron(boolean)
*/
public void setMinimumItemsToShow(int minimumItemsToShow) {
if (checkDisposed()) { return; }
this.minimumItemsToShow = minimumItemsToShow;
}
/**
* Enables or disables chevron support for the cool item. By default,
* chevron support is enabled.
*
* @param value
* <code>true</code> to enable chevron support, <code>false</code>
* otherwise.
*/
public void setUseChevron(boolean value) {
if (checkDisposed()) { return; }
useChevron = value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IContributionItem#update(java.lang.String)
*/
public void update(String propertyName) {
if (checkDisposed()) { return; }
if (coolItem != null) {
IToolBarManager manager = getToolBarManager();
if (manager != null) {
manager.update(true);
}
if ((propertyName == null)
|| propertyName.equals(ICoolBarManager.SIZE)) {
updateSize(true);
}
}
}
/**
* Updates the cool items' preferred, minimum, and current size. The
* preferred size is calculated based on the tool bar size and extra trim.
*
* @param changeCurrentSize
* <code>true</code> if the current size should be changed to
* the preferred size, <code>false</code> to not change the
* current size
*/
public void updateSize(boolean changeCurrentSize) {
if (checkDisposed()) { return; }
// cannot set size if coolItem is null
if (coolItem == null || coolItem.isDisposed()) { return; }
boolean locked = false;
CoolBar coolBar = coolItem.getParent();
try {
// Fix odd behaviour with locked tool bars
if (coolBar != null) {
if (coolBar.getLocked() == true) {
coolBar.setLocked(false);
locked = true;
}
}
ToolBar toolBar = (ToolBar) coolItem.getControl();
if ((toolBar == null) || (toolBar.isDisposed())
|| (toolBar.getItemCount() <= 0)) {
// if the toolbar does not contain any items then dispose of
// coolItem
coolItem.setData(null);
Control control = coolItem.getControl();
if ((control != null) && !control.isDisposed()) {
control.dispose();
coolItem.setControl(null);
}
if (!coolItem.isDisposed()) {
coolItem.dispose();
}
} else {
// If the toolbar item exists then adjust the size of the cool
// item
Point toolBarSize = toolBar.computeSize(SWT.DEFAULT,
SWT.DEFAULT);
// Set the preffered size to the size of the toolbar plus trim
Point prefferedSize = coolItem.computeSize(toolBarSize.x,
toolBarSize.y);
coolItem.setPreferredSize(prefferedSize);
// note setMinimumSize must be called before setSize, see PR
// 15565
// Set minimum size
if (getMinimumItemsToShow() != SHOW_ALL_ITEMS) {
int toolItemWidth = toolBar.getItems()[1].getWidth();
int minimumWidth = toolItemWidth * getMinimumItemsToShow();
coolItem.setMinimumSize(minimumWidth, toolBarSize.y);
} else {
coolItem.setMinimumSize(toolBarSize.x, toolBarSize.y);
}
if (changeCurrentSize) {
// Set current size to preffered size
coolItem.setSize(prefferedSize);
}
}
} finally {
// If the cool bar was locked, then set it back to locked
if ((locked) && (coolBar != null)) {
coolBar.setLocked(true);
}
}
}
}
| true | true | public void fill(CoolBar coolBar, int index) {
if (checkDisposed()) { return; }
if (coolItem == null && coolBar != null) {
ToolBar oldToolBar = toolBarManager.getControl();
ToolBar toolBar = toolBarManager.createControl(coolBar);
if ((oldToolBar != null) && (!oldToolBar.equals(toolBar))) {
// We are using a new tool bar, so we need to update.
toolBarManager.update(true);
}
// Do not create a coolItem if the toolbar is empty
if (toolBar.getItemCount() < 1) return;
int flags = SWT.DROP_DOWN;
if (index >= 0) {
coolItem = new CoolItem(coolBar, flags, index);
} else {
coolItem = new CoolItem(coolBar, flags);
}
// sets the back reference
coolItem.setData(this);
// Add the toolbar to the CoolItem widget
coolItem.setControl(toolBar);
// Handle Context Menu
toolBar.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
// if the toolbar does not have its own context menu then
// handle the event
if (toolBarManager.getContextMenuManager() == null) {
handleContextMenu(event);
}
}
});
// Handle for chevron clicking
if (getUseChevron()) {
// Chevron Support
coolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (event.detail == SWT.ARROW) {
handleChevron(event);
}
}
});
}
// Handle for disposal
coolItem.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
handleWidgetDispose(event);
}
});
// Sets the size of the coolItem
updateSize(true);
}
}
| public void fill(CoolBar coolBar, int index) {
if (checkDisposed()) { return; }
if (coolItem == null && coolBar != null) {
ToolBar oldToolBar = toolBarManager.getControl();
ToolBar toolBar = toolBarManager.createControl(coolBar);
if ((oldToolBar != null) && (oldToolBar.equals(toolBar))) {
// We are using an old tool bar, so we need to update.
toolBarManager.update(true);
}
// Do not create a coolItem if the toolbar is empty
if (toolBar.getItemCount() < 1) return;
int flags = SWT.DROP_DOWN;
if (index >= 0) {
coolItem = new CoolItem(coolBar, flags, index);
} else {
coolItem = new CoolItem(coolBar, flags);
}
// sets the back reference
coolItem.setData(this);
// Add the toolbar to the CoolItem widget
coolItem.setControl(toolBar);
// Handle Context Menu
toolBar.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
// if the toolbar does not have its own context menu then
// handle the event
if (toolBarManager.getContextMenuManager() == null) {
handleContextMenu(event);
}
}
});
// Handle for chevron clicking
if (getUseChevron()) {
// Chevron Support
coolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (event.detail == SWT.ARROW) {
handleChevron(event);
}
}
});
}
// Handle for disposal
coolItem.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
handleWidgetDispose(event);
}
});
// Sets the size of the coolItem
updateSize(true);
}
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java
index e2787175..b5d3afa9 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java
@@ -1,61 +1,62 @@
/*
* 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.shindig.gadgets.templates;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.google.inject.Inject;
/**
* TagHandler for the <os:Name person="..."/> tag.
*/
public class NameTagHandler extends AbstractTagHandler {
static final String TAG_NAME = "Name";
static final String PERSON_ATTR = "person";
@Inject
public NameTagHandler() {
super(TagHandler.OPENSOCIAL_NAMESPACE, TAG_NAME);
}
public void process(Node result, Element tag, TemplateProcessor processor) {
JSONObject person = getValueFromTag(tag, PERSON_ATTR, processor, JSONObject.class);
if (person == null) {
return;
}
JSONObject name = person.optJSONObject("name");
if (name == null) {
return;
}
String formatted = name.optString("formatted");
if (formatted.length() == 0) {
formatted = name.optString("givenName") + " " + name.optString("familyName");
}
Document doc = result.getOwnerDocument();
Element root = doc.createElement("b");
+ result.appendChild(root);
appendTextNode(root, formatted);
}
}
| true | true | public void process(Node result, Element tag, TemplateProcessor processor) {
JSONObject person = getValueFromTag(tag, PERSON_ATTR, processor, JSONObject.class);
if (person == null) {
return;
}
JSONObject name = person.optJSONObject("name");
if (name == null) {
return;
}
String formatted = name.optString("formatted");
if (formatted.length() == 0) {
formatted = name.optString("givenName") + " " + name.optString("familyName");
}
Document doc = result.getOwnerDocument();
Element root = doc.createElement("b");
appendTextNode(root, formatted);
}
| public void process(Node result, Element tag, TemplateProcessor processor) {
JSONObject person = getValueFromTag(tag, PERSON_ATTR, processor, JSONObject.class);
if (person == null) {
return;
}
JSONObject name = person.optJSONObject("name");
if (name == null) {
return;
}
String formatted = name.optString("formatted");
if (formatted.length() == 0) {
formatted = name.optString("givenName") + " " + name.optString("familyName");
}
Document doc = result.getOwnerDocument();
Element root = doc.createElement("b");
result.appendChild(root);
appendTextNode(root, formatted);
}
|
diff --git a/src/main/java/com/thisisdinosaur/protosaurus/shared/ResourceNodeDrawer.java b/src/main/java/com/thisisdinosaur/protosaurus/shared/ResourceNodeDrawer.java
index 64281f7..a67e36f 100644
--- a/src/main/java/com/thisisdinosaur/protosaurus/shared/ResourceNodeDrawer.java
+++ b/src/main/java/com/thisisdinosaur/protosaurus/shared/ResourceNodeDrawer.java
@@ -1,55 +1,55 @@
package com.thisisdinosaur.protosaurus.shared;
import java.awt.Color;
import java.awt.Graphics2D;
import com.thisisdinosaur.protosaurus.client.Displayable;
public class ResourceNodeDrawer implements Displayable
{
private static final Color DEFAULT_CITY_COLOUR = Color.magenta;
private static final int CITY_DIAMETER = 20;
private ResourceNodeEntity gameEntity;
public ResourceNodeDrawer(ResourceNodeEntity gameEntity)
{
this.gameEntity = gameEntity;
}
@Override
public void draw(Graphics2D g)
{
if(gameEntity.getOwner() == null)
{
g.setColor(DEFAULT_CITY_COLOUR);
}
else
{
g.setColor(Color.CYAN);
}
- g.fillOval(CITY_DIAMETER * -2, CITY_DIAMETER * -2, CITY_DIAMETER, CITY_DIAMETER);
+ g.fillOval(-CITY_DIAMETER / 2, -CITY_DIAMETER / 2, CITY_DIAMETER, CITY_DIAMETER);
}
@Override
public float getX()
{
return this.gameEntity.getX();
}
@Override
public float getY()
{
return this.gameEntity.getY();
}
@Override
public float getRotation()
{
//As of right now cities are just circles, so their rotation is meaningless.
return 0;
}
}
| true | true | public void draw(Graphics2D g)
{
if(gameEntity.getOwner() == null)
{
g.setColor(DEFAULT_CITY_COLOUR);
}
else
{
g.setColor(Color.CYAN);
}
g.fillOval(CITY_DIAMETER * -2, CITY_DIAMETER * -2, CITY_DIAMETER, CITY_DIAMETER);
}
| public void draw(Graphics2D g)
{
if(gameEntity.getOwner() == null)
{
g.setColor(DEFAULT_CITY_COLOUR);
}
else
{
g.setColor(Color.CYAN);
}
g.fillOval(-CITY_DIAMETER / 2, -CITY_DIAMETER / 2, CITY_DIAMETER, CITY_DIAMETER);
}
|
diff --git a/src/jag/kumamoto/apps/StampRally/LocationInfoActivity.java b/src/jag/kumamoto/apps/StampRally/LocationInfoActivity.java
index 692b1c9..2222752 100644
--- a/src/jag/kumamoto/apps/StampRally/LocationInfoActivity.java
+++ b/src/jag/kumamoto/apps/StampRally/LocationInfoActivity.java
@@ -1,423 +1,423 @@
package jag.kumamoto.apps.StampRally;
import java.io.IOException;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;
import jag.kumamoto.apps.StampRally.Data.QuizData;
import jag.kumamoto.apps.StampRally.Data.StampPin;
import jag.kumamoto.apps.StampRally.Data.StampRallyURL;
import jag.kumamoto.apps.StampRally.Data.User;
import jag.kumamoto.apps.StampRally.Data.UserRecord;
import jag.kumamoto.apps.gotochi.R;
import aharisu.util.DataGetter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
/**
*
* スタンプラリーのチェックポイントの情報を表示するアクティビティ
*
* @author aharisu
*
*/
public class LocationInfoActivity extends Activity{
private static final int MenuItemGoForward = 1;
private static final int RequestLogin = 0;
private User mUser;
private StampPin mPin;
private QuizData[] mQuizes;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if(extras == null) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
mPin = (StampPin)extras.getParcelable(ConstantValue.ExtrasStampPin);
boolean isShowGoQuiz = extras.getBoolean(ConstantValue.ExtrasShowGoQuiz, false);
boolean isArrive = extras.getBoolean(ConstantValue.ExtrasIsArrive, false);
if(mPin == null) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
mUser = extras.getParcelable(ConstantValue.ExtrasUser);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.location_infomation);
//WebViewの設定
WebView webInfo = (WebView)findViewById(R.id_location_info.webview);
webInfo.setWebViewClient(new WebViewClient() {
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("http")) {
view.loadUrl(url);
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
});
webInfo.setWebChromeClient(new WebChromeClient() {
@Override public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
ProgressBar progress = (ProgressBar)findViewById(R.id_location_info.webView_progress);
if(newProgress < 85) {
if(progress.getVisibility() == View.GONE) {
progress.setVisibility(View.VISIBLE);
}
progress.setProgress(newProgress);
} else {
progress.setVisibility(View.GONE);
}
}
});
WebSettings settings = webInfo.getSettings();
settings.setJavaScriptEnabled(true);
webInfo.loadUrl(getInfomationURL(mPin));
//クイズを表示できる状態ならボタンを表示
View goQuizFrame = findViewById(R.id_location_info.go_quiz_frame);
if(isShowGoQuiz) {
goQuizFrame.setVisibility(View.VISIBLE);
findViewById(R.id_location_info.progress_frame).setVisibility(View.VISIBLE);
Button goQuiz = (Button)findViewById(R.id_location_info.go_quiz);
goQuiz.setEnabled(false);
goQuiz.setText(null);
goQuiz.setOnClickListener(createGoQuizOnClickListener());
getAsyncQuizDataFromServer(mPin);
} else {
goQuizFrame.setVisibility(View.GONE);
}
//この場所に到着していれば到着報告を送信するボタンを表示
//また到着していなければ、この場所へ行くボタンを表示
View goLocation = findViewById(R.id_location_info.go_location_frame);
View btnArriveReport = findViewById(R.id_location_info.arrive_report);
if(isArrive) {
- if(StampRallyPreferences.getShowUrgeDialog()) {
+ if(mUser != null || StampRallyPreferences.getShowUrgeDialog()) {
goLocation.setVisibility(View.GONE);
btnArriveReport.setVisibility(View.VISIBLE);
btnArriveReport.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
if(mUser == null) {
showUrgeLoginDialog();
} else {
addUserRecord();
sendAsyncArrivedMessaeg();
}
}
});
} else {
goLocation.setVisibility(View.GONE);
btnArriveReport.setVisibility(View.GONE);
}
} else {
goLocation.setVisibility(View.VISIBLE);
btnArriveReport.setVisibility(View.GONE);
findViewById(R.id_location_info.go_location).setOnClickListener(createOnRouteSearachClickListener());
Spinner routeSearchKind = (Spinner)findViewById(R.id_location_info.route_search_kind);
routeSearchKind.setSelection(StampRallyPreferences.getRouteSearchKind());
routeSearchKind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
StampRallyPreferences.setRouteSearchKind(position);
}
@Override public void onNothingSelected(AdapterView<?> parent) {
parent.setSelection(0);
}
});
}
}
private String getInfomationURL(StampPin pin) {
return (pin.url != null && !pin.url.equals("") && !pin.url.equals("null")) ?
pin.url :
new StringBuilder("http://ja.wikipedia.org/wiki/")
.append(URLEncoder.encode(pin.name))
.toString();
}
private View.OnClickListener createGoQuizOnClickListener() {
return new View.OnClickListener() {
@Override public void onClick(View v) {
if(mQuizes == null) {
//TORO 何かがおかしいぞと表示
return;
}
Intent intent = new Intent(LocationInfoActivity.this, QuizActivity.class);
intent.putExtra(ConstantValue.ExtrasQuizData, mQuizes);
if(mUser != null) {
intent.putExtra(ConstantValue.ExtrasUser, mUser);
}
startActivity(intent);
}
};
}
private void getAsyncQuizDataFromServer(final StampPin pin) {
new AsyncTask<Void, Void, QuizData[]>() {
@Override protected QuizData[] doInBackground(Void... params) {
QuizData[] quizes = null;
try {
JSONObject obj = DataGetter.getJSONObject(StampRallyURL.getQuizesQuery(pin));
if(StampRallyURL.isSuccess(obj)) {
quizes = QuizData.decodeJSONObject(obj);
} else {
//XXX サーバとの通信失敗(クエリの間違い?)
Log.e("get quizes", obj.toString());
}
} catch (IOException e) {
//XXX ネットワーク通信の失敗
e.printStackTrace();
} catch (JSONException e) {
//XXX JSONフォーマットエラー
e.printStackTrace();
}
return quizes;
}
@Override protected void onPostExecute(QuizData[] result) {
super.onPostExecute(result);
setgettedQuizData(result);
}
}.execute((Void)null);
}
private void setgettedQuizData(QuizData[] quizes) {
mQuizes = quizes;
findViewById(R.id_location_info.progress_frame).setVisibility(View.GONE);
if(mQuizes == null) {
//TODO クイズデータの取得に失敗した
//エラー表示
Log.e("quizData" , "get failure");
return;
}
Button goQuiz = (Button)findViewById(R.id_location_info.go_quiz);
goQuiz.setEnabled(true);
goQuiz.setText("クイズへGo!!");
}
private View.OnClickListener createOnRouteSearachClickListener() {
return new View.OnClickListener() {
@Override public void onClick(View v) {
long id = ((Spinner)findViewById(R.id_location_info.route_search_kind)).getSelectedItemId();
String[] routeSearchKind = new String[] {"d", "r", "w"};
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
String uri = new StringBuilder("http://maps.google.com/maps?myl=saddr")
.append("&dirflg=").append(routeSearchKind[(int) (id < 3 ? id : 0)])
.append("&daddr=").append(mPin.latitude * 1e-6f).append(",").append(mPin.longitude * 1e-6f)
.toString();
intent.setData(Uri.parse(uri));
startActivity(intent);
}
};
}
private void showUrgeLoginDialog() {
View layout = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.location_urge_login_dialog_content, null);
((CheckBox)layout.findViewById(R.id_location_info.not_show_next_time)).setChecked(!StampRallyPreferences.getShowUrgeDialog());
((CheckBox)layout.findViewById(R.id_location_info.not_show_next_time)).setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
StampRallyPreferences.setShowUrgeDialog(!isChecked);
if(isChecked) {
Toast.makeText(LocationInfoActivity.this,
"設定画面でこのオプションを変更できます", Toast.LENGTH_LONG).show();
}
}
});
new AlertDialog.Builder(this)
.setTitle("ログインしていません")
.setView(layout)
.setPositiveButton("ログインする", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(LocationInfoActivity.this, SettingsActivity.class);
intent.putExtra(ConstantValue.ExtrasLoginRequest, true);
startActivityForResult(intent, RequestLogin);
}
})
.setNegativeButton("取り消し", null)
.show();
}
private void addUserRecord() {
boolean[] arrived = StampRallyDB.checkPinNonArrive(mPin.id);
if(arrived[0]) {
UserRecord record = StampRallyPreferences.getUserRecord();
record.point += mPin.point;
record.numStamp += 1;
StampRallyPreferences.setUserRecord(record);
}
}
private void sendAsyncArrivedMessaeg() {
Toast.makeText(LocationInfoActivity.this, "到着確認を送信します", Toast.LENGTH_SHORT).show();
final String query = StampRallyURL.getArriveQuery(mUser, mPin);
final View btnArriveReport = findViewById(R.id_location_info.arrive_report);
btnArriveReport.setEnabled(false);
new AsyncTask<Void, Void, Boolean>() {
@Override protected Boolean doInBackground(Void... params) {
try {
JSONObject obj = DataGetter.getJSONObject(query);
if(StampRallyURL.isSuccess(obj)) {
return true;
} else {
//XXX サーバとの通信失敗(クエリの間違い?)
Log.e("arrive data", obj.toString());
}
} catch (IOException e) {
//XXX ネットワーク通信の失敗
e.printStackTrace();
} catch (JSONException e) {
//XXX JSONフォーマットが不正
e.printStackTrace();
}
return false;
}
@Override protected void onPostExecute(Boolean result) {
if(result) {
btnArriveReport.setVisibility(View.GONE);
} else {
//TODO 到着データ送信に失敗
//さてどうしよう
Log.i("arrive data", "failure");
btnArriveReport.setEnabled(true);
}
Toast.makeText(LocationInfoActivity.this, result ?
"到着完了!" : "あれ?ネットワークの調子がおかしいぞ",
Toast.LENGTH_SHORT).show();
}
}.execute((Void)null);
}
//WebViewを操作するメニュー
@Override public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MenuItemGoForward, 0, "進む").setIcon(R.drawable.ic_menu_forward);
return super.onCreateOptionsMenu(menu);
}
@Override public boolean onMenuOpened(int featureId, Menu menu) {
WebView webInfo = (WebView)findViewById(R.id_location_info.webview);
menu.findItem(MenuItemGoForward).setEnabled(webInfo.canGoForward());
return super.onMenuOpened(featureId, menu);
}
@Override public boolean onMenuItemSelected(int featureId, MenuItem item) {
if(item.getItemId() == MenuItemGoForward) {
//進む履歴があれば次ページに進む
WebView webInfo = (WebView)findViewById(R.id_location_info.webview);
if(webInfo.canGoForward()) {
webInfo.goForward();
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
//戻る履歴があれば前ページに戻る
WebView webInfo = (WebView)findViewById(R.id_location_info.webview);
if(webInfo.canGoBack()) {
webInfo.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RequestLogin) {
if(resultCode == Activity.RESULT_OK) {
User user = data.getExtras().getParcelable(ConstantValue.ExtrasUser);
if(user != null) {
mUser = user;
addUserRecord();
sendAsyncArrivedMessaeg();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| true | true | @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if(extras == null) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
mPin = (StampPin)extras.getParcelable(ConstantValue.ExtrasStampPin);
boolean isShowGoQuiz = extras.getBoolean(ConstantValue.ExtrasShowGoQuiz, false);
boolean isArrive = extras.getBoolean(ConstantValue.ExtrasIsArrive, false);
if(mPin == null) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
mUser = extras.getParcelable(ConstantValue.ExtrasUser);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.location_infomation);
//WebViewの設定
WebView webInfo = (WebView)findViewById(R.id_location_info.webview);
webInfo.setWebViewClient(new WebViewClient() {
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("http")) {
view.loadUrl(url);
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
});
webInfo.setWebChromeClient(new WebChromeClient() {
@Override public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
ProgressBar progress = (ProgressBar)findViewById(R.id_location_info.webView_progress);
if(newProgress < 85) {
if(progress.getVisibility() == View.GONE) {
progress.setVisibility(View.VISIBLE);
}
progress.setProgress(newProgress);
} else {
progress.setVisibility(View.GONE);
}
}
});
WebSettings settings = webInfo.getSettings();
settings.setJavaScriptEnabled(true);
webInfo.loadUrl(getInfomationURL(mPin));
//クイズを表示できる状態ならボタンを表示
View goQuizFrame = findViewById(R.id_location_info.go_quiz_frame);
if(isShowGoQuiz) {
goQuizFrame.setVisibility(View.VISIBLE);
findViewById(R.id_location_info.progress_frame).setVisibility(View.VISIBLE);
Button goQuiz = (Button)findViewById(R.id_location_info.go_quiz);
goQuiz.setEnabled(false);
goQuiz.setText(null);
goQuiz.setOnClickListener(createGoQuizOnClickListener());
getAsyncQuizDataFromServer(mPin);
} else {
goQuizFrame.setVisibility(View.GONE);
}
//この場所に到着していれば到着報告を送信するボタンを表示
//また到着していなければ、この場所へ行くボタンを表示
View goLocation = findViewById(R.id_location_info.go_location_frame);
View btnArriveReport = findViewById(R.id_location_info.arrive_report);
if(isArrive) {
if(StampRallyPreferences.getShowUrgeDialog()) {
goLocation.setVisibility(View.GONE);
btnArriveReport.setVisibility(View.VISIBLE);
btnArriveReport.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
if(mUser == null) {
showUrgeLoginDialog();
} else {
addUserRecord();
sendAsyncArrivedMessaeg();
}
}
});
} else {
goLocation.setVisibility(View.GONE);
btnArriveReport.setVisibility(View.GONE);
}
} else {
goLocation.setVisibility(View.VISIBLE);
btnArriveReport.setVisibility(View.GONE);
findViewById(R.id_location_info.go_location).setOnClickListener(createOnRouteSearachClickListener());
Spinner routeSearchKind = (Spinner)findViewById(R.id_location_info.route_search_kind);
routeSearchKind.setSelection(StampRallyPreferences.getRouteSearchKind());
routeSearchKind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
StampRallyPreferences.setRouteSearchKind(position);
}
@Override public void onNothingSelected(AdapterView<?> parent) {
parent.setSelection(0);
}
});
}
}
| @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if(extras == null) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
mPin = (StampPin)extras.getParcelable(ConstantValue.ExtrasStampPin);
boolean isShowGoQuiz = extras.getBoolean(ConstantValue.ExtrasShowGoQuiz, false);
boolean isArrive = extras.getBoolean(ConstantValue.ExtrasIsArrive, false);
if(mPin == null) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
}
mUser = extras.getParcelable(ConstantValue.ExtrasUser);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.location_infomation);
//WebViewの設定
WebView webInfo = (WebView)findViewById(R.id_location_info.webview);
webInfo.setWebViewClient(new WebViewClient() {
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("http")) {
view.loadUrl(url);
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
});
webInfo.setWebChromeClient(new WebChromeClient() {
@Override public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
ProgressBar progress = (ProgressBar)findViewById(R.id_location_info.webView_progress);
if(newProgress < 85) {
if(progress.getVisibility() == View.GONE) {
progress.setVisibility(View.VISIBLE);
}
progress.setProgress(newProgress);
} else {
progress.setVisibility(View.GONE);
}
}
});
WebSettings settings = webInfo.getSettings();
settings.setJavaScriptEnabled(true);
webInfo.loadUrl(getInfomationURL(mPin));
//クイズを表示できる状態ならボタンを表示
View goQuizFrame = findViewById(R.id_location_info.go_quiz_frame);
if(isShowGoQuiz) {
goQuizFrame.setVisibility(View.VISIBLE);
findViewById(R.id_location_info.progress_frame).setVisibility(View.VISIBLE);
Button goQuiz = (Button)findViewById(R.id_location_info.go_quiz);
goQuiz.setEnabled(false);
goQuiz.setText(null);
goQuiz.setOnClickListener(createGoQuizOnClickListener());
getAsyncQuizDataFromServer(mPin);
} else {
goQuizFrame.setVisibility(View.GONE);
}
//この場所に到着していれば到着報告を送信するボタンを表示
//また到着していなければ、この場所へ行くボタンを表示
View goLocation = findViewById(R.id_location_info.go_location_frame);
View btnArriveReport = findViewById(R.id_location_info.arrive_report);
if(isArrive) {
if(mUser != null || StampRallyPreferences.getShowUrgeDialog()) {
goLocation.setVisibility(View.GONE);
btnArriveReport.setVisibility(View.VISIBLE);
btnArriveReport.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
if(mUser == null) {
showUrgeLoginDialog();
} else {
addUserRecord();
sendAsyncArrivedMessaeg();
}
}
});
} else {
goLocation.setVisibility(View.GONE);
btnArriveReport.setVisibility(View.GONE);
}
} else {
goLocation.setVisibility(View.VISIBLE);
btnArriveReport.setVisibility(View.GONE);
findViewById(R.id_location_info.go_location).setOnClickListener(createOnRouteSearachClickListener());
Spinner routeSearchKind = (Spinner)findViewById(R.id_location_info.route_search_kind);
routeSearchKind.setSelection(StampRallyPreferences.getRouteSearchKind());
routeSearchKind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
StampRallyPreferences.setRouteSearchKind(position);
}
@Override public void onNothingSelected(AdapterView<?> parent) {
parent.setSelection(0);
}
});
}
}
|
diff --git a/src/org/napile/idea/plugin/highlighter/JetColorSettingsPage.java b/src/org/napile/idea/plugin/highlighter/JetColorSettingsPage.java
index 6ba5097..2433724 100644
--- a/src/org/napile/idea/plugin/highlighter/JetColorSettingsPage.java
+++ b/src/org/napile/idea/plugin/highlighter/JetColorSettingsPage.java
@@ -1,185 +1,184 @@
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* 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.napile.idea.plugin.highlighter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import org.jetbrains.annotations.NotNull;
import org.napile.compiler.NapileLanguage;
import org.napile.idea.plugin.JetBundle;
import org.napile.idea.plugin.JetIcons;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.OptionsBundle;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
public class JetColorSettingsPage implements ColorSettingsPage
{
@Override
public Icon getIcon()
{
return JetIcons.SMALL_LOGO;
}
@NotNull
@Override
public SyntaxHighlighter getHighlighter()
{
return new JetHighlighter();
}
@NotNull
@Override
public String getDemoText()
{
return "/* Block comment */\n" +
"<KEYWORD>package</KEYWORD> hello\n" +
"<KEYWORD>import</KEYWORD> kotlin.util.* // line comment\n" +
"\n" +
"/**\n" +
" * Doc comment here for `SomeClass`\n" +
" * @see Iterator#next()\n" +
" */\n" +
"<ANNOTATION>@Deprecated</ANNOTATION>\n" +
"<BUILTIN_ANNOTATION>covered</BUILTIN_ANNOTATION> class <CLASS>MyClass</CLASS><<TYPE_PARAMETER>T</TYPE_PARAMETER> : <CLASS>Iterable</CLASS><<TYPE_PARAMETER>T</TYPE_PARAMETER>>>\n" +
"{\n" +
" meth <FUNCTION_DECLARATION>foo</FUNCTION_DECLARATION>(<PARAMETER>nullable</PARAMETER> : String?, <PARAMETER>r</PARAMETER> : <CLASS>Runnable</CLASS>, <PARAMETER>f</PARAMETER> : () -> Int) {\n" +
" <FUNCTION_CALL><NAMESPACE_FUNCTION_CALL>println</NAMESPACE_FUNCTION_CALL></FUNCTION_CALL>(\"length\\nis ${<PARAMETER>nullable</PARAMETER><SAFE_ACCESS>?.</SAFE_ACCESS><INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>} <INVALID_STRING_ESCAPE><STRING_ESCAPE>\\e</STRING_ESCAPE></INVALID_STRING_ESCAPE>\")\n" +
" final var <LOCAL_VARIABLE>ints</LOCAL_VARIABLE> = java.util.<CONSTRUCTOR_CALL>ArrayList</CONSTRUCTOR_CALL><Int?>(2)\n" +
" <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>[0] = 102 + <PARAMETER>f</PARAMETER>()\n" +
" final var <LOCAL_VARIABLE>myFun</LOCAL_VARIABLE> = <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW> <FUNCTION_LITERAL_BRACES_AND_ARROW>-></FUNCTION_LITERAL_BRACES_AND_ARROW> \"\" <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW>; var <LOCAL_VARIABLE><MUTABLE_VARIABLE><WRAPPED_INTO_REF>ref</WRAPPED_INTO_REF></MUTABLE_VARIABLE></LOCAL_VARIABLE> = <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<FUNCTION_CALL>size</FUNCTION_CALL>()\n" +
" if (!<LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<EXTENSION_PROPERTY><STATIC_PROPERTY>empty</STATIC_PROPERTY></EXTENSION_PROPERTY>) {\n" +
" <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<EXTENSION_FUNCTION_CALL><NAMESPACE_FUNCTION_CALL><FUNCTION_CALL>forEach</FUNCTION_CALL></NAMESPACE_FUNCTION_CALL></EXTENSION_FUNCTION_CALL> @lit <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW>\n" +
" if (<FUNCTION_LITERAL_DEFAULT_PARAMETER>it</FUNCTION_LITERAL_DEFAULT_PARAMETER> == null) return @lit\n" +
" <FUNCTION_CALL><NAMESPACE_FUNCTION_CALL>println</NAMESPACE_FUNCTION_CALL></FUNCTION_CALL>(<FUNCTION_LITERAL_DEFAULT_PARAMETER><AUTO_CASTED_VALUE>it</AUTO_CASTED_VALUE></FUNCTION_LITERAL_DEFAULT_PARAMETER> + <LOCAL_VARIABLE><MUTABLE_VARIABLE><WRAPPED_INTO_REF>ref</WRAPPED_INTO_REF></MUTABLE_VARIABLE></LOCAL_VARIABLE>)\n" +
" <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW>\n" +
" }\n" +
" }\n" +
"}\n" +
"\n" +
"<BUILTIN_ANNOTATION>heritable</BUILTIN_ANNOTATION> <KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS> {\n" +
"}\n" +
" Bad character: \\n\n";
}
@Override
public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap()
{
Map<String, TextAttributesKey> map = new HashMap<String, TextAttributesKey>();
for(Field field : JetHighlightingColors.class.getFields())
{
if(Modifier.isStatic(field.getModifiers()))
{
try
{
map.put(field.getName(), (TextAttributesKey) field.get(null));
}
catch(IllegalAccessException e)
{
assert false;
}
}
}
return map;
}
@NotNull
@Override
public AttributesDescriptor[] getAttributeDescriptors()
{
return new AttributesDescriptor[]{
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.keyword"), JetHighlightingColors.KEYWORD),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.builtin.annotation"), JetHighlightingColors.BUILTIN_ANNOTATION),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.number"), JetHighlightingColors.NUMBER),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.string"), JetHighlightingColors.STRING),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.string.escape"), JetHighlightingColors.STRING_ESCAPE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.invalid.escape.in.string"), JetHighlightingColors.INVALID_STRING_ESCAPE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.operator.sign"), JetHighlightingColors.OPERATOR_SIGN),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.parentheses"), JetHighlightingColors.PARENTHESIS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.braces"), JetHighlightingColors.BRACES),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.closure.braces"), JetHighlightingColors.FUNCTION_LITERAL_BRACES_AND_ARROW),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.arrow"), JetHighlightingColors.ARROW),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.brackets"), JetHighlightingColors.BRACKETS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.comma"), JetHighlightingColors.COMMA),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.semicolon"), JetHighlightingColors.SEMICOLON),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.dot"), JetHighlightingColors.DOT),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.safe.access"), JetHighlightingColors.SAFE_ACCESS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.line.comment"), JetHighlightingColors.LINE_COMMENT),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.block.comment"), JetHighlightingColors.BLOCK_COMMENT),
// KDoc highlighting options are temporarily disabled, until actual highlighting and parsing of them is implemented
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.comment"), JetHighlightingColors.DOC_COMMENT),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.tag"), JetHighlightingColors.DOC_COMMENT_TAG),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.tag.value"), JetHighlightingColors.DOC_COMMENT_TAG_VALUE),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.markup"), JetHighlightingColors.DOC_COMMENT_MARKUP),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.class"), JetHighlightingColors.CLASS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.type.parameter"), JetHighlightingColors.TYPE_PARAMETER),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.abstract.class"), JetHighlightingColors.ABSTRACT_CLASS),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.annotation"), JetHighlightingColors.ANNOTATION),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.var"), JetHighlightingColors.MUTABLE_VARIABLE),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.local.variable"), JetHighlightingColors.LOCAL_VARIABLE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.parameter"), JetHighlightingColors.PARAMETER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.captured.variable"), JetHighlightingColors.WRAPPED_INTO_REF),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.instance.property"), JetHighlightingColors.INSTANCE_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.namespace.property"), JetHighlightingColors.STATIC_PROPERTY),
- new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.property.with.backing"), JetHighlightingColors.PROPERTY_WITH_BACKING_FIELD),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.backing.field.access"), JetHighlightingColors.BACKING_FIELD_ACCESS),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.extension.property"), JetHighlightingColors.EXTENSION_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.it"), JetHighlightingColors.FUNCTION_LITERAL_DEFAULT_PARAMETER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.fun"), JetHighlightingColors.FUNCTION_DECLARATION),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.fun.call"), JetHighlightingColors.METHOD_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.namespace.fun.call"), JetHighlightingColors.STATIC_METHOD_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.extension.fun.call"), JetHighlightingColors.EXTENSION_FUNCTION_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.constructor.call"), JetHighlightingColors.CONSTRUCTOR_CALL),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.bad.character"), JetHighlightingColors.BAD_CHARACTER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.auto.casted"), JetHighlightingColors.AUTO_CASTED_VALUE),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.label"), JetHighlightingColors.LABEL),
};
}
@NotNull
@Override
public ColorDescriptor[] getColorDescriptors()
{
return ColorDescriptor.EMPTY_ARRAY;
}
@NotNull
@Override
public String getDisplayName()
{
return NapileLanguage.NAME;
}
}
| true | true | public AttributesDescriptor[] getAttributeDescriptors()
{
return new AttributesDescriptor[]{
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.keyword"), JetHighlightingColors.KEYWORD),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.builtin.annotation"), JetHighlightingColors.BUILTIN_ANNOTATION),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.number"), JetHighlightingColors.NUMBER),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.string"), JetHighlightingColors.STRING),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.string.escape"), JetHighlightingColors.STRING_ESCAPE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.invalid.escape.in.string"), JetHighlightingColors.INVALID_STRING_ESCAPE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.operator.sign"), JetHighlightingColors.OPERATOR_SIGN),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.parentheses"), JetHighlightingColors.PARENTHESIS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.braces"), JetHighlightingColors.BRACES),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.closure.braces"), JetHighlightingColors.FUNCTION_LITERAL_BRACES_AND_ARROW),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.arrow"), JetHighlightingColors.ARROW),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.brackets"), JetHighlightingColors.BRACKETS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.comma"), JetHighlightingColors.COMMA),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.semicolon"), JetHighlightingColors.SEMICOLON),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.dot"), JetHighlightingColors.DOT),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.safe.access"), JetHighlightingColors.SAFE_ACCESS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.line.comment"), JetHighlightingColors.LINE_COMMENT),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.block.comment"), JetHighlightingColors.BLOCK_COMMENT),
// KDoc highlighting options are temporarily disabled, until actual highlighting and parsing of them is implemented
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.comment"), JetHighlightingColors.DOC_COMMENT),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.tag"), JetHighlightingColors.DOC_COMMENT_TAG),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.tag.value"), JetHighlightingColors.DOC_COMMENT_TAG_VALUE),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.markup"), JetHighlightingColors.DOC_COMMENT_MARKUP),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.class"), JetHighlightingColors.CLASS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.type.parameter"), JetHighlightingColors.TYPE_PARAMETER),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.abstract.class"), JetHighlightingColors.ABSTRACT_CLASS),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.annotation"), JetHighlightingColors.ANNOTATION),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.var"), JetHighlightingColors.MUTABLE_VARIABLE),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.local.variable"), JetHighlightingColors.LOCAL_VARIABLE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.parameter"), JetHighlightingColors.PARAMETER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.captured.variable"), JetHighlightingColors.WRAPPED_INTO_REF),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.instance.property"), JetHighlightingColors.INSTANCE_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.namespace.property"), JetHighlightingColors.STATIC_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.property.with.backing"), JetHighlightingColors.PROPERTY_WITH_BACKING_FIELD),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.backing.field.access"), JetHighlightingColors.BACKING_FIELD_ACCESS),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.extension.property"), JetHighlightingColors.EXTENSION_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.it"), JetHighlightingColors.FUNCTION_LITERAL_DEFAULT_PARAMETER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.fun"), JetHighlightingColors.FUNCTION_DECLARATION),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.fun.call"), JetHighlightingColors.METHOD_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.namespace.fun.call"), JetHighlightingColors.STATIC_METHOD_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.extension.fun.call"), JetHighlightingColors.EXTENSION_FUNCTION_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.constructor.call"), JetHighlightingColors.CONSTRUCTOR_CALL),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.bad.character"), JetHighlightingColors.BAD_CHARACTER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.auto.casted"), JetHighlightingColors.AUTO_CASTED_VALUE),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.label"), JetHighlightingColors.LABEL),
};
}
| public AttributesDescriptor[] getAttributeDescriptors()
{
return new AttributesDescriptor[]{
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.keyword"), JetHighlightingColors.KEYWORD),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.builtin.annotation"), JetHighlightingColors.BUILTIN_ANNOTATION),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.number"), JetHighlightingColors.NUMBER),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.string"), JetHighlightingColors.STRING),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.string.escape"), JetHighlightingColors.STRING_ESCAPE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.invalid.escape.in.string"), JetHighlightingColors.INVALID_STRING_ESCAPE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.operator.sign"), JetHighlightingColors.OPERATOR_SIGN),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.parentheses"), JetHighlightingColors.PARENTHESIS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.braces"), JetHighlightingColors.BRACES),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.closure.braces"), JetHighlightingColors.FUNCTION_LITERAL_BRACES_AND_ARROW),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.arrow"), JetHighlightingColors.ARROW),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.brackets"), JetHighlightingColors.BRACKETS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.comma"), JetHighlightingColors.COMMA),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.semicolon"), JetHighlightingColors.SEMICOLON),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.dot"), JetHighlightingColors.DOT),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.safe.access"), JetHighlightingColors.SAFE_ACCESS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.line.comment"), JetHighlightingColors.LINE_COMMENT),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.block.comment"), JetHighlightingColors.BLOCK_COMMENT),
// KDoc highlighting options are temporarily disabled, until actual highlighting and parsing of them is implemented
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.comment"), JetHighlightingColors.DOC_COMMENT),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.tag"), JetHighlightingColors.DOC_COMMENT_TAG),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.tag.value"), JetHighlightingColors.DOC_COMMENT_TAG_VALUE),
//new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.kdoc.markup"), JetHighlightingColors.DOC_COMMENT_MARKUP),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.class"), JetHighlightingColors.CLASS),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.type.parameter"), JetHighlightingColors.TYPE_PARAMETER),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.abstract.class"), JetHighlightingColors.ABSTRACT_CLASS),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.annotation"), JetHighlightingColors.ANNOTATION),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.var"), JetHighlightingColors.MUTABLE_VARIABLE),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.local.variable"), JetHighlightingColors.LOCAL_VARIABLE),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.parameter"), JetHighlightingColors.PARAMETER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.captured.variable"), JetHighlightingColors.WRAPPED_INTO_REF),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.instance.property"), JetHighlightingColors.INSTANCE_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.namespace.property"), JetHighlightingColors.STATIC_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.backing.field.access"), JetHighlightingColors.BACKING_FIELD_ACCESS),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.extension.property"), JetHighlightingColors.EXTENSION_PROPERTY),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.it"), JetHighlightingColors.FUNCTION_LITERAL_DEFAULT_PARAMETER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.fun"), JetHighlightingColors.FUNCTION_DECLARATION),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.fun.call"), JetHighlightingColors.METHOD_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.namespace.fun.call"), JetHighlightingColors.STATIC_METHOD_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.extension.fun.call"), JetHighlightingColors.EXTENSION_FUNCTION_CALL),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.constructor.call"), JetHighlightingColors.CONSTRUCTOR_CALL),
new AttributesDescriptor(OptionsBundle.message("options.java.attribute.descriptor.bad.character"), JetHighlightingColors.BAD_CHARACTER),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.auto.casted"), JetHighlightingColors.AUTO_CASTED_VALUE),
new AttributesDescriptor(JetBundle.message("options.idea.attribute.descriptor.label"), JetHighlightingColors.LABEL),
};
}
|
diff --git a/src/de/hotmail/gurkilein/bankcraft/database/mysql/ExperienceMysqlInterface.java b/src/de/hotmail/gurkilein/bankcraft/database/mysql/ExperienceMysqlInterface.java
index adfb0ca..d89185b 100644
--- a/src/de/hotmail/gurkilein/bankcraft/database/mysql/ExperienceMysqlInterface.java
+++ b/src/de/hotmail/gurkilein/bankcraft/database/mysql/ExperienceMysqlInterface.java
@@ -1,166 +1,166 @@
package de.hotmail.gurkilein.bankcraft.database.mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import de.hotmail.gurkilein.bankcraft.Bankcraft;
import de.hotmail.gurkilein.bankcraft.database.AccountDatabaseInterface;
public class ExperienceMysqlInterface implements AccountDatabaseInterface <Integer>{
private Connection conn;
@SuppressWarnings("unused")
private Bankcraft bankcraft;
public ExperienceMysqlInterface(Bankcraft bankcraft) {
this.bankcraft = bankcraft;
this.conn = ((DatabaseManagerMysql)bankcraft.getDatabaseManagerInterface()).getConnection();
}
@Override
public boolean hasAccount(String player) {
try {
String sql = "SELECT `player_name` FROM `bc_accounts` WHERE `player_name` = ?";;
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, player.toLowerCase());
ResultSet result = preparedStatement.executeQuery();
while (result.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean createAccount(String player) {
try {
String sql = "INSERT INTO `bc_accounts`(`player_name`, `balance`, `balance_xp`) " +
"VALUES(?, ?, ?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, player.toLowerCase());
preparedStatement.setString(2, "0");
preparedStatement.setString(3, "0");
preparedStatement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public Integer getBalance(String player) {
if (!hasAccount(player.toLowerCase())) {
createAccount(player.toLowerCase());
}
try {
String sql = "SELECT `balance_xp` FROM `bc_accounts` WHERE `player_name` = ?";
PreparedStatement preparedUpdateStatement = conn.prepareStatement(sql);
preparedUpdateStatement.setString(1, player.toLowerCase());
ResultSet result = preparedUpdateStatement.executeQuery();
while (result.next()) {
- return Integer.parseInt(result.getString("balance_xp"));
+ return (int)Double.parseDouble(result.getString("balance_xp"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public boolean setBalance(String player, Integer amount) {
if (!hasAccount(player.toLowerCase())) {
createAccount(player.toLowerCase());
}
try {
String updateSql = "UPDATE `bc_accounts` " +
"SET `balance_xp` = ?" +
"WHERE `player_name` = ?";
PreparedStatement preparedUpdateStatement = conn.prepareStatement(updateSql);
preparedUpdateStatement.setString(1, amount+"");
preparedUpdateStatement.setString(2, player.toLowerCase());
preparedUpdateStatement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean addToAccount(String player, Integer amount) {
if (!hasAccount(player.toLowerCase())) {
createAccount(player.toLowerCase());
}
if (amount < 0) {
return removeFromAccount(player.toLowerCase(), -amount);
}
Integer currentBalance = getBalance(player.toLowerCase());
if (currentBalance <= Integer.MAX_VALUE-amount) {
setBalance(player.toLowerCase(), currentBalance+amount);
return true;
}
return false;
}
@Override
public boolean removeFromAccount(String player, Integer amount) {
if (!hasAccount(player.toLowerCase())) {
createAccount(player.toLowerCase());
}
if (amount < 0) {
return addToAccount(player.toLowerCase(), -amount);
}
Integer currentBalance = getBalance(player.toLowerCase());
if (currentBalance >= Integer.MIN_VALUE+amount) {
setBalance(player.toLowerCase(), currentBalance-amount);
return true;
}
return false;
}
@Override
public String[] getAccounts() {
Statement query;
try {
query = conn.createStatement();
String sql = "SELECT `player_name` FROM `bc_accounts`";
ResultSet result = query.executeQuery(sql);
List <String> loadingList= new ArrayList <String>();
while (result.next()) {
loadingList.add(result.getString("player_name"));
}
return loadingList.toArray(new String [0]);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
| true | true | public Integer getBalance(String player) {
if (!hasAccount(player.toLowerCase())) {
createAccount(player.toLowerCase());
}
try {
String sql = "SELECT `balance_xp` FROM `bc_accounts` WHERE `player_name` = ?";
PreparedStatement preparedUpdateStatement = conn.prepareStatement(sql);
preparedUpdateStatement.setString(1, player.toLowerCase());
ResultSet result = preparedUpdateStatement.executeQuery();
while (result.next()) {
return Integer.parseInt(result.getString("balance_xp"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
| public Integer getBalance(String player) {
if (!hasAccount(player.toLowerCase())) {
createAccount(player.toLowerCase());
}
try {
String sql = "SELECT `balance_xp` FROM `bc_accounts` WHERE `player_name` = ?";
PreparedStatement preparedUpdateStatement = conn.prepareStatement(sql);
preparedUpdateStatement.setString(1, player.toLowerCase());
ResultSet result = preparedUpdateStatement.executeQuery();
while (result.next()) {
return (int)Double.parseDouble(result.getString("balance_xp"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
|
diff --git a/src/info/guardianproject/iocipher/IOCipherFileChannel.java b/src/info/guardianproject/iocipher/IOCipherFileChannel.java
index 6b7d81d..120a839 100644
--- a/src/info/guardianproject/iocipher/IOCipherFileChannel.java
+++ b/src/info/guardianproject/iocipher/IOCipherFileChannel.java
@@ -1,648 +1,649 @@
/* 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 info.guardianproject.iocipher;
import static info.guardianproject.libcore.io.OsConstants.EAGAIN;
import static info.guardianproject.libcore.io.OsConstants.O_ACCMODE;
import static info.guardianproject.libcore.io.OsConstants.O_RDONLY;
import static info.guardianproject.libcore.io.OsConstants.O_WRONLY;
import static info.guardianproject.libcore.io.OsConstants.SEEK_CUR;
import static info.guardianproject.libcore.io.OsConstants.SEEK_END;
import static info.guardianproject.libcore.io.OsConstants.SEEK_SET;
import info.guardianproject.libcore.io.ErrnoException;
import info.guardianproject.libcore.io.Libcore;
import info.guardianproject.libcore.io.StructStat;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ByteChannel;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.channels.spi.AbstractInterruptibleChannel;
/**
* Our implementation of the FileChannel class.
* It supports basic i/o operations, but not everything you
* might be accustomed to from the java NIO classes.
*
* Unsupported operations:
* * mmap
* * file locking
* * scattered reads / gathered writes (io vectors, readv, writev)
*/
public class IOCipherFileChannel extends AbstractInterruptibleChannel implements
ByteChannel {
private final Object stream;
private final FileDescriptor fd;
private final int mode;
/**
* Create a new file channel implementation class that wraps the given fd
* and operates in the specified mode.
*/
public IOCipherFileChannel(Object stream, FileDescriptor fd, int mode) {
this.fd = fd;
this.stream = stream;
this.mode = mode;
}
private void checkOpen() throws ClosedChannelException {
if (!isOpen()) {
throw new ClosedChannelException();
}
}
private void checkReadable() {
if ((mode & O_ACCMODE) == O_WRONLY) {
throw new NonReadableChannelException();
}
}
private void checkWritable() {
if ((mode & O_ACCMODE) == O_RDONLY) {
throw new NonWritableChannelException();
}
}
/**
* Implements the channel closing behavior.
* <p>
* Closes the channel with a guarantee that the channel is not currently
* closed through another invocation of {@code close()} and that the method
* is thread-safe.
* <p>
* Any outstanding threads blocked on I/O operations on this channel must be
* released with either a normal return code, or by throwing an
* {@code AsynchronousCloseException}.
*
* @throws IOException
* if a problem occurs while closing the channel.
*/
@Override
protected void implCloseChannel() throws IOException {
if (stream instanceof Closeable) {
((Closeable) stream).close();
}
}
/**
* Requests that all updates to this channel are committed to the storage
* device.
* <p>
* When this method returns, all modifications made to the platform file
* underlying this channel have been committed if the file resides on a
* local storage device. If the file is not hosted locally, for example on a
* networked file system, then applications cannot be certain that the
* modifications have been committed.
* <p>
* There are no assurances given that changes made to the file using methods
* defined elsewhere will be committed. For example, changes made via a
* mapped byte buffer may not be committed.
* <p>
* The <code>metadata</code> parameter indicates whether the update should
* include the file's metadata such as last modification time, last access
* time, etc. Note that passing <code>true</code> may invoke an underlying
* write to the operating system (if the platform is maintaining metadata
* such as last access time), even if the channel is opened read-only.
*
* @param metadata
* {@code true} if the file metadata should be flushed in
* addition to the file content, {@code false} otherwise.
* @throws ClosedChannelException
* if this channel is already closed.
* @throws IOException
* if another I/O error occurs.
*/
public void force(boolean metadata) throws IOException {
checkOpen();
if ((mode & O_ACCMODE) != O_RDONLY) {
try {
Libcore.os.fsync(fd); // FUSE only has fsync, not fdatasync
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsIOException();
}
}
}
/**
* IOCipher version of POSIX lseek, since the underlying FUSE layer does not
* track the position in open files for us, we do it inside of this class.
* This class wraps a {@link FileDescriptor}, so you cannot specify one as
* an argument.
*
* @param offset
* the new position to seek to.
* @param whence
* changes the pointer repositioning behavior:
* <ul>
* <li>if
* {@link info.guardianproject.libcore.io.OsConstants.SEEK_SET
* SEEK_SET} then file pointer is set to <i>offset</i></li>
* <li>if
* {@link info.guardianproject.libcore.io.OsConstants.SEEK_CUR
* SEEK_CUR} then file pointer is set to <i>current position +
* offset</i></li>
* <li>if
* {@link info.guardianproject.libcore.io.OsConstants.SEEK_END
* SEEK_END} then file pointer is set to <i>file size +
* offset</i></li>
* </ul>
*
* @throws ClosedChannelException
* if this channel is already closed.
*
* @return new position of file pointer
*/
public long lseek(long offset, int whence) throws IOException {
checkOpen();
long tmpPosition = fd.position;
if (whence == SEEK_SET) {
tmpPosition = offset;
} else if (whence == SEEK_CUR) {
tmpPosition += offset;
} else if (whence == SEEK_END) {
tmpPosition = size() + offset;
} else {
throw new IllegalArgumentException("Unknown 'whence': " + whence);
}
if (tmpPosition < 0)
throw new IOException("negative resulting position: " + tmpPosition);
else
fd.position = tmpPosition;
return fd.position;
}
/**
* Returns the current value of the file position pointer.
*
* @return the current position as a positive integer number of bytes from
* the start of the file.
* @throws ClosedChannelException
* if this channel is closed.
*/
public long position() throws IOException {
checkOpen();
return fd.position;
}
/**
* Sets the file position pointer to a new value.
* <p>
* The argument is the number of bytes counted from the start of the file.
* The position cannot be set to a value that is negative. The new position
* can be set beyond the current file size. If set beyond the current file
* size, attempts to read will return end of file. Write operations will
* succeed but they will fill the bytes between the current end of file and
* the new position with the required number of (unspecified) byte values.
*
* @param newPosition
* the new file position, in bytes.
* @return the receiver.
* @throws IllegalArgumentException
* if the new position is negative.
* @throws ClosedChannelException
* if this channel is closed.
*/
public IOCipherFileChannel position(long newPosition) throws IOException {
if (newPosition < 0)
throw new IllegalArgumentException(
"negative file position not allowed: " + newPosition);
checkOpen();
fd.position = newPosition;
return this;
}
private int readImpl(ByteBuffer buffer, long position) throws IOException {
- // buffer.checkWritable(); // TODO ByteBuffer.checkWritable() is
- // protected
+ if(buffer.isReadOnly()) {
+ throw new IllegalArgumentException("read-only buffer");
+ }
checkOpen();
checkReadable();
if (!buffer.hasRemaining()) {
return 0;
}
int bytesRead = 0;
boolean completed = false;
try {
begin();
try {
if (position == -1) {
bytesRead = Libcore.os.read(fd, buffer);
} else {
bytesRead = Libcore.os.pread(fd, buffer, position);
}
if (bytesRead == 0) {
bytesRead = -1;
}
} catch (ErrnoException errnoException) {
if (errnoException.errno == EAGAIN) {
// We don't throw if we try to read from an empty
// non-blocking pipe.
bytesRead = 0;
} else {
throw errnoException.rethrowAsIOException();
}
}
completed = true;
} finally {
end(completed && bytesRead >= 0);
}
if (bytesRead > 0) {
buffer.position(buffer.position() + bytesRead);
}
return bytesRead;
}
/**
* Reads bytes from this file channel into the given buffer.
* <p>
* The maximum number of bytes that will be read is the remaining number of
* bytes in the buffer when the method is invoked. The bytes will be copied
* into the buffer starting at the buffer's current position.
* <p>
* The call may block if other threads are also attempting to read from this
* channel.
* <p>
* Upon completion, the buffer's position is set to the end of the bytes
* that have been read. The buffer's limit is not changed.
*
* @param buffer
* the byte buffer to receive the bytes.
* @return the number of bytes actually read.
* @throws AsynchronousCloseException
* if another thread closes the channel during the read.
* @throws ClosedByInterruptException
* if another thread interrupts the calling thread during the
* read.
* @throws ClosedChannelException
* if this channel is closed.
* @throws IOException
* if another I/O error occurs, details are in the message.
* @throws NonReadableChannelException
* if the channel has not been opened in a mode that permits
* reading.
*/
@Override
public int read(ByteBuffer buffer) throws IOException {
return readImpl(buffer, -1);
}
/**
* Reads bytes from this file channel into the given buffer starting from
* the specified file position.
* <p>
* The bytes are read starting at the given file position (up to the
* remaining number of bytes in the buffer). The number of bytes actually
* read is returned.
* <p>
* If {@code position} is beyond the current end of file, then no bytes are
* read.
* <p>
* Note that the file position is unmodified by this method.
*
* @param buffer
* the buffer to receive the bytes.
* @param position
* the (non-negative) position at which to read the bytes.
* @return the number of bytes actually read.
* @throws AsynchronousCloseException
* if this channel is closed by another thread while this method
* is executing.
* @throws ClosedByInterruptException
* if another thread interrupts the calling thread while this
* operation is in progress. The calling thread will have the
* interrupt state set, and the channel will be closed.
* @throws ClosedChannelException
* if this channel is closed.
* @throws IllegalArgumentException
* if <code>position</code> is less than 0.
* @throws IOException
* if another I/O error occurs.
* @throws NonReadableChannelException
* if the channel has not been opened in a mode that permits
* reading.
*/
public int read(ByteBuffer buffer, long position) throws IOException {
if (position < 0)
throw new IllegalArgumentException(
"negative file position not allowed: " + position);
return readImpl(buffer, position);
}
/**
* Returns the size of the file underlying this channel in bytes.
*
* @return the size of the file in bytes.
* @throws ClosedChannelException
* if this channel is closed.
* @throws IOException
* if an I/O error occurs while getting the size of the file.
*/
public long size() throws IOException {
try {
StructStat sb = Libcore.os.fstat(fd);
return sb.st_size;
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsIOException();
}
}
private int writeImpl(ByteBuffer buffer, long position) throws IOException {
checkOpen();
checkWritable();
if (buffer == null) {
throw new NullPointerException("buffer == null");
}
if (!buffer.hasRemaining()) {
return 0;
}
int bytesWritten = 0;
boolean completed = false;
try {
begin();
try {
if (position == -1) {
bytesWritten = Libcore.os.write(fd, buffer);
} else {
bytesWritten = Libcore.os.pwrite(fd, buffer, position);
}
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsIOException();
}
completed = true;
} finally {
end(completed);
}
if (bytesWritten > 0) {
buffer.position(buffer.position() + bytesWritten);
}
return bytesWritten;
}
/**
* Writes bytes from the given byte buffer to this file channel.
* <p>
* The bytes are written starting at the current file position, and after
* some number of bytes are written (up to the remaining number of bytes in
* the buffer) the file position is increased by the number of bytes
* actually written.
*
* @param src
* the byte buffer containing the bytes to be written.
* @return the number of bytes actually written.
* @throws NonWritableChannelException
* if the channel was not opened for writing.
* @throws ClosedChannelException
* if the channel was already closed.
* @throws AsynchronousCloseException
* if another thread closes the channel during the write.
* @throws ClosedByInterruptException
* if another thread interrupts the calling thread while this
* operation is in progress. The interrupt state of the calling
* thread is set and the channel is closed.
* @throws IOException
* if another I/O error occurs, details are in the message.
* @see java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer)
*/
@Override
public int write(ByteBuffer src) throws IOException {
return writeImpl(src, -1);
}
/**
* Reads up to {@code count} bytes from {@code src} and stores them in this
* channel's file starting at {@code position}. No bytes are transferred if
* {@code position} is larger than the size of this channel's file. Less
* than {@code count} bytes are transferred if there are less bytes
* remaining in the source channel or if the source channel is non-blocking
* and has less than {@code count} bytes immediately available in its output
* buffer.
* <p>
* Note that this channel's position is not modified.
*
* @param src
* the source channel to read bytes from.
* @param position
* the non-negative start position.
* @param count
* the non-negative number of bytes to transfer.
* @return the number of bytes that are transferred.
* @throws IllegalArgumentException
* if the parameters are invalid.
* @throws NonReadableChannelException
* if the source channel is not readable.
* @throws NonWritableChannelException
* if this channel is not writable.
* @throws ClosedChannelException
* if either channel has already been closed.
* @throws AsynchronousCloseException
* if either channel is closed by other threads during this
* operation.
* @throws ClosedByInterruptException
* if the thread is interrupted during this operation.
* @throws IOException
* if any I/O error occurs.
*/
public long transferFrom(ReadableByteChannel src, long position, long count)
throws IOException {
checkOpen();
if (!src.isOpen()) {
throw new ClosedChannelException();
}
checkWritable();
if (position < 0 || count < 0 || count > Integer.MAX_VALUE) {
throw new IllegalArgumentException("position=" + position + " count=" + count);
}
if (position > size()) {
return 0;
}
// TODO investigate more performant write methods (mmap?)
// Right now all we can do is read and write via userspace.
ByteBuffer buffer = ByteBuffer.allocate((int) count);
src.read(buffer);
buffer.flip();
return write(buffer, position);
}
/**
* Reads up to {@code count} bytes from this channel's file starting at
* {@code position} and writes them to {@code target}. No bytes are
* transferred if {@code position} is larger than the size of this channel's
* file. Less than {@code count} bytes are transferred if there less bytes
* available from this channel's file or if the target channel is
* non-blocking and has less than {@code count} bytes free in its input
* buffer.
* <p>
* Note that this channel's position is not modified.
*
* @param position
* the non-negative position to begin.
* @param count
* the non-negative number of bytes to transfer.
* @param target
* the target channel to write to.
* @return the number of bytes that were transferred.
* @throws IllegalArgumentException
* if the parameters are invalid.
* @throws NonReadableChannelException
* if this channel is not readable.
* @throws NonWritableChannelException
* if the target channel is not writable.
* @throws ClosedChannelException
* if either channel has already been closed.
* @throws AsynchronousCloseException
* if either channel is closed by other threads during this
* operation.
* @throws ClosedByInterruptException
* if the thread is interrupted during this operation.
* @throws IOException
* if any I/O error occurs.
*/
public long transferTo(long position, long count, WritableByteChannel target)
throws IOException {
checkOpen();
if (!target.isOpen()) {
throw new ClosedChannelException();
}
checkReadable();
if (target instanceof IOCipherFileChannel) {
((IOCipherFileChannel) target).checkWritable();
}
if (position < 0 || count < 0) {
throw new IllegalArgumentException("position=" + position + " count=" + count);
}
if (count == 0 || position >= size()) {
return 0;
}
count = Math.min(count, size() - position);
try {
ByteBuffer buffer = ByteBuffer.allocate((int) count);
read(buffer, position);
buffer.flip();
return target.write(buffer);
} finally {
// TODO free buffer here? original android impl does.
}
}
/**
* Truncates the file underlying this channel to a given size. Any bytes
* beyond the given size are removed from the file. If there are no bytes
* beyond the given size then the file contents are unmodified.
* <p>
* If the file position is currently greater than the given size, then it is
* set to the new size.
*
* @param size
* the maximum size of the underlying file.
* @throws IllegalArgumentException
* if the requested size is negative.
* @throws ClosedChannelException
* if this channel is closed.
* @throws NonWritableChannelException
* if the channel cannot be written to.
* @throws IOException
* if another I/O error occurs.
* @return this channel.
*/
public IOCipherFileChannel truncate(long size) throws IOException {
checkOpen();
if (size < 0) {
throw new IllegalArgumentException("size: " + size);
}
checkWritable();
if (size < size()) {
try {
Libcore.os.ftruncate(fd, size);
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsIOException();
}
}
return this;
}
/**
* Writes bytes from the given buffer to this file channel starting at the
* given file position.
* <p>
* The bytes are written starting at the given file position (up to the
* remaining number of bytes in the buffer). The number of bytes actually
* written is returned.
* <p>
* If the position is beyond the current end of file, then the file is first
* extended up to the given position by the required number of unspecified
* byte values.
* <p>
* Note that the file position is not modified by this method.
*
* @param buffer
* the buffer containing the bytes to be written.
* @param position
* the (non-negative) position at which to write the bytes.
* @return the number of bytes actually written.
* @throws IllegalArgumentException
* if <code>position</code> is less than 0.
* @throws ClosedChannelException
* if this channel is closed.
* @throws NonWritableChannelException
* if the channel was not opened in write-mode.
* @throws AsynchronousCloseException
* if this channel is closed by another thread while this method
* is executing.
* @throws ClosedByInterruptException
* if another thread interrupts the calling thread while this
* operation is in progress. The interrupt state of the calling
* thread is set and the channel is closed.
* @throws IOException
* if another I/O error occurs.
*/
public int write(ByteBuffer buffer, long position) throws IOException {
if (position < 0) {
throw new IllegalArgumentException("position: " + position);
}
return writeImpl(buffer, position);
}
// TODO implement readv and writev ?
/*@Override
public long read(ByteBuffer[] buffers, int start, int number)
throws IOException {
Arrays.checkOffsetAndCount(buffers.length, offset, length);
checkOpen();
checkReadable();
return transferIoVec(new IoVec(buffers, offset, length, IoVec.Direction.READV));
}*/
/*@Override
public long write(ByteBuffer[] buffers, int offset, int length)
throws IOException {
}*/
}
| true | true | private int readImpl(ByteBuffer buffer, long position) throws IOException {
// buffer.checkWritable(); // TODO ByteBuffer.checkWritable() is
// protected
checkOpen();
checkReadable();
if (!buffer.hasRemaining()) {
return 0;
}
int bytesRead = 0;
boolean completed = false;
try {
begin();
try {
if (position == -1) {
bytesRead = Libcore.os.read(fd, buffer);
} else {
bytesRead = Libcore.os.pread(fd, buffer, position);
}
if (bytesRead == 0) {
bytesRead = -1;
}
} catch (ErrnoException errnoException) {
if (errnoException.errno == EAGAIN) {
// We don't throw if we try to read from an empty
// non-blocking pipe.
bytesRead = 0;
} else {
throw errnoException.rethrowAsIOException();
}
}
completed = true;
} finally {
end(completed && bytesRead >= 0);
}
if (bytesRead > 0) {
buffer.position(buffer.position() + bytesRead);
}
return bytesRead;
}
| private int readImpl(ByteBuffer buffer, long position) throws IOException {
if(buffer.isReadOnly()) {
throw new IllegalArgumentException("read-only buffer");
}
checkOpen();
checkReadable();
if (!buffer.hasRemaining()) {
return 0;
}
int bytesRead = 0;
boolean completed = false;
try {
begin();
try {
if (position == -1) {
bytesRead = Libcore.os.read(fd, buffer);
} else {
bytesRead = Libcore.os.pread(fd, buffer, position);
}
if (bytesRead == 0) {
bytesRead = -1;
}
} catch (ErrnoException errnoException) {
if (errnoException.errno == EAGAIN) {
// We don't throw if we try to read from an empty
// non-blocking pipe.
bytesRead = 0;
} else {
throw errnoException.rethrowAsIOException();
}
}
completed = true;
} finally {
end(completed && bytesRead >= 0);
}
if (bytesRead > 0) {
buffer.position(buffer.position() + bytesRead);
}
return bytesRead;
}
|
diff --git a/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyConnectionsPool.java b/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyConnectionsPool.java
index b09a22462..c53b086b4 100644
--- a/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyConnectionsPool.java
+++ b/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyConnectionsPool.java
@@ -1,283 +1,288 @@
/*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.ning.http.client.providers.netty;
import com.ning.http.client.ConnectionsPool;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A simple implementation of {@link com.ning.http.client.ConnectionsPool} based on a {@link java.util.concurrent.ConcurrentHashMap}
*/
public class NettyConnectionsPool implements ConnectionsPool<String, Channel> {
private final static Logger log = LoggerFactory.getLogger(NettyConnectionsPool.class);
private final ConcurrentHashMap<String, ConcurrentLinkedQueue<IdleChannel>> connectionsPool = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IdleChannel>>();
private final ConcurrentHashMap<Channel, IdleChannel> channel2IdleChannel = new ConcurrentHashMap<Channel, IdleChannel>();
private final ConcurrentHashMap<Channel, Long> channel2CreationDate = new ConcurrentHashMap<Channel, Long>();
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final Timer idleConnectionDetector = new Timer(true);
private final boolean sslConnectionPoolEnabled;
private final int maxTotalConnections;
private final int maxConnectionPerHost;
private final int maxConnectionLifeTimeInMs;
private final long maxIdleTime;
public NettyConnectionsPool(NettyAsyncHttpProvider provider) {
this.maxTotalConnections = provider.getConfig().getMaxTotalConnections();
this.maxConnectionPerHost = provider.getConfig().getMaxConnectionPerHost();
this.sslConnectionPoolEnabled = provider.getConfig().isSslConnectionPoolEnabled();
this.maxIdleTime = provider.getConfig().getIdleConnectionInPoolTimeoutInMs();
this.maxConnectionLifeTimeInMs = provider.getConfig().getMaxConnectionLifeTimeInMs();
this.idleConnectionDetector.schedule(new IdleChannelDetector(), maxIdleTime, maxIdleTime);
}
private static class IdleChannel {
final String uri;
final Channel channel;
final long start;
IdleChannel(String uri, Channel channel) {
this.uri = uri;
this.channel = channel;
this.start = System.currentTimeMillis();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IdleChannel)) return false;
IdleChannel that = (IdleChannel) o;
if (channel != null ? !channel.equals(that.channel) : that.channel != null) return false;
return true;
}
@Override
public int hashCode() {
return channel != null ? channel.hashCode() : 0;
}
}
private class IdleChannelDetector extends TimerTask {
@Override
public void run() {
try {
if (isClosed.get()) return;
if (log.isDebugEnabled()) {
Set<String> keys = connectionsPool.keySet();
for (String s : keys) {
log.debug("Entry count for : {} : {}", s, connectionsPool.get(s).size());
}
}
List<IdleChannel> channelsInTimeout = new ArrayList<IdleChannel>();
long currentTime = System.currentTimeMillis();
for (IdleChannel idleChannel : channel2IdleChannel.values()) {
long age = currentTime - idleChannel.start;
if (age > maxIdleTime) {
log.debug("Adding Candidate Idle Channel {}", idleChannel.channel);
// store in an unsynchronized list to minimize the impact on the ConcurrentHashMap.
channelsInTimeout.add(idleChannel);
}
}
long endConcurrentLoop = System.currentTimeMillis();
for (IdleChannel idleChannel : channelsInTimeout) {
Object attachment = idleChannel.channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
if (attachment != null) {
if (NettyResponseFuture.class.isAssignableFrom(attachment.getClass())) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) attachment;
if (!future.isDone() && !future.isCancelled()) {
log.debug("Future not in appropriate state %s\n", future);
continue;
}
}
}
if (remove(idleChannel)) {
log.debug("Closing Idle Channel {}", idleChannel.channel);
close(idleChannel.channel);
}
}
- if (log.isTraceEnabled())
+ if (log.isTraceEnabled()) {
+ int openChannels = 0;
+ for (ConcurrentLinkedQueue<IdleChannel> hostChannels: connectionsPool.values()) {
+ openChannels += hostChannels.size();
+ }
log.trace(String.format("%d channel open, %d idle channels closed (times: 1st-loop=%d, 2nd-loop=%d).\n",
- connectionsPool.size(), channelsInTimeout.size(), endConcurrentLoop - currentTime, System.currentTimeMillis() - endConcurrentLoop));
+ openChannels, channelsInTimeout.size(), endConcurrentLoop - currentTime, System.currentTimeMillis() - endConcurrentLoop));
+ }
} catch (Throwable t) {
log.error("uncaught exception!", t);
}
}
}
/**
* {@inheritDoc}
*/
public boolean offer(String uri, Channel channel) {
if (isClosed.get()) return false;
if (!sslConnectionPoolEnabled && uri.startsWith("https")) {
return false;
}
Long createTime = channel2CreationDate.get(channel);
if (createTime == null){
channel2CreationDate.putIfAbsent(channel, System.currentTimeMillis());
}
else if (maxConnectionLifeTimeInMs != -1 && (createTime + maxConnectionLifeTimeInMs) < System.currentTimeMillis() ) {
log.debug("Channel {} expired", channel);
return false;
}
log.debug("Adding uri: {} for channel {}", uri, channel);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(new NettyAsyncHttpProvider.DiscardEvent());
ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri);
if (idleConnectionForHost == null) {
ConcurrentLinkedQueue<IdleChannel> newPool = new ConcurrentLinkedQueue<IdleChannel>();
idleConnectionForHost = connectionsPool.putIfAbsent(uri, newPool);
if (idleConnectionForHost == null) idleConnectionForHost = newPool;
}
boolean added;
int size = idleConnectionForHost.size();
if (maxConnectionPerHost == -1 || size < maxConnectionPerHost) {
IdleChannel idleChannel = new IdleChannel(uri, channel);
synchronized (idleConnectionForHost) {
added = idleConnectionForHost.add(idleChannel);
if (channel2IdleChannel.put(channel, idleChannel) != null) {
log.error("Channel {} already exists in the connections pool!", channel);
}
}
} else {
log.debug("Maximum number of requests per host reached {} for {}", maxConnectionPerHost, uri);
added = false;
}
return added;
}
/**
* {@inheritDoc}
*/
public Channel poll(String uri) {
if (!sslConnectionPoolEnabled && uri.startsWith("https")) {
return null;
}
IdleChannel idleChannel = null;
ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri);
if (idleConnectionForHost != null) {
boolean poolEmpty = false;
while (!poolEmpty && idleChannel == null) {
if (idleConnectionForHost.size() > 0) {
synchronized (idleConnectionForHost) {
idleChannel = idleConnectionForHost.poll();
if (idleChannel != null) {
channel2IdleChannel.remove(idleChannel.channel);
}
}
}
if (idleChannel == null) {
poolEmpty = true;
} else if (!idleChannel.channel.isConnected() || !idleChannel.channel.isOpen()) {
idleChannel = null;
log.trace("Channel not connected or not opened!");
}
}
}
return idleChannel != null ? idleChannel.channel : null;
}
private boolean remove(IdleChannel pooledChannel) {
if (pooledChannel == null || isClosed.get()) return false;
boolean isRemoved = false;
ConcurrentLinkedQueue<IdleChannel> pooledConnectionForHost = connectionsPool.get(pooledChannel.uri);
if (pooledConnectionForHost != null) {
isRemoved = pooledConnectionForHost.remove(pooledChannel);
}
isRemoved |= channel2IdleChannel.remove(pooledChannel.channel) != null;
return isRemoved;
}
/**
* {@inheritDoc}
*/
public boolean removeAll(Channel channel) {
channel2CreationDate.remove(channel);
return !isClosed.get() && remove(channel2IdleChannel.get(channel));
}
/**
* {@inheritDoc}
*/
public boolean canCacheConnection() {
if (!isClosed.get() && maxTotalConnections != -1 && channel2IdleChannel.size() >= maxTotalConnections) {
return false;
} else {
return true;
}
}
/**
* {@inheritDoc}
*/
public void destroy() {
if (isClosed.getAndSet(true)) return;
// stop timer
idleConnectionDetector.cancel();
idleConnectionDetector.purge();
for (Channel channel : channel2IdleChannel.keySet()) {
close(channel);
}
connectionsPool.clear();
channel2IdleChannel.clear();
channel2CreationDate.clear();
}
private void close(Channel channel) {
try {
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(new NettyAsyncHttpProvider.DiscardEvent());
channel2CreationDate.remove(channel);
channel.close();
} catch (Throwable t) {
// noop
}
}
public final String toString() {
return String.format("NettyConnectionPool: {pool-size: %d}", channel2IdleChannel.size());
}
}
| false | true | public void run() {
try {
if (isClosed.get()) return;
if (log.isDebugEnabled()) {
Set<String> keys = connectionsPool.keySet();
for (String s : keys) {
log.debug("Entry count for : {} : {}", s, connectionsPool.get(s).size());
}
}
List<IdleChannel> channelsInTimeout = new ArrayList<IdleChannel>();
long currentTime = System.currentTimeMillis();
for (IdleChannel idleChannel : channel2IdleChannel.values()) {
long age = currentTime - idleChannel.start;
if (age > maxIdleTime) {
log.debug("Adding Candidate Idle Channel {}", idleChannel.channel);
// store in an unsynchronized list to minimize the impact on the ConcurrentHashMap.
channelsInTimeout.add(idleChannel);
}
}
long endConcurrentLoop = System.currentTimeMillis();
for (IdleChannel idleChannel : channelsInTimeout) {
Object attachment = idleChannel.channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
if (attachment != null) {
if (NettyResponseFuture.class.isAssignableFrom(attachment.getClass())) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) attachment;
if (!future.isDone() && !future.isCancelled()) {
log.debug("Future not in appropriate state %s\n", future);
continue;
}
}
}
if (remove(idleChannel)) {
log.debug("Closing Idle Channel {}", idleChannel.channel);
close(idleChannel.channel);
}
}
if (log.isTraceEnabled())
log.trace(String.format("%d channel open, %d idle channels closed (times: 1st-loop=%d, 2nd-loop=%d).\n",
connectionsPool.size(), channelsInTimeout.size(), endConcurrentLoop - currentTime, System.currentTimeMillis() - endConcurrentLoop));
} catch (Throwable t) {
log.error("uncaught exception!", t);
}
}
| public void run() {
try {
if (isClosed.get()) return;
if (log.isDebugEnabled()) {
Set<String> keys = connectionsPool.keySet();
for (String s : keys) {
log.debug("Entry count for : {} : {}", s, connectionsPool.get(s).size());
}
}
List<IdleChannel> channelsInTimeout = new ArrayList<IdleChannel>();
long currentTime = System.currentTimeMillis();
for (IdleChannel idleChannel : channel2IdleChannel.values()) {
long age = currentTime - idleChannel.start;
if (age > maxIdleTime) {
log.debug("Adding Candidate Idle Channel {}", idleChannel.channel);
// store in an unsynchronized list to minimize the impact on the ConcurrentHashMap.
channelsInTimeout.add(idleChannel);
}
}
long endConcurrentLoop = System.currentTimeMillis();
for (IdleChannel idleChannel : channelsInTimeout) {
Object attachment = idleChannel.channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
if (attachment != null) {
if (NettyResponseFuture.class.isAssignableFrom(attachment.getClass())) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) attachment;
if (!future.isDone() && !future.isCancelled()) {
log.debug("Future not in appropriate state %s\n", future);
continue;
}
}
}
if (remove(idleChannel)) {
log.debug("Closing Idle Channel {}", idleChannel.channel);
close(idleChannel.channel);
}
}
if (log.isTraceEnabled()) {
int openChannels = 0;
for (ConcurrentLinkedQueue<IdleChannel> hostChannels: connectionsPool.values()) {
openChannels += hostChannels.size();
}
log.trace(String.format("%d channel open, %d idle channels closed (times: 1st-loop=%d, 2nd-loop=%d).\n",
openChannels, channelsInTimeout.size(), endConcurrentLoop - currentTime, System.currentTimeMillis() - endConcurrentLoop));
}
} catch (Throwable t) {
log.error("uncaught exception!", t);
}
}
|
diff --git a/okapi-ui/swt/steps/rainbowkit-ui/src/main/java/net/sf/okapi/steps/rainbowkit/ui/CreationParametersEditor.java b/okapi-ui/swt/steps/rainbowkit-ui/src/main/java/net/sf/okapi/steps/rainbowkit/ui/CreationParametersEditor.java
index 5e4893ad0..27f10c36b 100644
--- a/okapi-ui/swt/steps/rainbowkit-ui/src/main/java/net/sf/okapi/steps/rainbowkit/ui/CreationParametersEditor.java
+++ b/okapi-ui/swt/steps/rainbowkit-ui/src/main/java/net/sf/okapi/steps/rainbowkit/ui/CreationParametersEditor.java
@@ -1,676 +1,677 @@
/*===========================================================================
Copyright (C) 2010-2012 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.steps.rainbowkit.ui;
import java.io.File;
import java.util.ArrayList;
import net.sf.okapi.common.EditorFor;
import net.sf.okapi.common.IContext;
import net.sf.okapi.common.IHelp;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.IParametersEditor;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.ui.Dialogs;
import net.sf.okapi.common.ui.ISWTEmbeddableParametersEditor;
import net.sf.okapi.common.ui.OKCancelPanel;
import net.sf.okapi.common.ui.TextAndBrowsePanel;
import net.sf.okapi.common.ui.UIUtil;
import net.sf.okapi.common.ui.genericeditor.GenericEditor;
import net.sf.okapi.common.uidescription.IEditorDescriptionProvider;
import net.sf.okapi.steps.rainbowkit.creation.Parameters;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
@EditorFor(Parameters.class)
public class CreationParametersEditor implements IParametersEditor, ISWTEmbeddableParametersEditor {
private static String SEPARATOR = " --> ";
private Shell shell;
private boolean result = false;
private OKCancelPanel pnlActions;
private Parameters params;
private IHelp help;
private TabFolder tabs;
private Text edPackageName;
private TextAndBrowsePanel pnlPackageDir;
private Button btCreateZip;
private Composite mainComposite;
private List lbTypes;
private Button btOptions;
private Button btHelp;
private Text edDescription;
private GenericEditor gedit;
private ArrayList<String> optEditors;
private ArrayList<String> writers;
private ArrayList<IParameters> optStrings;
private ArrayList<String> optMoreInfo;
private IContext context;
private Button chkSendOutput;
private Text edAncilOrigin;
private Text edAncilDestination;
private Button btAddAncilFile;
private Button btRemoveAncilFile;
private List lbAncilList;
private boolean supportFileMode;
public boolean edit (IParameters params,
boolean readOnly,
IContext context)
{
boolean bRes = false;
try {
shell = null;
this.context = context;
help = (IHelp)context.getObject("help");
this.params = (Parameters)params;
shell = new Shell((Shell)context.getObject("shell"), SWT.CLOSE | SWT.TITLE | SWT.RESIZE | SWT.APPLICATION_MODAL);
create((Shell)context.getObject("shell"), readOnly);
return showDialog();
}
catch ( Exception e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
bRes = false;
}
finally {
// Dispose of the shell, but not of the display
if ( shell != null ) shell.dispose();
}
return bRes;
}
public IParameters createParameters () {
return new Parameters();
}
@Override
public Composite getComposite () {
return mainComposite;
}
@Override
public void initializeEmbeddableEditor (Composite parent,
IParameters paramsObject,
IContext context)
{
shell = (Shell)context.getObject("shell");
help = (IHelp)context.getObject("help");
this.context = context;
params = (Parameters)paramsObject;
createComposite(parent);
setData();
}
@Override
public String validateAndSaveParameters () {
if ( supportFileMode ) {
return null;
}
if ( !saveData() ) return null;
return params.toString();
}
private void create (Shell parent,
boolean readOnly)
{
shell.setText("Translation Kit Creation");
if ( parent != null ) UIUtil.inheritIcon(shell, parent);
GridLayout layTmp = new GridLayout();
layTmp.marginBottom = 0;
layTmp.verticalSpacing = 0;
shell.setLayout(layTmp);
createComposite(shell);
//--- Dialog-level buttons
SelectionAdapter OKCancelActions = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
result = false;
if ( e.widget.getData().equals("h") ) {
if ( help != null ) help.showWiki("Translation Kit Creation Step");
return;
}
if ( supportFileMode ) {
e.doit = false;
return;
}
if ( e.widget.getData().equals("o") ) {
saveData();
}
shell.close();
};
};
pnlActions = new OKCancelPanel(shell, SWT.NONE, OKCancelActions, true);
pnlActions.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
pnlActions.btOK.setEnabled(!readOnly);
if ( !readOnly ) {
shell.setDefaultButton(pnlActions.btOK);
}
setData();
shell.pack();
shell.setMinimumSize(shell.getSize());
Dialogs.centerWindow(shell, parent);
}
private void createComposite (Composite parent) {
optEditors = new ArrayList<String>();
optStrings = new ArrayList<IParameters>();
optMoreInfo = new ArrayList<String>();
writers = new ArrayList<String>();
// XLIFF options
optEditors.add("net.sf.okapi.steps.rainbowkit.xliff.Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Generic XLIFF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFFPackageWriter");
// PO options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - PO Package"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.po.POPackageWriter");
// RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - Original with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.rtf.RTFPackageWriter");
// XLIFF-RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - XLIFF with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliffrtf.XLIFFRTFPackageWriter");
// OmegaT options
optEditors.add("net.sf.okapi.steps.rainbowkit.omegat.Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - OmegaT Project"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.omegat.OmegaTPackageWriter");
// Transifex options
optEditors.add("net.sf.okapi.steps.rainbowkit.transifex.Parameters");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Transifex Project"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.transifex.TransifexPackageWriter");
// ONTRAM options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - ONTRAM XINI"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.ontram.OntramPackageWriter");
// XLIFF 2
optEditors.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFF2Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - XLIFF 2.0"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFF2PackageWriter");
// Versified RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - Versified with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.versified.VersifiedRtfPackageWriter");
// Table options
optEditors.add("net.sf.okapi.filters.transtable.Parameters");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Translation Table"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.table.TablePackageWriter");
mainComposite = new Composite(parent, SWT.BORDER);
mainComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
mainComposite.setLayout(layout);
tabs = new TabFolder(mainComposite, SWT.NONE);
tabs.setLayout(new GridLayout());
GridData gdTmp = new GridData(GridData.FILL_BOTH);
-// // Auto-size is too high, we need to fix it manually
-// gdTmp.heightHint = 430;
+ // Auto-size is too high, we need to fix it manually
+ gdTmp.heightHint = 430;
tabs.setLayoutData(gdTmp);
//--- Output format tab
Composite cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(2, false));
TabItem tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Package Format");
tiTmp.setControl(cmpTmp);
Label label = new Label(cmpTmp, SWT.NONE);
label.setText("Type of package to create:");
gdTmp = new GridData();
gdTmp.horizontalSpan = 2;
label.setLayoutData(gdTmp);
lbTypes = new List(cmpTmp, SWT.BORDER | SWT.V_SCROLL);
lbTypes.add("Generic XLIFF");
lbTypes.setData("0", "net.sf.okapi.steps.rainbowkit.xliff.XLIFFPackageWriter");
lbTypes.add("PO Package");
lbTypes.setData("1", "net.sf.okapi.steps.rainbowkit.po.POPackageWriter");
lbTypes.add("Original with RTF");
lbTypes.setData("2", "net.sf.okapi.steps.rainbowkit.rtf.RTFPackageWriter");
lbTypes.add("XLIFF with RTF");
lbTypes.setData("3", "net.sf.okapi.steps.rainbowkit.xliffrtf.XLIFFRTFPackageWriter");
lbTypes.add("OmegaT Project");
lbTypes.setData("4", "net.sf.okapi.steps.rainbowkit.omegat.OmegaTPackageWriter");
lbTypes.add("Transifex Project");
lbTypes.setData("5", "net.sf.okapi.steps.rainbowkit.transifex.TransifexPackageWriter");
lbTypes.add("ONTRAM XINI");
lbTypes.setData("6", "net.sf.okapi.steps.rainbowkit.ontram.OntramPackageWriter");
lbTypes.add("XLIFF 2.0 (Experimental - output only)");
lbTypes.setData("7", "net.sf.okapi.steps.rainbowkit.xliff.XLIFF2PackageWriter");
lbTypes.add("Versified with RTF (Beta)");
lbTypes.setData("8", "net.sf.okapi.steps.rainbowkit.versified.VersifiedRtfPackageWriter");
lbTypes.add("Translation Table (Beta)");
lbTypes.setData("9", "net.sf.okapi.steps.rainbowkit.table.TablePackageWriter");
gdTmp = new GridData(GridData.FILL_BOTH);
- gdTmp.heightHint = 70;
+ gdTmp.heightHint = 50;
gdTmp.verticalSpan = 2;
lbTypes.setLayoutData(gdTmp);
lbTypes.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updatePackageType();
}
});
final int btnWidth = 95;
btOptions = new Button(cmpTmp, SWT.PUSH);
btOptions.setText("&Options...");
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
btOptions.setLayoutData(gdTmp);
UIUtil.ensureWidth(btOptions, btnWidth);
btOptions.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editOptions();
}
});
btHelp = new Button(cmpTmp, SWT.PUSH);
btHelp.setText("&More Info");
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
btHelp.setLayoutData(gdTmp);
UIUtil.ensureWidth(btHelp, btnWidth);
btHelp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
callMoreInfo();
}
});
edDescription = new Text(cmpTmp, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
edDescription.setEditable(false);
- gdTmp = new GridData(GridData.FILL_BOTH);
- gdTmp.heightHint = 50;
+ gdTmp = new GridData(GridData.FILL_HORIZONTAL);
+ gdTmp.heightHint = 100;
gdTmp.horizontalSpan = 2;
edDescription.setLayoutData(gdTmp);
chkSendOutput = new Button(cmpTmp, SWT.CHECK);
chkSendOutput.setText("Send the prepared files to the next step");
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 2;
chkSendOutput.setLayoutData(gdTmp);
//--- Location tab
cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(2, false));
tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Output Location");
tiTmp.setControl(cmpTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("Root of the output directory:");
new Label(cmpTmp, SWT.NONE);
pnlPackageDir = new TextAndBrowsePanel(cmpTmp, SWT.NONE, true);
gdTmp = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
pnlPackageDir.setLayoutData(gdTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("Name of the package:");
new Label(cmpTmp, SWT.NONE);
edPackageName = new Text(cmpTmp, SWT.BORDER);
edPackageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
btCreateZip = new Button(cmpTmp, SWT.CHECK);
btCreateZip.setText("Create a ZIP file for the package");
//--- Support Material tab
cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(1, false));
tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Support Material");
tiTmp.setControl(cmpTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("List of the files to include in the package");
lbAncilList = new List(cmpTmp, SWT.BORDER | SWT.V_SCROLL);
- lbAncilList.setLayoutData(new GridData(GridData.FILL_BOTH));
+ gdTmp = new GridData(GridData.FILL_BOTH);
+ gdTmp.heightHint = 100;
+ lbAncilList.setLayoutData(gdTmp);
Composite cmpTmp2 = new Composite(cmpTmp, SWT.NONE);
cmpTmp2.setLayout(new GridLayout(3, false));
- gdTmp = new GridData(GridData.FILL_BOTH);
- gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_END;
+ gdTmp = new GridData(GridData.FILL_HORIZONTAL);
cmpTmp2.setLayoutData(gdTmp);
btAddAncilFile = UIUtil.createGridButton(cmpTmp2, SWT.PUSH, "Add...", UIUtil.BUTTON_DEFAULT_WIDTH, 1);
btAddAncilFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( supportFileMode ) endSupportFileMode(true);
else startSupportFileMode();
}
});
label = new Label(cmpTmp2, SWT.NONE);
label.setText("File(s) path");
edAncilOrigin = new Text(cmpTmp2, SWT.BORDER);
edAncilOrigin.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btRemoveAncilFile = UIUtil.createGridButton(cmpTmp2, SWT.PUSH, "Remove", UIUtil.BUTTON_DEFAULT_WIDTH, 1);
btRemoveAncilFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( supportFileMode ) endSupportFileMode(false);
else removeAncillaryFile();
}
});
label = new Label(cmpTmp2, SWT.NONE);
label.setText("Destination");
edAncilDestination = new Text(cmpTmp2, SWT.BORDER);
edAncilDestination.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
endSupportFileMode(false);
}
private void removeAncillaryFile () {
try {
int n = lbAncilList.getSelectionIndex();
if ( n == -1 ) return;
lbAncilList.remove(n);
if ( n >= lbAncilList.getItemCount() ) n = lbAncilList.getItemCount()-1;
lbAncilList.select(n);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
private void startSupportFileMode () {
try {
supportFileMode = true;
btAddAncilFile.setText("Accept");
btRemoveAncilFile.setText("Discard");
edAncilOrigin.setEnabled(true);
edAncilDestination.setEnabled(true);
edAncilDestination.setText(File.separator+Parameters.SUPPORTFILE_SAMENAME);
edAncilOrigin.setFocus();
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
private boolean endSupportFileMode (boolean saveData) {
try {
if ( saveData ) {
String origin = edAncilOrigin.getText().trim();
if ( origin.isEmpty() ) {
Dialogs.showError(shell, "You must specify a file or a pattern.", null);
edAncilOrigin.setFocus();
return false;
}
String destination = edAncilDestination.getText().trim();
if ( destination.isEmpty() ) {
Dialogs.showError(shell, "You must specify a destination.", null);
edAncilDestination.setFocus();
return false;
}
lbAncilList.add(origin+SEPARATOR+destination);
lbAncilList.select(lbAncilList.getItemCount()-1);
}
btAddAncilFile.setText("Add...");
btRemoveAncilFile.setText("Remove");
edAncilOrigin.setEnabled(false);
edAncilOrigin.setText("");
edAncilDestination.setEnabled(false);
edAncilDestination.setText("");
supportFileMode = false;
return true;
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
return false;
}
}
private void updatePackageType () {
int n = lbTypes.getSelectionIndex();
if ( n == -1 ) {
btOptions.setEnabled(false);
edDescription.setText("");
return;
}
switch ( n ) {
case 0: // XLIFF
btOptions.setEnabled(optEditors.get(n)!=null);
edDescription.setText("Simple package where translatable files are extracted into XLIFF documents.\n"
+ "You can translate this package with any XLIFF editor and many XML-enabled tools.");
break;
case 1: // PO
btOptions.setEnabled(false);
edDescription.setText("Simple package where translatable files are extracted into PO files.\n"
+ "You can translate this package with any PO editor.");
break;
case 2: // Original with RTF
btOptions.setEnabled(false);
edDescription.setText("Package where the files to translate are converted into an RTF file with Trados-compatible styles.\n"
+ "You can translate this package with Trados Translator's Workbench or any compatible tool.");
break;
case 3: // XLIFF with RTF
btOptions.setEnabled(false);
edDescription.setText("Package where the files are extracted to XLIFF then converted into an Trados-compatible RTF file.\n"
+ "You can translate this package with Trados Translator's Workbench or any compatible tool.");
break;
case 4: // OmegaT
btOptions.setEnabled(optEditors.get(n)!=null);
edDescription.setText("OmegaT project with all its files and directory structure in place.\n"
+ "You can translate this package with OmegaT.");
break;
case 5: // Transifex
btOptions.setEnabled(optEditors.get(n)!=null);
edDescription.setText("Package where translatable files are uploaded to an online Transifex project.\n"
+ "You can translate this package with the online Transifex editor or locally with PO editors. "
+ "You can also use OmegaT to access the remote project directly.");
break;
case 6: // ONTRAM
btOptions.setEnabled(false);
edDescription.setText("Simple package where translatable files are extracted into a XINI document.\n"
+ "You can translate this package with ONTRAM.");
break;
case 7: // XLIFF 2
btOptions.setEnabled(optEditors.get(n)!=null);
edDescription.setText("Simple package with XLIFF 2.0 experimental files.\n"
+ "Not for real projects. The XLIFF 2.0 format is defined yet. See XLIFF TC for more information or to provide feedback.");
break;
case 8: // Versified Text with RTF
btOptions.setEnabled(false);
edDescription.setText("Package where the files to translate are converted into a Versified RTF file with Trados-compatible styles.\n"
+ "You can translate this package with Trados Translator's Workbench, WordFast or any RTF compatible editor.");
break;
case 9: // Table
btOptions.setEnabled(optEditors.get(n)!=null);
edDescription.setText("Package where the files to translate are converted into tab-delimited tables.\n"
+ "You can translate this package with a spreadsheet application.");
break;
}
}
private IParameters createParameters (String className) {
IParameters p = null;
try {
p = (IParameters)Class.forName(className).newInstance();
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
return p;
}
private void editOptions () {
try {
int n = lbTypes.getSelectionIndex();
if ( n == -1 ) return;
// Create the editor description
IEditorDescriptionProvider descProv = (IEditorDescriptionProvider)Class.forName(
optEditors.get(n)).newInstance();
// Create the generic editor if needed
if ( gedit == null ) {
gedit = new GenericEditor();
}
// Get the parameters
IParameters p = optStrings.get(n);
if ( !gedit.edit(p, descProv, false, context) ) {
return; // Cancel
}
// Else: Save the data
optStrings.set(n, p);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
private void callMoreInfo () {
try {
int n = lbTypes.getSelectionIndex();
if ( n == -1 ) return;
Util.openWikiTopic(optMoreInfo.get(n));
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
private boolean showDialog () {
shell.open();
while ( !shell.isDisposed() ) {
if ( !shell.getDisplay().readAndDispatch() )
shell.getDisplay().sleep();
}
return result;
}
private void setData () {
pnlPackageDir.setText(params.getPackageDirectory());
edPackageName.setText(params.getPackageName());
btCreateZip.setSelection(params.getCreateZip());
chkSendOutput.setSelection(params.getSendOutput());
String current = params.getWriterClass();
int n = 0;
for ( String str : writers ) {
if ( str.equals(current) ) break; // Found it
else n++;
}
lbTypes.select(n);
IParameters p = optStrings.get(n);
if ( p != null ) {
p.fromString(params.getWriterOptions());
}
// Support material
java.util.List<String> list = params.convertSupportFilesToList(params.getSupportFiles());
for ( String item : list ) {
lbAncilList.add(item.replace(Parameters.SUPPORTFILEDEST_SEP, SEPARATOR));
}
updatePackageType();
}
private boolean saveData () {
result = false;
if ( pnlPackageDir.getText().trim().length() == 0 ) {
//TODO: error box
return result;
}
if ( edPackageName.getText().trim().length() == 0 ) {
//TODO: error box
return result;
}
params.setPackageDirectory(pnlPackageDir.getText().trim());
params.setPackageName(edPackageName.getText().trim());
params.setCreateZip(btCreateZip.getSelection());
int n = lbTypes.getSelectionIndex();
// Writer type/class
params.setWriterClass((String)lbTypes.getData(String.valueOf(n)));
// Writer options
IParameters p = optStrings.get(n);
if ( p != null ) {
params.setWriterOptions(p.toString());
}
else {
params.setWriterOptions(null);
}
// Support material
ArrayList<String> list = new ArrayList<String>();
for ( String item : lbAncilList.getItems() ) {
list.add(item.replace(SEPARATOR, Parameters.SUPPORTFILEDEST_SEP));
}
String tmp = "";
if ( !list.isEmpty() ) {
tmp = params.convertSupportFilesToString(list);
}
params.setSupportFiles(tmp);
params.setSendOutput(chkSendOutput.getSelection());
result = true;
return result;
}
}
| false | true | private void createComposite (Composite parent) {
optEditors = new ArrayList<String>();
optStrings = new ArrayList<IParameters>();
optMoreInfo = new ArrayList<String>();
writers = new ArrayList<String>();
// XLIFF options
optEditors.add("net.sf.okapi.steps.rainbowkit.xliff.Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Generic XLIFF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFFPackageWriter");
// PO options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - PO Package"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.po.POPackageWriter");
// RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - Original with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.rtf.RTFPackageWriter");
// XLIFF-RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - XLIFF with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliffrtf.XLIFFRTFPackageWriter");
// OmegaT options
optEditors.add("net.sf.okapi.steps.rainbowkit.omegat.Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - OmegaT Project"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.omegat.OmegaTPackageWriter");
// Transifex options
optEditors.add("net.sf.okapi.steps.rainbowkit.transifex.Parameters");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Transifex Project"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.transifex.TransifexPackageWriter");
// ONTRAM options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - ONTRAM XINI"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.ontram.OntramPackageWriter");
// XLIFF 2
optEditors.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFF2Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - XLIFF 2.0"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFF2PackageWriter");
// Versified RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - Versified with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.versified.VersifiedRtfPackageWriter");
// Table options
optEditors.add("net.sf.okapi.filters.transtable.Parameters");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Translation Table"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.table.TablePackageWriter");
mainComposite = new Composite(parent, SWT.BORDER);
mainComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
mainComposite.setLayout(layout);
tabs = new TabFolder(mainComposite, SWT.NONE);
tabs.setLayout(new GridLayout());
GridData gdTmp = new GridData(GridData.FILL_BOTH);
// // Auto-size is too high, we need to fix it manually
// gdTmp.heightHint = 430;
tabs.setLayoutData(gdTmp);
//--- Output format tab
Composite cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(2, false));
TabItem tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Package Format");
tiTmp.setControl(cmpTmp);
Label label = new Label(cmpTmp, SWT.NONE);
label.setText("Type of package to create:");
gdTmp = new GridData();
gdTmp.horizontalSpan = 2;
label.setLayoutData(gdTmp);
lbTypes = new List(cmpTmp, SWT.BORDER | SWT.V_SCROLL);
lbTypes.add("Generic XLIFF");
lbTypes.setData("0", "net.sf.okapi.steps.rainbowkit.xliff.XLIFFPackageWriter");
lbTypes.add("PO Package");
lbTypes.setData("1", "net.sf.okapi.steps.rainbowkit.po.POPackageWriter");
lbTypes.add("Original with RTF");
lbTypes.setData("2", "net.sf.okapi.steps.rainbowkit.rtf.RTFPackageWriter");
lbTypes.add("XLIFF with RTF");
lbTypes.setData("3", "net.sf.okapi.steps.rainbowkit.xliffrtf.XLIFFRTFPackageWriter");
lbTypes.add("OmegaT Project");
lbTypes.setData("4", "net.sf.okapi.steps.rainbowkit.omegat.OmegaTPackageWriter");
lbTypes.add("Transifex Project");
lbTypes.setData("5", "net.sf.okapi.steps.rainbowkit.transifex.TransifexPackageWriter");
lbTypes.add("ONTRAM XINI");
lbTypes.setData("6", "net.sf.okapi.steps.rainbowkit.ontram.OntramPackageWriter");
lbTypes.add("XLIFF 2.0 (Experimental - output only)");
lbTypes.setData("7", "net.sf.okapi.steps.rainbowkit.xliff.XLIFF2PackageWriter");
lbTypes.add("Versified with RTF (Beta)");
lbTypes.setData("8", "net.sf.okapi.steps.rainbowkit.versified.VersifiedRtfPackageWriter");
lbTypes.add("Translation Table (Beta)");
lbTypes.setData("9", "net.sf.okapi.steps.rainbowkit.table.TablePackageWriter");
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.heightHint = 70;
gdTmp.verticalSpan = 2;
lbTypes.setLayoutData(gdTmp);
lbTypes.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updatePackageType();
}
});
final int btnWidth = 95;
btOptions = new Button(cmpTmp, SWT.PUSH);
btOptions.setText("&Options...");
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
btOptions.setLayoutData(gdTmp);
UIUtil.ensureWidth(btOptions, btnWidth);
btOptions.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editOptions();
}
});
btHelp = new Button(cmpTmp, SWT.PUSH);
btHelp.setText("&More Info");
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
btHelp.setLayoutData(gdTmp);
UIUtil.ensureWidth(btHelp, btnWidth);
btHelp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
callMoreInfo();
}
});
edDescription = new Text(cmpTmp, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
edDescription.setEditable(false);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.heightHint = 50;
gdTmp.horizontalSpan = 2;
edDescription.setLayoutData(gdTmp);
chkSendOutput = new Button(cmpTmp, SWT.CHECK);
chkSendOutput.setText("Send the prepared files to the next step");
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 2;
chkSendOutput.setLayoutData(gdTmp);
//--- Location tab
cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(2, false));
tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Output Location");
tiTmp.setControl(cmpTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("Root of the output directory:");
new Label(cmpTmp, SWT.NONE);
pnlPackageDir = new TextAndBrowsePanel(cmpTmp, SWT.NONE, true);
gdTmp = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
pnlPackageDir.setLayoutData(gdTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("Name of the package:");
new Label(cmpTmp, SWT.NONE);
edPackageName = new Text(cmpTmp, SWT.BORDER);
edPackageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
btCreateZip = new Button(cmpTmp, SWT.CHECK);
btCreateZip.setText("Create a ZIP file for the package");
//--- Support Material tab
cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(1, false));
tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Support Material");
tiTmp.setControl(cmpTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("List of the files to include in the package");
lbAncilList = new List(cmpTmp, SWT.BORDER | SWT.V_SCROLL);
lbAncilList.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite cmpTmp2 = new Composite(cmpTmp, SWT.NONE);
cmpTmp2.setLayout(new GridLayout(3, false));
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_END;
cmpTmp2.setLayoutData(gdTmp);
btAddAncilFile = UIUtil.createGridButton(cmpTmp2, SWT.PUSH, "Add...", UIUtil.BUTTON_DEFAULT_WIDTH, 1);
btAddAncilFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( supportFileMode ) endSupportFileMode(true);
else startSupportFileMode();
}
});
label = new Label(cmpTmp2, SWT.NONE);
label.setText("File(s) path");
edAncilOrigin = new Text(cmpTmp2, SWT.BORDER);
edAncilOrigin.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btRemoveAncilFile = UIUtil.createGridButton(cmpTmp2, SWT.PUSH, "Remove", UIUtil.BUTTON_DEFAULT_WIDTH, 1);
btRemoveAncilFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( supportFileMode ) endSupportFileMode(false);
else removeAncillaryFile();
}
});
label = new Label(cmpTmp2, SWT.NONE);
label.setText("Destination");
edAncilDestination = new Text(cmpTmp2, SWT.BORDER);
edAncilDestination.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
endSupportFileMode(false);
}
| private void createComposite (Composite parent) {
optEditors = new ArrayList<String>();
optStrings = new ArrayList<IParameters>();
optMoreInfo = new ArrayList<String>();
writers = new ArrayList<String>();
// XLIFF options
optEditors.add("net.sf.okapi.steps.rainbowkit.xliff.Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Generic XLIFF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFFPackageWriter");
// PO options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - PO Package"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.po.POPackageWriter");
// RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - Original with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.rtf.RTFPackageWriter");
// XLIFF-RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - XLIFF with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliffrtf.XLIFFRTFPackageWriter");
// OmegaT options
optEditors.add("net.sf.okapi.steps.rainbowkit.omegat.Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - OmegaT Project"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.omegat.OmegaTPackageWriter");
// Transifex options
optEditors.add("net.sf.okapi.steps.rainbowkit.transifex.Parameters");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Transifex Project"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.transifex.TransifexPackageWriter");
// ONTRAM options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - ONTRAM XINI"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.ontram.OntramPackageWriter");
// XLIFF 2
optEditors.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFF2Options");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - XLIFF 2.0"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.xliff.XLIFF2PackageWriter");
// Versified RTF options
optEditors.add(null);
optStrings.add(null);
optMoreInfo.add("Rainbow TKit - Versified with RTF"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.versified.VersifiedRtfPackageWriter");
// Table options
optEditors.add("net.sf.okapi.filters.transtable.Parameters");
optStrings.add(createParameters(optEditors.get(optEditors.size()-1)));
optMoreInfo.add("Rainbow TKit - Translation Table"); // wiki page
writers.add("net.sf.okapi.steps.rainbowkit.table.TablePackageWriter");
mainComposite = new Composite(parent, SWT.BORDER);
mainComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
mainComposite.setLayout(layout);
tabs = new TabFolder(mainComposite, SWT.NONE);
tabs.setLayout(new GridLayout());
GridData gdTmp = new GridData(GridData.FILL_BOTH);
// Auto-size is too high, we need to fix it manually
gdTmp.heightHint = 430;
tabs.setLayoutData(gdTmp);
//--- Output format tab
Composite cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(2, false));
TabItem tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Package Format");
tiTmp.setControl(cmpTmp);
Label label = new Label(cmpTmp, SWT.NONE);
label.setText("Type of package to create:");
gdTmp = new GridData();
gdTmp.horizontalSpan = 2;
label.setLayoutData(gdTmp);
lbTypes = new List(cmpTmp, SWT.BORDER | SWT.V_SCROLL);
lbTypes.add("Generic XLIFF");
lbTypes.setData("0", "net.sf.okapi.steps.rainbowkit.xliff.XLIFFPackageWriter");
lbTypes.add("PO Package");
lbTypes.setData("1", "net.sf.okapi.steps.rainbowkit.po.POPackageWriter");
lbTypes.add("Original with RTF");
lbTypes.setData("2", "net.sf.okapi.steps.rainbowkit.rtf.RTFPackageWriter");
lbTypes.add("XLIFF with RTF");
lbTypes.setData("3", "net.sf.okapi.steps.rainbowkit.xliffrtf.XLIFFRTFPackageWriter");
lbTypes.add("OmegaT Project");
lbTypes.setData("4", "net.sf.okapi.steps.rainbowkit.omegat.OmegaTPackageWriter");
lbTypes.add("Transifex Project");
lbTypes.setData("5", "net.sf.okapi.steps.rainbowkit.transifex.TransifexPackageWriter");
lbTypes.add("ONTRAM XINI");
lbTypes.setData("6", "net.sf.okapi.steps.rainbowkit.ontram.OntramPackageWriter");
lbTypes.add("XLIFF 2.0 (Experimental - output only)");
lbTypes.setData("7", "net.sf.okapi.steps.rainbowkit.xliff.XLIFF2PackageWriter");
lbTypes.add("Versified with RTF (Beta)");
lbTypes.setData("8", "net.sf.okapi.steps.rainbowkit.versified.VersifiedRtfPackageWriter");
lbTypes.add("Translation Table (Beta)");
lbTypes.setData("9", "net.sf.okapi.steps.rainbowkit.table.TablePackageWriter");
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.heightHint = 50;
gdTmp.verticalSpan = 2;
lbTypes.setLayoutData(gdTmp);
lbTypes.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updatePackageType();
}
});
final int btnWidth = 95;
btOptions = new Button(cmpTmp, SWT.PUSH);
btOptions.setText("&Options...");
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
btOptions.setLayoutData(gdTmp);
UIUtil.ensureWidth(btOptions, btnWidth);
btOptions.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editOptions();
}
});
btHelp = new Button(cmpTmp, SWT.PUSH);
btHelp.setText("&More Info");
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
btHelp.setLayoutData(gdTmp);
UIUtil.ensureWidth(btHelp, btnWidth);
btHelp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
callMoreInfo();
}
});
edDescription = new Text(cmpTmp, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
edDescription.setEditable(false);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.heightHint = 100;
gdTmp.horizontalSpan = 2;
edDescription.setLayoutData(gdTmp);
chkSendOutput = new Button(cmpTmp, SWT.CHECK);
chkSendOutput.setText("Send the prepared files to the next step");
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 2;
chkSendOutput.setLayoutData(gdTmp);
//--- Location tab
cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(2, false));
tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Output Location");
tiTmp.setControl(cmpTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("Root of the output directory:");
new Label(cmpTmp, SWT.NONE);
pnlPackageDir = new TextAndBrowsePanel(cmpTmp, SWT.NONE, true);
gdTmp = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
pnlPackageDir.setLayoutData(gdTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("Name of the package:");
new Label(cmpTmp, SWT.NONE);
edPackageName = new Text(cmpTmp, SWT.BORDER);
edPackageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
btCreateZip = new Button(cmpTmp, SWT.CHECK);
btCreateZip.setText("Create a ZIP file for the package");
//--- Support Material tab
cmpTmp = new Composite(tabs, SWT.NONE);
cmpTmp.setLayout(new GridLayout(1, false));
tiTmp = new TabItem(tabs, SWT.NONE);
tiTmp.setText("Support Material");
tiTmp.setControl(cmpTmp);
label = new Label(cmpTmp, SWT.NONE);
label.setText("List of the files to include in the package");
lbAncilList = new List(cmpTmp, SWT.BORDER | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.heightHint = 100;
lbAncilList.setLayoutData(gdTmp);
Composite cmpTmp2 = new Composite(cmpTmp, SWT.NONE);
cmpTmp2.setLayout(new GridLayout(3, false));
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
cmpTmp2.setLayoutData(gdTmp);
btAddAncilFile = UIUtil.createGridButton(cmpTmp2, SWT.PUSH, "Add...", UIUtil.BUTTON_DEFAULT_WIDTH, 1);
btAddAncilFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( supportFileMode ) endSupportFileMode(true);
else startSupportFileMode();
}
});
label = new Label(cmpTmp2, SWT.NONE);
label.setText("File(s) path");
edAncilOrigin = new Text(cmpTmp2, SWT.BORDER);
edAncilOrigin.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btRemoveAncilFile = UIUtil.createGridButton(cmpTmp2, SWT.PUSH, "Remove", UIUtil.BUTTON_DEFAULT_WIDTH, 1);
btRemoveAncilFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( supportFileMode ) endSupportFileMode(false);
else removeAncillaryFile();
}
});
label = new Label(cmpTmp2, SWT.NONE);
label.setText("Destination");
edAncilDestination = new Text(cmpTmp2, SWT.BORDER);
edAncilDestination.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
endSupportFileMode(false);
}
|
diff --git a/src/main/java/org/cojen/tupl/Database.java b/src/main/java/org/cojen/tupl/Database.java
index df0aaa65..a1bc5414 100644
--- a/src/main/java/org/cojen/tupl/Database.java
+++ b/src/main/java/org/cojen/tupl/Database.java
@@ -1,2807 +1,2807 @@
/*
* Copyright 2011-2012 Brian S O'Neill
*
* 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.cojen.tupl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.Writer;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import static org.cojen.tupl.Node.*;
import static org.cojen.tupl.Utils.*;
/**
* Main database class, containing a collection of transactional indexes. Call
* {@link #open open} to obtain a Database instance. Examples:
*
* <p>Open a non-durable database, limited to a max size of 100MB:
*
* <pre>
* DatabaseConfig config = new DatabaseConfig().maxCacheSize(100_000_000);
* Database db = Database.open(config);
* </pre>
*
* <p>Open a regular database, setting the minimum cache size to ensure enough
* memory is initially available. A weak {@link DurabilityMode durability mode}
* offers the best transactional commit performance.
*
* <pre>
* DatabaseConfig config = new DatabaseConfig()
* .baseFilePath("/var/lib/tupl")
* .minCacheSize(100_000_000)
* .durabilityMode(DurabilityMode.NO_FLUSH);
*
* Database db = Database.open(config);
* </pre>
*
* <p>The following files are created by the above example:
*
* <ul>
* <li><code>/var/lib/tupl.db</code> – primary data file
* <li><code>/var/lib/tupl.info</code> – text file describing the database configuration
* <li><code>/var/lib/tupl.lock</code> – lock file to ensure that at most one process can have the database open
* <li><code>/var/lib/tupl.redo.0</code> – first transaction redo log file
* </ul>
*
* <p>New redo log files are created by {@link #checkpoint checkpoints}, which
* also delete the old files. When {@link #beginSnapshot snapshots} are in
* progress, one or more numbered temporary files are created. For example:
* <code>/var/lib/tupl.temp.123</code>.
*
* @author Brian S O'Neill
* @see DatabaseConfig
*/
public final class Database extends CauseCloseable {
private static final int DEFAULT_CACHED_NODES = 1000;
// +2 for registry and key map root nodes, +1 for one user index, and +2
// for usage list to function correctly. It always assumes that the least
// recently used node points to a valid, more recently used node.
private static final int MIN_CACHED_NODES = 5;
// Approximate byte overhead per node. Influenced by many factors,
// including pointer size and child node references. This estimate assumes
// 32-bit pointers.
private static final int NODE_OVERHEAD = 100;
private static int nodeCountFromBytes(long bytes, int pageSize) {
if (bytes <= 0) {
return 0;
}
pageSize += NODE_OVERHEAD;
bytes += pageSize - 1;
if (bytes <= 0) {
// Overflow.
return Integer.MAX_VALUE;
}
long count = bytes / pageSize;
return count <= Integer.MAX_VALUE ? (int) count : Integer.MAX_VALUE;
}
private static long byteCountFromNodes(int nodes, int pageSize) {
return nodes * (long) (pageSize + NODE_OVERHEAD);
}
private static final int ENCODING_VERSION = 20120721;
private static final int I_ENCODING_VERSION = 0;
private static final int I_ROOT_PAGE_ID = I_ENCODING_VERSION + 4;
private static final int I_MASTER_UNDO_LOG_PAGE_ID = I_ROOT_PAGE_ID + 8;
private static final int I_TRANSACTION_ID = I_MASTER_UNDO_LOG_PAGE_ID + 8;
private static final int I_REDO_POSITION = I_TRANSACTION_ID + 8;
private static final int HEADER_SIZE = I_REDO_POSITION + 8;
static final byte KEY_TYPE_INDEX_NAME = 0;
static final byte KEY_TYPE_INDEX_ID = 1;
static final byte KEY_TYPE_NEXT_TREE_ID = 2;
private static final int DEFAULT_PAGE_SIZE = 4096;
private static final int MINIMUM_PAGE_SIZE = 512;
private static final int MAXIMUM_PAGE_SIZE = 65536;
private static final int OPEN_REGULAR = 0, OPEN_DESTROY = 1, OPEN_TEMP = 2;
private final EventListener mEventListener;
private final LockedFile mLockFile;
final DurabilityMode mDurabilityMode;
final long mDefaultLockTimeoutNanos;
final LockManager mLockManager;
final RedoWriter mRedoWriter;
final PageDb mPageDb;
private final BufferPool mSpareBufferPool;
private final Latch mUsageLatch;
private int mMaxNodeCount;
private int mNodeCount;
private Node mMostRecentlyUsed;
private Node mLeastRecentlyUsed;
private final Lock mSharedCommitLock;
// Is either CACHED_DIRTY_0 or CACHED_DIRTY_1. Access is guarded by commit lock.
private byte mCommitState;
// Is false for empty databases which have never checkpointed.
private volatile boolean mHasCheckpointed = true;
// Typically opposite of mCommitState, or negative if checkpoint is not in
// progress. Indicates which nodes are being flushed by the checkpoint.
private volatile int mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING;
private static final int CHECKPOINT_FLUSH_PREPARE = -2, CHECKPOINT_NOT_FLUSHING = -1;
// The root tree, which maps tree ids to other tree root node ids.
private final Tree mRegistry;
// Maps tree name keys to ids.
private final Tree mRegistryKeyMap;
private final Latch mOpenTreesLatch;
// Maps tree names to open trees.
private final Map<byte[], TreeRef> mOpenTrees;
private final LHashTable.Obj<TreeRef> mOpenTreesById;
private final ReferenceQueue<Tree> mOpenTreesRefQueue;
// Strong references to all trees opened during recovery. Not critical, but
// it keeps the trees from being closed and re-opened automatically by
// garbage collection. Access to this collection is thread-safe.
private List<Tree> mRecoveredTrees;
private final PageAllocator mAllocator;
private final FragmentCache mFragmentCache;
final int mMaxFragmentedEntrySize;
// Fragmented values which are transactionally deleted go here.
private volatile FragmentedTrash mFragmentedTrash;
private final Object mTxnIdLock = new Object();
// The following fields are guarded by mTxnIdLock.
private long mTxnId;
private UndoLog mTopUndoLog;
private int mUndoLogCount;
private final Object mCheckpointLock = new Object();
private long mLastCheckpointNanos;
private volatile Checkpointer mCheckpointer;
private final TempFileManager mTempFileManager;
volatile boolean mClosed;
volatile Throwable mClosedCause;
/**
* Open a database, creating it if necessary.
*/
public static Database open(DatabaseConfig config) throws IOException {
config = config.clone();
Database db = new Database(config, OPEN_REGULAR);
db.startCheckpointer(config);
return db;
}
/**
* Delete the contents of an existing database, and replace it with an
* empty one. When using a raw block device for the data file, this method
* must be used to format it.
*/
public static Database destroy(DatabaseConfig config) throws IOException {
config = config.clone();
if (config.mReadOnly) {
throw new IllegalArgumentException("Cannot destroy read-only database");
}
Database db = new Database(config, OPEN_DESTROY);
db.startCheckpointer(config);
return db;
}
/**
* @param config base file is set as a side-effect
*/
static Tree openTemp(TempFileManager tfm, DatabaseConfig config) throws IOException {
File file = tfm.createTempFile();
config.baseFile(file);
config.dataFile(file);
config.createFilePath(false);
config.durabilityMode(DurabilityMode.NO_FLUSH);
Database db = new Database(config, OPEN_TEMP);
tfm.register(file, db);
db.mCheckpointer = new Checkpointer(db, config);
db.mCheckpointer.start();
return db.mRegistry;
}
/**
* @param config unshared config
*/
private Database(DatabaseConfig config, int openMode) throws IOException {
config.mEventListener = mEventListener = SafeEventListener.makeSafe(config.mEventListener);
final File baseFile = config.mBaseFile;
final File[] dataFiles = config.dataFiles();
int pageSize = config.mPageSize;
if (pageSize <= 0) {
config.pageSize(pageSize = DEFAULT_PAGE_SIZE);
} else if (pageSize < MINIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE);
} else if (pageSize > MAXIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE);
}
int minCache, maxCache;
cacheSize: {
long minCachedBytes = Math.max(0, config.mMinCachedBytes);
long maxCachedBytes = Math.max(0, config.mMaxCachedBytes);
if (maxCachedBytes == 0) {
maxCachedBytes = minCachedBytes;
if (maxCachedBytes == 0) {
minCache = maxCache = DEFAULT_CACHED_NODES;
break cacheSize;
}
}
if (minCachedBytes > maxCachedBytes) {
throw new IllegalArgumentException
("Minimum cache size exceeds maximum: " +
minCachedBytes + " > " + maxCachedBytes);
}
minCache = nodeCountFromBytes(minCachedBytes, pageSize);
maxCache = nodeCountFromBytes(maxCachedBytes, pageSize);
minCache = Math.max(MIN_CACHED_NODES, minCache);
maxCache = Math.max(MIN_CACHED_NODES, maxCache);
}
// Update config such that info file is correct.
config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize);
config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize);
mUsageLatch = new Latch();
mMaxNodeCount = maxCache;
mDurabilityMode = config.mDurabilityMode;
mDefaultLockTimeoutNanos = config.mLockTimeoutNanos;
mLockManager = new LockManager(mDefaultLockTimeoutNanos);
if (baseFile != null && !config.mReadOnly && config.mMkdirs) {
baseFile.getParentFile().mkdirs();
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
// Create lock file and write info file of properties.
if (baseFile == null || openMode == OPEN_TEMP) {
mLockFile = null;
} else {
mLockFile = new LockedFile(new File(baseFile.getPath() + ".lock"), config.mReadOnly);
if (!config.mReadOnly) {
File infoFile = new File(baseFile.getPath() + ".info");
Writer w = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8"));
try {
config.writeInfo(w);
} finally {
w.close();
}
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
if (baseFile != null && openMode == OPEN_DESTROY) {
// Delete old redo log files.
deleteNumberedFiles(baseFile, ".redo.");
}
if (dataFiles == null) {
mPageDb = new NonPageDb(pageSize);
} else {
mPageDb = new DurablePageDb
(pageSize, dataFiles, options, config.mCrypto, openMode == OPEN_DESTROY);
}
mSharedCommitLock = mPageDb.sharedCommitLock();
try {
// Pre-allocate nodes. They are automatically added to the usage
// list, and so nothing special needs to be done to allow them to
// get used. Since the initial state is clean, evicting these
// nodes does nothing.
long cacheInitStart = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CACHE_INIT_BEGIN,
"Initializing %1$d cached nodes", minCache);
cacheInitStart = System.nanoTime();
}
try {
for (int i=minCache; --i>=0; ) {
allocLatchedNode(true).releaseExclusive();
}
} catch (OutOfMemoryError e) {
mMostRecentlyUsed = null;
mLeastRecentlyUsed = null;
throw new OutOfMemoryError
("Unable to allocate the minimum required number of cached nodes: " +
minCache);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0;
mEventListener.notify(EventType.CACHE_INIT_COMPLETE,
"Cache initialization completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
int spareBufferCount = Runtime.getRuntime().availableProcessors();
mSpareBufferPool = new BufferPool(mPageDb.pageSize(), spareBufferCount);
mSharedCommitLock.lock();
try {
mCommitState = CACHED_DIRTY_0;
} finally {
mSharedCommitLock.unlock();
}
byte[] header = new byte[HEADER_SIZE];
mPageDb.readExtraCommitData(header);
mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, loadRegistryRoot(header));
mOpenTreesLatch = new Latch();
if (openMode == OPEN_TEMP) {
mOpenTrees = Collections.emptyMap();
mOpenTreesById = new LHashTable.Obj<TreeRef>(0);
mOpenTreesRefQueue = null;
} else {
mOpenTrees = new TreeMap<byte[], TreeRef>(KeyComparator.THE);
mOpenTreesById = new LHashTable.Obj<TreeRef>(16);
mOpenTreesRefQueue = new ReferenceQueue<Tree>();
}
synchronized (mTxnIdLock) {
mTxnId = readLongLE(header, I_TRANSACTION_ID);
}
long redoPos = readLongLE(header, I_REDO_POSITION);
if (openMode == OPEN_TEMP) {
mRegistryKeyMap = null;
} else {
mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true);
}
mAllocator = new PageAllocator(mPageDb);
if (baseFile == null) {
// Non-durable database never evicts anything.
mFragmentCache = new FragmentMap();
} else {
// Regular database evicts automatically.
mFragmentCache = new FragmentCache(this, mMaxNodeCount);
}
if (openMode != OPEN_TEMP) {
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false);
if (tree != null) {
mFragmentedTrash = new FragmentedTrash(tree);
}
}
// Limit maximum fragmented entry size to guarantee that 2 entries
// fit. Each also requires 2 bytes for pointer and up to 3 bytes
// for value length field.
mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1;
long recoveryStart = 0;
if (baseFile == null || openMode == OPEN_TEMP) {
mRedoWriter = null;
} else {
// Perform recovery by examining redo and undo logs.
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin");
recoveryStart = System.nanoTime();
}
// Keep all the trees open during recovery.
mRecoveredTrees = Collections.synchronizedList(new ArrayList<Tree>());
UndoLog masterUndoLog;
LHashTable.Obj<UndoLog> undoLogs;
{
long nodeId = readLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID);
if (nodeId == 0) {
masterUndoLog = null;
undoLogs = null;
} else {
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs");
}
masterUndoLog = UndoLog.recoverMasterUndoLog(this, nodeId);
undoLogs = masterUndoLog.recoverLogs();
}
}
// FIXME: generic
RedoLogRecovery recovery = new RedoLogRecovery();
boolean doCheckpoint = recovery.recover(this, config, redoPos, undoLogs);
if (doCheckpoint) {
- // Bump up the highest transaction id if recovery has seen
- // higher. Although this is not expected to not happen, it
- // prevents transaction id collisions when it does.
+ // Avoid re-using transaction ids used by recovery.
long redoTxnId = recovery.highestTxnId();
- synchronized (mTxnIdLock) {
- // Subtract for modulo comparison.
- if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) {
- mTxnId = redoTxnId;
+ if (redoTxnId != 0) {
+ synchronized (mTxnIdLock) {
+ // Subtract for modulo comparison.
+ if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) {
+ mTxnId = redoTxnId;
+ }
}
}
}
if (masterUndoLog != null) {
// Rollback or truncate all remaining undo logs. They were
// never explicitly rolled back, or they were committed but
// not cleaned up. This also deletes the master undo log.
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_PROCESS_REMAINING,
"Processing remaining transactions");
}
if (masterUndoLog.processRemaining(undoLogs)) {
// Checkpoint ensures that undo logs don't get
// re-applied following a restart.
doCheckpoint = true;
}
}
mRedoWriter = recovery.newWriter();
if (doCheckpoint) {
checkpoint(true, 0, 0);
// Only cleanup after successful checkpoint.
recovery.cleanup();
}
mRecoveredTrees = null;
}
// Delete lingering fragmented values after undo logs have been
// processed, ensuring deletes were committed.
if (mFragmentedTrash != null) {
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS,
"Deleting unused large fragments");
}
if (mFragmentedTrash.emptyAllTrash()) {
checkpoint(false, 0, 0);
}
}
if (baseFile == null || openMode == OPEN_TEMP) {
mTempFileManager = null;
} else {
mTempFileManager = new TempFileManager(baseFile);
}
if (mRedoWriter != null && mEventListener != null) {
double duration = (System.nanoTime() - recoveryStart) / 1000000000.0;
mEventListener.notify(EventType.RECOVERY_COMPLETE,
"Recovery completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
} catch (Throwable e) {
closeQuietly(null, this, e);
throw rethrow(e);
}
}
private void startCheckpointer(DatabaseConfig config) {
if (mRedoWriter == null && mTempFileManager == null) {
// Nothing is durable and nothing to ever clean up
return;
}
mCheckpointer = new Checkpointer(this, config);
// Register objects to automatically shutdown.
mCheckpointer.register(mRedoWriter);
mCheckpointer.register(mTempFileManager);
mCheckpointer.start();
}
/*
void trace() throws IOException {
java.util.BitSet pages = mPageDb.tracePages();
mRegistry.mRoot.tracePages(this, pages);
mRegistryKeyMap.mRoot.tracePages(this, pages);
mOpenTreesLatch.acquireShared();
try {
for (Tree tree : mOpenTrees.values()) {
tree.mRoot.tracePages(this, pages);
}
} finally {
mOpenTreesLatch.releaseShared();
}
System.out.println(pages);
System.out.println("lost: " + pages.cardinality());
System.out.println(mPageDb.stats());
}
*/
/**
* Returns the given named index, returning null if not found.
*
* @return shared Index instance; null if not found
*/
public Index findIndex(byte[] name) throws IOException {
return openIndex(name.clone(), false);
}
/**
* Returns the given named index, returning null if not found. Name is UTF-8
* encoded.
*
* @return shared Index instance; null if not found
*/
public Index findIndex(String name) throws IOException {
return openIndex(name.getBytes("UTF-8"), false);
}
/**
* Returns the given named index, creating it if necessary.
*
* @return shared Index instance
*/
public Index openIndex(byte[] name) throws IOException {
return openIndex(name.clone(), true);
}
/**
* Returns the given named index, creating it if necessary. Name is UTF-8
* encoded.
*
* @return shared Index instance
*/
public Index openIndex(String name) throws IOException {
return openIndex(name.getBytes("UTF-8"), true);
}
/**
* Returns an index by its identifier, returning null if not found.
*
* @throws IllegalArgumentException if id is reserved
*/
public Index indexById(long id) throws IOException {
if (Tree.isInternal(id)) {
throw new IllegalArgumentException("Invalid id: " + id);
}
Index index;
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
if ((index = lookupIndexById(id)) != null) {
return index;
}
byte[] idKey = new byte[9];
idKey[0] = KEY_TYPE_INDEX_ID;
writeLongBE(idKey, 1, id);
byte[] name = mRegistryKeyMap.load(null, idKey);
if (name == null) {
return null;
}
index = openIndex(name, false);
} catch (Throwable e) {
throw closeOnFailure(this, e);
} finally {
commitLock.unlock();
}
if (index == null) {
// Registry needs to be repaired to fix this.
throw new DatabaseException("Unable to find index in registry");
}
return index;
}
/**
* @return null if index is not open
*/
private Tree lookupIndexById(long id) {
mOpenTreesLatch.acquireShared();
try {
LHashTable.ObjEntry<TreeRef> entry = mOpenTreesById.get(id);
return entry == null ? null : entry.value.get();
} finally {
mOpenTreesLatch.releaseShared();
}
}
/**
* Returns an index by its identifier, returning null if not found.
*
* @param id big-endian encoded long integer
* @throws IllegalArgumentException if id is malformed or reserved
*/
public Index indexById(byte[] id) throws IOException {
if (id.length != 8) {
throw new IllegalArgumentException("Expected 8 byte identifier: " + id.length);
}
return indexById(readLongBE(id, 0));
}
/**
* Allows access to internal indexes which can use the redo log.
*/
Index anyIndexById(long id) throws IOException {
if (id == Tree.REGISTRY_KEY_MAP_ID) {
return mRegistryKeyMap;
} else if (id == Tree.FRAGMENTED_TRASH_ID) {
return fragmentedTrash().mTrash;
}
return indexById(id);
}
/**
* Returns a Cursor which maps all available index names to
* identifiers. Identifiers are long integers, big-endian encoded.
* Attempting to store anything into the Cursor causes an {@link
* UnmodifiableViewException} to be thrown.
*/
public Cursor allIndexes() throws IOException {
return new IndexesCursor(mRegistryKeyMap.newCursor(null));
}
/**
* Returns a new Transaction with the {@link DatabaseConfig#durabilityMode default}
* durability mode.
*/
public Transaction newTransaction() {
return doNewTransaction(mDurabilityMode);
}
/**
* Returns a new Transaction with the given durability mode. If null, the
* {@link DatabaseConfig#durabilityMode default} is used.
*/
public Transaction newTransaction(DurabilityMode durabilityMode) {
return doNewTransaction(durabilityMode == null ? mDurabilityMode : durabilityMode);
}
private Transaction doNewTransaction(DurabilityMode durabilityMode) {
return new Transaction
(this, durabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos);
}
/**
* Convenience method which returns a transaction intended for locking, and
* not for making modifications.
*/
Transaction newLockTransaction() {
return new Transaction(this, DurabilityMode.NO_REDO, LockMode.UPGRADABLE_READ, -1);
}
/**
* Caller must hold commit lock. This ensures that highest transaction id
* is persisted correctly by checkpoint.
*/
void register(UndoLog undo) {
synchronized (mTxnIdLock) {
UndoLog top = mTopUndoLog;
if (top != null) {
undo.mPrev = top;
top.mNext = undo;
}
mTopUndoLog = undo;
mUndoLogCount++;
}
}
/**
* Caller must hold commit lock. This ensures that highest transaction id
* is persisted correctly by checkpoint.
*
* @return non-zero transaction id
*/
long registerAndBeginTransaction(UndoLog undo, long parentTxnId) throws IOException {
// FIXME: check if redo allows writes
long txnId;
synchronized (mTxnIdLock) {
UndoLog top = mTopUndoLog;
if (top != null) {
undo.mPrev = top;
top.mNext = undo;
}
mTopUndoLog = undo;
mUndoLogCount++;
while ((txnId = ++mTxnId) == 0);
}
RedoWriter redo = mRedoWriter;
if (redo != null) {
redo.txnBegin(txnId, parentTxnId);
}
return txnId;
}
/**
* Caller must hold commit lock. This ensures that highest transaction id
* is persisted correctly by checkpoint.
*
* @return non-zero transaction id
*/
long beginTransaction(long parentTxnId) throws IOException {
// FIXME: check if redo allows writes
long txnId;
do {
synchronized (mTxnIdLock) {
txnId = ++mTxnId;
}
} while (txnId == 0);
RedoWriter redo = mRedoWriter;
if (redo != null) {
redo.txnBegin(txnId, parentTxnId);
}
return txnId;
}
/**
* Called only by UndoLog.
*/
void unregister(UndoLog log) {
synchronized (mTxnIdLock) {
UndoLog prev = log.mPrev;
UndoLog next = log.mNext;
if (prev != null) {
prev.mNext = next;
log.mPrev = null;
}
if (next != null) {
next.mPrev = prev;
log.mNext = null;
} else if (log == mTopUndoLog) {
mTopUndoLog = prev;
}
mUndoLogCount--;
}
}
/**
* Preallocates pages for immediate use. The actual amount allocated
* varies, depending on the amount of free pages already available.
*
* @return actual amount allocated
*/
public long preallocate(long bytes) throws IOException {
if (!mClosed && mPageDb instanceof DurablePageDb) {
int pageSize = pageSize();
long pageCount = (bytes + pageSize - 1) / pageSize;
if (pageCount > 0) {
pageCount = mPageDb.allocatePages(pageCount);
if (pageCount > 0) {
checkpoint(true, 0, 0);
}
return pageCount * pageSize;
}
}
return 0;
}
/**
* Support for capturing a snapshot (hot backup) of the database, while
* still allowing concurrent modifications. The snapshot contains all data
* up to the last checkpoint. Call the {@link #checkpoint checkpoint}
* method immediately before to ensure that an up-to-date snapshot is
* captured.
*
* <p>To restore from a snapshot, store it in the primary data file, which
* is the base file with a ".db" extension. Make sure no redo log files
* exist and then open the database. Alternatively, call {@link
* #restoreFromSnapshot restoreFromSnapshot}, which also supports restoring
* into separate data files.
*
* <p>During the snapshot, temporary files are created to hold pre-modified
* copies of pages. If the snapshot destination stream blocks for too long,
* these files keep growing. File growth rate increases too if the database
* is being heavily modified. In the worst case, the temporary files can
* become larger than the primary database files.
*
* @return a snapshot control object, which must be closed when no longer needed
*/
public Snapshot beginSnapshot() throws IOException {
if (!(mPageDb instanceof DurablePageDb)) {
throw new UnsupportedOperationException("Snapshot only allowed for durable databases");
}
checkClosed();
DurablePageDb pageDb = (DurablePageDb) mPageDb;
return pageDb.beginSnapshot(mTempFileManager);
}
/**
* Restore from a {@link #beginSnapshot snapshot}, into the data files
* defined by the given configuration.
*
* @param in snapshot source; does not require extra buffering; auto-closed
*/
public static Database restoreFromSnapshot(DatabaseConfig config, InputStream in)
throws IOException
{
File[] dataFiles = config.dataFiles();
if (dataFiles == null) {
throw new UnsupportedOperationException("Restore only allowed for durable databases");
}
if (!config.mReadOnly && config.mMkdirs) {
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
// Delete old redo log files.
deleteNumberedFiles(config.mBaseFile, ".redo.");
DurablePageDb.restoreFromSnapshot
(config.mPageSize, dataFiles, options, config.mCrypto, in).close();
return Database.open(config);
}
/**
* Returns an immutable copy of database statistics.
*/
public Stats stats() {
Stats stats = new Stats();
stats.mPageSize = pageSize();
mSharedCommitLock.lock();
try {
long cursorCount = 0;
mOpenTreesLatch.acquireShared();
try {
stats.mOpenIndexes = mOpenTrees.size();
for (TreeRef treeRef : mOpenTrees.values()) {
Tree tree = treeRef.get();
if (tree != null) {
cursorCount += tree.mRoot.countCursors();
}
}
} finally {
mOpenTreesLatch.releaseShared();
}
stats.mCursorCount = cursorCount;
PageDb.Stats pstats = mPageDb.stats();
stats.mFreePages = pstats.freePages;
stats.mTotalPages = pstats.totalPages;
stats.mLockCount = mLockManager.numLocksHeld();
synchronized (mTxnIdLock) {
stats.mTxnCount = mUndoLogCount;
stats.mTxnsCreated = mTxnId;
}
} finally {
mSharedCommitLock.unlock();
}
return stats;
}
/**
* Immutable copy of database {@link Database#stats statistics}.
*/
public static class Stats implements Serializable {
private static final long serialVersionUID = 2L;
int mPageSize;
long mFreePages;
long mTotalPages;
int mOpenIndexes;
long mLockCount;
long mCursorCount;
long mTxnCount;
long mTxnsCreated;
Stats() {
}
/**
* Returns the allocation page size.
*/
public int pageSize() {
return mPageSize;
}
/**
* Returns the amount of unused pages in the database.
*/
public long freePages() {
return mFreePages;
}
/**
* Returns the total amount of pages in the database.
*/
public long totalPages() {
return mTotalPages;
}
/**
* Returns the amount of indexes currently open.
*/
public int openIndexes() {
return mOpenIndexes;
}
/**
* Returns the amount of locks currently allocated. Locks are created
* as transactions access or modify records, and they are destroyed
* when transactions exit or reset. An accumulation of locks can
* indicate that transactions are not being reset properly.
*/
public long lockCount() {
return mLockCount;
}
/**
* Returns the amount of cursors which are in a non-reset state. An
* accumulation of cursors can indicate that cursors are not being
* reset properly.
*/
public long cursorCount() {
return mCursorCount;
}
/**
* Returns the amount of transactions which are in a non-reset
* state. An accumulation of transactions can indicate that
* transactions are not being reset properly.
*/
public long transactionCount() {
return mTxnCount;
}
/**
* Returns the total amount of transactions explicitly created since
* the database was created. Nested transaction scopes are included as well.
*/
public long transactionsCreated() {
return mTxnsCreated;
}
@Override
public String toString() {
return "Database.Stats {pageSize=" + mPageSize
+ ", freePages=" + mFreePages
+ ", totalPages=" + mTotalPages
+ ", openIndexes=" + mOpenIndexes
+ ", lockCount=" + mLockCount
+ ", cursorCount=" + mCursorCount
+ ", transactionCount=" + mTxnCount
+ ", transactionsCreated=" + mTxnsCreated
+ '}';
}
}
/**
* Flushes, but does not sync, all non-flushed transactions. Transactions
* committed with {@link DurabilityMode#NO_FLUSH no-flush} effectively
* become {@link DurabilityMode#NO_SYNC no-sync} durable.
*/
public void flush() throws IOException {
if (!mClosed && mRedoWriter != null) {
mRedoWriter.flush();
}
}
/**
* Persists all non-flushed and non-sync'd transactions. Transactions
* committed with {@link DurabilityMode#NO_FLUSH no-flush} and {@link
* DurabilityMode#NO_SYNC no-sync} effectively become {@link
* DurabilityMode#SYNC sync} durable.
*/
public void sync() throws IOException {
if (!mClosed && mRedoWriter != null) {
mRedoWriter.sync();
}
}
/**
* Durably sync and checkpoint all changes to the database. In addition to
* ensuring that all transactions are durable, checkpointing ensures that
* non-transactional modifications are durable. Checkpoints are performed
* automatically by a background thread, at a {@link
* DatabaseConfig#checkpointRate configurable} rate.
*/
public void checkpoint() throws IOException {
if (!mClosed && mPageDb instanceof DurablePageDb) {
checkpoint(false, 0, 0);
}
}
/**
* Verifies the integrity of the database and all indexes.
*
* @param observer optional observer; pass null for default
* @return true if verification passed
*/
public boolean verify(VerificationObserver observer) throws IOException {
// TODO: Verify free lists.
if (observer == null) {
observer = new VerificationObserver();
}
boolean[] passedRef = {true};
indexes: {
if (!verify(passedRef, mRegistry, observer)) {
break indexes;
}
if (!verify(passedRef, mRegistryKeyMap, observer)) {
break indexes;
}
FragmentedTrash trash = mFragmentedTrash;
if (trash != null) {
if (!verify(passedRef, trash.mTrash, observer)) {
break indexes;
}
}
Cursor all = allIndexes();
for (all.first(); all.key() != null; all.next()) {
long id = readLongBE(all.value(), 0);
Tree index = lookupIndexById(id);
if (index != null) {
if (!verify(passedRef, index, observer)) {
break indexes;
}
} else {
// Open the index.
index = (Tree) indexById(id);
boolean keepGoing = verify(passedRef, index, observer);
try {
index.close();
} catch (IllegalStateException e) {
// Leave open if in use now.
}
if (!keepGoing) {
break indexes;
}
}
}
all.reset();
}
return passedRef[0];
}
/**
* @return false if should stop
*/
private boolean verify(boolean[] passedRef, Tree tree,
VerificationObserver observer)
throws IOException
{
observer.failed = false;
boolean keepGoing = tree.verifyTree(observer);
passedRef[0] &= !observer.failed;
if (keepGoing) {
keepGoing = observer.indexComplete(tree, !observer.failed, null);
}
return keepGoing;
}
/**
* Closes the database, ensuring durability of committed transactions. No
* checkpoint is performed by this method, and so non-transactional
* modifications can be lost.
*/
@Override
public void close() throws IOException {
close(null);
}
@Override
void close(Throwable cause) throws IOException {
if (cause != null) {
if (mClosedCause == null && mEventListener != null) {
mEventListener.notify(EventType.PANIC_UNHANDLED_EXCEPTION,
"Closing database due to unhandled exception: %1$s",
rootCause(cause));
}
mClosedCause = cause;
}
mClosed = true;
Checkpointer c = mCheckpointer;
if (c != null) {
c.close();
c = null;
}
// Synchronize to wait for any in-progress checkpoint to complete.
synchronized (mCheckpointLock) {
// Nothing really needs to be done in the synchronized block, but
// do something just in case a "smart" compiler thinks an empty
// synchronized block can be eliminated.
mClosed = true;
}
if (mOpenTrees != null) {
mOpenTreesLatch.acquireExclusive();
try {
mOpenTrees.clear();
mOpenTreesById.clear(0);
} finally {
mOpenTreesLatch.releaseExclusive();
}
}
mSharedCommitLock.lock();
try {
closeNodeCache();
if (mAllocator != null) {
mAllocator.clearDirtyNodes();
}
IOException ex = null;
ex = closeQuietly(ex, mRedoWriter, cause);
ex = closeQuietly(ex, mPageDb, cause);
ex = closeQuietly(ex, mLockFile, cause);
mLockManager.close();
if (ex != null) {
throw ex;
}
} finally {
mSharedCommitLock.unlock();
}
}
void checkClosed() throws DatabaseException {
if (mClosed) {
String message = "Closed";
Throwable cause = mClosedCause;
if (cause != null) {
message += "; " + rootCause(cause);
}
throw new DatabaseException(message, cause);
}
}
void treeClosed(Tree tree) {
mOpenTreesLatch.acquireExclusive();
try {
TreeRef ref = mOpenTrees.get(tree.mName);
if (ref != null && ref.get() == tree) {
ref.clear();
mOpenTrees.remove(tree.mName);
mOpenTreesById.remove(tree.mId);
}
} finally {
mOpenTreesLatch.releaseExclusive();
}
}
/**
* @param rootId pass zero to create
* @return unlatched and unevictable root node
*/
private Node loadTreeRoot(long rootId) throws IOException {
Node rootNode = allocLatchedNode(false);
try {
if (rootId == 0) {
rootNode.asEmptyRoot();
} else {
try {
rootNode.read(this, rootId);
} catch (IOException e) {
makeEvictableNow(rootNode);
throw e;
}
}
} finally {
rootNode.releaseExclusive();
}
return rootNode;
}
/**
* Loads the root registry node, or creates one if store is new. Root node
* is not eligible for eviction.
*/
private Node loadRegistryRoot(byte[] header) throws IOException {
int version = readIntLE(header, I_ENCODING_VERSION);
long rootId;
if (version == 0) {
rootId = 0;
// No registry; clearly nothing has been checkpointed.
mHasCheckpointed = false;
} else {
if (version != ENCODING_VERSION) {
throw new CorruptDatabaseException("Unknown encoding version: " + version);
}
rootId = readLongLE(header, I_ROOT_PAGE_ID);
}
return loadTreeRoot(rootId);
}
private Tree openInternalTree(long treeId, boolean create) throws IOException {
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
byte[] treeIdBytes = new byte[8];
writeLongBE(treeIdBytes, 0, treeId);
byte[] rootIdBytes = mRegistry.load(Transaction.BOGUS, treeIdBytes);
long rootId;
if (rootIdBytes != null) {
rootId = readLongLE(rootIdBytes, 0);
} else {
if (!create) {
return null;
}
rootId = 0;
}
return new Tree(this, treeId, treeIdBytes, null, loadTreeRoot(rootId));
} finally {
commitLock.unlock();
}
}
private Index openIndex(byte[] name, boolean create) throws IOException {
checkClosed();
Tree tree = quickFindIndex(null, name);
if (tree != null) {
return tree;
}
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
// Cleaup before opening more indexes.
cleanupUnreferencedTrees(null);
byte[] nameKey = newKey(KEY_TYPE_INDEX_NAME, name);
byte[] treeIdBytes = mRegistryKeyMap.load(null, nameKey);
long treeId;
// Is non-null if index was created.
byte[] idKey;
if (treeIdBytes != null) {
idKey = null;
treeId = readLongBE(treeIdBytes, 0);
} else if (!create) {
return null;
} else {
mOpenTreesLatch.acquireExclusive();
try {
treeIdBytes = mRegistryKeyMap.load(null, nameKey);
if (treeIdBytes != null) {
idKey = null;
treeId = readLongBE(treeIdBytes, 0);
} else {
treeIdBytes = new byte[8];
try {
do {
treeId = nextTreeId();
writeLongBE(treeIdBytes, 0, treeId);
} while (!mRegistry.insert
(Transaction.BOGUS, treeIdBytes, EMPTY_BYTES));
if (!mRegistryKeyMap.insert(null, nameKey, treeIdBytes)) {
mRegistry.delete(Transaction.BOGUS, treeIdBytes);
throw new DatabaseException("Unable to insert index name");
}
idKey = newKey(KEY_TYPE_INDEX_ID, treeIdBytes);
if (!mRegistryKeyMap.insert(null, idKey, name)) {
mRegistryKeyMap.delete(null, nameKey);
mRegistry.delete(Transaction.BOGUS, treeIdBytes);
throw new DatabaseException("Unable to insert index id");
}
} catch (IOException e) {
throw closeOnFailure(this, e);
}
}
} finally {
mOpenTreesLatch.releaseExclusive();
}
}
// Use a transaction to ensure that only one thread loads the
// requested index. Nothing is written into it.
Transaction txn = newLockTransaction();
try {
// Pass the transaction to acquire the lock.
byte[] rootIdBytes = mRegistry.load(txn, treeIdBytes);
tree = quickFindIndex(txn, name);
if (tree != null) {
// Another thread got the lock first and loaded the index.
return tree;
}
long rootId = (rootIdBytes == null || rootIdBytes.length == 0) ? 0
: readLongLE(rootIdBytes, 0);
tree = new Tree(this, treeId, treeIdBytes, name, loadTreeRoot(rootId));
TreeRef treeRef = new TreeRef(tree, mOpenTreesRefQueue);
mOpenTreesLatch.acquireExclusive();
try {
mOpenTrees.put(name, treeRef);
mOpenTreesById.insert(treeId).value = treeRef;
} finally {
mOpenTreesLatch.releaseExclusive();
}
List<Tree> recovered = mRecoveredTrees;
if (recovered != null) {
recovered.add(tree);
}
return tree;
} catch (Throwable e) {
if (idKey != null) {
// Rollback create of new index.
try {
mRegistryKeyMap.delete(null, idKey);
mRegistryKeyMap.delete(null, nameKey);
mRegistry.delete(Transaction.BOGUS, treeIdBytes);
} catch (Throwable e2) {
// Ignore.
}
}
throw rethrow(e);
} finally {
txn.reset();
}
} finally {
commitLock.unlock();
}
}
private long nextTreeId() throws IOException {
// By generating identifiers from a 64-bit sequence, it's effectively
// impossible for them to get re-used after trees are deleted.
Transaction txn = newTransaction();
try {
byte[] key = {KEY_TYPE_NEXT_TREE_ID};
byte[] nextTreeIdBytes = mRegistryKeyMap.load(txn, key);
if (nextTreeIdBytes == null) {
nextTreeIdBytes = new byte[8];
}
long nextTreeId = readLongLE(nextTreeIdBytes, 0);
long treeId;
do {
treeId = nextTreeId++;
byte[] databaseId = mPageDb.databaseId();
if (databaseId.length >= 8) {
// Mask with the unique database id, making the identifiers
// less predictable and non-compatible with other databases.
treeId ^= Utils.readLongLE(databaseId, 0);
}
treeId = Utils.scramble(treeId);
} while (Tree.isInternal(treeId));
writeLongLE(nextTreeIdBytes, 0, nextTreeId);
mRegistryKeyMap.store(txn, key, nextTreeIdBytes);
txn.commit();
return treeId;
} finally {
txn.reset();
}
}
/**
* @return null if not found
*/
private Tree quickFindIndex(Transaction txn, byte[] name) throws IOException {
TreeRef treeRef;
mOpenTreesLatch.acquireShared();
try {
treeRef = mOpenTrees.get(name);
if (treeRef == null) {
return null;
}
Tree tree = treeRef.get();
if (tree != null) {
return tree;
}
} finally {
mOpenTreesLatch.releaseShared();
}
// Ensure that all nodes of cleared tree reference are evicted before
// potentially replacing them. Weak references are cleared before they
// are enqueued, and so polling the queue does not guarantee node
// eviction. Process the tree directly.
cleanupUnreferencedTree(txn, treeRef);
return null;
}
/**
* Trees retain a references to an unevictable root node. If tree is no
* longer in use, evict everything, including the root node. Method cannot
* be called while a checkpoint is in progress.
*/
private void cleanupUnreferencedTrees(Transaction txn) throws IOException {
final ReferenceQueue queue = mOpenTreesRefQueue;
if (queue == null) {
return;
}
try {
while (true) {
Reference ref = queue.poll();
if (ref == null) {
break;
}
if (ref instanceof TreeRef) {
cleanupUnreferencedTree(txn, (TreeRef) ref);
}
}
} catch (Exception e) {
if (!mClosed) {
throw rethrow(e);
}
}
}
private void cleanupUnreferencedTree(Transaction txn, TreeRef ref) throws IOException {
// Acquire lock to prevent tree from being reloaded too soon.
byte[] treeIdBytes = new byte[8];
writeLongBE(treeIdBytes, 0, ref.mId);
if (txn == null) {
txn = newLockTransaction();
} else {
txn.enter();
}
try {
// Pass the transaction to acquire the lock.
mRegistry.load(txn, treeIdBytes);
mOpenTreesLatch.acquireShared();
try {
LHashTable.ObjEntry<TreeRef> entry = mOpenTreesById.get(ref.mId);
if (entry == null || entry.value != ref) {
return;
}
} finally {
mOpenTreesLatch.releaseShared();
}
Node root = ref.mRoot;
root.acquireExclusive();
root.forceEvictTree(mPageDb);
root.releaseExclusive();
mOpenTreesLatch.acquireExclusive();
try {
mOpenTreesById.remove(ref.mId);
mOpenTrees.remove(ref.mName);
} finally {
mOpenTreesLatch.releaseExclusive();
}
} finally {
txn.exit();
}
// Move root node into usage list, allowing it to be re-used.
makeEvictableNow(ref.mRoot);
}
private static byte[] newKey(byte type, byte[] payload) {
byte[] key = new byte[1 + payload.length];
key[0] = type;
System.arraycopy(payload, 0, key, 1, payload.length);
return key;
}
/**
* Returns the fixed size of all pages in the store, in bytes.
*/
int pageSize() {
return mPageDb.pageSize();
}
/**
* Access the shared commit lock, which prevents commits while held.
*/
Lock sharedCommitLock() {
return mSharedCommitLock;
}
/**
* Returns a new or recycled Node instance, latched exclusively, with an id
* of zero and a clean state.
*/
Node allocLatchedNode() throws IOException {
return allocLatchedNode(true);
}
/**
* Returns a new or recycled Node instance, latched exclusively, with an id
* of zero and a clean state.
*
* @param evictable true if allocated node can be automatically evicted
*/
Node allocLatchedNode(boolean evictable) throws IOException {
final Latch usageLatch = mUsageLatch;
for (int trial = 1; trial <= 3; trial++) {
usageLatch.acquireExclusive();
alloc: try {
int max = mMaxNodeCount;
if (max == 0) {
break alloc;
}
if (mNodeCount < max) {
checkClosed();
Node node = new Node(pageSize());
node.acquireExclusive();
mNodeCount++;
if (evictable) {
if ((node.mLessUsed = mMostRecentlyUsed) == null) {
mLeastRecentlyUsed = node;
} else {
mMostRecentlyUsed.mMoreUsed = node;
}
mMostRecentlyUsed = node;
}
return node;
}
if (!evictable && mLeastRecentlyUsed.mMoreUsed == mMostRecentlyUsed) {
// Cannot allow list to shrink to less than two elements.
break alloc;
}
do {
Node node = mLeastRecentlyUsed;
(mLeastRecentlyUsed = node.mMoreUsed).mLessUsed = null;
node.mMoreUsed = null;
(node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node;
mMostRecentlyUsed = node;
if (node.tryAcquireExclusive() && (node = Node.evict(node, mPageDb)) != null) {
if (!evictable) {
// Detach from linked list.
(mMostRecentlyUsed = node.mLessUsed).mMoreUsed = null;
node.mLessUsed = null;
}
// Return with latch still held.
return node;
}
} while (--max > 0);
} finally {
usageLatch.releaseExclusive();
}
checkClosed();
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
// Try to free up nodes from unreferenced trees.
cleanupUnreferencedTrees(null);
} finally {
commitLock.unlock();
}
}
throw new CacheExhaustedException();
}
/**
* Unlinks all nodes from each other in usage list, and prevents new nodes
* from being allocated.
*/
private void closeNodeCache() {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
// Prevent new allocations.
mMaxNodeCount = 0;
Node node = mLeastRecentlyUsed;
mLeastRecentlyUsed = null;
mMostRecentlyUsed = null;
while (node != null) {
Node next = node.mMoreUsed;
node.mLessUsed = null;
node.mMoreUsed = null;
// Make node appear to be evicted.
node.mId = 0;
// Attempt to unlink child nodes, making them appear to be evicted.
if (node.tryAcquireExclusive()) {
Node[] childNodes = node.mChildNodes;
if (childNodes != null) {
Arrays.fill(childNodes, null);
}
node.releaseExclusive();
}
node = next;
}
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Returns a new or recycled Node instance, latched exclusively and marked
* dirty. Caller must hold commit lock.
*/
Node allocDirtyNode() throws IOException {
Node node = allocLatchedNode(true);
try {
dirty(node, mAllocator.allocPage(node));
return node;
} catch (IOException e) {
node.releaseExclusive();
throw e;
}
}
/**
* Returns a new or recycled Node instance, latched exclusively, marked
* dirty and unevictable. Caller must hold commit lock.
*/
Node allocUnevictableNode() throws IOException {
Node node = allocLatchedNode(false);
try {
dirty(node, mAllocator.allocPage(node));
return node;
} catch (IOException e) {
makeEvictableNow(node);
node.releaseExclusive();
throw e;
}
}
/**
* Allow a Node which was allocated as unevictable to be evictable,
* starting off as the most recently used.
*/
void makeEvictable(Node node) {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
if (node.mMoreUsed != null || node.mLessUsed != null) {
throw new IllegalStateException();
}
(node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node;
mMostRecentlyUsed = node;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Allow a Node which was allocated as unevictable to be evictable, as the
* least recently used.
*/
void makeEvictableNow(Node node) {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
if (node.mMoreUsed != null || node.mLessUsed != null) {
throw new IllegalStateException();
}
(node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node;
mLeastRecentlyUsed = node;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Allow a Node which was allocated as evictable to be unevictable.
*/
void makeUnevictable(final Node node) {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
final Node lessUsed = node.mLessUsed;
final Node moreUsed = node.mMoreUsed;
if (lessUsed == null) {
(mLeastRecentlyUsed = moreUsed).mLessUsed = null;
} else if (moreUsed == null) {
(mMostRecentlyUsed = lessUsed).mMoreUsed = null;
} else {
lessUsed.mMoreUsed = moreUsed;
moreUsed.mLessUsed = lessUsed;
}
node.mMoreUsed = null;
node.mLessUsed = null;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Caller must hold commit lock and any latch on node.
*/
boolean shouldMarkDirty(Node node) {
return node.mCachedState != mCommitState && node.mId != Node.STUB_ID;
}
/**
* Caller must hold commit lock and exclusive latch on node. Method does
* nothing if node is already dirty. Latch is never released by this method,
* even if an exception is thrown.
*
* @return true if just made dirty and id changed
*/
boolean markDirty(Tree tree, Node node) throws IOException {
if (node.mCachedState == mCommitState || node.mId == Node.STUB_ID) {
return false;
} else {
doMarkDirty(tree, node);
return true;
}
}
/**
* Caller must hold commit lock and exclusive latch on node. Method does
* nothing if node is already dirty. Latch is never released by this method,
* even if an exception is thrown.
*/
void markUndoLogDirty(Node node) throws IOException {
if (node.mCachedState != mCommitState) {
long oldId = node.mId;
long newId = mAllocator.allocPage(node);
mPageDb.deletePage(oldId);
node.write(mPageDb);
dirty(node, newId);
}
}
/**
* Caller must hold commit lock and exclusive latch on node. Method must
* not be called if node is already dirty. Latch is never released by this
* method, even if an exception is thrown.
*/
void doMarkDirty(Tree tree, Node node) throws IOException {
long oldId = node.mId;
long newId = mAllocator.allocPage(node);
if (oldId != 0) {
mPageDb.deletePage(oldId);
}
if (node.mCachedState != CACHED_CLEAN) {
node.write(mPageDb);
}
if (node == tree.mRoot && tree.mIdBytes != null) {
byte[] newEncodedId = new byte[8];
writeLongLE(newEncodedId, 0, newId);
mRegistry.store(Transaction.BOGUS, tree.mIdBytes, newEncodedId);
}
dirty(node, newId);
}
/**
* Caller must hold commit lock and exclusive latch on node.
*/
private void dirty(Node node, long newId) {
node.mId = newId;
node.mCachedState = mCommitState;
}
/**
* Caller must hold commit lock and exclusive latch on node. This method
* should only be called for nodes whose existing data is not needed.
*/
void redirty(Node node) {
node.mCachedState = mCommitState;
mAllocator.dirty(node);
}
/**
* Similar to markDirty method except no new page is reserved, and old page
* is not immediately deleted. Caller must hold commit lock and exclusive
* latch on node. Latch is never released by this method, unless an
* exception is thrown.
*/
void prepareToDelete(Node node) throws IOException {
// Hello. My name is Inigo Montoya. You killed my father. Prepare to die.
if (node.mCachedState == mCheckpointFlushState) {
// Node must be committed with the current checkpoint, and so
// it must be written out before it can be deleted.
try {
node.write(mPageDb);
} catch (Throwable e) {
node.releaseExclusive();
throw rethrow(e);
}
}
}
/**
* Caller must hold commit lock and exclusive latch on node. The
* prepareToDelete method must have been called first. Latch is always
* released by this method, even if an exception is thrown.
*/
void deleteNode(Node node) throws IOException {
try {
deletePage(node.mId, node.mCachedState);
node.mId = 0;
// TODO: child node array should be recycled
node.mChildNodes = null;
// When node is re-allocated, it will be evicted. Ensure that eviction
// doesn't write anything.
node.mCachedState = CACHED_CLEAN;
} finally {
node.releaseExclusive();
}
// Indicate that node is least recently used, allowing it to be
// re-allocated immediately without evicting another node. Node must be
// unlatched at this point, to prevent it from being immediately
// promoted to most recently used by allocLatchedNode.
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
Node lessUsed = node.mLessUsed;
if (lessUsed == null) {
// Node might already be least...
if (node.mMoreUsed != null) {
// ...confirmed.
return;
}
// ...Node isn't in the usage list at all.
} else {
Node moreUsed = node.mMoreUsed;
if ((lessUsed.mMoreUsed = moreUsed) == null) {
mMostRecentlyUsed = lessUsed;
} else {
moreUsed.mLessUsed = lessUsed;
}
node.mLessUsed = null;
}
(node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node;
mLeastRecentlyUsed = node;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Caller must hold commit lock.
*/
void deletePage(long id, int cachedState) throws IOException {
if (id != 0) {
if (cachedState == mCommitState) {
// Newly reserved page was never used, so recycle it.
mAllocator.recyclePage(id);
} else {
// Old data must survive until after checkpoint.
mPageDb.deletePage(id);
}
}
}
/**
* Indicate that non-root node is most recently used. Root node is not
* managed in usage list and cannot be evicted. Caller must hold any latch
* on node. Latch is never released by this method, even if an exception is
* thrown.
*/
void used(Node node) {
// Because this method can be a bottleneck, don't wait for exclusive
// latch. If node is popular, it will get more chances to be identified
// as most recently used. This strategy works well enough because cache
// eviction is always a best-guess approach.
final Latch usageLatch = mUsageLatch;
if (usageLatch.tryAcquireExclusive()) {
Node moreUsed = node.mMoreUsed;
if (moreUsed != null) {
Node lessUsed = node.mLessUsed;
if ((moreUsed.mLessUsed = lessUsed) == null) {
mLeastRecentlyUsed = moreUsed;
} else {
lessUsed.mMoreUsed = moreUsed;
}
node.mMoreUsed = null;
(node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node;
mMostRecentlyUsed = node;
}
usageLatch.releaseExclusive();
}
}
/**
* Breakup a large value into separate pages, returning a new value which
* encodes the page references. Caller must hold commit lock.
*
* Returned value begins with a one byte header:
*
* 0b0000_ffip
*
* The leading 4 bits define the encoding type, which must be 0. The 'f'
* bits define the full value length field size: 2, 4, 6, or 8 bytes. The
* array is limited to a 4 byte length, and so only the 2 and 4 byte forms
* apply. The 'i' bit defines the inline content length field size: 0 or 2
* bytes. The 'p' bit is clear if direct pointers are used, and set for
* indirect pointers. Pointers are always 6 bytes.
*
* @param caller optional tree node which is latched and calling this method
* @param max maximum allowed size for returned byte array; must not be
* less than 11 (can be 9 if full value length is < 65536)
* @return null if max is too small
*/
byte[] fragment(Node caller, byte[] value, int max) throws IOException {
int pageSize = pageSize();
int pageCount = value.length / pageSize;
int remainder = value.length % pageSize;
if (value.length >= 65536) {
// Subtract header size, full length field size, and size of one pointer.
max -= (1 + 4 + 6);
} else if (pageCount == 0 && remainder <= (max - (1 + 2 + 2))) {
// Entire value fits inline. It didn't really need to be
// encoded this way, but do as we're told.
byte[] newValue = new byte[(1 + 2 + 2) + value.length];
newValue[0] = 0x02; // ff=0, i=1, p=0
writeShortLE(newValue, 1, value.length); // full length
writeShortLE(newValue, 1 + 2, value.length); // inline length
System.arraycopy(value, 0, newValue, (1 + 2 + 2), value.length);
return newValue;
} else {
// Subtract header size, full length field size, and size of one pointer.
max -= (1 + 2 + 6);
}
if (max < 0) {
return null;
}
int pointerSpace = pageCount * 6;
byte[] newValue;
if (remainder <= max && remainder < 65536
&& (pointerSpace <= (max + (6 - 2) - remainder)))
{
// Remainder fits inline, minimizing internal fragmentation. All
// extra pages will be full. All pointers fit too; encode direct.
byte header;
int offset;
if (value.length >= 65536) {
header = 0x06; // ff = 1, i=1
offset = 1 + 4;
} else {
header = 0x02; // ff = 0, i=1
offset = 1 + 2;
}
int poffset = offset + 2 + remainder;
newValue = new byte[poffset + pointerSpace];
if (pageCount > 0) {
int voffset = remainder;
while (true) {
Node node = allocDirtyNode();
try {
mFragmentCache.put(caller, node);
writeInt48LE(newValue, poffset, node.mId);
System.arraycopy(value, voffset, node.mPage, 0, pageSize);
if (pageCount == 1) {
break;
}
} finally {
node.releaseExclusive();
}
pageCount--;
poffset += 6;
voffset += pageSize;
}
}
newValue[0] = header;
writeShortLE(newValue, offset, remainder); // inline length
System.arraycopy(value, 0, newValue, offset + 2, remainder);
} else {
// Remainder doesn't fit inline, so don't encode any inline
// content. Last extra page will not be full.
pageCount++;
pointerSpace += 6;
byte header;
int offset;
if (value.length >= 65536) {
header = 0x04; // ff = 1, i=0
offset = 1 + 4;
} else {
header = 0x00; // ff = 0, i=0
offset = 1 + 2;
}
if (pointerSpace <= (max + 6)) {
// All pointers fit, so encode as direct.
newValue = new byte[offset + pointerSpace];
if (pageCount > 0) {
int voffset = 0;
while (true) {
Node node = allocDirtyNode();
try {
mFragmentCache.put(caller, node);
writeInt48LE(newValue, offset, node.mId);
if (pageCount > 1) {
System.arraycopy(value, voffset, node.mPage, 0, pageSize);
} else {
System.arraycopy(value, voffset, node.mPage, 0, remainder);
break;
}
} finally {
node.releaseExclusive();
}
pageCount--;
offset += 6;
voffset += pageSize;
}
}
} else {
// Use indirect pointers.
header |= 0x01;
newValue = new byte[offset + 6];
int levels = calculateInodeLevels(value.length, pageSize);
Node inode = allocDirtyNode();
writeInt48LE(newValue, offset, inode.mId);
writeMultilevelFragments(caller, levels, inode, value, 0, value.length);
}
newValue[0] = header;
}
// Encode full length field.
if (value.length >= 65536) {
writeIntLE(newValue, 1, value.length);
} else {
writeShortLE(newValue, 1, value.length);
}
return newValue;
}
private static int calculateInodeLevels(long valueLength, int pageSize) {
int levels = 0;
if (valueLength >= 0 && valueLength < (Long.MAX_VALUE / 2)) {
long len = (valueLength + (pageSize - 1)) / pageSize;
if (len > 1) {
int ptrCount = pageSize / 6;
do {
levels++;
} while ((len = (len + (ptrCount - 1)) / ptrCount) > 1);
}
} else {
BigInteger bPageSize = BigInteger.valueOf(pageSize);
BigInteger bLen = (valueOfUnsigned(valueLength)
.add(bPageSize.subtract(BigInteger.ONE))).divide(bPageSize);
if (bLen.compareTo(BigInteger.ONE) > 0) {
BigInteger bPtrCount = bPageSize.divide(BigInteger.valueOf(6));
BigInteger bPtrCountM1 = bPtrCount.subtract(BigInteger.ONE);
do {
levels++;
} while ((bLen = (bLen.add(bPtrCountM1)).divide(bPtrCount))
.compareTo(BigInteger.ONE) > 0);
}
}
return levels;
}
/**
* @param level inode level; at least 1
* @param inode exclusive latched parent inode; always released by this method
* @param value slice of complete value being fragmented
*/
private void writeMultilevelFragments(Node caller,
int level, Node inode,
byte[] value, int voffset, int vlength)
throws IOException
{
long levelCap;
long[] childNodeIds;
Node[] childNodes;
try {
byte[] page = inode.mPage;
level--;
levelCap = levelCap(page.length, level);
// Pre-allocate and reference the required child nodes in order for
// parent node latch to be released early. FragmentCache can then
// safely evict the parent node if necessary.
int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap);
childNodeIds = new long[childNodeCount];
childNodes = new Node[childNodeCount];
try {
for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) {
Node childNode = allocDirtyNode();
writeInt48LE(page, poffset, childNodeIds[i] = childNode.mId);
childNodes[i] = childNode;
// Allow node to be evicted, but don't write anything yet.
childNode.mCachedState = CACHED_CLEAN;
childNode.releaseExclusive();
}
} catch (Throwable e) {
for (Node childNode : childNodes) {
if (childNode != null) {
childNode.acquireExclusive();
deleteNode(childNode);
}
}
throw rethrow(e);
}
mFragmentCache.put(caller, inode);
} finally {
inode.releaseExclusive();
}
for (int i=0; i<childNodeIds.length; i++) {
long childNodeId = childNodeIds[i];
Node childNode = childNodes[i];
latchChild: {
if (childNodeId == childNode.mId) {
childNode.acquireExclusive();
if (childNodeId == childNode.mId) {
// Since commit lock is held, only need to switch the
// state. Calling redirty is unnecessary and it would
// screw up the dirty list order for no good reason.
childNode.mCachedState = mCommitState;
break latchChild;
}
}
// Child node was evicted, although it was clean.
childNode = allocLatchedNode();
childNode.mId = childNodeId;
redirty(childNode);
}
int len = (int) Math.min(levelCap, vlength);
if (level <= 0) {
System.arraycopy(value, voffset, childNode.mPage, 0, len);
mFragmentCache.put(caller, childNode);
childNode.releaseExclusive();
} else {
writeMultilevelFragments(caller, level, childNode, value, voffset, len);
}
vlength -= len;
voffset += len;
}
}
/**
* Reconstruct a fragmented value.
*
* @param caller optional tree node which is latched and calling this method
*/
byte[] reconstruct(Node caller, byte[] fragmented, int off, int len) throws IOException {
int header = fragmented[off++];
len--;
int vLen;
switch ((header >> 2) & 0x03) {
default:
vLen = readUnsignedShortLE(fragmented, off);
break;
case 1:
vLen = readIntLE(fragmented, off);
if (vLen < 0) {
throw new LargeValueException(vLen & 0xffffffffL);
}
break;
case 2:
long vLenL = readUnsignedInt48LE(fragmented, off);
if (vLenL > Integer.MAX_VALUE) {
throw new LargeValueException(vLenL);
}
vLen = (int) vLenL;
break;
case 3:
vLenL = readLongLE(fragmented, off);
if (vLenL < 0 || vLenL > Integer.MAX_VALUE) {
throw new LargeValueException(vLenL);
}
vLen = (int) vLenL;
break;
}
{
int vLenFieldSize = 2 + ((header >> 1) & 0x06);
off += vLenFieldSize;
len -= vLenFieldSize;
}
byte[] value;
try {
value = new byte[vLen];
} catch (OutOfMemoryError e) {
throw new LargeValueException(vLen, e);
}
int vOff = 0;
if ((header & 0x02) != 0) {
// Inline content.
int inLen = readUnsignedShortLE(fragmented, off);
off += 2;
len -= 2;
System.arraycopy(fragmented, off, value, vOff, inLen);
off += inLen;
len -= inLen;
vOff += inLen;
vLen -= inLen;
}
if ((header & 0x01) == 0) {
// Direct pointers.
while (len >= 6) {
long nodeId = readUnsignedInt48LE(fragmented, off);
off += 6;
len -= 6;
Node node = mFragmentCache.get(caller, nodeId);
try {
byte[] page = node.mPage;
int pLen = Math.min(vLen, page.length);
System.arraycopy(page, 0, value, vOff, pLen);
vOff += pLen;
vLen -= pLen;
} finally {
node.releaseShared();
}
}
} else {
// Indirect pointers.
int levels = calculateInodeLevels(vLen, pageSize());
long nodeId = readUnsignedInt48LE(fragmented, off);
Node inode = mFragmentCache.get(caller, nodeId);
readMultilevelFragments(caller, levels, inode, value, 0, vLen);
}
return value;
}
/**
* @param level inode level; at least 1
* @param inode shared latched parent inode; always released by this method
* @param value slice of complete value being reconstructed
*/
private void readMultilevelFragments(Node caller,
int level, Node inode,
byte[] value, int voffset, int vlength)
throws IOException
{
byte[] page = inode.mPage;
level--;
long levelCap = levelCap(page.length, level);
// Copy all child node ids and release parent latch early.
// FragmentCache can then safely evict the parent node if necessary.
int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap);
long[] childNodeIds = new long[childNodeCount];
for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) {
childNodeIds[i] = readUnsignedInt48LE(page, poffset);
}
inode.releaseShared();
for (long childNodeId : childNodeIds) {
Node childNode = mFragmentCache.get(caller, childNodeId);
int len = (int) Math.min(levelCap, vlength);
if (level <= 0) {
System.arraycopy(childNode.mPage, 0, value, voffset, len);
childNode.releaseShared();
} else {
readMultilevelFragments(caller, level, childNode, value, voffset, len);
}
vlength -= len;
voffset += len;
}
}
/**
* Delete the extra pages of a fragmented value. Caller must hold commit
* lock.
*
* @param caller optional tree node which is latched and calling this method
*/
void deleteFragments(Node caller, byte[] fragmented, int off, int len)
throws IOException
{
int header = fragmented[off++];
len--;
long vLen;
if ((header & 0x01) == 0) {
// Don't need to read the value length when deleting direct pointers.
vLen = 0;
} else {
switch ((header >> 2) & 0x03) {
default:
vLen = readUnsignedShortLE(fragmented, off);
break;
case 1:
vLen = readIntLE(fragmented, off) & 0xffffffffL;
break;
case 2:
vLen = readUnsignedInt48LE(fragmented, off);
break;
case 3:
vLen = readLongLE(fragmented, off);
break;
}
}
{
int vLenFieldSize = 2 + ((header >> 1) & 0x06);
off += vLenFieldSize;
len -= vLenFieldSize;
}
if ((header & 0x02) != 0) {
// Skip inline content.
int inLen = 2 + readUnsignedShortLE(fragmented, off);
off += inLen;
len -= inLen;
}
if ((header & 0x01) == 0) {
// Direct pointers.
while (len >= 6) {
long nodeId = readUnsignedInt48LE(fragmented, off);
off += 6;
len -= 6;
deleteFragment(caller, nodeId);
}
} else {
// Indirect pointers.
int levels = calculateInodeLevels(vLen, pageSize());
long nodeId = readUnsignedInt48LE(fragmented, off);
Node inode = removeInode(caller, nodeId);
deleteMultilevelFragments(caller, levels, inode, vLen);
}
}
/**
* @param level inode level; at least 1
* @param inode exclusive latched parent inode; always released by this method
*/
private void deleteMultilevelFragments(Node caller,
int level, Node inode, long vlength)
throws IOException
{
byte[] page = inode.mPage;
level--;
long levelCap = levelCap(page.length, level);
// Copy all child node ids and release parent latch early.
int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap);
long[] childNodeIds = new long[childNodeCount];
for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) {
childNodeIds[i] = readUnsignedInt48LE(page, poffset);
}
deleteNode(inode);
if (level <= 0) for (long childNodeId : childNodeIds) {
deleteFragment(caller, childNodeId);
} else for (long childNodeId : childNodeIds) {
Node childNode = removeInode(caller, childNodeId);
long len = Math.min(levelCap, vlength);
deleteMultilevelFragments(caller, level, childNode, len);
vlength -= len;
}
}
/**
* @return non-null Node with exclusive latch held
*/
private Node removeInode(Node caller, long nodeId) throws IOException {
Node node = mFragmentCache.remove(caller, nodeId);
if (node == null) {
node = allocLatchedNode(false);
node.mId = nodeId;
node.mType = TYPE_FRAGMENT;
node.mCachedState = readNodePage(nodeId, node.mPage);
}
return node;
}
private void deleteFragment(Node caller, long nodeId) throws IOException {
Node node = mFragmentCache.remove(caller, nodeId);
if (node != null) {
deleteNode(node);
} else if (!mHasCheckpointed) {
// Page was never used if nothing has ever been checkpointed.
mAllocator.recyclePage(nodeId);
} else {
// Page is clean if not in a Node, and so it must survive until
// after the next checkpoint.
mPageDb.deletePage(nodeId);
}
}
private static long levelCap(int pageLength, int level) {
return pageLength * (long) Math.pow(pageLength / 6, level);
}
/**
* Obtain the trash for transactionally deleting fragmented values.
*/
FragmentedTrash fragmentedTrash() throws IOException {
FragmentedTrash trash = mFragmentedTrash;
if (trash != null) {
return trash;
}
mOpenTreesLatch.acquireExclusive();
try {
if ((trash = mFragmentedTrash) != null) {
return trash;
}
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, true);
return mFragmentedTrash = new FragmentedTrash(tree);
} finally {
mOpenTreesLatch.releaseExclusive();
}
}
byte[] removeSpareBuffer() {
return mSpareBufferPool.remove();
}
void addSpareBuffer(byte[] buffer) {
mSpareBufferPool.add(buffer);
}
/**
* @return initial cached state for node
*/
byte readNodePage(long id, byte[] page) throws IOException {
mPageDb.readPage(id, page);
if (!mHasCheckpointed) {
// Read is reloading an evicted node which is known to be dirty.
mSharedCommitLock.lock();
try {
return mCommitState;
} finally {
mSharedCommitLock.unlock();
}
}
// TODO: Keep some sort of cache of ids known to be dirty. If reloaded
// before commit, then they're still dirty. Without this optimization,
// too many pages are allocated when: evictions are high, write rate is
// high, and commits are bogged down. A Bloom filter is not
// appropriate, because of false positives. A random evicting cache
// works well -- it has no collision chains. Evict whatever else was
// there in the slot. An array of longs should suffice.
return CACHED_CLEAN;
}
void checkpoint(boolean force, long sizeThreshold, long delayThresholdNanos)
throws IOException
{
// Checkpoint lock ensures consistent state between page store and logs.
synchronized (mCheckpointLock) {
if (mClosed) {
return;
}
// Now's a good time to clean things up.
cleanupUnreferencedTrees(null);
final Node root = mRegistry.mRoot;
long nowNanos = System.nanoTime();
if (!force) {
check: {
if (delayThresholdNanos == 0) {
break check;
}
if (delayThresholdNanos > 0 &&
((nowNanos - mLastCheckpointNanos) >= delayThresholdNanos))
{
break check;
}
if (mRedoWriter == null || mRedoWriter.shouldCheckpoint(sizeThreshold)) {
break check;
}
// Thresholds not met for a full checkpoint, but sync the
// redo log for durability.
mRedoWriter.sync();
return;
}
root.acquireShared();
try {
if (root.mCachedState == CACHED_CLEAN) {
// Root is clean, so nothing to do.
return;
}
} finally {
root.releaseShared();
}
}
if (mEventListener != null) {
// FIXME: Need to log a stable position; the one last recorded.
long pos = mRedoWriter == null ? 0 : mRedoWriter.checkpointPosition();
mEventListener.notify(EventType.CHECKPOINT_BEGIN,
"Checkpoint begin: %1$d", pos);
}
mLastCheckpointNanos = nowNanos;
final RedoWriter redo = mRedoWriter;
if (redo != null) {
// File-based redo log should begin writing to a new file.
redo.prepareCheckpoint();
}
{
// If the commit lock cannot be immediately obtained, it's due to a
// shared lock being held for a long time. While waiting for the
// exclusive lock, all other shared requests are queued. By waiting
// a timed amount and giving up, the exclusive lock request is
// effectively de-prioritized. For each retry, the timeout is
// doubled, to ensure that the checkpoint request is not starved.
Lock commitLock = mPageDb.exclusiveCommitLock();
while (true) {
try {
long timeoutMillis = 1;
while (!commitLock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS)) {
timeoutMillis <<= 1;
}
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
// Registry root is infrequently modified, and so shared latch
// is usually available. If not, cause might be a deadlock. To
// be safe, always release commit lock and start over.
if (root.tryAcquireShared()) {
break;
}
commitLock.unlock();
}
}
// Capture the redo checkpoint position after commit lock has been
// acquired, ensuring that no changes are in progress.
final long redoPos = redo == null ? 0 : redo.checkpointPosition();
mCheckpointFlushState = CHECKPOINT_FLUSH_PREPARE;
UndoLog masterUndoLog;
try {
// TODO: I don't like all this activity with exclusive commit
// lock held. UndoLog can be refactored to store into a special
// Tree, but this requires more features to be added to Tree
// first. Specifically, large values and appending to them.
final long masterUndoLogId;
synchronized (mTxnIdLock) {
int count = mUndoLogCount;
if (count == 0) {
masterUndoLog = null;
masterUndoLogId = 0;
} else {
masterUndoLog = new UndoLog(this);
byte[] workspace = null;
for (UndoLog log = mTopUndoLog; log != null; log = log.mPrev) {
workspace = log.writeToMaster(masterUndoLog, workspace);
}
masterUndoLogId = masterUndoLog.topNodeId();
if (masterUndoLogId == 0) {
// Nothing was actually written to the log.
masterUndoLog = null;
}
}
}
mPageDb.commit(new PageDb.CommitCallback() {
@Override
public byte[] prepare() throws IOException {
return flush(redoPos, masterUndoLogId);
}
});
} catch (IOException e) {
if (mCheckpointFlushState == CHECKPOINT_FLUSH_PREPARE) {
// Exception was thrown with locks still held.
mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING;
root.releaseShared();
mPageDb.exclusiveCommitLock().unlock();
}
throw e;
}
if (masterUndoLog != null) {
// Delete the master undo log, which won't take effect until
// the next checkpoint.
masterUndoLog.truncate(false);
}
// Note: This step is intended to discard old redo data, but it can
// get skipped if process exits at this point. Data is discarded
// again when database is re-opened.
if (mRedoWriter != null) {
mRedoWriter.checkpointed(redoPos);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - mLastCheckpointNanos) / 1000000000.0;
mEventListener.notify(EventType.CHECKPOINT_BEGIN,
"Checkpoint completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
}
}
/**
* Method is invoked with exclusive commit lock and shared root node latch
* held. Both are released by this method.
*/
private byte[] flush(final long redoPos, final long masterUndoLogId) throws IOException {
final long txnId;
synchronized (mTxnIdLock) {
txnId = mTxnId;
}
final Node root = mRegistry.mRoot;
final long rootId = root.mId;
final int stateToFlush = mCommitState;
mHasCheckpointed = true; // Must be set before switching commit state.
mCheckpointFlushState = stateToFlush;
mCommitState = (byte) (stateToFlush ^ 1);
root.releaseShared();
mPageDb.exclusiveCommitLock().unlock();
if (mEventListener != null) {
mEventListener.notify(EventType.CHECKPOINT_FLUSH, "Flushing all dirty nodes");
}
try {
mAllocator.flushDirtyNodes(stateToFlush);
} finally {
mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING;
}
byte[] header = new byte[HEADER_SIZE];
writeIntLE(header, I_ENCODING_VERSION, ENCODING_VERSION);
writeLongLE(header, I_ROOT_PAGE_ID, rootId);
writeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID, masterUndoLogId);
writeLongLE(header, I_TRANSACTION_ID, txnId);
writeLongLE(header, I_REDO_POSITION, redoPos);
// FIXME: Add a UUID field which indicates what redo system is in use.
// FIXME: Add a region for custom redo system attributes.
return header;
}
}
| false | true | private Database(DatabaseConfig config, int openMode) throws IOException {
config.mEventListener = mEventListener = SafeEventListener.makeSafe(config.mEventListener);
final File baseFile = config.mBaseFile;
final File[] dataFiles = config.dataFiles();
int pageSize = config.mPageSize;
if (pageSize <= 0) {
config.pageSize(pageSize = DEFAULT_PAGE_SIZE);
} else if (pageSize < MINIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE);
} else if (pageSize > MAXIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE);
}
int minCache, maxCache;
cacheSize: {
long minCachedBytes = Math.max(0, config.mMinCachedBytes);
long maxCachedBytes = Math.max(0, config.mMaxCachedBytes);
if (maxCachedBytes == 0) {
maxCachedBytes = minCachedBytes;
if (maxCachedBytes == 0) {
minCache = maxCache = DEFAULT_CACHED_NODES;
break cacheSize;
}
}
if (minCachedBytes > maxCachedBytes) {
throw new IllegalArgumentException
("Minimum cache size exceeds maximum: " +
minCachedBytes + " > " + maxCachedBytes);
}
minCache = nodeCountFromBytes(minCachedBytes, pageSize);
maxCache = nodeCountFromBytes(maxCachedBytes, pageSize);
minCache = Math.max(MIN_CACHED_NODES, minCache);
maxCache = Math.max(MIN_CACHED_NODES, maxCache);
}
// Update config such that info file is correct.
config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize);
config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize);
mUsageLatch = new Latch();
mMaxNodeCount = maxCache;
mDurabilityMode = config.mDurabilityMode;
mDefaultLockTimeoutNanos = config.mLockTimeoutNanos;
mLockManager = new LockManager(mDefaultLockTimeoutNanos);
if (baseFile != null && !config.mReadOnly && config.mMkdirs) {
baseFile.getParentFile().mkdirs();
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
// Create lock file and write info file of properties.
if (baseFile == null || openMode == OPEN_TEMP) {
mLockFile = null;
} else {
mLockFile = new LockedFile(new File(baseFile.getPath() + ".lock"), config.mReadOnly);
if (!config.mReadOnly) {
File infoFile = new File(baseFile.getPath() + ".info");
Writer w = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8"));
try {
config.writeInfo(w);
} finally {
w.close();
}
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
if (baseFile != null && openMode == OPEN_DESTROY) {
// Delete old redo log files.
deleteNumberedFiles(baseFile, ".redo.");
}
if (dataFiles == null) {
mPageDb = new NonPageDb(pageSize);
} else {
mPageDb = new DurablePageDb
(pageSize, dataFiles, options, config.mCrypto, openMode == OPEN_DESTROY);
}
mSharedCommitLock = mPageDb.sharedCommitLock();
try {
// Pre-allocate nodes. They are automatically added to the usage
// list, and so nothing special needs to be done to allow them to
// get used. Since the initial state is clean, evicting these
// nodes does nothing.
long cacheInitStart = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CACHE_INIT_BEGIN,
"Initializing %1$d cached nodes", minCache);
cacheInitStart = System.nanoTime();
}
try {
for (int i=minCache; --i>=0; ) {
allocLatchedNode(true).releaseExclusive();
}
} catch (OutOfMemoryError e) {
mMostRecentlyUsed = null;
mLeastRecentlyUsed = null;
throw new OutOfMemoryError
("Unable to allocate the minimum required number of cached nodes: " +
minCache);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0;
mEventListener.notify(EventType.CACHE_INIT_COMPLETE,
"Cache initialization completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
int spareBufferCount = Runtime.getRuntime().availableProcessors();
mSpareBufferPool = new BufferPool(mPageDb.pageSize(), spareBufferCount);
mSharedCommitLock.lock();
try {
mCommitState = CACHED_DIRTY_0;
} finally {
mSharedCommitLock.unlock();
}
byte[] header = new byte[HEADER_SIZE];
mPageDb.readExtraCommitData(header);
mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, loadRegistryRoot(header));
mOpenTreesLatch = new Latch();
if (openMode == OPEN_TEMP) {
mOpenTrees = Collections.emptyMap();
mOpenTreesById = new LHashTable.Obj<TreeRef>(0);
mOpenTreesRefQueue = null;
} else {
mOpenTrees = new TreeMap<byte[], TreeRef>(KeyComparator.THE);
mOpenTreesById = new LHashTable.Obj<TreeRef>(16);
mOpenTreesRefQueue = new ReferenceQueue<Tree>();
}
synchronized (mTxnIdLock) {
mTxnId = readLongLE(header, I_TRANSACTION_ID);
}
long redoPos = readLongLE(header, I_REDO_POSITION);
if (openMode == OPEN_TEMP) {
mRegistryKeyMap = null;
} else {
mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true);
}
mAllocator = new PageAllocator(mPageDb);
if (baseFile == null) {
// Non-durable database never evicts anything.
mFragmentCache = new FragmentMap();
} else {
// Regular database evicts automatically.
mFragmentCache = new FragmentCache(this, mMaxNodeCount);
}
if (openMode != OPEN_TEMP) {
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false);
if (tree != null) {
mFragmentedTrash = new FragmentedTrash(tree);
}
}
// Limit maximum fragmented entry size to guarantee that 2 entries
// fit. Each also requires 2 bytes for pointer and up to 3 bytes
// for value length field.
mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1;
long recoveryStart = 0;
if (baseFile == null || openMode == OPEN_TEMP) {
mRedoWriter = null;
} else {
// Perform recovery by examining redo and undo logs.
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin");
recoveryStart = System.nanoTime();
}
// Keep all the trees open during recovery.
mRecoveredTrees = Collections.synchronizedList(new ArrayList<Tree>());
UndoLog masterUndoLog;
LHashTable.Obj<UndoLog> undoLogs;
{
long nodeId = readLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID);
if (nodeId == 0) {
masterUndoLog = null;
undoLogs = null;
} else {
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs");
}
masterUndoLog = UndoLog.recoverMasterUndoLog(this, nodeId);
undoLogs = masterUndoLog.recoverLogs();
}
}
// FIXME: generic
RedoLogRecovery recovery = new RedoLogRecovery();
boolean doCheckpoint = recovery.recover(this, config, redoPos, undoLogs);
if (doCheckpoint) {
// Bump up the highest transaction id if recovery has seen
// higher. Although this is not expected to not happen, it
// prevents transaction id collisions when it does.
long redoTxnId = recovery.highestTxnId();
synchronized (mTxnIdLock) {
// Subtract for modulo comparison.
if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) {
mTxnId = redoTxnId;
}
}
}
if (masterUndoLog != null) {
// Rollback or truncate all remaining undo logs. They were
// never explicitly rolled back, or they were committed but
// not cleaned up. This also deletes the master undo log.
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_PROCESS_REMAINING,
"Processing remaining transactions");
}
if (masterUndoLog.processRemaining(undoLogs)) {
// Checkpoint ensures that undo logs don't get
// re-applied following a restart.
doCheckpoint = true;
}
}
mRedoWriter = recovery.newWriter();
if (doCheckpoint) {
checkpoint(true, 0, 0);
// Only cleanup after successful checkpoint.
recovery.cleanup();
}
mRecoveredTrees = null;
}
// Delete lingering fragmented values after undo logs have been
// processed, ensuring deletes were committed.
if (mFragmentedTrash != null) {
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS,
"Deleting unused large fragments");
}
if (mFragmentedTrash.emptyAllTrash()) {
checkpoint(false, 0, 0);
}
}
if (baseFile == null || openMode == OPEN_TEMP) {
mTempFileManager = null;
} else {
mTempFileManager = new TempFileManager(baseFile);
}
if (mRedoWriter != null && mEventListener != null) {
double duration = (System.nanoTime() - recoveryStart) / 1000000000.0;
mEventListener.notify(EventType.RECOVERY_COMPLETE,
"Recovery completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
} catch (Throwable e) {
closeQuietly(null, this, e);
throw rethrow(e);
}
}
| private Database(DatabaseConfig config, int openMode) throws IOException {
config.mEventListener = mEventListener = SafeEventListener.makeSafe(config.mEventListener);
final File baseFile = config.mBaseFile;
final File[] dataFiles = config.dataFiles();
int pageSize = config.mPageSize;
if (pageSize <= 0) {
config.pageSize(pageSize = DEFAULT_PAGE_SIZE);
} else if (pageSize < MINIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE);
} else if (pageSize > MAXIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE);
}
int minCache, maxCache;
cacheSize: {
long minCachedBytes = Math.max(0, config.mMinCachedBytes);
long maxCachedBytes = Math.max(0, config.mMaxCachedBytes);
if (maxCachedBytes == 0) {
maxCachedBytes = minCachedBytes;
if (maxCachedBytes == 0) {
minCache = maxCache = DEFAULT_CACHED_NODES;
break cacheSize;
}
}
if (minCachedBytes > maxCachedBytes) {
throw new IllegalArgumentException
("Minimum cache size exceeds maximum: " +
minCachedBytes + " > " + maxCachedBytes);
}
minCache = nodeCountFromBytes(minCachedBytes, pageSize);
maxCache = nodeCountFromBytes(maxCachedBytes, pageSize);
minCache = Math.max(MIN_CACHED_NODES, minCache);
maxCache = Math.max(MIN_CACHED_NODES, maxCache);
}
// Update config such that info file is correct.
config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize);
config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize);
mUsageLatch = new Latch();
mMaxNodeCount = maxCache;
mDurabilityMode = config.mDurabilityMode;
mDefaultLockTimeoutNanos = config.mLockTimeoutNanos;
mLockManager = new LockManager(mDefaultLockTimeoutNanos);
if (baseFile != null && !config.mReadOnly && config.mMkdirs) {
baseFile.getParentFile().mkdirs();
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
// Create lock file and write info file of properties.
if (baseFile == null || openMode == OPEN_TEMP) {
mLockFile = null;
} else {
mLockFile = new LockedFile(new File(baseFile.getPath() + ".lock"), config.mReadOnly);
if (!config.mReadOnly) {
File infoFile = new File(baseFile.getPath() + ".info");
Writer w = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8"));
try {
config.writeInfo(w);
} finally {
w.close();
}
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
if (baseFile != null && openMode == OPEN_DESTROY) {
// Delete old redo log files.
deleteNumberedFiles(baseFile, ".redo.");
}
if (dataFiles == null) {
mPageDb = new NonPageDb(pageSize);
} else {
mPageDb = new DurablePageDb
(pageSize, dataFiles, options, config.mCrypto, openMode == OPEN_DESTROY);
}
mSharedCommitLock = mPageDb.sharedCommitLock();
try {
// Pre-allocate nodes. They are automatically added to the usage
// list, and so nothing special needs to be done to allow them to
// get used. Since the initial state is clean, evicting these
// nodes does nothing.
long cacheInitStart = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CACHE_INIT_BEGIN,
"Initializing %1$d cached nodes", minCache);
cacheInitStart = System.nanoTime();
}
try {
for (int i=minCache; --i>=0; ) {
allocLatchedNode(true).releaseExclusive();
}
} catch (OutOfMemoryError e) {
mMostRecentlyUsed = null;
mLeastRecentlyUsed = null;
throw new OutOfMemoryError
("Unable to allocate the minimum required number of cached nodes: " +
minCache);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0;
mEventListener.notify(EventType.CACHE_INIT_COMPLETE,
"Cache initialization completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
int spareBufferCount = Runtime.getRuntime().availableProcessors();
mSpareBufferPool = new BufferPool(mPageDb.pageSize(), spareBufferCount);
mSharedCommitLock.lock();
try {
mCommitState = CACHED_DIRTY_0;
} finally {
mSharedCommitLock.unlock();
}
byte[] header = new byte[HEADER_SIZE];
mPageDb.readExtraCommitData(header);
mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, loadRegistryRoot(header));
mOpenTreesLatch = new Latch();
if (openMode == OPEN_TEMP) {
mOpenTrees = Collections.emptyMap();
mOpenTreesById = new LHashTable.Obj<TreeRef>(0);
mOpenTreesRefQueue = null;
} else {
mOpenTrees = new TreeMap<byte[], TreeRef>(KeyComparator.THE);
mOpenTreesById = new LHashTable.Obj<TreeRef>(16);
mOpenTreesRefQueue = new ReferenceQueue<Tree>();
}
synchronized (mTxnIdLock) {
mTxnId = readLongLE(header, I_TRANSACTION_ID);
}
long redoPos = readLongLE(header, I_REDO_POSITION);
if (openMode == OPEN_TEMP) {
mRegistryKeyMap = null;
} else {
mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true);
}
mAllocator = new PageAllocator(mPageDb);
if (baseFile == null) {
// Non-durable database never evicts anything.
mFragmentCache = new FragmentMap();
} else {
// Regular database evicts automatically.
mFragmentCache = new FragmentCache(this, mMaxNodeCount);
}
if (openMode != OPEN_TEMP) {
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false);
if (tree != null) {
mFragmentedTrash = new FragmentedTrash(tree);
}
}
// Limit maximum fragmented entry size to guarantee that 2 entries
// fit. Each also requires 2 bytes for pointer and up to 3 bytes
// for value length field.
mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1;
long recoveryStart = 0;
if (baseFile == null || openMode == OPEN_TEMP) {
mRedoWriter = null;
} else {
// Perform recovery by examining redo and undo logs.
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin");
recoveryStart = System.nanoTime();
}
// Keep all the trees open during recovery.
mRecoveredTrees = Collections.synchronizedList(new ArrayList<Tree>());
UndoLog masterUndoLog;
LHashTable.Obj<UndoLog> undoLogs;
{
long nodeId = readLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID);
if (nodeId == 0) {
masterUndoLog = null;
undoLogs = null;
} else {
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs");
}
masterUndoLog = UndoLog.recoverMasterUndoLog(this, nodeId);
undoLogs = masterUndoLog.recoverLogs();
}
}
// FIXME: generic
RedoLogRecovery recovery = new RedoLogRecovery();
boolean doCheckpoint = recovery.recover(this, config, redoPos, undoLogs);
if (doCheckpoint) {
// Avoid re-using transaction ids used by recovery.
long redoTxnId = recovery.highestTxnId();
if (redoTxnId != 0) {
synchronized (mTxnIdLock) {
// Subtract for modulo comparison.
if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) {
mTxnId = redoTxnId;
}
}
}
}
if (masterUndoLog != null) {
// Rollback or truncate all remaining undo logs. They were
// never explicitly rolled back, or they were committed but
// not cleaned up. This also deletes the master undo log.
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_PROCESS_REMAINING,
"Processing remaining transactions");
}
if (masterUndoLog.processRemaining(undoLogs)) {
// Checkpoint ensures that undo logs don't get
// re-applied following a restart.
doCheckpoint = true;
}
}
mRedoWriter = recovery.newWriter();
if (doCheckpoint) {
checkpoint(true, 0, 0);
// Only cleanup after successful checkpoint.
recovery.cleanup();
}
mRecoveredTrees = null;
}
// Delete lingering fragmented values after undo logs have been
// processed, ensuring deletes were committed.
if (mFragmentedTrash != null) {
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS,
"Deleting unused large fragments");
}
if (mFragmentedTrash.emptyAllTrash()) {
checkpoint(false, 0, 0);
}
}
if (baseFile == null || openMode == OPEN_TEMP) {
mTempFileManager = null;
} else {
mTempFileManager = new TempFileManager(baseFile);
}
if (mRedoWriter != null && mEventListener != null) {
double duration = (System.nanoTime() - recoveryStart) / 1000000000.0;
mEventListener.notify(EventType.RECOVERY_COMPLETE,
"Recovery completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
} catch (Throwable e) {
closeQuietly(null, this, e);
throw rethrow(e);
}
}
|
diff --git a/exporter/src/main/java/com/miravtech/sbgn/exporter/Main.java b/exporter/src/main/java/com/miravtech/sbgn/exporter/Main.java
index f46c260..138ea46 100644
--- a/exporter/src/main/java/com/miravtech/sbgn/exporter/Main.java
+++ b/exporter/src/main/java/com/miravtech/sbgn/exporter/Main.java
@@ -1,144 +1,145 @@
package com.miravtech.sbgn.exporter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import com.miravtech.SBGNUtils.INIConfiguration;
import com.miravtech.SBGNUtils.SBGNUtils;
import com.miravtech.sbgn.SBGNPDl1;
public class Main {
static JAXBContext jaxbContext;
static Unmarshaller unmarshaller;
static Marshaller marshaller;
/**
* @param args
* @throws JAXBException
*/
public static void main(String[] args) throws Exception {
String organism ;
String db ;
String method ;
File srcDir;
File destDir;
boolean filtering = true;
Properties p = INIConfiguration.getConfiguration();
OptionParser parser = new OptionParser();
parser.accepts("srcSBGN", "Name of the SBGN file to use.")
.withRequiredArg().ofType(File.class).describedAs("file path");
parser.accepts("outFile", "The target file.").withRequiredArg().ofType(
File.class).describedAs("file path");
String prop;
prop = p.getProperty("organism","HS");
parser.accepts("organism", "The name of the organism to consider")
.withOptionalArg().ofType(String.class).describedAs("Organism")
.defaultsTo(prop);
+ prop = p.getProperty("database","EntrezGeneID");
parser.accepts("db", "The database to consider.").withOptionalArg()
.ofType(String.class).describedAs("Database").defaultsTo(
prop);
prop = p.getProperty("exporter.method","GeneList");
parser.accepts("method", "The method to use.").withOptionalArg()
.ofType(String.class).describedAs("GeneList").defaultsTo(
prop);
parser.accepts("disableFilter", "Disable filtering.");
try {
OptionSet opts = parser.parse(args);
srcDir = (File) opts.valueOf("srcSBGN");
destDir = (File) opts.valueOf("outFile");
method = (String) opts.valueOf("method");
organism = (String) opts.valueOf("organism");
db = (String) opts.valueOf("db");
if (opts.has("disableFilter"))
filtering = false;
if (srcDir.getAbsolutePath().compareToIgnoreCase(
destDir.getAbsolutePath()) == 0)
throw new RuntimeException(
"Source and destination directories or files cannot be identical!");
jaxbContext = JAXBContext
.newInstance("com.miravtech.sbgn:com.miravtech.sbgn_graphics");
unmarshaller = jaxbContext.createUnmarshaller();
marshaller = jaxbContext.createMarshaller();
} catch (Exception e) {
System.out.println("Exception occured: " + e.toString()
+ "\nPossible commands:\n");
parser.printHelpOn(System.out);
return;
}
// run the function, we have the arguments;
if (method.equalsIgnoreCase("GeneList"))
exportSBGN(srcDir, destDir, organism, db, filtering);
else
throw new Exception(
"Method not supported, currently supported: GeneList");
}
public static void exportSBGN(File sourceSBGN, File destFile,
final String organism, final String db, final boolean usefilter)
throws JAXBException, IOException {
SBGNPDl1 sbgnpath = (SBGNPDl1) unmarshaller.unmarshal(sourceSBGN);
SBGNUtils utils = new SBGNUtils(sbgnpath.getValue());
utils.fillRedundantData();
Set<String> genes = utils.getSymbols(organism, db, usefilter);
FileOutputStream fos = new FileOutputStream(destFile);
PrintWriter pr = new PrintWriter(fos);
for (String g : genes)
pr.println(g);
pr.close();
}
}
class XMLFiles implements FilenameFilter {
public final static String XML = "xml";
private static Pattern file = Pattern.compile("(.*)\\." + XML);
@Override
public boolean accept(File dir, String name) {
return file.matcher(name.toLowerCase()).matches();
}
public static String getName(String name) {
Matcher m = file.matcher(name.toLowerCase());
if (!m.matches())
throw new RuntimeException("The name does not match the pattern");
return m.group(0);
}
}
| true | true | public static void main(String[] args) throws Exception {
String organism ;
String db ;
String method ;
File srcDir;
File destDir;
boolean filtering = true;
Properties p = INIConfiguration.getConfiguration();
OptionParser parser = new OptionParser();
parser.accepts("srcSBGN", "Name of the SBGN file to use.")
.withRequiredArg().ofType(File.class).describedAs("file path");
parser.accepts("outFile", "The target file.").withRequiredArg().ofType(
File.class).describedAs("file path");
String prop;
prop = p.getProperty("organism","HS");
parser.accepts("organism", "The name of the organism to consider")
.withOptionalArg().ofType(String.class).describedAs("Organism")
.defaultsTo(prop);
parser.accepts("db", "The database to consider.").withOptionalArg()
.ofType(String.class).describedAs("Database").defaultsTo(
prop);
prop = p.getProperty("exporter.method","GeneList");
parser.accepts("method", "The method to use.").withOptionalArg()
.ofType(String.class).describedAs("GeneList").defaultsTo(
prop);
parser.accepts("disableFilter", "Disable filtering.");
try {
OptionSet opts = parser.parse(args);
srcDir = (File) opts.valueOf("srcSBGN");
destDir = (File) opts.valueOf("outFile");
method = (String) opts.valueOf("method");
organism = (String) opts.valueOf("organism");
db = (String) opts.valueOf("db");
if (opts.has("disableFilter"))
filtering = false;
if (srcDir.getAbsolutePath().compareToIgnoreCase(
destDir.getAbsolutePath()) == 0)
throw new RuntimeException(
"Source and destination directories or files cannot be identical!");
jaxbContext = JAXBContext
.newInstance("com.miravtech.sbgn:com.miravtech.sbgn_graphics");
unmarshaller = jaxbContext.createUnmarshaller();
marshaller = jaxbContext.createMarshaller();
} catch (Exception e) {
System.out.println("Exception occured: " + e.toString()
+ "\nPossible commands:\n");
parser.printHelpOn(System.out);
return;
}
// run the function, we have the arguments;
if (method.equalsIgnoreCase("GeneList"))
exportSBGN(srcDir, destDir, organism, db, filtering);
else
throw new Exception(
"Method not supported, currently supported: GeneList");
}
| public static void main(String[] args) throws Exception {
String organism ;
String db ;
String method ;
File srcDir;
File destDir;
boolean filtering = true;
Properties p = INIConfiguration.getConfiguration();
OptionParser parser = new OptionParser();
parser.accepts("srcSBGN", "Name of the SBGN file to use.")
.withRequiredArg().ofType(File.class).describedAs("file path");
parser.accepts("outFile", "The target file.").withRequiredArg().ofType(
File.class).describedAs("file path");
String prop;
prop = p.getProperty("organism","HS");
parser.accepts("organism", "The name of the organism to consider")
.withOptionalArg().ofType(String.class).describedAs("Organism")
.defaultsTo(prop);
prop = p.getProperty("database","EntrezGeneID");
parser.accepts("db", "The database to consider.").withOptionalArg()
.ofType(String.class).describedAs("Database").defaultsTo(
prop);
prop = p.getProperty("exporter.method","GeneList");
parser.accepts("method", "The method to use.").withOptionalArg()
.ofType(String.class).describedAs("GeneList").defaultsTo(
prop);
parser.accepts("disableFilter", "Disable filtering.");
try {
OptionSet opts = parser.parse(args);
srcDir = (File) opts.valueOf("srcSBGN");
destDir = (File) opts.valueOf("outFile");
method = (String) opts.valueOf("method");
organism = (String) opts.valueOf("organism");
db = (String) opts.valueOf("db");
if (opts.has("disableFilter"))
filtering = false;
if (srcDir.getAbsolutePath().compareToIgnoreCase(
destDir.getAbsolutePath()) == 0)
throw new RuntimeException(
"Source and destination directories or files cannot be identical!");
jaxbContext = JAXBContext
.newInstance("com.miravtech.sbgn:com.miravtech.sbgn_graphics");
unmarshaller = jaxbContext.createUnmarshaller();
marshaller = jaxbContext.createMarshaller();
} catch (Exception e) {
System.out.println("Exception occured: " + e.toString()
+ "\nPossible commands:\n");
parser.printHelpOn(System.out);
return;
}
// run the function, we have the arguments;
if (method.equalsIgnoreCase("GeneList"))
exportSBGN(srcDir, destDir, organism, db, filtering);
else
throw new Exception(
"Method not supported, currently supported: GeneList");
}
|
diff --git a/src/main/ed/lang/ruby/RubyConvert.java b/src/main/ed/lang/ruby/RubyConvert.java
index 0d9fd966e..623effe07 100644
--- a/src/main/ed/lang/ruby/RubyConvert.java
+++ b/src/main/ed/lang/ruby/RubyConvert.java
@@ -1,683 +1,685 @@
// RubyConvert.java
package ed.lang.ruby;
import java.io.*;
import java.util.*;
import org.jruby.ast.*;
import org.jruby.common.*;
import org.jruby.parser.*;
import org.jruby.lexer.yacc.*;
import ed.js.*;
import ed.js.engine.*;
public class RubyConvert extends ed.MyAsserts {
final static boolean D = Boolean.getBoolean( "DEBUG.RUBY" );
public RubyConvert( File f )
throws IOException {
this( f.toString() , new FileInputStream( f ) );
}
public RubyConvert( String name , String code )
throws IOException {
this( name , new ByteArrayInputStream( code.getBytes() ) );
}
public RubyConvert( String name , InputStream in )
throws IOException {
_name = name;
_lines = new ArrayList<String>();
_warnings = new NullWarnings();
DefaultRubyParser p = new DefaultRubyParser();
p.setWarnings( _warnings );
RubyParserResult r = p.parse( new ParserConfiguration( 1 , true ) ,
new InputStreamLexerSource( _name , in ,
_lines , 1 , false ) );
_ast = r.getAST();
if ( D ) _print( 0 , _ast );
_add( _ast , new State() );
}
void _add( Node node , State state ){
if ( node == null || state == null )
throw new RuntimeException( "can't be null" );
// --- blocking ----
if ( node instanceof RootNode ){
_assertOne( node );
_add( node.childNodes().get(0) , state );
}
else if ( node instanceof BlockNode ){
_appned( "{\n" , node );
if ( node.childNodes() != null )
for ( Node c : node.childNodes() )
_add( c , state );
_appned( "\n}\n" , node );
}
else if ( node instanceof NewlineNode ){
_assertOne( node );
_add( node.childNodes().get(0) , state );
_appned( ";\n" , node );
}
else if ( node instanceof ReturnNode ){
_assertOne( node );
_appned( "return " , node );
_add( node.childNodes().get(0), state );
}
else if ( node instanceof IterNode ){
_addIterBlock( (IterNode)node , state );
}
// --- function stuff ---
else if ( node instanceof FCallNode ){
FCallNode f = (FCallNode)node;
if ( f.childNodes().size() == 1 &&
f.childNodes().get(0) instanceof IterNode ){
_appned( Ruby.RUBY_V_CALL + "(" + _getFuncName( f ) + ")" , f );
+ _appned( " ( " , f );
_addIterBlock( (IterNode)f.childNodes().get(0) , state );
+ _appned( " ) " , f );
}
else if ( f.getArgsNode() == null ||
f.getArgsNode().childNodes() == null ||
f.getArgsNode().childNodes().size() == 0 ){
// no args
_appned( Ruby.RUBY_V_CALL + "(" + _getFuncName( f ) + ")" , f );
}
else {
// has args
_appned( _getFuncName( f ) , node );
_addArgs( f , f.getArgsNode().childNodes() , state );
}
}
else if ( node instanceof CallNode ){
_addCall( (CallNode)node , state );
}
else if ( node instanceof DefnNode ){
DefnNode dn = (DefnNode)node;
if ( dn.childNodes().size() != 3 )
throw new RuntimeException( "DefnNode should only have 3 children" );
if ( state._className != null )
_appned( state._className + ".prototype." , node );
_appned( _mangleFunctionName( dn.getName() ) + " = function(" , node );
ArgsNode an = dn.getArgsNode();
if ( an != null && an.getArgs() != null ){
for ( int i=0; i<an.getArgs().size(); i++ ){
ArgumentNode a = (ArgumentNode)an.getArgs().get(i);
if ( i > 0 )
_appned( " , " , a );
_appned( a.getName() , a );
}
}
_appned( " ){\n" , node );
_add( dn.childNodes().get( 2 ) , state );
_appned( " \n}\n " , node );
}
else if ( node instanceof VCallNode ){
_assertNoChildren( node );
VCallNode vcn = (VCallNode)node;
_appned( Ruby.RUBY_V_CALL + "( " + vcn.getName() + ")" , node );
}
// --- class stuff ---
else if ( node instanceof ClassNode ){
// complicated enough to warrant own method
_addClass( (ClassNode)node , state );
}
else if ( node instanceof InstAsgnNode ){
_assertOne( node );
InstAsgnNode lan = (InstAsgnNode)node;
_appned( "this." + lan.getName().substring(1) + " = " , node );
_add( node.childNodes().get( 0 ) , state );
_appned( "" , node );
}
else if ( node instanceof InstVarNode ){
_assertNoChildren( node );
InstVarNode lvn = (InstVarNode)node;
_appned( "this." + lvn.getName().substring(1) , node );
}
// --- looping ---
else if ( node instanceof WhileNode ){
_assertType( node.childNodes().get(0) , NewlineNode.class );
_appned( "while ( " , node );
_add( node.childNodes().get(0).childNodes().get(0) , state );
_appned( " ){ \n " , node );
_add( node.childNodes().get(1) , state );
_appned( "\n } \n " , node );
}
else if ( node instanceof IfNode ){
IfNode ifn = (IfNode)node;
_appned( "if ( " , ifn );
if ( ifn.getCondition() != null )
_add( ifn.getCondition() , state );
_appned( " ){ \n " , ifn );
if ( ifn.getThenBody() != null )
_add( ifn.getThenBody() , state );
_appned( " } \n " , ifn );
if ( ifn.getElseBody() != null ){
_appned( " else { \n " , ifn );
_add( ifn.getElseBody() , state );
_appned( " } \n " , ifn );
}
}
// --- vars ---
else if ( node instanceof LocalAsgnNode ){
_assertOne( node );
LocalAsgnNode lan = (LocalAsgnNode)node;
_appned( "var " + lan.getName() + " = " , node );
_add( node.childNodes().get( 0 ) , state );
_appned( "" , node );
}
else if ( node instanceof LocalVarNode ){
_assertNoChildren( node );
LocalVarNode lvn = (LocalVarNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof DVarNode ){
_assertNoChildren( node );
DVarNode lvn = (DVarNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof ConstNode ){
_assertNoChildren( node );
ConstNode lvn = (ConstNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof DStrNode ){
_appned( " ( " , node );
for ( int i=0; i<node.childNodes().size(); i++ ){
if ( i > 0 )
_appned( " + " , node );
_add( node.childNodes().get(i) , state );
}
_appned( " ) " , node );
}
else if ( node instanceof EvStrNode ){
_assertOne( node );
_add( node.childNodes().get(0).childNodes().get(0) , state );
}
else if ( node instanceof Colon2Node ){
_assertOne( node );
Colon2Node cn = (Colon2Node)node;
_add( node.childNodes().get(0) , state );
_appned( "." + cn.getName() , node );
}
else if ( node instanceof AttrAssignNode ){
AttrAssignNode aan = (AttrAssignNode)node;
_appned( " ( " , aan );
_add( aan.getReceiverNode() , state );
_appned( "[" , aan );
_add( aan.getArgsNode().childNodes().get(0) , state );
_appned( "]" , aan );
_appned( " = " , aan );
_add( aan.getArgsNode().childNodes().get(1) , state );
_appned( " ) " , aan );
}
// --- literals ---
else if ( node instanceof ArrayNode ){
if ( node.childNodes() == null ||
node.childNodes().size() == 0 ){}
else if ( node.childNodes().size() > 1 ){
_appned( "[" , node );
for ( int i=0; i<node.childNodes().size(); i++){
if ( i > 0 )
_appned( " , " , node );
_add( node.childNodes().get(i) , state );
}
_appned( "]" , node );
}
else {
_add( node.childNodes().get(0) , state );
}
}
else if ( node instanceof FixnumNode ){
_assertNoChildren( node );
_appned( String.valueOf( ((FixnumNode)node).getValue() ) , node );
}
else if ( node instanceof StrNode ){
_assertNoChildren( node );
_appned( "\"" , node );
_appned( _escape( ((StrNode)node).getValue().toString() ) , node );
_appned( "\"" , node );
}
else if ( node instanceof SymbolNode ){
_assertNoChildren( node );
_appned( "\"" , node );
_appned( _escape( ((SymbolNode)node).getName() ) , node );
_appned( "\"" , node );
}
else if ( node instanceof HashNode ){
_assertOne( node );
_assertType( node.childNodes().get(0) , ArrayNode.class );
_appned( " { " , node );
List<Node> lst = node.childNodes().get(0).childNodes();
for ( int i=0; i<lst.size(); i+=2 ){
if ( i > 0 )
_appned( " , " , node );
_add( lst.get(i) , state );
_appned( " : " , node );
_add( lst.get(i+1) , state );
}
_appned( " } " , node );
}
// --- end ---
else {
String msg = "don't yet support : " + node.getClass();
msg += "\t" + node.getPosition();
System.err.println( msg );
_print( 0 , node );
throw new RuntimeException( msg );
}
}
// --- code generation types ---
void _addIterBlock( IterNode it , State state ){
_appned( "function(" , it );
if ( it.getVarNode() != null ){
final Node var = it.getVarNode();
if ( var instanceof DAsgnNode )
_appned( ((DAsgnNode)var).getName() , it );
else if ( var instanceof ConstDeclNode )
_appned( ((ConstDeclNode)var).getName() , it );
else
throw new RuntimeException( "don't know what to do with : " + var );
}
_appned( " ){ \n" , it );
_add( it.getBodyNode() , state );
_appned( " }" , it );
}
void _addClass( ClassNode cn , State state ){
final String name = cn.getCPath().getName();
state = state.child();
state._className = name;
_assertType( cn.childNodes().get(0) , Colon2Node.class );
state._classInit = _findClassInit( cn );
// constructor
if ( state._classInit == null ){
_appned( name + " = function(){};" , cn );
}
else {
_appned( name + " = function(" , state._classInit );
_appned( "){\n" , state._classInit );
_add( state._classInit.childNodes().get(2) , state );
_appned( "\n}\n" , state._classInit );
}
if ( cn.getSuperNode() != null ){
_appned( "\n" + name + ".prototype = new " , cn );
_add( cn.getSuperNode() , state );
_appned( "();\n" , cn );
}
for ( Node c : cn.childNodes() )
_addClassPiece( c , state );
}
DefnNode _findClassInit( Node n ){
for ( Node c : n.childNodes() ){
if ( c instanceof DefnNode ){
DefnNode dn = (DefnNode)c;
if ( dn.getName().equals( "initialize" ) )
return dn;
}
if ( c instanceof BlockNode ||
c instanceof NewlineNode ){
DefnNode ret = _findClassInit( c );
if ( ret != null )
return ret;
}
}
return null;
}
void _addClassPiece( Node n , State state ){
if ( n instanceof Colon2Node || // meta class info
n instanceof ConstNode // inheritance
)
return;
if ( n instanceof BlockNode ){
for ( Node c : n.childNodes() )
_addClassPiece( c , state );
return;
}
if ( n instanceof NewlineNode ){
_addClassPiece( n.childNodes().get(0) , state );
_appned( ";\n" , n );
return;
}
if ( n instanceof DefnNode ){
DefnNode dn = (DefnNode)n;
if ( dn != state._classInit )
_add( dn , state );
return;
}
if ( n instanceof FCallNode ){
FCallNode f = (FCallNode)n;
_appned( _getFuncName( f ) + ".call( " + state._className + ".prototype " , f );
if ( f.getArgsNode() != null && f.getArgsNode().childNodes() != null ){
for ( int i=0; i<f.getArgsNode().childNodes().size(); i++ ){
_appned( " , " , f );
_add( f.childNodes().get(i) , state );
}
}
_appned( ")" , f );
return;
}
throw new RuntimeException( "don't know about class piece : " + n.getClass() );
}
void _addCall( CallNode call , State state ){
if ( call.getName().equals( "[]" ) ){
_add( call.childNodes().get(0) , state );
_appned( "[" , call );
_add( call.childNodes().get(1) , state );
_appned( "]" , call );
return;
}
if ( _isOperator( call ) ){
_addArgs( call , call.childNodes() , state , " " + call.getName() + " " );
return;
}
if ( call.getName().equals( "new" ) ){
_appned( Ruby.RUBY_NEW + "( " , call );
_add( call.childNodes().get(0) , state );
_appned( " ) " , call );
return;
}
// normal function call
if ( call.childNodes().get(0) instanceof ArrayNode ){
_appned( call.getName() , call );
_addArgs( call , call.childNodes() , state );
return;
}
// class method call
if ( call.childNodes().size() > 1 ){
Node self = call.childNodes().get(0);
Node args = call.childNodes().get(1);
if ( args.childNodes().size() > 0 ){
_add( call.childNodes().get(0) , state );
_appned( "." + call.getName() , call );
if ( args instanceof ArrayNode )
_addArgs( call , args.childNodes() , state );
else {
_appned( "(" , call );
_add( args , state );
_appned( ")" , call );
}
}
else {
_appned( Ruby.RUBY_CV_CALL + "( " , call);
_add( self , state );
_appned( " , " , call );
_appned( "\"" + call.getName() + "\"" , call );
_appned( " ) " , call );
}
return;
}
// no-args
_appned( Ruby.RUBY_V_CALL + "(" , call );
_add( call.childNodes().get(0) , state );
_appned( "." + call.getName() , call );
_appned( ")" , call );
}
// ---- add args ----
void _addArgs( final Node where , List<Node> lst , final State state ){
_addArgs( where , lst , state , " , " );
}
void _addArgs( final Node where , final List<Node> lst , final State state , final String sep ){
_appned( "(" , where );
if ( lst != null ){
for ( int i=0; i<lst.size(); i++ ){
if ( i > 0 )
_appned( sep , where );
_add( lst.get( i ) , state );
}
}
_appned( ")" , where );
}
// --- asserts ---
void _assertNoChildren( Node n ){
if ( n.childNodes() != null && n.childNodes().size() > 0 )
throw new RuntimeException( "has children but shouldn't" );
}
void _assertOne( Node n ){
if ( n == null )
throw new RuntimeException( "can't be null" );
if ( n.childNodes() == null || n.childNodes().size() != 1 )
throw new RuntimeException( "need exactly 1 child" );
}
void _assertType( Node n , Class c ){
_assertType( n , c , null );
}
void _assertType( Node n , Class c , Node toDisplay ){
if ( n != null && c.isAssignableFrom( n.getClass() ) )
return;
if ( toDisplay != null )
_print( 0 , toDisplay );
String msg = n + " is not an instanceof " + c;
{
Node line = n != null ? n : toDisplay;
if ( line != null )
msg += " line: " + line.getPosition();
}
throw new RuntimeException( msg );
}
// --- utility stuff ---
void _print( int space , Node n ){
for ( int i=0; i<space; i++ )
System.out.print( " " );
System.out.println( n );
for ( Node c : n.childNodes() )
_print( space + 1 , c );
}
void _appned( String s , Node where ){
_js.append( s );
}
String _escape( String s ){
StringBuilder buf = new StringBuilder( s.length() );
for ( int i=0; i<s.length(); i++ ){
char c = s.charAt( i );
if(c == '\\')
buf.append("\\\\");
else if(c == '"')
buf.append("\\\"");
else if(c == '\n')
buf.append("\\n");
else if(c == '\r')
buf.append("\\r");
else
buf.append(c);
}
return buf.toString();
}
boolean _isOperator( CallNode node ){
if ( node.getName().equals( "[]" ) )
throw new RuntimeException( "array thing" );
return _operatorNames.contains( node.getName() );
}
String _getFuncName( FCallNode node ){
final String name = node.getName();
if ( name.equals( "puts" ) )
return "print";
return _mangleFunctionName( name );
}
String _mangleFunctionName( String name ){
if ( name.equals( "new" ) )
return Ruby.RUBY_NEWNAME;
return name;
}
public String getJSSource(){
String js = _js.toString();
if ( D ) System.out.println( js );
return js;
}
public JSFunction get()
throws IOException {
return getFunc();
}
public JSFunction getFunc()
throws IOException {
if ( _func != null )
return _func;
final String js = getJSSource();
Convert c = new Convert( _name , js , false );
_func = c.get();
return _func;
}
class State {
State(){
this( null );
}
State( State parent ){
_parent = parent;
}
State child(){
return new State( this );
}
final State _parent;
String _className;
DefnNode _classInit;
}
final String _name;
final List<String> _lines;
final IRubyWarnings _warnings;
final Node _ast;
final StringBuilder _js = new StringBuilder();
final Map<Integer,ISourcePosition> _lineMap = new TreeMap<Integer,ISourcePosition>();
private JSFunction _func;
static final Set<String> _operatorNames = new HashSet<String>();
static {
_operatorNames.add( "+" );
_operatorNames.add( "-" );
_operatorNames.add( "*" );
_operatorNames.add( "/" );
_operatorNames.add( ">" );
_operatorNames.add( ">=" );
_operatorNames.add( "<" );
_operatorNames.add( "<=" );
_operatorNames.add( "==" );
}
}
| false | true | void _add( Node node , State state ){
if ( node == null || state == null )
throw new RuntimeException( "can't be null" );
// --- blocking ----
if ( node instanceof RootNode ){
_assertOne( node );
_add( node.childNodes().get(0) , state );
}
else if ( node instanceof BlockNode ){
_appned( "{\n" , node );
if ( node.childNodes() != null )
for ( Node c : node.childNodes() )
_add( c , state );
_appned( "\n}\n" , node );
}
else if ( node instanceof NewlineNode ){
_assertOne( node );
_add( node.childNodes().get(0) , state );
_appned( ";\n" , node );
}
else if ( node instanceof ReturnNode ){
_assertOne( node );
_appned( "return " , node );
_add( node.childNodes().get(0), state );
}
else if ( node instanceof IterNode ){
_addIterBlock( (IterNode)node , state );
}
// --- function stuff ---
else if ( node instanceof FCallNode ){
FCallNode f = (FCallNode)node;
if ( f.childNodes().size() == 1 &&
f.childNodes().get(0) instanceof IterNode ){
_appned( Ruby.RUBY_V_CALL + "(" + _getFuncName( f ) + ")" , f );
_addIterBlock( (IterNode)f.childNodes().get(0) , state );
}
else if ( f.getArgsNode() == null ||
f.getArgsNode().childNodes() == null ||
f.getArgsNode().childNodes().size() == 0 ){
// no args
_appned( Ruby.RUBY_V_CALL + "(" + _getFuncName( f ) + ")" , f );
}
else {
// has args
_appned( _getFuncName( f ) , node );
_addArgs( f , f.getArgsNode().childNodes() , state );
}
}
else if ( node instanceof CallNode ){
_addCall( (CallNode)node , state );
}
else if ( node instanceof DefnNode ){
DefnNode dn = (DefnNode)node;
if ( dn.childNodes().size() != 3 )
throw new RuntimeException( "DefnNode should only have 3 children" );
if ( state._className != null )
_appned( state._className + ".prototype." , node );
_appned( _mangleFunctionName( dn.getName() ) + " = function(" , node );
ArgsNode an = dn.getArgsNode();
if ( an != null && an.getArgs() != null ){
for ( int i=0; i<an.getArgs().size(); i++ ){
ArgumentNode a = (ArgumentNode)an.getArgs().get(i);
if ( i > 0 )
_appned( " , " , a );
_appned( a.getName() , a );
}
}
_appned( " ){\n" , node );
_add( dn.childNodes().get( 2 ) , state );
_appned( " \n}\n " , node );
}
else if ( node instanceof VCallNode ){
_assertNoChildren( node );
VCallNode vcn = (VCallNode)node;
_appned( Ruby.RUBY_V_CALL + "( " + vcn.getName() + ")" , node );
}
// --- class stuff ---
else if ( node instanceof ClassNode ){
// complicated enough to warrant own method
_addClass( (ClassNode)node , state );
}
else if ( node instanceof InstAsgnNode ){
_assertOne( node );
InstAsgnNode lan = (InstAsgnNode)node;
_appned( "this." + lan.getName().substring(1) + " = " , node );
_add( node.childNodes().get( 0 ) , state );
_appned( "" , node );
}
else if ( node instanceof InstVarNode ){
_assertNoChildren( node );
InstVarNode lvn = (InstVarNode)node;
_appned( "this." + lvn.getName().substring(1) , node );
}
// --- looping ---
else if ( node instanceof WhileNode ){
_assertType( node.childNodes().get(0) , NewlineNode.class );
_appned( "while ( " , node );
_add( node.childNodes().get(0).childNodes().get(0) , state );
_appned( " ){ \n " , node );
_add( node.childNodes().get(1) , state );
_appned( "\n } \n " , node );
}
else if ( node instanceof IfNode ){
IfNode ifn = (IfNode)node;
_appned( "if ( " , ifn );
if ( ifn.getCondition() != null )
_add( ifn.getCondition() , state );
_appned( " ){ \n " , ifn );
if ( ifn.getThenBody() != null )
_add( ifn.getThenBody() , state );
_appned( " } \n " , ifn );
if ( ifn.getElseBody() != null ){
_appned( " else { \n " , ifn );
_add( ifn.getElseBody() , state );
_appned( " } \n " , ifn );
}
}
// --- vars ---
else if ( node instanceof LocalAsgnNode ){
_assertOne( node );
LocalAsgnNode lan = (LocalAsgnNode)node;
_appned( "var " + lan.getName() + " = " , node );
_add( node.childNodes().get( 0 ) , state );
_appned( "" , node );
}
else if ( node instanceof LocalVarNode ){
_assertNoChildren( node );
LocalVarNode lvn = (LocalVarNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof DVarNode ){
_assertNoChildren( node );
DVarNode lvn = (DVarNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof ConstNode ){
_assertNoChildren( node );
ConstNode lvn = (ConstNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof DStrNode ){
_appned( " ( " , node );
for ( int i=0; i<node.childNodes().size(); i++ ){
if ( i > 0 )
_appned( " + " , node );
_add( node.childNodes().get(i) , state );
}
_appned( " ) " , node );
}
else if ( node instanceof EvStrNode ){
_assertOne( node );
_add( node.childNodes().get(0).childNodes().get(0) , state );
}
else if ( node instanceof Colon2Node ){
_assertOne( node );
Colon2Node cn = (Colon2Node)node;
_add( node.childNodes().get(0) , state );
_appned( "." + cn.getName() , node );
}
else if ( node instanceof AttrAssignNode ){
AttrAssignNode aan = (AttrAssignNode)node;
_appned( " ( " , aan );
_add( aan.getReceiverNode() , state );
_appned( "[" , aan );
_add( aan.getArgsNode().childNodes().get(0) , state );
_appned( "]" , aan );
_appned( " = " , aan );
_add( aan.getArgsNode().childNodes().get(1) , state );
_appned( " ) " , aan );
}
// --- literals ---
else if ( node instanceof ArrayNode ){
if ( node.childNodes() == null ||
node.childNodes().size() == 0 ){}
else if ( node.childNodes().size() > 1 ){
_appned( "[" , node );
for ( int i=0; i<node.childNodes().size(); i++){
if ( i > 0 )
_appned( " , " , node );
_add( node.childNodes().get(i) , state );
}
_appned( "]" , node );
}
else {
_add( node.childNodes().get(0) , state );
}
}
else if ( node instanceof FixnumNode ){
_assertNoChildren( node );
_appned( String.valueOf( ((FixnumNode)node).getValue() ) , node );
}
else if ( node instanceof StrNode ){
_assertNoChildren( node );
_appned( "\"" , node );
_appned( _escape( ((StrNode)node).getValue().toString() ) , node );
_appned( "\"" , node );
}
else if ( node instanceof SymbolNode ){
_assertNoChildren( node );
_appned( "\"" , node );
_appned( _escape( ((SymbolNode)node).getName() ) , node );
_appned( "\"" , node );
}
else if ( node instanceof HashNode ){
_assertOne( node );
_assertType( node.childNodes().get(0) , ArrayNode.class );
_appned( " { " , node );
List<Node> lst = node.childNodes().get(0).childNodes();
for ( int i=0; i<lst.size(); i+=2 ){
if ( i > 0 )
_appned( " , " , node );
_add( lst.get(i) , state );
_appned( " : " , node );
_add( lst.get(i+1) , state );
}
_appned( " } " , node );
}
// --- end ---
else {
String msg = "don't yet support : " + node.getClass();
msg += "\t" + node.getPosition();
System.err.println( msg );
_print( 0 , node );
throw new RuntimeException( msg );
}
}
| void _add( Node node , State state ){
if ( node == null || state == null )
throw new RuntimeException( "can't be null" );
// --- blocking ----
if ( node instanceof RootNode ){
_assertOne( node );
_add( node.childNodes().get(0) , state );
}
else if ( node instanceof BlockNode ){
_appned( "{\n" , node );
if ( node.childNodes() != null )
for ( Node c : node.childNodes() )
_add( c , state );
_appned( "\n}\n" , node );
}
else if ( node instanceof NewlineNode ){
_assertOne( node );
_add( node.childNodes().get(0) , state );
_appned( ";\n" , node );
}
else if ( node instanceof ReturnNode ){
_assertOne( node );
_appned( "return " , node );
_add( node.childNodes().get(0), state );
}
else if ( node instanceof IterNode ){
_addIterBlock( (IterNode)node , state );
}
// --- function stuff ---
else if ( node instanceof FCallNode ){
FCallNode f = (FCallNode)node;
if ( f.childNodes().size() == 1 &&
f.childNodes().get(0) instanceof IterNode ){
_appned( Ruby.RUBY_V_CALL + "(" + _getFuncName( f ) + ")" , f );
_appned( " ( " , f );
_addIterBlock( (IterNode)f.childNodes().get(0) , state );
_appned( " ) " , f );
}
else if ( f.getArgsNode() == null ||
f.getArgsNode().childNodes() == null ||
f.getArgsNode().childNodes().size() == 0 ){
// no args
_appned( Ruby.RUBY_V_CALL + "(" + _getFuncName( f ) + ")" , f );
}
else {
// has args
_appned( _getFuncName( f ) , node );
_addArgs( f , f.getArgsNode().childNodes() , state );
}
}
else if ( node instanceof CallNode ){
_addCall( (CallNode)node , state );
}
else if ( node instanceof DefnNode ){
DefnNode dn = (DefnNode)node;
if ( dn.childNodes().size() != 3 )
throw new RuntimeException( "DefnNode should only have 3 children" );
if ( state._className != null )
_appned( state._className + ".prototype." , node );
_appned( _mangleFunctionName( dn.getName() ) + " = function(" , node );
ArgsNode an = dn.getArgsNode();
if ( an != null && an.getArgs() != null ){
for ( int i=0; i<an.getArgs().size(); i++ ){
ArgumentNode a = (ArgumentNode)an.getArgs().get(i);
if ( i > 0 )
_appned( " , " , a );
_appned( a.getName() , a );
}
}
_appned( " ){\n" , node );
_add( dn.childNodes().get( 2 ) , state );
_appned( " \n}\n " , node );
}
else if ( node instanceof VCallNode ){
_assertNoChildren( node );
VCallNode vcn = (VCallNode)node;
_appned( Ruby.RUBY_V_CALL + "( " + vcn.getName() + ")" , node );
}
// --- class stuff ---
else if ( node instanceof ClassNode ){
// complicated enough to warrant own method
_addClass( (ClassNode)node , state );
}
else if ( node instanceof InstAsgnNode ){
_assertOne( node );
InstAsgnNode lan = (InstAsgnNode)node;
_appned( "this." + lan.getName().substring(1) + " = " , node );
_add( node.childNodes().get( 0 ) , state );
_appned( "" , node );
}
else if ( node instanceof InstVarNode ){
_assertNoChildren( node );
InstVarNode lvn = (InstVarNode)node;
_appned( "this." + lvn.getName().substring(1) , node );
}
// --- looping ---
else if ( node instanceof WhileNode ){
_assertType( node.childNodes().get(0) , NewlineNode.class );
_appned( "while ( " , node );
_add( node.childNodes().get(0).childNodes().get(0) , state );
_appned( " ){ \n " , node );
_add( node.childNodes().get(1) , state );
_appned( "\n } \n " , node );
}
else if ( node instanceof IfNode ){
IfNode ifn = (IfNode)node;
_appned( "if ( " , ifn );
if ( ifn.getCondition() != null )
_add( ifn.getCondition() , state );
_appned( " ){ \n " , ifn );
if ( ifn.getThenBody() != null )
_add( ifn.getThenBody() , state );
_appned( " } \n " , ifn );
if ( ifn.getElseBody() != null ){
_appned( " else { \n " , ifn );
_add( ifn.getElseBody() , state );
_appned( " } \n " , ifn );
}
}
// --- vars ---
else if ( node instanceof LocalAsgnNode ){
_assertOne( node );
LocalAsgnNode lan = (LocalAsgnNode)node;
_appned( "var " + lan.getName() + " = " , node );
_add( node.childNodes().get( 0 ) , state );
_appned( "" , node );
}
else if ( node instanceof LocalVarNode ){
_assertNoChildren( node );
LocalVarNode lvn = (LocalVarNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof DVarNode ){
_assertNoChildren( node );
DVarNode lvn = (DVarNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof ConstNode ){
_assertNoChildren( node );
ConstNode lvn = (ConstNode)node;
_appned( lvn.getName() , node );
}
else if ( node instanceof DStrNode ){
_appned( " ( " , node );
for ( int i=0; i<node.childNodes().size(); i++ ){
if ( i > 0 )
_appned( " + " , node );
_add( node.childNodes().get(i) , state );
}
_appned( " ) " , node );
}
else if ( node instanceof EvStrNode ){
_assertOne( node );
_add( node.childNodes().get(0).childNodes().get(0) , state );
}
else if ( node instanceof Colon2Node ){
_assertOne( node );
Colon2Node cn = (Colon2Node)node;
_add( node.childNodes().get(0) , state );
_appned( "." + cn.getName() , node );
}
else if ( node instanceof AttrAssignNode ){
AttrAssignNode aan = (AttrAssignNode)node;
_appned( " ( " , aan );
_add( aan.getReceiverNode() , state );
_appned( "[" , aan );
_add( aan.getArgsNode().childNodes().get(0) , state );
_appned( "]" , aan );
_appned( " = " , aan );
_add( aan.getArgsNode().childNodes().get(1) , state );
_appned( " ) " , aan );
}
// --- literals ---
else if ( node instanceof ArrayNode ){
if ( node.childNodes() == null ||
node.childNodes().size() == 0 ){}
else if ( node.childNodes().size() > 1 ){
_appned( "[" , node );
for ( int i=0; i<node.childNodes().size(); i++){
if ( i > 0 )
_appned( " , " , node );
_add( node.childNodes().get(i) , state );
}
_appned( "]" , node );
}
else {
_add( node.childNodes().get(0) , state );
}
}
else if ( node instanceof FixnumNode ){
_assertNoChildren( node );
_appned( String.valueOf( ((FixnumNode)node).getValue() ) , node );
}
else if ( node instanceof StrNode ){
_assertNoChildren( node );
_appned( "\"" , node );
_appned( _escape( ((StrNode)node).getValue().toString() ) , node );
_appned( "\"" , node );
}
else if ( node instanceof SymbolNode ){
_assertNoChildren( node );
_appned( "\"" , node );
_appned( _escape( ((SymbolNode)node).getName() ) , node );
_appned( "\"" , node );
}
else if ( node instanceof HashNode ){
_assertOne( node );
_assertType( node.childNodes().get(0) , ArrayNode.class );
_appned( " { " , node );
List<Node> lst = node.childNodes().get(0).childNodes();
for ( int i=0; i<lst.size(); i+=2 ){
if ( i > 0 )
_appned( " , " , node );
_add( lst.get(i) , state );
_appned( " : " , node );
_add( lst.get(i+1) , state );
}
_appned( " } " , node );
}
// --- end ---
else {
String msg = "don't yet support : " + node.getClass();
msg += "\t" + node.getPosition();
System.err.println( msg );
_print( 0 , node );
throw new RuntimeException( msg );
}
}
|
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/ProcessPanelAutomationHelper.java b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/ProcessPanelAutomationHelper.java
index 8ec6a3fe..fb97e1e0 100644
--- a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/ProcessPanelAutomationHelper.java
+++ b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/ProcessPanelAutomationHelper.java
@@ -1,130 +1,130 @@
/*
* IzPack - Copyright 2001-2006 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://developer.berlios.de/projects/izpack/
*
* Copyright 2003 Jonathan Halliday
*
* 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.izforge.izpack.panels;
import java.io.IOException;
import net.n3.nanoxml.XMLElement;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.PanelAutomation;
import com.izforge.izpack.installer.PanelAutomationHelper;
import com.izforge.izpack.installer.ProcessPanelWorker;
import com.izforge.izpack.util.AbstractUIProcessHandler;
/**
* Functions to support automated usage of the CompilePanel
*
* @author Jonathan Halliday
* @author Tino Schwarze
*/
public class ProcessPanelAutomationHelper extends PanelAutomationHelper implements PanelAutomation,
AbstractUIProcessHandler
{
private int noOfJobs = 0;
private int currentJob = 0;
/**
* Save data for running automated.
*
* @param installData installation parameters
* @param panelRoot unused.
*/
public void makeXMLData(AutomatedInstallData installData, XMLElement panelRoot)
{
// not used here - during automatic installation, no automatic
// installation information is generated
}
/**
* Perform the installation actions.
*
* @param panelRoot The panel XML tree root.
*
* @return true if processes were run successfully.
*/
public boolean runAutomated(AutomatedInstallData idata, XMLElement panelRoot)
{
try
{
ProcessPanelWorker worker = new ProcessPanelWorker(idata, this);
worker.run();
- return this.worker.getResult();
+ return worker.getResult();
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
public void logOutput(String message, boolean stderr)
{
if (stderr)
{
System.err.println(message);
}
else
{
System.out.println(message);
}
}
/**
* Reports progress on System.out
*
* @see com.izforge.izpack.util.AbstractUIProcessHandler#startProcessing(int)
*/
public void startProcessing(int noOfJobs)
{
System.out.println("[ Starting processing ]");
this.noOfJobs = noOfJobs;
}
/**
*
* @see com.izforge.izpack.util.AbstractUIProcessHandler#finishProcessing()
*/
public void finishProcessing()
{
System.out.println("[ Processing finished ]");
}
/**
*
*/
public void startProcess(String name)
{
this.currentJob++;
System.out.println("Starting process " + name + " (" + Integer.toString(this.currentJob)
+ "/" + Integer.toString(this.noOfJobs) + ")");
}
public void finishProcess()
{
}
}
| true | true | public boolean runAutomated(AutomatedInstallData idata, XMLElement panelRoot)
{
try
{
ProcessPanelWorker worker = new ProcessPanelWorker(idata, this);
worker.run();
return this.worker.getResult();
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
| public boolean runAutomated(AutomatedInstallData idata, XMLElement panelRoot)
{
try
{
ProcessPanelWorker worker = new ProcessPanelWorker(idata, this);
worker.run();
return worker.getResult();
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
|
diff --git a/src/cytoscape/data/readers/CyAttributesReader.java b/src/cytoscape/data/readers/CyAttributesReader.java
index 85bd3a9c2..04d7927fc 100644
--- a/src/cytoscape/data/readers/CyAttributesReader.java
+++ b/src/cytoscape/data/readers/CyAttributesReader.java
@@ -1,360 +1,374 @@
/*
File: CyAttributesReader.java
Copyright (c) 2006, The Cytoscape Consortium (www.cytoscape.org)
The Cytoscape Consortium is:
- Institute for Systems Biology
- University of California San Diego
- Memorial Sloan-Kettering Cancer Center
- Institut Pasteur
- Agilent Technologies
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package cytoscape.data.readers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import cytoscape.data.CyAttributes;
import cytoscape.data.attr.MultiHashMapDefinition;
import cytoscape.data.writers.CyAttributesWriter;
import cytoscape.logger.CyLogger;
import java.net.URLDecoder;
import java.text.MessageFormat;
// I hate writing parsing code. Grumble grumble grumble.
/**
*
*/
public class CyAttributesReader {
public static final String DECODE_PROPERTY = "cytoscape.decode.attributes";
private static final String badDecodeMessage =
"Trouble when decoding attribute value, first occurence line no. {0}" +
"\nIgnore if attributes file was created before 2.6.3 or wasn't creatad by Cytoscape." +
"\nUse -Dcytoscape.decode.attributes=false when starting Cytoscape to turn off decoding.";
private boolean badDecode;
private int lineNum;
private boolean doDecoding;
public CyAttributesReader() {
lineNum = 0;
doDecoding = Boolean.valueOf(System.getProperty(DECODE_PROPERTY, "true"));
}
/**
* DOCUMENT ME!
*
* @param cyAttrs DOCUMENT ME!
* @param fileIn DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
public static void loadAttributes(CyAttributes cyAttrs, Reader fileIn) throws IOException {
CyAttributesReader ar = new CyAttributesReader();
ar.loadAttributesInternal(cyAttrs, fileIn);
}
/**
* DOCUMENT ME!
*
* @param cyAttrs DOCUMENT ME!
* @param fileIn DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
public void loadAttributesInternal(CyAttributes cyAttrs, Reader fileIn)
throws IOException {
badDecode = false;
+ boolean guessedAttrType = false; // We later set this to true if we have to guess the attribute type.
try {
final BufferedReader reader;
if (fileIn instanceof BufferedReader) {
reader = (BufferedReader) fileIn;
} else {
reader = new BufferedReader(fileIn);
}
String attributeName;
byte type = -1;
{
final String firstLine = reader.readLine();
lineNum++;
if (firstLine == null) {
return;
}
final String searchStr = "class=";
final int inx = firstLine.indexOf(searchStr);
if (inx < 0) {
attributeName = firstLine.trim();
} else {
attributeName = firstLine.substring(0, inx - 1).trim();
String foo = firstLine.substring(inx);
final StringTokenizer tokens = new StringTokenizer(foo);
foo = tokens.nextToken();
String className = foo.substring(searchStr.length()).trim();
if (className.endsWith(")")) {
className = className.substring(0, className.length() - 1);
}
if (className.equalsIgnoreCase("java.lang.String")
|| className.equalsIgnoreCase("String")) {
type = MultiHashMapDefinition.TYPE_STRING;
} else if (className.equalsIgnoreCase("java.lang.Boolean")
|| className.equalsIgnoreCase("Boolean")) {
type = MultiHashMapDefinition.TYPE_BOOLEAN;
} else if (className.equalsIgnoreCase("java.lang.Integer")
|| className.equalsIgnoreCase("Integer")) {
type = MultiHashMapDefinition.TYPE_INTEGER;
} else if (className.equalsIgnoreCase("java.lang.Double")
|| className.equalsIgnoreCase("Double")
|| className.equalsIgnoreCase("java.lang.Float")
|| className.equalsIgnoreCase("Float")) {
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
}
}
}
if (attributeName.indexOf("(") >= 0) {
attributeName = attributeName.substring(0, attributeName.indexOf("(")).trim();
}
boolean firstLine = true;
boolean list = false;
while (true) {
final String line = reader.readLine();
lineNum++;
if (line == null) {
break;
}
if ("".equals(line.trim())) {
continue;
}
int inx = line.indexOf('=');
String key = line.substring(0, inx).trim();
String val = line.substring(inx + 1).trim();
key = decodeString(key);
if (firstLine && val.startsWith("(")) {
list = true;
}
if (list) {
// Chop away leading '(' and trailing ')'.
val = val.substring(1).trim();
val = val.substring(0, val.length() - 1).trim();
String[] elms = val.split("::");
final ArrayList elmsBuff = new ArrayList();
for (String vs : elms) {
vs = decodeString(vs);
vs = decodeSlashEscapes(vs);
elmsBuff.add(vs);
}
if (firstLine) {
if (type < 0) {
+ guessedAttrType = true;
while (true) {
try {
new Integer((String) elmsBuff.get(0));
type = MultiHashMapDefinition.TYPE_INTEGER;
break;
} catch (Exception e) {
}
try {
new Double((String) elmsBuff.get(0));
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
break;
} catch (Exception e) {
}
// try {
// new Boolean((String) elmsBuff.get(0));
// type = MultiHashMapDefinition.TYPE_BOOLEAN;
// break; }
// catch (Exception e) {}
type = MultiHashMapDefinition.TYPE_STRING;
break;
}
}
firstLine = false;
}
for (int i = 0; i < elmsBuff.size(); i++) {
if (type == MultiHashMapDefinition.TYPE_INTEGER) {
elmsBuff.set(i, new Integer((String) elmsBuff.get(i)));
} else if (type == MultiHashMapDefinition.TYPE_BOOLEAN) {
elmsBuff.set(i, new Boolean((String) elmsBuff.get(i)));
} else if (type == MultiHashMapDefinition.TYPE_FLOATING_POINT) {
elmsBuff.set(i, new Double((String) elmsBuff.get(i)));
} else {
// A string; do nothing.
}
}
cyAttrs.setListAttribute(key, attributeName, elmsBuff);
} else { // Not a list.
val = decodeString(val);
val = decodeSlashEscapes(val);
if (firstLine) {
if (type < 0) {
+ guessedAttrType = true;
while (true) {
try {
new Integer(val);
type = MultiHashMapDefinition.TYPE_INTEGER;
break;
} catch (Exception e) {
}
try {
new Double(val);
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
break;
} catch (Exception e) {
}
// try {
// new Boolean(val);
// type = MultiHashMapDefinition.TYPE_BOOLEAN;
// break; }
// catch (Exception e) {}
type = MultiHashMapDefinition.TYPE_STRING;
break;
}
}
firstLine = false;
}
if (type == MultiHashMapDefinition.TYPE_INTEGER) {
cyAttrs.setAttribute(key, attributeName, new Integer(val));
} else if (type == MultiHashMapDefinition.TYPE_BOOLEAN) {
cyAttrs.setAttribute(key, attributeName, new Boolean(val));
} else if (type == MultiHashMapDefinition.TYPE_FLOATING_POINT) {
cyAttrs.setAttribute(key, attributeName, new Double(val));
} else {
cyAttrs.setAttribute(key, attributeName, val);
}
}
}
} catch (Exception e) {
- String message = "failed parsing attributes file at line: " + lineNum
- + " with exception: " + e.getMessage();
+ String message;
+ if (guessedAttrType) {
+ message = "failed parsing attributes file at line: " + lineNum
+ + " with exception: " + e.getMessage()
+ + " This is most likely due to a missing attribute type on the first line.\n"
+ + "Attribute type should be one of the following: "
+ + "(class=String), (class=Boolean), (class=Integer), or (class=Double). "
+ + "(\"Double\" stands for a floating point a.k.a. \"decimal\" number.)"
+ + " This should be added to end of the first line.";
+ }
+ else
+ message = "failed parsing attributes file at line: " + lineNum
+ + " with exception: " + e.getMessage();
CyLogger.getLogger(CyAttributesReader.class).warn(message, e);
throw new IOException(message);
}
}
private String decodeString(String in) throws IOException {
if (doDecoding) {
try {
in = URLDecoder.decode(in, CyAttributesWriter.ENCODING_SCHEME);
}
catch (IllegalArgumentException iae) {
if (!badDecode) {
CyLogger.getLogger(CyAttributesReader.class).info(MessageFormat.format(badDecodeMessage, lineNum), iae);
badDecode = true;
}
}
}
return in;
}
private static String decodeSlashEscapes(String in) {
final StringBuilder elmBuff = new StringBuilder();
int inx2;
for (inx2 = 0; inx2 < in.length(); inx2++) {
char ch = in.charAt(inx2);
if (ch == '\\') {
if ((inx2 + 1) < in.length()) {
inx2++;
char ch2 = in.charAt(inx2);
if (ch2 == 'n') {
elmBuff.append('\n');
} else if (ch2 == 't') {
elmBuff.append('\t');
} else if (ch2 == 'b') {
elmBuff.append('\b');
} else if (ch2 == 'r') {
elmBuff.append('\r');
} else if (ch2 == 'f') {
elmBuff.append('\f');
} else {
elmBuff.append(ch2);
}
} else {
/* val ends in '\' - just ignore it. */ }
} else {
elmBuff.append(ch);
}
}
return elmBuff.toString();
}
public boolean isDoDecoding() {
return doDecoding;
}
public void setDoDecoding(boolean doDec) {
doDecoding = doDec;
}
}
| false | true | public void loadAttributesInternal(CyAttributes cyAttrs, Reader fileIn)
throws IOException {
badDecode = false;
try {
final BufferedReader reader;
if (fileIn instanceof BufferedReader) {
reader = (BufferedReader) fileIn;
} else {
reader = new BufferedReader(fileIn);
}
String attributeName;
byte type = -1;
{
final String firstLine = reader.readLine();
lineNum++;
if (firstLine == null) {
return;
}
final String searchStr = "class=";
final int inx = firstLine.indexOf(searchStr);
if (inx < 0) {
attributeName = firstLine.trim();
} else {
attributeName = firstLine.substring(0, inx - 1).trim();
String foo = firstLine.substring(inx);
final StringTokenizer tokens = new StringTokenizer(foo);
foo = tokens.nextToken();
String className = foo.substring(searchStr.length()).trim();
if (className.endsWith(")")) {
className = className.substring(0, className.length() - 1);
}
if (className.equalsIgnoreCase("java.lang.String")
|| className.equalsIgnoreCase("String")) {
type = MultiHashMapDefinition.TYPE_STRING;
} else if (className.equalsIgnoreCase("java.lang.Boolean")
|| className.equalsIgnoreCase("Boolean")) {
type = MultiHashMapDefinition.TYPE_BOOLEAN;
} else if (className.equalsIgnoreCase("java.lang.Integer")
|| className.equalsIgnoreCase("Integer")) {
type = MultiHashMapDefinition.TYPE_INTEGER;
} else if (className.equalsIgnoreCase("java.lang.Double")
|| className.equalsIgnoreCase("Double")
|| className.equalsIgnoreCase("java.lang.Float")
|| className.equalsIgnoreCase("Float")) {
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
}
}
}
if (attributeName.indexOf("(") >= 0) {
attributeName = attributeName.substring(0, attributeName.indexOf("(")).trim();
}
boolean firstLine = true;
boolean list = false;
while (true) {
final String line = reader.readLine();
lineNum++;
if (line == null) {
break;
}
if ("".equals(line.trim())) {
continue;
}
int inx = line.indexOf('=');
String key = line.substring(0, inx).trim();
String val = line.substring(inx + 1).trim();
key = decodeString(key);
if (firstLine && val.startsWith("(")) {
list = true;
}
if (list) {
// Chop away leading '(' and trailing ')'.
val = val.substring(1).trim();
val = val.substring(0, val.length() - 1).trim();
String[] elms = val.split("::");
final ArrayList elmsBuff = new ArrayList();
for (String vs : elms) {
vs = decodeString(vs);
vs = decodeSlashEscapes(vs);
elmsBuff.add(vs);
}
if (firstLine) {
if (type < 0) {
while (true) {
try {
new Integer((String) elmsBuff.get(0));
type = MultiHashMapDefinition.TYPE_INTEGER;
break;
} catch (Exception e) {
}
try {
new Double((String) elmsBuff.get(0));
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
break;
} catch (Exception e) {
}
// try {
// new Boolean((String) elmsBuff.get(0));
// type = MultiHashMapDefinition.TYPE_BOOLEAN;
// break; }
// catch (Exception e) {}
type = MultiHashMapDefinition.TYPE_STRING;
break;
}
}
firstLine = false;
}
for (int i = 0; i < elmsBuff.size(); i++) {
if (type == MultiHashMapDefinition.TYPE_INTEGER) {
elmsBuff.set(i, new Integer((String) elmsBuff.get(i)));
} else if (type == MultiHashMapDefinition.TYPE_BOOLEAN) {
elmsBuff.set(i, new Boolean((String) elmsBuff.get(i)));
} else if (type == MultiHashMapDefinition.TYPE_FLOATING_POINT) {
elmsBuff.set(i, new Double((String) elmsBuff.get(i)));
} else {
// A string; do nothing.
}
}
cyAttrs.setListAttribute(key, attributeName, elmsBuff);
} else { // Not a list.
val = decodeString(val);
val = decodeSlashEscapes(val);
if (firstLine) {
if (type < 0) {
while (true) {
try {
new Integer(val);
type = MultiHashMapDefinition.TYPE_INTEGER;
break;
} catch (Exception e) {
}
try {
new Double(val);
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
break;
} catch (Exception e) {
}
// try {
// new Boolean(val);
// type = MultiHashMapDefinition.TYPE_BOOLEAN;
// break; }
// catch (Exception e) {}
type = MultiHashMapDefinition.TYPE_STRING;
break;
}
}
firstLine = false;
}
if (type == MultiHashMapDefinition.TYPE_INTEGER) {
cyAttrs.setAttribute(key, attributeName, new Integer(val));
} else if (type == MultiHashMapDefinition.TYPE_BOOLEAN) {
cyAttrs.setAttribute(key, attributeName, new Boolean(val));
} else if (type == MultiHashMapDefinition.TYPE_FLOATING_POINT) {
cyAttrs.setAttribute(key, attributeName, new Double(val));
} else {
cyAttrs.setAttribute(key, attributeName, val);
}
}
}
} catch (Exception e) {
String message = "failed parsing attributes file at line: " + lineNum
+ " with exception: " + e.getMessage();
CyLogger.getLogger(CyAttributesReader.class).warn(message, e);
throw new IOException(message);
}
}
| public void loadAttributesInternal(CyAttributes cyAttrs, Reader fileIn)
throws IOException {
badDecode = false;
boolean guessedAttrType = false; // We later set this to true if we have to guess the attribute type.
try {
final BufferedReader reader;
if (fileIn instanceof BufferedReader) {
reader = (BufferedReader) fileIn;
} else {
reader = new BufferedReader(fileIn);
}
String attributeName;
byte type = -1;
{
final String firstLine = reader.readLine();
lineNum++;
if (firstLine == null) {
return;
}
final String searchStr = "class=";
final int inx = firstLine.indexOf(searchStr);
if (inx < 0) {
attributeName = firstLine.trim();
} else {
attributeName = firstLine.substring(0, inx - 1).trim();
String foo = firstLine.substring(inx);
final StringTokenizer tokens = new StringTokenizer(foo);
foo = tokens.nextToken();
String className = foo.substring(searchStr.length()).trim();
if (className.endsWith(")")) {
className = className.substring(0, className.length() - 1);
}
if (className.equalsIgnoreCase("java.lang.String")
|| className.equalsIgnoreCase("String")) {
type = MultiHashMapDefinition.TYPE_STRING;
} else if (className.equalsIgnoreCase("java.lang.Boolean")
|| className.equalsIgnoreCase("Boolean")) {
type = MultiHashMapDefinition.TYPE_BOOLEAN;
} else if (className.equalsIgnoreCase("java.lang.Integer")
|| className.equalsIgnoreCase("Integer")) {
type = MultiHashMapDefinition.TYPE_INTEGER;
} else if (className.equalsIgnoreCase("java.lang.Double")
|| className.equalsIgnoreCase("Double")
|| className.equalsIgnoreCase("java.lang.Float")
|| className.equalsIgnoreCase("Float")) {
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
}
}
}
if (attributeName.indexOf("(") >= 0) {
attributeName = attributeName.substring(0, attributeName.indexOf("(")).trim();
}
boolean firstLine = true;
boolean list = false;
while (true) {
final String line = reader.readLine();
lineNum++;
if (line == null) {
break;
}
if ("".equals(line.trim())) {
continue;
}
int inx = line.indexOf('=');
String key = line.substring(0, inx).trim();
String val = line.substring(inx + 1).trim();
key = decodeString(key);
if (firstLine && val.startsWith("(")) {
list = true;
}
if (list) {
// Chop away leading '(' and trailing ')'.
val = val.substring(1).trim();
val = val.substring(0, val.length() - 1).trim();
String[] elms = val.split("::");
final ArrayList elmsBuff = new ArrayList();
for (String vs : elms) {
vs = decodeString(vs);
vs = decodeSlashEscapes(vs);
elmsBuff.add(vs);
}
if (firstLine) {
if (type < 0) {
guessedAttrType = true;
while (true) {
try {
new Integer((String) elmsBuff.get(0));
type = MultiHashMapDefinition.TYPE_INTEGER;
break;
} catch (Exception e) {
}
try {
new Double((String) elmsBuff.get(0));
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
break;
} catch (Exception e) {
}
// try {
// new Boolean((String) elmsBuff.get(0));
// type = MultiHashMapDefinition.TYPE_BOOLEAN;
// break; }
// catch (Exception e) {}
type = MultiHashMapDefinition.TYPE_STRING;
break;
}
}
firstLine = false;
}
for (int i = 0; i < elmsBuff.size(); i++) {
if (type == MultiHashMapDefinition.TYPE_INTEGER) {
elmsBuff.set(i, new Integer((String) elmsBuff.get(i)));
} else if (type == MultiHashMapDefinition.TYPE_BOOLEAN) {
elmsBuff.set(i, new Boolean((String) elmsBuff.get(i)));
} else if (type == MultiHashMapDefinition.TYPE_FLOATING_POINT) {
elmsBuff.set(i, new Double((String) elmsBuff.get(i)));
} else {
// A string; do nothing.
}
}
cyAttrs.setListAttribute(key, attributeName, elmsBuff);
} else { // Not a list.
val = decodeString(val);
val = decodeSlashEscapes(val);
if (firstLine) {
if (type < 0) {
guessedAttrType = true;
while (true) {
try {
new Integer(val);
type = MultiHashMapDefinition.TYPE_INTEGER;
break;
} catch (Exception e) {
}
try {
new Double(val);
type = MultiHashMapDefinition.TYPE_FLOATING_POINT;
break;
} catch (Exception e) {
}
// try {
// new Boolean(val);
// type = MultiHashMapDefinition.TYPE_BOOLEAN;
// break; }
// catch (Exception e) {}
type = MultiHashMapDefinition.TYPE_STRING;
break;
}
}
firstLine = false;
}
if (type == MultiHashMapDefinition.TYPE_INTEGER) {
cyAttrs.setAttribute(key, attributeName, new Integer(val));
} else if (type == MultiHashMapDefinition.TYPE_BOOLEAN) {
cyAttrs.setAttribute(key, attributeName, new Boolean(val));
} else if (type == MultiHashMapDefinition.TYPE_FLOATING_POINT) {
cyAttrs.setAttribute(key, attributeName, new Double(val));
} else {
cyAttrs.setAttribute(key, attributeName, val);
}
}
}
} catch (Exception e) {
String message;
if (guessedAttrType) {
message = "failed parsing attributes file at line: " + lineNum
+ " with exception: " + e.getMessage()
+ " This is most likely due to a missing attribute type on the first line.\n"
+ "Attribute type should be one of the following: "
+ "(class=String), (class=Boolean), (class=Integer), or (class=Double). "
+ "(\"Double\" stands for a floating point a.k.a. \"decimal\" number.)"
+ " This should be added to end of the first line.";
}
else
message = "failed parsing attributes file at line: " + lineNum
+ " with exception: " + e.getMessage();
CyLogger.getLogger(CyAttributesReader.class).warn(message, e);
throw new IOException(message);
}
}
|
diff --git a/x10.compiler/src/x10cpp/types/X10CPPSourceClassResolver.java b/x10.compiler/src/x10cpp/types/X10CPPSourceClassResolver.java
index c5e9e736d..9a638f9f5 100644
--- a/x10.compiler/src/x10cpp/types/X10CPPSourceClassResolver.java
+++ b/x10.compiler/src/x10cpp/types/X10CPPSourceClassResolver.java
@@ -1,102 +1,108 @@
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2010.
*/
package x10cpp.types;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import polyglot.frontend.Compiler;
import polyglot.frontend.ExtensionInfo;
import polyglot.frontend.Globals;
import polyglot.frontend.Resource;
import polyglot.frontend.Source;
import polyglot.main.Options;
import polyglot.types.QName;
import x10.types.X10SourceClassResolver;
import x10.util.StreamWrapper;
import x10cpp.X10CPPCompilerOptions;
import x10cpp.visit.X10CPPTranslator;
public class X10CPPSourceClassResolver extends X10SourceClassResolver {
public X10CPPSourceClassResolver(Compiler compiler, ExtensionInfo ext, String classpath, boolean compileCommandLineOnly, boolean ignoreModTimes) {
super(compiler, ext, classpath, compileCommandLineOnly, ignoreModTimes);
}
private static File oldestFile (File[] files) {
long record = 0;
File oldest = null;
for (File f : files) {
if (f.lastModified() > record) {
record = f.lastModified();
oldest = f;
}
}
return oldest;
}
/**
* Load a class file for class <code>name</code>.
*/
protected Resource loadFile(QName name) {
if (nocache.contains(name)) {
return null;
}
Source source = ext.sourceLoader().classSource(name);
if (source == null)
return null;
String packageName = name.qualifier() != null ? name.qualifier().toString() : null;
final File cc = X10CPPTranslator.outputFile(ext.getOptions(), packageName, name.name().toString(), StreamWrapper.CC);
final File h = X10CPPTranslator.outputFile(ext.getOptions(), packageName, name.name().toString(), StreamWrapper.Header);
- if (cc.exists() && h.exists()) {
+ // DISABLE again due to XTENLANG-2326.
+ // To re-enable, the proper fix is in handleUpToDateTarget we need to schedule a subset of the compilation
+ // phases so that we will do sufficient processing of the class to be able to walk it's class decls
+ // correctly identify output files and process @NativeCPP directives (if any).
+ // Until the typechecker isn't the bottleneck in compilation, skipping the compilation isn't worth the hassle
+ // because we're going to include the .cc file in the post compilation command anyways.
+ if (false && cc.exists() && h.exists()) {
final File oldest = oldestFile(new File[] {cc,h});
return new Resource() {
public File file() {
return oldest;
}
public InputStream getInputStream() throws IOException {
throw new IOException();
}
public String name() {
return cc.getPath();
}
};
}
nocache.add(name);
return null;
}
protected void handleUpToDateTarget(QName name, Resource file) {
// FIXME: [IP] HACK
// Add the files associated to this class to outputFiles even if they won't be compiled
if (!isOutput(name))
return;
String packageName = name.qualifier() != null ? name.qualifier().toString() : null;
String cc = X10CPPTranslator.outputFileName(packageName, name.name().toString(), StreamWrapper.CC);
String h = X10CPPTranslator.outputFileName(packageName, name.name().toString(), StreamWrapper.Header);
System.out.println("Not recompiling: "+name);
((X10CPPCompilerOptions)ext.getOptions()).compilationUnits().add(cc);
ext.compiler().outputFiles().add(cc);
ext.compiler().outputFiles().add(h);
}
}
| true | true | protected Resource loadFile(QName name) {
if (nocache.contains(name)) {
return null;
}
Source source = ext.sourceLoader().classSource(name);
if (source == null)
return null;
String packageName = name.qualifier() != null ? name.qualifier().toString() : null;
final File cc = X10CPPTranslator.outputFile(ext.getOptions(), packageName, name.name().toString(), StreamWrapper.CC);
final File h = X10CPPTranslator.outputFile(ext.getOptions(), packageName, name.name().toString(), StreamWrapper.Header);
if (cc.exists() && h.exists()) {
final File oldest = oldestFile(new File[] {cc,h});
return new Resource() {
public File file() {
return oldest;
}
public InputStream getInputStream() throws IOException {
throw new IOException();
}
public String name() {
return cc.getPath();
}
};
}
nocache.add(name);
return null;
}
| protected Resource loadFile(QName name) {
if (nocache.contains(name)) {
return null;
}
Source source = ext.sourceLoader().classSource(name);
if (source == null)
return null;
String packageName = name.qualifier() != null ? name.qualifier().toString() : null;
final File cc = X10CPPTranslator.outputFile(ext.getOptions(), packageName, name.name().toString(), StreamWrapper.CC);
final File h = X10CPPTranslator.outputFile(ext.getOptions(), packageName, name.name().toString(), StreamWrapper.Header);
// DISABLE again due to XTENLANG-2326.
// To re-enable, the proper fix is in handleUpToDateTarget we need to schedule a subset of the compilation
// phases so that we will do sufficient processing of the class to be able to walk it's class decls
// correctly identify output files and process @NativeCPP directives (if any).
// Until the typechecker isn't the bottleneck in compilation, skipping the compilation isn't worth the hassle
// because we're going to include the .cc file in the post compilation command anyways.
if (false && cc.exists() && h.exists()) {
final File oldest = oldestFile(new File[] {cc,h});
return new Resource() {
public File file() {
return oldest;
}
public InputStream getInputStream() throws IOException {
throw new IOException();
}
public String name() {
return cc.getPath();
}
};
}
nocache.add(name);
return null;
}
|
diff --git a/src/com/android/contacts/calllog/ClearCallLogDialog.java b/src/com/android/contacts/calllog/ClearCallLogDialog.java
index 0f999bdda..426732aea 100644
--- a/src/com/android/contacts/calllog/ClearCallLogDialog.java
+++ b/src/com/android/contacts/calllog/ClearCallLogDialog.java
@@ -1,78 +1,78 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.contacts.calllog;
import com.android.contacts.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog.Calls;
/**
* Dialog that clears the call log after confirming with the user
*/
public class ClearCallLogDialog extends DialogFragment {
/** Preferred way to show this dialog */
public static void show(FragmentManager fragmentManager) {
ClearCallLogDialog dialog = new ClearCallLogDialog();
dialog.show(fragmentManager, "deleteCallLog");
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final ContentResolver resolver = getActivity().getContentResolver();
final OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final ProgressDialog progressDialog = ProgressDialog.show(getActivity(),
getString(R.string.clearCallLogProgress_title),
"", true, false);
final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
- resolver.delete(Calls.CONTENT_URI_WITH_VOICEMAIL, null, null);
+ resolver.delete(Calls.CONTENT_URI, null, null);
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
};
// TODO: Once we have the API, we should configure this ProgressDialog
// to only show up after a certain time (e.g. 150ms)
progressDialog.show();
task.execute();
}
};
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.clearCallLogConfirmation_title)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setMessage(R.string.clearCallLogConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, okListener)
.setCancelable(true)
.create();
}
}
| true | true | public Dialog onCreateDialog(Bundle savedInstanceState) {
final ContentResolver resolver = getActivity().getContentResolver();
final OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final ProgressDialog progressDialog = ProgressDialog.show(getActivity(),
getString(R.string.clearCallLogProgress_title),
"", true, false);
final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
resolver.delete(Calls.CONTENT_URI_WITH_VOICEMAIL, null, null);
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
};
// TODO: Once we have the API, we should configure this ProgressDialog
// to only show up after a certain time (e.g. 150ms)
progressDialog.show();
task.execute();
}
};
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.clearCallLogConfirmation_title)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setMessage(R.string.clearCallLogConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, okListener)
.setCancelable(true)
.create();
}
| public Dialog onCreateDialog(Bundle savedInstanceState) {
final ContentResolver resolver = getActivity().getContentResolver();
final OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final ProgressDialog progressDialog = ProgressDialog.show(getActivity(),
getString(R.string.clearCallLogProgress_title),
"", true, false);
final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
resolver.delete(Calls.CONTENT_URI, null, null);
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
};
// TODO: Once we have the API, we should configure this ProgressDialog
// to only show up after a certain time (e.g. 150ms)
progressDialog.show();
task.execute();
}
};
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.clearCallLogConfirmation_title)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setMessage(R.string.clearCallLogConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, okListener)
.setCancelable(true)
.create();
}
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/GroupReferenceBox.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/GroupReferenceBox.java
index f41535db7..9da9c22cb 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/GroupReferenceBox.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/GroupReferenceBox.java
@@ -1,143 +1,143 @@
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.admin;
import com.google.gerrit.client.ui.AccountGroupSuggestOracle;
import com.google.gerrit.client.ui.RPCSuggestOracle;
import com.google.gerrit.common.data.GroupReference;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.HasCloseHandlers;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwtexpui.globalkey.client.NpTextBox;
public class GroupReferenceBox extends Composite implements
LeafValueEditor<GroupReference>, HasSelectionHandlers<GroupReference>,
HasCloseHandlers<GroupReferenceBox>, Focusable {
private final DefaultSuggestionDisplay suggestions;
private final NpTextBox textBox;
private final AccountGroupSuggestOracle oracle;
private final SuggestBox suggestBox;
private boolean submitOnSelection;
public GroupReferenceBox() {
suggestions = new DefaultSuggestionDisplay();
textBox = new NpTextBox();
oracle = new AccountGroupSuggestOracle();
suggestBox = new SuggestBox( //
new RPCSuggestOracle(oracle), //
textBox, //
suggestions);
initWidget(suggestBox);
- suggestBox.addKeyPressHandler(new KeyPressHandler() {
+ textBox.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
submitOnSelection = false;
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
if (suggestions.isSuggestionListShowing()) {
submitOnSelection = true;
} else {
SelectionEvent.fire(GroupReferenceBox.this, getValue());
}
}
}
});
suggestBox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
suggestBox.setText("");
CloseEvent.fire(GroupReferenceBox.this, GroupReferenceBox.this);
}
}
});
suggestBox.addSelectionHandler(new SelectionHandler<Suggestion>() {
@Override
public void onSelection(SelectionEvent<Suggestion> event) {
if (submitOnSelection) {
submitOnSelection = false;
SelectionEvent.fire(GroupReferenceBox.this, getValue());
}
}
});
}
public void setVisibleLength(int len) {
textBox.setVisibleLength(len);
}
@Override
public HandlerRegistration addSelectionHandler(
SelectionHandler<GroupReference> handler) {
return addHandler(handler, SelectionEvent.getType());
}
@Override
public HandlerRegistration addCloseHandler(
CloseHandler<GroupReferenceBox> handler) {
return addHandler(handler, CloseEvent.getType());
}
@Override
public GroupReference getValue() {
String name = suggestBox.getText();
if (name != null && !name.isEmpty()) {
return new GroupReference(oracle.getUUID(name), name);
} else {
return null;
}
}
@Override
public void setValue(GroupReference value) {
suggestBox.setText(value != null ? value.getName() : "");
}
@Override
public int getTabIndex() {
return suggestBox.getTabIndex();
}
@Override
public void setTabIndex(int index) {
suggestBox.setTabIndex(index);
}
public void setFocus(boolean focused) {
suggestBox.setFocus(focused);
}
@Override
public void setAccessKey(char key) {
suggestBox.setAccessKey(key);
}
}
| true | true | public GroupReferenceBox() {
suggestions = new DefaultSuggestionDisplay();
textBox = new NpTextBox();
oracle = new AccountGroupSuggestOracle();
suggestBox = new SuggestBox( //
new RPCSuggestOracle(oracle), //
textBox, //
suggestions);
initWidget(suggestBox);
suggestBox.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
submitOnSelection = false;
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
if (suggestions.isSuggestionListShowing()) {
submitOnSelection = true;
} else {
SelectionEvent.fire(GroupReferenceBox.this, getValue());
}
}
}
});
suggestBox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
suggestBox.setText("");
CloseEvent.fire(GroupReferenceBox.this, GroupReferenceBox.this);
}
}
});
suggestBox.addSelectionHandler(new SelectionHandler<Suggestion>() {
@Override
public void onSelection(SelectionEvent<Suggestion> event) {
if (submitOnSelection) {
submitOnSelection = false;
SelectionEvent.fire(GroupReferenceBox.this, getValue());
}
}
});
}
| public GroupReferenceBox() {
suggestions = new DefaultSuggestionDisplay();
textBox = new NpTextBox();
oracle = new AccountGroupSuggestOracle();
suggestBox = new SuggestBox( //
new RPCSuggestOracle(oracle), //
textBox, //
suggestions);
initWidget(suggestBox);
textBox.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
submitOnSelection = false;
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
if (suggestions.isSuggestionListShowing()) {
submitOnSelection = true;
} else {
SelectionEvent.fire(GroupReferenceBox.this, getValue());
}
}
}
});
suggestBox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
suggestBox.setText("");
CloseEvent.fire(GroupReferenceBox.this, GroupReferenceBox.this);
}
}
});
suggestBox.addSelectionHandler(new SelectionHandler<Suggestion>() {
@Override
public void onSelection(SelectionEvent<Suggestion> event) {
if (submitOnSelection) {
submitOnSelection = false;
SelectionEvent.fire(GroupReferenceBox.this, getValue());
}
}
});
}
|
diff --git a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java
index e011dc42..f45749c4 100644
--- a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java
+++ b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java
@@ -1,69 +1,69 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.clustering.kmeans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.mahout.clustering.WeightedVectorWritable;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.math.VectorWritable;
public class KMeansClusterMapper extends Mapper<WritableComparable<?>,VectorWritable,IntWritable,WeightedVectorWritable> {
private final List<Cluster> clusters = new ArrayList<Cluster>();
private KMeansClusterer clusterer;
@Override
protected void map(WritableComparable<?> key, VectorWritable point, Context context) throws IOException, InterruptedException {
clusterer.outputPointWithClusterInfo(point.get(), clusters, context);
}
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
- throw new IllegalStateException("Cluster is empty!");
+ throw new IllegalStateException("No clusters found. Check your -c path.");
}
}
this.clusterer = new KMeansClusterer(measure);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
}
| true | true | protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
throw new IllegalStateException("Cluster is empty!");
}
}
this.clusterer = new KMeansClusterer(measure);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
| protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
throw new IllegalStateException("No clusters found. Check your -c path.");
}
}
this.clusterer = new KMeansClusterer(measure);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
|
diff --git a/applications/src/main/java/org/rcsb/lx/ui/FullSequencesViewer.java b/applications/src/main/java/org/rcsb/lx/ui/FullSequencesViewer.java
index c0c8867..99138e6 100644
--- a/applications/src/main/java/org/rcsb/lx/ui/FullSequencesViewer.java
+++ b/applications/src/main/java/org/rcsb/lx/ui/FullSequencesViewer.java
@@ -1,245 +1,258 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* This code was contributed from the Molecular Biology Toolkit
* (MBT) project at the University of California San Diego.
*
* Please reference J.L. Moreland, A.Gramada, O.V. Buzko, Qing
* Zhang and P.E. Bourne 2005 The Molecular Biology Toolkit (MBT):
* A Modular Platform for Developing Molecular Visualization
* Applications. BMC Bioinformatics, 6:21.
*
* The MBT project was funded as part of the National Institutes
* of Health PPG grant number 1-P01-GM63208 and its National
* Institute of General Medical Sciences (NIGMS) division. Ongoing
* development for the MBT project is managed by the RCSB
* Protein Data Bank(http://www.pdb.org) and supported by funds
* from the National Science Foundation (NSF), the National
* Institute of General Medical Sciences (NIGMS), the Office of
* Science, Department of Energy (DOE), the National Library of
* Medicine (NLM), the National Cancer Institute (NCI), the
* National Center for Research Resources (NCRR), the National
* Institute of Biomedical Imaging and Bioengineering (NIBIB),
* the National Institute of Neurological Disorders and Stroke
* (NINDS), and the National Institute of Diabetes and Digestive
* and Kidney Diseases (NIDDK).
*
* Created on 2008/12/22
*
*/
package org.rcsb.lx.ui;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import org.rcsb.lx.controllers.app.LigandExplorer;
import org.rcsb.lx.controllers.update.LXUpdateEvent;
import org.rcsb.mbt.model.ExternChain;
import org.rcsb.mbt.model.Residue;
import org.rcsb.mbt.model.Structure;
import org.rcsb.mbt.model.StructureComponent;
import org.rcsb.mbt.model.StructureMap;
import org.rcsb.mbt.model.StructureModel;
import org.rcsb.mbt.model.util.DebugState;
import org.rcsb.uiApp.controllers.app.AppBase;
import org.rcsb.uiApp.controllers.update.IUpdateListener;
import org.rcsb.uiApp.controllers.update.UpdateEvent;
import org.rcsb.vf.glscene.jogl.SequencePanelBase;
/**
* @author John Beaver
*/
@SuppressWarnings("serial")
public class FullSequencesViewer extends JScrollPane implements IUpdateListener
{
JPanel contentPane = new JPanel(null,false);
// definitions for painted component sizes
public ArrayList<SequencePanelBase> sequencePanels = new ArrayList<SequencePanelBase>();
private boolean isDirty;
public FullSequencesViewer()
{
super();
super.setViewportView(contentPane);
super.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
super.setDoubleBuffered(false);
LigandExplorer.sgetUpdateController().registerListener(this);
}
public void setComponents()
{
createViewersForCurrentEpitope();
}
public void createViewersForCurrentEpitope()
{
- contentPane.removeAll();
+ // use invokeLater causes:
+ // Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
+ //at org.rcsb.lx.ui.SequenceStructureTitlePanel.heightForWidth(SequenceStructureTitlePanel.java:111)
+// javax.swing.SwingUtilities.invokeLater(new Runnable()
+// {
+// public void run()
+// {
+// System.out.println("FullSequencesView: removeAll()");
+// contentPane.removeAll();
+// }
+// }
+// );
+ System.out.println("FullSequencesView: removeAll() commented out!");
+ // contentPane.removeAll();
sequencePanels.clear();
StructureModel model = AppBase.sgetModel();
if (model.getStructures() == null)
return;
for (Structure struc : model.getStructures())
{
final StructureMap sm = struc.getStructureMap();
final int scrollbarWidth = (int)super.getVerticalScrollBar().getPreferredSize().getWidth();
final Vector<StructureComponent> topChains = sm.getPdbTopLevelElements();
Vector<StructureComponent> chains = new Vector<StructureComponent>();
for (StructureComponent comp : topChains)
if (!(comp instanceof ExternChain && ((ExternChain)comp).getResidue(0).getClassification() ==
Residue.Classification.LIGAND)) chains.add(comp);
// leave out the ligands...
if (chains != null)
{
FullSequencePanel[] tempSequencePanels = new FullSequencePanel[chains.size()];
int i = 0;
for (StructureComponent c : chains)
{
String description = null;
if (DebugState.isDebug())
assert (c instanceof ExternChain);
// curious if we ever get anything else (and why)...
if (c instanceof ExternChain)
{
ExternChain xc = (ExternChain)c;
switch (xc.getExternChainType())
{
case BASIC: description = "Chain " + xc.getChainId() + ":"; break;
case MISCELLANEOUS: description = "Non Protein:"; break;
default:
continue;
// no waters...
}
}
tempSequencePanels[i++] = new FullSequencePanel(description, c, scrollbarWidth);
}
Arrays.sort(tempSequencePanels,
new Comparator<FullSequencePanel>()
{
public int compare(final FullSequencePanel s1, final FullSequencePanel s2)
{
if (s1 == null)
return 1;
else if (s2 == null)
return -1;
ExternChain xc1 = (ExternChain)s1.chain;
ExternChain xc2 = (ExternChain)s2.chain;
// non-protein chains always go to the bottom
if (xc1.isMiscellaneousChain())
return 1;
// non-protein chains always go to the bottom
if (xc2.isMiscellaneousChain())
return -1;
return xc1.getChainId().compareTo(xc2.getChainId());
}
});
sequencePanels.add(new SequenceStructureTitlePanel(struc));
for (FullSequencePanel panel : tempSequencePanels)
if (panel != null) sequencePanels.add(panel);
}
}
for (SequencePanelBase panel : sequencePanels)
contentPane.add(panel);
// force a resize of the components (see paintComponent())
isDirty = true;
super.repaint();
}
private final Dimension oldSize = new Dimension(-1,-1);
@Override
public void paintComponent(final Graphics g)
{
final Dimension newSize = contentPane.getSize();
if(!newSize.equals(oldSize) || isDirty) {
final JScrollBar bar = super.getVerticalScrollBar();
if(bar == null) {
return;
}
final int scrollWidth = bar.getWidth();
final Insets insets = super.getInsets();
int curY = 0;
if (!sequencePanels.isEmpty())
for (SequencePanelBase panel : sequencePanels)
{
panel.heightForWidth(newSize.width);
panel.setBounds(0,curY,newSize.width,panel.preferredHeight);
curY += panel.preferredHeight + 3;
}
contentPane.setPreferredSize(new Dimension(newSize.width - scrollWidth - insets.left - insets.right,
curY + insets.top + insets.bottom));
}
}
/*
* Called either from the SequencesTab or from the update manager.
*
* 24-Oct-08 - rickb
*/
public void updateSequences()
{
isDirty = true;
for (SequencePanelBase panel : sequencePanels)
panel.isDirty = true;
this.invalidate();
}
public void handleUpdateEvent(UpdateEvent evt)
{
if (evt.action == UpdateEvent.Action.EXTENDED &&
((LXUpdateEvent)evt).lxAction == LXUpdateEvent.LXAction.INTERACTIONS_CHANGED)
updateSequences();
}
}
| true | true | public void createViewersForCurrentEpitope()
{
contentPane.removeAll();
sequencePanels.clear();
StructureModel model = AppBase.sgetModel();
if (model.getStructures() == null)
return;
for (Structure struc : model.getStructures())
{
final StructureMap sm = struc.getStructureMap();
final int scrollbarWidth = (int)super.getVerticalScrollBar().getPreferredSize().getWidth();
final Vector<StructureComponent> topChains = sm.getPdbTopLevelElements();
Vector<StructureComponent> chains = new Vector<StructureComponent>();
for (StructureComponent comp : topChains)
if (!(comp instanceof ExternChain && ((ExternChain)comp).getResidue(0).getClassification() ==
Residue.Classification.LIGAND)) chains.add(comp);
// leave out the ligands...
if (chains != null)
{
FullSequencePanel[] tempSequencePanels = new FullSequencePanel[chains.size()];
int i = 0;
for (StructureComponent c : chains)
{
String description = null;
if (DebugState.isDebug())
assert (c instanceof ExternChain);
// curious if we ever get anything else (and why)...
if (c instanceof ExternChain)
{
ExternChain xc = (ExternChain)c;
switch (xc.getExternChainType())
{
case BASIC: description = "Chain " + xc.getChainId() + ":"; break;
case MISCELLANEOUS: description = "Non Protein:"; break;
default:
continue;
// no waters...
}
}
tempSequencePanels[i++] = new FullSequencePanel(description, c, scrollbarWidth);
}
Arrays.sort(tempSequencePanels,
new Comparator<FullSequencePanel>()
{
public int compare(final FullSequencePanel s1, final FullSequencePanel s2)
{
if (s1 == null)
return 1;
else if (s2 == null)
return -1;
ExternChain xc1 = (ExternChain)s1.chain;
ExternChain xc2 = (ExternChain)s2.chain;
// non-protein chains always go to the bottom
if (xc1.isMiscellaneousChain())
return 1;
// non-protein chains always go to the bottom
if (xc2.isMiscellaneousChain())
return -1;
return xc1.getChainId().compareTo(xc2.getChainId());
}
});
sequencePanels.add(new SequenceStructureTitlePanel(struc));
for (FullSequencePanel panel : tempSequencePanels)
if (panel != null) sequencePanels.add(panel);
}
}
for (SequencePanelBase panel : sequencePanels)
contentPane.add(panel);
// force a resize of the components (see paintComponent())
isDirty = true;
super.repaint();
}
| public void createViewersForCurrentEpitope()
{
// use invokeLater causes:
// Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
//at org.rcsb.lx.ui.SequenceStructureTitlePanel.heightForWidth(SequenceStructureTitlePanel.java:111)
// javax.swing.SwingUtilities.invokeLater(new Runnable()
// {
// public void run()
// {
// System.out.println("FullSequencesView: removeAll()");
// contentPane.removeAll();
// }
// }
// );
System.out.println("FullSequencesView: removeAll() commented out!");
// contentPane.removeAll();
sequencePanels.clear();
StructureModel model = AppBase.sgetModel();
if (model.getStructures() == null)
return;
for (Structure struc : model.getStructures())
{
final StructureMap sm = struc.getStructureMap();
final int scrollbarWidth = (int)super.getVerticalScrollBar().getPreferredSize().getWidth();
final Vector<StructureComponent> topChains = sm.getPdbTopLevelElements();
Vector<StructureComponent> chains = new Vector<StructureComponent>();
for (StructureComponent comp : topChains)
if (!(comp instanceof ExternChain && ((ExternChain)comp).getResidue(0).getClassification() ==
Residue.Classification.LIGAND)) chains.add(comp);
// leave out the ligands...
if (chains != null)
{
FullSequencePanel[] tempSequencePanels = new FullSequencePanel[chains.size()];
int i = 0;
for (StructureComponent c : chains)
{
String description = null;
if (DebugState.isDebug())
assert (c instanceof ExternChain);
// curious if we ever get anything else (and why)...
if (c instanceof ExternChain)
{
ExternChain xc = (ExternChain)c;
switch (xc.getExternChainType())
{
case BASIC: description = "Chain " + xc.getChainId() + ":"; break;
case MISCELLANEOUS: description = "Non Protein:"; break;
default:
continue;
// no waters...
}
}
tempSequencePanels[i++] = new FullSequencePanel(description, c, scrollbarWidth);
}
Arrays.sort(tempSequencePanels,
new Comparator<FullSequencePanel>()
{
public int compare(final FullSequencePanel s1, final FullSequencePanel s2)
{
if (s1 == null)
return 1;
else if (s2 == null)
return -1;
ExternChain xc1 = (ExternChain)s1.chain;
ExternChain xc2 = (ExternChain)s2.chain;
// non-protein chains always go to the bottom
if (xc1.isMiscellaneousChain())
return 1;
// non-protein chains always go to the bottom
if (xc2.isMiscellaneousChain())
return -1;
return xc1.getChainId().compareTo(xc2.getChainId());
}
});
sequencePanels.add(new SequenceStructureTitlePanel(struc));
for (FullSequencePanel panel : tempSequencePanels)
if (panel != null) sequencePanels.add(panel);
}
}
for (SequencePanelBase panel : sequencePanels)
contentPane.add(panel);
// force a resize of the components (see paintComponent())
isDirty = true;
super.repaint();
}
|
diff --git a/runwaysdk-test/src/main/java/com/runwaysdk/business/ControllerGenTest.java b/runwaysdk-test/src/main/java/com/runwaysdk/business/ControllerGenTest.java
index e43ca4eda..8436a92fd 100644
--- a/runwaysdk-test/src/main/java/com/runwaysdk/business/ControllerGenTest.java
+++ b/runwaysdk-test/src/main/java/com/runwaysdk/business/ControllerGenTest.java
@@ -1,973 +1,973 @@
package com.runwaysdk.business;
/*******************************************************************************
* Copyright (c) 2013 TerraFrame, Inc. All rights reserved.
*
* This file is part of Runway SDK(tm).
*
* Runway SDK(tm) 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.
*
* Runway SDK(tm) 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 Runway SDK(tm). If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
import java.lang.reflect.Constructor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.catalina.core.DummyRequest;
import org.apache.catalina.core.DummyResponse;
import org.apache.catalina.session.StandardSession;
import com.runwaysdk.ClientSession;
import com.runwaysdk.constants.ClientConstants;
import com.runwaysdk.constants.ClientRequestIF;
import com.runwaysdk.constants.CommonProperties;
import com.runwaysdk.constants.Constants;
import com.runwaysdk.constants.MdActionInfo;
import com.runwaysdk.constants.MdAttributeBooleanInfo;
import com.runwaysdk.constants.MdAttributeCharacterInfo;
import com.runwaysdk.constants.MdAttributeDoubleInfo;
import com.runwaysdk.constants.MdAttributeIntegerInfo;
import com.runwaysdk.constants.MdAttributeLocalInfo;
import com.runwaysdk.constants.MdAttributeStructInfo;
import com.runwaysdk.constants.MdBusinessInfo;
import com.runwaysdk.constants.MdControllerInfo;
import com.runwaysdk.constants.MdExceptionInfo;
import com.runwaysdk.constants.MdParameterInfo;
import com.runwaysdk.constants.MdRelationshipInfo;
import com.runwaysdk.constants.MdStructInfo;
import com.runwaysdk.constants.ServerConstants;
import com.runwaysdk.controller.IllegalURIMethodException;
import com.runwaysdk.controller.ServletDispatcher;
import com.runwaysdk.controller.UnknownServletException;
import com.runwaysdk.dataaccess.BusinessDAO;
import com.runwaysdk.dataaccess.metadata.MdActionDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeCharacterDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeConcreteDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeDoubleDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeIntegerDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeStructDAO;
import com.runwaysdk.dataaccess.metadata.MdBusinessDAO;
import com.runwaysdk.dataaccess.metadata.MdControllerDAO;
import com.runwaysdk.dataaccess.metadata.MdExceptionDAO;
import com.runwaysdk.dataaccess.metadata.MdPackage;
import com.runwaysdk.dataaccess.metadata.MdParameterDAO;
import com.runwaysdk.dataaccess.metadata.MdRelationshipDAO;
import com.runwaysdk.dataaccess.metadata.MdStructDAO;
import com.runwaysdk.generation.loader.LoaderDecorator;
import com.runwaysdk.generation.loader.Reloadable;
public class ControllerGenTest extends TestCase
{
class MockSession extends StandardSession
{
/**
*
*/
private static final long serialVersionUID = 3674944194141854328L;
private HashMap<String, Object> attributes;
public MockSession()
{
super(null);
this.attributes = new HashMap<String, Object>();
}
public Object getAttribute(String arg0)
{
return attributes.get(arg0);
}
public void setAttribute(String arg0, Object arg1)
{
attributes.put(arg0, arg1);
}
}
class MockRequest extends DummyRequest
{
private String method;
private HashMap<String, String[]> parameters;
private HashMap<String, Object> attributes;
// private HashMap<String, String[]> parameterValues;
private MockSession session;
public MockRequest(String method, String uri)
{
this.method = method;
this.parameters = new HashMap<String, String[]>();
// this.parameterValues = new HashMap<String, String[]>();
this.attributes = new HashMap<String, Object>();
this.session = new MockSession();
String[] split = uri.split("/");
this.setRequestURI(uri);
this.setContextPath("/" + split[1]);
this.setServletPath("/" + split[2]);
}
@Override
public Map<?, ?> getParameterMap()
{
return parameters;
}
@Override
public String getMethod()
{
return method;
}
@Override
public String getParameter(String name)
{
String[] params = parameters.get(name);
if (params != null && params.length > 0)
{
return params[0];
}
else
{
return null;
}
}
public void setParameter(String name, String value)
{
parameters.put(name, new String[] { value });
}
@Override
public String[] getParameterValues(String name)
{
return parameters.get(name);
// return parameterValues.get(name);
}
public void setParameterValues(String name, String[] values)
{
parameters.put(name, values);
// parameterValues.put(name, values);
}
@Override
public Locale getLocale()
{
return CommonProperties.getDefaultLocale();
}
@SuppressWarnings("unchecked")
@Override
public Enumeration getParameterNames()
{
StringBuffer buffer = new StringBuffer();
for (String key : parameters.keySet())
{
buffer.append(" " + key);
}
StringTokenizer tok = new StringTokenizer(buffer.toString().replaceFirst(" ", ""));
return tok;
}
@Override
public Object getAttribute(String name)
{
return attributes.get(name);
}
@Override
public void setAttribute(String name, Object value)
{
attributes.put(name, value);
}
@Override
public HttpSession getSession()
{
return session;
}
}
private static final String pack = "test.generated";
private static MdControllerDAO mdController;
private static MdBusinessDAO mdBusiness;
private static MdStructDAO mdStruct;
private static MdRelationshipDAO mdRelationship;
private static MdExceptionDAO mdException;
private static String testActionUri;
private static String changeRequestUri;
private static String testPrimitiveUri;
private static String testBusinessUri;
private static String testRelationshipUri;
private static String testPrimitiveArrayUri;
private static String testDTOArrayUri;
private static String testExceptionUri;
// private static String testMultipartFileParameterUri;
public static Test suite()
{
TestSuite suite = new TestSuite(ControllerGenTest.class.getSimpleName());
suite.addTestSuite(ControllerGenTest.class);
TestSetup wrapper = new TestSetup(suite)
{
protected void setUp()
{
classSetUp();
}
protected void tearDown()
{
classTearDown();
}
};
return wrapper;
}
private static void classSetUp()
{
mdStruct = MdStructDAO.newInstance();
mdStruct.setValue(MdStructInfo.PACKAGE, pack);
mdStruct.setValue(MdStructInfo.NAME, "TestStruct");
mdStruct.setStructValue(MdStructInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Struct");
mdStruct.apply();
MdAttributeConcreteDAO mdDouble = MdAttributeDoubleDAO.newInstance();
mdDouble.setValue(MdAttributeDoubleInfo.NAME, "testDouble");
mdDouble.setStructValue(MdAttributeDoubleInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Double");
mdDouble.setValue(MdAttributeDoubleInfo.DEFINING_MD_CLASS, mdStruct.getId());
mdDouble.setValue(MdAttributeDoubleInfo.DECIMAL, "2");
mdDouble.setValue(MdAttributeDoubleInfo.LENGTH, "2");
mdDouble.apply();
mdBusiness = MdBusinessDAO.newInstance();
mdBusiness.setValue(MdBusinessInfo.PACKAGE, pack);
mdBusiness.setValue(MdBusinessInfo.NAME, "TestBusiness");
mdBusiness.setStructValue(MdBusinessInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdBusiness.setGenerateMdController(false);
mdBusiness.apply();
MdAttributeConcreteDAO mdAttribute = MdAttributeCharacterDAO.newInstance();
mdAttribute.setValue(MdAttributeCharacterInfo.NAME, "testCharacter");
mdAttribute.setStructValue(MdAttributeCharacterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Character");
mdAttribute.setValue(MdAttributeCharacterInfo.DEFINING_MD_CLASS, mdBusiness.getId());
mdAttribute.setValue(MdAttributeCharacterInfo.SIZE, "255");
mdAttribute.apply();
MdAttributeConcreteDAO structAttribute = MdAttributeStructDAO.newInstance();
structAttribute.setValue(MdAttributeStructInfo.NAME, "testStruct");
structAttribute.setStructValue(MdAttributeStructInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Struct");
structAttribute.setValue(MdAttributeStructInfo.DEFINING_MD_CLASS, mdBusiness.getId());
structAttribute.setValue(MdAttributeStructInfo.MD_STRUCT, mdStruct.getId());
structAttribute.apply();
mdRelationship = MdRelationshipDAO.newInstance();
mdRelationship.setValue(MdRelationshipInfo.PACKAGE, pack);
mdRelationship.setValue(MdRelationshipInfo.NAME, "TestRelationship");
mdRelationship.setStructValue(MdRelationshipInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdRelationship.setValue(MdRelationshipInfo.PARENT_CARDINALITY, "*");
mdRelationship.setStructValue(MdRelationshipInfo.PARENT_DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Parent Relationship");
mdRelationship.setValue(MdRelationshipInfo.PARENT_MD_BUSINESS, mdBusiness.getId());
mdRelationship.setValue(MdRelationshipInfo.PARENT_METHOD, "testParent");
mdRelationship.setValue(MdRelationshipInfo.CHILD_CARDINALITY, "*");
mdRelationship.setStructValue(MdRelationshipInfo.CHILD_DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Child Relationship");
mdRelationship.setValue(MdRelationshipInfo.CHILD_MD_BUSINESS, mdBusiness.getId());
mdRelationship.setValue(MdRelationshipInfo.CHILD_METHOD, "testChild");
mdRelationship.setGenerateMdController(false);
mdRelationship.apply();
MdAttributeConcreteDAO integerAttribute = MdAttributeIntegerDAO.newInstance();
integerAttribute.setValue(MdAttributeIntegerInfo.NAME, "testInteger");
integerAttribute.setValue(MdAttributeIntegerInfo.DEFINING_MD_CLASS, mdRelationship.getId());
integerAttribute.setStructValue(MdAttributeIntegerInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Integer");
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_NEGATIVE, MdAttributeBooleanInfo.FALSE);
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_POSITIVE, MdAttributeBooleanInfo.FALSE);
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_ZERO, MdAttributeBooleanInfo.FALSE);
integerAttribute.apply();
mdController = MdControllerDAO.newInstance();
mdController.setValue(MdControllerInfo.NAME, "TestController");
mdController.setValue(MdControllerInfo.PACKAGE, pack);
mdController.setStructValue(MdControllerInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Controller");
mdController.setStructValue(MdControllerInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Controller");
mdController.apply();
MdActionDAO mdAction = MdActionDAO.newInstance();
mdAction.setValue(MdActionInfo.NAME, "testAction");
mdAction.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Action");
mdAction.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Action");
mdAction.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction.apply();
MdParameterDAO seqParameter = MdParameterDAO.newInstance();
seqParameter.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction.getId());
seqParameter.setValue(MdParameterInfo.TYPE, "java.lang.Long");
seqParameter.setValue(MdParameterInfo.NAME, "seq");
seqParameter.setValue(MdParameterInfo.ORDER, "0");
seqParameter.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
seqParameter.apply();
MdParameterDAO testParameter = MdParameterDAO.newInstance();
testParameter.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction.getId());
testParameter.setValue(MdParameterInfo.TYPE, "java.lang.Long");
testParameter.setValue(MdParameterInfo.NAME, "value");
testParameter.setValue(MdParameterInfo.ORDER, "1");
testParameter.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "value");
testParameter.apply();
MdActionDAO mdAction2 = MdActionDAO.newInstance();
mdAction2.setValue(MdActionInfo.NAME, "changeRequest");
mdAction2.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction2.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Change Request");
mdAction2.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Change Request");
mdAction2.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction2.apply();
MdActionDAO mdAction3 = MdActionDAO.newInstance();
mdAction3.setValue(MdActionInfo.NAME, "testPrimitives");
mdAction3.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction3.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Primitives");
mdAction3.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Primitives");
mdAction3.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction3.apply();
MdParameterDAO shortParam = MdParameterDAO.newInstance();
shortParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
shortParam.setValue(MdParameterInfo.TYPE, "java.lang.Short");
shortParam.setValue(MdParameterInfo.NAME, "shortParam");
shortParam.setValue(MdParameterInfo.ORDER, "0");
shortParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
shortParam.apply();
MdParameterDAO integerParam = MdParameterDAO.newInstance();
integerParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
integerParam.setValue(MdParameterInfo.TYPE, "java.lang.Integer");
integerParam.setValue(MdParameterInfo.NAME, "integerParam");
integerParam.setValue(MdParameterInfo.ORDER, "1");
integerParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
integerParam.apply();
MdParameterDAO longParam = MdParameterDAO.newInstance();
longParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
longParam.setValue(MdParameterInfo.TYPE, "java.lang.Long");
longParam.setValue(MdParameterInfo.NAME, "longParam");
longParam.setValue(MdParameterInfo.ORDER, "2");
longParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
longParam.apply();
MdParameterDAO floatParam = MdParameterDAO.newInstance();
floatParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
floatParam.setValue(MdParameterInfo.TYPE, "java.lang.Float");
floatParam.setValue(MdParameterInfo.NAME, "floatParam");
floatParam.setValue(MdParameterInfo.ORDER, "3");
floatParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
floatParam.apply();
MdParameterDAO doubleParam = MdParameterDAO.newInstance();
doubleParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
doubleParam.setValue(MdParameterInfo.TYPE, "java.lang.Double");
doubleParam.setValue(MdParameterInfo.NAME, "doubleParam");
doubleParam.setValue(MdParameterInfo.ORDER, "4");
doubleParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
doubleParam.apply();
MdParameterDAO characterParam = MdParameterDAO.newInstance();
characterParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
characterParam.setValue(MdParameterInfo.TYPE, "java.lang.Character");
characterParam.setValue(MdParameterInfo.NAME, "characterParam");
characterParam.setValue(MdParameterInfo.ORDER, "5");
characterParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
characterParam.apply();
MdParameterDAO stringParam = MdParameterDAO.newInstance();
stringParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
stringParam.setValue(MdParameterInfo.TYPE, "java.lang.String");
stringParam.setValue(MdParameterInfo.NAME, "stringParam");
stringParam.setValue(MdParameterInfo.ORDER, "6");
stringParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
stringParam.apply();
MdParameterDAO dateParam = MdParameterDAO.newInstance();
dateParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
dateParam.setValue(MdParameterInfo.TYPE, "java.util.Date");
dateParam.setValue(MdParameterInfo.NAME, "dateParam");
dateParam.setValue(MdParameterInfo.ORDER, "7");
dateParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
dateParam.apply();
MdActionDAO mdAction4 = MdActionDAO.newInstance();
mdAction4.setValue(MdActionInfo.NAME, "testBusiness");
mdAction4.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction4.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdAction4.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdAction4.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction4.apply();
MdParameterDAO businessParam = MdParameterDAO.newInstance();
businessParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction4.getId());
businessParam.setValue(MdParameterInfo.TYPE, mdBusiness.definesType());
businessParam.setValue(MdParameterInfo.NAME, "businessParam");
businessParam.setValue(MdParameterInfo.ORDER, "0");
businessParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Business Param");
businessParam.apply();
MdActionDAO mdAction5 = MdActionDAO.newInstance();
mdAction5.setValue(MdActionInfo.NAME, "testRelationship");
mdAction5.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction5.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdAction5.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdAction5.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction5.apply();
MdParameterDAO relationshipParam = MdParameterDAO.newInstance();
relationshipParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction5.getId());
relationshipParam.setValue(MdParameterInfo.TYPE, mdRelationship.definesType());
relationshipParam.setValue(MdParameterInfo.NAME, "relationshipParam");
relationshipParam.setValue(MdParameterInfo.ORDER, "0");
relationshipParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Relationship Param");
relationshipParam.apply();
MdActionDAO mdAction6 = MdActionDAO.newInstance();
mdAction6.setValue(MdActionInfo.NAME, "testArray");
mdAction6.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction6.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
mdAction6.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
mdAction6.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction6.apply();
MdParameterDAO stringArrayParam = MdParameterDAO.newInstance();
stringArrayParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction6.getId());
stringArrayParam.setValue(MdParameterInfo.TYPE, "java.lang.String[]");
stringArrayParam.setValue(MdParameterInfo.NAME, "testArray");
stringArrayParam.setValue(MdParameterInfo.ORDER, "0");
stringArrayParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
stringArrayParam.apply();
MdActionDAO mdAction7 = MdActionDAO.newInstance();
mdAction7.setValue(MdActionInfo.NAME, "testDTOArray");
mdAction7.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction7.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction7.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction7.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction7.apply();
MdParameterDAO dtoArrayParam = MdParameterDAO.newInstance();
dtoArrayParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction7.getId());
dtoArrayParam.setValue(MdParameterInfo.TYPE, mdBusiness.definesType() + "[]");
dtoArrayParam.setValue(MdParameterInfo.NAME, "testArray");
dtoArrayParam.setValue(MdParameterInfo.ORDER, "0");
dtoArrayParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
dtoArrayParam.apply();
MdActionDAO mdAction8 = MdActionDAO.newInstance();
mdAction8.setValue(MdActionInfo.NAME, "testException");
mdAction8.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction8.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction8.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction8.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction8.apply();
MdActionDAO mdAction9 = MdActionDAO.newInstance();
mdAction9.setValue(MdActionInfo.NAME, "testMultipartFileParameter");
mdAction9.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction9.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction9.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction9.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction9.apply();
MdParameterDAO multipartFileParam = MdParameterDAO.newInstance();
multipartFileParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction9.getId());
multipartFileParam.setValue(MdParameterInfo.TYPE, MdActionInfo.MULTIPART_FILE_PARAMETER);
multipartFileParam.setValue(MdParameterInfo.NAME, "file");
multipartFileParam.setValue(MdParameterInfo.ORDER, "0");
multipartFileParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "File parameter");
multipartFileParam.apply();
mdException = MdExceptionDAO.newInstance();
mdException.setValue(MdExceptionInfo.NAME, "TestException");
mdException.setValue(MdExceptionInfo.PACKAGE, pack);
mdException.setStructValue(MdExceptionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Exception");
mdException.apply();
testActionUri = "/contextPath/" + mdController.definesType() + "." + mdAction.getName() + MdActionInfo.ACTION_SUFFIX;
changeRequestUri = "/contextPath/" + mdController.definesType() + "." + mdAction2.getName() + MdActionInfo.ACTION_SUFFIX;
testPrimitiveUri = "/contextPath/" + mdController.definesType() + "." + mdAction3.getName() + MdActionInfo.ACTION_SUFFIX;
testBusinessUri = "/contextPath/" + mdController.definesType() + "." + mdAction4.getName() + MdActionInfo.ACTION_SUFFIX;
testRelationshipUri = "/contextPath/" + mdController.definesType() + "." + mdAction5.getName() + MdActionInfo.ACTION_SUFFIX;
testPrimitiveArrayUri = "/contextPath/" + mdController.definesType() + "." + mdAction6.getName() + MdActionInfo.ACTION_SUFFIX;
testDTOArrayUri = "/contextPath/" + mdController.definesType() + "." + mdAction7.getName() + MdActionInfo.ACTION_SUFFIX;
testExceptionUri = "/contextPath/" + mdController.definesType() + "." + mdAction8.getName() + MdActionInfo.ACTION_SUFFIX;
- testMultipartFileParameterUri = "/contextPath/" + mdController.definesType() + "." + mdAction9.getName() + MdActionInfo.ACTION_SUFFIX;
+// testMultipartFileParameterUri = "/contextPath/" + mdController.definesType() + "." + mdAction9.getName() + MdActionInfo.ACTION_SUFFIX;
finalizeSetup();
}
private static void finalizeSetup()
{
mdController.setValue(MdControllerInfo.STUB_SOURCE, getSource());
mdController.apply();
mdBusiness.setValue(MdBusinessInfo.DTO_STUB_SOURCE, getDTOsource());
mdBusiness.apply();
}
private static void classTearDown()
{
new MdPackage(pack).delete();
}
public void testSetRequestParameter() throws Exception
{
HttpServletRequest req = new MockRequest("GET", testActionUri);
HttpServletResponse resp = new DummyResponse();
Boolean b = new Boolean(false);
req.setAttribute("testAttribute", MdAttributeBooleanInfo.FALSE);
Class<?> controllerClass = LoaderDecorator.load(mdController.definesType());
Constructor<?> constructor = controllerClass.getConstructor(HttpServletRequest.class, HttpServletResponse.class, Boolean.class);
Object object = constructor.newInstance(req, resp, b);
controllerClass.getMethod("changeRequest").invoke(object);
HttpServletRequest ret = (HttpServletRequest) controllerClass.getMethod("getRequest").invoke(object);
assertEquals(MdAttributeBooleanInfo.TRUE, ret.getAttribute("testAttribute"));
}
public void testActionParameter() throws Exception
{
HttpServletRequest req = new MockRequest("GET", testActionUri);
HttpServletResponse resp = new DummyResponse();
Boolean b = new Boolean(false);
long value = 10;
req.setAttribute("testAttribute", 0);
assertEquals(0, req.getAttribute("testAttribute"));
Class<?> controllerClass = LoaderDecorator.load(mdController.definesType());
Constructor<?> constructor = controllerClass.getConstructor(HttpServletRequest.class, HttpServletResponse.class, Boolean.class);
Object object = constructor.newInstance(req, resp, b);
controllerClass.getMethod("testAction", Long.class, Long.class).invoke(object, value, 0L);
HttpServletRequest ret = (HttpServletRequest) controllerClass.getMethod("getRequest").invoke(object);
assertEquals(value, ret.getAttribute("testAttribute"));
}
public void testDispatcherNoParameter() throws Exception
{
HttpServletRequest req = new MockRequest("POST", changeRequestUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute("testAttribute", MdAttributeBooleanInfo.FALSE);
new ServletDispatcher().service(req, resp);
assertEquals(MdAttributeBooleanInfo.TRUE, req.getAttribute("testAttribute"));
}
public void testDispatcherPrimitiveParameters() throws Exception
{
MockRequest req = new MockRequest("POST", testActionUri);
HttpServletResponse resp = new DummyResponse();
long value = 10;
req.setAttribute("testAttribute", 0);
req.setParameter("seq", Long.toString(value));
req.setParameter("value", Long.toString(value));
assertEquals(0, req.getAttribute("testAttribute"));
new ServletDispatcher().service(req, resp);
assertEquals(value * 2, req.getAttribute("testAttribute"));
}
public void testDispatcherAllPrimitiveParameters() throws Exception
{
MockRequest req = new MockRequest("POST", testPrimitiveUri);
HttpServletResponse resp = new DummyResponse();
Short shortParam = new Short((short) 1);
Integer integerParam = new Integer(2);
Long longParam = new Long(3);
Float floatParam = new Float(1.1);
Double doubleParam = new Double(2.2);
Character characterParam = new Character('a');
String stringParam = new String("ab");
Date dateParam = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATETIME_FORMAT, CommonProperties.getDefaultLocale());
req.setParameter("shortParam", shortParam.toString());
req.setParameter("integerParam", integerParam.toString());
req.setParameter("longParam", longParam.toString());
req.setParameter("floatParam", floatParam.toString());
req.setParameter("doubleParam", doubleParam.toString());
req.setParameter("characterParam", characterParam.toString());
req.setParameter("stringParam", stringParam.toString());
req.setParameter("dateParam", dateFormat.format(dateParam));
new ServletDispatcher().service(req, resp);
assertEquals(req.getAttribute("shortParam"), shortParam);
assertEquals(req.getAttribute("integerParam"), integerParam);
assertEquals(req.getAttribute("longParam"), longParam);
assertEquals(req.getAttribute("floatParam"), floatParam);
assertEquals(req.getAttribute("doubleParam"), doubleParam);
assertEquals(req.getAttribute("characterParam"), characterParam);
assertEquals(req.getAttribute("stringParam"), stringParam);
assertEquals(dateFormat.format(dateParam), dateFormat.format(req.getAttribute("dateParam")));
}
public void testDispatcherBusinessParameters() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientSession = systemSession.getRequest();
MockRequest req = new MockRequest("POST", testBusinessUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientSession);
req.setParameter("businessParam.testCharacter", "testValue");
req.setParameter("businessParam.testStruct.testDouble", "10.2");
req.setParameter("businessParam.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("businessParam.componentId", "unknown");
new ServletDispatcher().service(req, resp);
assertEquals("10.2", req.getAttribute("testDouble"));
systemSession.logout();
}
public void testDispatcherRelationshipParameters() throws Exception
{
BusinessDAO dao = BusinessDAO.newInstance(mdBusiness.definesType());
dao.setValue("testCharacter", "test");
dao.apply();
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("POST", testRelationshipUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
req.setParameter("relationshipParam.testInteger", "10");
req.setParameter("relationshipParam.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("relationshipParam.componentId", "blank");
req.setParameter("#relationshipParam.parent.id", dao.getId());
req.setParameter("#relationshipParam.child.id", dao.getId());
new ServletDispatcher().service(req, resp);
assertEquals(10, req.getAttribute("testInteger"));
systemSession.logout();
}
public void testDispatcherPrimitiveArrayParameters() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
try
{
MockRequest req = new MockRequest("POST", testPrimitiveArrayUri);
HttpServletResponse resp = new DummyResponse();
String[] array = new String[] { "cat", "mouse", "dog", "lion", "eagle", "bat" };
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
req.setParameterValues("testArray", array);
new ServletDispatcher().service(req, resp);
assertEquals("lion", req.getAttribute("testArray"));
}
finally
{
systemSession.logout();
}
}
public void testDispatcherPrimitiveFailure() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
try
{
MockRequest req = new MockRequest("POST", testActionUri);
HttpServletResponse resp = new DummyResponse();
long value = 10;
req.setAttribute(ClientConstants.CLIENTSESSION, systemSession);
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
req.setAttribute("testAttribute", 20);
// Set invalid value
req.setParameter("seq", "abcdef");
req.setParameter("value", Long.toString(value));
assertEquals(20, req.getAttribute("testAttribute"));
new ServletDispatcher().service(req, resp);
assertEquals("abcdef", req.getAttribute("testAttribute"));
}
finally
{
systemSession.logout();
}
}
public void testDispatcherDTOFailure() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("POST", testBusinessUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
req.setAttribute(ClientConstants.CLIENTSESSION, systemSession);
req.setParameter("businessParam.testCharacter", "testValue");
req.setParameter("businessParam.testStruct.testDouble", "invalid");
req.setParameter("businessParam.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("businessParam.componentId", "unknown");
new ServletDispatcher().service(req, resp);
assertEquals("invalid", req.getAttribute("testDouble"));
assertEquals("testValue Extra Stuff", req.getAttribute("testCharacter"));
systemSession.logout();
}
public void testDispatcherUnknownAction() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("POST", "/contextPath/" + mdController.definesType() + ".unknown.mojo");
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
try
{
new ServletDispatcher().service(req, resp);
fail("Update to invoke an action which has not been defined");
}
catch (UnknownServletException e)
{
// This is expected
assertEquals("An action at the uri [/test.generated.TestController.unknown] does not exist.", e.getMessage());
}
finally
{
systemSession.logout();
}
}
public void testGetMethodOnPost() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("GET", testBusinessUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
req.setParameter("businessParam.testCharacter", "testValue");
req.setParameter("businessParam.testStruct.testDouble", "invalid");
req.setParameter("businessParam.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("businessParam.componentId", "unknown");
try
{
new ServletDispatcher().service(req, resp);
fail("Able to invoke a POST only method through a GET");
}
catch (IllegalURIMethodException e)
{
// This is expected
}
finally
{
systemSession.logout();
}
}
public void testDispatcherUnknownServlet() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("POST", "/contextPath/invalid.unkown.mojo");
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
try
{
new ServletDispatcher().service(req, resp);
fail("Update to invoke an action which has not been defined");
}
catch (UnknownServletException e)
{
// This is expected
assertEquals("An action at the uri [/invalid.unkown] does not exist.", e.getMessage());
}
finally
{
systemSession.logout();
}
}
public void testPropigateException() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("POST", testExceptionUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
try
{
new ServletDispatcher().service(req, resp);
fail("Update to invoke an action which has not been defined");
}
catch (RuntimeException e)
{
assertTrue(LoaderDecorator.load(pack + ".TestExceptionDTO").isInstance(e));
}
finally
{
systemSession.logout();
}
}
public void testDTOArray() throws Exception
{
ClientSession systemSession = ClientSession.createUserSession(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { CommonProperties.getDefaultLocale() });
ClientRequestIF clientRequest = systemSession.getRequest();
MockRequest req = new MockRequest("POST", testDTOArrayUri);
HttpServletResponse resp = new DummyResponse();
req.setAttribute(ClientConstants.CLIENTREQUEST, clientRequest);
req.setParameter("testArray_0.testCharacter", "testValue");
req.setParameter("testArray_0.testStruct.testDouble", "10.2");
req.setParameter("testArray_0.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("testArray_0.componentId", "unknown");
req.setParameter("testArray_1.testCharacter", "testValue2");
req.setParameter("testArray_1.testStruct.testDouble", "10.3");
req.setParameter("testArray_1.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("testArray_1.componentId", "unknown");
req.setParameter("testArray_2.testCharacter", "testValue3");
req.setParameter("testArray_2.testStruct.testDouble", "10.4");
req.setParameter("testArray_2.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("testArray_2.componentId", "unknown");
req.setParameter("testArray_3.testCharacter", "testValue4");
req.setParameter("testArray_3.testStruct.testDouble", "10.5");
req.setParameter("testArray_3.isNew", MdAttributeBooleanInfo.TRUE);
req.setParameter("testArray_3.componentId", "unknown");
try
{
new ServletDispatcher().service(req, resp);
Object testCharacter = req.getAttribute("testCharacter");
assertEquals("10.5", req.getAttribute("testDouble"));
assertEquals("testValue4", testCharacter);
}
finally
{
systemSession.logout();
}
}
private static String getDTOsource()
{
String source = "package test.generated; \n" + "" + "import java.util.Locale;\n" + "" + "public class TestBusinessDTO extends TestBusinessDTOBase implements " + Reloadable.class.getName() + "\n" + "{\n" + " public final static String CLASS = \"test.generated.TestBusiness\";\n" + " private static final long serialVersionUID = 1220396508382L;\n" + " public TestBusinessDTO(" + ClientRequestIF.class.getName() + " clientRequest)\n" + " {\n" + " super(clientRequest);\n" + " }\n" + " /**\n" + " * Copy Constructor: Duplicates the values and attributes of the given BusinessDTO into a new DTO.\n" + " * \n" + " * @param businessDTO The BusinessDTO to duplicate\n" + " * @param clientRequest The clientRequest this DTO should use to communicate with the server.\n" + " */\n"
+ " protected TestBusinessDTO(" + BusinessDTO.class.getName() + " businessDTO, " + ClientRequestIF.class.getName() + " clientRequest)\n" + " {\n" + " super(businessDTO, clientRequest);\n" + " }\n" + "}\n";
return source;
}
private static String getSource()
{
String source = "package test.generated; \n" + "public class TestController extends TestControllerBase implements " + Reloadable.class.getName() + "\n" + "{\n" + " public TestController(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp, java.lang.Boolean bool)\n" + " {\n" + " super(req, resp, bool);\n" + " }\n" + " public void testAction(java.lang.Long seq, java.lang.Long value)\n" + " {\n" + " req.setAttribute(\"testAttribute\", seq + value);\n" + " }\n" + " public void failTestAction(java.lang.String seq, java.lang.String value)\n" + " {\n" + " req.setAttribute(\"testAttribute\", seq);\n" + " }\n" + " public void changeRequest()\n" + " {\n" + " req.setAttribute(\"testAttribute\", \"true\");\n" + " }\n"
+ " public void testPrimitives(java.lang.Short shortParam, java.lang.Integer integerParam, java.lang.Long longParam, java.lang.Float floatParam, java.lang.Double doubleParam, java.lang.Character characterParam, java.lang.String stringParam, java.util.Date dateParam)\n" + " {\n" + " req.setAttribute(\"shortParam\", shortParam);\n" + " req.setAttribute(\"integerParam\", integerParam);\n" + " req.setAttribute(\"longParam\", longParam);\n" + " req.setAttribute(\"floatParam\", floatParam);\n" + " req.setAttribute(\"doubleParam\", doubleParam);\n" + " req.setAttribute(\"characterParam\", characterParam);\n" + " req.setAttribute(\"stringParam\", stringParam);\n" + " req.setAttribute(\"dateParam\", dateParam);\n" + " }\n"
+ " public void testBusiness(test.generated.TestBusinessDTO businessParam)\n" + " {\n" + " req.setAttribute(\"testCharacter\", businessParam.getValue(\"testCharacter\"));\n" + " req.setAttribute(\"testDouble\", businessParam.getTestStruct().getValue(\"testDouble\"));\n" + " }\n" + " public void failTestBusiness(test.generated.TestBusinessDTO businessParam)\n" + " {\n" + " req.setAttribute(\"testCharacter\", \"testValue Extra Stuff\");\n" + " req.setAttribute(\"testDouble\", \"invalid\");\n" + " }\n" + " public void testRelationship(test.generated.TestRelationshipDTO relationshipParam)\n" + " {\n" + " req.setAttribute(\"testInteger\", relationshipParam.getTestInteger());\n" + " }\n" + " public void testArray(java.lang.String[] testArray)\n" + " {\n"
+ " req.setAttribute(\"testArray\", testArray[3]);\n" + " }\n" + " public void testDTOArray(test.generated.TestBusinessDTO[] testArray)\n" + " {\n" + " req.setAttribute(\"testCharacter\", testArray[3].getValue(\"testCharacter\"));\n" + " req.setAttribute(\"testDouble\", testArray[3].getTestStruct().getValue(\"testDouble\"));\n" + " }\n" + " public void testException()\n" + " {\n" + " throw new " + pack + ".TestExceptionDTO(super.getClientRequest());\n" + " }\n" + " public void testMultipartFileParameter(" + MdActionInfo.MULTIPART_FILE_PARAMETER +" file)\n" + " {\n" + "}\n" + "}\n";
return source;
}
}
| true | true | private static void classSetUp()
{
mdStruct = MdStructDAO.newInstance();
mdStruct.setValue(MdStructInfo.PACKAGE, pack);
mdStruct.setValue(MdStructInfo.NAME, "TestStruct");
mdStruct.setStructValue(MdStructInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Struct");
mdStruct.apply();
MdAttributeConcreteDAO mdDouble = MdAttributeDoubleDAO.newInstance();
mdDouble.setValue(MdAttributeDoubleInfo.NAME, "testDouble");
mdDouble.setStructValue(MdAttributeDoubleInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Double");
mdDouble.setValue(MdAttributeDoubleInfo.DEFINING_MD_CLASS, mdStruct.getId());
mdDouble.setValue(MdAttributeDoubleInfo.DECIMAL, "2");
mdDouble.setValue(MdAttributeDoubleInfo.LENGTH, "2");
mdDouble.apply();
mdBusiness = MdBusinessDAO.newInstance();
mdBusiness.setValue(MdBusinessInfo.PACKAGE, pack);
mdBusiness.setValue(MdBusinessInfo.NAME, "TestBusiness");
mdBusiness.setStructValue(MdBusinessInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdBusiness.setGenerateMdController(false);
mdBusiness.apply();
MdAttributeConcreteDAO mdAttribute = MdAttributeCharacterDAO.newInstance();
mdAttribute.setValue(MdAttributeCharacterInfo.NAME, "testCharacter");
mdAttribute.setStructValue(MdAttributeCharacterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Character");
mdAttribute.setValue(MdAttributeCharacterInfo.DEFINING_MD_CLASS, mdBusiness.getId());
mdAttribute.setValue(MdAttributeCharacterInfo.SIZE, "255");
mdAttribute.apply();
MdAttributeConcreteDAO structAttribute = MdAttributeStructDAO.newInstance();
structAttribute.setValue(MdAttributeStructInfo.NAME, "testStruct");
structAttribute.setStructValue(MdAttributeStructInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Struct");
structAttribute.setValue(MdAttributeStructInfo.DEFINING_MD_CLASS, mdBusiness.getId());
structAttribute.setValue(MdAttributeStructInfo.MD_STRUCT, mdStruct.getId());
structAttribute.apply();
mdRelationship = MdRelationshipDAO.newInstance();
mdRelationship.setValue(MdRelationshipInfo.PACKAGE, pack);
mdRelationship.setValue(MdRelationshipInfo.NAME, "TestRelationship");
mdRelationship.setStructValue(MdRelationshipInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdRelationship.setValue(MdRelationshipInfo.PARENT_CARDINALITY, "*");
mdRelationship.setStructValue(MdRelationshipInfo.PARENT_DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Parent Relationship");
mdRelationship.setValue(MdRelationshipInfo.PARENT_MD_BUSINESS, mdBusiness.getId());
mdRelationship.setValue(MdRelationshipInfo.PARENT_METHOD, "testParent");
mdRelationship.setValue(MdRelationshipInfo.CHILD_CARDINALITY, "*");
mdRelationship.setStructValue(MdRelationshipInfo.CHILD_DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Child Relationship");
mdRelationship.setValue(MdRelationshipInfo.CHILD_MD_BUSINESS, mdBusiness.getId());
mdRelationship.setValue(MdRelationshipInfo.CHILD_METHOD, "testChild");
mdRelationship.setGenerateMdController(false);
mdRelationship.apply();
MdAttributeConcreteDAO integerAttribute = MdAttributeIntegerDAO.newInstance();
integerAttribute.setValue(MdAttributeIntegerInfo.NAME, "testInteger");
integerAttribute.setValue(MdAttributeIntegerInfo.DEFINING_MD_CLASS, mdRelationship.getId());
integerAttribute.setStructValue(MdAttributeIntegerInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Integer");
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_NEGATIVE, MdAttributeBooleanInfo.FALSE);
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_POSITIVE, MdAttributeBooleanInfo.FALSE);
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_ZERO, MdAttributeBooleanInfo.FALSE);
integerAttribute.apply();
mdController = MdControllerDAO.newInstance();
mdController.setValue(MdControllerInfo.NAME, "TestController");
mdController.setValue(MdControllerInfo.PACKAGE, pack);
mdController.setStructValue(MdControllerInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Controller");
mdController.setStructValue(MdControllerInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Controller");
mdController.apply();
MdActionDAO mdAction = MdActionDAO.newInstance();
mdAction.setValue(MdActionInfo.NAME, "testAction");
mdAction.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Action");
mdAction.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Action");
mdAction.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction.apply();
MdParameterDAO seqParameter = MdParameterDAO.newInstance();
seqParameter.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction.getId());
seqParameter.setValue(MdParameterInfo.TYPE, "java.lang.Long");
seqParameter.setValue(MdParameterInfo.NAME, "seq");
seqParameter.setValue(MdParameterInfo.ORDER, "0");
seqParameter.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
seqParameter.apply();
MdParameterDAO testParameter = MdParameterDAO.newInstance();
testParameter.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction.getId());
testParameter.setValue(MdParameterInfo.TYPE, "java.lang.Long");
testParameter.setValue(MdParameterInfo.NAME, "value");
testParameter.setValue(MdParameterInfo.ORDER, "1");
testParameter.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "value");
testParameter.apply();
MdActionDAO mdAction2 = MdActionDAO.newInstance();
mdAction2.setValue(MdActionInfo.NAME, "changeRequest");
mdAction2.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction2.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Change Request");
mdAction2.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Change Request");
mdAction2.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction2.apply();
MdActionDAO mdAction3 = MdActionDAO.newInstance();
mdAction3.setValue(MdActionInfo.NAME, "testPrimitives");
mdAction3.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction3.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Primitives");
mdAction3.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Primitives");
mdAction3.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction3.apply();
MdParameterDAO shortParam = MdParameterDAO.newInstance();
shortParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
shortParam.setValue(MdParameterInfo.TYPE, "java.lang.Short");
shortParam.setValue(MdParameterInfo.NAME, "shortParam");
shortParam.setValue(MdParameterInfo.ORDER, "0");
shortParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
shortParam.apply();
MdParameterDAO integerParam = MdParameterDAO.newInstance();
integerParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
integerParam.setValue(MdParameterInfo.TYPE, "java.lang.Integer");
integerParam.setValue(MdParameterInfo.NAME, "integerParam");
integerParam.setValue(MdParameterInfo.ORDER, "1");
integerParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
integerParam.apply();
MdParameterDAO longParam = MdParameterDAO.newInstance();
longParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
longParam.setValue(MdParameterInfo.TYPE, "java.lang.Long");
longParam.setValue(MdParameterInfo.NAME, "longParam");
longParam.setValue(MdParameterInfo.ORDER, "2");
longParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
longParam.apply();
MdParameterDAO floatParam = MdParameterDAO.newInstance();
floatParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
floatParam.setValue(MdParameterInfo.TYPE, "java.lang.Float");
floatParam.setValue(MdParameterInfo.NAME, "floatParam");
floatParam.setValue(MdParameterInfo.ORDER, "3");
floatParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
floatParam.apply();
MdParameterDAO doubleParam = MdParameterDAO.newInstance();
doubleParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
doubleParam.setValue(MdParameterInfo.TYPE, "java.lang.Double");
doubleParam.setValue(MdParameterInfo.NAME, "doubleParam");
doubleParam.setValue(MdParameterInfo.ORDER, "4");
doubleParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
doubleParam.apply();
MdParameterDAO characterParam = MdParameterDAO.newInstance();
characterParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
characterParam.setValue(MdParameterInfo.TYPE, "java.lang.Character");
characterParam.setValue(MdParameterInfo.NAME, "characterParam");
characterParam.setValue(MdParameterInfo.ORDER, "5");
characterParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
characterParam.apply();
MdParameterDAO stringParam = MdParameterDAO.newInstance();
stringParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
stringParam.setValue(MdParameterInfo.TYPE, "java.lang.String");
stringParam.setValue(MdParameterInfo.NAME, "stringParam");
stringParam.setValue(MdParameterInfo.ORDER, "6");
stringParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
stringParam.apply();
MdParameterDAO dateParam = MdParameterDAO.newInstance();
dateParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
dateParam.setValue(MdParameterInfo.TYPE, "java.util.Date");
dateParam.setValue(MdParameterInfo.NAME, "dateParam");
dateParam.setValue(MdParameterInfo.ORDER, "7");
dateParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
dateParam.apply();
MdActionDAO mdAction4 = MdActionDAO.newInstance();
mdAction4.setValue(MdActionInfo.NAME, "testBusiness");
mdAction4.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction4.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdAction4.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdAction4.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction4.apply();
MdParameterDAO businessParam = MdParameterDAO.newInstance();
businessParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction4.getId());
businessParam.setValue(MdParameterInfo.TYPE, mdBusiness.definesType());
businessParam.setValue(MdParameterInfo.NAME, "businessParam");
businessParam.setValue(MdParameterInfo.ORDER, "0");
businessParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Business Param");
businessParam.apply();
MdActionDAO mdAction5 = MdActionDAO.newInstance();
mdAction5.setValue(MdActionInfo.NAME, "testRelationship");
mdAction5.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction5.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdAction5.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdAction5.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction5.apply();
MdParameterDAO relationshipParam = MdParameterDAO.newInstance();
relationshipParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction5.getId());
relationshipParam.setValue(MdParameterInfo.TYPE, mdRelationship.definesType());
relationshipParam.setValue(MdParameterInfo.NAME, "relationshipParam");
relationshipParam.setValue(MdParameterInfo.ORDER, "0");
relationshipParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Relationship Param");
relationshipParam.apply();
MdActionDAO mdAction6 = MdActionDAO.newInstance();
mdAction6.setValue(MdActionInfo.NAME, "testArray");
mdAction6.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction6.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
mdAction6.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
mdAction6.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction6.apply();
MdParameterDAO stringArrayParam = MdParameterDAO.newInstance();
stringArrayParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction6.getId());
stringArrayParam.setValue(MdParameterInfo.TYPE, "java.lang.String[]");
stringArrayParam.setValue(MdParameterInfo.NAME, "testArray");
stringArrayParam.setValue(MdParameterInfo.ORDER, "0");
stringArrayParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
stringArrayParam.apply();
MdActionDAO mdAction7 = MdActionDAO.newInstance();
mdAction7.setValue(MdActionInfo.NAME, "testDTOArray");
mdAction7.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction7.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction7.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction7.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction7.apply();
MdParameterDAO dtoArrayParam = MdParameterDAO.newInstance();
dtoArrayParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction7.getId());
dtoArrayParam.setValue(MdParameterInfo.TYPE, mdBusiness.definesType() + "[]");
dtoArrayParam.setValue(MdParameterInfo.NAME, "testArray");
dtoArrayParam.setValue(MdParameterInfo.ORDER, "0");
dtoArrayParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
dtoArrayParam.apply();
MdActionDAO mdAction8 = MdActionDAO.newInstance();
mdAction8.setValue(MdActionInfo.NAME, "testException");
mdAction8.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction8.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction8.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction8.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction8.apply();
MdActionDAO mdAction9 = MdActionDAO.newInstance();
mdAction9.setValue(MdActionInfo.NAME, "testMultipartFileParameter");
mdAction9.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction9.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction9.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction9.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction9.apply();
MdParameterDAO multipartFileParam = MdParameterDAO.newInstance();
multipartFileParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction9.getId());
multipartFileParam.setValue(MdParameterInfo.TYPE, MdActionInfo.MULTIPART_FILE_PARAMETER);
multipartFileParam.setValue(MdParameterInfo.NAME, "file");
multipartFileParam.setValue(MdParameterInfo.ORDER, "0");
multipartFileParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "File parameter");
multipartFileParam.apply();
mdException = MdExceptionDAO.newInstance();
mdException.setValue(MdExceptionInfo.NAME, "TestException");
mdException.setValue(MdExceptionInfo.PACKAGE, pack);
mdException.setStructValue(MdExceptionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Exception");
mdException.apply();
testActionUri = "/contextPath/" + mdController.definesType() + "." + mdAction.getName() + MdActionInfo.ACTION_SUFFIX;
changeRequestUri = "/contextPath/" + mdController.definesType() + "." + mdAction2.getName() + MdActionInfo.ACTION_SUFFIX;
testPrimitiveUri = "/contextPath/" + mdController.definesType() + "." + mdAction3.getName() + MdActionInfo.ACTION_SUFFIX;
testBusinessUri = "/contextPath/" + mdController.definesType() + "." + mdAction4.getName() + MdActionInfo.ACTION_SUFFIX;
testRelationshipUri = "/contextPath/" + mdController.definesType() + "." + mdAction5.getName() + MdActionInfo.ACTION_SUFFIX;
testPrimitiveArrayUri = "/contextPath/" + mdController.definesType() + "." + mdAction6.getName() + MdActionInfo.ACTION_SUFFIX;
testDTOArrayUri = "/contextPath/" + mdController.definesType() + "." + mdAction7.getName() + MdActionInfo.ACTION_SUFFIX;
testExceptionUri = "/contextPath/" + mdController.definesType() + "." + mdAction8.getName() + MdActionInfo.ACTION_SUFFIX;
testMultipartFileParameterUri = "/contextPath/" + mdController.definesType() + "." + mdAction9.getName() + MdActionInfo.ACTION_SUFFIX;
finalizeSetup();
}
| private static void classSetUp()
{
mdStruct = MdStructDAO.newInstance();
mdStruct.setValue(MdStructInfo.PACKAGE, pack);
mdStruct.setValue(MdStructInfo.NAME, "TestStruct");
mdStruct.setStructValue(MdStructInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Struct");
mdStruct.apply();
MdAttributeConcreteDAO mdDouble = MdAttributeDoubleDAO.newInstance();
mdDouble.setValue(MdAttributeDoubleInfo.NAME, "testDouble");
mdDouble.setStructValue(MdAttributeDoubleInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Double");
mdDouble.setValue(MdAttributeDoubleInfo.DEFINING_MD_CLASS, mdStruct.getId());
mdDouble.setValue(MdAttributeDoubleInfo.DECIMAL, "2");
mdDouble.setValue(MdAttributeDoubleInfo.LENGTH, "2");
mdDouble.apply();
mdBusiness = MdBusinessDAO.newInstance();
mdBusiness.setValue(MdBusinessInfo.PACKAGE, pack);
mdBusiness.setValue(MdBusinessInfo.NAME, "TestBusiness");
mdBusiness.setStructValue(MdBusinessInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdBusiness.setGenerateMdController(false);
mdBusiness.apply();
MdAttributeConcreteDAO mdAttribute = MdAttributeCharacterDAO.newInstance();
mdAttribute.setValue(MdAttributeCharacterInfo.NAME, "testCharacter");
mdAttribute.setStructValue(MdAttributeCharacterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Character");
mdAttribute.setValue(MdAttributeCharacterInfo.DEFINING_MD_CLASS, mdBusiness.getId());
mdAttribute.setValue(MdAttributeCharacterInfo.SIZE, "255");
mdAttribute.apply();
MdAttributeConcreteDAO structAttribute = MdAttributeStructDAO.newInstance();
structAttribute.setValue(MdAttributeStructInfo.NAME, "testStruct");
structAttribute.setStructValue(MdAttributeStructInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Struct");
structAttribute.setValue(MdAttributeStructInfo.DEFINING_MD_CLASS, mdBusiness.getId());
structAttribute.setValue(MdAttributeStructInfo.MD_STRUCT, mdStruct.getId());
structAttribute.apply();
mdRelationship = MdRelationshipDAO.newInstance();
mdRelationship.setValue(MdRelationshipInfo.PACKAGE, pack);
mdRelationship.setValue(MdRelationshipInfo.NAME, "TestRelationship");
mdRelationship.setStructValue(MdRelationshipInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdRelationship.setValue(MdRelationshipInfo.PARENT_CARDINALITY, "*");
mdRelationship.setStructValue(MdRelationshipInfo.PARENT_DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Parent Relationship");
mdRelationship.setValue(MdRelationshipInfo.PARENT_MD_BUSINESS, mdBusiness.getId());
mdRelationship.setValue(MdRelationshipInfo.PARENT_METHOD, "testParent");
mdRelationship.setValue(MdRelationshipInfo.CHILD_CARDINALITY, "*");
mdRelationship.setStructValue(MdRelationshipInfo.CHILD_DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Child Relationship");
mdRelationship.setValue(MdRelationshipInfo.CHILD_MD_BUSINESS, mdBusiness.getId());
mdRelationship.setValue(MdRelationshipInfo.CHILD_METHOD, "testChild");
mdRelationship.setGenerateMdController(false);
mdRelationship.apply();
MdAttributeConcreteDAO integerAttribute = MdAttributeIntegerDAO.newInstance();
integerAttribute.setValue(MdAttributeIntegerInfo.NAME, "testInteger");
integerAttribute.setValue(MdAttributeIntegerInfo.DEFINING_MD_CLASS, mdRelationship.getId());
integerAttribute.setStructValue(MdAttributeIntegerInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Integer");
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_NEGATIVE, MdAttributeBooleanInfo.FALSE);
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_POSITIVE, MdAttributeBooleanInfo.FALSE);
integerAttribute.setValue(MdAttributeIntegerInfo.REJECT_ZERO, MdAttributeBooleanInfo.FALSE);
integerAttribute.apply();
mdController = MdControllerDAO.newInstance();
mdController.setValue(MdControllerInfo.NAME, "TestController");
mdController.setValue(MdControllerInfo.PACKAGE, pack);
mdController.setStructValue(MdControllerInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Controller");
mdController.setStructValue(MdControllerInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Controller");
mdController.apply();
MdActionDAO mdAction = MdActionDAO.newInstance();
mdAction.setValue(MdActionInfo.NAME, "testAction");
mdAction.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Action");
mdAction.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Action");
mdAction.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction.apply();
MdParameterDAO seqParameter = MdParameterDAO.newInstance();
seqParameter.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction.getId());
seqParameter.setValue(MdParameterInfo.TYPE, "java.lang.Long");
seqParameter.setValue(MdParameterInfo.NAME, "seq");
seqParameter.setValue(MdParameterInfo.ORDER, "0");
seqParameter.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
seqParameter.apply();
MdParameterDAO testParameter = MdParameterDAO.newInstance();
testParameter.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction.getId());
testParameter.setValue(MdParameterInfo.TYPE, "java.lang.Long");
testParameter.setValue(MdParameterInfo.NAME, "value");
testParameter.setValue(MdParameterInfo.ORDER, "1");
testParameter.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "value");
testParameter.apply();
MdActionDAO mdAction2 = MdActionDAO.newInstance();
mdAction2.setValue(MdActionInfo.NAME, "changeRequest");
mdAction2.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction2.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Change Request");
mdAction2.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Change Request");
mdAction2.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction2.apply();
MdActionDAO mdAction3 = MdActionDAO.newInstance();
mdAction3.setValue(MdActionInfo.NAME, "testPrimitives");
mdAction3.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction3.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Primitives");
mdAction3.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Primitives");
mdAction3.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction3.apply();
MdParameterDAO shortParam = MdParameterDAO.newInstance();
shortParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
shortParam.setValue(MdParameterInfo.TYPE, "java.lang.Short");
shortParam.setValue(MdParameterInfo.NAME, "shortParam");
shortParam.setValue(MdParameterInfo.ORDER, "0");
shortParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
shortParam.apply();
MdParameterDAO integerParam = MdParameterDAO.newInstance();
integerParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
integerParam.setValue(MdParameterInfo.TYPE, "java.lang.Integer");
integerParam.setValue(MdParameterInfo.NAME, "integerParam");
integerParam.setValue(MdParameterInfo.ORDER, "1");
integerParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
integerParam.apply();
MdParameterDAO longParam = MdParameterDAO.newInstance();
longParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
longParam.setValue(MdParameterInfo.TYPE, "java.lang.Long");
longParam.setValue(MdParameterInfo.NAME, "longParam");
longParam.setValue(MdParameterInfo.ORDER, "2");
longParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
longParam.apply();
MdParameterDAO floatParam = MdParameterDAO.newInstance();
floatParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
floatParam.setValue(MdParameterInfo.TYPE, "java.lang.Float");
floatParam.setValue(MdParameterInfo.NAME, "floatParam");
floatParam.setValue(MdParameterInfo.ORDER, "3");
floatParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
floatParam.apply();
MdParameterDAO doubleParam = MdParameterDAO.newInstance();
doubleParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
doubleParam.setValue(MdParameterInfo.TYPE, "java.lang.Double");
doubleParam.setValue(MdParameterInfo.NAME, "doubleParam");
doubleParam.setValue(MdParameterInfo.ORDER, "4");
doubleParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
doubleParam.apply();
MdParameterDAO characterParam = MdParameterDAO.newInstance();
characterParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
characterParam.setValue(MdParameterInfo.TYPE, "java.lang.Character");
characterParam.setValue(MdParameterInfo.NAME, "characterParam");
characterParam.setValue(MdParameterInfo.ORDER, "5");
characterParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
characterParam.apply();
MdParameterDAO stringParam = MdParameterDAO.newInstance();
stringParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
stringParam.setValue(MdParameterInfo.TYPE, "java.lang.String");
stringParam.setValue(MdParameterInfo.NAME, "stringParam");
stringParam.setValue(MdParameterInfo.ORDER, "6");
stringParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
stringParam.apply();
MdParameterDAO dateParam = MdParameterDAO.newInstance();
dateParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction3.getId());
dateParam.setValue(MdParameterInfo.TYPE, "java.util.Date");
dateParam.setValue(MdParameterInfo.NAME, "dateParam");
dateParam.setValue(MdParameterInfo.ORDER, "7");
dateParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Sequence");
dateParam.apply();
MdActionDAO mdAction4 = MdActionDAO.newInstance();
mdAction4.setValue(MdActionInfo.NAME, "testBusiness");
mdAction4.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction4.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdAction4.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Business");
mdAction4.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction4.apply();
MdParameterDAO businessParam = MdParameterDAO.newInstance();
businessParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction4.getId());
businessParam.setValue(MdParameterInfo.TYPE, mdBusiness.definesType());
businessParam.setValue(MdParameterInfo.NAME, "businessParam");
businessParam.setValue(MdParameterInfo.ORDER, "0");
businessParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Business Param");
businessParam.apply();
MdActionDAO mdAction5 = MdActionDAO.newInstance();
mdAction5.setValue(MdActionInfo.NAME, "testRelationship");
mdAction5.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction5.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdAction5.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Relationship");
mdAction5.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction5.apply();
MdParameterDAO relationshipParam = MdParameterDAO.newInstance();
relationshipParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction5.getId());
relationshipParam.setValue(MdParameterInfo.TYPE, mdRelationship.definesType());
relationshipParam.setValue(MdParameterInfo.NAME, "relationshipParam");
relationshipParam.setValue(MdParameterInfo.ORDER, "0");
relationshipParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Relationship Param");
relationshipParam.apply();
MdActionDAO mdAction6 = MdActionDAO.newInstance();
mdAction6.setValue(MdActionInfo.NAME, "testArray");
mdAction6.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction6.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
mdAction6.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
mdAction6.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction6.apply();
MdParameterDAO stringArrayParam = MdParameterDAO.newInstance();
stringArrayParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction6.getId());
stringArrayParam.setValue(MdParameterInfo.TYPE, "java.lang.String[]");
stringArrayParam.setValue(MdParameterInfo.NAME, "testArray");
stringArrayParam.setValue(MdParameterInfo.ORDER, "0");
stringArrayParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
stringArrayParam.apply();
MdActionDAO mdAction7 = MdActionDAO.newInstance();
mdAction7.setValue(MdActionInfo.NAME, "testDTOArray");
mdAction7.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction7.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction7.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction7.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction7.apply();
MdParameterDAO dtoArrayParam = MdParameterDAO.newInstance();
dtoArrayParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction7.getId());
dtoArrayParam.setValue(MdParameterInfo.TYPE, mdBusiness.definesType() + "[]");
dtoArrayParam.setValue(MdParameterInfo.NAME, "testArray");
dtoArrayParam.setValue(MdParameterInfo.ORDER, "0");
dtoArrayParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Array");
dtoArrayParam.apply();
MdActionDAO mdAction8 = MdActionDAO.newInstance();
mdAction8.setValue(MdActionInfo.NAME, "testException");
mdAction8.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction8.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction8.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction8.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction8.apply();
MdActionDAO mdAction9 = MdActionDAO.newInstance();
mdAction9.setValue(MdActionInfo.NAME, "testMultipartFileParameter");
mdAction9.setValue(MdActionInfo.ENCLOSING_MD_CONTROLLER, mdController.getId());
mdAction9.setStructValue(MdActionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction9.setStructValue(MdActionInfo.DESCRIPTION, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test DTO Array");
mdAction9.setValue(MdActionInfo.IS_POST, MdAttributeBooleanInfo.TRUE);
mdAction9.apply();
MdParameterDAO multipartFileParam = MdParameterDAO.newInstance();
multipartFileParam.setValue(MdParameterInfo.ENCLOSING_METADATA, mdAction9.getId());
multipartFileParam.setValue(MdParameterInfo.TYPE, MdActionInfo.MULTIPART_FILE_PARAMETER);
multipartFileParam.setValue(MdParameterInfo.NAME, "file");
multipartFileParam.setValue(MdParameterInfo.ORDER, "0");
multipartFileParam.setStructValue(MdParameterInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "File parameter");
multipartFileParam.apply();
mdException = MdExceptionDAO.newInstance();
mdException.setValue(MdExceptionInfo.NAME, "TestException");
mdException.setValue(MdExceptionInfo.PACKAGE, pack);
mdException.setStructValue(MdExceptionInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Test Exception");
mdException.apply();
testActionUri = "/contextPath/" + mdController.definesType() + "." + mdAction.getName() + MdActionInfo.ACTION_SUFFIX;
changeRequestUri = "/contextPath/" + mdController.definesType() + "." + mdAction2.getName() + MdActionInfo.ACTION_SUFFIX;
testPrimitiveUri = "/contextPath/" + mdController.definesType() + "." + mdAction3.getName() + MdActionInfo.ACTION_SUFFIX;
testBusinessUri = "/contextPath/" + mdController.definesType() + "." + mdAction4.getName() + MdActionInfo.ACTION_SUFFIX;
testRelationshipUri = "/contextPath/" + mdController.definesType() + "." + mdAction5.getName() + MdActionInfo.ACTION_SUFFIX;
testPrimitiveArrayUri = "/contextPath/" + mdController.definesType() + "." + mdAction6.getName() + MdActionInfo.ACTION_SUFFIX;
testDTOArrayUri = "/contextPath/" + mdController.definesType() + "." + mdAction7.getName() + MdActionInfo.ACTION_SUFFIX;
testExceptionUri = "/contextPath/" + mdController.definesType() + "." + mdAction8.getName() + MdActionInfo.ACTION_SUFFIX;
// testMultipartFileParameterUri = "/contextPath/" + mdController.definesType() + "." + mdAction9.getName() + MdActionInfo.ACTION_SUFFIX;
finalizeSetup();
}
|
diff --git a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/contentassist/RemoteCompletionProposalAdapter.java b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/contentassist/RemoteCompletionProposalAdapter.java
index c13c61479..3dc4d7277 100644
--- a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/contentassist/RemoteCompletionProposalAdapter.java
+++ b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/contentassist/RemoteCompletionProposalAdapter.java
@@ -1,45 +1,47 @@
/*******************************************************************************
* Copyright (c) 2008 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.ptp.internal.rdt.ui.contentassist;
import org.eclipse.core.resources.IProject;
import org.eclipse.ptp.rdt.core.services.IRDTServiceConstants;
import org.eclipse.ptp.rdt.services.core.IService;
import org.eclipse.ptp.rdt.services.core.IServiceConfiguration;
import org.eclipse.ptp.rdt.services.core.IServiceProvider;
import org.eclipse.ptp.rdt.services.core.ServiceModelManager;
import org.eclipse.ptp.rdt.ui.serviceproviders.IIndexServiceProvider2;
/**
* Adapts <code>Proposal</code>s from a standalone content assist invocation
* to proposal instances required by Eclipse's content assist framework.
*/
public class RemoteCompletionProposalAdapter extends AbstractCompletionProposalAdapter {
@Override
protected IContentAssistService getService(IProject project) {
ServiceModelManager manager = ServiceModelManager.getInstance();
+ if(!manager.isConfigured(project))
+ return null;
IServiceConfiguration config = manager.getActiveConfiguration(project);
if (config == null) {
return null;
}
IService service = manager.getService(IRDTServiceConstants.SERVICE_C_INDEX);
IServiceProvider provider = config.getServiceProvider(service);
if (!(provider instanceof IIndexServiceProvider2)) {
return null;
}
return ((IIndexServiceProvider2) provider).getContentAssistService();
}
}
| true | true | protected IContentAssistService getService(IProject project) {
ServiceModelManager manager = ServiceModelManager.getInstance();
IServiceConfiguration config = manager.getActiveConfiguration(project);
if (config == null) {
return null;
}
IService service = manager.getService(IRDTServiceConstants.SERVICE_C_INDEX);
IServiceProvider provider = config.getServiceProvider(service);
if (!(provider instanceof IIndexServiceProvider2)) {
return null;
}
return ((IIndexServiceProvider2) provider).getContentAssistService();
}
| protected IContentAssistService getService(IProject project) {
ServiceModelManager manager = ServiceModelManager.getInstance();
if(!manager.isConfigured(project))
return null;
IServiceConfiguration config = manager.getActiveConfiguration(project);
if (config == null) {
return null;
}
IService service = manager.getService(IRDTServiceConstants.SERVICE_C_INDEX);
IServiceProvider provider = config.getServiceProvider(service);
if (!(provider instanceof IIndexServiceProvider2)) {
return null;
}
return ((IIndexServiceProvider2) provider).getContentAssistService();
}
|
diff --git a/src/pt/up/fe/dceg/neptus/util/comm/transports/udp/UDPTransport.java b/src/pt/up/fe/dceg/neptus/util/comm/transports/udp/UDPTransport.java
index efa1ced6b..23ed4ab73 100644
--- a/src/pt/up/fe/dceg/neptus/util/comm/transports/udp/UDPTransport.java
+++ b/src/pt/up/fe/dceg/neptus/util/comm/transports/udp/UDPTransport.java
@@ -1,895 +1,895 @@
/*
* Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact lsts@fe.up.pt.
*
* European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://www.lsts.pt/neptus/licence.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author: Paulo Dias
* 2010/01/16
*/
package pt.up.fe.dceg.neptus.util.comm.transports.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import pt.up.fe.dceg.neptus.NeptusLog;
import pt.up.fe.dceg.neptus.util.ByteUtil;
import pt.up.fe.dceg.neptus.util.comm.transports.DeliveryListener;
import pt.up.fe.dceg.neptus.util.comm.transports.DeliveryListener.ResultEnum;
/**
* @author pdias
*
*/
public class UDPTransport {
protected LinkedHashSet<UDPMessageListener> listeners = new LinkedHashSet<UDPMessageListener>();
private LinkedBlockingQueue<UDPNotification> receptionMessageList = new LinkedBlockingQueue<UDPNotification>();
private LinkedBlockingQueue<UDPNotification> sendmessageList = new LinkedBlockingQueue<UDPNotification>();
private Thread sockedListenerThread = null;
private Thread dispacherThread = null;
private Vector<Thread> senderThreads = new Vector<Thread>();
private int numberOfSenderThreads = 1;
private DatagramSocket sock;
private LinkedHashMap<String, InetAddress> solvedAddresses = new LinkedHashMap<String, InetAddress>();
private int bindPort = 6001;
private int timeoutMillis = 1000;
private int maxBufferSize = 65507;
private boolean purging = false;
private boolean broadcastEnable = false;
private boolean broadcastActive = false;
private boolean multicastEnable = false;
private boolean multicastActive = false;
private String multicastAddress = "224.0.75.69";
private boolean isOnBindError = false;
/**
*
*/
public UDPTransport() {
initialize();
}
/**
* @param numberOfSenderThreads
*/
public UDPTransport(int numberOfSenderThreads) {
this.numberOfSenderThreads = numberOfSenderThreads;
initialize();
}
/**
* @param bindPort
* @param numberOfSenderThreads
*/
public UDPTransport(int bindPort, int numberOfSenderThreads) {
setBindPort(bindPort);
initialize();
}
public UDPTransport(boolean isBroadcastEnable, int bindPort, int numberOfSenderThreads) {
setBindPort(bindPort);
setBroadcastEnable(isBroadcastEnable);
initialize();
}
/**
* @param multicastAddress
* @param bindPort
* @param numberOfSenderThreads
*/
public UDPTransport(String multicastAddress, int bindPort, int numberOfSenderThreads) {
setNumberOfSenderThreads(numberOfSenderThreads);
setBindPort(bindPort);
setMulticastAddress(multicastAddress);
setMulticastEnable(true);
initialize();
}
/**
* @param multicastAddress
* @param bindPort
*/
public UDPTransport(String multicastAddress, int bindPort) {
this(multicastAddress, bindPort, 1);
}
/**
*
*/
private void initialize() {
createReceivers();
createSenders();
}
/**
* @return the isOnBindError
*/
public boolean isOnBindError() {
return isOnBindError;
}
/**
* @param isOnBindError the isOnBindError to set
*/
private void setOnBindError(boolean isOnBindError) {
this.isOnBindError = isOnBindError;
}
// /**
// * For now tests is the receiver thread is alive and
// * this transport is {@link #isRunnning()}.
// * Can serve for binding error.
// * @return
// */
// public boolean isReceiverConnected() {
// if (dispacherThread == null)
// return false;
// return isRunnning() && dispacherThread.isAlive();
// }
/**
* @return
*/
public int getBindPort() {
return bindPort;
}
/**
* @param bindPort
*/
public void setBindPort(int bindPort) {
this.bindPort = bindPort;
}
/**
* @return the multicastAddress
*/
public String getMulticastAddress() {
return multicastAddress;
}
/**
* @param multicastAddress the multicastAddress to set
*/
public void setMulticastAddress(String multicastAddress) {
this.multicastAddress = multicastAddress;
}
/**
* @return the multicastEnable
*/
public boolean isMulticastEnable() {
return multicastEnable;
}
/**
* @param multicastEnable the multicastEnable to set
*/
public void setMulticastEnable(boolean multicastEnable) {
this.multicastEnable = multicastEnable;
}
/**
* @return the multicastActive
*/
protected boolean isMulticastActive() {
return multicastActive;
}
/**
* @param multicastActive the multicastActive to set
*/
protected void setMulticastActive(boolean multicastActive) {
this.multicastActive = multicastActive;
}
/**
* @return the broadcastEnable
*/
public boolean isBroadcastEnable() {
return broadcastEnable;
}
/**
* @param broadcastEnable the broadcastEnable to set
*/
public void setBroadcastEnable(boolean broadcastEnable) {
this.broadcastEnable = broadcastEnable;
}
/**
* @return the broadcastActive
*/
protected boolean isBroadcastActive() {
return broadcastActive;
}
/**
* @param broadcastActive the broadcastActive to set
*/
protected void setBroadcastActive(boolean broadcastActive) {
this.broadcastActive = broadcastActive;
}
/**
* @return the numberOfSenderThreads
*/
public int getNumberOfSenderThreads() {
return numberOfSenderThreads;
}
/**
* @param numberOfSenderThreads the numberOfSenderThreads to set
*/
public void setNumberOfSenderThreads(int numberOfSenderThreads) {
this.numberOfSenderThreads = numberOfSenderThreads;
}
/**
* @return the timeoutMillis
*/
public int getTimeoutMillis() {
return timeoutMillis;
}
/**
* @param timeoutMillis the timeoutMillis to set
*/
public void setTimeoutMillis(int timeoutMillis) {
this.timeoutMillis = timeoutMillis;
}
/**
* @return the maxBufferSize
*/
public int getMaxBufferSize() {
return maxBufferSize;
}
/**
* @param maxBufferSize the maxBufferSize to set
*/
public void setMaxBufferSize(int maxBufferSize) {
this.maxBufferSize = maxBufferSize;
}
/**
* @param multicastAddress
* @return
*/
protected InetAddress resolveAddress(String multicastAddress) throws UnknownHostException {
if (!solvedAddresses.containsKey(multicastAddress)) {
solvedAddresses.put(multicastAddress, InetAddress.getByName(multicastAddress));
}
return solvedAddresses.get(multicastAddress);
}
/**
* @return
*/
public boolean reStart() {
if (!(!isStopping() && !isRunning()))
return false;
purging = false;
createReceivers();
createSenders();
return true;
}
/**
* Interrupts all the sending threads abruptly.
*
* @see {@link #purge()}
*/
public void stop() {
if (isRunning()) {
purging = true;
if (sockedListenerThread != null) {
sockedListenerThread.interrupt();
sockedListenerThread = null;
}
synchronized (receptionMessageList) {
receptionMessageList.clear();
}
if (dispacherThread != null) {
dispacherThread.interrupt();
dispacherThread = null;
}
int size = senderThreads.size();
for (int i = 0; i < size; i++) {
try {
senderThreads.get(0).interrupt();
senderThreads.remove(0); // shifts the right elements to the left
}
catch (Exception e) {
NeptusLog.pub().error(e.getMessage());
}
}
Vector<UDPNotification> toClearSen = new Vector<UDPNotification>();
sendmessageList.drainTo(toClearSen);
for (UDPNotification req : toClearSen) {
informDeliveryListener(req, ResultEnum.Error, new Exception("Server shutdown!!"));
}
}
}
/**
* Stops accepting new messages but waits until all the buffered messages are sent to the network before stopping
* the sending thread(s).
*/
public void purge() {
purging = true;
while (!receptionMessageList.isEmpty() || !sendmessageList.isEmpty()) {
try {
Thread.sleep(1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
stop();
}
/**
* @return
*/
public boolean isRunning() {
if (senderThreads.size() > 0)
return true;
if (sockedListenerThread == null && dispacherThread == null)
return false;
return true;
}
/**
* @return
*/
public boolean isRunningNormally() {
if (isOnBindError())
return false;
if (senderThreads.size() == 0)
return false;
if (sockedListenerThread == null)
return false;
if (dispacherThread == null)
return false;
return true;
}
/**
* @return
*/
public boolean isStopping() {
if (isRunning() && purging)
return true;
return false;
}
/**
*
*/
private void createSenders() {
senderThreads.clear();
for (int i = 0; i < this.numberOfSenderThreads; i++) {
if (i == 0)
senderThreads.add(getSenderThread(sock));
else
senderThreads.add(getSenderThread(null));
}
}
/**
*
*/
private void createReceivers() {
setOnBindError(false);
getSockedListenerThread();
getDispacherThread();
}
/**
* @return
*/
private Thread getSockedListenerThread() {
if (sockedListenerThread == null) {
Thread listenerThread = new Thread(UDPTransport.class.getSimpleName() + ": Listener Thread "
+ this.hashCode()) {
byte[] sBuffer = new byte[maxBufferSize];
String multicastGroup = "";
public synchronized void start() {
NeptusLog.pub().debug("Listener Thread Started");
try {
boolean useMulticast = isMulticastEnable();
sock = (!useMulticast) ? new DatagramSocket(null) : new MulticastSocket(null);
// if (useMulticast) {
// sock.setReuseAddress(true); // This may be a potential problem when opening two Neptus instances, we don't detect a bind error
// }
sock.setReuseAddress(false);
if (bindPort != 0) {
sock.bind(new InetSocketAddress(bindPort));
}
else {
sock.bind(new InetSocketAddress(0));
}
try {
if (useMulticast) {
((MulticastSocket) sock).joinGroup(resolveAddress(getMulticastAddress()));
multicastGroup = getMulticastAddress();
}
setMulticastActive(useMulticast);
}
catch (Exception e) {
- NeptusLog.pub().error(e.getMessage());
+ NeptusLog.pub().error("Multicast socket join :: " + e.getMessage());
setMulticastActive(false);
}
sock.setSoTimeout(timeoutMillis);
if (isBroadcastEnable()) {
try {
sock.setBroadcast(true);
setBroadcastActive(true);
}
catch (Exception e) {
NeptusLog.pub().error(e.getMessage());
setBroadcastActive(false);
}
}
}
catch (Exception e) {
NeptusLog.pub().error(e);
setOnBindError(true);
return;
}
finally {
if (isOnBindError()) {
try {
sock.disconnect();
sock.close();
}
catch (Exception e) {
NeptusLog.pub().error(e.getStackTrace());
}
}
}
super.start();
}
public void run() {
try {
while (!purging) {
DatagramPacket packet = new DatagramPacket(sBuffer, sBuffer.length);
try {
sock.receive(packet);
int lengthReceived = packet.getLength();
try {
byte[] recBytes = Arrays.copyOf(sBuffer, lengthReceived);
UDPNotification info = new UDPNotification(UDPNotification.RECEPTION,
(InetSocketAddress) packet.getSocketAddress(), recBytes,
System.currentTimeMillis());
receptionMessageList.offer(info);
}
catch (Exception e) {
e.printStackTrace();
// FIXME treat better this exception (pdias)
}
}
catch (SocketTimeoutException e) {
// NeptusLog.pub().warn(this + " Thread SocketTimeoutException");
// try { Thread.sleep(1500); } catch (Exception e1) { }
continue;
}
catch (Exception e) {
NeptusLog.pub().error(e);
e.printStackTrace();
// continue;
}
catch (Error e) {
NeptusLog.pub().error(e);
e.printStackTrace();
// continue;
}
// Thread.sleep(1);
// try { Thread.sleep(10); } catch (Exception e) { }
}
}
catch (Exception e) {
NeptusLog.pub().error(e);
// NeptusLog.pub().warn(this+" Thread interrupted");
}
NeptusLog.pub().warn(this + " Thread Stopped");
if (isMulticastActive()) {
try {
// ((MulticastSocket)sock).leaveGroup(((MulticastSocket)sock).getInetAddress());
((MulticastSocket) sock).leaveGroup(resolveAddress(multicastGroup));
}
catch (IOException e) {
e.printStackTrace();
}
}
sock.disconnect();
sock.close();
sock = null;
sockedListenerThread = null;
}
};
listenerThread.setPriority(Thread.MIN_PRIORITY);
listenerThread.setDaemon(true);
listenerThread.start();
sockedListenerThread = listenerThread;
}
return sockedListenerThread;
}
/**
* @return
*/
private Thread getDispacherThread() {
if (dispacherThread == null) {
Thread listenerThread = new Thread(UDPTransport.class.getSimpleName() + ": Dispacher Thread "
+ this.hashCode()) {
public synchronized void start() {
NeptusLog.pub().debug("Dispacher Thread Started");
super.start();
}
public void run() {
try {
while (!(purging && receptionMessageList.isEmpty())) {
UDPNotification req;
req = receptionMessageList.poll(1, TimeUnit.SECONDS);
if (req == null)
continue;
for (UDPMessageListener lst : listeners) {
try {
lst.onUDPMessageNotification(req);
}
catch (ArrayIndexOutOfBoundsException e) {
NeptusLog.pub().debug(
"Dispacher Thread: ArrayIndexOutOfBoundsException: "
+ "onUDPMessageNotification " + e.getMessage());
}
catch (Exception e) {
String addStr = "";
if (req != null) {
if (req.getBuffer() != null) {
addStr = ByteUtil.dumpAsHexToString(req.getAddress().toString(), req.getBuffer());
if (addStr != null && !"".equalsIgnoreCase(addStr))
addStr = "Buffer:\n" + addStr;
}
}
NeptusLog.pub().error(
"Dispacher Thread: Exception: " + "onUDPMessageNotification "
+ e.getMessage() + addStr, e);
}
catch (Error e) {
NeptusLog.pub().fatal(
"Dispacher Thread: Error: " + "onUDPMessageNotification " + e.getMessage(),
e);
}
}
}
}
catch (InterruptedException e) {
NeptusLog.pub().warn(this + " Thread interrupted");
}
NeptusLog.pub().info(this + " Thread Stopped");
dispacherThread = null;
}
};
listenerThread.setPriority(Thread.MIN_PRIORITY + 1);
listenerThread.setDaemon(true);
listenerThread.start();
dispacherThread = listenerThread;
}
return dispacherThread;
}
/**
* @return
*/
private Thread getSenderThread(final DatagramSocket sockToUseAlreadyOpen) {
Thread senderThread = new Thread(UDPTransport.class.getSimpleName() + ": Sender Thread " + this.hashCode()) {
DatagramSocket sock;
DatagramPacket dgram;
UDPNotification req;
public synchronized void start() {
NeptusLog.pub().debug("Sender Thread Started");
try {
if (sockToUseAlreadyOpen != null)
sock = sockToUseAlreadyOpen;
else
sock = new DatagramSocket();
super.start();
}
catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
try {
while (!(purging && sendmessageList.isEmpty())) {
// req = sendmessageList.take();
req = sendmessageList.poll(1, TimeUnit.SECONDS);
if (req == null)
continue;
try {
dgram = new DatagramPacket(req.getBuffer(), req.getBuffer().length, req.getAddress());
if (req.getAddress().getPort() != 0) {
sock.send(dgram);
informDeliveryListener(req, ResultEnum.Success, null);
}
else
throw new Exception(req.getAddress() + " port is not valid");
}
catch (Exception e) {
NeptusLog.pub().error(e + " :: " + req.getAddress());
// e.printStackTrace();
informDeliveryListener(req, ResultEnum.Error, e);
}
}
}
catch (InterruptedException e) {
NeptusLog.pub().warn(this + " Thread interrupted");
informDeliveryListener(req, ResultEnum.Error, e);
}
NeptusLog.pub().info(this + " Sender Thread Stopped");
senderThreads.remove(this);
}
};
senderThread.setPriority(Thread.MIN_PRIORITY);
senderThread.setDaemon(true);
senderThread.start();
return senderThread;
}
/**
* @param listener
* @return
*/
public boolean addListener(UDPMessageListener listener) {
synchronized (listeners) {
boolean ret = listeners.add(listener);
return ret;
}
}
/**
* @param listener
* @return
*/
public boolean removeListener(UDPMessageListener listener) {
synchronized (listeners) {
boolean ret = listeners.remove(listener);
return ret;
}
}
/**
* Sends a message to the network
*
* @param destination A valid hostname like "whale.fe.up.pt" or "127.0.0.1"
* @param port The destination's port
* @param buffer
* @return true meaning that the message was put on the send queue, and false if it was not put on the send queue.
*/
public boolean sendMessage(String destination, int port, byte[] buffer) {
return sendMessage(destination, port, buffer, null);
}
/**
* Sends a message to the network
*
* @param destination A valid hostname like "whale.fe.up.pt" or "127.0.0.1"
* @param port The destination's port
* @param buffer
* @param deliveryListener
* @return true meaning that the message was put on the send queue, and false if it was not put on the send queue.
*/
public boolean sendMessage(String destination, int port, byte[] buffer, DeliveryListener deliveryListener) {
if (purging) {
String txt = "Not accepting any more messages. IMCMessenger is terminating";
NeptusLog.pub().error(txt);
if (deliveryListener != null)
deliveryListener.deliveryResult(ResultEnum.UnFinished, new IOException(txt));
return false;
}
try {
UDPNotification req = new UDPNotification(UDPNotification.SEND, new InetSocketAddress(
resolveAddress(destination), port), buffer);
req.setDeliveryListener(deliveryListener);
sendmessageList.add(req);
}
catch (UnknownHostException e) {
e.printStackTrace();
if (deliveryListener != null)
deliveryListener.deliveryResult(ResultEnum.Unreacheable, e);
return false;
}
return true;
}
/**
* @param req
* @param e
*/
private void informDeliveryListener(UDPNotification req, ResultEnum result, Exception e) {
if (req != null && req.getDeliveryListener() != null) {
req.getDeliveryListener().deliveryResult(result, e);
}
}
/**
* @param args
* @throws Exception
*/
@SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
// Multicast Test
// UDPTransport udpT = new UDPTransport("224.0.75.69", 6969);
// udpT.addListener(new UDPMessageListener() {
// @Override
// public void onUDPMessageNotification(UDPNotification req) {
// System.err
// .println("Received "
// + req.getBuffer().length
// + " bytes from "
// + req.getAddress()
// + " :: "
// + new String(req.getBuffer(), 0, req
// .getBuffer().length));
// }
// });
//
// while (true) {
// udpT.sendMessage("224.0.75.69", 6969, new String("Ptah is a God!!!").getBytes());
// Thread.sleep(1000);
// }
// //Multicast Test2
// final String multicastAddress = "224.0.75.69";
// String multicastRangePortsStr = "6969-6972";
// final int localport = 6969;
// final int[] multicastPorts = CommUtil
// .parsePortRangeFromString(multicastRangePortsStr);
// class ThreadTest extends Thread {
// String id = "";
// public ThreadTest(String id) {
// super();
// this.id = id;
// }
// @Override
// public void run() {
// UDPTransport multicastUdpTransport;
//
// multicastUdpTransport = new UDPTransport(multicastAddress,
// (multicastPorts.length == 0) ? localport
// : multicastPorts[0]);
// multicastUdpTransport.reStart();
// if (multicastUdpTransport.isOnBindError()) {
// for (int i = 1; i < multicastPorts.length; i++) {
// multicastUdpTransport.stop();
// multicastUdpTransport.setBindPort(multicastPorts[i]);
// multicastUdpTransport.reStart();
// if (!multicastUdpTransport.isOnBindError())
// break;
// }
// }
// multicastUdpTransport.addListener(new UDPMessageListener() {
// @Override
// public void onUDPMessageNotification(UDPNotification req) {
// System.err.println("Received "
// + req.getBuffer().length
// + " bytes from "
// + req.getAddress()
// + " :: "
// + new String(req.getBuffer(), 0, req
// .getBuffer().length));
// }
// });
//
// for (int i = 0; i < 10; i++) {
// for (int port : multicastPorts)
// multicastUdpTransport.sendMessage(multicastAddress,
// port, id.concat(" :: "+
// multicastUdpTransport.getBindPort()).getBytes());
// }
//
// }
// };
//
// UDPTransport uup = new UDPTransport(6969, 1);
//
// ThreadTest tt1 = new ThreadTest("P1");
// ThreadTest tt2 = new ThreadTest("P2");
// tt1.start();
// tt2.start();
// for (int i = 0; i < 10; i++) {
// for (int port : multicastPorts)
// uup.sendMessage(multicastAddress,
// port, "Bind obstructor".concat(" :: "+
// uup.getBindPort()).getBytes());
// }
UDPTransport udpTB1 = new UDPTransport(7969, 1);
final UDPTransport udpTB = new UDPTransport(true, 6001, 1);
udpTB.addListener(new UDPMessageListener() {
@Override
public void onUDPMessageNotification(UDPNotification req) {
System.err.println(udpTB.isBroadcastActive() + " Received " + req.getBuffer().length + " bytes from "
+ req.getAddress() + " :: ");
// + new String(req.getBuffer(), 0, req
// .getBuffer().length));
NeptusLog.pub().info("<###> "+udpTB.receptionMessageList.size());
}
});
// while (true) {
// udpTB1.sendMessage(null, 7901, new String("Ptah is a God!!!").getBytes());
// Thread.sleep(1000);
// }
}
}
| true | true | private Thread getSockedListenerThread() {
if (sockedListenerThread == null) {
Thread listenerThread = new Thread(UDPTransport.class.getSimpleName() + ": Listener Thread "
+ this.hashCode()) {
byte[] sBuffer = new byte[maxBufferSize];
String multicastGroup = "";
public synchronized void start() {
NeptusLog.pub().debug("Listener Thread Started");
try {
boolean useMulticast = isMulticastEnable();
sock = (!useMulticast) ? new DatagramSocket(null) : new MulticastSocket(null);
// if (useMulticast) {
// sock.setReuseAddress(true); // This may be a potential problem when opening two Neptus instances, we don't detect a bind error
// }
sock.setReuseAddress(false);
if (bindPort != 0) {
sock.bind(new InetSocketAddress(bindPort));
}
else {
sock.bind(new InetSocketAddress(0));
}
try {
if (useMulticast) {
((MulticastSocket) sock).joinGroup(resolveAddress(getMulticastAddress()));
multicastGroup = getMulticastAddress();
}
setMulticastActive(useMulticast);
}
catch (Exception e) {
NeptusLog.pub().error(e.getMessage());
setMulticastActive(false);
}
sock.setSoTimeout(timeoutMillis);
if (isBroadcastEnable()) {
try {
sock.setBroadcast(true);
setBroadcastActive(true);
}
catch (Exception e) {
NeptusLog.pub().error(e.getMessage());
setBroadcastActive(false);
}
}
}
catch (Exception e) {
NeptusLog.pub().error(e);
setOnBindError(true);
return;
}
finally {
if (isOnBindError()) {
try {
sock.disconnect();
sock.close();
}
catch (Exception e) {
NeptusLog.pub().error(e.getStackTrace());
}
}
}
super.start();
}
public void run() {
try {
while (!purging) {
DatagramPacket packet = new DatagramPacket(sBuffer, sBuffer.length);
try {
sock.receive(packet);
int lengthReceived = packet.getLength();
try {
byte[] recBytes = Arrays.copyOf(sBuffer, lengthReceived);
UDPNotification info = new UDPNotification(UDPNotification.RECEPTION,
(InetSocketAddress) packet.getSocketAddress(), recBytes,
System.currentTimeMillis());
receptionMessageList.offer(info);
}
catch (Exception e) {
e.printStackTrace();
// FIXME treat better this exception (pdias)
}
}
catch (SocketTimeoutException e) {
// NeptusLog.pub().warn(this + " Thread SocketTimeoutException");
// try { Thread.sleep(1500); } catch (Exception e1) { }
continue;
}
catch (Exception e) {
NeptusLog.pub().error(e);
e.printStackTrace();
// continue;
}
catch (Error e) {
NeptusLog.pub().error(e);
e.printStackTrace();
// continue;
}
// Thread.sleep(1);
// try { Thread.sleep(10); } catch (Exception e) { }
}
}
catch (Exception e) {
NeptusLog.pub().error(e);
// NeptusLog.pub().warn(this+" Thread interrupted");
}
NeptusLog.pub().warn(this + " Thread Stopped");
if (isMulticastActive()) {
try {
// ((MulticastSocket)sock).leaveGroup(((MulticastSocket)sock).getInetAddress());
((MulticastSocket) sock).leaveGroup(resolveAddress(multicastGroup));
}
catch (IOException e) {
e.printStackTrace();
}
}
sock.disconnect();
sock.close();
sock = null;
sockedListenerThread = null;
}
};
listenerThread.setPriority(Thread.MIN_PRIORITY);
listenerThread.setDaemon(true);
listenerThread.start();
sockedListenerThread = listenerThread;
}
return sockedListenerThread;
}
| private Thread getSockedListenerThread() {
if (sockedListenerThread == null) {
Thread listenerThread = new Thread(UDPTransport.class.getSimpleName() + ": Listener Thread "
+ this.hashCode()) {
byte[] sBuffer = new byte[maxBufferSize];
String multicastGroup = "";
public synchronized void start() {
NeptusLog.pub().debug("Listener Thread Started");
try {
boolean useMulticast = isMulticastEnable();
sock = (!useMulticast) ? new DatagramSocket(null) : new MulticastSocket(null);
// if (useMulticast) {
// sock.setReuseAddress(true); // This may be a potential problem when opening two Neptus instances, we don't detect a bind error
// }
sock.setReuseAddress(false);
if (bindPort != 0) {
sock.bind(new InetSocketAddress(bindPort));
}
else {
sock.bind(new InetSocketAddress(0));
}
try {
if (useMulticast) {
((MulticastSocket) sock).joinGroup(resolveAddress(getMulticastAddress()));
multicastGroup = getMulticastAddress();
}
setMulticastActive(useMulticast);
}
catch (Exception e) {
NeptusLog.pub().error("Multicast socket join :: " + e.getMessage());
setMulticastActive(false);
}
sock.setSoTimeout(timeoutMillis);
if (isBroadcastEnable()) {
try {
sock.setBroadcast(true);
setBroadcastActive(true);
}
catch (Exception e) {
NeptusLog.pub().error(e.getMessage());
setBroadcastActive(false);
}
}
}
catch (Exception e) {
NeptusLog.pub().error(e);
setOnBindError(true);
return;
}
finally {
if (isOnBindError()) {
try {
sock.disconnect();
sock.close();
}
catch (Exception e) {
NeptusLog.pub().error(e.getStackTrace());
}
}
}
super.start();
}
public void run() {
try {
while (!purging) {
DatagramPacket packet = new DatagramPacket(sBuffer, sBuffer.length);
try {
sock.receive(packet);
int lengthReceived = packet.getLength();
try {
byte[] recBytes = Arrays.copyOf(sBuffer, lengthReceived);
UDPNotification info = new UDPNotification(UDPNotification.RECEPTION,
(InetSocketAddress) packet.getSocketAddress(), recBytes,
System.currentTimeMillis());
receptionMessageList.offer(info);
}
catch (Exception e) {
e.printStackTrace();
// FIXME treat better this exception (pdias)
}
}
catch (SocketTimeoutException e) {
// NeptusLog.pub().warn(this + " Thread SocketTimeoutException");
// try { Thread.sleep(1500); } catch (Exception e1) { }
continue;
}
catch (Exception e) {
NeptusLog.pub().error(e);
e.printStackTrace();
// continue;
}
catch (Error e) {
NeptusLog.pub().error(e);
e.printStackTrace();
// continue;
}
// Thread.sleep(1);
// try { Thread.sleep(10); } catch (Exception e) { }
}
}
catch (Exception e) {
NeptusLog.pub().error(e);
// NeptusLog.pub().warn(this+" Thread interrupted");
}
NeptusLog.pub().warn(this + " Thread Stopped");
if (isMulticastActive()) {
try {
// ((MulticastSocket)sock).leaveGroup(((MulticastSocket)sock).getInetAddress());
((MulticastSocket) sock).leaveGroup(resolveAddress(multicastGroup));
}
catch (IOException e) {
e.printStackTrace();
}
}
sock.disconnect();
sock.close();
sock = null;
sockedListenerThread = null;
}
};
listenerThread.setPriority(Thread.MIN_PRIORITY);
listenerThread.setDaemon(true);
listenerThread.start();
sockedListenerThread = listenerThread;
}
return sockedListenerThread;
}
|
diff --git a/src/com/gmail/benlynn/spelltap/MainView.java b/src/com/gmail/benlynn/spelltap/MainView.java
index e829891..65cc00a 100644
--- a/src/com/gmail/benlynn/spelltap/MainView.java
+++ b/src/com/gmail/benlynn/spelltap/MainView.java
@@ -1,2186 +1,2188 @@
// TODO: Log, character sheet.
// Turn UI pink on charm, to make it obvious why we need to wait for network?
// Victory/defeat screen with stats.
// Psych spell conflict.
// Resize event.
// Clean up get_ready() nonsense.
// Stop handlers on init.
package com.gmail.benlynn.spelltap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import com.gmail.benlynn.spelltap.SpellTap.Wisdom;
public class MainView extends View {
static Gesture[] gesture;
static String msg;
static float x0, y0, x1, y1;
static Tutorial tut;
static int main_state;
// If 0 or 1, represents left or right spell icon, otherwise represents
// controlled monster.
static int drag_i;
static boolean is_animating;
static BeingPosition being_pos[];
static final int STATE_VOID = -1;
static final int STATE_NORMAL = 0;
// Special states for tutorials.
static final int STATE_GESTURE_ONLY = 1;
static final int STATE_ON_END_ROUND = 2;
static int choice[]; // Gesture choice.
static int lastchoice[];
static History hist, opphist;
static final int ylower = 128 + 144 + 4 * 4;
static final int ystatus = ylower + 32 + 2 * 50 + 16 - 4;
static final int yicon = 64 + 48 + 2 * 4;
static String spell_text[];
static int ready_spell_count[];
static Spell[][] ready_spell;
static Spell[] spell_list;
static int spell_list_count;
static int spell_choice[];
static int spell_target[];
static int being_list_count;
static Being being_list[];
static int winner;
static MonsterAttack monatt[];
static Board board;
static ArrowView arrow_view;
void set_board(Board a) {
board = a;
}
void set_arrow_view(ArrowView a) {
arrow_view = a;
}
void run() { tut.run(); }
void set_state_dummytutorial() {
tut = new DummyTutorial();
}
void set_state_knifetutorial() {
tut = new KnifeTutorial();
}
void set_state_palmtutorial() {
tut = new PalmTutorial();
}
void set_state_win_to_advance(Agent a) {
tut = new WinToAdvance(a);
}
void set_state_practicemode(int hp) {
dummyhp = hp;
tut = new PracticeMode();
}
void set_state_missilelesson() {
tut = new SDTutorial();
}
void set_state_wfplesson() {
tut = new WFPTutorial();
}
void set_state_netduel() {
tut = new NetDuel();
}
static SpellTapMove oppmove;
static class SpellTapMove {
SpellTapMove() {
gest = new int[2];
spell = new int[2];
spell_target = new int[2];
attack_source = new int[16];
attack_target = new int[16];
}
int gest[];
int spell[];
int spell_target[];
int attack_count;
int attack_source[];
int attack_target[];
}
void jack_says(int string_constant) {
spelltap.jack_says(string_constant);
}
void set_main_state(int new_state) {
main_state = new_state;
}
abstract class Tutorial {
abstract void run();
}
void set_gesture_knowledge(int level) {
for (int i = 0; i < 9; i++) {
Gesture g = gesture[i];
if (null != g) g.learned = false;
}
// Exploit fall-through.
switch(level) {
case Wisdom.ALL_GESTURES:
gesture[Gesture.CLAP].learned = true;
case Wisdom.ALL_BUT_C:
gesture[Gesture.FINGERS].learned = true;
case Wisdom.ALL_BUT_FC:
gesture[Gesture.WAVE].learned = true;
case Wisdom.DKPS:
gesture[Gesture.DIGIT].learned = true;
case Wisdom.KPS:
gesture[Gesture.SNAP].learned = true;
case Wisdom.KNIFE_AND_PALM:
gesture[Gesture.PALM].learned = true;
case Wisdom.KNIFE_ONLY:
gesture[Gesture.KNIFE].learned = true;
case Wisdom.NONE:
}
}
void learn(Spell sp) {
sp.learned = true;
}
void set_spell_knowledge(int level) {
for (int i = 0; i < spell_list_count; i++) {
Spell sp = spell_list[i];
sp.learned = false;
}
// Exploits fall-through.
switch(level) {
case Wisdom.ALL_LEVEL_1:
learn(spellAtGesture("WWP"));
case Wisdom.UP_TO_DFW:
learn(spellAtGesture("DFW"));
learn(spellAtGesture("SFW"));
case Wisdom.UP_TO_DSF:
learn(spellAtGesture("DSF"));
case Wisdom.UP_TO_WFP:
learn(spellAtGesture("WFP"));
case Wisdom.UP_TO_MISSILE:
learn(spellAtGesture("SD"));
case Wisdom.STABNSHIELD:
learn(spellAtGesture("P"));
case Wisdom.STAB:
learn(stab_spell);
}
}
// To pass this tutorial, the player merely has to drag their finger up three
// times, starting from the lower part of the screen.
class KnifeTutorial extends Tutorial {
KnifeTutorial() {
state = 0;
count = 0;
}
void run() {
for(;;) switch(state) {
case 0:
clear_choices();
set_gesture_knowledge(Wisdom.KNIFE_ONLY);
set_spell_knowledge(Wisdom.STAB);
board.setVisibility(View.GONE);
arrow_view.setVisibility(View.GONE);
jack_says(R.string.welcome);
state = 100;
return;
case 100:
jack_says(R.string.howtoknife);
state = 1;
return;
case 1:
jack_says(R.string.howtoknife2);
state = 2;
return;
case 2:
clear_choices();
invalidate();
set_main_state(STATE_GESTURE_ONLY);
state = 3;
return;
case 3:
if (choice[0] == Gesture.KNIFE || choice[1] == Gesture.KNIFE) {
count++;
switch(count) {
case 3:
jack_says(R.string.howtoknifepass3);
state = 4;
break;
case 2:
jack_says(R.string.howtoknifepass2);
state = 2;
break;
case 1:
jack_says(R.string.howtoknifepass1);
state = 2;
break;
}
} else {
state = 1;
break;
}
return;
case 4:
set_main_state(STATE_NORMAL);
spelltap.next_state();
spelltap.goto_town();
return;
}
}
int state;
int count;
}
// Defeat a pacifist wooden dummy with 3 hitpoints to pass this one.
// Actually, as long as the battle ends, the player passes. The only way
// to lose is to stab yourself, which requires a player who knows what
// they're doing.
class DummyTutorial extends Tutorial {
DummyTutorial() {
state = 0;
}
void run() {
for(;;) switch(state) {
case 0:
init_opponent(Agent.getDummy());
being_list[1].start_life(3);
reset_game();
jack_says(R.string.dummytut);
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
invalidate();
state = 2;
return;
case 2:
get_ready();
state = 3;
return;
case 3:
switch(winner) {
case 0:
jack_says(R.string.dummytutwin);
tut = new TargetTutorial();
break;
case 1:
jack_says(R.string.dummytutlose);
state = 123;
break;
case 2:
jack_says(R.string.dummytutdraw);
state = 123;
break;
}
return;
case 123:
jack_says(R.string.dummytutskip);
state = 124;
return;
case 124:
spelltap.next_state();
spelltap.goto_town();
return;
}
}
int state;
}
// Now we're talking! Two goblins and a dummy. Since the dummy is the
// default target, the player is must retarget their stabs if they are
// to win.
class TargetTutorial extends Tutorial {
TargetTutorial() {
state = 0;
}
void run() {
for(;;) switch(state) {
case 0:
init_opponent(Agent.getDummy());
being_list[1].start_life(3);
reset_game();
// Two goblins.
being_list[2] = new Being("Porsap", R.drawable.goblin, 1);
being_list[2].start_life(1);
being_list[2].target = 0;
being_list[3] = new Being("Dedmeet", R.drawable.goblin, 1);
being_list[3].start_life(1);
being_list[3].target = 0;
being_list_count = 4;
jack_says(R.string.targettut);
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
state = 1;
invalidate();
return;
case 1:
set_main_state(STATE_NORMAL);
get_ready();
state = 2;
return;
case 2:
switch(winner) {
case 0:
jack_says(R.string.targettutwin);
state = 3;
break;
case 1:
jack_says(R.string.targettutlose);
state = 0;
break;
case 2:
jack_says(R.string.targettutlose);
state = 0;
break;
}
reset_being_pos();
return;
case 3:
spelltap.next_state();
spelltap.goto_town();
return;
}
}
int state;
}
// The Palm version of the Knife tutorial
// times, starting from the lower part of the screen.
class PalmTutorial extends Tutorial {
PalmTutorial() {
state = 0;
count = 0;
}
void run() {
for(;;) switch(state) {
case 0:
set_gesture_knowledge(Wisdom.KNIFE_AND_PALM);
reset_game();
board.setVisibility(View.GONE);
arrow_view.setVisibility(View.GONE);
jack_says(R.string.palmtut);
state = 100;
return;
case 100:
jack_says(R.string.palmtut1);
state = 1;
return;
case 1:
clear_choices();
set_main_state(STATE_GESTURE_ONLY);
invalidate();
state = 2;
return;
case 2:
if (choice[0] == Gesture.PALM || choice[1] == Gesture.PALM) {
count++;
switch(count) {
case 3:
jack_says(R.string.palmtutpass3);
state = 3;
break;
case 2:
jack_says(R.string.palmtutpass2);
state = 1;
break;
case 1:
jack_says(R.string.palmtutpass1);
state = 1;
break;
}
} else {
state = 100;
break;
}
return;
case 3:
jack_says(R.string.palmtutpass4);
state = 4;
return;
case 4:
jack_says(R.string.palmtutpass5);
state = 5;
return;
case 5:
set_main_state(STATE_NORMAL);
spelltap.next_state();
spelltap.goto_town();
return;
}
}
int state;
int count;
}
static int dummyhp;
// Practice Mode. A defenceless dummy.
class PracticeMode extends Tutorial {
PracticeMode() {
state = 0;
}
void run() {
for(;;) switch(state) {
case 0:
init_opponent(Agent.getDummy());
being_list[1].start_life(dummyhp);
reset_game();
state = 1;
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
get_ready();
invalidate();
return;
case 1:
state = 0;
spelltap.goto_town();
return;
}
}
int state;
}
// Beat given opponent to advance main game state.
class WinToAdvance extends Tutorial {
WinToAdvance(Agent a) {
state = 0;
agent = a;
}
void run() {
for(;;) switch(state) {
case 0:
init_opponent(agent);
reset_game();
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
get_ready();
invalidate();
state = 1;
return;
case 1:
if (winner == 0) spelltap.next_state();
spelltap.goto_town();
return;
}
}
int state;
Agent agent;
}
// Introduce SD.
class SDTutorial extends Tutorial {
SDTutorial() {
state = -1;
hand = 0;
}
void run() {
for(;;) switch(state) {
case -1:
set_gesture_knowledge(Wisdom.KPS);
init_opponent(Agent.getDummy());
reset_game();
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
jack_says(R.string.SDtut0);
state = 0;
return;
case 0:
// Restore life in case player has been messing around.
being_list[0].start_life(5);
being_list[1].start_life(5);
hist.reset();
opphist.reset();
jack_says(R.string.SDtut);
state = 1;
return;
case 1:
clear_choices();
get_ready();
set_main_state(STATE_ON_END_ROUND);
state = 2;
invalidate();
return;
case 2:
if (hist.gest[0][0] == Gesture.SNAP &&
hist.gest[0][1] == Gesture.SNAP) {
jack_says(R.string.SDtutpass1);
set_spell_knowledge(Wisdom.UP_TO_MISSILE);
state = 3;
} else {
jack_says(R.string.SDtutwrong);
state = 0;
}
return;
case 3:
set_gesture_knowledge(Wisdom.DKPS);
get_ready();
state = 4;
invalidate();
return;
case 4:
if (hist.gest[1][0] == Gesture.DIGIT &&
hist.gest[1][1] == Gesture.DIGIT) {
jack_says(R.string.SDtutpass2);
state = 5;
} else {
jack_says(R.string.SDtutwrong);
state = 0;
}
return;
case 5:
jack_says(R.string.SDtutpass3);
state = 6;
return;
case 6:
jack_says(R.string.SDtutpass4);
state = 7;
return;
case 7:
set_main_state(STATE_NORMAL);
get_ready();
state = 8;
return;
case 8:
spelltap.next_state();
spelltap.goto_town();
return;
}
}
int hand;
int state;
}
// Introduces WFP.
class WFPTutorial extends Tutorial {
WFPTutorial() {
state = 0;
hand = 0;
}
void run() {
for(;;) switch(state) {
case 0:
set_gesture_knowledge(Wisdom.ALL_BUT_FC);
init_opponent(Agent.getDummy());
being_list[1].start_life(4);
reset_game();
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
jack_says(R.string.wavetut);
state = 1;
return;
case 1:
clear_choices();
get_ready();
set_main_state(STATE_ON_END_ROUND);
state = 2;
invalidate();
return;
case 2:
if (hist.gest[0][0] == Gesture.WAVE &&
hist.gest[0][1] == Gesture.WAVE) {
jack_says(R.string.fingerstut);
state = 3;
} else {
jack_says(R.string.fingerstutfail);
state = 0;
}
return;
case 3:
set_gesture_knowledge(Wisdom.ALL_BUT_C);
get_ready();
state = 4;
invalidate();
return;
case 4:
if (hist.gest[1][0] == Gesture.FINGERS &&
hist.gest[1][1] == Gesture.FINGERS) {
jack_says(R.string.fingerstutpass1);
set_spell_knowledge(Wisdom.UP_TO_WFP);
state = 5;
} else {
jack_says(R.string.fingerstutfail);
state = 0;
}
return;
case 5:
get_ready();
invalidate();
state = 6;
return;
case 6:
if (hist.gest[2][0] == Gesture.PALM &&
hist.gest[2][1] == Gesture.PALM && 0 == winner) {
jack_says(R.string.fingerstutpass2);
state = 7;
} else {
jack_says(R.string.fingerstutfail);
state = 0;
}
return;
case 7:
jack_says(R.string.fingerstutpass3);
state = 8;
return;
case 8:
spelltap.next_state();
spelltap.goto_town();
return;
}
}
int hand;
int state;
}
static int indexOfSpell(String name) {
for(int i = 0; i < spell_list_count; i++) {
if (name == spell_list[i].name) return i;
}
return -1;
}
static int indexOfSpellGesture(String gesture) {
for(int i = 0; i < spell_list_count; i++) {
if (gesture == spell_list[i].gesture) return i;
}
return -1;
}
static Spell spellAtName(String name) {
for(int i = 0; i < spell_list_count; i++) {
if (name == spell_list[i].name) return spell_list[i];
}
return null;
}
static Spell spellAtGesture(String combo) {
for(int i = 0; i < spell_list_count; i++) {
if (combo == spell_list[i].gesture) return spell_list[i];
}
return null;
}
private char encode_target(int target) {
if (target <= 1) { // Player, opponent or thin air.
return (char) ('A' + target);
} else {
return (char) ('A' + 2 + being_list[target].id);
}
}
private int decode_target(char c) {
int raw = c - 'A';
if (-1 == raw) return -1;
if (0 == raw || 1 == raw) return 1 - raw;
raw -= 2;
if (0 == (raw & 1)) raw++;
else raw--;
for (int i = 2; i < being_list_count; i++) {
if (raw == being_list[i].id) return i;
}
return -1;
}
void net_move(SpellTapMove turn) {
String s = "";
// Encode gestures.
s += (char) (choice[0] + '0');
s += (char) (choice[1] + '0');
// Encode spells and targets.
for (int h = 0; h < 2; h++) {
if (-1 != spell_choice[h]) {
s += (char) (ready_spell[spell_choice[h]][h].index + 'A');
s += encode_target(spell_target[h]);
} else {
s += (char) ('A' - 1);
s += (char) ('A' - 1);
}
}
// Encode monster attacks.
String s2 = "";
int count = 0;
for (int i = 2; i < being_list_count; i++) {
Being b = being_list[i];
if (0 == b.controller) {
s2 += encode_target(i);
s2 += encode_target(b.target);
count++;
}
}
s += (char) ('0' + count);
s += s2;
opp_ready = false;
print("Waiting for opponent...");
invalidate();
// Spawn a thread to send move over the network, so we can keep handling
// user input.
net_state = NET_DECODE;
Tubes.send_move(s);
}
static int net_state;
static final int NET_DECODE = 0;
static final int NET_CHARM_CHOSEN = 1;
static final int NET_GET_CHARM_HAND = 2;
static final int NET_GET_CHARM_GESTURE = 3;
void net_set_charm(int hand, int gesture) {
opp_ready = false;
print("Informing server...");
invalidate();
net_state = NET_CHARM_CHOSEN;
Tubes.send_set_charm(hand, gesture);
}
int net_get_charm_hand() {
opp_ready = false;
print("Waiting for opponent to choose charmed hand...");
invalidate();
net_state = NET_GET_CHARM_HAND;
Tubes.send_get_charm_hand();
return -1;
}
int net_get_charm_gesture() {
opp_ready = false;
print("Waiting for server...");
invalidate();
net_state = NET_GET_CHARM_GESTURE;
Tubes.send_get_charm_gesture();
return -1;
}
static NetHandler net_handler;
class NetHandler extends Handler {
@Override
public void handleMessage(Message msg) {
// Valid reply received from network.
try {
Tubes.net_thread.join();
} catch (InterruptedException e) {
}
Log.i("Reply", Tubes.reply);
switch(net_state) {
case NET_DECODE:
decode_move(oppmove, Tubes.reply);
break;
case NET_CHARM_CHOSEN:
opp_ready = true;
is_waiting = false;
note_charm_chosen();
break;
case NET_GET_CHARM_HAND:
switch(Tubes.reply.charAt(0)) {
case '0':
charmed_hand = 0;
break;
case '1':
charmed_hand = 1;
break;
}
if (-1 == charmed_hand) {
Log.e("TODO", "Handle bad messages");
}
opp_ready = true;
is_waiting = false;
new_round_post_charm();
break;
case NET_GET_CHARM_GESTURE:
{
int g = Tubes.reply.charAt(0) - '0';
if (g >= 0 && g <= 8 && g != Gesture.NONE && gesture[g] != null) {
choice[charmed_hand] = g;
} else {
Log.e("TODO", "Handle bad messages");
break;
}
opp_ready = true;
is_waiting = false;
apply_charm();
break;
}
}
}
}
void decode_move(SpellTapMove turn, String r) {
if (null == r || r.length() < 7) {
// TODO: Do something for invalid messages!
return;
}
// TODO: Check message is valid!
// Decode gestures, spells and spell targets.
for (int h = 0; h < 2; h++) {
turn.gest[h] = r.charAt(h) - '0';
turn.spell[h] = r.charAt(2 + 2 * h) - 'A';
turn.spell_target[h] = decode_target(r.charAt(3 + 2 * h));
}
// Decode monster attacks.
turn.attack_count = r.charAt(6) - '0';
for (int n = 0; n < turn.attack_count; n++) {
turn.attack_source[n] = decode_target(r.charAt(7 + 2 * n));
turn.attack_target[n] = decode_target(r.charAt(7 + 2 * n + 1));
}
opp_ready = true;
is_waiting = false;
resolve();
}
class NetAgent extends Agent {
String name() { return "Opponent"; }
String name_full() { return "Opponent"; }
int life() { return 5; }
int bitmap_id() { return R.drawable.wiz; }
void move(SpellTapMove turn) {
net_move(turn);
}
void set_charm(int hand, int gesture) {
net_set_charm(hand, gesture);
}
int get_charm_hand() {
return net_get_charm_hand();
}
int get_charm_gesture() {
return net_get_charm_gesture();
}
}
class NetDuel extends Tutorial {
NetDuel() {
state = 0;
}
void run() {
for(;;) switch(state) {
case 0:
if (0 != Tubes.newgame()) {
main_state = STATE_VOID;
board.setVisibility(View.GONE);
arrow_view.setVisibility(View.GONE);
spelltap.narrate(R.string.servererror);
state = 1;
return;
}
init_opponent(new NetAgent());
reset_game();
board.setVisibility(View.VISIBLE);
arrow_view.setVisibility(View.VISIBLE);
state = 1;
get_ready();
invalidate();
return;
case 1:
spelltap.goto_town();
state = 0;
return;
}
}
int state;
}
void clear_choices() {
choice[1] = choice[0] = Gesture.NONE;
lastchoice[0] = lastchoice[1] = choice[0];
ready_spell_count[0] = ready_spell_count[1] = 0;
spell_choice[0] = spell_choice[1] = -1;
spell_text[0] = spell_text[1] = "";
arrow_view.bmspell[0] = arrow_view.bmspell[1] = null;
}
class History {
History() {
gest = new int[128][2];
start = new int[2];
reset();
}
void reset() {
cur = 0;
start[0] = start[1] = 0;
}
boolean is_doubleP() {
if (cur == 0) Log.e("History", "is_doubleP called with no history");
return gest[cur - 1][0] == Gesture.PALM && gest[cur - 1][1] == Gesture.PALM;
}
void add(int g[]) {
gest[cur][0] = g[0];
gest[cur][1] = g[1];
// Stabs and null gestures break combos.
if (cur > 0) {
if (gest[cur - 1][0] == Gesture.KNIFE) start[0] = cur;
if (gest[cur - 1][1] == Gesture.KNIFE) start[1] = cur;
}
if (g[0] == Gesture.KNIFE) start[0] = cur;
if (g[1] == Gesture.KNIFE) start[1] = cur;
cur++;
if (g[0] == Gesture.NONE) start[0] = cur;
if (g[1] == Gesture.NONE) start[1] = cur;
// No spell needs more than 7 turns.
if (cur > start[0] + 6) start[0]++;
if (cur > start[1] + 6) start[1]++;
}
int[][] gest;
int cur;
int[] start;
}
private void put_gest(String s, int x, int y) {
int n = Gesture.flattenxy(x, y);
Gesture g = gesture[n] = new Gesture(s, x, y);;
g.name = s;
g.x = x;
g.y = y;
}
void init_opponent(Agent a) {
being_list[1] = new Being(a.name(), a.bitmap_id(), -2);
being_list[1].start_life(a.life());
agent = a;
}
// Constructor.
public MainView(Context context, AttributeSet attrs) {
super(context, attrs);
con = context;
drag_i = -1;
is_animating = false;
choice = new int[2];
lastchoice = new int[2];
hist = new History();
opphist = new History();
ready_spell_count = new int[2];
ready_spell = new Spell[4][2];
spell_choice = new int[2];
spell_choice[0] = spell_choice[1] = 0;
spell_text = new String[2];
spell_text[0] = spell_text[1] = "";
spell_list = new Spell[64];
spell_list_count = 0;
stab_spell = new StabSpell();
add_spell(stab_spell, 65);
add_spell(new ShieldSpell(), 8);
add_spell(new MissileSpell(), 64);
add_spell(new CauseLightWoundsSpell(), 63);
add_spell(new ConfusionSpell(), 28);
add_spell(new CureLightWoundsSpell(), 128);
add_spell(new SummonGoblinSpell(), 17);
add_spell(new ProtectionSpell(), 7);
add_spell(new CharmPersonSpell(), 31);
being_list = new Being[16];
summon_count = new int[2];
summon_count[0] = summon_count[1] = 0;
init_being_pos();
being_list[0] = new Being("Player", R.drawable.wiz, -1);
being_list[0].start_life(5);
init_opponent(Agent.getDummy());
being_list[1].start_life(3);
being_list_count = 2;
spell_target = new int[2];
exec_queue = new SpellCast[16];
monatt = new MonsterAttack[5];
for (int i = 1; i <= 4; i++) {
monatt[i] = new MonsterAttack(i);
}
msg = "";
bmcorpse = BitmapFactory.decodeResource(getResources(), R.drawable.corpse);
oppmove = new SpellTapMove();
gesture = new Gesture[9];
put_gest("Snap", -1, -1);
put_gest("Knife", 0, -1);
put_gest("Digit", 1, -1);
put_gest("Clap", 1, 0);
put_gest("Wave", -1, 1);
put_gest("Palm", 0, 1);
put_gest("Fingers", 1, 1);
arrow_view = null;
tilt_state = TILT_AWAIT_UP;
charmed_hand = -1;
freeze_gesture = false;
choosing_charm = false;
net_handler = new NetHandler();
}
static String emptyleftmsg;
static String emptyrightmsg;
public void get_ready() {
print("Draw gestures, and tap here to confirm.");
}
public void add_spell(Spell sp, int priority) {
spell_list[spell_list_count] = sp;
sp.index = spell_list_count;
sp.priority = priority;
spell_list_count++;
}
static StabSpell stab_spell;
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x, y;
// Board class handles avatars and status line.
// Opponent history.
y = 16 - 4;
String s = "";
for (int i = opphist.start[0]; i < opphist.cur; i++) {
s += " " + gesture[opphist.gest[i][0]].abbr;
}
canvas.drawText(s, 0, y, Easel.grey_text);
s = "";
for (int i = opphist.start[1]; i < opphist.cur; i++) {
s += " " + gesture[opphist.gest[i][1]].abbr;
}
canvas.drawText(s, 320, y, Easel.grey_rtext);
// Player history.
y = ylower - 4;
s = "";
for (int i = hist.start[0]; i < hist.cur; i++) {
s += " " + gesture[hist.gest[i][0]].abbr;
}
canvas.drawText(s, 0, y, Easel.grey_text);
s = "";
for (int i = hist.start[1]; i < hist.cur; i++) {
s += " " + gesture[hist.gest[i][1]].abbr;
}
canvas.drawText(s, 320, y, Easel.grey_rtext);
// Gesture area.
y = ylower;
canvas.drawRect(0, y, 320, 480, Easel.octarine);
// Status line highlight.
canvas.drawRect(0, ystatus, 320, 480, Easel.status_paint);
// Gesture and spell text.
// TODO: Rethink Charm presentation.
y = ylower + 16 - 4;
if (0 == charmed_hand) {
if (freeze_gesture) {
Gesture g = gesture[choice[0]];
canvas.drawText(g.statusname, 0, y, Easel.charm_text);
} else {
canvas.drawText("[Charmed]", 0, y, Easel.charm_text);
}
} else {
Gesture g = gesture[choice[0]];
if (null == g) {
canvas.drawText(emptyleftmsg, 0, y, Easel.grey_text);
} else {
canvas.drawText(g.statusname, 0, y, Easel.white_text);
}
}
if (1 == charmed_hand) {
if (freeze_gesture) {
Gesture g = gesture[choice[1]];
canvas.drawText(g.statusname, 320, y, Easel.charm_rtext);
} else {
canvas.drawText("[Charmed]", 320, y, Easel.charm_rtext);
}
} else {
Gesture g = gesture[choice[1]];
if (null == g) {
canvas.drawText(emptyrightmsg, 320, y, Easel.grey_rtext);
} else {
canvas.drawText(g.statusname, 320, y, Easel.white_rtext);
}
}
canvas.drawText(spell_text[0], 0, y + 16, Easel.white_text);
canvas.drawText(spell_text[1], 320, y + 16, Easel.white_rtext);
// Spell choice row 1
x = 0;
y = ylower + 32;
for (int h = 0; h < 2; h++) {
for (int i = 0; i < ready_spell_count[h]; i++) {
if (i == spell_choice[h]) {
canvas.drawRect(x, y, x + 50, y + 50, Easel.sel_paint);
}
canvas.drawBitmap(ready_spell[i][h].bitmap, x + 1, y + 1, Easel.paint);
if (h == 0) x += 50;
else x -= 50;
}
x = 320 - 50;
}
// Spell choice row 2
/*
y += 50;
canvas.drawRect(0, y, 50 - 1, y + 50 - 1, Easel.paint);
*/
}
static boolean okstate;
private void choose_spell(int h, int i) {
// Assumes i is a valid choice for hand h.
if (i == spell_choice[h]) return;
spell_choice[h] = i;
spell_target[h] = ready_spell[i][h].target;
if (-1 != spell_choice[h]) {
Spell sp = ready_spell[spell_choice[h]][h];
arrow_view.bmspell[h] = sp.bitmap;
spell_text[h] = sp.name;
} else {
arrow_view.bmspell[h] = null;
}
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (is_animating) return false;
if (is_waiting) return false;
x0 = event.getX();
y0 = event.getY();
if (y0 < ylower) {
if (STATE_GESTURE_ONLY == main_state) {
run();
return false;
}
// Check for spell retargeting drag.
if (y0 >= yicon - SLOP && y0 < yicon + 48 + SLOP) {
if (x0 < 48 + SLOP) {
drag_i = 0;
} else if (x0 >= 320 - 48 - SLOP) {
drag_i = 1;
}
} else {
// Check for monster retargeting drag.
for (int i = 2; i < being_list_count; i++) {
Being b = being_list[i];
// It might not matter if you can retarget a corpse's
// attack, but it doesn't seem useful.
if (b.dead || 0 != b.controller) continue;
if (b.contains(x0, y0)) {
drag_i = i;
break;
}
}
}
if (-1 != drag_i) {
print("Drag to target.");
// TODO: Only invalidate status bar.
invalidate();
return true;
}
return false;
}
okstate = y0 >= ystatus;
return true;
case MotionEvent.ACTION_UP:
if (is_animating) return false;
if (is_waiting) return false;
x1 = event.getX();
y1 = event.getY();
if (drag_i != -1) {
get_ready();
int target;
for(target = being_list_count - 1; target >= 0; target--) {
Being b = being_list[target];
if (b.contains(x1, y1)) break;
}
// drag_i = 0, 1 means player is targeting spell.
if (drag_i <= 1) {
if (target == -1) {
// Doesn't count if still in spell icon.
- if (y0 >= yicon && y0 < yicon + 48) {
- if (x0 < 48) {
+ if (y1 >= yicon - SLOP && y1 < yicon + 48 + SLOP) {
+ if (x1 < 48 + SLOP) {
// In the future I plan to add a meaning for dragging
// one spell icon to the other.
- } else if (x0 >= 320 - 48) {
+ } else if (x1 >= 320 - 48 - SLOP) {
} else {
spell_target[drag_i] = -1;
}
+ } else {
+ spell_target[drag_i] = -1;
}
} else {
spell_target[drag_i] = target;
}
} else {
Being b = being_list[drag_i];
if (Status.OK == b.status) {
b.target = target;
}
}
drag_i = -1;
invalidate();
return true;
}
float dx = x1 - x0;
float dy = y1 - y0;
if (dx * dx + dy * dy < 32 * 32) {
if (STATE_GESTURE_ONLY == main_state) {
run();
return true;
}
if (okstate && y1 >= ystatus) {
confirm_move();
return true;
}
if (y1 >= ylower + 32 && y1 < ylower + 32 + 50) {
// Could be choosing a ready spell.
for (int h = 0; h < 2; h++) {
int i;
if (h == 1) {
if (x1 < 160) break;
i = (320 - (int) x1) / 50;
} else {
i = ((int) x1) / 50;
}
if (i >= 0 && i < ready_spell_count[h]) {
choose_spell(h, i);
return true;
}
}
}
} else {
int dirx, diry;
int h;
dirx = dx > 0 ? 1 : -1;
diry = dy > 0 ? 1 : -1;
if (Math.abs(dy) > Math.abs(dx) * 2) {
dirx = 0;
} else if (Math.abs(dx) > Math.abs(dy) * 2) {
diry = 0;
}
if (x0 < 160) {
h = 0;
} else {
h = 1;
dirx *= -1;
}
if (h == charmed_hand || freeze_gesture) {
return true;
}
choice[h] = Gesture.flattenxy(dirx, diry);
if (null == gesture[choice[h]] || !gesture[choice[h]].learned) {
choice[h] = Gesture.NONE;
}
if (choice[h] != lastchoice[h]) {
handle_new_choice(h);
}
if (STATE_GESTURE_ONLY == main_state) run();
return true;
}
}
return false;
}
static int tilt_state;
void tilt_up() {
if (TILT_AWAIT_UP != tilt_state) return;
if (STATE_NORMAL != main_state) return;
// Tilt only works when there are gestures in both hands not counting
// charmed hands, or when the player has chosen a gesture for the opponent.
if ((choice[0] != Gesture.NONE && choice[1] != Gesture.NONE) ||
(-1 != charmed_hand && choice[1 - charmed_hand] != Gesture.NONE) ||
(choosing_charm && (choice[0] != Gesture.NONE || choice[1] != Gesture.NONE))) {
tilt_state = TILT_AWAIT_DOWN;
board.set_notify_me(tilt_done_handler);
board.animate_tilt();
}
}
void tilt_down() {
if (TILT_AWAIT_DOWN != tilt_state) return;
confirm_move();
}
private TiltDoneHandler tilt_done_handler = new TiltDoneHandler();
class TiltDoneHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (TILT_DISABLED != tilt_state) tilt_state = TILT_AWAIT_UP;
}
}
class SpellCast {
SpellCast(Spell init_spell, int init_source, int init_target) {
spell = init_spell;
source = init_source;
target = init_target;
}
Spell spell;
int target;
int source;
}
static int exec_queue_count;
static SpellCast[] exec_queue;
// TODO: Move to Agent class. Also, introduce charm_hand and charm_gesture
// variables there, so network code in this class can avoid touching
// charmed_hand and choice[].
static boolean opp_ready;
private void confirm_move() {
tilt_state = TILT_DISABLED;
board.animation_reset(); // Stop tilt animation if it's still going.
// If Charm Person has been cast on opponent, must first send
// chosen gesture before normal turn.
if (choosing_charm) {
tilt_state = TILT_AWAIT_UP;
int h;
for (h = 0; h < 2 && Gesture.NONE == choice[h]; h++);
if (h < 2) {
opp_ready = true;
agent.set_charm(h, choice[h]);
if (opp_ready) {
note_charm_chosen();
} else {
// In network games, network code eventually calls
// note_charm_chosen().
is_waiting = true;
}
}
return;
}
if (-1 != charmed_hand) {
if (!freeze_gesture) {
tilt_state = TILT_AWAIT_UP;
opp_ready = true;
choice[charmed_hand] = agent.get_charm_gesture();
if (opp_ready) {
apply_charm();
} else {
is_waiting = true;
// Network code calls apply_charm().
}
return;
}
freeze_gesture = false;
}
get_opp_moves();
}
void apply_charm() {
handle_new_choice(charmed_hand);
freeze_gesture = true;
print("Charm takes effect. Confirm spells and targets.");
}
void get_opp_moves() {
arrow_view.setVisibility(View.GONE);
hist.add(choice);
opp_ready = true;
agent.move(oppmove);
// In local duels, opp_ready should still be true.
if (opp_ready) {
resolve();
return;
}
// Otherwise we wait for network code to call resolve().
is_waiting = true;
}
void note_charm_chosen() {
choosing_charm = false;
clear_choices();
get_ready();
invalidate();
new_round2();
}
static boolean is_waiting;
// Insert spells by priority.
private void insert_spell(SpellCast sc) {
int i;
for (i = 0; i < exec_queue_count; i++) {
if (exec_queue[i].spell.priority > sc.spell.priority) break;
}
for (int j = exec_queue_count; j > i; j--) {
exec_queue[j] = exec_queue[j - 1];
}
exec_queue[i] = sc;
exec_queue_count++;
}
private void resolve() {
is_animating = true;
opphist.add(oppmove.gest);
// Expire status effects.
for (int i = 0; i < being_list_count; i++) {
Being b = being_list[i];
b.status = Status.OK;
}
exec_queue_count = 0;
// Insert player spells and targets into execution queue.
for (int h = 0; h < 2; h++) {
if (-1 == spell_choice[h]) continue;
SpellCast sc = new SpellCast(
ready_spell[spell_choice[h]][h], 0, spell_target[h]);
insert_spell(sc);
}
// Insert opponent spells and targets.
for (int h = 0; h < 2; h++) {
if (-1 == oppmove.spell[h]) continue;
Spell sp = spell_list[oppmove.spell[h]];
SpellCast sc = new SpellCast(sp, 1, oppmove.spell_target[h]);
insert_spell(sc);
}
// Retarget monsters controlled by oppponent.
for (int i = 0; i < oppmove.attack_count; i++) {
Being b = being_list[oppmove.attack_source[i]];
b.target = oppmove.attack_target[i];
}
// Insert monster attacks.
for (int i = 2; i < being_list_count; i++) {
Being b = being_list[i];
if (b.dead) continue;
if (-1 != b.target) {
SpellCast sc = new SpellCast(monatt[b.life_max], i, b.target);
insert_spell(sc);
}
}
clear_choices();
exec_cursor = 0;
// TODO: Print message and delay if there are no spells.
// Or maybe flash the screen and make a sound unconditionally to get
// attention; in multiplayer, there can be a delay while waiting for
// opponent.
next_spell();
}
public void print(String s) {
msg = s;
}
static int exec_cursor;
public void next_spell() {
if (exec_cursor < exec_queue_count) {
SpellCast sc = exec_queue[exec_cursor];
String s = "";
String srcname = being_list[sc.source].name;
String tgtname = null;
if (sc.target != -1) {
tgtname = being_list[sc.target].name;
}
if (sc.source >= 2) {
s += srcname + " attacks ";
} else if (sc.spell == stab_spell) {
if (0 == sc.source) {
s += "You stab ";
} else {
s += srcname + " stabs ";
}
} else {
if (0 == sc.source) {
s += "You cast ";
} else {
s += srcname + " casts ";
}
s += sc.spell.name + " on ";
}
if (0 == sc.target) {
if (0 == sc.source) {
s += "yourself.";
} else {
s += "you.";
}
} else if (-1 == sc.target) {
s += "thin air!";
} else {
s += tgtname + ".";
}
print(s);
Log.i("MV", s);
sc.spell.execute(sc.source, sc.target);
exec_cursor++;
} else {
end_round();
}
}
// End of round. Check for death, shield expiration, etc.
void end_round() {
boolean gameover = false;
for(int i = being_list_count - 1; i >= 0; i--) {
Being b = being_list[i];
if (b.shield > 0) b.shield--;
// TODO: Shield off animation.
if (b.life <= 0) {
if (i >= 2) b.bitmap = bmcorpse;
b.die();
}
}
is_animating = false;
tilt_state = TILT_AWAIT_UP;
arrow_view.setVisibility(View.VISIBLE);
int sid = R.string.bug;
winner = -1;
if (being_list[1].dead) {
gameover = true;
winner = 0;
sid = R.string.win;
if (being_list[0].dead) {
winner = 2;
sid = R.string.draw;
}
} else if (being_list[0].dead) {
winner = 1;
gameover = true;
sid = R.string.lose;
}
if (!gameover) {
if (hist.is_doubleP()) {
if (opphist.is_doubleP()) {
winner = 2;
gameover = true;
sid = R.string.surrenderdraw;
} else {
winner = 1;
gameover = true;
sid = R.string.surrenderlose;
}
} else if (opphist.is_doubleP()) {
winner = 0;
gameover = true;
sid = R.string.surrenderwin;
}
}
invalidate();
if (gameover) {
print("");
spelltap.narrate(sid);
// run() is called once the player has tapped through the
// victory screen.
} else if (STATE_ON_END_ROUND == main_state) {
run();
} else {
new_round();
}
}
boolean player_charmed() {
return Status.CHARMED == being_list[0].status;
}
boolean opp_charmed() {
return Status.CHARMED == being_list[1].status;
}
// Start new round.
void new_round() {
// Thus begins the Charm Person spaghetti. The most complex case is
// when Charm Person has simultaneously been cast on both players. Then:
// 1. I pick a hand and gesture for my opponent.
// 2. I ask which hand of mine was chosen by my opponent.
// 3. I choose a gesture with my other hand.
// 4. I ask which gesture the opponent chose for my charmed hand.
// 5. I choose spells and targets from the results.
// Non-blocking network communication complicates the code further.
if (opp_charmed()) {
choosing_charm = true;
print("Charm: Pick gesture for opponent.");
return;
}
new_round2();
}
void reset_game() {
clear_choices();
hist.reset();
opphist.reset();
being_list_count = 2;
being_list[0].status = Status.OK;
being_list[1].status = Status.OK;
being_list[0].shield = 0;
being_list[1].shield = 0;
being_list[0].heal_full();
being_list[1].heal_full();
set_main_state(STATE_NORMAL);
is_waiting = false;
}
void new_round2() {
// Handle charm on player.
if (player_charmed()) {
// Get charmed hand from opponent.
opp_ready = true;
charmed_hand = agent.get_charm_hand();
if (!opp_ready) {
// Network game. Handler will call new_round_post_charm once
// a valid reply is received.
is_waiting = true;
return;
}
} else {
charmed_hand = -1;
}
new_round_post_charm();
}
void new_round_post_charm() {
// Handle confused monsters.
for (int i = 2; i < being_list_count; i++) {
Being b = being_list[i];
if (Status.CONFUSED == b.status) {
b.target = b.controller;
}
}
get_ready();
invalidate();
}
private void handle_new_choice(int h) {
if (choosing_charm) {
if (Gesture.NONE != choice[h]) {
choice[1 - h] = Gesture.NONE;
}
invalidate();
return;
}
spell_search(h);
if (Status.CONFUSED == being_list[0].status) {
if (choice[1 - h] != choice[h]) {
choice[1 - h] = choice[h];
spell_search(1 - h);
}
}
invalidate();
}
private void spell_search(int h) {
ready_spell_count[h] = 0;
spell_choice[h] = -1;
if (choice[h] == Gesture.KNIFE) {
if (choice[1 - h] == Gesture.KNIFE) {
spell_text[h] = "(only one knife)";
return;
} else {
add_ready_spell(h, stab_spell);
spell_text[h] = "";
}
} else {
if (lastchoice[h] == Gesture.KNIFE && choice[1 - h] == Gesture.KNIFE) {
ready_spell_count[1 - h] = 0;
add_ready_spell(1 - h, stab_spell);
choose_spell(1 - h, 0);
}
spell_text[h] = "";
if (choice[h] != Gesture.NONE) {
for (int i = 0; i < spell_list_count; i++) {
String g = spell_list[i].gesture;
int k = g.length();
if (k > hist.cur - hist.start[h] + 1) continue;
k--;
if (g.charAt(k) != gesture[choice[h]].abbr) continue;
k--;
int k2 = hist.cur - 1;
while (k >= 0) {
if (g.charAt(k) != gesture[hist.gest[k2][h]].abbr) {
break;
}
k2--;
k--;
}
if (0 > k) {
// At last we have a match.
add_ready_spell(h, spell_list[i]);
}
}
}
}
if (ready_spell_count[h] > 0) {
choose_spell(h, ready_spell_count[h] - 1);
} else {
arrow_view.bmspell[h] = null;
}
lastchoice[0] = choice[0];
lastchoice[1] = choice[1];
}
public void add_ready_spell(int h, Spell sp) {
ready_spell[ready_spell_count[h]][h] = sp;
ready_spell_count[h]++;
}
static Context con; // Need this for styling strings.
abstract public class Spell {
public void init(String init_name, String init_gest, int bitmapid,
int descid, int def_target) {
name = init_name;
description = descid;
gesture = init_gest;
purty = new SpannableString(gesture + " " + name + ": " + con.getText(description) + "\n");
int n = gesture.length();
purty.setSpan(new StyleSpan(Typeface.BOLD), 0, n, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
purty.setSpan(new StyleSpan(Typeface.ITALIC), n + 1, n + name.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
bitmap = BitmapFactory.decodeResource(getResources(), bitmapid);
target = def_target;
learned = false;
}
abstract public void cast(int init_source, int init_target);
Bitmap bitmap;
String name;
String gesture;
int index;
int target;
int state;
int description;
SpannableString purty;
boolean learned;
boolean is_finished; // Set this to true before calling last animation.
// Or call finish_spell() [it's slower].
int cast_source, cast_target;
public void execute(int init_source, int init_target) {
state = 0;
is_finished = false;
board.set_notify_me(done_handler);
cast_source = init_source;
cast_target = init_target;
cast(cast_source, cast_target);
}
public void finish_spell() {
is_finished = true;
done_handler.sendEmptyMessage(0);
}
private DoneHandler done_handler = new DoneHandler();
class DoneHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (is_finished) {
MainView.this.next_spell();
} else {
state++;
cast(cast_source, cast_target);
}
}
}
int priority;
}
public class ShieldSpell extends Spell {
ShieldSpell() {
init("Shield", "P", R.drawable.shield, R.string.Pdesc, 0);
}
public void cast(int source, int target) {
switch(state) {
case 0:
board.animate_shield(target);
return;
case 1:
if (target != -1) {
Being b = being_list[target];
if (0 == b.shield) b.shield = 1;
}
finish_spell();
return;
}
}
}
public class StabSpell extends Spell {
StabSpell() {
init("Stab", "K", R.drawable.stab, R.string.stabdesc, 1);
}
public void cast(int source, int target) {
switch(state) {
case 0:
board.animate_move(source, target);
return;
case 1:
// TODO: Remove duplicated code.
if (target != -1) {
Being b = being_list[target];
if (0 == b.shield) {
b.get_hurt(1);
board.animate_move_damage(target, 1);
} else {
Log.i("TODO", "block animation");
board.animate_move_damage(target, 0);
}
} else {
board.animate_delay();
}
return;
case 2:
is_finished = true;
board.animate_move_back();
return;
}
}
}
public class MissileSpell extends Spell {
MissileSpell() {
init("Missile", "SD", R.drawable.missile, R.string.SDdesc, 1);
}
public void cast(int source, int target) {
switch(state) {
case 0:
board.animate_bullet(source, target);
return;
case 1:
is_finished = true;
if (target != -1) {
Being b = being_list[target];
if (0 == b.shield) {
b.get_hurt(1);
board.animate_damage(target, 1);
} else {
Log.i("TODO", "block animation");
board.animate_damage(target, 0);
}
} else {
board.animate_delay();
}
return;
}
}
}
public class CauseLightWoundsSpell extends Spell {
CauseLightWoundsSpell() {
init("Cause Light Wounds", "WFP", R.drawable.wound, R.string.WFPdesc, 1);
}
public void cast(int source, int target) {
switch(state) {
case 0:
board.animate_spell(target, bitmap);
return;
case 1:
is_finished = true;
if (-1 != target) {
being_list[target].get_hurt(2);
print("Cause Light Wounds deals 2 damage.");
}
board.animate_damage(target, 2);
return;
}
}
}
public class SummonGoblinSpell extends Spell {
SummonGoblinSpell() {
init("Summon Goblin", "SFW", R.drawable.summon1, R.string.SFWdesc, 0);
}
public void cast(int source, int target) {
switch(state) {
case 0:
is_finished = true;
if (-1 != target) {
int k = being_list[target].controller;
Being b = being_list[being_list_count] = new Being("Goblin", R.drawable.goblin, k);
being_list_count++;
b.start_life(1);
b.target = 1 - k;
Log.i("TODO", "fade in goblin");
board.animate_spell(target, bitmap);
} else {
board.animate_delay();
}
return;
}
}
}
public class CureLightWoundsSpell extends Spell {
CureLightWoundsSpell() {
init("Cure Light Wounds", "DFW", R.drawable.curelight, R.string.DFWdesc, 0);
}
public void cast(int source, int target) {
switch(state) {
case 0:
is_finished = true;
if (-1 != target) {
being_list[target].heal(1);
}
board.animate_spell(target, bitmap);
return;
}
}
}
public class ConfusionSpell extends Spell {
ConfusionSpell() {
init("Confusion", "DSF", R.drawable.confusion, R.string.DSFdesc, 1);
}
public void cast(int source, int target) {
switch(state) {
case 0:
is_finished = true;
if (-1 != target) {
being_list[target].status = Status.CONFUSED;
}
board.animate_spell(target, bitmap);
return;
}
}
}
public class CharmPersonSpell extends Spell {
CharmPersonSpell() {
init("Charm Person", "PSDF", R.drawable.confusion, R.string.PSDFdesc, 1);
}
public void cast(int source, int target) {
switch(state) {
case 0:
is_finished = true;
if (-1 != target) {
// Only works on opponent.
if (1 - source == target) {
being_list[target].status = Status.CHARMED;
}
}
board.animate_spell(target, bitmap);
return;
}
}
}
public class ProtectionSpell extends Spell {
ProtectionSpell() {
init("Protection From Evil", "WWP", R.drawable.shield, R.string.WWPdesc, 0);
}
public void cast(int source, int target) {
switch(state) {
case 0:
board.animate_shield(target);
return;
case 1:
if (target != -1) {
Being b = being_list[target];
b.shield = 4;
}
finish_spell();
return;
}
}
}
public class MonsterAttack extends Spell {
MonsterAttack(int n) {
init("", "", R.drawable.goblin, R.string.bug, 1);
level = n;
}
public void cast(int source, int target) {
switch(state) {
case 0:
board.animate_move(source, target);
return;
case 1:
if (target != -1) {
Being b = being_list[target];
if (0 == b.shield) {
b.get_hurt(1);
board.animate_move_damage(target, 1);
} else {
Log.i("TODO", "block animation");
board.animate_move_damage(target, 0);
}
} else {
board.animate_delay();
}
return;
case 2:
is_finished = true;
board.animate_move_back();
return;
}
}
int level;
}
static public class Status {
static public final int OK = 0;
static public final int CONFUSED = 1;
static public final int CHARMED = 2;
}
static int[] summon_count;
static Bitmap bmcorpse;
public class Being {
public Being(String init_name, int bitmapid, int owner) {
switch(owner) {
case -1: // This being is the player.
y = ylower - 64;
index = -1;
controller = 0;
break;
case -2: // This being is the opponent.
y = 0;
index = -2;
controller = 1;
break;
case 0: // Player controls this being.
for (index = 0; index < 16; index++) {
if (null == being_pos[index].being) break;
}
controller = 0;
break;
case 1: // Opponent controls this being.
for (index = 16 - 1; index >= 0; index--) {
if (null == being_pos[index].being) break;
}
controller = 1;
break;
default:
Log.e("Being", "Ctor given bad owner.");
break;
}
if (owner < 0) {
x = 160 - 32;
set_size_64();
} else {
if (index < 0 || index >= 16) Log.e("Being", "index out of range! Summon should never have been successful?");
x = being_pos[index].x;
y = being_pos[index].y;
being_pos[index].being = this;
set_size_48();
id = controller + 2 * summon_count[controller];
summon_count[controller]++;
}
status = Status.OK;
shield = 0;
dead = false;
setup(init_name, bitmapid, 0);
}
void setup(String init_name, int bitmapid, int life) {
name = init_name;
bitmap = BitmapFactory.decodeResource(getResources(), bitmapid);
start_life(life);
}
void heal(int amount) {
if (!dead) {
life += amount;
if (life > life_max) life = life_max;
lifeline = Integer.toString(life) + "/" + Integer.toString(life_max);
}
}
void get_hurt(int amount) {
if (!dead) {
life -= amount;
lifeline = Integer.toString(life) + "/" + Integer.toString(life_max);
}
}
void set_size_48() {
w = h = 48;
midw = midh = 24;
}
void set_size_64() {
w = h = 64;
midw = midh = 32;
}
void start_life(int n) {
life_max = n;
dead = false;
heal_full();
}
void heal_full() {
life = life_max;
lifeline = Integer.toString(life) + "/" + Integer.toString(life);
}
void die() {
dead = true;
lifeline = "Dead";
}
boolean contains(float xf, float yf) {
int x0 = (int) xf;
int y0 = (int) yf;
return x0 + SLOP >= x && x0 < x + w + SLOP &&
y0 + SLOP >= y && y0 < y + h + SLOP;
}
Bitmap bitmap;
String name;
String lifeline;
int index;
int x, y;
int life;
int life_max;
int status;
int target;
int shield;
int w, h;
int midw, midh;
// For monsters, the player that controls it.
// In future, if ever we support more than two players, for players it
// could represent the source of a Charm Person spell. For now we know
// it must be the other player.
short controller;
boolean dead;
// ID of monster consistent amongst all players in a net game.
int id;
}
class BeingPosition {
BeingPosition(int init_x, int init_y) {
x = init_x;
y = init_y;
being = null;
}
int x, y;
Being being;
}
// Summoned creatures should appear close to their owner, hence this mess.
void init_being_pos() {
int x, y;
x = 160 - 32;
y = ylower - 64;
being_pos = new BeingPosition[16];
being_pos[0] = new BeingPosition(x - 48 - 10, y);
being_pos[1] = new BeingPosition(x + 64 + 10, y);
being_pos[2] = new BeingPosition(x - 48 - 10, y - 48 - 4);
being_pos[3] = new BeingPosition(x + 64 + 10, y - 48 - 4);
being_pos[4] = new BeingPosition(x - 2 * 48 - 2 * 10, y);
being_pos[5] = new BeingPosition(x + 64 + 48 + 2 * 10, y);
being_pos[6] = new BeingPosition(x - 2 * 48 - 2 * 10, y - 48 - 4);
being_pos[7] = new BeingPosition(x + 64 + 48 + 2 * 10, y - 48 - 4);
for (int i = 0; i < 8; i++) {
being_pos[8 + i] = new BeingPosition(
being_pos[8 - i - 1].x, ylower - 64 - being_pos[8 - i - 1].y + 16);
}
}
void reset_being_pos() {
for (int i = 0; i < 16; i++) being_pos[i].being = null;
}
static SpellTap spelltap;
static int charmed_hand;
static boolean freeze_gesture;
static boolean choosing_charm;
static final int SLOP = 4;
static Agent agent;
static final int TILT_AWAIT_UP = 0;
static final int TILT_AWAIT_DOWN = 1;
static final int TILT_DISABLED = 2;
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (is_animating) return false;
if (is_waiting) return false;
x0 = event.getX();
y0 = event.getY();
if (y0 < ylower) {
if (STATE_GESTURE_ONLY == main_state) {
run();
return false;
}
// Check for spell retargeting drag.
if (y0 >= yicon - SLOP && y0 < yicon + 48 + SLOP) {
if (x0 < 48 + SLOP) {
drag_i = 0;
} else if (x0 >= 320 - 48 - SLOP) {
drag_i = 1;
}
} else {
// Check for monster retargeting drag.
for (int i = 2; i < being_list_count; i++) {
Being b = being_list[i];
// It might not matter if you can retarget a corpse's
// attack, but it doesn't seem useful.
if (b.dead || 0 != b.controller) continue;
if (b.contains(x0, y0)) {
drag_i = i;
break;
}
}
}
if (-1 != drag_i) {
print("Drag to target.");
// TODO: Only invalidate status bar.
invalidate();
return true;
}
return false;
}
okstate = y0 >= ystatus;
return true;
case MotionEvent.ACTION_UP:
if (is_animating) return false;
if (is_waiting) return false;
x1 = event.getX();
y1 = event.getY();
if (drag_i != -1) {
get_ready();
int target;
for(target = being_list_count - 1; target >= 0; target--) {
Being b = being_list[target];
if (b.contains(x1, y1)) break;
}
// drag_i = 0, 1 means player is targeting spell.
if (drag_i <= 1) {
if (target == -1) {
// Doesn't count if still in spell icon.
if (y0 >= yicon && y0 < yicon + 48) {
if (x0 < 48) {
// In the future I plan to add a meaning for dragging
// one spell icon to the other.
} else if (x0 >= 320 - 48) {
} else {
spell_target[drag_i] = -1;
}
}
} else {
spell_target[drag_i] = target;
}
} else {
Being b = being_list[drag_i];
if (Status.OK == b.status) {
b.target = target;
}
}
drag_i = -1;
invalidate();
return true;
}
float dx = x1 - x0;
float dy = y1 - y0;
if (dx * dx + dy * dy < 32 * 32) {
if (STATE_GESTURE_ONLY == main_state) {
run();
return true;
}
if (okstate && y1 >= ystatus) {
confirm_move();
return true;
}
if (y1 >= ylower + 32 && y1 < ylower + 32 + 50) {
// Could be choosing a ready spell.
for (int h = 0; h < 2; h++) {
int i;
if (h == 1) {
if (x1 < 160) break;
i = (320 - (int) x1) / 50;
} else {
i = ((int) x1) / 50;
}
if (i >= 0 && i < ready_spell_count[h]) {
choose_spell(h, i);
return true;
}
}
}
} else {
int dirx, diry;
int h;
dirx = dx > 0 ? 1 : -1;
diry = dy > 0 ? 1 : -1;
if (Math.abs(dy) > Math.abs(dx) * 2) {
dirx = 0;
} else if (Math.abs(dx) > Math.abs(dy) * 2) {
diry = 0;
}
if (x0 < 160) {
h = 0;
} else {
h = 1;
dirx *= -1;
}
if (h == charmed_hand || freeze_gesture) {
return true;
}
choice[h] = Gesture.flattenxy(dirx, diry);
if (null == gesture[choice[h]] || !gesture[choice[h]].learned) {
choice[h] = Gesture.NONE;
}
if (choice[h] != lastchoice[h]) {
handle_new_choice(h);
}
if (STATE_GESTURE_ONLY == main_state) run();
return true;
}
}
return false;
}
| public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (is_animating) return false;
if (is_waiting) return false;
x0 = event.getX();
y0 = event.getY();
if (y0 < ylower) {
if (STATE_GESTURE_ONLY == main_state) {
run();
return false;
}
// Check for spell retargeting drag.
if (y0 >= yicon - SLOP && y0 < yicon + 48 + SLOP) {
if (x0 < 48 + SLOP) {
drag_i = 0;
} else if (x0 >= 320 - 48 - SLOP) {
drag_i = 1;
}
} else {
// Check for monster retargeting drag.
for (int i = 2; i < being_list_count; i++) {
Being b = being_list[i];
// It might not matter if you can retarget a corpse's
// attack, but it doesn't seem useful.
if (b.dead || 0 != b.controller) continue;
if (b.contains(x0, y0)) {
drag_i = i;
break;
}
}
}
if (-1 != drag_i) {
print("Drag to target.");
// TODO: Only invalidate status bar.
invalidate();
return true;
}
return false;
}
okstate = y0 >= ystatus;
return true;
case MotionEvent.ACTION_UP:
if (is_animating) return false;
if (is_waiting) return false;
x1 = event.getX();
y1 = event.getY();
if (drag_i != -1) {
get_ready();
int target;
for(target = being_list_count - 1; target >= 0; target--) {
Being b = being_list[target];
if (b.contains(x1, y1)) break;
}
// drag_i = 0, 1 means player is targeting spell.
if (drag_i <= 1) {
if (target == -1) {
// Doesn't count if still in spell icon.
if (y1 >= yicon - SLOP && y1 < yicon + 48 + SLOP) {
if (x1 < 48 + SLOP) {
// In the future I plan to add a meaning for dragging
// one spell icon to the other.
} else if (x1 >= 320 - 48 - SLOP) {
} else {
spell_target[drag_i] = -1;
}
} else {
spell_target[drag_i] = -1;
}
} else {
spell_target[drag_i] = target;
}
} else {
Being b = being_list[drag_i];
if (Status.OK == b.status) {
b.target = target;
}
}
drag_i = -1;
invalidate();
return true;
}
float dx = x1 - x0;
float dy = y1 - y0;
if (dx * dx + dy * dy < 32 * 32) {
if (STATE_GESTURE_ONLY == main_state) {
run();
return true;
}
if (okstate && y1 >= ystatus) {
confirm_move();
return true;
}
if (y1 >= ylower + 32 && y1 < ylower + 32 + 50) {
// Could be choosing a ready spell.
for (int h = 0; h < 2; h++) {
int i;
if (h == 1) {
if (x1 < 160) break;
i = (320 - (int) x1) / 50;
} else {
i = ((int) x1) / 50;
}
if (i >= 0 && i < ready_spell_count[h]) {
choose_spell(h, i);
return true;
}
}
}
} else {
int dirx, diry;
int h;
dirx = dx > 0 ? 1 : -1;
diry = dy > 0 ? 1 : -1;
if (Math.abs(dy) > Math.abs(dx) * 2) {
dirx = 0;
} else if (Math.abs(dx) > Math.abs(dy) * 2) {
diry = 0;
}
if (x0 < 160) {
h = 0;
} else {
h = 1;
dirx *= -1;
}
if (h == charmed_hand || freeze_gesture) {
return true;
}
choice[h] = Gesture.flattenxy(dirx, diry);
if (null == gesture[choice[h]] || !gesture[choice[h]].learned) {
choice[h] = Gesture.NONE;
}
if (choice[h] != lastchoice[h]) {
handle_new_choice(h);
}
if (STATE_GESTURE_ONLY == main_state) run();
return true;
}
}
return false;
}
|
diff --git a/PA3B/src/ray/accel/Bvh.java b/PA3B/src/ray/accel/Bvh.java
index 5f8bec8..f7d3dc7 100755
--- a/PA3B/src/ray/accel/Bvh.java
+++ b/PA3B/src/ray/accel/Bvh.java
@@ -1,222 +1,222 @@
package ray.accel;
import java.util.Arrays;
import java.util.Comparator;
import ray.IntersectionRecord;
import ray.Ray;
import ray.math.Point3;
import ray.surface.Surface;
/**
* Class for Axis-Aligned-Bounding-Box to speed up the intersection look up time.
*
* @author ss932, pramook
*/
public class Bvh implements AccelStruct {
/** A shared surfaces array that will be used across every node in the tree. */
private Surface[] surfaces;
/** A comparator class that can sort surfaces by x, y, or z coordinate. */
static MyComparator cmp = new MyComparator();
/** left and right are indices for []surfaces,
* meaning that this tree node contains a set of surfaces
* from surfaces[left] to surfaces[right-1]. */
int left, right;
/** The root of the BVH tree. */
BvhNode root;
public Bvh(Surface[] surfaces, int left, int right) {
this.surfaces = surfaces;
this.left = left;
this.right = right;
}
/**
* Set the shared surfaces that every node in the tree will use by
* using start and end indices.
*/
public void setSurfaces(Surface []surfaces) {
this.surfaces = surfaces;
}
/**
* Set outRecord to the first intersection of ray with the scene. Return true
* if there was an intersection and false otherwise. If no intersection was
* found outRecord is unchanged.
*
* @param outRecord the output IntersectionRecord
* @param ray the ray to intersect
* @param anyIntersection if true, will immediately return when found an intersection
* @return true if and intersection is found.
*/
public boolean intersect(IntersectionRecord outRecord, Ray rayIn, boolean anyIntersection) {
return intersectHelper(root, outRecord, rayIn, anyIntersection);
}
/**
* A helper method to the main intersect method. It finds the intersection with
* any of the surfaces under the given BVH node.
*
* @param node a BVH node that we would like to find an intersection with surfaces under it
* @param outRecord the output InsersectionMethod
* @param rayIn the ray to intersect
* @param anyIntersection if true, will immediately return when found an intersection
* @return true if an intersection is found with any surface under the given node
*/
private boolean intersectHelper(BvhNode node, IntersectionRecord outRecord, Ray rayIn, boolean anyIntersection)
{
// TODO(B): fill in this function.
// Hint: For a leaf node, use a normal linear search.
// Otherwise, search in the left and right children.
// check if it intersect this node, if not return false
if (!node.intersects(rayIn)) {
return false;
}
IntersectionRecord closest = new IntersectionRecord();
closest.t = Double.POSITIVE_INFINITY;
boolean intersectFound = false;
// if leaf node, check intersection with surfaces and find closest t
if (node.isLeaf()) {
for (int i=node.surfaceIndexStart; i < node.surfaceIndexEnd; i++) {
IntersectionRecord record = new IntersectionRecord();
if (surfaces[i].intersect(record, rayIn)) {
intersectFound = true;
if (anyIntersection) {
outRecord.set(record);
return true;
}
if (closest.t > record.t) {
closest.set(record);
}
}
}
if (intersectFound) {
outRecord.set(closest);
return true;
} else {
return false;
}
}
// recursive: call it on left and right child
IntersectionRecord record = new IntersectionRecord();
for (int i = 0; i < 2; i++) {
if (intersectHelper(node.child[i], record, rayIn, anyIntersection)) {
intersectFound = true;
if (anyIntersection) {
outRecord.set(record);
return true;
}
if (closest.t > record.t) {
closest.set(record);
}
}
}
if (intersectFound) {
outRecord.set(closest);
return true;
} else {
return false;
}
}
@Override
public void build() {
root = createTree(left, right);
}
/**
* Create a BVH [sub]tree. This tree node will be responsible for storing
* and processing surfaces[left] to surfaces[right-1].
* @param left The left index of surfaces
* @param left The right index of surfaces
*/
private BvhNode createTree(int left, int right) {
// TODO(B): fill in this function.
// int i, j;
// ==== Step 1 ====
// Find out the BIG bounding box enclosing all the surfaces in the range [left, right)
// and store them in minB and maxB.
// Hint: To find the bounding box for each surface, use getMinBound() and getMaxBound() */
Point3 minB = new Point3(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
Point3 maxB = new Point3(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
for (int i = left; i < right; i++) {
Point3 surfMinB = surfaces[i].getMinBound();
Point3 surfMaxB = surfaces[i].getMaxBound();
for (int j = 0; j < 3; j++) {
if (surfMinB.getE(j) < minB.getE(j)) {
minB.setE(j, surfMinB.getE(j));
}
if (surfMaxB.getE(j) > maxB.getE(j)) {
maxB.setE(j, surfMaxB.getE(j));
}
}
}
// ==== Step 2 ====
// Check for the base case.
// If the range [left, right) is small enough, just return a new leaf node.
- if (right - left == 10) {
+ if (right - left <= 10) {
return new BvhNode(minB, maxB, null, null, left, right);
}
// ==== Step 3 ====
// Figure out the widest dimension (x or y or z).
// If x is the widest, set widestDim = 0. If y, set widestDim = 1. If z, set widestDim = 2.
int widestDim = 0;
double[] dims = new double[3];
for (int i = 0; i < 3; i++) {
dims[i] = maxB.getE(i) - minB.getE(i);
}
for (int i = 0; i < 3; i++) {
if (dims[widestDim] < dims[i]) {
widestDim = i;
}
}
// ==== Step 4 (DONE) ====
// Sort surfaces according to the widest dimension.
// You can also implement O(n) randomized splitting algorithm.
cmp.setIndex(widestDim);
Arrays.sort(surfaces, left, right, cmp);
// ==== Step 5 ====
// Recursively create left and right children.
int mid = (right-left)/2;
BvhNode leftChild = createTree(left, mid);
BvhNode rightChild = createTree(mid, right);
return new BvhNode(minB, maxB, leftChild, rightChild, left, right);
}
}
class MyComparator implements Comparator<Surface> {
int index;
public MyComparator() { }
public void setIndex(int index) {
this.index = index;
}
public int compare(Surface o1, Surface o2) {
double v1 = o1.getAveragePosition().getE(index);
double v2 = o2.getAveragePosition().getE(index);
if(v1 < v2) return 1;
if(v1 > v2) return -1;
return 0;
}
}
| true | true | private BvhNode createTree(int left, int right) {
// TODO(B): fill in this function.
// int i, j;
// ==== Step 1 ====
// Find out the BIG bounding box enclosing all the surfaces in the range [left, right)
// and store them in minB and maxB.
// Hint: To find the bounding box for each surface, use getMinBound() and getMaxBound() */
Point3 minB = new Point3(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
Point3 maxB = new Point3(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
for (int i = left; i < right; i++) {
Point3 surfMinB = surfaces[i].getMinBound();
Point3 surfMaxB = surfaces[i].getMaxBound();
for (int j = 0; j < 3; j++) {
if (surfMinB.getE(j) < minB.getE(j)) {
minB.setE(j, surfMinB.getE(j));
}
if (surfMaxB.getE(j) > maxB.getE(j)) {
maxB.setE(j, surfMaxB.getE(j));
}
}
}
// ==== Step 2 ====
// Check for the base case.
// If the range [left, right) is small enough, just return a new leaf node.
if (right - left == 10) {
return new BvhNode(minB, maxB, null, null, left, right);
}
// ==== Step 3 ====
// Figure out the widest dimension (x or y or z).
// If x is the widest, set widestDim = 0. If y, set widestDim = 1. If z, set widestDim = 2.
int widestDim = 0;
double[] dims = new double[3];
for (int i = 0; i < 3; i++) {
dims[i] = maxB.getE(i) - minB.getE(i);
}
for (int i = 0; i < 3; i++) {
if (dims[widestDim] < dims[i]) {
widestDim = i;
}
}
// ==== Step 4 (DONE) ====
// Sort surfaces according to the widest dimension.
// You can also implement O(n) randomized splitting algorithm.
cmp.setIndex(widestDim);
Arrays.sort(surfaces, left, right, cmp);
// ==== Step 5 ====
// Recursively create left and right children.
int mid = (right-left)/2;
BvhNode leftChild = createTree(left, mid);
BvhNode rightChild = createTree(mid, right);
return new BvhNode(minB, maxB, leftChild, rightChild, left, right);
}
| private BvhNode createTree(int left, int right) {
// TODO(B): fill in this function.
// int i, j;
// ==== Step 1 ====
// Find out the BIG bounding box enclosing all the surfaces in the range [left, right)
// and store them in minB and maxB.
// Hint: To find the bounding box for each surface, use getMinBound() and getMaxBound() */
Point3 minB = new Point3(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
Point3 maxB = new Point3(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
for (int i = left; i < right; i++) {
Point3 surfMinB = surfaces[i].getMinBound();
Point3 surfMaxB = surfaces[i].getMaxBound();
for (int j = 0; j < 3; j++) {
if (surfMinB.getE(j) < minB.getE(j)) {
minB.setE(j, surfMinB.getE(j));
}
if (surfMaxB.getE(j) > maxB.getE(j)) {
maxB.setE(j, surfMaxB.getE(j));
}
}
}
// ==== Step 2 ====
// Check for the base case.
// If the range [left, right) is small enough, just return a new leaf node.
if (right - left <= 10) {
return new BvhNode(minB, maxB, null, null, left, right);
}
// ==== Step 3 ====
// Figure out the widest dimension (x or y or z).
// If x is the widest, set widestDim = 0. If y, set widestDim = 1. If z, set widestDim = 2.
int widestDim = 0;
double[] dims = new double[3];
for (int i = 0; i < 3; i++) {
dims[i] = maxB.getE(i) - minB.getE(i);
}
for (int i = 0; i < 3; i++) {
if (dims[widestDim] < dims[i]) {
widestDim = i;
}
}
// ==== Step 4 (DONE) ====
// Sort surfaces according to the widest dimension.
// You can also implement O(n) randomized splitting algorithm.
cmp.setIndex(widestDim);
Arrays.sort(surfaces, left, right, cmp);
// ==== Step 5 ====
// Recursively create left and right children.
int mid = (right-left)/2;
BvhNode leftChild = createTree(left, mid);
BvhNode rightChild = createTree(mid, right);
return new BvhNode(minB, maxB, leftChild, rightChild, left, right);
}
|
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java
index 5d1e5a2ca..dab9fc7a3 100644
--- a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java
+++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java
@@ -1,268 +1,270 @@
/*******************************************************************************
* Copyright (c) 2000, 2008 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.jface.text.contentassist;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.jface.internal.text.DelayedInputChangeListener;
import org.eclipse.jface.internal.text.InformationControlReplacer;
import org.eclipse.jface.text.IDelayedInputChangeProvider;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlExtension5;
import org.eclipse.jface.text.IInputChangedListener;
/**
* A generic closer class used to monitor various
* interface events in order to determine whether
* a content assistant should be terminated and all
* associated windows be closed.
*/
class PopupCloser extends ShellAdapter implements FocusListener, SelectionListener, Listener {
/** The content assistant to be monitored. */
private ContentAssistant fContentAssistant;
/** The table of a selector popup opened by the content assistant. */
private Table fTable;
/** The scroll bar of the table for the selector popup. */
private ScrollBar fScrollbar;
/** Indicates whether the scroll bar thumb has been grabbed. */
private boolean fScrollbarClicked= false;
/**
* The shell on which some listeners are registered.
* @since 3.1
*/
private Shell fShell;
/**
* The display on which some filters are registered.
* @since 3.4
*/
private Display fDisplay;
/**
* The additional info controller, or <code>null</code>.
* @since 3.4
*/
private AdditionalInfoController fAdditionalInfoController;
/**
* Installs this closer on the given table opened by the given content assistant.
*
* @param contentAssistant the content assistant
* @param table the table to be tracked
*/
public void install(ContentAssistant contentAssistant, Table table) {
install(contentAssistant, table, null);
}
/**
* Installs this closer on the given table opened by the given content assistant.
*
* @param contentAssistant the content assistant
* @param table the table to be tracked
* @param additionalInfoController the additional info controller, or <code>null</code>
* @since 3.4
*/
public void install(ContentAssistant contentAssistant, Table table, AdditionalInfoController additionalInfoController) {
fContentAssistant= contentAssistant;
fTable= table;
fAdditionalInfoController= additionalInfoController;
if (Helper.okToUse(fTable)) {
fShell= fTable.getShell();
fDisplay= fShell.getDisplay();
fShell.addShellListener(this);
fTable.addFocusListener(this);
fScrollbar= fTable.getVerticalBar();
if (fScrollbar != null)
fScrollbar.addSelectionListener(this);
fDisplay.addFilter(SWT.Activate, this);
fDisplay.addFilter(SWT.MouseWheel, this);
fDisplay.addFilter(SWT.Deactivate, this);
fDisplay.addFilter(SWT.MouseUp, this);
}
}
/**
* Uninstalls this closer if previously installed.
*/
public void uninstall() {
fContentAssistant= null;
if (Helper.okToUse(fShell))
fShell.removeShellListener(this);
fShell= null;
if (Helper.okToUse(fScrollbar))
fScrollbar.removeSelectionListener(this);
if (Helper.okToUse(fTable))
fTable.removeFocusListener(this);
if (fDisplay != null && ! fDisplay.isDisposed()) {
fDisplay.removeFilter(SWT.Activate, this);
fDisplay.removeFilter(SWT.MouseWheel, this);
fDisplay.removeFilter(SWT.Deactivate, this);
fDisplay.removeFilter(SWT.MouseUp, this);
}
}
/*
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
fScrollbarClicked= true;
}
/*
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent e) {
fScrollbarClicked= true;
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {
}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(final FocusEvent e) {
fScrollbarClicked= false;
Display d= fTable.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (Helper.okToUse(fTable) && !fTable.isFocusControl() && !fScrollbarClicked && fContentAssistant != null)
fContentAssistant.popupFocusLost(e);
}
});
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
* @since 3.1
*/
public void shellDeactivated(ShellEvent e) {
if (fContentAssistant != null && ! fContentAssistant.hasProposalPopupFocus())
fContentAssistant.hide();
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellClosed(org.eclipse.swt.events.ShellEvent)
* @since 3.1
*/
public void shellClosed(ShellEvent e) {
if (fContentAssistant != null)
fContentAssistant.hide();
}
/*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
* @since 3.4
*/
public void handleEvent(Event event) {
switch (event.type) {
case SWT.Activate:
case SWT.MouseWheel:
if (fAdditionalInfoController == null)
return;
if (event.widget == fShell || event.widget == fTable || event.widget == fScrollbar)
return;
if (fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer() == null)
fAdditionalInfoController.hideInformationControl();
else if (!fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) {
IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2();
// During isReplaceInProgress(), events can come from the replacing information control
if (event.widget instanceof Control && infoControl instanceof IInformationControlExtension5) {
Control control= (Control) event.widget;
IInformationControlExtension5 iControl5= (IInformationControlExtension5) infoControl;
if (!(iControl5.containsControl(control)))
fAdditionalInfoController.hideInformationControl();
else if (event.type == SWT.MouseWheel)
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(false);
} else if (infoControl != null && infoControl.isFocusControl()) {
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true);
}
}
break;
case SWT.MouseUp:
- if (fAdditionalInfoController.getInternalAccessor().isReplaceInProgress())
+ if (fAdditionalInfoController == null || fAdditionalInfoController.getInternalAccessor().isReplaceInProgress())
break;
if (event.widget instanceof Control) {
Control control= (Control) event.widget;
IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2();
if (infoControl instanceof IInformationControlExtension5) {
final IInformationControlExtension5 iControl5= (IInformationControlExtension5) infoControl;
if (iControl5.containsControl(control)) {
if (infoControl instanceof IDelayedInputChangeProvider) {
final IDelayedInputChangeProvider delayedICP= (IDelayedInputChangeProvider) infoControl;
final IInputChangedListener inputChangeListener= new DelayedInputChangeListener(delayedICP, fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer());
delayedICP.setDelayedInputChangeListener(inputChangeListener);
// cancel automatic input updating after a small timeout:
control.getShell().getDisplay().timerExec(1000, new Runnable() {
public void run() {
delayedICP.setDelayedInputChangeListener(null);
}
});
}
// XXX: workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212392 :
control.getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true);
}
});
}
}
}
break;
case SWT.Deactivate:
+ if (fAdditionalInfoController == null)
+ break;
InformationControlReplacer replacer= fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer();
if (replacer != null && fContentAssistant != null) {
IInformationControl iControl= replacer.getCurrentInformationControl2();
if (event.widget instanceof Control && iControl instanceof IInformationControlExtension5) {
Control control= (Control) event.widget;
IInformationControlExtension5 iControl5= (IInformationControlExtension5) iControl;
if (iControl5.containsControl(control)) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fContentAssistant != null && ! fContentAssistant.hasProposalPopupFocus())
fContentAssistant.hide();
}
});
}
}
}
break;
}
}
}
| false | true | public void handleEvent(Event event) {
switch (event.type) {
case SWT.Activate:
case SWT.MouseWheel:
if (fAdditionalInfoController == null)
return;
if (event.widget == fShell || event.widget == fTable || event.widget == fScrollbar)
return;
if (fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer() == null)
fAdditionalInfoController.hideInformationControl();
else if (!fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) {
IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2();
// During isReplaceInProgress(), events can come from the replacing information control
if (event.widget instanceof Control && infoControl instanceof IInformationControlExtension5) {
Control control= (Control) event.widget;
IInformationControlExtension5 iControl5= (IInformationControlExtension5) infoControl;
if (!(iControl5.containsControl(control)))
fAdditionalInfoController.hideInformationControl();
else if (event.type == SWT.MouseWheel)
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(false);
} else if (infoControl != null && infoControl.isFocusControl()) {
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true);
}
}
break;
case SWT.MouseUp:
if (fAdditionalInfoController.getInternalAccessor().isReplaceInProgress())
break;
if (event.widget instanceof Control) {
Control control= (Control) event.widget;
IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2();
if (infoControl instanceof IInformationControlExtension5) {
final IInformationControlExtension5 iControl5= (IInformationControlExtension5) infoControl;
if (iControl5.containsControl(control)) {
if (infoControl instanceof IDelayedInputChangeProvider) {
final IDelayedInputChangeProvider delayedICP= (IDelayedInputChangeProvider) infoControl;
final IInputChangedListener inputChangeListener= new DelayedInputChangeListener(delayedICP, fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer());
delayedICP.setDelayedInputChangeListener(inputChangeListener);
// cancel automatic input updating after a small timeout:
control.getShell().getDisplay().timerExec(1000, new Runnable() {
public void run() {
delayedICP.setDelayedInputChangeListener(null);
}
});
}
// XXX: workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212392 :
control.getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true);
}
});
}
}
}
break;
case SWT.Deactivate:
InformationControlReplacer replacer= fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer();
if (replacer != null && fContentAssistant != null) {
IInformationControl iControl= replacer.getCurrentInformationControl2();
if (event.widget instanceof Control && iControl instanceof IInformationControlExtension5) {
Control control= (Control) event.widget;
IInformationControlExtension5 iControl5= (IInformationControlExtension5) iControl;
if (iControl5.containsControl(control)) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fContentAssistant != null && ! fContentAssistant.hasProposalPopupFocus())
fContentAssistant.hide();
}
});
}
}
}
break;
}
}
| public void handleEvent(Event event) {
switch (event.type) {
case SWT.Activate:
case SWT.MouseWheel:
if (fAdditionalInfoController == null)
return;
if (event.widget == fShell || event.widget == fTable || event.widget == fScrollbar)
return;
if (fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer() == null)
fAdditionalInfoController.hideInformationControl();
else if (!fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) {
IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2();
// During isReplaceInProgress(), events can come from the replacing information control
if (event.widget instanceof Control && infoControl instanceof IInformationControlExtension5) {
Control control= (Control) event.widget;
IInformationControlExtension5 iControl5= (IInformationControlExtension5) infoControl;
if (!(iControl5.containsControl(control)))
fAdditionalInfoController.hideInformationControl();
else if (event.type == SWT.MouseWheel)
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(false);
} else if (infoControl != null && infoControl.isFocusControl()) {
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true);
}
}
break;
case SWT.MouseUp:
if (fAdditionalInfoController == null || fAdditionalInfoController.getInternalAccessor().isReplaceInProgress())
break;
if (event.widget instanceof Control) {
Control control= (Control) event.widget;
IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2();
if (infoControl instanceof IInformationControlExtension5) {
final IInformationControlExtension5 iControl5= (IInformationControlExtension5) infoControl;
if (iControl5.containsControl(control)) {
if (infoControl instanceof IDelayedInputChangeProvider) {
final IDelayedInputChangeProvider delayedICP= (IDelayedInputChangeProvider) infoControl;
final IInputChangedListener inputChangeListener= new DelayedInputChangeListener(delayedICP, fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer());
delayedICP.setDelayedInputChangeListener(inputChangeListener);
// cancel automatic input updating after a small timeout:
control.getShell().getDisplay().timerExec(1000, new Runnable() {
public void run() {
delayedICP.setDelayedInputChangeListener(null);
}
});
}
// XXX: workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212392 :
control.getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true);
}
});
}
}
}
break;
case SWT.Deactivate:
if (fAdditionalInfoController == null)
break;
InformationControlReplacer replacer= fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer();
if (replacer != null && fContentAssistant != null) {
IInformationControl iControl= replacer.getCurrentInformationControl2();
if (event.widget instanceof Control && iControl instanceof IInformationControlExtension5) {
Control control= (Control) event.widget;
IInformationControlExtension5 iControl5= (IInformationControlExtension5) iControl;
if (iControl5.containsControl(control)) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fContentAssistant != null && ! fContentAssistant.hasProposalPopupFocus())
fContentAssistant.hide();
}
});
}
}
}
break;
}
}
|
diff --git a/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/activity/ActivityController.java b/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/activity/ActivityController.java
index 7f9bb3b71..c347d8f16 100644
--- a/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/activity/ActivityController.java
+++ b/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/activity/ActivityController.java
@@ -1,159 +1,159 @@
package edu.northwestern.bioinformatics.studycalendar.web.activity;
import edu.northwestern.bioinformatics.studycalendar.web.PscAbstractController;
import edu.northwestern.bioinformatics.studycalendar.dao.*;
import edu.northwestern.bioinformatics.studycalendar.domain.tools.NamedComparatorByLetterCase;
import edu.northwestern.bioinformatics.studycalendar.domain.tools.ActivityTypeComparator;
import edu.northwestern.bioinformatics.studycalendar.domain.*;
import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.PscAuthorizedHandler;
import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.ResourceAuthorization;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.beans.factory.annotation.Required;
import org.displaytag.tags.TableTagParameters;
import org.displaytag.util.ParamEncoder;
import org.displaytag.properties.SortOrderEnum;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import static edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole.BUSINESS_ADMINISTRATOR;
public class ActivityController extends PscAbstractController implements PscAuthorizedHandler {
private ActivityDao activityDao;
private SourceDao sourceDao;
private PlannedActivityDao plannedActivityDao;
private ActivityTypeDao activityTypeDao;
private final static Integer pageIncrementor =100;
public Collection<ResourceAuthorization> authorizations(String httpMethod, Map<String, String[]> queryParameters) {
return ResourceAuthorization.createCollection(BUSINESS_ADMINISTRATOR);
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
String sortOrder = request.getParameter((new ParamEncoder("row").encodeParameterName(TableTagParameters.PARAMETER_ORDER)));
SortOrderEnum sortOrderEnum = (sortOrder == null || sortOrder.equals("2"))
? SortOrderEnum.DESCENDING : SortOrderEnum.ASCENDING;
String sortItem = request.getParameter((new ParamEncoder("row").encodeParameterName(TableTagParameters.PARAMETER_SORT)));
String sourceId = ServletRequestUtils.getStringParameter(request, "sourceId");
if ("POST".equals(request.getMethod())) {
Integer index = ServletRequestUtils.getRequiredIntParameter(request, "index");
model = processRequest(model, sourceId, index, sortOrderEnum, sortItem);
return new ModelAndView("template/ajax/activityTableUpdate", model);
} else {
if (request.getParameterMap().isEmpty()) {
model.put("sources", sourceDao.getAll());
} else {
model = processRequest(model, sourceId, 0, sortOrderEnum, sortItem);
model.put("sourceId", sourceId);
model.put("sources", sourceDao.getAll());
}
return new ModelAndView("activity", model);
}
}
private Map<String, Object> processRequest( Map<String, Object> model, String sourceId, Integer index, SortOrderEnum sortOrderEnum, String sortItem) throws Exception{
List<Activity> activities = new ArrayList<Activity>();
if (sourceId == null) {
activities = activityDao.getAll();
- } else if(!sourceId.equals("select")) {
+ } else if(!sourceId.equals("select") || !sourceId.equals("selectAll")) {
activities = activityDao.getBySourceId(new Integer(sourceId));
}
Integer numberOfPages = getNumberOfPagesFromList(activities);
activities = sortListBasedOnRequest(activities, sortOrderEnum, sortItem);
Integer indexSecondBorder = index + pageIncrementor;
//the condition below is for the "previous" event
if (index < 0) {
indexSecondBorder = (-1)*indexSecondBorder;
index= indexSecondBorder - pageIncrementor;
}
model.put("selectedPage", index);
//happens only if we have a large amount of activities (> 100 in our case)
if (activities.size() > pageIncrementor) {
model.put("index", indexSecondBorder);
if (indexSecondBorder > activities.size()){
//we reached the last page
model.put("showNext", false);
model.put("activitiesPerSource", activities.subList(index, activities.size()));
} else {
model.put("showNext", true);
model.put("activitiesPerSource", activities.subList(index, indexSecondBorder));
}
if(index >= pageIncrementor ) {
model.put("showPrev", true);
} else {
model.put("showPrev", false);
}
} else {
model.put("index", 0);
model.put("showNext", false);
model.put("activitiesPerSource", activities);
}
model.put("activityTypes", activityTypeDao.getAll());
if (! (sourceId == null || sourceId.equals("select"))) {
model.put("displayCreateNewActivity", Boolean.TRUE);
model.put("showtable", Boolean.TRUE);
} else {
model.put("displayCreateNewActivity", Boolean.FALSE);
}
model.put("numberOfPages", numberOfPages);
return model;
}
List<Activity> sortListBasedOnRequest(List<Activity> activities, SortOrderEnum sortOrderEnum, String sortItem) {
if (sortItem!= null) {
if (sortItem.toLowerCase().equals("name")){
Collections.sort(activities, new NamedComparatorByLetterCase());
} else if (sortItem.toLowerCase().equals("type")){
Collections.sort(activities, new ActivityTypeComparator());
}
if (sortOrderEnum.equals(SortOrderEnum.DESCENDING)){
Collections.reverse(activities);
}
} else {
Collections.sort(activities);
}
return activities;
}
private Integer getNumberOfPagesFromList(List<Activity> activities) {
Integer size = activities.size();
Integer amountOfPages = size/pageIncrementor;
if (amountOfPages * pageIncrementor < size) {
amountOfPages++;
}
return amountOfPages;
}
//// CONFIGURATION
@Required
public void setActivityDao(ActivityDao activityDao) {
this.activityDao = activityDao;
}
@Required
public void setSourceDao(SourceDao sourceDao) {
this.sourceDao = sourceDao;
}
@Required
public void setPlannedActivityDao(PlannedActivityDao plannedActivityDao) {
this.plannedActivityDao = plannedActivityDao;
}
@Required
public void setActivityTypeDao(ActivityTypeDao activityTypeDao) {
this.activityTypeDao = activityTypeDao;
}
}
| true | true | private Map<String, Object> processRequest( Map<String, Object> model, String sourceId, Integer index, SortOrderEnum sortOrderEnum, String sortItem) throws Exception{
List<Activity> activities = new ArrayList<Activity>();
if (sourceId == null) {
activities = activityDao.getAll();
} else if(!sourceId.equals("select")) {
activities = activityDao.getBySourceId(new Integer(sourceId));
}
Integer numberOfPages = getNumberOfPagesFromList(activities);
activities = sortListBasedOnRequest(activities, sortOrderEnum, sortItem);
Integer indexSecondBorder = index + pageIncrementor;
//the condition below is for the "previous" event
if (index < 0) {
indexSecondBorder = (-1)*indexSecondBorder;
index= indexSecondBorder - pageIncrementor;
}
model.put("selectedPage", index);
//happens only if we have a large amount of activities (> 100 in our case)
if (activities.size() > pageIncrementor) {
model.put("index", indexSecondBorder);
if (indexSecondBorder > activities.size()){
//we reached the last page
model.put("showNext", false);
model.put("activitiesPerSource", activities.subList(index, activities.size()));
} else {
model.put("showNext", true);
model.put("activitiesPerSource", activities.subList(index, indexSecondBorder));
}
if(index >= pageIncrementor ) {
model.put("showPrev", true);
} else {
model.put("showPrev", false);
}
} else {
model.put("index", 0);
model.put("showNext", false);
model.put("activitiesPerSource", activities);
}
model.put("activityTypes", activityTypeDao.getAll());
if (! (sourceId == null || sourceId.equals("select"))) {
model.put("displayCreateNewActivity", Boolean.TRUE);
model.put("showtable", Boolean.TRUE);
} else {
model.put("displayCreateNewActivity", Boolean.FALSE);
}
model.put("numberOfPages", numberOfPages);
return model;
}
| private Map<String, Object> processRequest( Map<String, Object> model, String sourceId, Integer index, SortOrderEnum sortOrderEnum, String sortItem) throws Exception{
List<Activity> activities = new ArrayList<Activity>();
if (sourceId == null) {
activities = activityDao.getAll();
} else if(!sourceId.equals("select") || !sourceId.equals("selectAll")) {
activities = activityDao.getBySourceId(new Integer(sourceId));
}
Integer numberOfPages = getNumberOfPagesFromList(activities);
activities = sortListBasedOnRequest(activities, sortOrderEnum, sortItem);
Integer indexSecondBorder = index + pageIncrementor;
//the condition below is for the "previous" event
if (index < 0) {
indexSecondBorder = (-1)*indexSecondBorder;
index= indexSecondBorder - pageIncrementor;
}
model.put("selectedPage", index);
//happens only if we have a large amount of activities (> 100 in our case)
if (activities.size() > pageIncrementor) {
model.put("index", indexSecondBorder);
if (indexSecondBorder > activities.size()){
//we reached the last page
model.put("showNext", false);
model.put("activitiesPerSource", activities.subList(index, activities.size()));
} else {
model.put("showNext", true);
model.put("activitiesPerSource", activities.subList(index, indexSecondBorder));
}
if(index >= pageIncrementor ) {
model.put("showPrev", true);
} else {
model.put("showPrev", false);
}
} else {
model.put("index", 0);
model.put("showNext", false);
model.put("activitiesPerSource", activities);
}
model.put("activityTypes", activityTypeDao.getAll());
if (! (sourceId == null || sourceId.equals("select"))) {
model.put("displayCreateNewActivity", Boolean.TRUE);
model.put("showtable", Boolean.TRUE);
} else {
model.put("displayCreateNewActivity", Boolean.FALSE);
}
model.put("numberOfPages", numberOfPages);
return model;
}
|
diff --git a/src/org/usfirst/frc4682/Audacity/OI.java b/src/org/usfirst/frc4682/Audacity/OI.java
index ced314e..ec3312f 100644
--- a/src/org/usfirst/frc4682/Audacity/OI.java
+++ b/src/org/usfirst/frc4682/Audacity/OI.java
@@ -1,75 +1,75 @@
package org.usfirst.frc4682.Audacity;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.Joystick;
import org.usfirst.frc4682.Audacity.commands.*;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
public Joystick leftStick = new Joystick(1);
public Joystick rightStick = new Joystick(2);
public Joystick thirdStick = new Joystick(3);
Button shootingButton = new JoystickButton(thirdStick, 2);
Button firingButton = new JoystickButton(thirdStick, 1);
Button firstDisable = new JoystickButton(leftStick, 11);
Button secondDisable = new JoystickButton(rightStick, 11);
Button thirdDisable = new JoystickButton(thirdStick, 11);
Button firstDisableAlt = new JoystickButton(leftStick, 10);
Button secondDisableAlt = new JoystickButton(rightStick, 10);
Button thirdDisableAlt = new JoystickButton(thirdStick, 10);
Button firstEnable = new JoystickButton(leftStick, 6);
Button secondEnable = new JoystickButton(rightStick, 6);
Button thirdEnable = new JoystickButton(thirdStick, 6);
Button firstEnableAlt = new JoystickButton(leftStick, 7);
Button secondEnableAlt = new JoystickButton(rightStick, 7);
Button thirdEnableAlt = new JoystickButton(thirdStick, 7);
public OI() {
shootingButton.whenPressed(new TuneShooter());
firingButton.whenPressed(new Feed());
firstDisable.whenPressed(new StopAll());
secondDisable.whenPressed(new StopAll());
thirdDisable.whenPressed(new StopAll());
firstDisableAlt.whenPressed(new StopAll());
secondDisableAlt.whenPressed(new StopAll());
thirdDisableAlt.whenPressed(new StopAll());
- firstEnable.whenPressed(new RestartDrive());
- secondEnable.whenPressed(new RestartDrive());
- thirdEnable.whenPressed(new RestartDrive());
+ firstEnable.whenPressed(new Restart());
+ secondEnable.whenPressed(new Restart());
+ thirdEnable.whenPressed(new Restart());
- firstEnableAlt.whenPressed(new RestartDrive());
- secondEnableAlt.whenPressed(new RestartDrive());
- thirdEnableAlt.whenPressed(new RestartDrive());
+ firstEnableAlt.whenPressed(new Restart());
+ secondEnableAlt.whenPressed(new Restart());
+ thirdEnableAlt.whenPressed(new Restart());
}
public double getFirstThrottle() { // returns 0 < double < 1
return getThrottle(leftStick);
}
public double getSecondThrottle() {
return getThrottle(rightStick);
}
public double getThirdThrottle() {
return getThrottle(thirdStick);
}
public double getThrottle(Joystick stick) {
return (-(stick.getRawAxis(3) + 1)/2) + 1;
}
}
| false | true | public OI() {
shootingButton.whenPressed(new TuneShooter());
firingButton.whenPressed(new Feed());
firstDisable.whenPressed(new StopAll());
secondDisable.whenPressed(new StopAll());
thirdDisable.whenPressed(new StopAll());
firstDisableAlt.whenPressed(new StopAll());
secondDisableAlt.whenPressed(new StopAll());
thirdDisableAlt.whenPressed(new StopAll());
firstEnable.whenPressed(new RestartDrive());
secondEnable.whenPressed(new RestartDrive());
thirdEnable.whenPressed(new RestartDrive());
firstEnableAlt.whenPressed(new RestartDrive());
secondEnableAlt.whenPressed(new RestartDrive());
thirdEnableAlt.whenPressed(new RestartDrive());
}
| public OI() {
shootingButton.whenPressed(new TuneShooter());
firingButton.whenPressed(new Feed());
firstDisable.whenPressed(new StopAll());
secondDisable.whenPressed(new StopAll());
thirdDisable.whenPressed(new StopAll());
firstDisableAlt.whenPressed(new StopAll());
secondDisableAlt.whenPressed(new StopAll());
thirdDisableAlt.whenPressed(new StopAll());
firstEnable.whenPressed(new Restart());
secondEnable.whenPressed(new Restart());
thirdEnable.whenPressed(new Restart());
firstEnableAlt.whenPressed(new Restart());
secondEnableAlt.whenPressed(new Restart());
thirdEnableAlt.whenPressed(new Restart());
}
|
diff --git a/framework/src/play/db/jpa/JPASupport.java b/framework/src/play/db/jpa/JPASupport.java
index 5e118643..2f9c317b 100644
--- a/framework/src/play/db/jpa/JPASupport.java
+++ b/framework/src/play/db/jpa/JPASupport.java
@@ -1,690 +1,688 @@
package play.db.jpa;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PersistenceException;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.collection.PersistentMap;
import org.hibernate.ejb.HibernateEntityManager;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.proxy.HibernateProxy;
import play.Play;
import play.PlayPlugin;
import play.data.binding.BeanWrapper;
import play.data.binding.Binder;
import play.exceptions.UnexpectedException;
import play.mvc.Scope.Params;
/**
* A super class for JPA entities
*/
@MappedSuperclass
public class JPASupport implements Serializable {
public transient boolean willBeSaved = false;
public static <T extends JPASupport> T create(Class type, String name, Map<String, String[]> params) {
try {
Object model = type.newInstance();
return (T) edit(model, name, params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T extends JPASupport> T edit(String name, Params params) {
return (T) edit(this, name, params.all());
}
public static <T extends JPASupport> T edit(Object o, String name, Map<String, String[]> params) {
try {
BeanWrapper bw = new BeanWrapper(o.getClass());
bw.bind(name, o.getClass(), params, "", o);
// relations
Set<Field> fields = new HashSet<Field>();
Class clazz = o.getClass();
while (!clazz.equals(JPASupport.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Field field : fields) {
boolean isEntity = false;
String relation = null;
boolean multiple = false;
//
if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) {
isEntity = true;
relation = field.getType().getName();
}
if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) {
Class fieldType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isEntity = true;
relation = fieldType.getName();
multiple = true;
}
if (isEntity) {
if (multiple && Collection.class.isAssignableFrom(field.getType())) {
Collection l = new ArrayList();
if (Set.class.isAssignableFrom(field.getType())) {
l = new HashSet();
}
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null) {
for (String _id : ids) {
if (_id.equals("")) {
continue;
}
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(_id, findKeyType(Play.classloader.loadClass(relation))));
l.add(q.getSingleResult());
}
}
bw.set(field.getName(), o, l);
} else {
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null && ids.length > 0 && !ids[0].equals("")) {
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(ids[0], findKeyType(Play.classloader.loadClass(relation))));
Object to = q.getSingleResult();
bw.set(field.getName(), o, to);
- } else {
- bw.set(field.getName(), o, null);
}
}
}
if (field.getType().equals(FileAttachment.class)) {
FileAttachment fileAttachment = ((FileAttachment) field.get(o));
if (fileAttachment == null) {
fileAttachment = new FileAttachment(o, field.getName());
bw.set(field.getName(), o, fileAttachment);
}
File file = Params.current().get(name + "." + field.getName(), File.class);
if (file != null && file.exists() && file.length() > 0) {
fileAttachment.set(Params.current().get(name + "." + field.getName(), File.class));
fileAttachment.filename = file.getName();
} else {
String df = Params.current().get(name + "." + field.getName() + "_delete_", String.class);
if (df != null && df.equals("true")) {
fileAttachment.delete();
bw.set(field.getName(), o, null);
}
}
}
}
return (T) o;
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
/**
* store (ie insert) the entity.
*/
public <T extends JPASupport> T save() {
if (!em().contains(this)) {
em().persist(this);
PlayPlugin.postEvent("JPASupport.objectPersisted", this);
}
avoidCascadeSaveLoops.set(new ArrayList<JPASupport>());
try {
saveAndCascade(true);
} finally {
avoidCascadeSaveLoops.get().clear();
}
try {
em().flush();
} catch (PersistenceException e) {
if (e.getCause() instanceof GenericJDBCException) {
throw new PersistenceException(((GenericJDBCException) e.getCause()).getSQL());
} else {
throw e;
}
}
avoidCascadeSaveLoops.set(new ArrayList<JPASupport>());
try {
saveAndCascade(false);
} finally {
avoidCascadeSaveLoops.get().clear();
}
return (T) this;
}
static transient ThreadLocal<List<JPASupport>> avoidCascadeSaveLoops = new ThreadLocal<List<JPASupport>>();
private void saveAndCascade(boolean willBeSaved) {
this.willBeSaved = willBeSaved;
if (avoidCascadeSaveLoops.get().contains(this)) {
return;
} else {
avoidCascadeSaveLoops.get().add(this);
PlayPlugin.postEvent("JPASupport.objectUpdated", this);
}
// Cascade save
try {
for (Field field : this.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (Modifier.isTransient(field.getModifiers())) {
continue;
}
boolean doCascade = false;
if (field.isAnnotationPresent(OneToOne.class)) {
doCascade = cascadeAll(field.getAnnotation(OneToOne.class).cascade());
}
if (field.isAnnotationPresent(OneToMany.class)) {
doCascade = cascadeAll(field.getAnnotation(OneToMany.class).cascade());
}
if (field.isAnnotationPresent(ManyToOne.class)) {
doCascade = cascadeAll(field.getAnnotation(ManyToOne.class).cascade());
}
if (field.isAnnotationPresent(ManyToMany.class)) {
doCascade = cascadeAll(field.getAnnotation(ManyToMany.class).cascade());
}
if (doCascade) {
Object value = field.get(this);
if (value == null) {
continue;
}
if (value instanceof PersistentMap) {
if (((PersistentMap) value).wasInitialized()) {
for (Object o : ((Map) value).values()) {
if (o instanceof JPASupport) {
((JPASupport) o).saveAndCascade(willBeSaved);
}
}
}
continue;
}
if (value instanceof PersistentCollection) {
if (((PersistentCollection) value).wasInitialized()) {
for (Object o : (Collection) value) {
if (o instanceof JPASupport) {
((JPASupport) o).saveAndCascade(willBeSaved);
}
}
}
continue;
}
if (value instanceof HibernateProxy && value instanceof JPASupport) {
if (!((HibernateProxy) value).getHibernateLazyInitializer().isUninitialized()) {
((JPASupport) ((HibernateProxy) value).getHibernateLazyInitializer().getImplementation()).saveAndCascade(willBeSaved);
}
continue;
}
if (value instanceof JPASupport) {
((JPASupport) value).saveAndCascade(willBeSaved);
continue;
}
}
}
} catch (Exception e) {
throw new UnexpectedException("During cascading save()", e);
}
}
static boolean cascadeAll(CascadeType[] types) {
for (CascadeType cascadeType : types) {
if (cascadeType == CascadeType.ALL || cascadeType == CascadeType.PERSIST) {
return true;
}
}
return false;
}
/**
* Refresh the entity state.
*/
public <T extends JPASupport> T refresh() {
em().refresh(this);
return (T) this;
}
/**
* Merge this object to obtain a managed entity (usefull when the object comes from the Cache).
*/
public <T extends JPASupport> T merge() {
return (T) em().merge(this);
}
/**
* Delete the entity.
* @return The deleted entity.
*/
public <T extends JPASupport> T delete() {
try {
avoidCascadeSaveLoops.set(new ArrayList<JPASupport>());
try {
saveAndCascade(true);
} finally {
avoidCascadeSaveLoops.get().clear();
}
em().remove(this);
try {
em().flush();
} catch (PersistenceException e) {
if (e.getCause() instanceof GenericJDBCException) {
throw new PersistenceException(((GenericJDBCException) e.getCause()).getSQL());
} else {
throw e;
}
}
avoidCascadeSaveLoops.set(new ArrayList<JPASupport>());
try {
saveAndCascade(false);
} finally {
avoidCascadeSaveLoops.get().clear();
}
PlayPlugin.postEvent("JPASupport.objectDeleted", this);
return (T) this;
} catch (PersistenceException e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public static <T extends JPASupport> T create(String name, Params params) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Count entities
* @return number of entities of this class
*/
public static long count() {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Count entities with a special query.
* Example : Long moderatedPosts = Post.count("moderated", true);
* @param query HQL query or shortcut
* @param params Params to bind to the query
* @return A long
*/
public static long count(String query, Object... params) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Find all entities of this type
*/
public static <T extends JPASupport> List<T> findAll() {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Find the entity with the corresponding id.
* @param id The entity id
* @return The entity
*/
public static <T extends JPASupport> T findById(Object id) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Prepare a query to find entities.
* @param query HQL query or shortcut
* @param params Params to bind to the query
* @return A JPAQuery
*/
public static JPAQuery find(String query, Object... params) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Try all()
*/
@Deprecated
public static JPAQuery find() {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Prepare a query to find *all* entities.
* @return A JPAQuery
*/
public static JPAQuery all() {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Batch delete of entities
* @param query HQL query or shortcut
* @param params Params to bind to the query
* @return Number of entities deleted
*/
public static int delete(String query, Object... params) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Delete all entities
* @return Number of entities deleted
*/
public static int deleteAll() {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* find one item matching the parametrized query
* @param <T>
* @param query the parametrized query expressed in OQL
* @param params parameters of the query
* @return <T> the first item matching the query or null
*/
@Deprecated
public static <T extends JPASupport> T findOneBy(String query, Object... params) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* find all items matching a parametrized query
* @param <T>
* @param query the parametrized query expressed in OQL
* @param params parameters of the query
* @return a list<T> of items matching the query
*/
@Deprecated
public static <T extends JPASupport> List<T> findBy(String query, Object... params) {
throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
}
/**
* Retrieve the current entityManager
* @return the current entityManager
*/
public static EntityManager em() {
return JPA.em();
}
/**
* Try em();
*/
@Deprecated
public static EntityManager getEntityManager() {
return JPA.em();
}
/**
* JPASupport instances a and b are equals if either <strong>a == b</strong> or a and b have same </strong>{@link #key key} and class</strong>
* @param other
* @return true if equality condition above is verified
*/
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if ((this == other)) {
return true;
}
if (!(this.getClass().equals(other.getClass()))) {
return false;
}
if (this.getEntityId() == null) {
return false;
}
return this.getEntityId().equals(((JPASupport) other).getEntityId());
}
@Override
public int hashCode() {
if (this.getEntityId() == null) {
return 0;
}
return this.getEntityId().hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + getEntityId() + "]";
}
/**
* A JPAQuery
*/
public static class JPAQuery {
public Query query;
public String sq;
public JPAQuery(String sq, Query query) {
this.query = query;
this.sq = sq;
}
public JPAQuery(Query query) {
this.query = query;
this.sq = query.toString();
}
/**
* Try first();
*/
@Deprecated
public <T> T one() {
try {
List<T> results = query.setMaxResults(1).getResultList();
if (results.size() == 0) {
return null;
}
return (T) results.get(0);
} catch (Exception e) {
throw new IllegalArgumentException("Error while executing query <strong>" + sq + "</strong>", e);
}
}
public <T> T first() {
return (T) one();
}
/**
* Bind a JPQL named parameter to the current query.
*/
public JPAQuery bind(String name, Object param) {
if (param.getClass().isArray()) {
param = Arrays.asList((Object[]) param);
}
if (param instanceof Integer) {
param = ((Integer) param).longValue();
}
query.setParameter(name, param);
return this;
}
/**
* Try fetch();
*/
@Deprecated
public <T> List<T> all() {
try {
return query.getResultList();
} catch (Exception e) {
throw new IllegalArgumentException("Error while executing query <strong>" + sq + "</strong>", e);
}
}
/**
* Retrieve all results of the query
* @return A list of entities
*/
public <T> List<T> fetch() {
return all();
}
/**
* Retrieve results of the query
* @param max Max results to fetch
* @return A list of entities
*/
public <T> List<T> fetch(int max) {
try {
query.setMaxResults(max);
return query.getResultList();
} catch (Exception e) {
throw new IllegalArgumentException("Error while executing query <strong>" + sq + "</strong>", e);
}
}
/**
* Set the position to start
* @param position Position of the first element
* @return A new query
*/
public <T> JPAQuery from(int position) {
query.setFirstResult(position);
return this;
}
/**
* Try fetch(page, length);
*/
@Deprecated
public <T> List<T> page(int page, int length) {
if (page < 1) {
page = 1;
}
query.setFirstResult((page - 1) * length);
query.setMaxResults(length);
try {
return query.getResultList();
} catch (Exception e) {
throw new IllegalArgumentException("Error while executing query <strong>" + sq + "</strong>", e);
}
}
/**
* Retrieve a page of result
* @param page Page number (start at 1)
* @param length (page length)
* @return a list of entities
*/
public <T> List<T> fetch(int page, int length) {
return page(page, length);
}
}
// File attachments
public void setupAttachment() {
for (Field field : getClass().getFields()) {
if (FileAttachment.class.isAssignableFrom(field.getType())) {
try {
FileAttachment attachment = (FileAttachment) field.get(this);
if (attachment != null) {
attachment.model = this;
attachment.name = field.getName();
}
} catch (Exception ex) {
throw new UnexpectedException(ex);
}
}
}
}
public void saveAttachment() {
for (Field field : getClass().getFields()) {
if (field.getType().equals(FileAttachment.class)) {
try {
FileAttachment attachment = (FileAttachment) field.get(this);
if (attachment != null) {
attachment.model = this;
attachment.name = field.getName();
attachment.save();
}
} catch (Exception ex) {
throw new UnexpectedException(ex);
}
}
}
}
// More utils
public static Object findKey(Object entity) {
try {
Class c = entity.getClass();
while (!c.equals(Object.class)) {
for (Field field : c.getDeclaredFields()) {
if (field.isAnnotationPresent(Id.class)) {
field.setAccessible(true);
return field.get(entity);
}
}
c = c.getSuperclass();
}
} catch (Exception e) {
throw new UnexpectedException("Error while determining the object @Id for an object of type " + entity.getClass());
}
return null;
}
public static Class findKeyType(Class c) {
try {
while (!c.equals(Object.class)) {
for (Field field : c.getDeclaredFields()) {
if (field.isAnnotationPresent(Id.class)) {
field.setAccessible(true);
return field.getType();
}
}
c = c.getSuperclass();
}
} catch (Exception e) {
throw new UnexpectedException("Error while determining the object @Id for an object of type " + c);
}
return null;
}
private transient Object key;
public Object getEntityId() {
if (key == null) {
key = findKey(this);
}
return key;
}
// Events
@PostLoad
public void onLoad() {
setupAttachment();
}
@PostPersist
@PostUpdate
public void onSave() {
saveAttachment();
}
private Session rawSession() {
return ((HibernateEntityManager) em()).getSession();
}
}
| true | true | public static <T extends JPASupport> T edit(Object o, String name, Map<String, String[]> params) {
try {
BeanWrapper bw = new BeanWrapper(o.getClass());
bw.bind(name, o.getClass(), params, "", o);
// relations
Set<Field> fields = new HashSet<Field>();
Class clazz = o.getClass();
while (!clazz.equals(JPASupport.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Field field : fields) {
boolean isEntity = false;
String relation = null;
boolean multiple = false;
//
if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) {
isEntity = true;
relation = field.getType().getName();
}
if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) {
Class fieldType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isEntity = true;
relation = fieldType.getName();
multiple = true;
}
if (isEntity) {
if (multiple && Collection.class.isAssignableFrom(field.getType())) {
Collection l = new ArrayList();
if (Set.class.isAssignableFrom(field.getType())) {
l = new HashSet();
}
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null) {
for (String _id : ids) {
if (_id.equals("")) {
continue;
}
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(_id, findKeyType(Play.classloader.loadClass(relation))));
l.add(q.getSingleResult());
}
}
bw.set(field.getName(), o, l);
} else {
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null && ids.length > 0 && !ids[0].equals("")) {
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(ids[0], findKeyType(Play.classloader.loadClass(relation))));
Object to = q.getSingleResult();
bw.set(field.getName(), o, to);
} else {
bw.set(field.getName(), o, null);
}
}
}
if (field.getType().equals(FileAttachment.class)) {
FileAttachment fileAttachment = ((FileAttachment) field.get(o));
if (fileAttachment == null) {
fileAttachment = new FileAttachment(o, field.getName());
bw.set(field.getName(), o, fileAttachment);
}
File file = Params.current().get(name + "." + field.getName(), File.class);
if (file != null && file.exists() && file.length() > 0) {
fileAttachment.set(Params.current().get(name + "." + field.getName(), File.class));
fileAttachment.filename = file.getName();
} else {
String df = Params.current().get(name + "." + field.getName() + "_delete_", String.class);
if (df != null && df.equals("true")) {
fileAttachment.delete();
bw.set(field.getName(), o, null);
}
}
}
}
return (T) o;
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
| public static <T extends JPASupport> T edit(Object o, String name, Map<String, String[]> params) {
try {
BeanWrapper bw = new BeanWrapper(o.getClass());
bw.bind(name, o.getClass(), params, "", o);
// relations
Set<Field> fields = new HashSet<Field>();
Class clazz = o.getClass();
while (!clazz.equals(JPASupport.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Field field : fields) {
boolean isEntity = false;
String relation = null;
boolean multiple = false;
//
if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) {
isEntity = true;
relation = field.getType().getName();
}
if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) {
Class fieldType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isEntity = true;
relation = fieldType.getName();
multiple = true;
}
if (isEntity) {
if (multiple && Collection.class.isAssignableFrom(field.getType())) {
Collection l = new ArrayList();
if (Set.class.isAssignableFrom(field.getType())) {
l = new HashSet();
}
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null) {
for (String _id : ids) {
if (_id.equals("")) {
continue;
}
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(_id, findKeyType(Play.classloader.loadClass(relation))));
l.add(q.getSingleResult());
}
}
bw.set(field.getName(), o, l);
} else {
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null && ids.length > 0 && !ids[0].equals("")) {
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(ids[0], findKeyType(Play.classloader.loadClass(relation))));
Object to = q.getSingleResult();
bw.set(field.getName(), o, to);
}
}
}
if (field.getType().equals(FileAttachment.class)) {
FileAttachment fileAttachment = ((FileAttachment) field.get(o));
if (fileAttachment == null) {
fileAttachment = new FileAttachment(o, field.getName());
bw.set(field.getName(), o, fileAttachment);
}
File file = Params.current().get(name + "." + field.getName(), File.class);
if (file != null && file.exists() && file.length() > 0) {
fileAttachment.set(Params.current().get(name + "." + field.getName(), File.class));
fileAttachment.filename = file.getName();
} else {
String df = Params.current().get(name + "." + field.getName() + "_delete_", String.class);
if (df != null && df.equals("true")) {
fileAttachment.delete();
bw.set(field.getName(), o, null);
}
}
}
}
return (T) o;
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
|
diff --git a/src/main/java/freemarker/core/EvalUtil.java b/src/main/java/freemarker/core/EvalUtil.java
index 7d443998..75b6e8cb 100644
--- a/src/main/java/freemarker/core/EvalUtil.java
+++ b/src/main/java/freemarker/core/EvalUtil.java
@@ -1,422 +1,422 @@
/*
* Copyright (c) 2003 The Visigoth Software Society. 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 acknowledgement:
* "This product includes software developed by the
* Visigoth Software Society (http://www.visigoths.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
* project contributors may be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact visigoths@visigoths.org.
*
* 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
* nor may "FreeMarker" or "Visigoth" appear in their names
* without prior written permission of the Visigoth Software Society.
*
* 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 VISIGOTH SOFTWARE SOCIETY 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 Visigoth Software Society. For more
* information on the Visigoth Software Society, please see
* http://www.visigoths.org/
*/
package freemarker.core;
import java.util.Date;
import freemarker.ext.beans.BeanModel;
import freemarker.ext.beans._BeansAPI;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateCollectionModel;
import freemarker.template.TemplateDateModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;
import freemarker.template.TemplateSequenceModel;
/**
* Internally used static utilities for evaluation expressions.
*/
class EvalUtil
{
static final int CMP_OP_EQUALS = 1;
static final int CMP_OP_NOT_EQUALS = 2;
static final int CMP_OP_LESS_THAN = 3;
static final int CMP_OP_GREATER_THAN = 4;
static final int CMP_OP_LESS_THAN_EQUALS = 5;
static final int CMP_OP_GREATER_THAN_EQUALS = 6;
// If you add a new operator here, update the "compare" and "cmpOpToString" methods!
// Prevents instantination.
private EvalUtil() { }
/**
* @param expr {@code null} is allowed, but may results in less helpful error messages
* @param env {@code null} is allowed, but may results in lower performance in classic-compatible mode
*/
static String modelToString(TemplateScalarModel model, Expression expr, Environment env)
throws TemplateModelException {
String value = model.getAsString();
if(value == null) {
if (env == null) env = Environment.getCurrentEnvironment();
if (env != null && env.isClassicCompatible()) {
return "";
} else {
throw newModelHasStoredNullException(String.class, model, expr);
}
}
return value;
}
/**
* @param expr {@code null} is allowed, but may results in less helpful error messages
*/
static Number modelToNumber(TemplateNumberModel model, Expression expr)
throws TemplateModelException
{
Number value = model.getAsNumber();
if(value == null) throw newModelHasStoredNullException(Number.class, model, expr);
return value;
}
/**
* @param expr {@code null} is allowed, but may results in less helpful error messages
*/
static Date modelToDate(TemplateDateModel model, Expression expr)
throws TemplateModelException, TemplateException
{
Date value = model.getAsDate();
if(value == null) throw newModelHasStoredNullException(Date.class, model, expr);
return value;
}
/** Signals the buggy case where we have a non-null model, but its wraps a null. */
private static TemplateModelException newModelHasStoredNullException(
Class expected, TemplateModel model, Expression expr) {
return new _TemplateModelException(expr, _TemplateModelException.modelHasStoredNullDescription(expected, model));
}
/**
* Compares two expressions according the rules of the FTL comparator operators.
*
* @param leftExp not {@code null}
* @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
* @param operatorString can be null {@code null}; the actual operator used, used for more accurate error message.
* @param rightExp not {@code null}
* @param env {@code null} is tolerated, but should be avoided
*/
static boolean compare(
Expression leftExp,
int operator, String operatorString,
Expression rightExp,
Expression defaultBlamed,
Environment env) throws TemplateException {
TemplateModel ltm = leftExp.eval(env);
TemplateModel rtm = rightExp.eval(env);
return compare(
ltm, leftExp,
operator, operatorString,
rtm, rightExp,
defaultBlamed,
false, false, false,
env);
}
/**
* Compares values according the rules of the FTL comparator operators; if the {@link Expression}-s are
* accessible, use {@link #compare(Expression, int, String, Expression, Expression, Environment)} instead, as
* that gives better error messages.
*
* @param leftValue maybe {@code null}, which will usually cause the appropriate {@link TemplateException}.
* @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
* @param rightValue maybe {@code null}, which will usually cause the appropriate {@link TemplateException}.
* @param env {@code null} is tolerated, but should be avoided
*/
static boolean compare(
TemplateModel leftValue, int operator, TemplateModel rightValue,
Environment env) throws TemplateException {
return compare(
leftValue, null,
operator, null,
rightValue, null,
null,
false, false, false,
env);
}
/**
* Same as {@link #compare(TemplateModel, int, TemplateModel, Environment)}, but if the two types are incompatible,
* they are treated as non-equal instead of throwing an exception. Comparing dates of different types will
* still throw an exception, however.
*/
static boolean compareLenient(
TemplateModel leftValue, int operator, TemplateModel rightValue,
Environment env) throws TemplateException {
return compare(
leftValue, null,
operator, null,
rightValue, null,
null,
true, false, false,
env);
}
private static final String DATE_OF_THE_COMPARISON_IS_OF_TYPE_UNKNOWN
= "date of the comparison is of UNKNOWN type (it's not known if it's date-only, time-only, or date-time), "
+ "and thus can't be used in a comparison.";
/**
* @param leftExp {@code null} is allowed, but may results in less helpful error messages
* @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
* @param operatorString can be null {@code null}; the actual operator used, used for more accurate error message.
* @param rightExp {@code null} is allowed, but may results in less helpful error messages
* @param defaultBlamed {@code null} allowed; the expression who to which error will point to if something goes
* wrong that is not specific to the left or right side expression, or if that expression is {@code null}.
* @param typeMismatchMeansNotEqual If the two types are incompatible, they are treated as non-equal instead
* of throwing an exception. Comparing dates of different types will still throw an exception, however.
* @param leftNullReturnsFalse if {@code true}, a {@code null} left value will not cause exception, but make the
* expression {@code false}.
* @param rightNullReturnsFalse if {@code true}, a {@code null} right value will not cause exception, but make the
* expression {@code false}.
*/
static boolean compare(
TemplateModel leftValue, Expression leftExp,
int operator, String operatorString,
TemplateModel rightValue, Expression rightExp,
Expression defaultBlamed,
boolean typeMismatchMeansNotEqual,
boolean leftNullReturnsFalse, boolean rightNullReturnsFalse,
Environment env) throws TemplateException {
if (leftValue == null) {
if (env != null && env.isClassicCompatible()) {
leftValue = TemplateScalarModel.EMPTY_STRING;
} else {
if (leftNullReturnsFalse) {
return false;
} else {
if (leftExp != null) {
throw InvalidReferenceException.getInstance(leftExp, env);
} else {
throw new _MiscTemplateException(defaultBlamed, env,
"The left operand of the comparison was undefined or null.");
}
}
}
}
if (rightValue == null) {
if (env != null && env.isClassicCompatible()) {
rightValue = TemplateScalarModel.EMPTY_STRING;
} else {
if (rightNullReturnsFalse) {
return false;
} else {
if (rightExp != null) {
throw InvalidReferenceException.getInstance(rightExp, env);
} else {
throw new _MiscTemplateException(defaultBlamed, env,
"The right operand of the comparison was undefined or null.");
}
}
}
}
final int cmpResult;
if (leftValue instanceof TemplateNumberModel && rightValue instanceof TemplateNumberModel) {
Number leftNum = EvalUtil.modelToNumber((TemplateNumberModel) leftValue, leftExp);
Number rightNum = EvalUtil.modelToNumber((TemplateNumberModel) rightValue, rightExp);
ArithmeticEngine ae =
env != null
? env.getArithmeticEngine()
: (leftExp != null
? leftExp.getTemplate().getArithmeticEngine()
: ArithmeticEngine.BIGDECIMAL_ENGINE);
try {
cmpResult = ae.compareNumbers(leftNum, rightNum);
} catch (RuntimeException e) {
throw new _MiscTemplateException(defaultBlamed, e, env, new Object[]
{ "Unexpected error while comparing two numbers: ", e });
}
} else if (leftValue instanceof TemplateDateModel && rightValue instanceof TemplateDateModel) {
TemplateDateModel leftDateModel = (TemplateDateModel) leftValue;
TemplateDateModel rightDateModel = (TemplateDateModel) rightValue;
int leftDateType = leftDateModel.getDateType();
int rightDateType = rightDateModel.getDateType();
if (leftDateType == TemplateDateModel.UNKNOWN || rightDateType == TemplateDateModel.UNKNOWN) {
String sideName;
Expression sideExp;
if (leftDateType == TemplateDateModel.UNKNOWN) {
sideName = "left";
sideExp = leftExp;
} else {
sideName = "right";
sideExp = rightExp;
}
throw new _MiscTemplateException(sideExp != null ? sideExp : defaultBlamed, env, new Object[] {
"The ", sideName, " ", DATE_OF_THE_COMPARISON_IS_OF_TYPE_UNKNOWN });
}
if (leftDateType != rightDateType) {
;
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
- "Can't compare dates of different types. Left date tpye is ",
+ "Can't compare dates of different types. Left date type is ",
TemplateDateModel.TYPE_NAMES.get(leftDateType), ", right date type is ",
TemplateDateModel.TYPE_NAMES.get(rightDateType), "." });
}
Date leftDate = EvalUtil.modelToDate(leftDateModel, leftExp);
Date rightDate = EvalUtil.modelToDate(rightDateModel, rightExp);
cmpResult = leftDate.compareTo(rightDate);
} else if (leftValue instanceof TemplateScalarModel && rightValue instanceof TemplateScalarModel) {
if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't use operator \"", cmpOpToString(operator, operatorString), "\" on string values." });
}
String leftString = EvalUtil.modelToString((TemplateScalarModel) leftValue, leftExp, env);
String rightString = EvalUtil.modelToString((TemplateScalarModel) rightValue, rightExp, env);
// FIXME NBC: Don't use the Collator here. That's locale-specific, but ==/!= should not be.
cmpResult = env.getCollator().compare(leftString, rightString);
} else if (leftValue instanceof TemplateBooleanModel && rightValue instanceof TemplateBooleanModel) {
if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't use operator \"", cmpOpToString(operator, operatorString), "\" on boolean values." });
}
boolean leftBool = ((TemplateBooleanModel) leftValue).getAsBoolean();
boolean rightBool = ((TemplateBooleanModel) rightValue).getAsBoolean();
cmpResult = (leftBool ? 1 : 0) - (rightBool ? 1 : 0);
} else if (env.isClassicCompatible()) {
String leftSting = leftExp.evalAndCoerceToString(env);
String rightString = rightExp.evalAndCoerceToString(env);
cmpResult = env.getCollator().compare(leftSting, rightString);
} else {
if (typeMismatchMeansNotEqual) {
if (operator == CMP_OP_EQUALS) {
return false;
} else if (operator == CMP_OP_NOT_EQUALS) {
return true;
}
// Falls through
}
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't compare values of these types. ",
"Allowed comparisons are between two numbers, two strings, or two dates.\n",
"Left hand operand is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(leftValue)), ".\n",
"Right hand operand is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(rightValue)), "." });
}
switch (operator) {
case CMP_OP_EQUALS: return cmpResult == 0;
case CMP_OP_NOT_EQUALS: return cmpResult != 0;
case CMP_OP_LESS_THAN: return cmpResult < 0;
case CMP_OP_GREATER_THAN: return cmpResult > 0;
case CMP_OP_LESS_THAN_EQUALS: return cmpResult <= 0;
case CMP_OP_GREATER_THAN_EQUALS: return cmpResult >= 0;
default: throw new RuntimeException("Unsupported comparator operator code: " + operator);
}
}
private static String cmpOpToString(int operator, String operatorString) {
if (operatorString != null) {
return operatorString;
} else {
switch (operator) {
case CMP_OP_EQUALS: return "equals";
case CMP_OP_NOT_EQUALS: return "not-equals";
case CMP_OP_LESS_THAN: return "less-than";
case CMP_OP_GREATER_THAN: return "greater-than";
case CMP_OP_LESS_THAN_EQUALS: return "less-than-equals";
case CMP_OP_GREATER_THAN_EQUALS: return "greater-than-equals";
default: return "???";
}
}
}
static String coerceModelToString(TemplateModel tm, Expression exp, String seqHint, Environment env) throws TemplateException {
if (tm instanceof TemplateNumberModel) {
return env.formatNumber(modelToNumber((TemplateNumberModel) tm, exp));
} else if (tm instanceof TemplateDateModel) {
TemplateDateModel dm = (TemplateDateModel) tm;
return env.formatDate(modelToDate(dm, exp), dm.getDateType());
} else if (tm instanceof TemplateScalarModel) {
return modelToString((TemplateScalarModel) tm, exp, env);
} else if(tm == null) {
if (env.isClassicCompatible()) {
return "";
} else {
if (exp != null) {
throw InvalidReferenceException.getInstance(exp, env);
} else {
throw new InvalidReferenceException(
"Null/missing value (no more informatoin avilable)",
env);
}
}
} else if (tm instanceof TemplateBooleanModel) {
// This should be before TemplateScalarModel, but automatic boolean-to-string is only non-error since 2.3.20
// (and before that when classic_compatible was true), so to keep backward compatibility we couldn't insert
// this before TemplateScalarModel.
boolean booleanValue = ((TemplateBooleanModel) tm).getAsBoolean();
int compatMode = env.getClassicCompatibleAsInt();
if (compatMode == 0) {
return env.formatBoolean(booleanValue);
} else {
if (compatMode == 1) {
return booleanValue ? "true" : "";
} else if (compatMode == 2) {
if (tm instanceof BeanModel) {
// In 2.1, bean-wrapped booleans where strings, so that has overridden the boolean behavior:
return _BeansAPI.getAsClassicCompatibleString((BeanModel) tm);
} else {
return booleanValue ? "true" : "";
}
} else {
throw new RuntimeException("Unsupported classic_compatible variation: " + compatMode);
}
}
} else {
if (env.isClassicCompatible() && tm instanceof BeanModel) {
return _BeansAPI.getAsClassicCompatibleString((BeanModel) tm);
} if (seqHint != null && (tm instanceof TemplateSequenceModel || tm instanceof TemplateCollectionModel)) {
throw new NonStringException(exp, tm, seqHint, env);
} else {
throw new NonStringException(exp, tm, env);
}
}
}
}
| true | true | static boolean compare(
TemplateModel leftValue, Expression leftExp,
int operator, String operatorString,
TemplateModel rightValue, Expression rightExp,
Expression defaultBlamed,
boolean typeMismatchMeansNotEqual,
boolean leftNullReturnsFalse, boolean rightNullReturnsFalse,
Environment env) throws TemplateException {
if (leftValue == null) {
if (env != null && env.isClassicCompatible()) {
leftValue = TemplateScalarModel.EMPTY_STRING;
} else {
if (leftNullReturnsFalse) {
return false;
} else {
if (leftExp != null) {
throw InvalidReferenceException.getInstance(leftExp, env);
} else {
throw new _MiscTemplateException(defaultBlamed, env,
"The left operand of the comparison was undefined or null.");
}
}
}
}
if (rightValue == null) {
if (env != null && env.isClassicCompatible()) {
rightValue = TemplateScalarModel.EMPTY_STRING;
} else {
if (rightNullReturnsFalse) {
return false;
} else {
if (rightExp != null) {
throw InvalidReferenceException.getInstance(rightExp, env);
} else {
throw new _MiscTemplateException(defaultBlamed, env,
"The right operand of the comparison was undefined or null.");
}
}
}
}
final int cmpResult;
if (leftValue instanceof TemplateNumberModel && rightValue instanceof TemplateNumberModel) {
Number leftNum = EvalUtil.modelToNumber((TemplateNumberModel) leftValue, leftExp);
Number rightNum = EvalUtil.modelToNumber((TemplateNumberModel) rightValue, rightExp);
ArithmeticEngine ae =
env != null
? env.getArithmeticEngine()
: (leftExp != null
? leftExp.getTemplate().getArithmeticEngine()
: ArithmeticEngine.BIGDECIMAL_ENGINE);
try {
cmpResult = ae.compareNumbers(leftNum, rightNum);
} catch (RuntimeException e) {
throw new _MiscTemplateException(defaultBlamed, e, env, new Object[]
{ "Unexpected error while comparing two numbers: ", e });
}
} else if (leftValue instanceof TemplateDateModel && rightValue instanceof TemplateDateModel) {
TemplateDateModel leftDateModel = (TemplateDateModel) leftValue;
TemplateDateModel rightDateModel = (TemplateDateModel) rightValue;
int leftDateType = leftDateModel.getDateType();
int rightDateType = rightDateModel.getDateType();
if (leftDateType == TemplateDateModel.UNKNOWN || rightDateType == TemplateDateModel.UNKNOWN) {
String sideName;
Expression sideExp;
if (leftDateType == TemplateDateModel.UNKNOWN) {
sideName = "left";
sideExp = leftExp;
} else {
sideName = "right";
sideExp = rightExp;
}
throw new _MiscTemplateException(sideExp != null ? sideExp : defaultBlamed, env, new Object[] {
"The ", sideName, " ", DATE_OF_THE_COMPARISON_IS_OF_TYPE_UNKNOWN });
}
if (leftDateType != rightDateType) {
;
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't compare dates of different types. Left date tpye is ",
TemplateDateModel.TYPE_NAMES.get(leftDateType), ", right date type is ",
TemplateDateModel.TYPE_NAMES.get(rightDateType), "." });
}
Date leftDate = EvalUtil.modelToDate(leftDateModel, leftExp);
Date rightDate = EvalUtil.modelToDate(rightDateModel, rightExp);
cmpResult = leftDate.compareTo(rightDate);
} else if (leftValue instanceof TemplateScalarModel && rightValue instanceof TemplateScalarModel) {
if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't use operator \"", cmpOpToString(operator, operatorString), "\" on string values." });
}
String leftString = EvalUtil.modelToString((TemplateScalarModel) leftValue, leftExp, env);
String rightString = EvalUtil.modelToString((TemplateScalarModel) rightValue, rightExp, env);
// FIXME NBC: Don't use the Collator here. That's locale-specific, but ==/!= should not be.
cmpResult = env.getCollator().compare(leftString, rightString);
} else if (leftValue instanceof TemplateBooleanModel && rightValue instanceof TemplateBooleanModel) {
if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't use operator \"", cmpOpToString(operator, operatorString), "\" on boolean values." });
}
boolean leftBool = ((TemplateBooleanModel) leftValue).getAsBoolean();
boolean rightBool = ((TemplateBooleanModel) rightValue).getAsBoolean();
cmpResult = (leftBool ? 1 : 0) - (rightBool ? 1 : 0);
} else if (env.isClassicCompatible()) {
String leftSting = leftExp.evalAndCoerceToString(env);
String rightString = rightExp.evalAndCoerceToString(env);
cmpResult = env.getCollator().compare(leftSting, rightString);
} else {
if (typeMismatchMeansNotEqual) {
if (operator == CMP_OP_EQUALS) {
return false;
} else if (operator == CMP_OP_NOT_EQUALS) {
return true;
}
// Falls through
}
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't compare values of these types. ",
"Allowed comparisons are between two numbers, two strings, or two dates.\n",
"Left hand operand is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(leftValue)), ".\n",
"Right hand operand is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(rightValue)), "." });
}
switch (operator) {
case CMP_OP_EQUALS: return cmpResult == 0;
case CMP_OP_NOT_EQUALS: return cmpResult != 0;
case CMP_OP_LESS_THAN: return cmpResult < 0;
case CMP_OP_GREATER_THAN: return cmpResult > 0;
case CMP_OP_LESS_THAN_EQUALS: return cmpResult <= 0;
case CMP_OP_GREATER_THAN_EQUALS: return cmpResult >= 0;
default: throw new RuntimeException("Unsupported comparator operator code: " + operator);
}
}
| static boolean compare(
TemplateModel leftValue, Expression leftExp,
int operator, String operatorString,
TemplateModel rightValue, Expression rightExp,
Expression defaultBlamed,
boolean typeMismatchMeansNotEqual,
boolean leftNullReturnsFalse, boolean rightNullReturnsFalse,
Environment env) throws TemplateException {
if (leftValue == null) {
if (env != null && env.isClassicCompatible()) {
leftValue = TemplateScalarModel.EMPTY_STRING;
} else {
if (leftNullReturnsFalse) {
return false;
} else {
if (leftExp != null) {
throw InvalidReferenceException.getInstance(leftExp, env);
} else {
throw new _MiscTemplateException(defaultBlamed, env,
"The left operand of the comparison was undefined or null.");
}
}
}
}
if (rightValue == null) {
if (env != null && env.isClassicCompatible()) {
rightValue = TemplateScalarModel.EMPTY_STRING;
} else {
if (rightNullReturnsFalse) {
return false;
} else {
if (rightExp != null) {
throw InvalidReferenceException.getInstance(rightExp, env);
} else {
throw new _MiscTemplateException(defaultBlamed, env,
"The right operand of the comparison was undefined or null.");
}
}
}
}
final int cmpResult;
if (leftValue instanceof TemplateNumberModel && rightValue instanceof TemplateNumberModel) {
Number leftNum = EvalUtil.modelToNumber((TemplateNumberModel) leftValue, leftExp);
Number rightNum = EvalUtil.modelToNumber((TemplateNumberModel) rightValue, rightExp);
ArithmeticEngine ae =
env != null
? env.getArithmeticEngine()
: (leftExp != null
? leftExp.getTemplate().getArithmeticEngine()
: ArithmeticEngine.BIGDECIMAL_ENGINE);
try {
cmpResult = ae.compareNumbers(leftNum, rightNum);
} catch (RuntimeException e) {
throw new _MiscTemplateException(defaultBlamed, e, env, new Object[]
{ "Unexpected error while comparing two numbers: ", e });
}
} else if (leftValue instanceof TemplateDateModel && rightValue instanceof TemplateDateModel) {
TemplateDateModel leftDateModel = (TemplateDateModel) leftValue;
TemplateDateModel rightDateModel = (TemplateDateModel) rightValue;
int leftDateType = leftDateModel.getDateType();
int rightDateType = rightDateModel.getDateType();
if (leftDateType == TemplateDateModel.UNKNOWN || rightDateType == TemplateDateModel.UNKNOWN) {
String sideName;
Expression sideExp;
if (leftDateType == TemplateDateModel.UNKNOWN) {
sideName = "left";
sideExp = leftExp;
} else {
sideName = "right";
sideExp = rightExp;
}
throw new _MiscTemplateException(sideExp != null ? sideExp : defaultBlamed, env, new Object[] {
"The ", sideName, " ", DATE_OF_THE_COMPARISON_IS_OF_TYPE_UNKNOWN });
}
if (leftDateType != rightDateType) {
;
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't compare dates of different types. Left date type is ",
TemplateDateModel.TYPE_NAMES.get(leftDateType), ", right date type is ",
TemplateDateModel.TYPE_NAMES.get(rightDateType), "." });
}
Date leftDate = EvalUtil.modelToDate(leftDateModel, leftExp);
Date rightDate = EvalUtil.modelToDate(rightDateModel, rightExp);
cmpResult = leftDate.compareTo(rightDate);
} else if (leftValue instanceof TemplateScalarModel && rightValue instanceof TemplateScalarModel) {
if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't use operator \"", cmpOpToString(operator, operatorString), "\" on string values." });
}
String leftString = EvalUtil.modelToString((TemplateScalarModel) leftValue, leftExp, env);
String rightString = EvalUtil.modelToString((TemplateScalarModel) rightValue, rightExp, env);
// FIXME NBC: Don't use the Collator here. That's locale-specific, but ==/!= should not be.
cmpResult = env.getCollator().compare(leftString, rightString);
} else if (leftValue instanceof TemplateBooleanModel && rightValue instanceof TemplateBooleanModel) {
if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't use operator \"", cmpOpToString(operator, operatorString), "\" on boolean values." });
}
boolean leftBool = ((TemplateBooleanModel) leftValue).getAsBoolean();
boolean rightBool = ((TemplateBooleanModel) rightValue).getAsBoolean();
cmpResult = (leftBool ? 1 : 0) - (rightBool ? 1 : 0);
} else if (env.isClassicCompatible()) {
String leftSting = leftExp.evalAndCoerceToString(env);
String rightString = rightExp.evalAndCoerceToString(env);
cmpResult = env.getCollator().compare(leftSting, rightString);
} else {
if (typeMismatchMeansNotEqual) {
if (operator == CMP_OP_EQUALS) {
return false;
} else if (operator == CMP_OP_NOT_EQUALS) {
return true;
}
// Falls through
}
throw new _MiscTemplateException(defaultBlamed, env, new Object[] {
"Can't compare values of these types. ",
"Allowed comparisons are between two numbers, two strings, or two dates.\n",
"Left hand operand is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(leftValue)), ".\n",
"Right hand operand is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(rightValue)), "." });
}
switch (operator) {
case CMP_OP_EQUALS: return cmpResult == 0;
case CMP_OP_NOT_EQUALS: return cmpResult != 0;
case CMP_OP_LESS_THAN: return cmpResult < 0;
case CMP_OP_GREATER_THAN: return cmpResult > 0;
case CMP_OP_LESS_THAN_EQUALS: return cmpResult <= 0;
case CMP_OP_GREATER_THAN_EQUALS: return cmpResult >= 0;
default: throw new RuntimeException("Unsupported comparator operator code: " + operator);
}
}
|
diff --git a/src/jircbot/commands/jIBCTTell.java b/src/jircbot/commands/jIBCTTell.java
index d58c2be..a8173a1 100644
--- a/src/jircbot/commands/jIBCTTell.java
+++ b/src/jircbot/commands/jIBCTTell.java
@@ -1,73 +1,72 @@
package jircbot.commands;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import org.jibble.pircbot.PircBot;
public class jIBCTTell extends jIBCommand {
private final int MAX_MSG_QUEUE = 25;
private class storedMsg {
Date storedDate;
String message;
String sender;
public storedMsg(Date storedDate, String message, String sender) {
super();
this.storedDate = storedDate;
this.message = message;
this.sender = sender;
}
}
private HashMap<String, ArrayList<storedMsg>> msgMap = new HashMap<String, ArrayList<storedMsg>>();
@Override
public String getCommandName() {
return "tell";
}
@Override
public void runHandleMessage(PircBot bot, String channel, String sender, String message) {
- sender = sender.toLowerCase();
String[] splitMsg = message.split(" ", 3);
if(splitMsg[0].equals(getCommandName())) {
if(splitMsg.length == 3) {
// Add the tell message
// - [command] [target user] [message]
ArrayList<storedMsg> msglist;
if((msglist = msgMap.get(splitMsg[1])) == null) {
msglist = new ArrayList<storedMsg>();
- msgMap.put(splitMsg[1], msglist);
+ msgMap.put(splitMsg[1].toLowerCase(), msglist);
}
if(msglist.size() <= MAX_MSG_QUEUE) {
msglist.add(new storedMsg(new Date(), splitMsg[2], sender));
// Tell the sender that the 'tell' was added for 'target user'
bot.sendMessage(sender, "I will tell " + splitMsg[1] + " the next time he talks in channel.");
} else {
bot.sendMessage(sender, splitMsg[1] + " already has the max (" +
MAX_MSG_QUEUE + ") number of messages saved for him.");
}
} else {
bot.sendMessage(sender, "The correct syntax is: !tell username Remember the milk");
}
}
// Now we need to check to see if sender has any waiting messages.
ArrayList<storedMsg> msgList;
- if((msgList = msgMap.remove(sender)) != null) {
+ if((msgList = msgMap.remove(sender.toLowerCase())) != null) {
Iterator<storedMsg> i = msgList.iterator();
while(i.hasNext()) {
storedMsg curMsg = i.next();
bot.sendMessage(sender, curMsg.sender
+ " sent the following to you on "
+ curMsg.storedDate.toString()
+ " : " + curMsg.message);
}
}
}
}
| false | true | public void runHandleMessage(PircBot bot, String channel, String sender, String message) {
sender = sender.toLowerCase();
String[] splitMsg = message.split(" ", 3);
if(splitMsg[0].equals(getCommandName())) {
if(splitMsg.length == 3) {
// Add the tell message
// - [command] [target user] [message]
ArrayList<storedMsg> msglist;
if((msglist = msgMap.get(splitMsg[1])) == null) {
msglist = new ArrayList<storedMsg>();
msgMap.put(splitMsg[1], msglist);
}
if(msglist.size() <= MAX_MSG_QUEUE) {
msglist.add(new storedMsg(new Date(), splitMsg[2], sender));
// Tell the sender that the 'tell' was added for 'target user'
bot.sendMessage(sender, "I will tell " + splitMsg[1] + " the next time he talks in channel.");
} else {
bot.sendMessage(sender, splitMsg[1] + " already has the max (" +
MAX_MSG_QUEUE + ") number of messages saved for him.");
}
} else {
bot.sendMessage(sender, "The correct syntax is: !tell username Remember the milk");
}
}
// Now we need to check to see if sender has any waiting messages.
ArrayList<storedMsg> msgList;
if((msgList = msgMap.remove(sender)) != null) {
Iterator<storedMsg> i = msgList.iterator();
while(i.hasNext()) {
storedMsg curMsg = i.next();
bot.sendMessage(sender, curMsg.sender
+ " sent the following to you on "
+ curMsg.storedDate.toString()
+ " : " + curMsg.message);
}
}
}
| public void runHandleMessage(PircBot bot, String channel, String sender, String message) {
String[] splitMsg = message.split(" ", 3);
if(splitMsg[0].equals(getCommandName())) {
if(splitMsg.length == 3) {
// Add the tell message
// - [command] [target user] [message]
ArrayList<storedMsg> msglist;
if((msglist = msgMap.get(splitMsg[1])) == null) {
msglist = new ArrayList<storedMsg>();
msgMap.put(splitMsg[1].toLowerCase(), msglist);
}
if(msglist.size() <= MAX_MSG_QUEUE) {
msglist.add(new storedMsg(new Date(), splitMsg[2], sender));
// Tell the sender that the 'tell' was added for 'target user'
bot.sendMessage(sender, "I will tell " + splitMsg[1] + " the next time he talks in channel.");
} else {
bot.sendMessage(sender, splitMsg[1] + " already has the max (" +
MAX_MSG_QUEUE + ") number of messages saved for him.");
}
} else {
bot.sendMessage(sender, "The correct syntax is: !tell username Remember the milk");
}
}
// Now we need to check to see if sender has any waiting messages.
ArrayList<storedMsg> msgList;
if((msgList = msgMap.remove(sender.toLowerCase())) != null) {
Iterator<storedMsg> i = msgList.iterator();
while(i.hasNext()) {
storedMsg curMsg = i.next();
bot.sendMessage(sender, curMsg.sender
+ " sent the following to you on "
+ curMsg.storedDate.toString()
+ " : " + curMsg.message);
}
}
}
|
diff --git a/src/test/java/HelloWorldIT.java b/src/test/java/HelloWorldIT.java
index b0424c7..ab7ab6a 100644
--- a/src/test/java/HelloWorldIT.java
+++ b/src/test/java/HelloWorldIT.java
@@ -1,12 +1,12 @@
import org.jsoup.Jsoup;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class HelloWorldIT {
@Test
public void testHelloWorld() throws Exception {
- assertTrue(Jsoup.connect("http://localhost:18080/maven-vbox-plugin-example").get().html().contains("Hello World"));
+ assertTrue(Jsoup.connect("http://192.168.56.2:8080/maven-vbox-plugin-example").get().html().contains("Hello World"));
}
}
| true | true | public void testHelloWorld() throws Exception {
assertTrue(Jsoup.connect("http://localhost:18080/maven-vbox-plugin-example").get().html().contains("Hello World"));
}
| public void testHelloWorld() throws Exception {
assertTrue(Jsoup.connect("http://192.168.56.2:8080/maven-vbox-plugin-example").get().html().contains("Hello World"));
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem.core/src/org/eclipse/tcf/te/tcf/filesystem/core/model/FSModel.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem.core/src/org/eclipse/tcf/te/tcf/filesystem/core/model/FSModel.java
index e9941fb77..1c5229336 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem.core/src/org/eclipse/tcf/te/tcf/filesystem/core/model/FSModel.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem.core/src/org/eclipse/tcf/te/tcf/filesystem/core/model/FSModel.java
@@ -1,148 +1,149 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.filesystem.core.model;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.te.tcf.filesystem.core.activator.CorePlugin;
import org.eclipse.tcf.te.tcf.filesystem.core.nls.Messages;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel;
/**
* The file system model implementation.
*/
public final class FSModel implements ITreeNodeModel {
/* default */static final String FSMODEL_KEY = CorePlugin.getUniqueIdentifier() + ".file.system"; //$NON-NLS-1$
/**
* Get the file system model of the peer model. If it does not
* exist yet, create a new instance and store it.
*
* @param peerModel The peer model
* @return The file system model connected this peer model.
*/
public static FSModel getFSModel(final IPeerModel peerModel) {
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- if (peerModel != null) {
- FSModel model = (FSModel) peerModel.getProperty(FSMODEL_KEY);
- if (model == null) {
- model = new FSModel(peerModel);
- peerModel.setProperty(FSMODEL_KEY, model);
- }
+ final AtomicReference<FSModel> model = new AtomicReference<FSModel>();
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ if (peerModel != null) {
+ model.set((FSModel) peerModel.getProperty(FSMODEL_KEY));
+ if (model.get() == null) {
+ model.set(new FSModel(peerModel));
+ peerModel.setProperty(FSMODEL_KEY, model.get());
}
}
- };
+ }
+ };
- if (Protocol.isDispatchThread()) runnable.run();
- else Protocol.invokeAndWait(runnable);
+ if (Protocol.isDispatchThread()) runnable.run();
+ else Protocol.invokeAndWait(runnable);
- return peerModel != null ? (FSModel)peerModel.getProperty(FSMODEL_KEY) : null;
+ return model.get();
}
// The root node of the peer model
private FSTreeNode root;
private IPeerModel peerNode;
/**
* Create a File System Model.
*/
/* default */ FSModel(IPeerModel peerNode) {
this.peerNode = peerNode;
}
/**
* Get the root node of the peer model.
*
* @return The root node.
*/
@Override
public FSTreeNode getRoot() {
if(root == null) {
root = createRoot();
}
return root;
}
/**
* Create a root node for the specified peer.
*
* @param peerNode The peer.
*/
/* default */ FSTreeNode createRoot() {
if (Protocol.isDispatchThread()) {
return createRootNode(peerNode);
}
else {
final AtomicReference<FSTreeNode> ref = new AtomicReference<FSTreeNode>();
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
ref.set(createRoot());
}
});
return ref.get();
}
}
/**
* Create a root node for the peer.
*
* @param peerNode The peer.
* @return The root file system node.
*/
public static FSTreeNode createRootNode(IPeerModel peerNode) {
FSTreeNode node = new FSTreeNode();
node.type = "FSRootNode"; //$NON-NLS-1$
node.peerNode = peerNode;
node.name = Messages.FSTreeNodeContentProvider_rootNode_label;
return node;
}
/**
* Create a file node under the folder specified folder using the new name.
*
* @param name The file's name.
* @param folder The parent folder.
* @return The file tree node.
*/
public static FSTreeNode createFileNode(String name, FSTreeNode folder) {
return createTreeNode(name, "FSFileNode", folder); //$NON-NLS-1$
}
/**
* Create a folder node under the folder specified folder using the new name.
*
* @param name The folder's name.
* @param folder The parent folder.
* @return The folder tree node.
*/
public static FSTreeNode createFolderNode(String name, FSTreeNode folder) {
return createTreeNode(name, "FSDirNode", folder); //$NON-NLS-1$
}
/**
* Create a tree node under the folder specified folder using the new name.
*
* @param name The tree node's name.
* @param type The new node's type.
* @param folder The parent folder.
* @return The tree node.
*/
private static FSTreeNode createTreeNode(String name, String type, FSTreeNode folder) {
FSTreeNode node = new FSTreeNode();
node.name = name;
node.parent = folder;
node.peerNode = folder.peerNode;
node.type = type;
return node;
}
}
| false | true | public static FSModel getFSModel(final IPeerModel peerModel) {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (peerModel != null) {
FSModel model = (FSModel) peerModel.getProperty(FSMODEL_KEY);
if (model == null) {
model = new FSModel(peerModel);
peerModel.setProperty(FSMODEL_KEY, model);
}
}
}
};
if (Protocol.isDispatchThread()) runnable.run();
else Protocol.invokeAndWait(runnable);
return peerModel != null ? (FSModel)peerModel.getProperty(FSMODEL_KEY) : null;
}
| public static FSModel getFSModel(final IPeerModel peerModel) {
final AtomicReference<FSModel> model = new AtomicReference<FSModel>();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (peerModel != null) {
model.set((FSModel) peerModel.getProperty(FSMODEL_KEY));
if (model.get() == null) {
model.set(new FSModel(peerModel));
peerModel.setProperty(FSMODEL_KEY, model.get());
}
}
}
};
if (Protocol.isDispatchThread()) runnable.run();
else Protocol.invokeAndWait(runnable);
return model.get();
}
|
diff --git a/relevance_filter/src/main/java/com/edge/twitter_research/relevance_filter/TopEmoticonsCalculator.java b/relevance_filter/src/main/java/com/edge/twitter_research/relevance_filter/TopEmoticonsCalculator.java
index 0e22043..3e4cd32 100644
--- a/relevance_filter/src/main/java/com/edge/twitter_research/relevance_filter/TopEmoticonsCalculator.java
+++ b/relevance_filter/src/main/java/com/edge/twitter_research/relevance_filter/TopEmoticonsCalculator.java
@@ -1,102 +1,102 @@
package com.edge.twitter_research.relevance_filter;
import com.edge.twitter_research.core.KijiConnection;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.kiji.mapreduce.MapReduceJob;
import org.kiji.mapreduce.gather.KijiGatherJobBuilder;
import org.kiji.mapreduce.output.TextMapReduceJobOutput;
import org.kiji.schema.*;
import java.io.IOException;
public class TopEmoticonsCalculator extends Configured{
public MapReduceJob mapReduceJob = null;
public static Logger logger =
Logger.getLogger(TopEmoticonsCalculator.class);
public static int pageSize;
public static int maxVersions;
public TopEmoticonsCalculator (String outputFilePath,
String log4jPropertiesFilePath,
String inputTableName){
PropertyConfigurator.configure(log4jPropertiesFilePath);
try{
setConf(HBaseConfiguration.addHbaseResources(new Configuration(true)));
KijiURI tableUri =
KijiURI.newBuilder(String.format("kiji://.env/default/%s", inputTableName)).build();
this.mapReduceJob = KijiGatherJobBuilder.create()
.withConf(getConf())
.withGatherer(TopEmoticonsGatherer.class)
.withReducer(TopEmoticonsReducer.class)
.withInputTable(tableUri)
.withOutput(new TextMapReduceJobOutput(new Path(outputFilePath), 1))
.build();
}catch (IOException ioException){
logger.error("IO Exception while configuring MapReduce Job", ioException);
System.exit(1);
} catch (Exception unknownException){
logger.error("Unknown Exception while configuring MapReduce Job", unknownException);
System.exit(1);
}
}
public static void main(String[] args){
if (args.length < 4){
System.out.println("Usage: TopEmoticonsCalculator " +
"<relevance_filter_root> " +
- "<input_table_name>" +
+ "<input_table_name> " +
"<HDFS_output_file_path> " +
"<page_size> " +
"<max_num_versions>");
return;
}
- pageSize = Integer.parseInt(args[2]);
+ pageSize = Integer.parseInt(args[3]);
maxVersions = HConstants.ALL_VERSIONS;
- if (args.length == 4)
- maxVersions = Integer.parseInt(args[3]);
+ if (args.length == 5)
+ maxVersions = Integer.parseInt(args[4]);
TopEmoticonsCalculator topEmoticonsCalculator =
new TopEmoticonsCalculator(args[2],
args[0] + "/" + Constants.LOG4J_PROPERTIES_FILE_PATH,
args[1]);
boolean isSuccessful = false;
if (topEmoticonsCalculator.mapReduceJob != null){
try{
isSuccessful = topEmoticonsCalculator.mapReduceJob.run();
}catch (Exception unknownException){
logger.error("Unknown Exception while running MapReduce Job", unknownException);
System.exit(1);
}
}
String result = isSuccessful ? "Successful" : "Failure";
logger.info(result);
}
}
| false | true | public static void main(String[] args){
if (args.length < 4){
System.out.println("Usage: TopEmoticonsCalculator " +
"<relevance_filter_root> " +
"<input_table_name>" +
"<HDFS_output_file_path> " +
"<page_size> " +
"<max_num_versions>");
return;
}
pageSize = Integer.parseInt(args[2]);
maxVersions = HConstants.ALL_VERSIONS;
if (args.length == 4)
maxVersions = Integer.parseInt(args[3]);
TopEmoticonsCalculator topEmoticonsCalculator =
new TopEmoticonsCalculator(args[2],
args[0] + "/" + Constants.LOG4J_PROPERTIES_FILE_PATH,
args[1]);
boolean isSuccessful = false;
if (topEmoticonsCalculator.mapReduceJob != null){
try{
isSuccessful = topEmoticonsCalculator.mapReduceJob.run();
}catch (Exception unknownException){
logger.error("Unknown Exception while running MapReduce Job", unknownException);
System.exit(1);
}
}
String result = isSuccessful ? "Successful" : "Failure";
logger.info(result);
}
| public static void main(String[] args){
if (args.length < 4){
System.out.println("Usage: TopEmoticonsCalculator " +
"<relevance_filter_root> " +
"<input_table_name> " +
"<HDFS_output_file_path> " +
"<page_size> " +
"<max_num_versions>");
return;
}
pageSize = Integer.parseInt(args[3]);
maxVersions = HConstants.ALL_VERSIONS;
if (args.length == 5)
maxVersions = Integer.parseInt(args[4]);
TopEmoticonsCalculator topEmoticonsCalculator =
new TopEmoticonsCalculator(args[2],
args[0] + "/" + Constants.LOG4J_PROPERTIES_FILE_PATH,
args[1]);
boolean isSuccessful = false;
if (topEmoticonsCalculator.mapReduceJob != null){
try{
isSuccessful = topEmoticonsCalculator.mapReduceJob.run();
}catch (Exception unknownException){
logger.error("Unknown Exception while running MapReduce Job", unknownException);
System.exit(1);
}
}
String result = isSuccessful ? "Successful" : "Failure";
logger.info(result);
}
|
diff --git a/AlkitabConverter/src/yuku/alkitabconverter/util/TextDb.java b/AlkitabConverter/src/yuku/alkitabconverter/util/TextDb.java
index d2f91393..3d32030d 100644
--- a/AlkitabConverter/src/yuku/alkitabconverter/util/TextDb.java
+++ b/AlkitabConverter/src/yuku/alkitabconverter/util/TextDb.java
@@ -1,254 +1,254 @@
package yuku.alkitabconverter.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import yuku.alkitab.base.model.Ari;
public class TextDb {
public static final String TAG = TextDb.class.getSimpleName();
public interface TextProcessor {
void process(int ari, VerseState verseState);
}
public static class VerseState {
// was: "public int menjorok;" but no longer used
public String text;
}
TreeMap<Integer, VerseState> map = new TreeMap<Integer, VerseState>();
public String append(int bookId, int chapter_1, int verse_1, String s, int currentIndent) {
return append(Ari.encode(bookId, chapter_1, verse_1), s, currentIndent);
}
public String append(int bookId, int chapter_1, int verse_1, String s, int currentIndent, String separatorWhenExisting) {
return append(Ari.encode(bookId, chapter_1, verse_1), s, currentIndent, separatorWhenExisting);
}
/**
* @param currentIndent if -1, don't write anything.
* @return
*/
public String append(int ari, String s, int currentIndent) {
return append(ari, s, currentIndent, null);
}
/**
* @param separatorWhenExisting if the text is appended to an ari that has already some text, append this first, then the text.
* @param currentIndent if -1, don't write anything.
* @return
*/
public String append(int ari, String text, int currentIndent, String separatorWhenExisting) {
VerseState as = map.get(ari);
boolean isNew = false;
if (as == null) {
as = new VerseState();
as.text = "";
map.put(ari, as);
isNew = true;
}
boolean writtenParaMarker = false;
if (currentIndent != -1) {
if (currentIndent == -2) {
as.text += "@^";
} else if (currentIndent < 0 || currentIndent > 4) {
throw new RuntimeException("menjorok ngaco: " + currentIndent);
} else {
as.text += "@" + String.valueOf(currentIndent);
}
writtenParaMarker = true;
// was: "update menjoroknya ayatstate" but no longer used
// for (int i = 0; i < as.isi.length(); i++) {
// if (as.isi.charAt(i) == '@' && as.isi.charAt(i+1) >= '0' && as.isi.charAt(i+1) <= '4') {
// as.menjorok = as.isi.charAt(i+1) - '0';
// }
// }
}
- if (!isNew) {
+ if (!isNew && separatorWhenExisting != null) {
as.text += separatorWhenExisting;
}
if (writtenParaMarker) {
as.text += leftSpaceTrim(text);
} else {
as.text += text;
}
// buang spasi di depan kalo ada
while (as.text.startsWith(" ")) {
as.text = as.text.substring(1);
}
// kasih @@ kalo depannya blum ada
if (as.text.contains("@") && !as.text.startsWith("@@")) {
as.text = "@@" + as.text;
}
return as.text;
}
private static String leftSpaceTrim(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ') {
return s.substring(i);
}
}
return s;
}
public void normalize() {
Set<Integer> keys = new TreeSet<Integer>(map.keySet());
int last_bookId = -1;
int last_chapter_1 = 0;
int last_verse_1 = 0;
for (int ari: keys) {
int bookId = Ari.toBook(ari);
int chapter_1 = Ari.toChapter(ari);
int verse_1 = Ari.toVerse(ari);
if (bookId != last_bookId) {
// must start with chapter_1 1 and verse_1 1
if (chapter_1 != 1 || verse_1 != 1) {
throw new RuntimeException("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " new book does not start from 1:1");
}
// different book, ignore and restart
last_bookId = bookId;
last_chapter_1 = chapter_1;
last_verse_1 = verse_1;
continue;
}
if (chapter_1 == last_chapter_1) {
if (verse_1 != last_verse_1 + 1) {
System.out.println("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " skipped after " + last_bookId + " " + last_chapter_1 + " " + last_verse_1);
System.out.println("Adding empty verses:");
for (int a = last_verse_1 + 1; a < verse_1; a++) {
System.out.println(" at " + bookId + " " + chapter_1 + " " + a + ": " + " (blank)");
append(bookId, chapter_1, a, "", 0);
}
}
} else if (chapter_1 == last_chapter_1 + 1) {
if (verse_1 != 1) {
throw new RuntimeException("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " verse_1 is not 1");
}
} else {
throw new RuntimeException("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " so wrong! it's after " + last_bookId + " " + last_chapter_1 + " " + last_verse_1);
}
last_bookId = bookId;
last_chapter_1 = chapter_1;
last_verse_1 = verse_1;
}
System.out.println("normalize done");
}
public void dump(PrintStream ps) {
ps.println("TOTAL text: " + map.size());
for (Entry<Integer, VerseState> e: map.entrySet()) {
ps.printf("%d\t%d\t%d\t%s%n", Ari.toBook(e.getKey()) + 1, Ari.toChapter(e.getKey()), Ari.toVerse(e.getKey()), e.getValue().text);
}
}
public void dump() {
dump(System.out);
}
public int size() {
return map.size();
}
public List<Rec> toRecList() {
List<Rec> res = new ArrayList<Rec>();
for (Entry<Integer, VerseState> e: map.entrySet()) {
Rec rec = new Rec();
int ari = e.getKey();
rec.book_1 = Ari.toBook(ari) + 1;
rec.chapter_1 = Ari.toChapter(ari);
rec.verse_1 = Ari.toVerse(ari);
rec.text = e.getValue().text;
res.add(rec);
}
return res;
}
public void processEach(TextProcessor textProcessor) {
for (Map.Entry<Integer, VerseState> e: map.entrySet()) {
textProcessor.process(e.getKey(), e.getValue());
}
}
public int getBookCount() {
Set<Integer> bookIds = new LinkedHashSet<>();
for (Map.Entry<Integer, VerseState> e: map.entrySet()) {
int bookId = Ari.toBook(e.getKey());
bookIds.add(bookId);
}
return bookIds.size();
}
public int[] getBookIds() {
Set<Integer> bookIds = new TreeSet<>();
for (Map.Entry<Integer, VerseState> e: map.entrySet()) {
int bookId = Ari.toBook(e.getKey());
bookIds.add(bookId);
}
int[] res = new int[bookIds.size()];
int c = 0;
for (Integer bookId: bookIds) {
res[c++] = bookId;
}
return res;
}
/**
* No skipped chapters recognized. So if a book has chapters [1, 5, 6], this returns 6, not 3.
*/
public int getChapterCountForBook(int bookId) {
int maxChapter = 0;
for (Map.Entry<Integer, VerseState> e: map.entrySet()) {
int ari = e.getKey();
if (Ari.toBook(ari) == bookId) {
int chapter_1 = Ari.toChapter(ari);
if (chapter_1 > maxChapter) maxChapter = chapter_1;
}
}
return maxChapter;
}
/**
* No skipped verses recognized. So if a chapter has verses [1, 5, 6], this returns 6, not 3.
*/
public int getVerseCountForBookChapter(int bookId, int chapter_1) {
int maxVerse = 0;
for (Map.Entry<Integer, VerseState> e: map.entrySet()) {
int ari = e.getKey();
if (Ari.toBook(ari) == bookId && Ari.toChapter(ari) == chapter_1) {
int verse_1 = Ari.toVerse(ari);
if (verse_1 > maxVerse) maxVerse = verse_1;
}
}
return maxVerse;
}
public String getVerseText(int bookId, int chapter_1, int verse_1) {
return map.get(Ari.encode(bookId, chapter_1, verse_1)).text;
}
}
| true | true | public String append(int ari, String text, int currentIndent, String separatorWhenExisting) {
VerseState as = map.get(ari);
boolean isNew = false;
if (as == null) {
as = new VerseState();
as.text = "";
map.put(ari, as);
isNew = true;
}
boolean writtenParaMarker = false;
if (currentIndent != -1) {
if (currentIndent == -2) {
as.text += "@^";
} else if (currentIndent < 0 || currentIndent > 4) {
throw new RuntimeException("menjorok ngaco: " + currentIndent);
} else {
as.text += "@" + String.valueOf(currentIndent);
}
writtenParaMarker = true;
// was: "update menjoroknya ayatstate" but no longer used
// for (int i = 0; i < as.isi.length(); i++) {
// if (as.isi.charAt(i) == '@' && as.isi.charAt(i+1) >= '0' && as.isi.charAt(i+1) <= '4') {
// as.menjorok = as.isi.charAt(i+1) - '0';
// }
// }
}
if (!isNew) {
as.text += separatorWhenExisting;
}
if (writtenParaMarker) {
as.text += leftSpaceTrim(text);
} else {
as.text += text;
}
// buang spasi di depan kalo ada
while (as.text.startsWith(" ")) {
as.text = as.text.substring(1);
}
// kasih @@ kalo depannya blum ada
if (as.text.contains("@") && !as.text.startsWith("@@")) {
as.text = "@@" + as.text;
}
return as.text;
}
| public String append(int ari, String text, int currentIndent, String separatorWhenExisting) {
VerseState as = map.get(ari);
boolean isNew = false;
if (as == null) {
as = new VerseState();
as.text = "";
map.put(ari, as);
isNew = true;
}
boolean writtenParaMarker = false;
if (currentIndent != -1) {
if (currentIndent == -2) {
as.text += "@^";
} else if (currentIndent < 0 || currentIndent > 4) {
throw new RuntimeException("menjorok ngaco: " + currentIndent);
} else {
as.text += "@" + String.valueOf(currentIndent);
}
writtenParaMarker = true;
// was: "update menjoroknya ayatstate" but no longer used
// for (int i = 0; i < as.isi.length(); i++) {
// if (as.isi.charAt(i) == '@' && as.isi.charAt(i+1) >= '0' && as.isi.charAt(i+1) <= '4') {
// as.menjorok = as.isi.charAt(i+1) - '0';
// }
// }
}
if (!isNew && separatorWhenExisting != null) {
as.text += separatorWhenExisting;
}
if (writtenParaMarker) {
as.text += leftSpaceTrim(text);
} else {
as.text += text;
}
// buang spasi di depan kalo ada
while (as.text.startsWith(" ")) {
as.text = as.text.substring(1);
}
// kasih @@ kalo depannya blum ada
if (as.text.contains("@") && !as.text.startsWith("@@")) {
as.text = "@@" + as.text;
}
return as.text;
}
|
diff --git a/src/main/java/org/owasp/proxy/httpclient/HttpClient.java b/src/main/java/org/owasp/proxy/httpclient/HttpClient.java
index 53d4663..946fde7 100644
--- a/src/main/java/org/owasp/proxy/httpclient/HttpClient.java
+++ b/src/main/java/org/owasp/proxy/httpclient/HttpClient.java
@@ -1,427 +1,429 @@
/*
* This file is part of the OWASP Proxy, a free intercepting HTTP proxy
* library.
* Copyright (C) 2008 Rogan Dawes <rogan@dawes.za.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package org.owasp.proxy.httpclient;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.owasp.proxy.daemon.Listener;
import org.owasp.proxy.io.CopyInputStream;
import org.owasp.proxy.model.Conversation;
import org.owasp.proxy.model.MessageFormatException;
import org.owasp.proxy.model.Request;
import org.owasp.proxy.model.Response;
public class HttpClient {
public static final ProxySelector NO_PROXY = new ProxySelector() {
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
}
@Override
public List<Proxy> select(URI uri) {
return Arrays.asList(Proxy.NO_PROXY);
}
};
private SSLContextManager contextManager = new SSLContextManager();
private ProxySelector proxySelector = null;
private Socket socket;
private InetSocketAddress target = null;
private boolean direct = true;
private ByteArrayOutputStream copy = null;
private CopyInputStream in = null;
private Conversation conversation = null;
private Resolver resolver;
public void setSSLContextManager(SSLContextManager contextManager) {
this.contextManager = contextManager;
}
public void setProxySelector(ProxySelector proxySelector) {
this.proxySelector = proxySelector;
}
public void setResolver(Resolver resolver) {
this.resolver = resolver;
}
public Conversation fetchResponse(Request request)
throws MessageFormatException, IOException {
// try to clean up any previous conversations
if (in != null && conversation != null) {
try {
fetchResponseContent(null);
} catch (MessageFormatException mfe) {
close();
} catch (IOException ioe) {
close();
}
}
fetchResponseHeader(request);
readResponseBody();
Conversation conversation = this.conversation;
this.conversation = null;
return conversation;
}
public Conversation fetchResponseHeader(Request request)
throws MessageFormatException, IOException {
conversation = new Conversation();
conversation.setRequest(request);
// establish a socket connection that is connected either to the proxy server
// or to the server itself. conversation.response will be non-null if the proxy
// server returned an error
// instance variable "direct" is set to false if we connect through a non-SSL http proxy
openConnection(conversation);
if (conversation.getResponse() != null)
return conversation;
if (socket == null)
throw new IOException("Couldn't connect to server!");
if (!socket.isConnected() || socket.isClosed())
throw new IOException("Socket is not connected");
conversation.setConnection(socket.getLocalSocketAddress().toString() + "->" + socket.getRemoteSocketAddress().toString());
conversation.setRequest(request);
writeRequest(conversation);
copy = new ByteArrayOutputStream();
in = new CopyInputStream(socket.getInputStream(), copy);
readResponseHeader();
return conversation;
}
public void fetchResponseContent(OutputStream out) throws MessageFormatException, IOException {
if (conversation == null)
throw new IllegalStateException("fetchResponseContent called without fetchResponseHeader");
if (out != null)
in = new CopyInputStream(socket.getInputStream(), new OutputStream[] { copy, out });
readResponseBody();
String version = conversation.getResponse().getVersion();
boolean close = "HTTP/1.0".equals(version); // default to close
String connection = conversation.getResponse().getHeader("Connection");
if (connection != null)
close = "close".equalsIgnoreCase(connection);
if (close)
close();
}
public void close() throws IOException {
if (socket != null && !socket.isClosed()) {
socket.close();
in = null;
copy = null;
}
}
private URI constructUri(boolean ssl, String host, int port) {
StringBuilder buff = new StringBuilder();
buff.append(ssl ? "https" : "http").append("://").append(host).append(":").append(port);
return URI.create(buff.toString());
}
private void checkLoop(SocketAddress dest) throws IOException {
// FIXME - this is looking a bit clunky
SocketAddress[] listeners = Listener.getListeners();
if (dest instanceof InetSocketAddress) {
InetSocketAddress dst = (InetSocketAddress) dest;
for (int i=0; i<listeners.length; i++) {
if (listeners[i] instanceof InetSocketAddress) {
InetSocketAddress isa = (InetSocketAddress) listeners[i];
if (isa.getAddress().isAnyLocalAddress()) {
if (NetworkInterface.getByInetAddress(dst.getAddress()) != null &&
dst.getPort() == isa.getPort())
throw new IOException("Loop detected! Request target is a local Listener");
} else if (dest.equals(listeners[i]))
throw new IOException("Loop detected! Request target is a local Listener");
}
}
}
}
private void openConnection(Conversation conversation) throws MessageFormatException, IOException {
Request request = conversation.getRequest();
boolean ssl = request.isSsl();
String host = request.getHost();
if (host == null)
throw new MessageFormatException("Host is not set, don't know where to connect to!");
int port = request.getPort();
if (port == -1)
port = (ssl ? 443 : 80);
InetSocketAddress target = null;
if (resolver != null) {
target = new InetSocketAddress(resolver.getAddress(host), port);
} else {
target = new InetSocketAddress(host, port);
}
URI uri = constructUri(ssl, host, port);
List<Proxy> proxies = getProxySelector().select(uri);
if (isConnected(target)) {
return;
} else if (socket != null && !socket.isClosed()) {
try {
socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
this.target = target;
socket = null;
IOException lastAttempt = null;
for (Proxy proxy : proxies) {
direct = true;
try {
SocketAddress addr = proxy.address();
checkLoop(addr);
if (proxy.type() == Proxy.Type.HTTP) {
socket = new Socket(Proxy.NO_PROXY);
socket.setSoTimeout(10000);
socket.connect(addr);
if (ssl) {
proxyConnect(target, conversation);
if (conversation.getResponse() != null) // CONNECT failed!
return;
layerSsl(target);
} else
direct = false;
} else {
socket = new Socket(proxy);
socket.setSoTimeout(10000);
socket.connect(target);
if (ssl)
layerSsl(target);
}
} catch (IOException ioe) {
getProxySelector().connectFailed(uri, target, ioe);
lastAttempt = ioe;
- socket.close();
- socket = null;
+ if (socket != null) {
+ socket.close();
+ socket = null;
+ }
}
if (conversation.getResponse() != null)
return;
if (socket != null && socket.isConnected()) {
// success
return;
}
}
if (lastAttempt != null)
throw lastAttempt;
throw new IOException("Couldn't connect to server");
}
private boolean isConnected(InetSocketAddress target) {
if (socket == null || socket.isClosed() || socket.isInputShutdown())
return false;
if (target.equals(this.target)) {
try {
// FIXME: This only works because we don't implement pipelining!
int oldtimeout = socket.getSoTimeout();
try {
socket.setSoTimeout(1);
byte[] buff = new byte[1024];
int got = socket.getInputStream().read(buff);
if (got == -1)
return false;
if (got > 0) {
System.err.println("Unexpected data read from socket:\n\n" + new String(buff, 0, got));
return false;
}
} catch (SocketTimeoutException e) {
return true;
} finally {
socket.setSoTimeout(oldtimeout);
}
} catch (IOException ioe) {
System.err.println("Looks closed!");
return false;
}
}
return false;
}
private void layerSsl(InetSocketAddress target) throws IOException {
if (contextManager == null)
throw new IOException(
"Context Manager is null, SSL is not supported!");
SSLContext sslContext = contextManager.getSSLContext(target.getHostName());
SSLSocketFactory factory = sslContext.getSocketFactory();
SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket,
socket.getInetAddress().getHostName(), socket.getPort(),
true);
sslsocket.setUseClientMode(true);
sslsocket.setSoTimeout(10000);
sslsocket.startHandshake();
socket = sslsocket;
}
private void proxyConnect(InetSocketAddress target, Conversation conversation) throws IOException, MessageFormatException {
OutputStream out = new BufferedOutputStream(socket.getOutputStream());
Request request = new Request();
request.setStartLine("CONNECT " + target.getHostName() + ":" + target.getPort() + " HTTP/1.0");
long requestTime = System.currentTimeMillis();
out.write(request.getMessage());
out.flush();
ByteArrayOutputStream copy = new ByteArrayOutputStream();
CopyInputStream in = new CopyInputStream(socket.getInputStream(), copy);
while (!"".equals(in.readLine()))
; // flush the response headers
long responseHeaderTime = System.currentTimeMillis();
Response response = new Response();
response.setMessage(copy.toByteArray());
if (!"200".equals(response.getStatus())) {
conversation.setRequest(request);
conversation.setRequestTime(requestTime);
conversation.setResponse(response);
conversation.setResponseHeaderTime(responseHeaderTime);
if (Response.flushContent(request.getMethod(), response, in)) {
conversation.setResponseBodyTime(System.currentTimeMillis());
response.setMessage(copy.toByteArray());
conversation.setResponse(response);
}
socket.close();
socket = null;
}
}
private ProxySelector getProxySelector() {
if (proxySelector == null)
return NO_PROXY;
return proxySelector;
}
private void writeRequest(Conversation conversation) throws MessageFormatException, IOException {
OutputStream out = new BufferedOutputStream(socket.getOutputStream());
conversation.setRequestTime(System.currentTimeMillis());
if (!direct) {
writeProxy(out, conversation.getRequest());
} else {
out.write(conversation.getRequest().getMessage());
}
out.flush();
}
private void readResponseHeader() throws MessageFormatException, IOException {
// read the whole header. Each line gets written into the copy defined
// above
String line;
do {
line = in.readLine();
} while (line != null && !"".equals(line));
if (line == null) {
throw new IOException("Unexpected end of stream reading response header");
}
Response response = new Response();
response.setMessage(copy.toByteArray());
if ("100".equals(response.getStatus())) { // 100 Continue, expect another set of headers
// read the next header
while (!"".equals(in.readLine()))
System.err.println("'");
response.setMessage(copy.toByteArray());
}
conversation.setResponse(response);
conversation.setResponseHeaderTime(System.currentTimeMillis());
}
private void readResponseBody() throws MessageFormatException, IOException {
copy.reset();
Response response = conversation.getResponse();
if (Response.flushContent(conversation.getRequest().getMethod(), response, in)) {
conversation.setResponseBodyTime(System.currentTimeMillis());
response.setContent(copy.toByteArray());
conversation.setResponse(response);
copy.reset();
}
// allow the copy ByteArrayOutputStream to be GC'd
copy = null;
in = null;
}
private void writeProxy(OutputStream out, Request request)
throws MessageFormatException, IOException {
int resourceStart = -1;
boolean method = true;
byte[] message = request.getMessage();
for (int i = 0; i < message.length; i++) {
if (method && Character.isWhitespace(message[i])) {
method = false;
}
if (!method && !Character.isWhitespace(message[i])
&& resourceStart == -1) {
resourceStart = i;
break;
}
if (message[i] == 0x0d || message[i] == 0x0a)
throw new MessageFormatException(
"Encountered CR or LF when parsing the URI!");
}
if (resourceStart > 0) {
BufferedOutputStream bos = new BufferedOutputStream(out);
bos.write(message, 0, resourceStart);
bos.write(constructUri(request.isSsl(), request.getHost(), request.getPort()).toString().getBytes());
bos.write(message, resourceStart, message.length - resourceStart);
bos.flush();
} else {
throw new MessageFormatException("Couldn't parse the URI!");
}
}
}
| true | true | private void openConnection(Conversation conversation) throws MessageFormatException, IOException {
Request request = conversation.getRequest();
boolean ssl = request.isSsl();
String host = request.getHost();
if (host == null)
throw new MessageFormatException("Host is not set, don't know where to connect to!");
int port = request.getPort();
if (port == -1)
port = (ssl ? 443 : 80);
InetSocketAddress target = null;
if (resolver != null) {
target = new InetSocketAddress(resolver.getAddress(host), port);
} else {
target = new InetSocketAddress(host, port);
}
URI uri = constructUri(ssl, host, port);
List<Proxy> proxies = getProxySelector().select(uri);
if (isConnected(target)) {
return;
} else if (socket != null && !socket.isClosed()) {
try {
socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
this.target = target;
socket = null;
IOException lastAttempt = null;
for (Proxy proxy : proxies) {
direct = true;
try {
SocketAddress addr = proxy.address();
checkLoop(addr);
if (proxy.type() == Proxy.Type.HTTP) {
socket = new Socket(Proxy.NO_PROXY);
socket.setSoTimeout(10000);
socket.connect(addr);
if (ssl) {
proxyConnect(target, conversation);
if (conversation.getResponse() != null) // CONNECT failed!
return;
layerSsl(target);
} else
direct = false;
} else {
socket = new Socket(proxy);
socket.setSoTimeout(10000);
socket.connect(target);
if (ssl)
layerSsl(target);
}
} catch (IOException ioe) {
getProxySelector().connectFailed(uri, target, ioe);
lastAttempt = ioe;
socket.close();
socket = null;
}
if (conversation.getResponse() != null)
return;
if (socket != null && socket.isConnected()) {
// success
return;
}
}
if (lastAttempt != null)
throw lastAttempt;
throw new IOException("Couldn't connect to server");
}
| private void openConnection(Conversation conversation) throws MessageFormatException, IOException {
Request request = conversation.getRequest();
boolean ssl = request.isSsl();
String host = request.getHost();
if (host == null)
throw new MessageFormatException("Host is not set, don't know where to connect to!");
int port = request.getPort();
if (port == -1)
port = (ssl ? 443 : 80);
InetSocketAddress target = null;
if (resolver != null) {
target = new InetSocketAddress(resolver.getAddress(host), port);
} else {
target = new InetSocketAddress(host, port);
}
URI uri = constructUri(ssl, host, port);
List<Proxy> proxies = getProxySelector().select(uri);
if (isConnected(target)) {
return;
} else if (socket != null && !socket.isClosed()) {
try {
socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
this.target = target;
socket = null;
IOException lastAttempt = null;
for (Proxy proxy : proxies) {
direct = true;
try {
SocketAddress addr = proxy.address();
checkLoop(addr);
if (proxy.type() == Proxy.Type.HTTP) {
socket = new Socket(Proxy.NO_PROXY);
socket.setSoTimeout(10000);
socket.connect(addr);
if (ssl) {
proxyConnect(target, conversation);
if (conversation.getResponse() != null) // CONNECT failed!
return;
layerSsl(target);
} else
direct = false;
} else {
socket = new Socket(proxy);
socket.setSoTimeout(10000);
socket.connect(target);
if (ssl)
layerSsl(target);
}
} catch (IOException ioe) {
getProxySelector().connectFailed(uri, target, ioe);
lastAttempt = ioe;
if (socket != null) {
socket.close();
socket = null;
}
}
if (conversation.getResponse() != null)
return;
if (socket != null && socket.isConnected()) {
// success
return;
}
}
if (lastAttempt != null)
throw lastAttempt;
throw new IOException("Couldn't connect to server");
}
|
diff --git a/src/fr/crafter/tickleman/RealShop/RealShopConfig.java b/src/fr/crafter/tickleman/RealShop/RealShopConfig.java
index c76a47d..ab15808 100644
--- a/src/fr/crafter/tickleman/RealShop/RealShopConfig.java
+++ b/src/fr/crafter/tickleman/RealShop/RealShopConfig.java
@@ -1,136 +1,142 @@
package fr.crafter.tickleman.RealShop;
import java.io.BufferedWriter;
import fr.crafter.tickleman.RealPlugin.RealConfig;
//################################################################################## RealShopConfig
public class RealShopConfig extends RealConfig
{
/** Default configuration values (if not in file) */
public String dailyPricesCalculation = "false";
public String economyPlugin = "RealEconomy";
public String shopDamagedItems = "true";
public String shopInfiniteBuy = "false";
public String shopInfiniteSell = "false";
public String shopMarketItemsOnly = "false";
public String shopOpOnly = "false";
public double workForceRatio = (double)1.1;
public double buySellRatio = (double).95;
public double minDailyRatio = (double).05;
public double maxDailyRatio = (double)1.95;
public double amountRatio = (double)5000;
public double minItemPrice = (double).1;
public double maxItemPrice = (double)99999;
//-------------------------------------------------------------------------------- RealShopConfig
public RealShopConfig(final RealShopPlugin plugin)
{
super(plugin);
}
//------------------------------------------------------------------------------------------ load
@Override
public void load()
{
super.load();
if (!economyPlugin.equals("RealEconomy") && !economyPlugin.equals("iConomy")) {
plugin.log.warning(
"unknown economyPlugin " + economyPlugin + " was set to RealEconomy instead", true
);
economyPlugin = "RealEconomy";
}
}
//------------------------------------------------------------------------------------- loadValue
protected boolean loadValue(String key, String value)
{
if (super.loadValue(key, value)) {
return true;
}
if (key.equals("dailyPricesCalculation")) { dailyPricesCalculation = value; return true; }
if (key.equals("economyPlugin")) { economyPlugin = value; return true; }
if (key.equals("shopDamagedItems")) { shopDamagedItems = value; return true; }
if (key.equals("shopInfiniteBuy")) { shopInfiniteBuy = value; return true; }
if (key.equals("shopInfiniteSell")) { shopInfiniteSell = value; return true; }
if (key.equals("shopMarketItemsOnly")) { shopMarketItemsOnly = value; return true; }
if (key.equals("shopOpOnly")) { shopOpOnly = value; return true; }
if (key.equals("workForceRatio")) {
try {
workForceRatio = Double.parseDouble(value);
} catch (Exception e) {
workForceRatio = (double)1.1;
}
return true;
}
if (key.equals("buySellRatio")) {
try {
buySellRatio = Double.parseDouble(value);
} catch (Exception e) {
buySellRatio = (double).95;
}
+ return true;
}
if (key.equals("minDailyRatio")) {
try {
minDailyRatio = Double.parseDouble(value);
} catch (Exception e) {
minDailyRatio = (double).05;
}
+ return true;
}
if (key.equals("maxDailyRatio")) {
try {
maxDailyRatio = Double.parseDouble(value);
} catch (Exception e) {
maxDailyRatio = (double)1.95;
}
+ return true;
}
if (key.equals("amountRatio")) {
try {
amountRatio = Double.parseDouble(value);
} catch (Exception e) {
amountRatio = (double)5000;
}
+ return true;
}
if (key.equals("minItemPrice")) {
try {
minItemPrice = Double.parseDouble(value);
} catch (Exception e) {
minItemPrice = (double).1;
}
+ return true;
}
if (key.equals("maxItemPrice")) {
try {
maxItemPrice = Double.parseDouble(value);
} catch (Exception e) {
maxItemPrice = (double)99999;
}
+ return true;
}
return false;
}
//------------------------------------------------------------------------------------------ save
/*
* Save values. Override original to add my own configuration values.
*/
@Override
protected void saveValues(BufferedWriter writer)
{
super.saveValues(writer);
saveValue(writer, "dailyPricesCalculation");
saveValue(writer, "economyPlugin");
saveValue(writer, "shopDamagedItems");
saveValue(writer, "shopInfiniteBuy");
saveValue(writer, "shopInfiniteSell");
saveValue(writer, "shopMarketItemsOnly");
saveValue(writer, "shopOpOnly");
saveValue(writer, "workForceRatio");
saveValue(writer, "buySellRatio");
saveValue(writer, "minDailyRatio");
saveValue(writer, "maxDailyRatio");
saveValue(writer, "amountRatio");
saveValue(writer, "minItemPrice");
saveValue(writer, "maxItemPrice");
}
}
| false | true | protected boolean loadValue(String key, String value)
{
if (super.loadValue(key, value)) {
return true;
}
if (key.equals("dailyPricesCalculation")) { dailyPricesCalculation = value; return true; }
if (key.equals("economyPlugin")) { economyPlugin = value; return true; }
if (key.equals("shopDamagedItems")) { shopDamagedItems = value; return true; }
if (key.equals("shopInfiniteBuy")) { shopInfiniteBuy = value; return true; }
if (key.equals("shopInfiniteSell")) { shopInfiniteSell = value; return true; }
if (key.equals("shopMarketItemsOnly")) { shopMarketItemsOnly = value; return true; }
if (key.equals("shopOpOnly")) { shopOpOnly = value; return true; }
if (key.equals("workForceRatio")) {
try {
workForceRatio = Double.parseDouble(value);
} catch (Exception e) {
workForceRatio = (double)1.1;
}
return true;
}
if (key.equals("buySellRatio")) {
try {
buySellRatio = Double.parseDouble(value);
} catch (Exception e) {
buySellRatio = (double).95;
}
}
if (key.equals("minDailyRatio")) {
try {
minDailyRatio = Double.parseDouble(value);
} catch (Exception e) {
minDailyRatio = (double).05;
}
}
if (key.equals("maxDailyRatio")) {
try {
maxDailyRatio = Double.parseDouble(value);
} catch (Exception e) {
maxDailyRatio = (double)1.95;
}
}
if (key.equals("amountRatio")) {
try {
amountRatio = Double.parseDouble(value);
} catch (Exception e) {
amountRatio = (double)5000;
}
}
if (key.equals("minItemPrice")) {
try {
minItemPrice = Double.parseDouble(value);
} catch (Exception e) {
minItemPrice = (double).1;
}
}
if (key.equals("maxItemPrice")) {
try {
maxItemPrice = Double.parseDouble(value);
} catch (Exception e) {
maxItemPrice = (double)99999;
}
}
return false;
}
| protected boolean loadValue(String key, String value)
{
if (super.loadValue(key, value)) {
return true;
}
if (key.equals("dailyPricesCalculation")) { dailyPricesCalculation = value; return true; }
if (key.equals("economyPlugin")) { economyPlugin = value; return true; }
if (key.equals("shopDamagedItems")) { shopDamagedItems = value; return true; }
if (key.equals("shopInfiniteBuy")) { shopInfiniteBuy = value; return true; }
if (key.equals("shopInfiniteSell")) { shopInfiniteSell = value; return true; }
if (key.equals("shopMarketItemsOnly")) { shopMarketItemsOnly = value; return true; }
if (key.equals("shopOpOnly")) { shopOpOnly = value; return true; }
if (key.equals("workForceRatio")) {
try {
workForceRatio = Double.parseDouble(value);
} catch (Exception e) {
workForceRatio = (double)1.1;
}
return true;
}
if (key.equals("buySellRatio")) {
try {
buySellRatio = Double.parseDouble(value);
} catch (Exception e) {
buySellRatio = (double).95;
}
return true;
}
if (key.equals("minDailyRatio")) {
try {
minDailyRatio = Double.parseDouble(value);
} catch (Exception e) {
minDailyRatio = (double).05;
}
return true;
}
if (key.equals("maxDailyRatio")) {
try {
maxDailyRatio = Double.parseDouble(value);
} catch (Exception e) {
maxDailyRatio = (double)1.95;
}
return true;
}
if (key.equals("amountRatio")) {
try {
amountRatio = Double.parseDouble(value);
} catch (Exception e) {
amountRatio = (double)5000;
}
return true;
}
if (key.equals("minItemPrice")) {
try {
minItemPrice = Double.parseDouble(value);
} catch (Exception e) {
minItemPrice = (double).1;
}
return true;
}
if (key.equals("maxItemPrice")) {
try {
maxItemPrice = Double.parseDouble(value);
} catch (Exception e) {
maxItemPrice = (double)99999;
}
return true;
}
return false;
}
|
diff --git a/scoutmaster/src/main/java/au/org/scoutmaster/util/SMSSession.java b/scoutmaster/src/main/java/au/org/scoutmaster/util/SMSSession.java
index eef00e3..ae73aa2 100644
--- a/scoutmaster/src/main/java/au/org/scoutmaster/util/SMSSession.java
+++ b/scoutmaster/src/main/java/au/org/scoutmaster/util/SMSSession.java
@@ -1,96 +1,97 @@
package au.org.scoutmaster.util;
import java.io.Closeable;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.marre.SmsSender;
import org.marre.sms.SmsException;
import au.org.scoutmaster.application.SMSession;
import au.org.scoutmaster.dao.ActivityDao;
import au.org.scoutmaster.dao.ActivityTypeDao;
import au.org.scoutmaster.dao.ContactDao;
import au.org.scoutmaster.dao.DaoFactory;
import au.org.scoutmaster.domain.Activity;
import au.org.scoutmaster.domain.ActivityType;
import au.org.scoutmaster.domain.Phone;
import au.org.scoutmaster.domain.SMSProvider;
import au.org.scoutmaster.domain.Tag;
import au.org.scoutmaster.domain.access.User;
import au.org.scoutmaster.views.wizards.bulkSMS.SMSTransmission;
import com.google.gwt.thirdparty.guava.common.base.Preconditions;
import com.vaadin.ui.Notification.Type;
public class SMSSession implements Closeable
{
static private Logger logger = Logger.getLogger(SMSSession.class);
private SmsSender smsSender;
public SMSSession(SMSProvider provider) throws SmsException, IOException
{
smsSender = SmsSender.getClickatellSender(provider.getUsername(), provider.getPassword(), provider.getApiId());
Preconditions.checkNotNull(smsSender);
smsSender.connect();
}
@Override
public void close() throws IOException
{
if (smsSender != null)
try
{
smsSender.disconnect();
}
catch (SmsException e)
{
logger.error(e, e);
}
}
public void send(SMSTransmission transmission) throws SmsException, IOException
{
User user = (User) SMSession.INSTANCE.getLoggedInUser();
try
{
// The message that you want to send.
String msg = transmission.getMessage().expandBody(user, transmission.getContact()).toString();
// International number to target without leading "+"
Phone reciever = transmission.getRecipient();
// Number of sender (not supported on all transports)
smsSender.sendTextSms(msg, reciever.getPhoneNo().replaceAll("\\s", ""), transmission.getMessage()
.getSender().getPhoneNo());
// Log the activity
ActivityDao daoActivity = new DaoFactory().getActivityDao();
ActivityTypeDao daoActivityType = new DaoFactory().getActivityTypeDao();
Activity activity = new Activity();
activity.setAddedBy(user);
activity.setWithContact(transmission.getContact());
activity.setSubject(transmission.getMessage().getSubject());
activity.setType(daoActivityType.findByName(ActivityType.BULK_SMS));
activity.setDetails(transmission.getMessage().getBody());
daoActivity.persist(activity);
// Tag the contact
ContactDao daoContact = new DaoFactory().getContactDao();
for (Tag tag : transmission.getActivityTags())
{
daoContact.attachTag(transmission.getContact(), tag);
}
+ daoContact.merge(transmission.getContact());
}
catch (VelocityFormatException e)
{
SMNotification.show(e, Type.ERROR_MESSAGE);
}
}
}
| true | true | public void send(SMSTransmission transmission) throws SmsException, IOException
{
User user = (User) SMSession.INSTANCE.getLoggedInUser();
try
{
// The message that you want to send.
String msg = transmission.getMessage().expandBody(user, transmission.getContact()).toString();
// International number to target without leading "+"
Phone reciever = transmission.getRecipient();
// Number of sender (not supported on all transports)
smsSender.sendTextSms(msg, reciever.getPhoneNo().replaceAll("\\s", ""), transmission.getMessage()
.getSender().getPhoneNo());
// Log the activity
ActivityDao daoActivity = new DaoFactory().getActivityDao();
ActivityTypeDao daoActivityType = new DaoFactory().getActivityTypeDao();
Activity activity = new Activity();
activity.setAddedBy(user);
activity.setWithContact(transmission.getContact());
activity.setSubject(transmission.getMessage().getSubject());
activity.setType(daoActivityType.findByName(ActivityType.BULK_SMS));
activity.setDetails(transmission.getMessage().getBody());
daoActivity.persist(activity);
// Tag the contact
ContactDao daoContact = new DaoFactory().getContactDao();
for (Tag tag : transmission.getActivityTags())
{
daoContact.attachTag(transmission.getContact(), tag);
}
}
catch (VelocityFormatException e)
{
SMNotification.show(e, Type.ERROR_MESSAGE);
}
}
| public void send(SMSTransmission transmission) throws SmsException, IOException
{
User user = (User) SMSession.INSTANCE.getLoggedInUser();
try
{
// The message that you want to send.
String msg = transmission.getMessage().expandBody(user, transmission.getContact()).toString();
// International number to target without leading "+"
Phone reciever = transmission.getRecipient();
// Number of sender (not supported on all transports)
smsSender.sendTextSms(msg, reciever.getPhoneNo().replaceAll("\\s", ""), transmission.getMessage()
.getSender().getPhoneNo());
// Log the activity
ActivityDao daoActivity = new DaoFactory().getActivityDao();
ActivityTypeDao daoActivityType = new DaoFactory().getActivityTypeDao();
Activity activity = new Activity();
activity.setAddedBy(user);
activity.setWithContact(transmission.getContact());
activity.setSubject(transmission.getMessage().getSubject());
activity.setType(daoActivityType.findByName(ActivityType.BULK_SMS));
activity.setDetails(transmission.getMessage().getBody());
daoActivity.persist(activity);
// Tag the contact
ContactDao daoContact = new DaoFactory().getContactDao();
for (Tag tag : transmission.getActivityTags())
{
daoContact.attachTag(transmission.getContact(), tag);
}
daoContact.merge(transmission.getContact());
}
catch (VelocityFormatException e)
{
SMNotification.show(e, Type.ERROR_MESSAGE);
}
}
|
diff --git a/src/org/ssgwt/client/ui/AdvancedPasswordBox.java b/src/org/ssgwt/client/ui/AdvancedPasswordBox.java
index eb13dbd..d2a35cb 100644
--- a/src/org/ssgwt/client/ui/AdvancedPasswordBox.java
+++ b/src/org/ssgwt/client/ui/AdvancedPasswordBox.java
@@ -1,254 +1,254 @@
/**
* Copyright 2012 A24Group
*
* 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.ssgwt.client.ui;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
/**
* AdvancedPasswordBox
*
* A password box that allows the developer to set a placeholder label inside it.
* When in focus, the placeholder text is removed, when the focus fades, the
* placeholder text will be replaced if no value was supplied.
*
* @author Johannes Gryffenberg <johannes.gryffenberg@gmail.com>
* @since 19 July 2012
*/
public class AdvancedPasswordBox extends Composite implements HasValue<String> {
/**
* The panel that holds the place holder and the password field
*/
FlowPanel mainPanel = new FlowPanel();
/**
* The text box that displays the place holder text if no password is currently filled in
*/
TextBox placeholder = new TextBox();
/**
* The box that will display if the user types a password
*/
PasswordTextBox passwordBox = new PasswordTextBox();
/**
* Flag that indicates if the field is required
*/
private boolean required;
/**
* The name of the style that is applied to the field if it is required
*/
private String requiredStyleName;
/**
* Class constructor
*/
public AdvancedPasswordBox() {
mainPanel.add(placeholder);
placeholder.setWidth("100%");
mainPanel.add(passwordBox);
passwordBox.setWidth("100%");
passwordBox.setVisible(false);
placeholder.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
placeholder.setVisible(false);
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
public void execute () {
passwordBox.setFocus(true);
}
});
passwordBox.setVisible(true);
}
});
passwordBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
- if ( passwordBox.getText() == null || passwordBox.getText().equals("") ) {
+ if (passwordBox.getText() == null || passwordBox.getText().equals("")) {
placeholder.setVisible(true);
passwordBox.setVisible(false);
}
}
});
initWidget(mainPanel);
}
/**
* Adds a {@link ValueChangeEvent} handler.
*
* @param handler the handler
* @return the registration for the event
*/
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
return passwordBox.addValueChangeHandler(handler);
}
/**
* Gets this object's value.
*
* @return the object's value
*/
@Override
public String getValue() {
return passwordBox.getValue();
}
/**
* Sets this object's value without firing any events. This should be
* identical to calling setValue(value, false).
* <p>
* It is acceptable to fail assertions or throw (documented) unchecked
* exceptions in response to bad values.
* <p>
* Widgets must accept null as a valid value. By convention, setting a widget to
* null clears value, calling getValue() on a cleared widget returns null. Widgets
* that can not be cleared (e.g. {@link CheckBox}) must find another valid meaning
* for null input.
*
* @param value the object's new value
*/
@Override
public void setValue(String value) {
passwordBox.setValue(value);
}
/**
* Sets this object's value. Fires
* {@link com.google.gwt.event.logical.shared.ValueChangeEvent} when
* fireEvents is true and the new value does not equal the existing value.
* <p>
* It is acceptable to fail assertions or throw (documented) unchecked
* exceptions in response to bad values.
*
* @param value the object's new value
* @param fireEvents fire events if true and value is new
*/
@Override
public void setValue(String value, boolean fireEvents) {
passwordBox.setValue(value, fireEvents);
}
/**
* Sets the place holder text to be displayed when no value is given in the
* text input.
*
* @param placeholderText
* The text to be used as the placeholder
*/
public void setPlaceholder(String placeholderText) {
placeholder.setText(placeholderText.trim());
}
/**
* Returns whether the field is required or not
*
* @return required or not
*/
public boolean isRequired() {
return required;
}
/**
* Set the field to be either required or not. Will apply or remove the
* required style name from the element dependant on the value provided.
*
* @param required
* Whether the field is required or not
*/
public void setRequired(boolean required) {
this.required = required;
if (this.required) {
placeholder.addStyleName(this.getRequiredStyleName());
passwordBox.addStyleName(this.getRequiredStyleName());
} else {
placeholder.removeStyleName(this.getRequiredStyleName());
passwordBox.removeStyleName(this.getRequiredStyleName());
}
}
/**
* Retrieve the required style name
*
* @return the requiredStyleName
*/
public String getRequiredStyleName() {
return requiredStyleName;
}
/**
* Set the required style name
*
* @param requiredStyleName
* the required style name to set
*/
public void setRequiredStyleName(String requiredStyleName) {
this.removeStyleName(this.getRequiredStyleName());
this.requiredStyleName = requiredStyleName;
if (this.required) {
placeholder.addStyleName(this.getRequiredStyleName());
passwordBox.addStyleName(this.getRequiredStyleName());
}
}
/**
* Adds or removes a style name. This method is typically used to remove
* secondary style names, but it can be used to remove primary stylenames as
* well. That use is not recommended.
*
* @param style the style name to be added or removed
* @param add <code>true</code> to add the given style, <code>false</code> to
* remove it
* @see #addStyleName(String)
* @see #removeStyleName(String)
*/
public void setStyleName(String style, boolean add) {
placeholder.setStyleName(style, add);
passwordBox.setStyleName(style, add);
}
/**
* Clears all of the object's style names and sets it to the given style. You
* should normally use {@link #setStylePrimaryName(String)} unless you wish to
* explicitly remove all existing styles.
*
* @param style the new style name
* @see #setStylePrimaryName(String)
*/
public void setStyleName(String style) {
placeholder.setStyleName(style);
passwordBox.setStyleName(style);
}
}
| true | true | public AdvancedPasswordBox() {
mainPanel.add(placeholder);
placeholder.setWidth("100%");
mainPanel.add(passwordBox);
passwordBox.setWidth("100%");
passwordBox.setVisible(false);
placeholder.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
placeholder.setVisible(false);
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
public void execute () {
passwordBox.setFocus(true);
}
});
passwordBox.setVisible(true);
}
});
passwordBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
if ( passwordBox.getText() == null || passwordBox.getText().equals("") ) {
placeholder.setVisible(true);
passwordBox.setVisible(false);
}
}
});
initWidget(mainPanel);
}
| public AdvancedPasswordBox() {
mainPanel.add(placeholder);
placeholder.setWidth("100%");
mainPanel.add(passwordBox);
passwordBox.setWidth("100%");
passwordBox.setVisible(false);
placeholder.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
placeholder.setVisible(false);
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
public void execute () {
passwordBox.setFocus(true);
}
});
passwordBox.setVisible(true);
}
});
passwordBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
if (passwordBox.getText() == null || passwordBox.getText().equals("")) {
placeholder.setVisible(true);
passwordBox.setVisible(false);
}
}
});
initWidget(mainPanel);
}
|
diff --git a/samples/dynatablerf/src/com/google/gwt/sample/dynatablerf/client/widgets/ZipPlusFourBox.java b/samples/dynatablerf/src/com/google/gwt/sample/dynatablerf/client/widgets/ZipPlusFourBox.java
index 7712995d4..f035f7749 100644
--- a/samples/dynatablerf/src/com/google/gwt/sample/dynatablerf/client/widgets/ZipPlusFourBox.java
+++ b/samples/dynatablerf/src/com/google/gwt/sample/dynatablerf/client/widgets/ZipPlusFourBox.java
@@ -1,71 +1,74 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.sample.dynatablerf.client.widgets;
import com.google.gwt.dom.client.Document;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.text.shared.Parser;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.user.client.ui.ValueBox;
import java.io.IOException;
import java.text.ParseException;
/**
* A simple implementation of a US zip code input field.
* <p>
* Accepted formats are <code>ddddd</code> or <code>ddddd-dddd</code>.
*/
public class ZipPlusFourBox extends ValueBox<String> {
private static final RegExp PATTERN = RegExp.compile("^\\d{5}(-\\d{4})?$");
private static final Renderer<String> RENDERER = new Renderer<String>() {
public String render(String object) {
if (object == null) {
return null;
}
StringBuilder sb = new StringBuilder(String.valueOf(object));
if (sb.length() == 9) {
sb.insert(5, '-');
}
return sb.toString();
}
public void render(String object, Appendable appendable) throws IOException {
appendable.append(render(object));
}
};
private static final Parser<String> PARSER = new Parser<String>() {
public String parse(CharSequence text) throws ParseException {
switch (text.length()) {
case 9:
text = text.subSequence(0, 5) + "-" + text.subSequence(5, 9);
// Fall-though intentional
+ // CHECKSTYLE_OFF
case 5:
+ // Fall-through intentional
case 10:
+ // CHECKSTYLE_ON
if (PATTERN.test(text.toString())) {
return text.toString();
} else {
throw new ParseException("Illegal value", 0);
}
}
throw new ParseException("Illegal length", 0);
}
};
public ZipPlusFourBox() {
super(Document.get().createTextInputElement(), RENDERER, PARSER);
}
}
| false | true | public String parse(CharSequence text) throws ParseException {
switch (text.length()) {
case 9:
text = text.subSequence(0, 5) + "-" + text.subSequence(5, 9);
// Fall-though intentional
case 5:
case 10:
if (PATTERN.test(text.toString())) {
return text.toString();
} else {
throw new ParseException("Illegal value", 0);
}
}
throw new ParseException("Illegal length", 0);
}
| public String parse(CharSequence text) throws ParseException {
switch (text.length()) {
case 9:
text = text.subSequence(0, 5) + "-" + text.subSequence(5, 9);
// Fall-though intentional
// CHECKSTYLE_OFF
case 5:
// Fall-through intentional
case 10:
// CHECKSTYLE_ON
if (PATTERN.test(text.toString())) {
return text.toString();
} else {
throw new ParseException("Illegal value", 0);
}
}
throw new ParseException("Illegal length", 0);
}
|
diff --git a/common/vdvman1/betterAnvil/packet/PacketHandler.java b/common/vdvman1/betterAnvil/packet/PacketHandler.java
index 1197dd8..bd0a743 100644
--- a/common/vdvman1/betterAnvil/packet/PacketHandler.java
+++ b/common/vdvman1/betterAnvil/packet/PacketHandler.java
@@ -1,36 +1,37 @@
package vdvman1.betterAnvil.packet;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.util.ChatAllowedCharacters;
import vdvman1.betterAnvil.BetterAnvil;
import vdvman1.betterAnvil.inventory.ContainerRepairBA;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;
public class PacketHandler implements IPacketHandler {
@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player _player) {
if(packet.channel.equals(BetterAnvil.channel) && _player instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer)_player;
+ if(!(player.openContainer instanceof ContainerRepairBA)) return;
ContainerRepairBA container = (ContainerRepairBA)player.openContainer;
if (packet.data != null && packet.data.length >= 1)
{
String var15 = ChatAllowedCharacters.filerAllowedCharacters(new String(packet.data));
if (var15.length() <= 30)
{
container.updateItemName(var15);
}
}
else
{
container.updateItemName("");
}
}
}
}
| true | true | public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player _player) {
if(packet.channel.equals(BetterAnvil.channel) && _player instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer)_player;
ContainerRepairBA container = (ContainerRepairBA)player.openContainer;
if (packet.data != null && packet.data.length >= 1)
{
String var15 = ChatAllowedCharacters.filerAllowedCharacters(new String(packet.data));
if (var15.length() <= 30)
{
container.updateItemName(var15);
}
}
else
{
container.updateItemName("");
}
}
}
| public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player _player) {
if(packet.channel.equals(BetterAnvil.channel) && _player instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer)_player;
if(!(player.openContainer instanceof ContainerRepairBA)) return;
ContainerRepairBA container = (ContainerRepairBA)player.openContainer;
if (packet.data != null && packet.data.length >= 1)
{
String var15 = ChatAllowedCharacters.filerAllowedCharacters(new String(packet.data));
if (var15.length() <= 30)
{
container.updateItemName(var15);
}
}
else
{
container.updateItemName("");
}
}
}
|
diff --git a/src/Extensions/org/objectweb/proactive/extensions/scheduler/examples/AdminCommunicator.java b/src/Extensions/org/objectweb/proactive/extensions/scheduler/examples/AdminCommunicator.java
index fdba77f78..6bdb1e02b 100644
--- a/src/Extensions/org/objectweb/proactive/extensions/scheduler/examples/AdminCommunicator.java
+++ b/src/Extensions/org/objectweb/proactive/extensions/scheduler/examples/AdminCommunicator.java
@@ -1,458 +1,462 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive@objectweb.org
*
* This library 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 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.extensions.scheduler.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.PasswordCallback;
import org.apache.commons.cli.AlreadySelectedException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.objectweb.proactive.extensions.scheduler.common.exception.SchedulerException;
import org.objectweb.proactive.extensions.scheduler.common.job.JobId;
import org.objectweb.proactive.extensions.scheduler.common.job.JobResult;
import org.objectweb.proactive.extensions.scheduler.common.scheduler.AdminSchedulerInterface;
import org.objectweb.proactive.extensions.scheduler.common.scheduler.SchedulerAuthenticationInterface;
import org.objectweb.proactive.extensions.scheduler.common.scheduler.SchedulerConnection;
import org.objectweb.proactive.extensions.scheduler.common.task.TaskResult;
import com.sun.security.auth.callback.TextCallbackHandler;
/**
* AdminCommunicator ...
*
* @author SCHEEFER Jean-Luc & FRADJ Johann
* @since ProActive 3.9
*/
public class AdminCommunicator {
private static AdminSchedulerInterface scheduler;
private static final String STAT_CMD = "stat";
private static final String START_CMD = "start";
private static final String STOP_CMD = "stop";
private static final String PAUSE_CMD = "pause";
private static final String PAUSE_IM_CMD = "pausei";
private static final String RESUME_CMD = "resume";
private static final String SHUTDOWN_CMD = "shutdown";
private static final String KILL_CMD = "kill";
private static final String EXIT_CMD = "exit";
private static final String PAUSEJOB_CMD = "pausejob";
private static final String RESUMEJOB_CMD = "resumejob";
private static final String KILLJOB_CMD = "killjob";
private static final String GET_RESULT_CMD = "result";
private static final String RECONNECT_RM_CMD = "rebind";
private static boolean stopCommunicator;
private static boolean displayException = false;
private static void output(String message) {
System.out.print(message);
}
private static void error(String message) {
System.err.print(message);
}
private static void error(String message, Exception e) {
error(message);
if (displayException) {
e.printStackTrace();
System.out.println();
}
}
public static void main(String[] args) {
Options options = new Options();
Option help = new Option("h", "help", false, "to display this help");
help.setArgName("help");
help.setRequired(false);
options.addOption(help);
Option username = new Option("l", "login", true, "the login");
username.setArgName("login");
username.setRequired(false);
options.addOption(username);
Option exception = new Option("e", "exception", false, "display every exceptions");
exception.setArgName("exception");
exception.setRequired(false);
options.addOption(exception);
Option schedulerURL = new Option("u", "schedulerURL", true, "the scheduler URL (default //localhost)");
schedulerURL.setArgName("schedulerURL");
schedulerURL.setRequired(false);
options.addOption(schedulerURL);
boolean displayHelp = false;
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(reader);
try {
String user = null;
String pwd = null;
String pwdMsg = null;
SchedulerAuthenticationInterface auth = null;
Parser parser = new GnuParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h"))
displayHelp = true;
else {
if (cmd.hasOption("u"))
auth = SchedulerConnection.join(cmd.getOptionValue("u"));
else
auth = SchedulerConnection.join(null);
if (cmd.hasOption("e"))
displayException = true;
if (cmd.hasOption("l")) {
user = cmd.getOptionValue("l");
pwdMsg = user + "'s password: ";
} else {
System.out.print("login: ");
user = buf.readLine();
pwdMsg = "password: ";
}
//ask password to User
TextCallbackHandler handler = new TextCallbackHandler();
PasswordCallback pwdCallBack = new PasswordCallback(pwdMsg, false);
Callback[] callbacks = new Callback[] { pwdCallBack };
handler.handle(callbacks);
pwd = new String(pwdCallBack.getPassword());
scheduler = auth.logAsAdmin(user, pwd);
stopCommunicator = false;
startCommandListener();
}
} catch (MissingArgumentException e) {
System.out.println(e.getLocalizedMessage());
displayHelp = true;
} catch (MissingOptionException e) {
System.out.println("Missing option: " + e.getLocalizedMessage());
displayHelp = true;
} catch (UnrecognizedOptionException e) {
System.out.println(e.getLocalizedMessage());
displayHelp = true;
} catch (AlreadySelectedException e) {
System.out.println(e.getClass().getSimpleName() + " : " + e.getLocalizedMessage());
displayHelp = true;
} catch (ParseException e) {
displayHelp = true;
} catch (Exception e) {
error("A fatal error has occured : " + e.getMessage() + "\n Will shut down communicator.\n");
e.printStackTrace();
System.exit(1);
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e1) {
}
if (buf != null)
try {
buf.close();
} catch (IOException e) {
}
}
if (displayHelp) {
System.out.println();
new HelpFormatter().printHelp("jobLauncher", options, true);
System.exit(2);
}
// if execution reaches this point this means it must exit
System.exit(0);
}
private static void handleCommand(String command) {
if (command.equals("")) {
} else if (command.equals(EXIT_CMD)) {
output("Communicator will exit.\n");
stopCommunicator = true;
} else if (command.equals("?") || command.equals("help")) {
helpScreen();
} else if (command.equals(STAT_CMD)) {
statScreen();
} else if (command.equals(START_CMD)) {
try {
boolean success = scheduler.start().booleanValue();
if (success) {
output("Scheduler started.\n");
} else {
output("Start is impossible!!\n");
}
} catch (SchedulerException e) {
error("Start is impossible !!", e);
}
} else if (command.equals(STOP_CMD)) {
try {
boolean success = scheduler.stop().booleanValue();
if (success) {
output("Scheduler stopped.\n");
} else {
output("Stop is impossible !!\n");
}
} catch (SchedulerException e) {
error("Stop is impossible !!", e);
}
} else if (command.equals(PAUSE_CMD)) {
try {
boolean success = scheduler.pause().booleanValue();
if (success) {
output("Scheduler paused.\n");
} else {
output("Pause is impossible !!\n");
}
} catch (SchedulerException e) {
error("Pause is impossible !!", e);
}
} else if (command.equals(PAUSE_IM_CMD)) {
try {
boolean success = scheduler.pauseImmediate().booleanValue();
if (success) {
output("Scheduler freezed.\n");
} else {
output("Freeze is impossible !!\n");
}
} catch (SchedulerException e) {
error("Freeze is impossible !!", e);
}
} else if (command.equals(RESUME_CMD)) {
try {
boolean success = scheduler.resume().booleanValue();
if (success) {
output("Scheduler resumed.\n");
} else {
output("Resume is impossible !!\n");
}
} catch (SchedulerException e) {
error("Resume is impossible !!", e);
}
} else if (command.equals(SHUTDOWN_CMD)) {
try {
if (scheduler.shutdown().booleanValue()) {
output("Shutdown sequence initialized, it might take a while to finish all executions, communicator will exit.\n");
stopCommunicator = true;
} else {
output("Shutdown the scheduler is impossible for the moment.\n");
}
} catch (SchedulerException e) {
error("Shutdown is impossible !!", e);
}
} else if (command.equals(KILL_CMD)) {
try {
if (scheduler.kill().booleanValue()) {
output("Sheduler has just been killed, communicator will exit.\n");
stopCommunicator = true;
} else {
output("killed the scheduler is impossible for the moment.\n");
}
} catch (SchedulerException e) {
error("kill is impossible !!", e);
}
} else if (command.startsWith(PAUSEJOB_CMD)) {
try {
boolean success = scheduler.pause(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job paused.\n");
} else {
output("Paused job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while pausing this job !!", e);
}
} else if (command.startsWith(RESUMEJOB_CMD)) {
try {
boolean success = scheduler.resume(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job resumed.\n");
} else {
output("Resume job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while resuming this job !!", e);
}
} else if (command.startsWith(KILLJOB_CMD)) {
try {
boolean success = scheduler.kill(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job killed.\n");
} else {
output("Kill job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while killing this job !!", e);
}
} else if (command.startsWith(GET_RESULT_CMD)) {
try {
String jID = command.replaceFirst(GET_RESULT_CMD, "");
jID = jID.trim();
int begin = 0;
int end = 0;
if (jID.matches(".* to .*")) {
String[] TjID = jID.split(" to ");
begin = Integer.parseInt(TjID[0]);
end = Integer.parseInt(TjID[1]);
} else {
begin = Integer.parseInt(jID);
end = Integer.parseInt(jID);
}
for (int i = begin; i <= end; i++) {
try {
JobResult result = scheduler.getJobResult(JobId.makeJobId(i + ""));
if (result != null) {
System.out.println("Job " + i + " Result => ");
for (Entry<String, TaskResult> e : result.getAllResults().entrySet()) {
TaskResult tRes = e.getValue();
try {
System.out.println("\t " + e.getKey() + " : " + tRes.value());
} catch (Throwable e1) {
System.out.println("\t ERROR during execution of " + e.getKey() + "... ");
tRes.getException().printStackTrace();
}
}
} else {
System.out.println("Job " + i + " is not finished or unknown !");
}
} catch (SchedulerException e) {
System.out.println("Error on job " + i + " : " + e.getMessage());
}
}
} catch (Exception e) {
error("Error while getting this job result !!", e);
}
} else if (command.startsWith(RECONNECT_RM_CMD)) {
try {
String rmurl = command.replaceFirst(RECONNECT_RM_CMD, "");
- scheduler.linkResourceManager(rmurl.trim());
- output("The new Resource Manager has been rebind to the scheduler.\n");
+ boolean success = scheduler.linkResourceManager(rmurl.trim()).booleanValue();
+ if (success) {
+ output("The new Resource Manager has been rebind to the scheduler at " + rmurl + ".\n");
+ } else {
+ output("Reconnect a Resource Manager is possible only when RM is dead !\n");
+ }
} catch (Exception e) {
error("Cannot join the new RM !", e);
}
} else {
error("UNKNOWN COMMAND!!... Please type '?' or 'help' to see the list of commands\n");
}
}
private static void startCommandListener() throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (!stopCommunicator) {
output(" > ");
String line = reader.readLine();
try {
handleCommand(line);
} catch (NumberFormatException e) {
error("Id error !!\n", e);
}
}
}
private static void statScreen() {
try {
HashMap<String, Object> stat = scheduler.getStats().getProperties();
String out = "";
for (Entry<String, Object> e : stat.entrySet()) {
out += (e.getKey() + " : " + e.getValue() + "\n");
}
output(out + "\n");
} catch (SchedulerException e) {
e.printStackTrace();
}
}
private static void helpScreen() {
StringBuilder out = new StringBuilder("Communicator Commands are:\n\n");
out.append(String.format(" %1$-18s\t Display statistics\n", STAT_CMD));
out.append(String.format(" %1$-18s\t Starts scheduler\n", START_CMD));
out.append(String.format(" %1$-18s\t Stops scheduler\n", STOP_CMD));
out.append(String.format(" %1$-18s\t pauses all running tasks\n", PAUSE_CMD));
out.append(String.format(" %1$-18s\t pauses immediately all running jobs\n", PAUSE_IM_CMD));
out.append(String.format(" %1$-18s\t resumes all queued tasks\n", RESUME_CMD));
out
.append(String.format(" %1$-18s\t Waits for running tasks to finish and shutdown\n",
SHUTDOWN_CMD));
out.append(String.format(" %1$-18s\t Kill every tasks and jobs and shutdown\n", KILL_CMD));
out.append(String.format(" %1$-18s\t Pause the given job (" + PAUSEJOB_CMD + " num_job)\n",
PAUSEJOB_CMD));
out.append(String.format(" %1$-18s\t Resume the given job (" + RESUMEJOB_CMD + " num_job)\n",
RESUMEJOB_CMD));
out.append(String
.format(" %1$-18s\t Kill the given job (" + KILLJOB_CMD + " num_job)\n", KILLJOB_CMD));
out.append(String.format(" %1$-18s\t Get the result of the given job (" + GET_RESULT_CMD +
" num_job | result num_job to num_job)\n", GET_RESULT_CMD));
out.append(String.format(" %1$-18s\t Reconnect a Resource Manager (" + RECONNECT_RM_CMD + " url)\n",
RECONNECT_RM_CMD));
out.append(String.format(" %1$-18s\t Exits Communicator\n", EXIT_CMD));
output(out.toString());
}
}
| true | true | private static void handleCommand(String command) {
if (command.equals("")) {
} else if (command.equals(EXIT_CMD)) {
output("Communicator will exit.\n");
stopCommunicator = true;
} else if (command.equals("?") || command.equals("help")) {
helpScreen();
} else if (command.equals(STAT_CMD)) {
statScreen();
} else if (command.equals(START_CMD)) {
try {
boolean success = scheduler.start().booleanValue();
if (success) {
output("Scheduler started.\n");
} else {
output("Start is impossible!!\n");
}
} catch (SchedulerException e) {
error("Start is impossible !!", e);
}
} else if (command.equals(STOP_CMD)) {
try {
boolean success = scheduler.stop().booleanValue();
if (success) {
output("Scheduler stopped.\n");
} else {
output("Stop is impossible !!\n");
}
} catch (SchedulerException e) {
error("Stop is impossible !!", e);
}
} else if (command.equals(PAUSE_CMD)) {
try {
boolean success = scheduler.pause().booleanValue();
if (success) {
output("Scheduler paused.\n");
} else {
output("Pause is impossible !!\n");
}
} catch (SchedulerException e) {
error("Pause is impossible !!", e);
}
} else if (command.equals(PAUSE_IM_CMD)) {
try {
boolean success = scheduler.pauseImmediate().booleanValue();
if (success) {
output("Scheduler freezed.\n");
} else {
output("Freeze is impossible !!\n");
}
} catch (SchedulerException e) {
error("Freeze is impossible !!", e);
}
} else if (command.equals(RESUME_CMD)) {
try {
boolean success = scheduler.resume().booleanValue();
if (success) {
output("Scheduler resumed.\n");
} else {
output("Resume is impossible !!\n");
}
} catch (SchedulerException e) {
error("Resume is impossible !!", e);
}
} else if (command.equals(SHUTDOWN_CMD)) {
try {
if (scheduler.shutdown().booleanValue()) {
output("Shutdown sequence initialized, it might take a while to finish all executions, communicator will exit.\n");
stopCommunicator = true;
} else {
output("Shutdown the scheduler is impossible for the moment.\n");
}
} catch (SchedulerException e) {
error("Shutdown is impossible !!", e);
}
} else if (command.equals(KILL_CMD)) {
try {
if (scheduler.kill().booleanValue()) {
output("Sheduler has just been killed, communicator will exit.\n");
stopCommunicator = true;
} else {
output("killed the scheduler is impossible for the moment.\n");
}
} catch (SchedulerException e) {
error("kill is impossible !!", e);
}
} else if (command.startsWith(PAUSEJOB_CMD)) {
try {
boolean success = scheduler.pause(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job paused.\n");
} else {
output("Paused job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while pausing this job !!", e);
}
} else if (command.startsWith(RESUMEJOB_CMD)) {
try {
boolean success = scheduler.resume(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job resumed.\n");
} else {
output("Resume job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while resuming this job !!", e);
}
} else if (command.startsWith(KILLJOB_CMD)) {
try {
boolean success = scheduler.kill(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job killed.\n");
} else {
output("Kill job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while killing this job !!", e);
}
} else if (command.startsWith(GET_RESULT_CMD)) {
try {
String jID = command.replaceFirst(GET_RESULT_CMD, "");
jID = jID.trim();
int begin = 0;
int end = 0;
if (jID.matches(".* to .*")) {
String[] TjID = jID.split(" to ");
begin = Integer.parseInt(TjID[0]);
end = Integer.parseInt(TjID[1]);
} else {
begin = Integer.parseInt(jID);
end = Integer.parseInt(jID);
}
for (int i = begin; i <= end; i++) {
try {
JobResult result = scheduler.getJobResult(JobId.makeJobId(i + ""));
if (result != null) {
System.out.println("Job " + i + " Result => ");
for (Entry<String, TaskResult> e : result.getAllResults().entrySet()) {
TaskResult tRes = e.getValue();
try {
System.out.println("\t " + e.getKey() + " : " + tRes.value());
} catch (Throwable e1) {
System.out.println("\t ERROR during execution of " + e.getKey() + "... ");
tRes.getException().printStackTrace();
}
}
} else {
System.out.println("Job " + i + " is not finished or unknown !");
}
} catch (SchedulerException e) {
System.out.println("Error on job " + i + " : " + e.getMessage());
}
}
} catch (Exception e) {
error("Error while getting this job result !!", e);
}
} else if (command.startsWith(RECONNECT_RM_CMD)) {
try {
String rmurl = command.replaceFirst(RECONNECT_RM_CMD, "");
scheduler.linkResourceManager(rmurl.trim());
output("The new Resource Manager has been rebind to the scheduler.\n");
} catch (Exception e) {
error("Cannot join the new RM !", e);
}
} else {
error("UNKNOWN COMMAND!!... Please type '?' or 'help' to see the list of commands\n");
}
}
| private static void handleCommand(String command) {
if (command.equals("")) {
} else if (command.equals(EXIT_CMD)) {
output("Communicator will exit.\n");
stopCommunicator = true;
} else if (command.equals("?") || command.equals("help")) {
helpScreen();
} else if (command.equals(STAT_CMD)) {
statScreen();
} else if (command.equals(START_CMD)) {
try {
boolean success = scheduler.start().booleanValue();
if (success) {
output("Scheduler started.\n");
} else {
output("Start is impossible!!\n");
}
} catch (SchedulerException e) {
error("Start is impossible !!", e);
}
} else if (command.equals(STOP_CMD)) {
try {
boolean success = scheduler.stop().booleanValue();
if (success) {
output("Scheduler stopped.\n");
} else {
output("Stop is impossible !!\n");
}
} catch (SchedulerException e) {
error("Stop is impossible !!", e);
}
} else if (command.equals(PAUSE_CMD)) {
try {
boolean success = scheduler.pause().booleanValue();
if (success) {
output("Scheduler paused.\n");
} else {
output("Pause is impossible !!\n");
}
} catch (SchedulerException e) {
error("Pause is impossible !!", e);
}
} else if (command.equals(PAUSE_IM_CMD)) {
try {
boolean success = scheduler.pauseImmediate().booleanValue();
if (success) {
output("Scheduler freezed.\n");
} else {
output("Freeze is impossible !!\n");
}
} catch (SchedulerException e) {
error("Freeze is impossible !!", e);
}
} else if (command.equals(RESUME_CMD)) {
try {
boolean success = scheduler.resume().booleanValue();
if (success) {
output("Scheduler resumed.\n");
} else {
output("Resume is impossible !!\n");
}
} catch (SchedulerException e) {
error("Resume is impossible !!", e);
}
} else if (command.equals(SHUTDOWN_CMD)) {
try {
if (scheduler.shutdown().booleanValue()) {
output("Shutdown sequence initialized, it might take a while to finish all executions, communicator will exit.\n");
stopCommunicator = true;
} else {
output("Shutdown the scheduler is impossible for the moment.\n");
}
} catch (SchedulerException e) {
error("Shutdown is impossible !!", e);
}
} else if (command.equals(KILL_CMD)) {
try {
if (scheduler.kill().booleanValue()) {
output("Sheduler has just been killed, communicator will exit.\n");
stopCommunicator = true;
} else {
output("killed the scheduler is impossible for the moment.\n");
}
} catch (SchedulerException e) {
error("kill is impossible !!", e);
}
} else if (command.startsWith(PAUSEJOB_CMD)) {
try {
boolean success = scheduler.pause(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job paused.\n");
} else {
output("Paused job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while pausing this job !!", e);
}
} else if (command.startsWith(RESUMEJOB_CMD)) {
try {
boolean success = scheduler.resume(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job resumed.\n");
} else {
output("Resume job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while resuming this job !!", e);
}
} else if (command.startsWith(KILLJOB_CMD)) {
try {
boolean success = scheduler.kill(JobId.makeJobId(command.split(" ")[1])).booleanValue();
if (success) {
output("Job killed.\n");
} else {
output("Kill job is impossible !!\n");
}
} catch (SchedulerException e) {
error("Error while killing this job !!", e);
}
} else if (command.startsWith(GET_RESULT_CMD)) {
try {
String jID = command.replaceFirst(GET_RESULT_CMD, "");
jID = jID.trim();
int begin = 0;
int end = 0;
if (jID.matches(".* to .*")) {
String[] TjID = jID.split(" to ");
begin = Integer.parseInt(TjID[0]);
end = Integer.parseInt(TjID[1]);
} else {
begin = Integer.parseInt(jID);
end = Integer.parseInt(jID);
}
for (int i = begin; i <= end; i++) {
try {
JobResult result = scheduler.getJobResult(JobId.makeJobId(i + ""));
if (result != null) {
System.out.println("Job " + i + " Result => ");
for (Entry<String, TaskResult> e : result.getAllResults().entrySet()) {
TaskResult tRes = e.getValue();
try {
System.out.println("\t " + e.getKey() + " : " + tRes.value());
} catch (Throwable e1) {
System.out.println("\t ERROR during execution of " + e.getKey() + "... ");
tRes.getException().printStackTrace();
}
}
} else {
System.out.println("Job " + i + " is not finished or unknown !");
}
} catch (SchedulerException e) {
System.out.println("Error on job " + i + " : " + e.getMessage());
}
}
} catch (Exception e) {
error("Error while getting this job result !!", e);
}
} else if (command.startsWith(RECONNECT_RM_CMD)) {
try {
String rmurl = command.replaceFirst(RECONNECT_RM_CMD, "");
boolean success = scheduler.linkResourceManager(rmurl.trim()).booleanValue();
if (success) {
output("The new Resource Manager has been rebind to the scheduler at " + rmurl + ".\n");
} else {
output("Reconnect a Resource Manager is possible only when RM is dead !\n");
}
} catch (Exception e) {
error("Cannot join the new RM !", e);
}
} else {
error("UNKNOWN COMMAND!!... Please type '?' or 'help' to see the list of commands\n");
}
}
|
diff --git a/app/src/nl/digitalica/skydivekompasroos/CalculateActivity.java b/app/src/nl/digitalica/skydivekompasroos/CalculateActivity.java
index ed303da..a473dcb 100644
--- a/app/src/nl/digitalica/skydivekompasroos/CalculateActivity.java
+++ b/app/src/nl/digitalica/skydivekompasroos/CalculateActivity.java
@@ -1,972 +1,972 @@
package nl.digitalica.skydivekompasroos;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import nl.digitalica.skydivekompasroos.CanopyBase.AcceptabilityEnum;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TableRow;
import android.widget.TextView;
/**
* @author robbert
*
*/
public class CalculateActivity extends KompasroosBaseActivity {
// min & max weight in kg
final static int WEIGHT_MIN = 50;
final static int WEIGHT_MAX = 140;
final static int WEIGHT_DEFAULT = 100;
// max for total jumps
final static int TOTALJUMPS_MAX = 1100;
final static int TOTALJUMPS_LASTGROUP = 1000;
final static int TOTALJUMPS_DEFAULT = 100;
// max for total jumps
final static int JUMPS_LAST_12_MONTHS_MAX = 125;
final static int JUMPS_LAST_12_MONTHS_LASTGROUP = 100;
final static int JUMPS_LAST_12_MONTHS_DEFAULT = 25;
// dialog ID's
final static int SAVE_DIALOG_ID = 1;
final static int RESET_DIALOG_ID = 2;
final static int TOTAL_JUMPS_DIALOG_ID = 3;
final static int JUMPS_LAST_12_MONTHS_DIALOG_ID = 4;
final static int WEIGHT_DIALOG_ID = 5;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculate);
// if compile date over 1 year ago, show warning text
TextView tvWarning = (TextView) findViewById(R.id.textViewWarning);
String warning = "";
try {
long compilationDateTime = getCompileDateTime();
Calendar cal = Calendar.getInstance();
long now = cal.getTime().getTime();
- long maxDiff = 1000 * 60 * 60 * 24 * 365; // 1 year
+ long maxDiff = 1000L * 60L * 60L * 24L * 365L; // 1 year
// maxDiff = 1000 * 60 * 5; // 5 mins (for testing)
if (now - compilationDateTime > maxDiff)
warning = getString(R.string.calculationOvertimeWarning);
} catch (Exception e) {
warning = getString(R.string.calculationOvertimeUnknownWarning);
}
tvWarning.setText(warning);
// initialize seek bars and calculated texts
initSeekBars();
fillSpecificCanopyTable();
// set click listener for canopy list button
ImageButton canopyListButton = (ImageButton) findViewById(R.id.buttonShowCanopyList);
canopyListButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),
CanopyTypeListActivity.class));
}
});
// set click listener for about button
ImageButton aboutButton = (ImageButton) findViewById(R.id.buttonAbout);
aboutButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), AboutActivity.class));
}
});
// add click listener for allowed header
View filterHeader = findViewById(R.id.tablelayout_filterheader);
filterHeader.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),
CanopyTypeListActivity.class));
}
});
// set click listener for specific canopy add
Button addSpecificCanopy = (Button) findViewById(R.id.buttonAddSpecificCanopy);
addSpecificCanopy.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),
SpecificCanopyEdit.class);
Bundle bundle = new Bundle();
bundle.putInt(SPECIFICCANOPYID_KEY, 0);
intent.putExtras(bundle);
startActivity(intent);
}
});
TextView tvTotalJumps = (TextView) findViewById(R.id.textViewTotalJumpsLabel);
tvTotalJumps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TOTAL_JUMPS_DIALOG_ID);
}
});
TextView tvJumpsLast12Months = (TextView) findViewById(R.id.textViewJumpsLast12MonthsLabel);
tvJumpsLast12Months.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(JUMPS_LAST_12_MONTHS_DIALOG_ID);
}
});
TextView tvWeight = (TextView) findViewById(R.id.textViewWeightLabel);
tvWeight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(WEIGHT_DIALOG_ID);
}
});
// Just for testing the canopy list
// canopyListButton.performClick();
}
@Override
public void onStart() {
super.onStart();
fillSpecificCanopyTable();
}
@Override
public void onResume() {
super.onResume();
initSeekBarTextsAndCalculate();
updateSpecificCanopyTable();
}
private void fillSpecificCanopyTable() {
// TODO Auto-generated method stub
TableLayout scTable = (TableLayout) findViewById(R.id.tableSpecificCanopies);
scTable.removeAllViews();
insertCanopyHeaderRow(scTable);
List<SpecificCanopy> scList = SpecificCanopy
.getSpecificCanopiesInList(CalculateActivity.this);
HashMap<UUID, CanopyType> canopyTypes = CanopyType
.getCanopyTypeHash(CalculateActivity.this);
for (SpecificCanopy theCanopy : scList) {
CanopyType ct = canopyTypes.get(theCanopy.typeId);
insertSpecificCanopyRow(scTable, theCanopy, ct.specificName(),
ct.category);
}
// enable or disable button if needed
Button addSpecificCanopy = (Button) findViewById(R.id.buttonAddSpecificCanopy);
if (scList.size() >= SpecificCanopy.MAXSPECIFICCANOPIES)
addSpecificCanopy.setEnabled(false);
else
addSpecificCanopy.setEnabled(true);
}
/**
* Update the already drawn specific canopy table, based on the data in the
* table itself.
*/
private void updateSpecificCanopyTable() {
// TODO Auto-generated method stub
TableLayout scTable = (TableLayout) findViewById(R.id.tableSpecificCanopies);
for (int i = 1; i < scTable.getChildCount(); i++) {
TableRow canopyListRow = (TableRow) scTable.getChildAt(i);
TextView tvSize = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificSize);
TextView tvType = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificType);
TextView tvRemarks = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificRemarks);
TextView tvWingLoad = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificWingload);
int tagAll = (Integer) tvWingLoad.getTag();
int typeCategory = tagAll % 10;
int size = (tagAll - typeCategory) / 10;
double wingload = Calculation.wingLoad(size, currentWeight);
tvWingLoad.setText(String.format("%.2f", wingload));
AcceptabilityEnum acc = SpecificCanopy.acceptablility(
currentMaxCategory, typeCategory, size, currentWeight);
// We need different drawables for each column as the widths are
// different
Drawable backgroundCol1 = backgroundDrawableForAcceptance(acc);
Drawable backgroundCol2 = backgroundDrawableForAcceptance(acc);
Drawable backgroundCol3 = backgroundDrawableForAcceptance(acc);
Drawable backgroundCol4 = backgroundDrawableForAcceptance(acc);
tvSize.setBackgroundDrawable(backgroundCol1);
tvType.setBackgroundDrawable(backgroundCol2);
tvRemarks.setBackgroundDrawable(backgroundCol3);
tvWingLoad.setBackgroundDrawable(backgroundCol4);
}
}
private void insertCanopyHeaderRow(TableLayout scTable) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View canopyListRow = inflater.inflate(
R.layout.specific_canopy_row_layout, null);
TextView tvSize = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificSize);
TextView tvType = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificType);
TextView tvRemarks = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificRemarks);
TextView tvWingload = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificWingload);
tvSize.setText(getString(R.string.specificCanopyHeaderSize));
tvType.setText(getString(R.string.specificCanopyHeaderType));
tvRemarks.setText(getString(R.string.specificCanopyHeaderRemarks));
tvWingload.setText(getString(R.string.specificCanopyHeaderWingLoad));
scTable.addView(canopyListRow);
}
private void insertSpecificCanopyRow(TableLayout scTable,
SpecificCanopy theCanopy, String typeName, int typeCategory) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View canopyListRow = inflater.inflate(
R.layout.specific_canopy_row_layout, null);
TextView size = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificSize);
TextView type = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificType);
TextView remarks = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificRemarks);
TextView wingload = (TextView) canopyListRow
.findViewById(R.id.textViewSpecificWingload);
size.setText(Integer.toString(theCanopy.size));
type.setText(typeName);
remarks.setText(theCanopy.remarks);
wingload.setTag(theCanopy.size * 10 + typeCategory);
// set click listener for specific canopy edit
canopyListRow.setTag(theCanopy.id);
canopyListRow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),
SpecificCanopyEdit.class);
Bundle bundle = new Bundle();
bundle.putInt(SPECIFICCANOPYID_KEY, (Integer) v.getTag());
intent.putExtras(bundle);
startActivity(intent);
}
});
// add it to the table
scTable.addView(canopyListRow);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case SAVE_DIALOG_ID:
return saveDialog();
case RESET_DIALOG_ID:
return resetDialog();
case TOTAL_JUMPS_DIALOG_ID:
return totalJumpsDialog();
case JUMPS_LAST_12_MONTHS_DIALOG_ID:
return jumpsLast12MonthsDialog();
case WEIGHT_DIALOG_ID:
return weightDialog();
}
return null;
}
private Dialog totalJumpsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.totalNumberOfJumpsDialogTitle));
builder.setMessage(String.format(
getString(R.string.enterTotalNumberOfJumpsFormat),
TOTALJUMPS_MAX));
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String valueText = input.getText().toString();
int value = Integer.parseInt(valueText);
if (value >= 0 && value <= TOTALJUMPS_MAX) {
SeekBar sb = (SeekBar) findViewById(R.id.seekBarTotalJumps);
sb.setProgress(value);
}
// make sure it will be initialized next time...
removeDialog(TOTAL_JUMPS_DIALOG_ID);
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// make sure it will be initialized next time...
removeDialog(TOTAL_JUMPS_DIALOG_ID);
}
});
return builder.create();
}
private Dialog jumpsLast12MonthsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.numberOfJumpsLast12MonthsDialogTitle));
builder.setMessage(String.format(
getString(R.string.enterNumberOfJumpsLast12MonthsFormat),
JUMPS_LAST_12_MONTHS_MAX));
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String valueText = input.getText().toString();
int value = Integer.parseInt(valueText);
if (value >= 0 && value <= JUMPS_LAST_12_MONTHS_MAX) {
SeekBar sb = (SeekBar) findViewById(R.id.seekBarJumpsLast12Months);
sb.setProgress(value);
}
// make sure it will be initialized next time...
removeDialog(JUMPS_LAST_12_MONTHS_DIALOG_ID);
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// make sure it will be initialized next time...
removeDialog(JUMPS_LAST_12_MONTHS_DIALOG_ID);
}
});
return builder.create();
}
private Dialog weightDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.weightDialogTitle));
builder.setMessage(String.format(getString(R.string.enterWeightFormat),
WEIGHT_MIN, WEIGHT_MAX));
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String valueText = input.getText().toString();
int value = Integer.parseInt(valueText);
if (value >= WEIGHT_MIN && value <= WEIGHT_MAX) {
SeekBar sb = (SeekBar) findViewById(R.id.seekBarWeight);
sb.setProgress(value - WEIGHT_MIN);
}
// make sure it will be initialized next time...
removeDialog(WEIGHT_DIALOG_ID);
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// make sure it will be initialized next time...
removeDialog(WEIGHT_DIALOG_ID);
}
});
return builder.create();
}
/***
* The save dialog to allow saving the current settings. They can be saved
* as 'own' or 'friend' settings.
*
* @return
*/
private Dialog saveDialog() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.save_dialog,
(ViewGroup) findViewById(R.id.root));
Button asFriend = (Button) layout.findViewById(R.id.buttonFriend);
Button asOwn = (Button) layout.findViewById(R.id.buttonOwn);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// We forcefully dismiss and remove the Dialog, so it
// cannot be used again (no cached info)
CalculateActivity.this.removeDialog(SAVE_DIALOG_ID);
}
});
asFriend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prefs = getSharedPreferences(KOMPASROOSPREFS,
Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putInt(SETTING_FRIEND_TOTAL_JUMPS, currentTotalJumps);
e.putInt(SETTING_FRIEND_LAST_12_MONTHS,
currentJumpsLast12Months);
e.putInt(SETTING_FRIEND_WEIGHT, currentWeight);
e.commit();
CalculateActivity.this.removeDialog(SAVE_DIALOG_ID);
}
});
asOwn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prefs = getSharedPreferences(KOMPASROOSPREFS,
Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putInt(SETTING_OWN_TOTAL_JUMPS, currentTotalJumps);
e.putInt(SETTING_OWN_LAST_12_MONTHS, currentJumpsLast12Months);
e.putInt(SETTING_OWN_WEIGHT, currentWeight);
e.commit();
CalculateActivity.this.removeDialog(SAVE_DIALOG_ID);
}
});
return builder.create();
}
/***
* The dialog to reset the settings. Settings can be reset to beginner,
* intermediate or pro or to saved users own or friend settings.
*
* @return
*/
private Dialog resetDialog() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.reset_dialog,
(ViewGroup) findViewById(R.id.root));
Button asBeginner = (Button) layout.findViewById(R.id.buttonBeginner);
Button asIntermediate = (Button) layout
.findViewById(R.id.buttonIntermediate);
Button asSkyGod = (Button) layout.findViewById(R.id.buttonSkyGod);
Button asFriend = (Button) layout.findViewById(R.id.buttonFriend);
Button asOwn = (Button) layout.findViewById(R.id.buttonOwn);
// TODO: add onclick handlers to buttons
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// We forcefully dismiss and remove the Dialog, so it
// cannot be used again (no cached info)
CalculateActivity.this.removeDialog(RESET_DIALOG_ID);
}
});
asBeginner.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setSeekBars(WEIGHT_DEFAULT - WEIGHT_MIN, 5, 5);
CalculateActivity.this.removeDialog(RESET_DIALOG_ID);
}
});
asIntermediate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setSeekBars(WEIGHT_DEFAULT - WEIGHT_MIN, TOTALJUMPS_DEFAULT,
JUMPS_LAST_12_MONTHS_DEFAULT);
CalculateActivity.this.removeDialog(RESET_DIALOG_ID);
}
});
asSkyGod.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setSeekBars(WEIGHT_DEFAULT - WEIGHT_MIN, 1200, 200);
CalculateActivity.this.removeDialog(RESET_DIALOG_ID);
}
});
asFriend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prefs = getSharedPreferences(KOMPASROOSPREFS,
Context.MODE_PRIVATE);
int weight = prefs
.getInt(SETTING_FRIEND_WEIGHT, WEIGHT_DEFAULT);
int totalJumps = prefs.getInt(SETTING_FRIEND_TOTAL_JUMPS,
TOTALJUMPS_DEFAULT);
int jumpsLastMonth = prefs.getInt(
SETTING_FRIEND_LAST_12_MONTHS,
JUMPS_LAST_12_MONTHS_DEFAULT);
setSeekBars(weight - WEIGHT_MIN, totalJumps, jumpsLastMonth);
CalculateActivity.this.removeDialog(RESET_DIALOG_ID);
}
});
asOwn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prefs = getSharedPreferences(KOMPASROOSPREFS,
Context.MODE_PRIVATE);
int weight = prefs.getInt(SETTING_OWN_WEIGHT, WEIGHT_DEFAULT);
int totalJumps = prefs.getInt(SETTING_OWN_TOTAL_JUMPS,
TOTALJUMPS_DEFAULT);
int jumpsLastMonth = prefs.getInt(SETTING_OWN_LAST_12_MONTHS,
JUMPS_LAST_12_MONTHS_DEFAULT);
setSeekBars(weight - WEIGHT_MIN, totalJumps, jumpsLastMonth);
CalculateActivity.this.removeDialog(RESET_DIALOG_ID);
}
});
return builder.create();
}
/***
* Set three seekbars. This will automatically trigger calculate calls
* through the OnProgressChanged of the seekbars.
*
* @param weight
* @param totalJumps
* @param jumpsLast12Months
*/
private void setSeekBars(int weight, int totalJumps, int jumpsLast12Months) {
((SeekBar) findViewById(R.id.seekBarWeight)).setProgress(weight);
((SeekBar) findViewById(R.id.seekBarTotalJumps))
.setProgress(totalJumps);
((SeekBar) findViewById(R.id.seekBarJumpsLast12Months))
.setProgress(jumpsLast12Months);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_calculate, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_reset:
showDialog(RESET_DIALOG_ID);
return true;
case R.id.menu_save:
showDialog(SAVE_DIALOG_ID);
return true;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Initialize the seekbar listeners
*/
private void initSeekBars() {
// weight seek bar
SeekBar sbWeight = (SeekBar) findViewById(R.id.seekBarWeight);
sbWeight.setMax(WEIGHT_MAX - WEIGHT_MIN);
sbWeight.setOnSeekBarChangeListener(seekBarChangeListenerWeight);
setPlusMinButtonListeners(sbWeight, R.id.buttonWeightMin,
R.id.buttonWeightPlus);
// total jumps seek bar
SeekBar sbTotalJumps = (SeekBar) findViewById(R.id.seekBarTotalJumps);
sbTotalJumps.setMax(TOTALJUMPS_MAX);
sbTotalJumps
.setOnSeekBarChangeListener(seekBarChangeListenerTotalJumps);
setPlusMinButtonListeners(sbWeight, R.id.buttonTotalJumpsMin,
R.id.buttonTotalJumpsPlus);
// jumps last 12 months seek bar
SeekBar sbJumpsLast12Months = (SeekBar) findViewById(R.id.seekBarJumpsLast12Months);
sbJumpsLast12Months.setMax(JUMPS_LAST_12_MONTHS_MAX);
sbJumpsLast12Months
.setOnSeekBarChangeListener(seekBarChangeListenerJumpsLast12Months);
setPlusMinButtonListeners(sbWeight, R.id.buttonJumpLast12MonthsMin,
R.id.buttonJumpLast12MonthsPlus);
}
/***
* Initialize the seekbars texts
*/
private void initSeekBarTextsAndCalculate() {
// weight seek bar
SeekBar sbWeight = (SeekBar) findViewById(R.id.seekBarWeight);
int weightInKg = prefs.getInt(SETTING_WEIGHT, WEIGHT_DEFAULT);
sbWeight.setProgress(weightInKg - WEIGHT_MIN);
// total jumps seek bar
SeekBar sbTotalJumps = (SeekBar) findViewById(R.id.seekBarTotalJumps);
int totalJumps = prefs.getInt(SETTING_TOTAL_JUMPS, TOTALJUMPS_DEFAULT);
sbTotalJumps.setProgress(totalJumps);
// jumps last 12 months seek bar
SeekBar sbJumpsLast12Months = (SeekBar) findViewById(R.id.seekBarJumpsLast12Months);
int jumpsLast12Months = prefs.getInt(SETTING_JUMPS_LAST_12_MONTHS,
JUMPS_LAST_12_MONTHS_DEFAULT);
sbJumpsLast12Months.setProgress(jumpsLast12Months);
// now calculate to set all texts
calculate();
}
/***
* Add click listeners to the plus and min buttons at the left and right of
* a seekbar
*/
private void setPlusMinButtonListeners(SeekBar sb, int minButtonId,
int plusButtonId) {
// get the buttons based on the give id's
Button minButton = (Button) findViewById(minButtonId);
Button plusButton = (Button) findViewById(plusButtonId);
// add click listener to the min button
minButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// find matching seekbar
ViewGroup hList = (ViewGroup) v.getParent();
if (hList.getChildCount() != 3)
Log.e(LOG_TAG,
"Incorrect number of children in seekbargroup");
SeekBar sb = (SeekBar) hList.getChildAt(1);
int progress = sb.getProgress();
if (progress > 0)
sb.setProgress(progress - 1);
}
});
// add click listener to the plus button
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// find matching seekbar
ViewGroup hList = (ViewGroup) v.getParent();
if (hList.getChildCount() != 3)
Log.e(LOG_TAG,
"Incorrect number of children in seekbargroup");
SeekBar sb = (SeekBar) hList.getChildAt(1);
int progress = sb.getProgress();
if (progress < sb.getMax())
sb.setProgress(progress + 1);
}
});
}
/***
* The seekbar change listener for the exit weight
*/
private OnSeekBarChangeListener seekBarChangeListenerWeight = new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
int weightInKg = progress + WEIGHT_MIN;
savePreference(SETTING_WEIGHT, weightInKg);
currentWeight = weightInKg;
setWeightSettingText(weightInKg);
calculate();
}
public void onStartTrackingTouch(SeekBar seekBar) {
// No action required
}
public void onStopTrackingTouch(SeekBar seekBar) {
// No action required
}
};
/***
* Listener for changes on the total jumps seekbar. Triggers a calculate
* call, that updates texts where needed.
*/
private OnSeekBarChangeListener seekBarChangeListenerTotalJumps = new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
savePreference(SETTING_TOTAL_JUMPS, progress);
currentTotalJumps = progress;
setTotalJumpsSettingText(progress);
// check to see if jumps in last 12 months in not higher
SeekBar sbJumpsLast12Months = (SeekBar) findViewById(R.id.seekBarJumpsLast12Months);
int jumpsLast12Months = sbJumpsLast12Months.getProgress();
if (jumpsLast12Months > progress)
sbJumpsLast12Months.setProgress(progress);
calculate();
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
/***
* Listener for changes on the jumps in last 12 months seekbar. Triggers a
* calculate call, that updates texts where needed.
*/
private OnSeekBarChangeListener seekBarChangeListenerJumpsLast12Months = new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
savePreference(SETTING_JUMPS_LAST_12_MONTHS, progress);
currentJumpsLast12Months = progress;
setJumpsLast12MonthsSettingText(progress);
// check to see if jumps in last 12 months in not higher
SeekBar sbTotalJumps = (SeekBar) findViewById(R.id.seekBarTotalJumps);
int totalJumps = sbTotalJumps.getProgress();
if (totalJumps < progress)
sbTotalJumps.setProgress(progress);
calculate();
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
/**
* Fills the wingloadtable. As the table is allways six positings, its
* starting point depends on the current category and weight.
*
* @param weightInKg
* TODO: split in fill (first row) & update (second row & colors)
*/
private void fillWingloadTable(int weightInKg) {
final int[] WLTBL = new int[] { 120, 135, 150, 170, 190, 210, 230 };
// fill the wingload table
int column = 0;
TextView area1 = (TextView) findViewById(R.id.textViewArea1);
TextView wingLoad1 = (TextView) findViewById(R.id.textViewWingLoad1);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area1, wingLoad1);
TextView area2 = (TextView) findViewById(R.id.textViewArea2);
TextView wingLoad2 = (TextView) findViewById(R.id.textViewWingLoad2);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area2, wingLoad2);
TextView area3 = (TextView) findViewById(R.id.textViewArea3);
TextView wingLoad3 = (TextView) findViewById(R.id.textViewWingLoad3);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area3, wingLoad3);
TextView area4 = (TextView) findViewById(R.id.textViewArea4);
TextView wingLoad4 = (TextView) findViewById(R.id.textViewWingLoad4);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area4, wingLoad4);
TextView area5 = (TextView) findViewById(R.id.textViewArea5);
TextView wingLoad5 = (TextView) findViewById(R.id.textViewWingLoad5);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area5, wingLoad5);
TextView area6 = (TextView) findViewById(R.id.textViewArea6);
TextView wingLoad6 = (TextView) findViewById(R.id.textViewWingLoad6);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area6, wingLoad6);
TextView area7 = (TextView) findViewById(R.id.textViewArea7);
TextView wingLoad7 = (TextView) findViewById(R.id.textViewWingLoad7);
fillWingLoadTableColumn(WLTBL[column++], weightInKg, area7, wingLoad7);
}
/***
* Fills a single column in the wing load table
*
* @param area
* @param weightInKg
* @param tvArea
* @param tvWingLoad
*/
private void fillWingLoadTableColumn(int area, int weightInKg,
TextView tvArea, TextView tvWingLoad) {
double wingload = Calculation.wingLoad(area, weightInKg);
Drawable backgroundRed = getResources().getDrawable(
R.drawable.canopycategorytoohigh);
Drawable backgroundOrange = getResources().getDrawable(
R.drawable.canopyneededsizenotavailable);
Drawable backgroundGreen = getResources().getDrawable(
R.drawable.canopyacceptable);
int areaAllowedOnCat = Calculation
.minAreaBasedOnCategory(currentMaxCategory);
boolean areaOrWingloadOutOfRange = area < Calculation.minArea(
currentMaxCategory, weightInKg);
tvArea.setText(String.format("%d", area));
if (area < areaAllowedOnCat)
tvArea.setBackgroundDrawable(backgroundRed);
else if (areaOrWingloadOutOfRange)
tvArea.setBackgroundDrawable(backgroundOrange);
else
tvArea.setBackgroundDrawable(backgroundGreen);
double maxWinloadAllowed = Calculation
.maxWingLoadBasedOnCategory(currentMaxCategory);
tvWingLoad.setText(String.format("%.2f", wingload));
if (wingload > maxWinloadAllowed)
tvWingLoad.setBackgroundDrawable(backgroundRed);
else if (areaOrWingloadOutOfRange)
tvWingLoad.setBackgroundDrawable(backgroundOrange);
else
tvWingLoad.setBackgroundDrawable(backgroundGreen);
}
private void setTotalJumpsSettingText(int totalJumps) {
TextView tvTotalJumps = (TextView) findViewById(R.id.textViewTotalJumpsLabel);
String totalJumpsLabel = getString(R.string.calculationTotalJumpsLabel);
String totalJumpsFormat = getString(R.string.calculationTotalJumpsSetting);
String orMoreText = "";
if (totalJumps > TOTALJUMPS_LASTGROUP)
orMoreText = getString(R.string.ormore);
tvTotalJumps.setText(totalJumpsLabel
+ String.format(totalJumpsFormat, totalJumps, orMoreText));
}
private void setJumpsLast12MonthsSettingText(int jumps) {
TextView tvJumpsLast12Months = (TextView) findViewById(R.id.textViewJumpsLast12MonthsLabel);
String jumpsLast12MonthsLabel = getString(R.string.calculationJumpsLast12MonthsLabel);
String jumpsLast12MonthsFormat = getString(R.string.calculationJumpsLast12MonthsSetting);
String orMoreText = "";
if (jumps > JUMPS_LAST_12_MONTHS_LASTGROUP)
orMoreText = getString(R.string.ormore);
tvJumpsLast12Months.setText(jumpsLast12MonthsLabel
+ String.format(jumpsLast12MonthsFormat, jumps, orMoreText));
}
private void setWeightSettingText(int weightInKg) {
TextView tvWeight = (TextView) findViewById(R.id.textViewWeightLabel);
String weightLabel = getString(R.string.calculationWeightLabel);
String weightFormat = getString(R.string.calculationWeightSetting);
tvWeight.setText(weightLabel
+ String.format(weightFormat, weightInKg,
Calculation.kgToLbs(weightInKg)));
fillWingloadTable(weightInKg);
}
/**
* Calculate the current category, based on weight, total jumps and jumps
* last year.
*/
private void calculate() {
// get weight and set text
SeekBar sbWeight = (SeekBar) findViewById(R.id.seekBarWeight);
int weightInKg = sbWeight.getProgress() + WEIGHT_MIN;
SeekBar sbTotalJumps = (SeekBar) findViewById(R.id.seekBarTotalJumps);
int totalJumps = sbTotalJumps.getProgress();
SeekBar sbJumpsLast12Months = (SeekBar) findViewById(R.id.seekBarJumpsLast12Months);
int jumpsLast12Months = sbJumpsLast12Months.getProgress();
int jumperCategory = Calculation.jumperCategory(totalJumps,
jumpsLast12Months);
// now decide on minArea and maxWingload
int minArea = Calculation.minArea(jumperCategory, weightInKg);
// only update screen if there actually is a change, so seek bars
// respond quickly
if (KompasroosBaseActivity.currentMaxCategory != jumperCategory
|| KompasroosBaseActivity.currentMinArea != minArea) {
TextView tvJumperCategory = (TextView) findViewById(R.id.textViewJumperCategory);
String jumperCatFormat = getString(R.string.categorySetting);
tvJumperCategory.setText(String.format(jumperCatFormat,
jumperCategory));
TextView tvJumperCategoryDescription = (TextView) findViewById(R.id.textViewJumperCategoryDescription);
String jumperCatDescriptionFormat = getString(R.string.categorySettingDescription);
String jumperCategories[] = getResources().getStringArray(
R.array.jumperCategories);
tvJumperCategoryDescription.setText(String.format(
jumperCatDescriptionFormat,
jumperCategories[jumperCategory]));
TextView tvCanopyCategory = (TextView) findViewById(R.id.textViewCanopyCategoryText);
String canopyCatFormat;
canopyCatFormat = String.format(
getString(R.string.calculationCanopyCategory),
jumperCategory);
tvCanopyCategory.setText(canopyCatFormat);
TextView tvCanopyMinArea = (TextView) findViewById(R.id.textViewCanopyMinAreaText);
int minAreaBasedOnCategory = Calculation
.minAreaBasedOnCategory(jumperCategory);
String minAreaText;
// TODO: this string should be taken from canopy class (or method in
// calculation)
switch (minAreaBasedOnCategory) {
case 0:
minAreaText = getString(R.string.calculationCanopyMinAreaAny);
break;
default:
minAreaText = String.format(
getString(R.string.calculationCanopyMinArea),
minAreaBasedOnCategory);
break;
}
tvCanopyMinArea.setText(minAreaText);
TextView tvCanopyMaxWingLoad = (TextView) findViewById(R.id.textViewCanopyMaxWingLoadText);
double maxWingLoad = Calculation
.maxWingLoadBasedOnCategory(jumperCategory);
String maxWingLoadText;
if (maxWingLoad > 10)
maxWingLoadText = getString(R.string.calculationCanopyMaxWingLoadAny);
else
maxWingLoadText = String.format(
getString(R.string.calculationCanopyMaxWingLoad),
maxWingLoad);
tvCanopyMaxWingLoad.setText(maxWingLoadText);
TextView tvCanopyAdvise = (TextView) findViewById(R.id.textViewCanopyAdvise);
String canopyAdviseFormat;
// TODO: this string should be taken from a jumper class (or method
// in calculation)
canopyAdviseFormat = getString(R.string.canopyAdvise);
tvCanopyAdvise.setText(String.format(canopyAdviseFormat,
jumperCategory, minArea));
// save globally, to pass on in buttonClick
KompasroosBaseActivity.currentMaxCategory = jumperCategory;
KompasroosBaseActivity.currentMinArea = minArea;
fillWingloadTable(weightInKg);
updateSpecificCanopyTable();
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculate);
// if compile date over 1 year ago, show warning text
TextView tvWarning = (TextView) findViewById(R.id.textViewWarning);
String warning = "";
try {
long compilationDateTime = getCompileDateTime();
Calendar cal = Calendar.getInstance();
long now = cal.getTime().getTime();
long maxDiff = 1000 * 60 * 60 * 24 * 365; // 1 year
// maxDiff = 1000 * 60 * 5; // 5 mins (for testing)
if (now - compilationDateTime > maxDiff)
warning = getString(R.string.calculationOvertimeWarning);
} catch (Exception e) {
warning = getString(R.string.calculationOvertimeUnknownWarning);
}
tvWarning.setText(warning);
// initialize seek bars and calculated texts
initSeekBars();
fillSpecificCanopyTable();
// set click listener for canopy list button
ImageButton canopyListButton = (ImageButton) findViewById(R.id.buttonShowCanopyList);
canopyListButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),
CanopyTypeListActivity.class));
}
});
// set click listener for about button
ImageButton aboutButton = (ImageButton) findViewById(R.id.buttonAbout);
aboutButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), AboutActivity.class));
}
});
// add click listener for allowed header
View filterHeader = findViewById(R.id.tablelayout_filterheader);
filterHeader.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),
CanopyTypeListActivity.class));
}
});
// set click listener for specific canopy add
Button addSpecificCanopy = (Button) findViewById(R.id.buttonAddSpecificCanopy);
addSpecificCanopy.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),
SpecificCanopyEdit.class);
Bundle bundle = new Bundle();
bundle.putInt(SPECIFICCANOPYID_KEY, 0);
intent.putExtras(bundle);
startActivity(intent);
}
});
TextView tvTotalJumps = (TextView) findViewById(R.id.textViewTotalJumpsLabel);
tvTotalJumps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TOTAL_JUMPS_DIALOG_ID);
}
});
TextView tvJumpsLast12Months = (TextView) findViewById(R.id.textViewJumpsLast12MonthsLabel);
tvJumpsLast12Months.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(JUMPS_LAST_12_MONTHS_DIALOG_ID);
}
});
TextView tvWeight = (TextView) findViewById(R.id.textViewWeightLabel);
tvWeight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(WEIGHT_DIALOG_ID);
}
});
// Just for testing the canopy list
// canopyListButton.performClick();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculate);
// if compile date over 1 year ago, show warning text
TextView tvWarning = (TextView) findViewById(R.id.textViewWarning);
String warning = "";
try {
long compilationDateTime = getCompileDateTime();
Calendar cal = Calendar.getInstance();
long now = cal.getTime().getTime();
long maxDiff = 1000L * 60L * 60L * 24L * 365L; // 1 year
// maxDiff = 1000 * 60 * 5; // 5 mins (for testing)
if (now - compilationDateTime > maxDiff)
warning = getString(R.string.calculationOvertimeWarning);
} catch (Exception e) {
warning = getString(R.string.calculationOvertimeUnknownWarning);
}
tvWarning.setText(warning);
// initialize seek bars and calculated texts
initSeekBars();
fillSpecificCanopyTable();
// set click listener for canopy list button
ImageButton canopyListButton = (ImageButton) findViewById(R.id.buttonShowCanopyList);
canopyListButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),
CanopyTypeListActivity.class));
}
});
// set click listener for about button
ImageButton aboutButton = (ImageButton) findViewById(R.id.buttonAbout);
aboutButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), AboutActivity.class));
}
});
// add click listener for allowed header
View filterHeader = findViewById(R.id.tablelayout_filterheader);
filterHeader.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),
CanopyTypeListActivity.class));
}
});
// set click listener for specific canopy add
Button addSpecificCanopy = (Button) findViewById(R.id.buttonAddSpecificCanopy);
addSpecificCanopy.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),
SpecificCanopyEdit.class);
Bundle bundle = new Bundle();
bundle.putInt(SPECIFICCANOPYID_KEY, 0);
intent.putExtras(bundle);
startActivity(intent);
}
});
TextView tvTotalJumps = (TextView) findViewById(R.id.textViewTotalJumpsLabel);
tvTotalJumps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TOTAL_JUMPS_DIALOG_ID);
}
});
TextView tvJumpsLast12Months = (TextView) findViewById(R.id.textViewJumpsLast12MonthsLabel);
tvJumpsLast12Months.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(JUMPS_LAST_12_MONTHS_DIALOG_ID);
}
});
TextView tvWeight = (TextView) findViewById(R.id.textViewWeightLabel);
tvWeight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(WEIGHT_DIALOG_ID);
}
});
// Just for testing the canopy list
// canopyListButton.performClick();
}
|
diff --git a/src/dht/DHTClient.java b/src/dht/DHTClient.java
index f2de5db..d6f5311 100644
--- a/src/dht/DHTClient.java
+++ b/src/dht/DHTClient.java
@@ -1,137 +1,138 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dht;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author tcc10a
*/
public class DHTClient {
private static final int port = 1138;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
if (args.length != 1) {
System.err.println("Usage: <host>");
System.exit(1);
}
String serverHostname = args[0];
System.out.println("Attemping to connect to host " + serverHostname + " on port " + port);
while (true) {
String next = connect(serverHostname);
if (next == null) {
break;
}
serverHostname = next;
}
}
public static String connect(String serverHostname) throws IOException {
String nextHost = null;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
+ e.printStackTrace();
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Type Message (\"quit\" to quit, \"shutdown\" to shutdown both the client and the server)");
while ((userInput = stdIn.readLine()) != null) {
// send message to server
out.println(userInput);
// end loop
if (userInput.equals("quit") || userInput.equals("shutdown")) {
break;
}
String output = in.readLine();
if (output == null) {
System.out.println("Null response recived. Terminating");
break;
}
if (userInput.contains("article")) {
if (output.contains("FAIL:")) {
String node = output.substring(6);
System.out.println("Error: Try node: " + node);
nextHost = node;
break;
} else {
String request = userInput.substring(8);
//System.out.println(request);
int req = Integer.parseInt(request);
FileOutputStream fos = new FileOutputStream("article" + req + ".txt");
int x = 0;
while (true) {
x = in.read();
if (x == -1) {
break;
}
fos.write(x);
}
System.out.println("Wrote to file article" + req + ".txt");
System.out.println("Contents of file:\n"+readFile("article" + req + ".txt"));
nextHost = null;
}
} else {
System.out.println("Response: " + output);
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
return nextHost;
}
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
}
}
| true | true | public static String connect(String serverHostname) throws IOException {
String nextHost = null;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Type Message (\"quit\" to quit, \"shutdown\" to shutdown both the client and the server)");
while ((userInput = stdIn.readLine()) != null) {
// send message to server
out.println(userInput);
// end loop
if (userInput.equals("quit") || userInput.equals("shutdown")) {
break;
}
String output = in.readLine();
if (output == null) {
System.out.println("Null response recived. Terminating");
break;
}
if (userInput.contains("article")) {
if (output.contains("FAIL:")) {
String node = output.substring(6);
System.out.println("Error: Try node: " + node);
nextHost = node;
break;
} else {
String request = userInput.substring(8);
//System.out.println(request);
int req = Integer.parseInt(request);
FileOutputStream fos = new FileOutputStream("article" + req + ".txt");
int x = 0;
while (true) {
x = in.read();
if (x == -1) {
break;
}
fos.write(x);
}
System.out.println("Wrote to file article" + req + ".txt");
System.out.println("Contents of file:\n"+readFile("article" + req + ".txt"));
nextHost = null;
}
} else {
System.out.println("Response: " + output);
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
return nextHost;
}
| public static String connect(String serverHostname) throws IOException {
String nextHost = null;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Type Message (\"quit\" to quit, \"shutdown\" to shutdown both the client and the server)");
while ((userInput = stdIn.readLine()) != null) {
// send message to server
out.println(userInput);
// end loop
if (userInput.equals("quit") || userInput.equals("shutdown")) {
break;
}
String output = in.readLine();
if (output == null) {
System.out.println("Null response recived. Terminating");
break;
}
if (userInput.contains("article")) {
if (output.contains("FAIL:")) {
String node = output.substring(6);
System.out.println("Error: Try node: " + node);
nextHost = node;
break;
} else {
String request = userInput.substring(8);
//System.out.println(request);
int req = Integer.parseInt(request);
FileOutputStream fos = new FileOutputStream("article" + req + ".txt");
int x = 0;
while (true) {
x = in.read();
if (x == -1) {
break;
}
fos.write(x);
}
System.out.println("Wrote to file article" + req + ".txt");
System.out.println("Contents of file:\n"+readFile("article" + req + ".txt"));
nextHost = null;
}
} else {
System.out.println("Response: " + output);
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
return nextHost;
}
|
diff --git a/src/main/java/br/com/caelum/tubaina/parser/html/desktop/CodeTag.java b/src/main/java/br/com/caelum/tubaina/parser/html/desktop/CodeTag.java
index 0a71bb7..6c392b1 100644
--- a/src/main/java/br/com/caelum/tubaina/parser/html/desktop/CodeTag.java
+++ b/src/main/java/br/com/caelum/tubaina/parser/html/desktop/CodeTag.java
@@ -1,27 +1,27 @@
package br.com.caelum.tubaina.parser.html.desktop;
import br.com.caelum.tubaina.parser.Tag;
import br.com.caelum.tubaina.parser.html.HtmlAndKindleCodeTag;
import br.com.caelum.tubaina.parser.pygments.CodeCache;
import br.com.caelum.tubaina.parser.pygments.CodeOutputType;
import br.com.caelum.tubaina.util.CommandExecutor;
public class CodeTag implements Tag {
private HtmlAndKindleCodeTag htmlCodeTag;
public CodeTag() {
SyntaxHighlighter syntaxHighlighter = new SyntaxHighlighter(new CommandExecutor(),
- CodeOutputType.KINDLE_HTML, true, new CodeCache(CodeOutputType.HTML));
+ CodeOutputType.KINDLE_HTML, false, new CodeCache(CodeOutputType.HTML));
htmlCodeTag = new HtmlAndKindleCodeTag(syntaxHighlighter);
}
public CodeTag(HtmlAndKindleCodeTag htmlCodeTag) {
this.htmlCodeTag = htmlCodeTag;
}
public String parse(String content, String options) {
return htmlCodeTag.parse(content, options);
}
}
| true | true | public CodeTag() {
SyntaxHighlighter syntaxHighlighter = new SyntaxHighlighter(new CommandExecutor(),
CodeOutputType.KINDLE_HTML, true, new CodeCache(CodeOutputType.HTML));
htmlCodeTag = new HtmlAndKindleCodeTag(syntaxHighlighter);
}
| public CodeTag() {
SyntaxHighlighter syntaxHighlighter = new SyntaxHighlighter(new CommandExecutor(),
CodeOutputType.KINDLE_HTML, false, new CodeCache(CodeOutputType.HTML));
htmlCodeTag = new HtmlAndKindleCodeTag(syntaxHighlighter);
}
|
diff --git a/src/main/java/de/Lathanael/EC/Utils/Scheduler.java b/src/main/java/de/Lathanael/EC/Utils/Scheduler.java
index 7d79343..14c9958 100644
--- a/src/main/java/de/Lathanael/EC/Utils/Scheduler.java
+++ b/src/main/java/de/Lathanael/EC/Utils/Scheduler.java
@@ -1,178 +1,182 @@
/*************************************************************************
* Copyright (C) 2012 Philippe Leipold
*
* EntityCleaner 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.
*
* EntityCleaner 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 EntityCleaner. If not, see <http://www.gnu.org/licenses/>.
*
**************************************************************************/
package de.Lathanael.EC.Utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import be.Balor.Tools.MaterialContainer;
import be.Balor.Tools.Utils;
import be.Balor.Tools.Debug.ACLogger;
import be.Balor.Tools.Exceptions.InvalidInputException;
import de.Lathanael.EC.Main.EntityCleaner;
import de.Lathanael.EC.Tasks.AnimalTask;
import de.Lathanael.EC.Tasks.ArrowTask;
import de.Lathanael.EC.Tasks.BoatTask;
import de.Lathanael.EC.Tasks.CartTask;
import de.Lathanael.EC.Tasks.CompleteTask;
import de.Lathanael.EC.Tasks.FloatingItemsTask;
import de.Lathanael.EC.Tasks.MonsterTask;
import de.Lathanael.EC.Tasks.OrbTask;
import de.Lathanael.EC.Tasks.VehicleTask;
import de.Lathanael.EC.Tasks.VillagerTask;
/**
* @author Lathanael (aka Philippe Leipold)
*
*/
public class Scheduler {
public static HashMap<String, Integer> taskIDs = new HashMap<String, Integer>();
public static HashMap<String, TaskContainer> tasks = new HashMap<String, TaskContainer>();
public Server server;
public List<World> worlds = new ArrayList<World>();
public HashMap<String, List<Material>> items = new HashMap<String, List<Material>>();
private EntityCleaner instance;
public Scheduler(Server server, EntityCleaner instance) {
this.server = server;
this.instance = instance;
Set<String> list = ECConfig.getConfig().getKeys(false);
list.remove("debugMsg");
Tools.debugMsg("Loading worlds...");
for (String world : list) {
if (EntityCleaner.debug)
Tools.debugMsg("Adding world: " + server.getWorld(world).getName());
worlds.add(server.getWorld(world));
List<Material> item = new ArrayList<Material>();
List<String> itemName = ECConfig.getStringList(world + ".item.list");
for(String s : itemName) {
MaterialContainer m = null;
try {
m = Utils.checkMaterial(s);
} catch (InvalidInputException e) {
final HashMap<String, String> replace = new HashMap<String, String>();
replace.put("material", s);
ACLogger.Log(Utils.I18n("unknownMat", replace));
}
if (m.isNull()) {
continue;
}
Material mat = m.getMaterial();
if (mat != null)
item.add(mat);
}
items.put(world, item);
}
initTaskList();
}
public void startTasks() {
for (Map.Entry<String, TaskContainer> map : tasks.entrySet()) {
TaskContainer container = map.getValue();
if (container.isEnabled())
startTask(container.getTask(), map.getKey(), container.getInitTIme(), container.getTime());
}
}
public void startTask(Runnable task, String taskName, long initTime, long time) {
taskIDs.put(taskName, server.getScheduler().scheduleSyncRepeatingTask(
instance, task, initTime, time));
}
public void startTask(String task) {
TaskContainer container = tasks.get(task);
taskIDs.put(task, server.getScheduler().scheduleSyncRepeatingTask(
instance, container.getTask(), container.getInitTIme(), container.getTime()));
}
public void stopTasks() {
for (Map.Entry<String, Integer> entries : taskIDs.entrySet())
stopTask(entries.getKey(), entries.getValue());
}
public void stopTask(String taskName, int id) {
server.getScheduler().cancelTask(id);
taskIDs.remove(taskName);
}
public void stopTask(String className) {
int id = taskIDs.get(className);
server.getScheduler().cancelTask(id);
taskIDs.remove(className);
}
public void restartTask(String task) {
int id = taskIDs.get(task);
server.getScheduler().cancelTask(id);
taskIDs.remove(task);
startTask(task);
}
public void reInitTaskList() {
tasks.clear();
initTaskList();
}
//---------------------------------private functons-----------------------------------------
private void initTaskList() {
for (World world : worlds) {
+ if (world == null) {
+ Tools.debugMsg("World was null, contueing loop for other worlds if there are any in the list....");
+ continue;
+ }
String name = world.getName();
tasks.put(name + ".cart", new TaskContainer((Runnable) new CartTask(world), (long) (ECConfig.getDouble(name + ".cart.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".cart.time", 5D)*20*60), ECConfig.getBoolean(name + ".cart.enable"),
ECConfig.getBoolean(name + ".cart.protect"), ECConfig.getBoolean(name + ".cart.passenger")));
tasks.put(name + ".boat", new TaskContainer((Runnable) new BoatTask(world), (long) (ECConfig.getDouble(name + ".boat.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".boat.time", 5D)*20*60), ECConfig.getBoolean(name + ".boat.enable"),
ECConfig.getBoolean(name + ".boat.protect"), ECConfig.getBoolean(name + ".boat.passenger")));
tasks.put(name + ".arrow", new TaskContainer((Runnable) new ArrowTask(world), (long) (ECConfig.getDouble(name + ".arrow.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".arrow.time", 5D)*20*60), ECConfig.getBoolean(name + ".arrow.enable"), false, false));
tasks.put(name + ".animal", new TaskContainer((Runnable) new AnimalTask(world), (long) (ECConfig.getDouble(name + ".animal.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".animal.time", 5D)*20*60), ECConfig.getBoolean(name + "animal.enable"), false, false));
tasks.put(name + ".orb", new TaskContainer((Runnable) new OrbTask(world), (long) (ECConfig.getDouble(name + ".orb.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".orb.time", 5D)*20*60), ECConfig.getBoolean(name + ".orb.enable"), false, false));
tasks.put(name + ".monster", new TaskContainer((Runnable) new MonsterTask(world), (long) (ECConfig.getDouble(name + ".monster.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".monster.time", 5D)*20*60), ECConfig.getBoolean(name + ".monster.enable"), false, false));
tasks.put(name + ".villager", new TaskContainer((Runnable) new VillagerTask(world), (long) (ECConfig.getDouble(name + ".villager.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".villager.time", 5D)*20*60), ECConfig.getBoolean(name + ".villager.enable"), false, false));
tasks.put(name + ".item", new TaskContainer((Runnable) new FloatingItemsTask(world, items.get(world)), (long) (ECConfig.getDouble(name + ".item.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".item.time", 5D)*20*60), ECConfig.getBoolean(name + ".item.enable"), false, false));
tasks.put(name + ".vehicle", new TaskContainer((Runnable) new VehicleTask(world), (long) (ECConfig.getDouble(name + ".vehicle.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".vehicle.time", 5D)*20*60), ECConfig.getBoolean(name + ".vehicle.enable"),
ECConfig.getBoolean(name + ".vehicle.protect"), ECConfig.getBoolean(name + ".vehicle.passenger")));
tasks.put(name + ".all", new TaskContainer((Runnable) new CompleteTask(world), (long) (ECConfig.getDouble(name + ".all.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".all.time", 5D)*20*60), ECConfig.getBoolean(name + ".all.enable"),
ECConfig.getBoolean(name + ".all.protect"), ECConfig.getBoolean(name + ".all.passenger"))); }
}
}
| true | true | private void initTaskList() {
for (World world : worlds) {
String name = world.getName();
tasks.put(name + ".cart", new TaskContainer((Runnable) new CartTask(world), (long) (ECConfig.getDouble(name + ".cart.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".cart.time", 5D)*20*60), ECConfig.getBoolean(name + ".cart.enable"),
ECConfig.getBoolean(name + ".cart.protect"), ECConfig.getBoolean(name + ".cart.passenger")));
tasks.put(name + ".boat", new TaskContainer((Runnable) new BoatTask(world), (long) (ECConfig.getDouble(name + ".boat.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".boat.time", 5D)*20*60), ECConfig.getBoolean(name + ".boat.enable"),
ECConfig.getBoolean(name + ".boat.protect"), ECConfig.getBoolean(name + ".boat.passenger")));
tasks.put(name + ".arrow", new TaskContainer((Runnable) new ArrowTask(world), (long) (ECConfig.getDouble(name + ".arrow.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".arrow.time", 5D)*20*60), ECConfig.getBoolean(name + ".arrow.enable"), false, false));
tasks.put(name + ".animal", new TaskContainer((Runnable) new AnimalTask(world), (long) (ECConfig.getDouble(name + ".animal.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".animal.time", 5D)*20*60), ECConfig.getBoolean(name + "animal.enable"), false, false));
tasks.put(name + ".orb", new TaskContainer((Runnable) new OrbTask(world), (long) (ECConfig.getDouble(name + ".orb.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".orb.time", 5D)*20*60), ECConfig.getBoolean(name + ".orb.enable"), false, false));
tasks.put(name + ".monster", new TaskContainer((Runnable) new MonsterTask(world), (long) (ECConfig.getDouble(name + ".monster.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".monster.time", 5D)*20*60), ECConfig.getBoolean(name + ".monster.enable"), false, false));
tasks.put(name + ".villager", new TaskContainer((Runnable) new VillagerTask(world), (long) (ECConfig.getDouble(name + ".villager.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".villager.time", 5D)*20*60), ECConfig.getBoolean(name + ".villager.enable"), false, false));
tasks.put(name + ".item", new TaskContainer((Runnable) new FloatingItemsTask(world, items.get(world)), (long) (ECConfig.getDouble(name + ".item.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".item.time", 5D)*20*60), ECConfig.getBoolean(name + ".item.enable"), false, false));
tasks.put(name + ".vehicle", new TaskContainer((Runnable) new VehicleTask(world), (long) (ECConfig.getDouble(name + ".vehicle.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".vehicle.time", 5D)*20*60), ECConfig.getBoolean(name + ".vehicle.enable"),
ECConfig.getBoolean(name + ".vehicle.protect"), ECConfig.getBoolean(name + ".vehicle.passenger")));
tasks.put(name + ".all", new TaskContainer((Runnable) new CompleteTask(world), (long) (ECConfig.getDouble(name + ".all.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".all.time", 5D)*20*60), ECConfig.getBoolean(name + ".all.enable"),
ECConfig.getBoolean(name + ".all.protect"), ECConfig.getBoolean(name + ".all.passenger"))); }
}
| private void initTaskList() {
for (World world : worlds) {
if (world == null) {
Tools.debugMsg("World was null, contueing loop for other worlds if there are any in the list....");
continue;
}
String name = world.getName();
tasks.put(name + ".cart", new TaskContainer((Runnable) new CartTask(world), (long) (ECConfig.getDouble(name + ".cart.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".cart.time", 5D)*20*60), ECConfig.getBoolean(name + ".cart.enable"),
ECConfig.getBoolean(name + ".cart.protect"), ECConfig.getBoolean(name + ".cart.passenger")));
tasks.put(name + ".boat", new TaskContainer((Runnable) new BoatTask(world), (long) (ECConfig.getDouble(name + ".boat.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".boat.time", 5D)*20*60), ECConfig.getBoolean(name + ".boat.enable"),
ECConfig.getBoolean(name + ".boat.protect"), ECConfig.getBoolean(name + ".boat.passenger")));
tasks.put(name + ".arrow", new TaskContainer((Runnable) new ArrowTask(world), (long) (ECConfig.getDouble(name + ".arrow.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".arrow.time", 5D)*20*60), ECConfig.getBoolean(name + ".arrow.enable"), false, false));
tasks.put(name + ".animal", new TaskContainer((Runnable) new AnimalTask(world), (long) (ECConfig.getDouble(name + ".animal.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".animal.time", 5D)*20*60), ECConfig.getBoolean(name + "animal.enable"), false, false));
tasks.put(name + ".orb", new TaskContainer((Runnable) new OrbTask(world), (long) (ECConfig.getDouble(name + ".orb.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".orb.time", 5D)*20*60), ECConfig.getBoolean(name + ".orb.enable"), false, false));
tasks.put(name + ".monster", new TaskContainer((Runnable) new MonsterTask(world), (long) (ECConfig.getDouble(name + ".monster.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".monster.time", 5D)*20*60), ECConfig.getBoolean(name + ".monster.enable"), false, false));
tasks.put(name + ".villager", new TaskContainer((Runnable) new VillagerTask(world), (long) (ECConfig.getDouble(name + ".villager.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".villager.time", 5D)*20*60), ECConfig.getBoolean(name + ".villager.enable"), false, false));
tasks.put(name + ".item", new TaskContainer((Runnable) new FloatingItemsTask(world, items.get(world)), (long) (ECConfig.getDouble(name + ".item.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".item.time", 5D)*20*60), ECConfig.getBoolean(name + ".item.enable"), false, false));
tasks.put(name + ".vehicle", new TaskContainer((Runnable) new VehicleTask(world), (long) (ECConfig.getDouble(name + ".vehicle.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".vehicle.time", 5D)*20*60), ECConfig.getBoolean(name + ".vehicle.enable"),
ECConfig.getBoolean(name + ".vehicle.protect"), ECConfig.getBoolean(name + ".vehicle.passenger")));
tasks.put(name + ".all", new TaskContainer((Runnable) new CompleteTask(world), (long) (ECConfig.getDouble(name + ".all.inittime", 0.5D)*20*60),
(long) (ECConfig.getDouble(name + ".all.time", 5D)*20*60), ECConfig.getBoolean(name + ".all.enable"),
ECConfig.getBoolean(name + ".all.protect"), ECConfig.getBoolean(name + ".all.passenger"))); }
}
|
diff --git a/projects/java_dann_examples/src/com/syncleus/core/dann/examples/colormap/AboutDialog.java b/projects/java_dann_examples/src/com/syncleus/core/dann/examples/colormap/AboutDialog.java
index 6ad05d3..8d7ce6d 100644
--- a/projects/java_dann_examples/src/com/syncleus/core/dann/examples/colormap/AboutDialog.java
+++ b/projects/java_dann_examples/src/com/syncleus/core/dann/examples/colormap/AboutDialog.java
@@ -1,124 +1,124 @@
/******************************************************************************
* *
* Copyright: (c) Syncleus, Inc. *
* *
* You may redistribute and modify this source code under the terms and *
* conditions of the Open Source Community License - Type C version 1.0 *
* or any later version as published by Syncleus, Inc. at www.syncleus.com. *
* There should be a copy of the license included with this file. If a copy *
* of the license is not included you are granted no right to distribute or *
* otherwise use this file except through a legal and valid license. You *
* should also contact Syncleus, Inc. at the information below if you cannot *
* find a license: *
* *
* Syncleus, Inc. *
* 2604 South 12th Street *
* Philadelphia, PA 19148 *
* *
******************************************************************************/
package com.syncleus.core.dann.examples.colormap;
import com.syncleus.core.dann.examples.nci.ui.*;
import java.awt.Frame;
import javax.swing.JDialog;
public class AboutDialog extends JDialog
{
public AboutDialog(Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/** 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();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
jButton1.setText("OK");
jButton1.setName("ok button"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Syncleus, Inc.");
jLabel2.setText("SOM Color Map Demo");
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setHorizontalScrollBar(null);
jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setRows(5);
- jTextArea1.setText("Instructions:\n\nFirst select the number of iterations to train train the som. Next select the\ninitial learning rate for training. Finally choose 1D or 2d output lattice.\n\nNow when you click \"Train & Display\" it will train a new SOM and render the\noutput lattice colors. If the SOM was successful colors should be displayed as\nsmoothly blended colors in 1D or 2D. If the colors do not render properly\nexperiment with different values.");
+ jTextArea1.setText("Instructions:\n\nFirst select the number of iterations to train train the som. Next select the\ninitial learning rate for training. Finally choose 1D or 2D output lattice.\n\nNow when you click \"Train & Display\" it will train a new SOM and render the\noutput lattice colors. If the SOM was successful colors should be displayed as\nsmoothly blended colors in 1D or 2D. If the colors do not render properly\nexperiment with different values.");
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(170, 170, 170)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(jLabel1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(11, 11, 11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
jButton1.setText("OK");
jButton1.setName("ok button"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Syncleus, Inc.");
jLabel2.setText("SOM Color Map Demo");
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setHorizontalScrollBar(null);
jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setRows(5);
jTextArea1.setText("Instructions:\n\nFirst select the number of iterations to train train the som. Next select the\ninitial learning rate for training. Finally choose 1D or 2d output lattice.\n\nNow when you click \"Train & Display\" it will train a new SOM and render the\noutput lattice colors. If the SOM was successful colors should be displayed as\nsmoothly blended colors in 1D or 2D. If the colors do not render properly\nexperiment with different values.");
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(170, 170, 170)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(jLabel1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(11, 11, 11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
jButton1.setText("OK");
jButton1.setName("ok button"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Syncleus, Inc.");
jLabel2.setText("SOM Color Map Demo");
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setHorizontalScrollBar(null);
jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setRows(5);
jTextArea1.setText("Instructions:\n\nFirst select the number of iterations to train train the som. Next select the\ninitial learning rate for training. Finally choose 1D or 2D output lattice.\n\nNow when you click \"Train & Display\" it will train a new SOM and render the\noutput lattice colors. If the SOM was successful colors should be displayed as\nsmoothly blended colors in 1D or 2D. If the colors do not render properly\nexperiment with different values.");
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(170, 170, 170)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(jLabel1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(11, 11, 11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/com/bittrust/http/server/RequestWorker.java b/src/com/bittrust/http/server/RequestWorker.java
index ed20546..cce52a1 100644
--- a/src/com/bittrust/http/server/RequestWorker.java
+++ b/src/com/bittrust/http/server/RequestWorker.java
@@ -1,80 +1,80 @@
/**
* @author William Speirs <bill.speirs@gmail.com>
*/
package com.bittrust.http.server;
import java.io.IOException;
import java.net.Socket;
import org.apache.http.HttpException;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandlerResolver;
import org.apache.http.protocol.HttpService;
/**
* @class RequestWorker
*
* Process a request from the server.
*/
public class RequestWorker extends Thread{
private DefaultHttpServerConnection connection;
private HttpParams params;
private HttpRequestHandlerResolver resolver;
private HttpProcessor processor;
private HttpResponseFactory responseFactory;
private HttpContext context;
/**
* Setup the worker.
* @param socket The socket to read/write from/to
* @param resolver The resolvers for the URLs
*/
public RequestWorker(Socket socket, HttpRequestHandlerResolver resolver) {
this.resolver = resolver;
this.params = new BasicHttpParams();
this.connection = new DefaultHttpServerConnection();
this.processor = new BasicHttpProcessor();
this.responseFactory = new DefaultHttpResponseFactory();
this.context = new BasicHttpContext();
try { connection.bind(socket, params); }
catch(IOException e) {
e.printStackTrace();
}
}
/**
* Simply handle the request as described by the proper handler.
*/
public void run() {
HttpService httpService = new HttpService(this.processor,
new DefaultConnectionReuseStrategy(),
this.responseFactory,
this.resolver,
this.params);
while(connection.isOpen()) {
try {
// set the remote address in the context so we can audit it later
- context.setAttribute("REMOTE_ADDR", connection.getRemoteAddress());
+ context.setAttribute("REMOTE_ADDRESS", connection.getRemoteAddress());
httpService.handleRequest(connection, context);
} catch (IOException e) {
//e.printStackTrace();
} catch (HttpException e) {
System.err.println("HTTP EXCEPTION: " + e.getMessage());
e.printStackTrace();
}
}
}
}
| true | true | public void run() {
HttpService httpService = new HttpService(this.processor,
new DefaultConnectionReuseStrategy(),
this.responseFactory,
this.resolver,
this.params);
while(connection.isOpen()) {
try {
// set the remote address in the context so we can audit it later
context.setAttribute("REMOTE_ADDR", connection.getRemoteAddress());
httpService.handleRequest(connection, context);
} catch (IOException e) {
//e.printStackTrace();
} catch (HttpException e) {
System.err.println("HTTP EXCEPTION: " + e.getMessage());
e.printStackTrace();
}
}
}
| public void run() {
HttpService httpService = new HttpService(this.processor,
new DefaultConnectionReuseStrategy(),
this.responseFactory,
this.resolver,
this.params);
while(connection.isOpen()) {
try {
// set the remote address in the context so we can audit it later
context.setAttribute("REMOTE_ADDRESS", connection.getRemoteAddress());
httpService.handleRequest(connection, context);
} catch (IOException e) {
//e.printStackTrace();
} catch (HttpException e) {
System.err.println("HTTP EXCEPTION: " + e.getMessage());
e.printStackTrace();
}
}
}
|
diff --git a/DistFileSystem/src/distserver/ServCheckPosition.java b/DistFileSystem/src/distserver/ServCheckPosition.java
index 32af7d3..399425a 100644
--- a/DistFileSystem/src/distserver/ServCheckPosition.java
+++ b/DistFileSystem/src/distserver/ServCheckPosition.java
@@ -1,178 +1,179 @@
/**
* @author paul
*/
package distserver;
import distconfig.ConnectionCodes;
import distconfig.DistConfig;
import distnodelisting.NodeSearchTable;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Checks the clients position in the network
* @author paul
*/
public class ServCheckPosition implements Runnable {
private Socket client = null;
private DistConfig distConfig = null;
/**
*
* @param cli : The socket to which the client is connected
*/
public ServCheckPosition (Socket cli) {
this.client = cli;
}
/**
* Checks the position of the client
* If it is in the correct location, the server sends the new client
* its new predecessor ID and IP and new successor ID and IP
*/
@Override
public void run() {
try {
System.out.println("In thread for check position");
this.distConfig = DistConfig.get_Instance();
// Get the input stream for the client
BufferedReader inStream = new BufferedReader (
new InputStreamReader(client.getInputStream()));
System.out.println("Got the input stream");
// Get the output stream for the client
BufferedOutputStream bos = new BufferedOutputStream (
client.getOutputStream());
// Setup the writer to the client
PrintWriter outStream = new PrintWriter(bos, false);
System.out.println("Got the out stream");
// Setup the object writer to the client
ObjectOutputStream oos = new ObjectOutputStream (bos);
System.out.println("Got the object output stream");
// Send an acknowledgment that the server is connected
// for checking the position
System.out.println("Sending the connection code");
outStream.println(ConnectionCodes.CHECKPOSITION);
outStream.flush();
// Receive the new node's ID
System.out.println("Waiting for node ID");
- String newNodeID = (String)inStream.readLine();
+ String newNodeID = inStream.readLine();
int newID = Integer.parseInt(newNodeID);
+ System.out.println("Recieved ID as " + newNodeID);
System.out.printf("Recieved ID as %d\n", newID);
System.out.flush();
NodeSearchTable dct = NodeSearchTable.get_Instance();
// Get own ID
int id = Integer.parseInt(dct.get_ownID());
// If own ID = the new nodes ID, create a new ID for it
if (newID == id) {
newID = (newID + 1) % distConfig.get_MaxNodes();
outStream.println(ConnectionCodes.NEWID);
outStream.flush();
System.out.println("Sending ID as " + Integer.toString(newID));
System.out.flush();
outStream.println(Integer.toString(newID));
outStream.flush();
// Now continue with the check
}
System.out.printf("Own ID: %d\tPred ID: %d\n", id, Integer.parseInt(dct.get_predecessorID()));
System.out.flush();
// Check if the new node's ID is between the current ID and the next
int nextID = Integer.parseInt(dct.get_IDAt(0));
// If the new ID is between this ID and the next
if ((id < newID && newID < nextID) ||
(nextID < id && id < newID) ||
(newID < nextID && nextID < id) ||
(nextID == id)) {
// Send CORRECTPOSITION message
outStream.println(ConnectionCodes.CORRECTPOSITION);
outStream.flush();
// Send the string array of this id and ip
String[] ownInfo = { Integer.toString(id),
dct.get_ownIPAddress() };
oos.writeObject(ownInfo);
// Send the string array of the next id and ip
String[] nextInfo = { Integer.toString(nextID),
dct.get_IPAt(0) };
oos.writeObject(nextInfo);
// flush the output stream
oos.flush();
}
// Else, discover what two nodes it is between
else {
System.out.println("Not Correct Position");
// Check to see which two ID's in the connection table
// the new client ID is between
// First, use this server's ID as the starting point
String ipAddress = dct.get_ownIPAddress();
id = Integer.parseInt(dct.get_ownID());
boolean found = false;
// Now loop through all of the ID's and check if the new
// ID lies between them
for (int index = 0; index < dct.size(); index++) {
// Get the next ID
nextID = Integer.parseInt(dct.get_IDAt(index));
// Test if the new client is greater than or equal to the
// previous ID and less than the nextID
if (newID >= id && newID < nextID) {
found = true;
}
// Test if the new client is greater than or equal to the
// previous ID and greater than the next ID
else if (id > nextID && newID >= id && newID > nextID) {
found = true;
}
// Test if the new client is less than or equal to the
// previous ID and less than the next ID
else if (id > nextID && newID <= id && newID < nextID) {
found = true;
}
// If it is not between the two, set the id to the next
// id and the ip address to the next ip address
if (!found) {
id = nextID;
ipAddress = dct.get_IPAt(index);
}
}
// Once found, send the wrong position message
outStream.println(ConnectionCodes.WRONGPOSITION);
// Send the new ID and IP of the next node to check
outStream.println(Integer.toString(id));
outStream.println(ipAddress);
outStream.flush();
}
oos.close();
outStream.close();
bos.close();
inStream.close();
client.close();
}
catch (IOException ex) {
Logger.getLogger(ServCheckPosition.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| false | true | public void run() {
try {
System.out.println("In thread for check position");
this.distConfig = DistConfig.get_Instance();
// Get the input stream for the client
BufferedReader inStream = new BufferedReader (
new InputStreamReader(client.getInputStream()));
System.out.println("Got the input stream");
// Get the output stream for the client
BufferedOutputStream bos = new BufferedOutputStream (
client.getOutputStream());
// Setup the writer to the client
PrintWriter outStream = new PrintWriter(bos, false);
System.out.println("Got the out stream");
// Setup the object writer to the client
ObjectOutputStream oos = new ObjectOutputStream (bos);
System.out.println("Got the object output stream");
// Send an acknowledgment that the server is connected
// for checking the position
System.out.println("Sending the connection code");
outStream.println(ConnectionCodes.CHECKPOSITION);
outStream.flush();
// Receive the new node's ID
System.out.println("Waiting for node ID");
String newNodeID = (String)inStream.readLine();
int newID = Integer.parseInt(newNodeID);
System.out.printf("Recieved ID as %d\n", newID);
System.out.flush();
NodeSearchTable dct = NodeSearchTable.get_Instance();
// Get own ID
int id = Integer.parseInt(dct.get_ownID());
// If own ID = the new nodes ID, create a new ID for it
if (newID == id) {
newID = (newID + 1) % distConfig.get_MaxNodes();
outStream.println(ConnectionCodes.NEWID);
outStream.flush();
System.out.println("Sending ID as " + Integer.toString(newID));
System.out.flush();
outStream.println(Integer.toString(newID));
outStream.flush();
// Now continue with the check
}
System.out.printf("Own ID: %d\tPred ID: %d\n", id, Integer.parseInt(dct.get_predecessorID()));
System.out.flush();
// Check if the new node's ID is between the current ID and the next
int nextID = Integer.parseInt(dct.get_IDAt(0));
// If the new ID is between this ID and the next
if ((id < newID && newID < nextID) ||
(nextID < id && id < newID) ||
(newID < nextID && nextID < id) ||
(nextID == id)) {
// Send CORRECTPOSITION message
outStream.println(ConnectionCodes.CORRECTPOSITION);
outStream.flush();
// Send the string array of this id and ip
String[] ownInfo = { Integer.toString(id),
dct.get_ownIPAddress() };
oos.writeObject(ownInfo);
// Send the string array of the next id and ip
String[] nextInfo = { Integer.toString(nextID),
dct.get_IPAt(0) };
oos.writeObject(nextInfo);
// flush the output stream
oos.flush();
}
// Else, discover what two nodes it is between
else {
System.out.println("Not Correct Position");
// Check to see which two ID's in the connection table
// the new client ID is between
// First, use this server's ID as the starting point
String ipAddress = dct.get_ownIPAddress();
id = Integer.parseInt(dct.get_ownID());
boolean found = false;
// Now loop through all of the ID's and check if the new
// ID lies between them
for (int index = 0; index < dct.size(); index++) {
// Get the next ID
nextID = Integer.parseInt(dct.get_IDAt(index));
// Test if the new client is greater than or equal to the
// previous ID and less than the nextID
if (newID >= id && newID < nextID) {
found = true;
}
// Test if the new client is greater than or equal to the
// previous ID and greater than the next ID
else if (id > nextID && newID >= id && newID > nextID) {
found = true;
}
// Test if the new client is less than or equal to the
// previous ID and less than the next ID
else if (id > nextID && newID <= id && newID < nextID) {
found = true;
}
// If it is not between the two, set the id to the next
// id and the ip address to the next ip address
if (!found) {
id = nextID;
ipAddress = dct.get_IPAt(index);
}
}
// Once found, send the wrong position message
outStream.println(ConnectionCodes.WRONGPOSITION);
// Send the new ID and IP of the next node to check
outStream.println(Integer.toString(id));
outStream.println(ipAddress);
outStream.flush();
}
oos.close();
outStream.close();
bos.close();
inStream.close();
client.close();
}
catch (IOException ex) {
Logger.getLogger(ServCheckPosition.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public void run() {
try {
System.out.println("In thread for check position");
this.distConfig = DistConfig.get_Instance();
// Get the input stream for the client
BufferedReader inStream = new BufferedReader (
new InputStreamReader(client.getInputStream()));
System.out.println("Got the input stream");
// Get the output stream for the client
BufferedOutputStream bos = new BufferedOutputStream (
client.getOutputStream());
// Setup the writer to the client
PrintWriter outStream = new PrintWriter(bos, false);
System.out.println("Got the out stream");
// Setup the object writer to the client
ObjectOutputStream oos = new ObjectOutputStream (bos);
System.out.println("Got the object output stream");
// Send an acknowledgment that the server is connected
// for checking the position
System.out.println("Sending the connection code");
outStream.println(ConnectionCodes.CHECKPOSITION);
outStream.flush();
// Receive the new node's ID
System.out.println("Waiting for node ID");
String newNodeID = inStream.readLine();
int newID = Integer.parseInt(newNodeID);
System.out.println("Recieved ID as " + newNodeID);
System.out.printf("Recieved ID as %d\n", newID);
System.out.flush();
NodeSearchTable dct = NodeSearchTable.get_Instance();
// Get own ID
int id = Integer.parseInt(dct.get_ownID());
// If own ID = the new nodes ID, create a new ID for it
if (newID == id) {
newID = (newID + 1) % distConfig.get_MaxNodes();
outStream.println(ConnectionCodes.NEWID);
outStream.flush();
System.out.println("Sending ID as " + Integer.toString(newID));
System.out.flush();
outStream.println(Integer.toString(newID));
outStream.flush();
// Now continue with the check
}
System.out.printf("Own ID: %d\tPred ID: %d\n", id, Integer.parseInt(dct.get_predecessorID()));
System.out.flush();
// Check if the new node's ID is between the current ID and the next
int nextID = Integer.parseInt(dct.get_IDAt(0));
// If the new ID is between this ID and the next
if ((id < newID && newID < nextID) ||
(nextID < id && id < newID) ||
(newID < nextID && nextID < id) ||
(nextID == id)) {
// Send CORRECTPOSITION message
outStream.println(ConnectionCodes.CORRECTPOSITION);
outStream.flush();
// Send the string array of this id and ip
String[] ownInfo = { Integer.toString(id),
dct.get_ownIPAddress() };
oos.writeObject(ownInfo);
// Send the string array of the next id and ip
String[] nextInfo = { Integer.toString(nextID),
dct.get_IPAt(0) };
oos.writeObject(nextInfo);
// flush the output stream
oos.flush();
}
// Else, discover what two nodes it is between
else {
System.out.println("Not Correct Position");
// Check to see which two ID's in the connection table
// the new client ID is between
// First, use this server's ID as the starting point
String ipAddress = dct.get_ownIPAddress();
id = Integer.parseInt(dct.get_ownID());
boolean found = false;
// Now loop through all of the ID's and check if the new
// ID lies between them
for (int index = 0; index < dct.size(); index++) {
// Get the next ID
nextID = Integer.parseInt(dct.get_IDAt(index));
// Test if the new client is greater than or equal to the
// previous ID and less than the nextID
if (newID >= id && newID < nextID) {
found = true;
}
// Test if the new client is greater than or equal to the
// previous ID and greater than the next ID
else if (id > nextID && newID >= id && newID > nextID) {
found = true;
}
// Test if the new client is less than or equal to the
// previous ID and less than the next ID
else if (id > nextID && newID <= id && newID < nextID) {
found = true;
}
// If it is not between the two, set the id to the next
// id and the ip address to the next ip address
if (!found) {
id = nextID;
ipAddress = dct.get_IPAt(index);
}
}
// Once found, send the wrong position message
outStream.println(ConnectionCodes.WRONGPOSITION);
// Send the new ID and IP of the next node to check
outStream.println(Integer.toString(id));
outStream.println(ipAddress);
outStream.flush();
}
oos.close();
outStream.close();
bos.close();
inStream.close();
client.close();
}
catch (IOException ex) {
Logger.getLogger(ServCheckPosition.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
diff --git a/core/src/main/java/org/apache/mahout/vectors/ConstantValueEncoder.java b/core/src/main/java/org/apache/mahout/vectors/ConstantValueEncoder.java
index d76fd813..54670fa5 100644
--- a/core/src/main/java/org/apache/mahout/vectors/ConstantValueEncoder.java
+++ b/core/src/main/java/org/apache/mahout/vectors/ConstantValueEncoder.java
@@ -1,58 +1,58 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.vectors;
import org.apache.mahout.math.Vector;
/**
* An encoder that does the standard thing for a virtual bias term.
*/
public class ConstantValueEncoder extends FeatureVectorEncoder {
public ConstantValueEncoder(String name) {
super(name);
}
@Override
public void addToVector(byte[] originalForm, double weight, Vector data) {
int probes = getProbes();
String name = getName();
for (int i = 0; i < probes; i++) {
int n = hashForProbe(originalForm, data.size(), name, i);
if(isTraceEnabled()){
- trace((byte[]) null, n);
+ trace(name, n);
}
data.set(n, data.get(n) + getWeight(originalForm,weight));
}
}
@Override
protected double getWeight(byte[] originalForm, double w) {
return w;
}
@Override
public String asString(String originalForm) {
return getName();
}
@Override
protected int hashForProbe(byte[] originalForm, int dataSize, String name, int probe){
return hash(name, probe, dataSize);
}
}
| true | true | public void addToVector(byte[] originalForm, double weight, Vector data) {
int probes = getProbes();
String name = getName();
for (int i = 0; i < probes; i++) {
int n = hashForProbe(originalForm, data.size(), name, i);
if(isTraceEnabled()){
trace((byte[]) null, n);
}
data.set(n, data.get(n) + getWeight(originalForm,weight));
}
}
| public void addToVector(byte[] originalForm, double weight, Vector data) {
int probes = getProbes();
String name = getName();
for (int i = 0; i < probes; i++) {
int n = hashForProbe(originalForm, data.size(), name, i);
if(isTraceEnabled()){
trace(name, n);
}
data.set(n, data.get(n) + getWeight(originalForm,weight));
}
}
|
diff --git a/org.eclipse.zest.custom.sequence.assembly/src/org/eclipse/zest/custom/sequence/assembly/Activator.java b/org.eclipse.zest.custom.sequence.assembly/src/org/eclipse/zest/custom/sequence/assembly/Activator.java
index c3e3d95..ec109de 100644
--- a/org.eclipse.zest.custom.sequence.assembly/src/org/eclipse/zest/custom/sequence/assembly/Activator.java
+++ b/org.eclipse.zest.custom.sequence.assembly/src/org/eclipse/zest/custom/sequence/assembly/Activator.java
@@ -1,178 +1,179 @@
package org.eclipse.zest.custom.sequence.assembly;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.LinkedList;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.XMLMemento;
import org.eclipse.ui.internal.IWorkbenchConstants;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.zest.custom.sequence.assembly.editors.AssemblySequenceEditor;
import org.eclipse.zest.custom.sequence.assembly.editors.DynamicAssemblySequenceEditor;
import org.eclipse.zest.custom.sequence.assembly.editors.NavigationAssemblySequenceEditor;
import org.eclipse.zest.custom.sequence.assembly.editors.TraceEditor;
import org.eclipse.zest.custom.statediagram.assembly.editors.StateEditor;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*
* @author jbaldwin
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.eclipse.zest.custom.sequence.assembly";
static final String VERSION_STRING[] = { "0.046", "2.0" // from Workbench
// class in Eclipse
// 3.3
};
// The shared instance
private static Activator plugin;
public DynamicAssemblySequenceEditor dynamicEditor;
public NavigationAssemblySequenceEditor navEditor;
public AssemblySequenceEditor activeeditor;
//public TraceAssemblySequenceEditor tactiveeditor;
public static LinkedList<AssemblySequenceEditor> editors = new LinkedList<AssemblySequenceEditor>();
public static HashMap<String, StateEditor> stateeditors = new HashMap<String, StateEditor>();
//public static LinkedList<TraceAssemblySequenceEditor> teditors = new LinkedList<TraceAssemblySequenceEditor>();
//public static LinkedList<TraceAssemblySequenceEditor> traceEditors = new LinkedList<TraceAssemblySequenceEditor>();
public TraceEditor tactiveeditor;
public static LinkedList<TraceEditor> teditors = new LinkedList<TraceEditor>();
public static LinkedList<TraceEditor> traceEditors = new LinkedList<TraceEditor>();
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
plugin = this;
/*
* try { Location installLoc = Platform.getInstallLocation(); // fetch
* the Location that we will be modifying Location instanceLoc =
* Platform.getInstanceLocation(); // set location to c:\temp
* instanceLoc.set(installLoc.getURL(), false); } catch (Exception err)
* { err.printStackTrace(); }
*/
super.start(context);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
// TODO shut down dynamic editor because it never reopens properly
// editor.dispose();
plugin = null;
super.stop(context);
Startup.send(null, "bye");
}
private IStatus saveState(final IMemento memento) {
MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.Workbench_problemsSaving, null);
// Save the version number.
memento.putString(IWorkbenchConstants.TAG_VERSION, VERSION_STRING[1]);
// Save how many plug-ins were loaded while restoring the workbench
memento.putInteger(IWorkbenchConstants.TAG_PROGRESS_COUNT, 10); // we
// guesstimate
// this
// Save the advisor state.
result.add(Status.OK_STATUS);
// Save the workbench windows.
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
for (int nX = 0; nX < windows.length; nX++) {
WorkbenchWindow window = (WorkbenchWindow) windows[nX];
IMemento childMem = memento.createChild(IWorkbenchConstants.TAG_WINDOW);
- result.merge(window.saveState(childMem));
+ //TODO why is this now an error?
+ //result.merge(window.saveState(childMem));
}
result.add(((Workbench) workbench).getEditorHistory().saveState(memento.createChild(IWorkbenchConstants.TAG_MRU_LIST)));
return result;
}
private void saveMementoToFile(XMLMemento memento) {
File stateFile = getWorkbenchStateFile();
if (stateFile != null) {
try {
FileOutputStream stream = new FileOutputStream(stateFile);
OutputStreamWriter writer = new OutputStreamWriter(stream, "utf-8"); //$NON-NLS-1$
memento.save(writer);
writer.close();
} catch (IOException ioe) {
stateFile.delete();
// Activator.log( ioe );
}
}
}
private File getWorkbenchStateFile() {
IPath path = WorkbenchPlugin.getDefault().getDataLocation();
if (path == null) {
return null;
}
path = path.append("workbench.xml");
return path.toFile();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
public static void sendMessage(String message){
System.out.println("message to sent to comment thread " + message);
Plugin plug = Platform.getPlugin("AVADocumentationFrame");
}
}
| true | true | private IStatus saveState(final IMemento memento) {
MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.Workbench_problemsSaving, null);
// Save the version number.
memento.putString(IWorkbenchConstants.TAG_VERSION, VERSION_STRING[1]);
// Save how many plug-ins were loaded while restoring the workbench
memento.putInteger(IWorkbenchConstants.TAG_PROGRESS_COUNT, 10); // we
// guesstimate
// this
// Save the advisor state.
result.add(Status.OK_STATUS);
// Save the workbench windows.
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
for (int nX = 0; nX < windows.length; nX++) {
WorkbenchWindow window = (WorkbenchWindow) windows[nX];
IMemento childMem = memento.createChild(IWorkbenchConstants.TAG_WINDOW);
result.merge(window.saveState(childMem));
}
result.add(((Workbench) workbench).getEditorHistory().saveState(memento.createChild(IWorkbenchConstants.TAG_MRU_LIST)));
return result;
}
| private IStatus saveState(final IMemento memento) {
MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.Workbench_problemsSaving, null);
// Save the version number.
memento.putString(IWorkbenchConstants.TAG_VERSION, VERSION_STRING[1]);
// Save how many plug-ins were loaded while restoring the workbench
memento.putInteger(IWorkbenchConstants.TAG_PROGRESS_COUNT, 10); // we
// guesstimate
// this
// Save the advisor state.
result.add(Status.OK_STATUS);
// Save the workbench windows.
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
for (int nX = 0; nX < windows.length; nX++) {
WorkbenchWindow window = (WorkbenchWindow) windows[nX];
IMemento childMem = memento.createChild(IWorkbenchConstants.TAG_WINDOW);
//TODO why is this now an error?
//result.merge(window.saveState(childMem));
}
result.add(((Workbench) workbench).getEditorHistory().saveState(memento.createChild(IWorkbenchConstants.TAG_MRU_LIST)));
return result;
}
|
diff --git a/org.spearce.jgit/src/org/spearce/jgit/lib/PackWriter.java b/org.spearce.jgit/src/org/spearce/jgit/lib/PackWriter.java
index f9945c40..b8784094 100644
--- a/org.spearce.jgit/src/org/spearce/jgit/lib/PackWriter.java
+++ b/org.spearce.jgit/src/org/spearce/jgit/lib/PackWriter.java
@@ -1,980 +1,980 @@
/*
* Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Git Development Community nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spearce.jgit.lib;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import org.spearce.jgit.errors.IncorrectObjectTypeException;
import org.spearce.jgit.errors.MissingObjectException;
import org.spearce.jgit.revwalk.ObjectWalk;
import org.spearce.jgit.revwalk.RevFlag;
import org.spearce.jgit.revwalk.RevObject;
import org.spearce.jgit.revwalk.RevSort;
import org.spearce.jgit.transport.PackedObjectInfo;
import org.spearce.jgit.util.CountingOutputStream;
import org.spearce.jgit.util.NB;
/**
* <p>
* PackWriter class is responsible for generating pack files from specified set
* of objects from repository. This implementation produce pack files in format
* version 2.
* </p>
* <p>
* Source of objects may be specified in two ways:
* <ul>
* <li>(usually) by providing sets of interesting and uninteresting objects in
* repository - all interesting objects and their ancestors except uninteresting
* objects and their ancestors will be included in pack, or</li>
* <li>by providing iterator of {@link RevObject} specifying exact list and
* order of objects in pack</li>
* </ul>
* Typical usage consists of creating instance intended for some pack,
* configuring options, preparing the list of objects by calling
* {@link #preparePack(Iterator)} or
* {@link #preparePack(Collection, Collection, boolean, boolean)}, and finally
* producing the stream with {@link #writePack(OutputStream)}.
* </p>
* <p>
* Class provide set of configurable options and {@link ProgressMonitor}
* support, as operations may take a long time for big repositories. Deltas
* searching algorithm is <b>NOT IMPLEMENTED</b> yet - this implementation
* relies only on deltas and objects reuse.
* </p>
* <p>
* This class is not thread safe, it is intended to be used in one thread, with
* one instance per created pack. Subsequent calls to writePack result in
* undefined behavior.
* </p>
*/
public class PackWriter {
/**
* Title of {@link ProgressMonitor} task used during counting objects to
* pack.
*
* @see #preparePack(Collection, Collection, boolean, boolean)
*/
public static final String COUNTING_OBJECTS_PROGRESS = "Counting objects";
/**
* Title of {@link ProgressMonitor} task used during searching for objects
* reuse or delta reuse.
*
* @see #writePack(OutputStream)
*/
public static final String SEARCHING_REUSE_PROGRESS = "Compressing objects";
/**
* Title of {@link ProgressMonitor} task used during writing out pack
* (objects)
*
* @see #writePack(OutputStream)
*/
public static final String WRITING_OBJECTS_PROGRESS = "Writing objects";
/**
* Default value of deltas reuse option.
*
* @see #setReuseDeltas(boolean)
*/
public static final boolean DEFAULT_REUSE_DELTAS = true;
/**
* Default value of objects reuse option.
*
* @see #setReuseObjects(boolean)
*/
public static final boolean DEFAULT_REUSE_OBJECTS = true;
/**
* Default value of delta base as offset option.
*
* @see #setDeltaBaseAsOffset(boolean)
*/
public static final boolean DEFAULT_DELTA_BASE_AS_OFFSET = false;
/**
* Default value of maximum delta chain depth.
*
* @see #setMaxDeltaDepth(int)
*/
public static final int DEFAULT_MAX_DELTA_DEPTH = 50;
private static final int PACK_VERSION_GENERATED = 2;
@SuppressWarnings("unchecked")
private final List<ObjectToPack> objectsLists[] = new List[Constants.OBJ_TAG + 1];
{
objectsLists[0] = Collections.<ObjectToPack> emptyList();
objectsLists[Constants.OBJ_COMMIT] = new ArrayList<ObjectToPack>();
objectsLists[Constants.OBJ_TREE] = new ArrayList<ObjectToPack>();
objectsLists[Constants.OBJ_BLOB] = new ArrayList<ObjectToPack>();
objectsLists[Constants.OBJ_TAG] = new ArrayList<ObjectToPack>();
}
private final ObjectIdSubclassMap<ObjectToPack> objectsMap = new ObjectIdSubclassMap<ObjectToPack>();
// edge objects for thin packs
private final ObjectIdSubclassMap<ObjectId> edgeObjects = new ObjectIdSubclassMap<ObjectId>();
private final Repository db;
private DigestOutputStream out;
private CountingOutputStream countingOut;
private final Deflater deflater;
private ProgressMonitor initMonitor;
private ProgressMonitor writeMonitor;
private final byte[] buf = new byte[16384]; // 16 KB
private final WindowCursor windowCursor = new WindowCursor();
private List<ObjectToPack> sortedByName;
private byte packcsum[];
private boolean reuseDeltas = DEFAULT_REUSE_DELTAS;
private boolean reuseObjects = DEFAULT_REUSE_OBJECTS;
private boolean deltaBaseAsOffset = DEFAULT_DELTA_BASE_AS_OFFSET;
private int maxDeltaDepth = DEFAULT_MAX_DELTA_DEPTH;
private int outputVersion;
private boolean thin;
/**
* Create writer for specified repository.
* <p>
* Objects for packing are specified in {@link #preparePack(Iterator)} or
* {@link #preparePack(Collection, Collection, boolean, boolean)}.
*
* @param repo
* repository where objects are stored.
* @param monitor
* operations progress monitor, used within
* {@link #preparePack(Iterator)},
* {@link #preparePack(Collection, Collection, boolean, boolean)}
* , or {@link #writePack(OutputStream)}.
*/
public PackWriter(final Repository repo, final ProgressMonitor monitor) {
this(repo, monitor, monitor);
}
/**
* Create writer for specified repository.
* <p>
* Objects for packing are specified in {@link #preparePack(Iterator)} or
* {@link #preparePack(Collection, Collection, boolean, boolean)}.
*
* @param repo
* repository where objects are stored.
* @param imonitor
* operations progress monitor, used within
* {@link #preparePack(Iterator)},
* {@link #preparePack(Collection, Collection, boolean, boolean)}
* ;
* @param wmonitor
* operations progress monitor, used within
* {@link #writePack(OutputStream)}.
*/
public PackWriter(final Repository repo, final ProgressMonitor imonitor,
final ProgressMonitor wmonitor) {
this.db = repo;
initMonitor = imonitor;
writeMonitor = wmonitor;
this.deflater = new Deflater(db.getConfig().getCore().getCompression());
outputVersion = repo.getConfig().getCore().getPackIndexVersion();
}
/**
* Check whether object is configured to reuse deltas existing in
* repository.
* <p>
* Default setting: {@value #DEFAULT_REUSE_DELTAS}
* </p>
*
* @return true if object is configured to reuse deltas; false otherwise.
*/
public boolean isReuseDeltas() {
return reuseDeltas;
}
/**
* Set reuse deltas configuration option for this writer. When enabled,
* writer will search for delta representation of object in repository and
* use it if possible. Normally, only deltas with base to another object
* existing in set of objects to pack will be used. Exception is however
* thin-pack (see
* {@link #preparePack(Collection, Collection, boolean, boolean)} and
* {@link #preparePack(Iterator)}) where base object must exist on other
* side machine.
* <p>
* When raw delta data is directly copied from a pack file, checksum is
* computed to verify data.
* </p>
* <p>
* Default setting: {@value #DEFAULT_REUSE_DELTAS}
* </p>
*
* @param reuseDeltas
* boolean indicating whether or not try to reuse deltas.
*/
public void setReuseDeltas(boolean reuseDeltas) {
this.reuseDeltas = reuseDeltas;
}
/**
* Checks whether object is configured to reuse existing objects
* representation in repository.
* <p>
* Default setting: {@value #DEFAULT_REUSE_OBJECTS}
* </p>
*
* @return true if writer is configured to reuse objects representation from
* pack; false otherwise.
*/
public boolean isReuseObjects() {
return reuseObjects;
}
/**
* Set reuse objects configuration option for this writer. If enabled,
* writer searches for representation in a pack file. If possible,
* compressed data is directly copied from such a pack file. Data checksum
* is verified.
* <p>
* Default setting: {@value #DEFAULT_REUSE_OBJECTS}
* </p>
*
* @param reuseObjects
* boolean indicating whether or not writer should reuse existing
* objects representation.
*/
public void setReuseObjects(boolean reuseObjects) {
this.reuseObjects = reuseObjects;
}
/**
* Check whether writer can store delta base as an offset (new style
* reducing pack size) or should store it as an object id (legacy style,
* compatible with old readers).
* <p>
* Default setting: {@value #DEFAULT_DELTA_BASE_AS_OFFSET}
* </p>
*
* @return true if delta base is stored as an offset; false if it is stored
* as an object id.
*/
public boolean isDeltaBaseAsOffset() {
return deltaBaseAsOffset;
}
/**
* Set writer delta base format. Delta base can be written as an offset in a
* pack file (new approach reducing file size) or as an object id (legacy
* approach, compatible with old readers).
* <p>
* Default setting: {@value #DEFAULT_DELTA_BASE_AS_OFFSET}
* </p>
*
* @param deltaBaseAsOffset
* boolean indicating whether delta base can be stored as an
* offset.
*/
public void setDeltaBaseAsOffset(boolean deltaBaseAsOffset) {
this.deltaBaseAsOffset = deltaBaseAsOffset;
}
/**
* Get maximum depth of delta chain set up for this writer. Generated chains
* are not longer than this value.
* <p>
* Default setting: {@value #DEFAULT_MAX_DELTA_DEPTH}
* </p>
*
* @return maximum delta chain depth.
*/
public int getMaxDeltaDepth() {
return maxDeltaDepth;
}
/**
* Set up maximum depth of delta chain for this writer. Generated chains are
* not longer than this value. Too low value causes low compression level,
* while too big makes unpacking (reading) longer.
* <p>
* Default setting: {@value #DEFAULT_MAX_DELTA_DEPTH}
* </p>
*
* @param maxDeltaDepth
* maximum delta chain depth.
*/
public void setMaxDeltaDepth(int maxDeltaDepth) {
this.maxDeltaDepth = maxDeltaDepth;
}
/**
* Set the pack index file format version this instance will create.
*
* @param version
* the version to write. The special version 0 designates the
* oldest (most compatible) format available for the objects.
* @see PackIndexWriter
*/
public void setIndexVersion(final int version) {
outputVersion = version;
}
/**
* Returns objects number in a pack file that was created by this writer.
*
* @return number of objects in pack.
*/
public int getObjectsNumber() {
return objectsMap.size();
}
/**
* Prepare the list of objects to be written to the pack stream.
* <p>
* Iterator <b>exactly</b> determines which objects are included in a pack
* and order they appear in pack (except that objects order by type is not
* needed at input). This order should conform general rules of ordering
* objects in git - by recency and path (type and delta-base first is
* internally secured) and responsibility for guaranteeing this order is on
* a caller side. Iterator must return each id of object to write exactly
* once.
* </p>
* <p>
* When iterator returns object that has {@link RevFlag#UNINTERESTING} flag,
* this object won't be included in an output pack. Instead, it is recorded
* as edge-object (known to remote repository) for thin-pack. In such a case
* writer may pack objects with delta base object not within set of objects
* to pack, but belonging to party repository - those marked with
* {@link RevFlag#UNINTERESTING} flag. This type of pack is used only for
* transport.
* </p>
*
* @param objectsSource
* iterator of object to store in a pack; order of objects within
* each type is important, ordering by type is not needed;
* allowed types for objects are {@link Constants#OBJ_COMMIT},
* {@link Constants#OBJ_TREE}, {@link Constants#OBJ_BLOB} and
* {@link Constants#OBJ_TAG}; objects returned by iterator may
* be later reused by caller as object id and type are internally
* copied in each iteration; if object returned by iterator has
* {@link RevFlag#UNINTERESTING} flag set, it won't be included
* in a pack, but is considered as edge-object for thin-pack.
* @throws IOException
* when some I/O problem occur during reading objects.
*/
public void preparePack(final Iterator<RevObject> objectsSource)
throws IOException {
while (objectsSource.hasNext()) {
addObject(objectsSource.next());
}
}
/**
* Prepare the list of objects to be written to the pack stream.
* <p>
* Basing on these 2 sets, another set of objects to put in a pack file is
* created: this set consists of all objects reachable (ancestors) from
* interesting objects, except uninteresting objects and their ancestors.
* This method uses class {@link ObjectWalk} extensively to find out that
* appropriate set of output objects and their optimal order in output pack.
* Order is consistent with general git in-pack rules: sort by object type,
* recency, path and delta-base first.
* </p>
*
* @param interestingObjects
* collection of objects to be marked as interesting (start
* points of graph traversal).
* @param uninterestingObjects
* collection of objects to be marked as uninteresting (end
* points of graph traversal).
* @param thin
* a boolean indicating whether writer may pack objects with
* delta base object not within set of objects to pack, but
* belonging to party repository (uninteresting/boundary) as
* determined by set; this kind of pack is used only for
* transport; true - to produce thin pack, false - otherwise.
* @param ignoreMissingUninteresting
* true if writer should ignore non existing uninteresting
* objects during construction set of objects to pack; false
* otherwise - non existing uninteresting objects may cause
* {@link MissingObjectException}
* @throws IOException
* when some I/O problem occur during reading objects.
*/
public void preparePack(
final Collection<? extends ObjectId> interestingObjects,
final Collection<? extends ObjectId> uninterestingObjects,
final boolean thin, final boolean ignoreMissingUninteresting)
throws IOException {
this.thin = thin;
ObjectWalk walker = setUpWalker(interestingObjects,
uninterestingObjects, ignoreMissingUninteresting);
findObjectsToPack(walker);
}
/**
* Determine if the pack file will contain the requested object.
*
* @param id
* the object to test the existence of.
* @return true if the object will appear in the output pack file.
*/
public boolean willInclude(final AnyObjectId id) {
return objectsMap.get(id) != null;
}
/**
* Computes SHA-1 of lexicographically sorted objects ids written in this
* pack, as used to name a pack file in repository.
*
* @return ObjectId representing SHA-1 name of a pack that was created.
*/
public ObjectId computeName() {
final MessageDigest md = Constants.newMessageDigest();
for (ObjectToPack otp : sortByName()) {
otp.copyRawTo(buf, 0);
md.update(buf, 0, Constants.OBJECT_ID_LENGTH);
}
return ObjectId.fromRaw(md.digest());
}
/**
* Create an index file to match the pack file just written.
* <p>
* This method can only be invoked after {@link #preparePack(Iterator)} or
* {@link #preparePack(Collection, Collection, boolean, boolean)} has been
* invoked and completed successfully. Writing a corresponding index is an
* optional feature that not all pack users may require.
*
* @param indexStream
* output for the index data. Caller is responsible for closing
* this stream.
* @throws IOException
* the index data could not be written to the supplied stream.
*/
public void writeIndex(final OutputStream indexStream) throws IOException {
final List<ObjectToPack> list = sortByName();
final PackIndexWriter iw;
if (outputVersion <= 0)
iw = PackIndexWriter.createOldestPossible(indexStream, list);
else
iw = PackIndexWriter.createVersion(indexStream, outputVersion);
iw.write(list, packcsum);
}
private List<ObjectToPack> sortByName() {
if (sortedByName == null) {
sortedByName = new ArrayList<ObjectToPack>(objectsMap.size());
for (List<ObjectToPack> list : objectsLists) {
for (ObjectToPack otp : list)
sortedByName.add(otp);
}
Collections.sort(sortedByName);
}
return sortedByName;
}
/**
* Write the prepared pack to the supplied stream.
* <p>
* At first, this method collects and sorts objects to pack, then deltas
* search is performed if set up accordingly, finally pack stream is
* written. {@link ProgressMonitor} tasks {@value #SEARCHING_REUSE_PROGRESS}
* (only if reuseDeltas or reuseObjects is enabled) and
* {@value #WRITING_OBJECTS_PROGRESS} are updated during packing.
* </p>
* <p>
* All reused objects data checksum (Adler32/CRC32) is computed and
* validated against existing checksum.
* </p>
*
* @param packStream
* output stream of pack data. If the stream is not buffered it
* will be buffered by the writer. Caller is responsible for
* closing the stream.
* @throws IOException
* an error occurred reading a local object's data to include in
* the pack, or writing compressed object data to the output
* stream.
*/
public void writePack(OutputStream packStream) throws IOException {
if (reuseDeltas || reuseObjects)
searchForReuse();
if (!(packStream instanceof BufferedOutputStream))
packStream = new BufferedOutputStream(packStream);
countingOut = new CountingOutputStream(packStream);
out = new DigestOutputStream(countingOut, Constants.newMessageDigest());
writeMonitor.beginTask(WRITING_OBJECTS_PROGRESS, getObjectsNumber());
writeHeader();
writeObjects();
writeChecksum();
out.flush();
windowCursor.release();
writeMonitor.endTask();
}
private void searchForReuse() throws IOException {
initMonitor.beginTask(SEARCHING_REUSE_PROGRESS, getObjectsNumber());
final Collection<PackedObjectLoader> reuseLoaders = new ArrayList<PackedObjectLoader>();
for (List<ObjectToPack> list : objectsLists) {
for (ObjectToPack otp : list) {
if (initMonitor.isCancelled())
throw new IOException(
"Packing cancelled during objects writing");
reuseLoaders.clear();
db.openObjectInAllPacks(otp, reuseLoaders, windowCursor);
if (reuseDeltas) {
selectDeltaReuseForObject(otp, reuseLoaders);
}
// delta reuse is preferred over object reuse
if (reuseObjects && !otp.hasReuseLoader()) {
selectObjectReuseForObject(otp, reuseLoaders);
}
initMonitor.update(1);
}
}
initMonitor.endTask();
}
private void selectDeltaReuseForObject(final ObjectToPack otp,
final Collection<PackedObjectLoader> loaders) throws IOException {
PackedObjectLoader bestLoader = null;
ObjectId bestBase = null;
for (PackedObjectLoader loader : loaders) {
ObjectId idBase = loader.getDeltaBase();
if (idBase == null)
continue;
ObjectToPack otpBase = objectsMap.get(idBase);
// only if base is in set of objects to write or thin-pack's edge
if ((otpBase != null || (thin && edgeObjects.get(idBase) != null))
// select smallest possible delta if > 1 available
&& isBetterDeltaReuseLoader(bestLoader, loader)) {
bestLoader = loader;
bestBase = (otpBase != null ? otpBase : idBase);
}
}
if (bestLoader != null) {
otp.setReuseLoader(bestLoader);
otp.setDeltaBase(bestBase);
}
}
private static boolean isBetterDeltaReuseLoader(
PackedObjectLoader currentLoader, PackedObjectLoader loader)
throws IOException {
if (currentLoader == null)
return true;
if (loader.getRawSize() < currentLoader.getRawSize())
return true;
return (loader.getRawSize() == currentLoader.getRawSize()
&& loader.supportsFastCopyRawData() && !currentLoader
.supportsFastCopyRawData());
}
private void selectObjectReuseForObject(final ObjectToPack otp,
final Collection<PackedObjectLoader> loaders) {
for (final PackedObjectLoader loader : loaders) {
if (loader instanceof WholePackedObjectLoader) {
otp.setReuseLoader(loader);
return;
}
}
}
private void writeHeader() throws IOException {
out.write(Constants.PACK_SIGNATURE);
NB.encodeInt32(buf, 0, PACK_VERSION_GENERATED);
out.write(buf, 0, 4);
NB.encodeInt32(buf, 0, getObjectsNumber());
out.write(buf, 0, 4);
}
private void writeObjects() throws IOException {
for (List<ObjectToPack> list : objectsLists) {
for (ObjectToPack otp : list) {
if (writeMonitor.isCancelled())
throw new IOException(
"Packing cancelled during objects writing");
if (!otp.isWritten())
writeObject(otp);
}
}
}
private void writeObject(final ObjectToPack otp) throws IOException {
otp.markWantWrite();
if (otp.isDeltaRepresentation()) {
ObjectToPack deltaBase = otp.getDeltaBase();
assert deltaBase != null || thin;
if (deltaBase != null && !deltaBase.isWritten()) {
if (deltaBase.wantWrite()) {
otp.clearDeltaBase(); // cycle detected
otp.disposeLoader();
} else {
writeObject(deltaBase);
}
}
}
assert !otp.isWritten();
otp.setOffset(countingOut.getCount());
if (otp.isDeltaRepresentation())
writeDeltaObject(otp);
else
writeWholeObject(otp);
writeMonitor.update(1);
}
private void writeWholeObject(final ObjectToPack otp) throws IOException {
if (otp.hasReuseLoader()) {
final PackedObjectLoader loader = otp.getReuseLoader();
writeObjectHeader(otp.getType(), loader.getSize());
loader.copyRawData(out, buf);
otp.disposeLoader();
} else {
final ObjectLoader loader = db.openObject(windowCursor, otp);
final byte[] data = loader.getCachedBytes();
final DeflaterOutputStream deflaterOut = new DeflaterOutputStream(
out, deflater);
writeObjectHeader(otp.getType(), data.length);
deflaterOut.write(data);
deflaterOut.finish();
deflater.reset();
}
}
private void writeDeltaObject(final ObjectToPack otp) throws IOException {
final PackedObjectLoader loader = otp.getReuseLoader();
if (deltaBaseAsOffset && otp.getDeltaBase() != null) {
writeObjectHeader(Constants.OBJ_OFS_DELTA, loader.getRawSize());
final ObjectToPack deltaBase = otp.getDeltaBase();
long offsetDiff = otp.getOffset() - deltaBase.getOffset();
int pos = buf.length - 1;
buf[pos] = (byte) (offsetDiff & 0x7F);
while ((offsetDiff >>= 7) > 0) {
buf[--pos] = (byte) (0x80 | (--offsetDiff & 0x7F));
}
out.write(buf, pos, buf.length - pos);
} else {
writeObjectHeader(Constants.OBJ_REF_DELTA, loader.getRawSize());
otp.getDeltaBaseId().copyRawTo(buf, 0);
out.write(buf, 0, Constants.OBJECT_ID_LENGTH);
}
loader.copyRawData(out, buf);
otp.disposeLoader();
}
private void writeObjectHeader(final int objectType, long dataLength)
throws IOException {
long nextLength = dataLength >>> 4;
int size = 0;
buf[size++] = (byte) ((nextLength > 0 ? 0x80 : 0x00)
| (objectType << 4) | (dataLength & 0x0F));
dataLength = nextLength;
while (dataLength > 0) {
nextLength >>>= 7;
buf[size++] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (dataLength & 0x7F));
dataLength = nextLength;
}
out.write(buf, 0, size);
}
private void writeChecksum() throws IOException {
out.on(false);
packcsum = out.getMessageDigest().digest();
out.write(packcsum);
}
private ObjectWalk setUpWalker(
final Collection<? extends ObjectId> interestingObjects,
final Collection<? extends ObjectId> uninterestingObjects,
final boolean ignoreMissingUninteresting)
throws MissingObjectException, IOException,
IncorrectObjectTypeException {
final ObjectWalk walker = new ObjectWalk(db);
- walker.sort(RevSort.TOPO, true);
+ walker.sort(RevSort.TOPO);
walker.sort(RevSort.COMMIT_TIME_DESC, true);
if (thin)
- walker.sort(RevSort.BOUNDARY);
+ walker.sort(RevSort.BOUNDARY, true);
for (ObjectId id : interestingObjects) {
RevObject o = walker.parseAny(id);
walker.markStart(o);
}
for (ObjectId id : uninterestingObjects) {
final RevObject o;
try {
o = walker.parseAny(id);
} catch (MissingObjectException x) {
if (ignoreMissingUninteresting)
continue;
throw x;
}
walker.markUninteresting(o);
}
return walker;
}
private void findObjectsToPack(final ObjectWalk walker)
throws MissingObjectException, IncorrectObjectTypeException,
IOException {
initMonitor.beginTask(COUNTING_OBJECTS_PROGRESS,
ProgressMonitor.UNKNOWN);
RevObject o;
while ((o = walker.next()) != null) {
addObject(o);
o.dispose();
initMonitor.update(1);
}
while ((o = walker.nextObject()) != null) {
addObject(o);
o.dispose();
initMonitor.update(1);
}
initMonitor.endTask();
}
/**
* Include one object to the output file.
* <p>
* Objects are written in the order they are added. If the same object is
* added twice, it may be written twice, creating a larger than necessary
* file.
*
* @param object
* the object to add.
* @throws IncorrectObjectTypeException
* the object is an unsupported type.
*/
public void addObject(final RevObject object)
throws IncorrectObjectTypeException {
if (object.has(RevFlag.UNINTERESTING)) {
edgeObjects.add(object);
thin = true;
return;
}
final ObjectToPack otp = new ObjectToPack(object, object.getType());
try {
objectsLists[object.getType()].add(otp);
} catch (ArrayIndexOutOfBoundsException x) {
throw new IncorrectObjectTypeException(object,
"COMMIT nor TREE nor BLOB nor TAG");
} catch (UnsupportedOperationException x) {
// index pointing to "dummy" empty list
throw new IncorrectObjectTypeException(object,
"COMMIT nor TREE nor BLOB nor TAG");
}
objectsMap.add(otp);
}
/**
* Class holding information about object that is going to be packed by
* {@link PackWriter}. Information include object representation in a
* pack-file and object status.
*
*/
static class ObjectToPack extends PackedObjectInfo {
private ObjectId deltaBase;
private PackedObjectLoader reuseLoader;
/**
* Bit field, from bit 0 to bit 31:
* <ul>
* <li>1 bit: wantWrite</li>
* <li>3 bits: type</li>
* <li>28 bits: deltaDepth</li>
* </ul>
*/
private int flags;
/**
* Construct object for specified object id. <br/> By default object is
* marked as not written and non-delta packed (as a whole object).
*
* @param src
* object id of object for packing
* @param type
* real type code of the object, not its in-pack type.
*/
ObjectToPack(AnyObjectId src, final int type) {
super(src);
flags |= type << 1;
}
/**
* @return delta base object id if object is going to be packed in delta
* representation; null otherwise - if going to be packed as a
* whole object.
*/
ObjectId getDeltaBaseId() {
return deltaBase;
}
/**
* @return delta base object to pack if object is going to be packed in
* delta representation and delta is specified as object to
* pack; null otherwise - if going to be packed as a whole
* object or delta base is specified only as id.
*/
ObjectToPack getDeltaBase() {
if (deltaBase instanceof ObjectToPack)
return (ObjectToPack) deltaBase;
return null;
}
/**
* Set delta base for the object. Delta base set by this method is used
* by {@link PackWriter} to write object - determines its representation
* in a created pack.
*
* @param deltaBase
* delta base object or null if object should be packed as a
* whole object.
*
*/
void setDeltaBase(ObjectId deltaBase) {
this.deltaBase = deltaBase;
}
void clearDeltaBase() {
this.deltaBase = null;
}
/**
* @return true if object is going to be written as delta; false
* otherwise.
*/
boolean isDeltaRepresentation() {
return deltaBase != null;
}
/**
* Check if object is already written in a pack. This information is
* used to achieve delta-base precedence in a pack file.
*
* @return true if object is already written; false otherwise.
*/
boolean isWritten() {
return offset != 0;
}
PackedObjectLoader getReuseLoader() {
return reuseLoader;
}
boolean hasReuseLoader() {
return reuseLoader != null;
}
void setReuseLoader(PackedObjectLoader reuseLoader) {
this.reuseLoader = reuseLoader;
}
void disposeLoader() {
this.reuseLoader = null;
}
int getType() {
return (flags>>1) & 0x7;
}
int getDeltaDepth() {
return flags >>> 4;
}
void updateDeltaDepth() {
final int d;
if (deltaBase instanceof ObjectToPack)
d = ((ObjectToPack) deltaBase).getDeltaDepth() + 1;
else if (deltaBase != null)
d = 1;
else
d = 0;
flags = (d << 4) | flags & 0x15;
}
boolean wantWrite() {
return (flags & 1) == 1;
}
void markWantWrite() {
flags |= 1;
}
}
}
| false | true | private ObjectWalk setUpWalker(
final Collection<? extends ObjectId> interestingObjects,
final Collection<? extends ObjectId> uninterestingObjects,
final boolean ignoreMissingUninteresting)
throws MissingObjectException, IOException,
IncorrectObjectTypeException {
final ObjectWalk walker = new ObjectWalk(db);
walker.sort(RevSort.TOPO, true);
walker.sort(RevSort.COMMIT_TIME_DESC, true);
if (thin)
walker.sort(RevSort.BOUNDARY);
for (ObjectId id : interestingObjects) {
RevObject o = walker.parseAny(id);
walker.markStart(o);
}
for (ObjectId id : uninterestingObjects) {
final RevObject o;
try {
o = walker.parseAny(id);
} catch (MissingObjectException x) {
if (ignoreMissingUninteresting)
continue;
throw x;
}
walker.markUninteresting(o);
}
return walker;
}
| private ObjectWalk setUpWalker(
final Collection<? extends ObjectId> interestingObjects,
final Collection<? extends ObjectId> uninterestingObjects,
final boolean ignoreMissingUninteresting)
throws MissingObjectException, IOException,
IncorrectObjectTypeException {
final ObjectWalk walker = new ObjectWalk(db);
walker.sort(RevSort.TOPO);
walker.sort(RevSort.COMMIT_TIME_DESC, true);
if (thin)
walker.sort(RevSort.BOUNDARY, true);
for (ObjectId id : interestingObjects) {
RevObject o = walker.parseAny(id);
walker.markStart(o);
}
for (ObjectId id : uninterestingObjects) {
final RevObject o;
try {
o = walker.parseAny(id);
} catch (MissingObjectException x) {
if (ignoreMissingUninteresting)
continue;
throw x;
}
walker.markUninteresting(o);
}
return walker;
}
|
diff --git a/EdTempsECN/src/org/ecn/edtemps/servlets/impl/AdministrateurServlet.java b/EdTempsECN/src/org/ecn/edtemps/servlets/impl/AdministrateurServlet.java
index f7ea9a2..ee99f49 100644
--- a/EdTempsECN/src/org/ecn/edtemps/servlets/impl/AdministrateurServlet.java
+++ b/EdTempsECN/src/org/ecn/edtemps/servlets/impl/AdministrateurServlet.java
@@ -1,117 +1,116 @@
package org.ecn.edtemps.servlets.impl;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ecn.edtemps.exceptions.DatabaseException;
import org.ecn.edtemps.managers.BddGestion;
import org.ecn.edtemps.managers.UtilisateurGestion;
/**
* Servlet pour la connexion en grand administrateur
*
* @author Joffrey Terrade
*/
public class AdministrateurServlet extends HttpServlet {
private static final long serialVersionUID = 5303879641965806292L;
private static Logger logger = LogManager.getLogger(AdministrateurServlet.class.getName());
/**
* Servlet pour la connexion et la déconnexion en mode grand administrateur
* @param req Requête
* @param resp Réponse pour le client
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Vérification des valeurs possibles dans le path de la requête
String pathInfo = req.getPathInfo();
if (!pathInfo.equals("/connexion")) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
HttpSession session = req.getSession(true);
try {
switch (pathInfo) {
case "/connexion":
doConnexionAdministrateur(req, resp, session);
break;
}
} catch (IOException | ServletException e) {
logger.error("Erreur lors de l'écriture de la réponse");
session.setAttribute("connect", "KO");
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
logger.error("Erreur lors du cryptage du mot de passe");
session.setAttribute("connect", "KO");
} catch (SQLException | DatabaseException e) {
logger.error("Erreur liée à la base de données");
session.setAttribute("connect", "KO");
}
}
/**
* Connecter mode Administrateur
* @param resp Réponse à compléter
* @param requete Requête
* @param session Session HTTP
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws DatabaseException
* @throws SQLException
* @throws ServletException
*/
protected void doConnexionAdministrateur(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException, InvalidKeyException, NoSuchAlgorithmException, DatabaseException, SQLException, ServletException {
BddGestion bdd = new BddGestion();
// Récupération des identifiants passés en paramètre
String login = req.getParameter("login");
String password = req.getParameter("password");
String cryptedPassword = UtilisateurGestion.hmac_sha256("Chaine de cryptage", password);
- System.out.println(cryptedPassword);
logger.debug("Tentative de connexion à l'espace d'administration avec le login : " + login);
// Prépare la requête
PreparedStatement reqPreparee = bdd.getConnection().prepareStatement(
"SELECT COUNT(*) FROM edt.administrateurs WHERE admin_login=? AND admin_password=?");
reqPreparee.setString(1, login);
reqPreparee.setString(2, cryptedPassword);
// Exécute la requête
ResultSet reqResultat = reqPreparee.executeQuery();
reqResultat.next();
// Alimente les attributs de la session http
session.setAttribute("login", login);
if (reqResultat.getInt(1)>0) {
logger.error("Connexion réussie");
session.setAttribute("connect", "OK");
resp.sendRedirect("../admin/general.jsp");
} else {
logger.error("Echec de connexion : identifiant ou mot de passe erroné.");
session.setAttribute("connect", "KO");
resp.sendRedirect("../admin/login.jsp");
}
}
}
| true | true | protected void doConnexionAdministrateur(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException, InvalidKeyException, NoSuchAlgorithmException, DatabaseException, SQLException, ServletException {
BddGestion bdd = new BddGestion();
// Récupération des identifiants passés en paramètre
String login = req.getParameter("login");
String password = req.getParameter("password");
String cryptedPassword = UtilisateurGestion.hmac_sha256("Chaine de cryptage", password);
System.out.println(cryptedPassword);
logger.debug("Tentative de connexion à l'espace d'administration avec le login : " + login);
// Prépare la requête
PreparedStatement reqPreparee = bdd.getConnection().prepareStatement(
"SELECT COUNT(*) FROM edt.administrateurs WHERE admin_login=? AND admin_password=?");
reqPreparee.setString(1, login);
reqPreparee.setString(2, cryptedPassword);
// Exécute la requête
ResultSet reqResultat = reqPreparee.executeQuery();
reqResultat.next();
// Alimente les attributs de la session http
session.setAttribute("login", login);
if (reqResultat.getInt(1)>0) {
logger.error("Connexion réussie");
session.setAttribute("connect", "OK");
resp.sendRedirect("../admin/general.jsp");
} else {
logger.error("Echec de connexion : identifiant ou mot de passe erroné.");
session.setAttribute("connect", "KO");
resp.sendRedirect("../admin/login.jsp");
}
}
| protected void doConnexionAdministrateur(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException, InvalidKeyException, NoSuchAlgorithmException, DatabaseException, SQLException, ServletException {
BddGestion bdd = new BddGestion();
// Récupération des identifiants passés en paramètre
String login = req.getParameter("login");
String password = req.getParameter("password");
String cryptedPassword = UtilisateurGestion.hmac_sha256("Chaine de cryptage", password);
logger.debug("Tentative de connexion à l'espace d'administration avec le login : " + login);
// Prépare la requête
PreparedStatement reqPreparee = bdd.getConnection().prepareStatement(
"SELECT COUNT(*) FROM edt.administrateurs WHERE admin_login=? AND admin_password=?");
reqPreparee.setString(1, login);
reqPreparee.setString(2, cryptedPassword);
// Exécute la requête
ResultSet reqResultat = reqPreparee.executeQuery();
reqResultat.next();
// Alimente les attributs de la session http
session.setAttribute("login", login);
if (reqResultat.getInt(1)>0) {
logger.error("Connexion réussie");
session.setAttribute("connect", "OK");
resp.sendRedirect("../admin/general.jsp");
} else {
logger.error("Echec de connexion : identifiant ou mot de passe erroné.");
session.setAttribute("connect", "KO");
resp.sendRedirect("../admin/login.jsp");
}
}
|
diff --git a/maven-release-plugin/src/main/java/org/apache/maven/plugins/release/PerformReleaseMojo.java b/maven-release-plugin/src/main/java/org/apache/maven/plugins/release/PerformReleaseMojo.java
index 3714c0f..d24adce 100644
--- a/maven-release-plugin/src/main/java/org/apache/maven/plugins/release/PerformReleaseMojo.java
+++ b/maven-release-plugin/src/main/java/org/apache/maven/plugins/release/PerformReleaseMojo.java
@@ -1,138 +1,141 @@
package org.apache.maven.plugins.release;
/*
* 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.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.shared.release.ReleaseExecutionException;
import org.apache.maven.shared.release.ReleaseFailureException;
import org.apache.maven.shared.release.config.ReleaseDescriptor;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
/**
* Perform a release from SCM.
*
* @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a>
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
* @version $Id$
* @aggregator
* @requiresProject false
* @goal perform
*/
public class PerformReleaseMojo
extends AbstractReleaseMojo
{
/**
* A comma or space separated list of goals to execute on deployment.
*
* Default value is either <code>deploy</code> or
* <code>deploy site-deploy</code>, if the project has a
* <distributionManagement>/<site> element.
*
* @parameter expression="${goals}"
*/
private String goals;
/**
* Comma separated profiles to enable on deployment, in addition to active profiles
* for project execution.
*
* @parameter
*/
private String releaseProfiles;
/**
* The checkout directory.
*
* @parameter default-value="${project.build.directory}/checkout"
* @required
*/
private File workingDirectory;
/**
* The SCM URL to checkout from. If omitted, the one from the
* <code>release.properties</code> file is used, followed by the URL
* from the current POM.
*
* @parameter expression="${connectionUrl}"
*/
private String connectionUrl;
/**
* Whether to use the release profile that adds sources and javadocs to the
* released artifact, if appropriate.
*
* @parameter expression="${useReleaseProfile}" default-value="true"
*/
private boolean useReleaseProfile;
protected String getAdditionalProfiles()
{
return releaseProfiles;
}
public void execute()
throws MojoExecutionException, MojoFailureException
{
super.execute();
// goals may be splitted into multiple line in configuration.
// Let's build a single line command
- goals = StringUtils.join( StringUtils.split( goals ), " " );
+ if ( goals != null )
+ {
+ goals = StringUtils.join( StringUtils.split( goals ), " " );
+ }
try
{
// Note that the working directory here is not the same as in the release configuration, so don't reuse that
ReleaseDescriptor releaseDescriptor = createReleaseDescriptor();
if ( connectionUrl != null )
{
releaseDescriptor.setScmSourceUrl( connectionUrl );
}
releaseDescriptor.setCheckoutDirectory( workingDirectory.getAbsolutePath() );
releaseDescriptor.setUseReleaseProfile( useReleaseProfile );
if ( goals == null )
{
// set default
goals = "deploy";
if ( project.getDistributionManagement() != null &&
project.getDistributionManagement().getSite() != null )
{
goals += " site-deploy";
}
}
releaseDescriptor.setPerformGoals( goals );
releaseManager.perform( releaseDescriptor, settings, reactorProjects );
}
catch ( ReleaseExecutionException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ReleaseFailureException e )
{
throw new MojoFailureException( e.getMessage() );
}
}
}
| true | true | public void execute()
throws MojoExecutionException, MojoFailureException
{
super.execute();
// goals may be splitted into multiple line in configuration.
// Let's build a single line command
goals = StringUtils.join( StringUtils.split( goals ), " " );
try
{
// Note that the working directory here is not the same as in the release configuration, so don't reuse that
ReleaseDescriptor releaseDescriptor = createReleaseDescriptor();
if ( connectionUrl != null )
{
releaseDescriptor.setScmSourceUrl( connectionUrl );
}
releaseDescriptor.setCheckoutDirectory( workingDirectory.getAbsolutePath() );
releaseDescriptor.setUseReleaseProfile( useReleaseProfile );
if ( goals == null )
{
// set default
goals = "deploy";
if ( project.getDistributionManagement() != null &&
project.getDistributionManagement().getSite() != null )
{
goals += " site-deploy";
}
}
releaseDescriptor.setPerformGoals( goals );
releaseManager.perform( releaseDescriptor, settings, reactorProjects );
}
catch ( ReleaseExecutionException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ReleaseFailureException e )
{
throw new MojoFailureException( e.getMessage() );
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException
{
super.execute();
// goals may be splitted into multiple line in configuration.
// Let's build a single line command
if ( goals != null )
{
goals = StringUtils.join( StringUtils.split( goals ), " " );
}
try
{
// Note that the working directory here is not the same as in the release configuration, so don't reuse that
ReleaseDescriptor releaseDescriptor = createReleaseDescriptor();
if ( connectionUrl != null )
{
releaseDescriptor.setScmSourceUrl( connectionUrl );
}
releaseDescriptor.setCheckoutDirectory( workingDirectory.getAbsolutePath() );
releaseDescriptor.setUseReleaseProfile( useReleaseProfile );
if ( goals == null )
{
// set default
goals = "deploy";
if ( project.getDistributionManagement() != null &&
project.getDistributionManagement().getSite() != null )
{
goals += " site-deploy";
}
}
releaseDescriptor.setPerformGoals( goals );
releaseManager.perform( releaseDescriptor, settings, reactorProjects );
}
catch ( ReleaseExecutionException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ReleaseFailureException e )
{
throw new MojoFailureException( e.getMessage() );
}
}
|
diff --git a/components/services/src/main/java/org/openengsb/core/services/internal/virtual/InvokeAllIgnoreResultStrategy.java b/components/services/src/main/java/org/openengsb/core/services/internal/virtual/InvokeAllIgnoreResultStrategy.java
index 3476de27f..84b49e3b1 100644
--- a/components/services/src/main/java/org/openengsb/core/services/internal/virtual/InvokeAllIgnoreResultStrategy.java
+++ b/components/services/src/main/java/org/openengsb/core/services/internal/virtual/InvokeAllIgnoreResultStrategy.java
@@ -1,64 +1,64 @@
/**
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI 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.openengsb.core.services.internal.virtual;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.openengsb.core.api.CompositeConnectorStrategy;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple and generic {@link CompositeConnectorStrategy} that invokes all services that are passed to it sequentially.
* The result is always null. As soon as the first invocation throws an Exception it is re-thrown and no more services
* are invoked.
*/
public class InvokeAllIgnoreResultStrategy implements CompositeConnectorStrategy {
private static Logger LOGGER = LoggerFactory.getLogger(InvokeAllIgnoreResultStrategy.class);
private BundleContext bundleContext;
@Override
public Object invoke(List<ServiceReference> services, Method method, Object... args) throws Throwable {
for (ServiceReference ref : services) {
Object service = bundleContext.getService(ref);
try {
method.invoke(service, args);
} catch (InvocationTargetException e) {
- LOGGER.warn("connector in composition threw an Exception in methodcall %s", method.toString());
+ LOGGER.warn("connector in composition threw an Exception in method call %s", method.toString());
LOGGER.debug("ExceptionDetails: ", e);
}
}
return null;
}
@Override
public boolean supports(Class<?> domainClass) {
return true;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
| true | true | public Object invoke(List<ServiceReference> services, Method method, Object... args) throws Throwable {
for (ServiceReference ref : services) {
Object service = bundleContext.getService(ref);
try {
method.invoke(service, args);
} catch (InvocationTargetException e) {
LOGGER.warn("connector in composition threw an Exception in methodcall %s", method.toString());
LOGGER.debug("ExceptionDetails: ", e);
}
}
return null;
}
| public Object invoke(List<ServiceReference> services, Method method, Object... args) throws Throwable {
for (ServiceReference ref : services) {
Object service = bundleContext.getService(ref);
try {
method.invoke(service, args);
} catch (InvocationTargetException e) {
LOGGER.warn("connector in composition threw an Exception in method call %s", method.toString());
LOGGER.debug("ExceptionDetails: ", e);
}
}
return null;
}
|
diff --git a/signserver/modules/SignServer-ejb/src/java/org/signserver/server/cryptotokens/HardCodedCryptoToken.java b/signserver/modules/SignServer-ejb/src/java/org/signserver/server/cryptotokens/HardCodedCryptoToken.java
index 8949d8dde..128372efc 100644
--- a/signserver/modules/SignServer-ejb/src/java/org/signserver/server/cryptotokens/HardCodedCryptoToken.java
+++ b/signserver/modules/SignServer-ejb/src/java/org/signserver/server/cryptotokens/HardCodedCryptoToken.java
@@ -1,280 +1,285 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.server.cryptotokens;
import java.io.ByteArrayInputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import org.bouncycastle.util.encoders.Base64;
import org.signserver.common.ICertReqData;
import org.signserver.common.ISignerCertReqInfo;
import org.signserver.common.CryptoTokenAuthenticationFailureException;
import org.signserver.common.CryptoTokenInitializationFailureException;
import org.signserver.common.CryptoTokenOfflineException;
import org.signserver.common.SignerStatus;
import org.signserver.common.KeyTestResult;
/**
* Class used for testing purposes, contains soft dummy key and certificates
* @author Philip Vendil
* @version $Id$
*/
public class HardCodedCryptoToken implements ICryptoToken {
public static final String KEY_ALIAS_1 = "key00001";
public static final String KEY_ALIAS_2 = "key00002";
public HardCodedCryptoToken(){}
/**
* Hard coded keys used for testing purposes.
*/
private static byte[] passTestKey2 = Base64.decode((
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDmZqPJNogVtiRZ" +
"9loOFJ7UPMsrqWXZZ8R+nTPB72+kQ+4qOpgUHfto7QpSbs9/9wGrUsxc/mpadt/g" +
"RTztl6FWGQ4TknOkoDFP+MilP08u5ZbOJrbN3E7vy0dEszzO9aHLBHXV1w2pWTlV" +
"V2kWABpl4R4lfyWBroqpahhSReOrgL/utgcVgWkpYYb9Rx67aSl83F3lNZBMUTGR" +
"4gi/eQ5zug+VYDDWLyBPw7jymspQ+RwbeDaR7k8lS4sRI/QgJtVTDtzMgTPlfvWD" +
"QIxofdkiZnG3t30aDxif5O3qaUbwMSA4Jfo6xgc2f+NPdFjhYarRTezNB8D4J4yT" +
"02U5bI6HAgMBAAECggEAaRoZTQibO4xDOOawXgv6CEdTRy+XTn2PnVKI8ccP3pc+" +
"ZfUkusiSj2LSepgh//XlxQmYQDOuwGXJ6ryq9pdc+bGkQjlkl4yb8idDIF6o+HOz" +
"P4dZjL8bIzhP4n8BFkfm7n2yY0Ie8UnKZaviPC7/28m9vs0phubgSjgjsCRBn1HW" +
"hRwEFyjUXiKQYBZak/6AMUNrU/3fNOD5XZfRF56ppRNEUxq42ltUQidcKrPnKYgo" +
"xpJ8iFTm+NvGJdV6svoDZXsdR74PTEZYaxw9+4K6Cj7mXiFehsJqMjahTJtAh7Vx" +
"JL/U5+g/dJXXhTRaM10cDXn8ly81mV0iCIyb2YNQgQKBgQD7mATdp+9j7FFzfVKh" +
"70ld/hTeBLwa2sx/55jt+iK98cDAUzWZ36rwgO2MqSSmk1gwTnGG8JPMTO0NW3AU" +
"Qs7ozIubU1zichOXyyrKJPPSoKuVUD1KhqdOtX33kTIh0Hf3/9Xk025VH3zuzOZY" +
"SkdouNhhS9ZEa6xnJjS5xTI4uQKBgQDqb5sX3R8b2pAfiKp67Xn6oMuAf5lsPYWr" +
"CFTmBwjk2w5Ch9ffDeixtp+od6H3XzxWVfAfIYM1YtxpAfw11VtLaHPAC16fmBbc" +
"O9jZa5um5qDkg1xbvuXCekD7Hbb/juxA/+zxpZGWTegQ+0taVUanZBrCXdAIXF4j" +
"zc+uWObhPwKBgQCkDNrXYUJSKGxv3r67wlhXhm462mGBLTv9BpmMSvbOXc1uWpNv" +
"0w0WJys99ahlSVxOm0ehUks9AsfrVrz9KRbba0x4qmG9cd7esmYjSvcFVyiqgpiE" +
"eMqtIuCRRcanj9Q6DEJ/I3Ik5RREbayg00Y+vZCx2I5NLNxMofftTezSWQKBgGw8" +
"zwx7iQthI72LabqLvg+bAZn4T6uL1BUdKaVyhgazpKfO9DoFv/Oc76XmZh9CFyd9" +
"UfntjRiu5jiNNBbexOHR/e8i0LM6kwNnljz708eBH7OhepjZUFcz/qByHbVsFWQF" +
"RS5kVQ1iNszwWOACEzbhnwEyMwRJMSWytjo2zZIdAoGACPzW59zxy2lyVWbJIjXa" +
"Frf7tI8+FffkudTPxU/zNbJJqHlprTlqv7aeHn8gYO+++8HkJVksvBRMR3DVjF7h" +
"Bstg/zzNoMZgzxjL+afGxe4KNcfTmoXFm/rG2WCEio+H4AF3g9QyQUxpvaLXG7VW" +
"VI42L5Hy2MkUE1Mw7GfDoy4=").getBytes());
private static byte[] passTestKey1 = Base64.decode((
"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIUQj9LZl/yZQHm9" +
"QSrg+o/Ir+F2UQrEamEL5Q307kS+AsrB+9mLYZhFY3vqIo21aZmxKdtPa/d1ML0u" +
"E2Ykz0L1QGJ1MO5Wux+EOKwoj0+JsI/nkfCMbgDmYK79h11REc7quin3U2K0wm5t" +
"XAaDus8X7ZRwp4wm7gP+tllUS4SrAgMBAAECgYAvSZVy/vTuRaAOI12XWWBx3IX0" +
"f9GJHAgZ+NorvZE3SLdBSvKvesLyFCaokKo65e9jOPyA/ZaG2FS7xjYKpKYqwt96" +
"1l5Vyd3dloaTFEDjjp/ZJgbmEwDKICXudqCH7PyCaCB+SofXUYmD7Ss7OxtqZtjY" +
"MoXQ1IYwhPPFDJyjoQJBAPWXbC1Fzpx7LFisISbcmNlDt1qQg7GgOxq8IokRkqUm" +
"1e/faRCXq8ZJmQfR9UnsESEWsCOWZ8gO2SKCvSiH8tMCQQCKtEPMDKtX/I3MjkMW" +
"wkIX0ivTjPn9tFM6av0X2ppQELQINe/vZLRuplLfOnAgKuGNi712e+yHPpvugsX1" +
"Lo/JAkEAk/Mx1yA7tOc7MvwXSKsSZai2t5dhzsshcBywjXSJrHZ14XjseXN1pxHF" +
"YAGrTGorc4yQdg/w24OeaXzraZRkwwJBAIBC/+qh0JR1g76j0yAplKqofESNOeNE" +
"rC36H36+dDITsBdjoTNTgZJMlZe9V1A3twmILjRxliDeYZ1mKp52ZxkCQD0gyo9r" +
"gbE9jGM7yKu169PZXNpWN0YP3UPM+ctqNkKe2l2hK0rCopoymxJGthba9iKhzHCZ" +
"FHqzLUsiKmWnrwY=" ).getBytes());
public static byte[] certbytes2 = Base64.decode((
"MIID7zCCAqigAwIBAgIIWOzgRTcR/iAwPAYJKoZIhvcNAQEKMC+gDzANBglghkgB" +
"ZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFADA/MRMwEQYDVQQD" +
"EwpTZXRlY1Rlc3QyMRswGQYDVQQKExJSaWtzcG9saXNzdHlyZWxzZW4xCzAJBgNV" +
"BAYTAlNFMB4XDTA1MDkxMjA5MTg1MloXDTE1MDkwOTA5Mjg1MlowZzEcMBoGA1UE" +
"AxMTVGVzdCBhdiBFeHByZXNzUGFzczEOMAwGA1UEBRMFMTIzNDUxDTALBgNVBAsT" +
"BFBhc3MxGzAZBgNVBAoTElJpa3Nwb2xpc3N0eXJlbHNlbjELMAkGA1UEBhMCU0Uw" +
"ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDmZqPJNogVtiRZ9loOFJ7U" +
"PMsrqWXZZ8R+nTPB72+kQ+4qOpgUHfto7QpSbs9/9wGrUsxc/mpadt/gRTztl6FW" +
"GQ4TknOkoDFP+MilP08u5ZbOJrbN3E7vy0dEszzO9aHLBHXV1w2pWTlVV2kWABpl" +
"4R4lfyWBroqpahhSReOrgL/utgcVgWkpYYb9Rx67aSl83F3lNZBMUTGR4gi/eQ5z" +
"ug+VYDDWLyBPw7jymspQ+RwbeDaR7k8lS4sRI/QgJtVTDtzMgTPlfvWDQIxofdki" +
"ZnG3t30aDxif5O3qaUbwMSA4Jfo6xgc2f+NPdFjhYarRTezNB8D4J4yT02U5bI6H" +
"AgMBAAGjaTBnMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQUKvx2IjcjhAFFpp80" +
"ytO9KsC+rGgwHwYDVR0jBBgwFoAU19fDl5KAW2KqbuIHGG24AL+RfvAwFQYDVR0g" +
"BA4wDDAKBggqhXBUCgEBATA8BgkqhkiG9w0BAQowL6APMA0GCWCGSAFlAwQCAQUA" +
"oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAA4IBAQBIH8UOXoaZ/ImkF6Co" +
"eIII6KHsd+5CAro0hiBXDAkuLmPSVHp6jgv7chv0W7CL89veu7Vy+7aow1hVkGC9" +
"XTmgrCGiKzw9+XGJsunLmAMhLj/QztnkJgQBo/09geM+w5UTdR+5PP9nRs9oJtlU" +
"FCOcN8VJEeIvgDyWoMUDG7K1YvjmkEU6CPVYrL2PAdY0bPZvTIymC1HuyPmMnf83" +
"QKHW0KKtb4uhkruTkX87yZm7fZZXfso6HeUKQ0+fbcqmQdXFEcJJEKSHTCcu5BVj" +
"JebCC2FiSP88KPGGW5D351LJ+UL8En3oA5eHxZCy/LeGejPw0N02XjVFfBZEKnf6" +
"5a94").getBytes());
public static byte[] certbytes1 = Base64.decode((
"MIIC5DCCAcygAwIBAgIIfZgsZqV8NDAwDQYJKoZIhvcNAQEFBQAwNzERMA8GA1UE" +
"AxMIQWRtaW5DQTExFTATBgNVBAoTDEVKQkNBIFNhbXBsZTELMAkGA1UEBhMCU0Uw" +
"HhcNMDYwNjAzMTUzMzM5WhcNMjYwNTI5MTU0MzM5WjA3MRYwFAYDVQQDEw10aW1l" +
"c3RhbXB0ZXN0MR0wGwYDVQQKExRQcmltZUtleSBTb2x1dGlvbiBBQjCBnzANBgkq" +
"hkiG9w0BAQEFAAOBjQAwgYkCgYEAhRCP0tmX/JlAeb1BKuD6j8iv4XZRCsRqYQvl" +
"DfTuRL4CysH72YthmEVje+oijbVpmbEp209r93UwvS4TZiTPQvVAYnUw7la7H4Q4" +
"rCiPT4mwj+eR8IxuAOZgrv2HXVERzuq6KfdTYrTCbm1cBoO6zxftlHCnjCbuA/62" +
"WVRLhKsCAwEAAaN4MHYwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBsAwFgYD" +
"VR0lAQH/BAwwCgYIKwYBBQUHAwgwHQYDVR0OBBYEFOrxsQleE90vW4I2FC4cDim/" +
"hKjhMB8GA1UdIwQYMBaAFNrdQb5Q2K3ZL/KD+leV040azuwPMA0GCSqGSIb3DQEB" +
"BQUAA4IBAQB5WKwHfItwzbU3gdsszZ1V0yfnc9znP8De8fOjBHaGdgO3wxo2zB0G" +
"JbgcyvVeJ5kecZRZcM+/bTNraWFGlCTkaqLD+1pMeVc1oBbtR5hevuykA+OR7RKS" +
"mUZ7CadXnZjkDRgN8XsP5doDOpV2ZunLfrPCx61mJ3GxG6gvuMutOd7U2BN2vbMr" +
"VMNxWOftXR/XyJAJxY0YOgplV8hOkW+Ky0MyAe2ktFnOOuMIMKhLgrN338ZeAXRs" +
"2lhcc/p79imDL5QkPavZWrcnNZpT506DDyzn1cf68HpJNF1ICY57hWmx79gbIFhe" +
"mJxVZp+eyws3H9Yb9o2pLs7EOS7n+X26" ).getBytes());
private X509Certificate cert = null;
private PrivateKey privateKey = null;
public void init(int workerId, Properties props) throws CryptoTokenInitializationFailureException {
- final String defaultKey = props.getProperty("defaultKey", KEY_ALIAS_1);
+ final String defaultKey;
+ if (props == null) {
+ defaultKey = KEY_ALIAS_1;
+ } else {
+ defaultKey = props.getProperty("defaultKey", KEY_ALIAS_1);
+ }
final byte[] certbytes;
final byte[] passTestKey;
if (KEY_ALIAS_2.equals(defaultKey)) {
certbytes = certbytes2;
passTestKey = passTestKey2;
} else {
certbytes = certbytes1;
passTestKey = passTestKey1;
}
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certbytes));
PKCS8EncodedKeySpec pkKeySpec = new PKCS8EncodedKeySpec(passTestKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = keyFactory.generatePrivate(pkKeySpec);
} catch (NoSuchAlgorithmException e) {
throw new CryptoTokenInitializationFailureException("NoSuchAlgorithmException: " + e.getMessage());
} catch (InvalidKeySpecException e) {
throw new CryptoTokenInitializationFailureException("InvalidKeySpecException: " + e.getMessage());
}catch (CertificateException e) {
throw new CryptoTokenInitializationFailureException("CertificateException: " + e.getMessage());
} catch (NoSuchProviderException e) {
throw new CryptoTokenInitializationFailureException("NoSuchProviderException: " + e.getMessage());
}
}
/**
* Always returns ICryptoToken.STATUS_ACTIVE
*/
public int getCryptoTokenStatus() {
return SignerStatus.STATUS_ACTIVE;
}
/**
* Not used in current implementation
*/
public void activate(String authenticationcode)
throws CryptoTokenAuthenticationFailureException,
CryptoTokenOfflineException {
if(authenticationcode.equals("9876")){
throw new CryptoTokenAuthenticationFailureException("");
}
}
/**
* Not used in current implementation
*/
public boolean deactivate() {
return true;
}
/**
* Returns the private part of the testkey
*
* @param purpose not used
*/
public PrivateKey getPrivateKey(int purpose)
throws CryptoTokenOfflineException {
return privateKey;
}
/**
* Returns the public part of the testkey
*
* @param purpose not used
*/
public PublicKey getPublicKey(int purpose) throws CryptoTokenOfflineException {
return cert.getPublicKey();
}
public String getProvider(int providerUsage) {
return "BC";
}
public Certificate getCertificate(int purpose) throws CryptoTokenOfflineException {
return cert;
}
/**
* Not supported
*/
public Collection<Certificate> getCertificateChain(int purpose) throws CryptoTokenOfflineException {
ArrayList<Certificate> certs = new ArrayList<Certificate>();
certs.add(cert);
return certs;
}
/**
* Method not supported
*/
public ICertReqData genCertificateRequest(ISignerCertReqInfo info,
final boolean explicitEccParameters, final boolean defaultKey)
throws CryptoTokenOfflineException {
return null;
}
/**
* Method not supported
*/
public boolean destroyKey(int purpose) {
return true;
}
public Collection<KeyTestResult> testKey(final String alias,
final char[] authCode)
throws CryptoTokenOfflineException, KeyStoreException {
throw new UnsupportedOperationException("Not supported yet.");
}
public KeyStore getKeyStore() throws UnsupportedOperationException,
CryptoTokenOfflineException, KeyStoreException {
throw new UnsupportedOperationException(
"Operation not supported by crypto token.");
}
}
| true | true | public void init(int workerId, Properties props) throws CryptoTokenInitializationFailureException {
final String defaultKey = props.getProperty("defaultKey", KEY_ALIAS_1);
final byte[] certbytes;
final byte[] passTestKey;
if (KEY_ALIAS_2.equals(defaultKey)) {
certbytes = certbytes2;
passTestKey = passTestKey2;
} else {
certbytes = certbytes1;
passTestKey = passTestKey1;
}
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certbytes));
PKCS8EncodedKeySpec pkKeySpec = new PKCS8EncodedKeySpec(passTestKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = keyFactory.generatePrivate(pkKeySpec);
} catch (NoSuchAlgorithmException e) {
throw new CryptoTokenInitializationFailureException("NoSuchAlgorithmException: " + e.getMessage());
} catch (InvalidKeySpecException e) {
throw new CryptoTokenInitializationFailureException("InvalidKeySpecException: " + e.getMessage());
}catch (CertificateException e) {
throw new CryptoTokenInitializationFailureException("CertificateException: " + e.getMessage());
} catch (NoSuchProviderException e) {
throw new CryptoTokenInitializationFailureException("NoSuchProviderException: " + e.getMessage());
}
}
| public void init(int workerId, Properties props) throws CryptoTokenInitializationFailureException {
final String defaultKey;
if (props == null) {
defaultKey = KEY_ALIAS_1;
} else {
defaultKey = props.getProperty("defaultKey", KEY_ALIAS_1);
}
final byte[] certbytes;
final byte[] passTestKey;
if (KEY_ALIAS_2.equals(defaultKey)) {
certbytes = certbytes2;
passTestKey = passTestKey2;
} else {
certbytes = certbytes1;
passTestKey = passTestKey1;
}
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certbytes));
PKCS8EncodedKeySpec pkKeySpec = new PKCS8EncodedKeySpec(passTestKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = keyFactory.generatePrivate(pkKeySpec);
} catch (NoSuchAlgorithmException e) {
throw new CryptoTokenInitializationFailureException("NoSuchAlgorithmException: " + e.getMessage());
} catch (InvalidKeySpecException e) {
throw new CryptoTokenInitializationFailureException("InvalidKeySpecException: " + e.getMessage());
}catch (CertificateException e) {
throw new CryptoTokenInitializationFailureException("CertificateException: " + e.getMessage());
} catch (NoSuchProviderException e) {
throw new CryptoTokenInitializationFailureException("NoSuchProviderException: " + e.getMessage());
}
}
|
diff --git a/src/main/java/org/rcsb/sequence/view/html/ProtModSummary.java b/src/main/java/org/rcsb/sequence/view/html/ProtModSummary.java
index 467767b..95e9959 100644
--- a/src/main/java/org/rcsb/sequence/view/html/ProtModSummary.java
+++ b/src/main/java/org/rcsb/sequence/view/html/ProtModSummary.java
@@ -1,115 +1,115 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on Aug 9, 2010
* Author: Jianjiong Gao
*
*/
package org.rcsb.sequence.view.html;
import org.biojava3.protmod.ProteinModification;
import org.biojava3.protmod.structure.ModifiedCompound;
import org.rcsb.sequence.annotations.ProtModValue;
import org.rcsb.sequence.conf.Annotation2Jmol;
import org.rcsb.sequence.model.AnnotationGroup;
import org.rcsb.sequence.model.AnnotationValue;
import org.rcsb.sequence.util.ColorWheelUtil;
import org.rcsb.sequence.view.multiline.ProtModDrawerUtil;
public class ProtModSummary extends AnnotationSummaryCell<ModifiedCompound> {
public ProtModSummary(AnnotationGroup<ModifiedCompound> ag) {
super(ag);
}
@Override
protected void renderAnnotation(AnnotationValue<ModifiedCompound> av, HtmlElement el) {
//System.out.println("renderAnntoation " + av);
ProtModValue pv = (ProtModValue)av;
ModifiedCompound mc = pv.value();
//el.replaceContent("["+mc.getModification().getKeywords()+"]");
HtmlElement colouredDomId;
colouredDomId = new HtmlElement("span");
colouredDomId.addAttribute("style", "tooltip");
colouredDomId.addAttribute("title", "View in Jmol");
colouredDomId.addAttribute("style", "background-color: " + ColorWheelUtil.getColorHex(ProtModDrawerUtil.getColor(mc.getModification())));
colouredDomId.addAttribute("onclick", Annotation2Jmol.getOnclick(ag, av));
colouredDomId.addAttribute("class", "clickableIfJmol");
colouredDomId.appendToContent(" ")
.appendToContent(mc.getModification().getId())
.appendToContent(" ");
el.addChild(colouredDomId);
HtmlElement text = new HtmlElement("span");
String protModLegend = buildHTMLLegend(mc);
text.appendToContent(protModLegend).appendToContent(" ");
el.addChild(text);
//System.out.println(el.toString());
//el.replaceContent(protModLegend);
}
private String buildHTMLLegend(ModifiedCompound mc) {
StringBuilder b = new StringBuilder();
//b.append(mc.toString());
ProteinModification mod = mc.getModification();
b.append(mod.toString());
if ( mod.getResidId() != null ){
b.append(" <i>RESID</i>:<a target=\"_blank\" href=\"http://srs.ebi.ac.uk/srsbin/cgi-bin/wgetz?-newId+[RESID:'");
b.append(mod.getResidId());
b.append("']+-view+ResidEntry+-page+qResult\">");
b.append(mod.getResidId());
- b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></a>");
+ b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></span></a>");
}
if ( mod.getPsimodId() != null){
b.append(" <i>PSI-MOD</i>:<a target=\"_blank\" href=\"http://www.ebi.ac.uk/ontology-lookup/?termId=");
b.append(mod.getPsimodId());
b.append("\">");
b.append(mod.getPsimodId());
- b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></a>");
+ b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></span></a>");
}
if ( mod.getPdbccId() != null){
b.append(" <i>PDB</i>:<a href=\"http://www.pdb.org/pdb/ligand/ligandsummary.do?hetId=");
b.append(mod.getPdbccId());
b.append("\">");
b.append(mod.getPdbccId());
b.append("</a>");
}
return b.toString();
}
}
| false | true | private String buildHTMLLegend(ModifiedCompound mc) {
StringBuilder b = new StringBuilder();
//b.append(mc.toString());
ProteinModification mod = mc.getModification();
b.append(mod.toString());
if ( mod.getResidId() != null ){
b.append(" <i>RESID</i>:<a target=\"_blank\" href=\"http://srs.ebi.ac.uk/srsbin/cgi-bin/wgetz?-newId+[RESID:'");
b.append(mod.getResidId());
b.append("']+-view+ResidEntry+-page+qResult\">");
b.append(mod.getResidId());
b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></a>");
}
if ( mod.getPsimodId() != null){
b.append(" <i>PSI-MOD</i>:<a target=\"_blank\" href=\"http://www.ebi.ac.uk/ontology-lookup/?termId=");
b.append(mod.getPsimodId());
b.append("\">");
b.append(mod.getPsimodId());
b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></a>");
}
if ( mod.getPdbccId() != null){
b.append(" <i>PDB</i>:<a href=\"http://www.pdb.org/pdb/ligand/ligandsummary.do?hetId=");
b.append(mod.getPdbccId());
b.append("\">");
b.append(mod.getPdbccId());
b.append("</a>");
}
return b.toString();
}
| private String buildHTMLLegend(ModifiedCompound mc) {
StringBuilder b = new StringBuilder();
//b.append(mc.toString());
ProteinModification mod = mc.getModification();
b.append(mod.toString());
if ( mod.getResidId() != null ){
b.append(" <i>RESID</i>:<a target=\"_blank\" href=\"http://srs.ebi.ac.uk/srsbin/cgi-bin/wgetz?-newId+[RESID:'");
b.append(mod.getResidId());
b.append("']+-view+ResidEntry+-page+qResult\">");
b.append(mod.getResidId());
b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></span></a>");
}
if ( mod.getPsimodId() != null){
b.append(" <i>PSI-MOD</i>:<a target=\"_blank\" href=\"http://www.ebi.ac.uk/ontology-lookup/?termId=");
b.append(mod.getPsimodId());
b.append("\">");
b.append(mod.getPsimodId());
b.append("<span title=\"external link\" class=\"iconSet-main icon-external\"></span></a>");
}
if ( mod.getPdbccId() != null){
b.append(" <i>PDB</i>:<a href=\"http://www.pdb.org/pdb/ligand/ligandsummary.do?hetId=");
b.append(mod.getPdbccId());
b.append("\">");
b.append(mod.getPdbccId());
b.append("</a>");
}
return b.toString();
}
|
diff --git a/servlets/FBtestservlet.java b/servlets/FBtestservlet.java
index f4fd607..4a7d7f7 100644
--- a/servlets/FBtestservlet.java
+++ b/servlets/FBtestservlet.java
@@ -1,82 +1,80 @@
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.ArrayList;
import model.Schema;
import static model.Schema.*;
import model.*;
import scala.collection.*;
import static scala.collection.JavaConversions.*;
import java.util.*;
import scala.math.BigDecimal;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.StringTokenizer;
import javax.servlet.*;
import javax.servlet.http.*;
public class FBtestservlet extends HttpServlet {
protected void doPost( HttpServletRequest request,HttpServletResponse response )
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// String ticker= request.getParameter("ticker");
// String volume = request.getParameter("volume");
// System.out.println("***********************"+username+"***********************"+ticker+"*************************"+volume+"(((((((((((((((((((((((((((");
String userId = request.getParameter("username");
- String stockSymbol = "";
- String volume = "";
- System.out.println("))))))))))))))))))))))(((((((((((");
+ String stockSymbol = request.getParameter("ticker");
//String results = "";
try {
/*
*/
/* StringTokenizer token = new StringTokenizer(username,":");
int i = 0;
System.out.println("***********"+username+"***********");
if (token.countTokens() == 4) {
userId = token.nextToken();
String operation = token.nextToken();
volume = token.nextToken();
// int shares = Integer.parseInt(dollars_text);
stockSymbol = token.nextToken();
}
/* userId = results.get(0);
stockSymbol = results.get(1);
volume = results.get(2);
*/ User user = ensureUser("sonu_pillai");
//System.out.println("***********"+userId+"***********");
//System.out.println("***********"+volume+"***********");
Portfolio port = user.mainPortfolio().fetch(portfolios());
// port.buyStock("GOOG", new Dollars("2000"));
} catch (Exception e) {
e.printStackTrace();
}
- System.out.println("********************"+userId+"**********************************");
+ System.out.println("********************"+userId+"****************"+stockSymbol+"******************");
response.setContentType("text/html");
out.println("success");
}
}
| false | true | protected void doPost( HttpServletRequest request,HttpServletResponse response )
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// String ticker= request.getParameter("ticker");
// String volume = request.getParameter("volume");
// System.out.println("***********************"+username+"***********************"+ticker+"*************************"+volume+"(((((((((((((((((((((((((((");
String userId = request.getParameter("username");
String stockSymbol = "";
String volume = "";
System.out.println("))))))))))))))))))))))(((((((((((");
//String results = "";
try {
/*
*/
/* StringTokenizer token = new StringTokenizer(username,":");
int i = 0;
System.out.println("***********"+username+"***********");
if (token.countTokens() == 4) {
userId = token.nextToken();
String operation = token.nextToken();
volume = token.nextToken();
// int shares = Integer.parseInt(dollars_text);
stockSymbol = token.nextToken();
}
/* userId = results.get(0);
stockSymbol = results.get(1);
volume = results.get(2);
*/ User user = ensureUser("sonu_pillai");
//System.out.println("***********"+userId+"***********");
//System.out.println("***********"+volume+"***********");
Portfolio port = user.mainPortfolio().fetch(portfolios());
// port.buyStock("GOOG", new Dollars("2000"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("********************"+userId+"**********************************");
response.setContentType("text/html");
out.println("success");
}
| protected void doPost( HttpServletRequest request,HttpServletResponse response )
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// String ticker= request.getParameter("ticker");
// String volume = request.getParameter("volume");
// System.out.println("***********************"+username+"***********************"+ticker+"*************************"+volume+"(((((((((((((((((((((((((((");
String userId = request.getParameter("username");
String stockSymbol = request.getParameter("ticker");
//String results = "";
try {
/*
*/
/* StringTokenizer token = new StringTokenizer(username,":");
int i = 0;
System.out.println("***********"+username+"***********");
if (token.countTokens() == 4) {
userId = token.nextToken();
String operation = token.nextToken();
volume = token.nextToken();
// int shares = Integer.parseInt(dollars_text);
stockSymbol = token.nextToken();
}
/* userId = results.get(0);
stockSymbol = results.get(1);
volume = results.get(2);
*/ User user = ensureUser("sonu_pillai");
//System.out.println("***********"+userId+"***********");
//System.out.println("***********"+volume+"***********");
Portfolio port = user.mainPortfolio().fetch(portfolios());
// port.buyStock("GOOG", new Dollars("2000"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("********************"+userId+"****************"+stockSymbol+"******************");
response.setContentType("text/html");
out.println("success");
}
|
diff --git a/src/com/android/launcher2/CachedTextView.java b/src/com/android/launcher2/CachedTextView.java
index d0f6dd80..ac2cc3b5 100644
--- a/src/com/android/launcher2/CachedTextView.java
+++ b/src/com/android/launcher2/CachedTextView.java
@@ -1,181 +1,181 @@
/*
* 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.launcher2;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.util.AttributeSet;
import android.widget.TextView;
/*
* This class is a bit of a hack, designed to speed up long text labels in Launcher. It caches the
* text in a TextView to a bitmap and then just draws that Bitmap instead afterward, speeding up
* rendering. Marquee scrolling is not currently supported.
*
*/
public class CachedTextView extends TextView {
private Bitmap mCache;
private final Paint mCachePaint = new Paint();
private final Canvas mCacheCanvas = new Canvas();
private int mPrevAlpha = -1;
private boolean mIsBuildingCache;
boolean mIsTextCacheDirty;
float mTextCacheLeft;
float mTextCacheTop;
float mTextCacheScrollX;
float mRectLeft, mRectTop;
private float mPaddingH = 0;
private float mPaddingV = 0;
private CharSequence mText;
private boolean mEnabled = true;
public CachedTextView(Context context) {
super(context);
}
public CachedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CachedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected int getCacheTopPadding() {
return 0;
}
protected int getCacheLeftPadding() {
return 0;
}
protected int getCacheRightPadding() {
return 0;
}
protected int getCacheBottomPadding() {
return 0;
}
public void disableCache() {
mEnabled = false;
}
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
mIsTextCacheDirty = true;
}
private void buildAndUpdateCache() {
final Layout layout = getLayout();
final int left = getCompoundPaddingLeft();
final int top = getExtendedPaddingTop();
final float prevAlpha = getAlpha();
mTextCacheLeft = layout.getLineLeft(0) - getCacheLeftPadding();
mTextCacheTop = top + layout.getLineTop(0) - mPaddingV - getCacheTopPadding();
mRectLeft = mScrollX + getLeft();
mRectTop = 0;
mTextCacheScrollX = mScrollX;
final float textCacheRight =
Math.min(left + layout.getLineRight(0) + mPaddingH, mScrollX + mRight - mLeft) +
getCacheRightPadding();
final float textCacheBottom = top + layout.getLineBottom(0) + mPaddingV +
getCacheBottomPadding();
final float xCharWidth = getPaint().measureText("x");
int width = (int) (textCacheRight - mTextCacheLeft + (2 * xCharWidth));
int height = (int) (textCacheBottom - mTextCacheTop);
- if (width != 0 && height != 0) {
+ if (width > 0 && height > 0) {
if (mCache != null) {
if (mCache.getWidth() != width || mCache.getHeight() != height) {
mCache.recycle();
mCache = null;
}
}
if (mCache == null) {
mCache = Bitmap.createBitmap(width, height, Config.ARGB_8888);
mCacheCanvas.setBitmap(mCache);
} else {
mCacheCanvas.drawColor(0, Mode.CLEAR);
}
mCacheCanvas.save();
mCacheCanvas.translate(-mTextCacheLeft, -mTextCacheTop);
mIsBuildingCache = true;
setAlpha(1.0f);
draw(mCacheCanvas);
setAlpha(prevAlpha);
mIsBuildingCache = false;
mCacheCanvas.restore();
// A hack-- we set the text to be one space (we don't make it empty just to avoid any
// potential issues with text measurement, like line height, etc.) so that the text view
// doesn't draw it anymore, since it's been cached.
mText = getText();
setText(" ");
}
}
public CharSequence getText() {
return (mText == null) ? super.getText() : mText;
}
public void draw(Canvas canvas) {
if (mEnabled && mIsTextCacheDirty && !mIsBuildingCache) {
buildAndUpdateCache();
mIsTextCacheDirty = false;
}
if (mCache != null && !mIsBuildingCache) {
canvas.drawBitmap(mCache, mTextCacheLeft - mTextCacheScrollX + mScrollX,
mTextCacheTop, mCachePaint);
}
super.draw(canvas);
}
protected boolean isBuildingCache() {
return mIsBuildingCache;
}
@Override
protected boolean onSetAlpha(int alpha) {
if (mPrevAlpha != alpha) {
mPrevAlpha = alpha;
mCachePaint.setAlpha(alpha);
// We manually update the drawables alpha since the default TextView implementation may
// not do this if there is a background set (which we may due to the focus bg)
final Drawable[] dr = getCompoundDrawables();
for (int i = 0; i < dr.length; ++i) {
if (dr[i] != null) {
dr[i].mutate().setAlpha(alpha);
}
}
super.onSetAlpha(alpha);
}
return true;
}
}
| true | true | private void buildAndUpdateCache() {
final Layout layout = getLayout();
final int left = getCompoundPaddingLeft();
final int top = getExtendedPaddingTop();
final float prevAlpha = getAlpha();
mTextCacheLeft = layout.getLineLeft(0) - getCacheLeftPadding();
mTextCacheTop = top + layout.getLineTop(0) - mPaddingV - getCacheTopPadding();
mRectLeft = mScrollX + getLeft();
mRectTop = 0;
mTextCacheScrollX = mScrollX;
final float textCacheRight =
Math.min(left + layout.getLineRight(0) + mPaddingH, mScrollX + mRight - mLeft) +
getCacheRightPadding();
final float textCacheBottom = top + layout.getLineBottom(0) + mPaddingV +
getCacheBottomPadding();
final float xCharWidth = getPaint().measureText("x");
int width = (int) (textCacheRight - mTextCacheLeft + (2 * xCharWidth));
int height = (int) (textCacheBottom - mTextCacheTop);
if (width != 0 && height != 0) {
if (mCache != null) {
if (mCache.getWidth() != width || mCache.getHeight() != height) {
mCache.recycle();
mCache = null;
}
}
if (mCache == null) {
mCache = Bitmap.createBitmap(width, height, Config.ARGB_8888);
mCacheCanvas.setBitmap(mCache);
} else {
mCacheCanvas.drawColor(0, Mode.CLEAR);
}
mCacheCanvas.save();
mCacheCanvas.translate(-mTextCacheLeft, -mTextCacheTop);
mIsBuildingCache = true;
setAlpha(1.0f);
draw(mCacheCanvas);
setAlpha(prevAlpha);
mIsBuildingCache = false;
mCacheCanvas.restore();
// A hack-- we set the text to be one space (we don't make it empty just to avoid any
// potential issues with text measurement, like line height, etc.) so that the text view
// doesn't draw it anymore, since it's been cached.
mText = getText();
setText(" ");
}
}
| private void buildAndUpdateCache() {
final Layout layout = getLayout();
final int left = getCompoundPaddingLeft();
final int top = getExtendedPaddingTop();
final float prevAlpha = getAlpha();
mTextCacheLeft = layout.getLineLeft(0) - getCacheLeftPadding();
mTextCacheTop = top + layout.getLineTop(0) - mPaddingV - getCacheTopPadding();
mRectLeft = mScrollX + getLeft();
mRectTop = 0;
mTextCacheScrollX = mScrollX;
final float textCacheRight =
Math.min(left + layout.getLineRight(0) + mPaddingH, mScrollX + mRight - mLeft) +
getCacheRightPadding();
final float textCacheBottom = top + layout.getLineBottom(0) + mPaddingV +
getCacheBottomPadding();
final float xCharWidth = getPaint().measureText("x");
int width = (int) (textCacheRight - mTextCacheLeft + (2 * xCharWidth));
int height = (int) (textCacheBottom - mTextCacheTop);
if (width > 0 && height > 0) {
if (mCache != null) {
if (mCache.getWidth() != width || mCache.getHeight() != height) {
mCache.recycle();
mCache = null;
}
}
if (mCache == null) {
mCache = Bitmap.createBitmap(width, height, Config.ARGB_8888);
mCacheCanvas.setBitmap(mCache);
} else {
mCacheCanvas.drawColor(0, Mode.CLEAR);
}
mCacheCanvas.save();
mCacheCanvas.translate(-mTextCacheLeft, -mTextCacheTop);
mIsBuildingCache = true;
setAlpha(1.0f);
draw(mCacheCanvas);
setAlpha(prevAlpha);
mIsBuildingCache = false;
mCacheCanvas.restore();
// A hack-- we set the text to be one space (we don't make it empty just to avoid any
// potential issues with text measurement, like line height, etc.) so that the text view
// doesn't draw it anymore, since it's been cached.
mText = getText();
setText(" ");
}
}
|
diff --git a/src/com/android/calendar/month/MonthByWeekAdapter.java b/src/com/android/calendar/month/MonthByWeekAdapter.java
index 8b914304..a5b28119 100644
--- a/src/com/android/calendar/month/MonthByWeekAdapter.java
+++ b/src/com/android/calendar/month/MonthByWeekAdapter.java
@@ -1,428 +1,429 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar.month;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import com.android.calendar.CalendarController;
import com.android.calendar.CalendarController.EventType;
import com.android.calendar.CalendarController.ViewType;
import com.android.calendar.Event;
import com.android.calendar.R;
import com.android.calendar.Utils;
import java.util.ArrayList;
import java.util.HashMap;
public class MonthByWeekAdapter extends SimpleWeeksAdapter implements View.OnLongClickListener {
private static final String TAG = "MonthByWeekAdapter";
public static final String WEEK_PARAMS_IS_MINI = "mini_month";
protected static int DEFAULT_QUERY_DAYS = 7 * 8; // 8 weeks
private static final long ANIMATE_TODAY_TIMEOUT = 1000;
protected CalendarController mController;
protected String mHomeTimeZone;
protected Time mTempTime;
protected Time mToday;
protected int mFirstJulianDay;
protected int mQueryDays;
protected boolean mIsMiniMonth = true;
protected int mOrientation = Configuration.ORIENTATION_LANDSCAPE;
private final boolean mShowAgendaWithMonth;
protected ArrayList<ArrayList<Event>> mEventDayList = new ArrayList<ArrayList<Event>>();
protected ArrayList<Event> mEvents = null;
private boolean mAnimateToday = false;
private long mAnimateTime = 0;
private Handler mEventDialogHandler;
MonthWeekEventsView mClickedView;
MonthWeekEventsView mSingleTapUpView;
float mClickedXLocation; // Used to find which day was clicked
long mClickTime; // Used to calculate minimum click animation time
// Used to insure minimal time for seeing the click animation before switching views
private static final int mOnTapDelay = 100;
// Minimal time for a down touch action before stating the click animation, this insures that
// there is no click animation on flings
private static int mOnDownDelay;
private static int mTotalClickDelay;
// Minimal distance to move the finger in order to cancel the click animation
private static float mMovedPixelToCancel;
public MonthByWeekAdapter(Context context, HashMap<String, Integer> params, Handler handler) {
super(context, params);
mEventDialogHandler = handler;
if (params.containsKey(WEEK_PARAMS_IS_MINI)) {
mIsMiniMonth = params.get(WEEK_PARAMS_IS_MINI) != 0;
}
mShowAgendaWithMonth = Utils.getConfigBool(context, R.bool.show_agenda_with_month);
ViewConfiguration vc = ViewConfiguration.get(context);
mOnDownDelay = ViewConfiguration.getTapTimeout();
mMovedPixelToCancel = vc.getScaledTouchSlop();
mTotalClickDelay = mOnDownDelay + mOnTapDelay;
}
public void animateToday() {
mAnimateToday = true;
mAnimateTime = System.currentTimeMillis();
}
@Override
protected void init() {
super.init();
mController = CalendarController.getInstance(mContext);
mHomeTimeZone = Utils.getTimeZone(mContext, null);
mSelectedDay.switchTimezone(mHomeTimeZone);
mToday = new Time(mHomeTimeZone);
mToday.setToNow();
mTempTime = new Time(mHomeTimeZone);
}
private void updateTimeZones() {
mSelectedDay.timezone = mHomeTimeZone;
mSelectedDay.normalize(true);
mToday.timezone = mHomeTimeZone;
mToday.setToNow();
mTempTime.switchTimezone(mHomeTimeZone);
}
@Override
public void setSelectedDay(Time selectedTime) {
mSelectedDay.set(selectedTime);
long millis = mSelectedDay.normalize(true);
mSelectedWeek = Utils.getWeeksSinceEpochFromJulianDay(
Time.getJulianDay(millis, mSelectedDay.gmtoff), mFirstDayOfWeek);
notifyDataSetChanged();
}
public void setEvents(int firstJulianDay, int numDays, ArrayList<Event> events) {
if (mIsMiniMonth) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "Attempted to set events for mini view. Events only supported in full"
+ " view.");
}
return;
}
mEvents = events;
mFirstJulianDay = firstJulianDay;
mQueryDays = numDays;
// Create a new list, this is necessary since the weeks are referencing
// pieces of the old list
ArrayList<ArrayList<Event>> eventDayList = new ArrayList<ArrayList<Event>>();
for (int i = 0; i < numDays; i++) {
eventDayList.add(new ArrayList<Event>());
}
if (events == null || events.size() == 0) {
if(Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "No events. Returning early--go schedule something fun.");
}
mEventDayList = eventDayList;
refresh();
return;
}
// Compute the new set of days with events
for (Event event : events) {
int startDay = event.startDay - mFirstJulianDay;
int endDay = event.endDay - mFirstJulianDay + 1;
if (startDay < numDays || endDay >= 0) {
if (startDay < 0) {
startDay = 0;
}
if (startDay > numDays) {
continue;
}
if (endDay < 0) {
continue;
}
if (endDay > numDays) {
endDay = numDays;
}
for (int j = startDay; j < endDay; j++) {
eventDayList.get(j).add(event);
}
}
}
if(Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Processed " + events.size() + " events.");
}
mEventDayList = eventDayList;
refresh();
}
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mIsMiniMonth) {
return super.getView(position, convertView, parent);
}
MonthWeekEventsView v;
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
HashMap<String, Integer> drawingParams = null;
boolean isAnimatingToday = false;
if (convertView != null) {
v = (MonthWeekEventsView) convertView;
// Checking updateToday uses the current params instead of the new
// params, so this is assuming the view is relatively stable
if (mAnimateToday && v.updateToday(mSelectedDay.timezone)) {
long currentTime = System.currentTimeMillis();
// If it's been too long since we tried to start the animation
// don't show it. This can happen if the user stops a scroll
// before reaching today.
if (currentTime - mAnimateTime > ANIMATE_TODAY_TIMEOUT) {
mAnimateToday = false;
mAnimateTime = 0;
} else {
isAnimatingToday = true;
// There is a bug that causes invalidates to not work some
// of the time unless we recreate the view.
v = new MonthWeekEventsView(mContext);
- }
+ v.setOnLongClickListener(this);
+ }
} else {
drawingParams = (HashMap<String, Integer>) v.getTag();
}
} else {
v = new MonthWeekEventsView(mContext);
v.setOnLongClickListener(this);
}
if (drawingParams == null) {
drawingParams = new HashMap<String, Integer>();
}
drawingParams.clear();
v.setLayoutParams(params);
v.setClickable(true);
v.setOnTouchListener(this);
int selectedDay = -1;
if (mSelectedWeek == position) {
selectedDay = mSelectedDay.weekDay;
}
drawingParams.put(SimpleWeekView.VIEW_PARAMS_HEIGHT,
(parent.getHeight() + parent.getTop()) / mNumWeeks);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_SHOW_WK_NUM, mShowWeekNumber ? 1 : 0);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_WEEK_START, mFirstDayOfWeek);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_NUM_DAYS, mDaysPerWeek);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_WEEK, position);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_FOCUS_MONTH, mFocusMonth);
drawingParams.put(MonthWeekEventsView.VIEW_PARAMS_ORIENTATION, mOrientation);
if (isAnimatingToday) {
drawingParams.put(MonthWeekEventsView.VIEW_PARAMS_ANIMATE_TODAY, 1);
mAnimateToday = false;
}
v.setWeekParams(drawingParams, mSelectedDay.timezone);
sendEventsToView(v);
return v;
}
private void sendEventsToView(MonthWeekEventsView v) {
if (mEventDayList.size() == 0) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "No events loaded, did not pass any events to view.");
}
v.setEvents(null, null);
return;
}
int viewJulianDay = v.getFirstJulianDay();
int start = viewJulianDay - mFirstJulianDay;
int end = start + v.mNumDays;
if (start < 0 || end > mEventDayList.size()) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Week is outside range of loaded events. viewStart: " + viewJulianDay
+ " eventsStart: " + mFirstJulianDay);
}
v.setEvents(null, null);
return;
}
v.setEvents(mEventDayList.subList(start, end), mEvents);
}
@Override
protected void refresh() {
mFirstDayOfWeek = Utils.getFirstDayOfWeek(mContext);
mShowWeekNumber = Utils.getShowWeekNumber(mContext);
mHomeTimeZone = Utils.getTimeZone(mContext, null);
mOrientation = mContext.getResources().getConfiguration().orientation;
updateTimeZones();
notifyDataSetChanged();
}
@Override
protected void onDayTapped(Time day) {
setDayParameters(day);
if (mShowAgendaWithMonth || mIsMiniMonth) {
// If agenda view is visible with month view , refresh the views
// with the selected day's info
mController.sendEvent(mContext, EventType.GO_TO, day, day, -1,
ViewType.CURRENT, CalendarController.EXTRA_GOTO_DATE, null, null);
} else {
// Else , switch to the detailed view
mController.sendEvent(mContext, EventType.GO_TO, day, day, -1,
ViewType.DETAIL,
CalendarController.EXTRA_GOTO_DATE
| CalendarController.EXTRA_GOTO_BACK_TO_PREVIOUS, null, null);
}
}
private void setDayParameters(Time day) {
day.timezone = mHomeTimeZone;
Time currTime = new Time(mHomeTimeZone);
currTime.set(mController.getTime());
day.hour = currTime.hour;
day.minute = currTime.minute;
day.allDay = false;
day.normalize(true);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (!(v instanceof MonthWeekEventsView)) {
return super.onTouch(v, event);
}
int action = event.getAction();
// Event was tapped - switch to the detailed view making sure the click animation
// is done first.
if (mGestureDetector.onTouchEvent(event)) {
mSingleTapUpView = (MonthWeekEventsView) v;
long delay = System.currentTimeMillis() - mClickTime;
// Make sure the animation is visible for at least mOnTapDelay - mOnDownDelay ms
mListView.postDelayed(mDoSingleTapUp,
delay > mTotalClickDelay ? 0 : mTotalClickDelay - delay);
return true;
} else {
// Animate a click - on down: show the selected day in the "clicked" color.
// On Up/scroll/move/cancel: hide the "clicked" color.
switch (action) {
case MotionEvent.ACTION_DOWN:
mClickedView = (MonthWeekEventsView)v;
mClickedXLocation = event.getX();
mClickTime = System.currentTimeMillis();
mListView.postDelayed(mDoClick, mOnDownDelay);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_SCROLL:
case MotionEvent.ACTION_CANCEL:
clearClickedView((MonthWeekEventsView)v);
break;
case MotionEvent.ACTION_MOVE:
// No need to cancel on vertical movement, ACTION_SCROLL will do that.
if (Math.abs(event.getX() - mClickedXLocation) > mMovedPixelToCancel) {
clearClickedView((MonthWeekEventsView)v);
}
break;
default:
break;
}
}
// Do not tell the frameworks we consumed the touch action so that fling actions can be
// processed by the fragment.
return false;
}
/**
* This is here so we can identify events and process them
*/
protected class CalendarGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
}
// Clear the visual cues of the click animation and related running code.
private void clearClickedView(MonthWeekEventsView v) {
mListView.removeCallbacks(mDoClick);
synchronized(v) {
v.clearClickedDay();
}
mClickedView = null;
}
// Perform the tap animation in a runnable to allow a delay before showing the tap color.
// This is done to prevent a click animation when a fling is done.
private final Runnable mDoClick = new Runnable() {
@Override
public void run() {
if (mClickedView != null) {
synchronized(mClickedView) {
mClickedView.setClickedDay(mClickedXLocation);
}
mClickedView = null;
// This is a workaround , sometimes the top item on the listview doesn't refresh on
// invalidate, so this forces a re-draw.
mListView.invalidate();
}
}
};
// Performs the single tap operation: go to the tapped day.
// This is done in a runnable to allow the click animation to finish before switching views
private final Runnable mDoSingleTapUp = new Runnable() {
@Override
public void run() {
if (mSingleTapUpView != null) {
Time day = mSingleTapUpView.getDayFromLocation(mClickedXLocation);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Touched day at Row=" + mSingleTapUpView.mWeek + " day=" + day.toString());
}
if (day != null) {
onDayTapped(day);
}
clearClickedView(mSingleTapUpView);
mSingleTapUpView = null;
}
}
};
@Override
public boolean onLongClick(View v) {
MonthWeekEventsView weekView = (MonthWeekEventsView) v;
Time day = weekView.getDayFromLocation(mClickedXLocation);
if (day == null) {
// The day that was clicked is malformed, so just die here.
// Return true so nothing else tries to use the malformed day.
return true;
}
Message message = new Message();
message.obj = day;
mEventDialogHandler.sendMessage(message);
return true;
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
if (mIsMiniMonth) {
return super.getView(position, convertView, parent);
}
MonthWeekEventsView v;
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
HashMap<String, Integer> drawingParams = null;
boolean isAnimatingToday = false;
if (convertView != null) {
v = (MonthWeekEventsView) convertView;
// Checking updateToday uses the current params instead of the new
// params, so this is assuming the view is relatively stable
if (mAnimateToday && v.updateToday(mSelectedDay.timezone)) {
long currentTime = System.currentTimeMillis();
// If it's been too long since we tried to start the animation
// don't show it. This can happen if the user stops a scroll
// before reaching today.
if (currentTime - mAnimateTime > ANIMATE_TODAY_TIMEOUT) {
mAnimateToday = false;
mAnimateTime = 0;
} else {
isAnimatingToday = true;
// There is a bug that causes invalidates to not work some
// of the time unless we recreate the view.
v = new MonthWeekEventsView(mContext);
}
} else {
drawingParams = (HashMap<String, Integer>) v.getTag();
}
} else {
v = new MonthWeekEventsView(mContext);
v.setOnLongClickListener(this);
}
if (drawingParams == null) {
drawingParams = new HashMap<String, Integer>();
}
drawingParams.clear();
v.setLayoutParams(params);
v.setClickable(true);
v.setOnTouchListener(this);
int selectedDay = -1;
if (mSelectedWeek == position) {
selectedDay = mSelectedDay.weekDay;
}
drawingParams.put(SimpleWeekView.VIEW_PARAMS_HEIGHT,
(parent.getHeight() + parent.getTop()) / mNumWeeks);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_SHOW_WK_NUM, mShowWeekNumber ? 1 : 0);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_WEEK_START, mFirstDayOfWeek);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_NUM_DAYS, mDaysPerWeek);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_WEEK, position);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_FOCUS_MONTH, mFocusMonth);
drawingParams.put(MonthWeekEventsView.VIEW_PARAMS_ORIENTATION, mOrientation);
if (isAnimatingToday) {
drawingParams.put(MonthWeekEventsView.VIEW_PARAMS_ANIMATE_TODAY, 1);
mAnimateToday = false;
}
v.setWeekParams(drawingParams, mSelectedDay.timezone);
sendEventsToView(v);
return v;
}
| public View getView(int position, View convertView, ViewGroup parent) {
if (mIsMiniMonth) {
return super.getView(position, convertView, parent);
}
MonthWeekEventsView v;
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
HashMap<String, Integer> drawingParams = null;
boolean isAnimatingToday = false;
if (convertView != null) {
v = (MonthWeekEventsView) convertView;
// Checking updateToday uses the current params instead of the new
// params, so this is assuming the view is relatively stable
if (mAnimateToday && v.updateToday(mSelectedDay.timezone)) {
long currentTime = System.currentTimeMillis();
// If it's been too long since we tried to start the animation
// don't show it. This can happen if the user stops a scroll
// before reaching today.
if (currentTime - mAnimateTime > ANIMATE_TODAY_TIMEOUT) {
mAnimateToday = false;
mAnimateTime = 0;
} else {
isAnimatingToday = true;
// There is a bug that causes invalidates to not work some
// of the time unless we recreate the view.
v = new MonthWeekEventsView(mContext);
v.setOnLongClickListener(this);
}
} else {
drawingParams = (HashMap<String, Integer>) v.getTag();
}
} else {
v = new MonthWeekEventsView(mContext);
v.setOnLongClickListener(this);
}
if (drawingParams == null) {
drawingParams = new HashMap<String, Integer>();
}
drawingParams.clear();
v.setLayoutParams(params);
v.setClickable(true);
v.setOnTouchListener(this);
int selectedDay = -1;
if (mSelectedWeek == position) {
selectedDay = mSelectedDay.weekDay;
}
drawingParams.put(SimpleWeekView.VIEW_PARAMS_HEIGHT,
(parent.getHeight() + parent.getTop()) / mNumWeeks);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_SHOW_WK_NUM, mShowWeekNumber ? 1 : 0);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_WEEK_START, mFirstDayOfWeek);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_NUM_DAYS, mDaysPerWeek);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_WEEK, position);
drawingParams.put(SimpleWeekView.VIEW_PARAMS_FOCUS_MONTH, mFocusMonth);
drawingParams.put(MonthWeekEventsView.VIEW_PARAMS_ORIENTATION, mOrientation);
if (isAnimatingToday) {
drawingParams.put(MonthWeekEventsView.VIEW_PARAMS_ANIMATE_TODAY, 1);
mAnimateToday = false;
}
v.setWeekParams(drawingParams, mSelectedDay.timezone);
sendEventsToView(v);
return v;
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/internal/services/DebugService.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/internal/services/DebugService.java
index 70ba6b96f..faae61e9c 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/internal/services/DebugService.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/internal/services/DebugService.java
@@ -1,117 +1,117 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.launch.ui.internal.services;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.te.launch.core.lm.LaunchManager;
import org.eclipse.tcf.te.launch.core.lm.interfaces.ILaunchManagerDelegate;
import org.eclipse.tcf.te.launch.core.lm.interfaces.ILaunchSpecification;
import org.eclipse.tcf.te.launch.core.persistence.launchcontext.LaunchContextsPersistenceDelegate;
import org.eclipse.tcf.te.launch.core.selection.LaunchSelection;
import org.eclipse.tcf.te.launch.core.selection.RemoteSelectionContext;
import org.eclipse.tcf.te.launch.core.selection.interfaces.ILaunchSelection;
import org.eclipse.tcf.te.runtime.concurrent.util.ExecutorsUtil;
import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback;
import org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer;
import org.eclipse.tcf.te.runtime.model.interfaces.IModelNode;
import org.eclipse.tcf.te.runtime.services.AbstractService;
import org.eclipse.tcf.te.runtime.services.interfaces.IDebugService;
import org.eclipse.tcf.te.runtime.utils.StatusHelper;
import org.eclipse.tcf.te.tcf.launch.core.interfaces.ILaunchTypes;
/**
* Debug service implementations for TCF contexts.
*/
public class DebugService extends AbstractService implements IDebugService {
/* (non-Javadoc)
* @see org.eclipse.tcf.te.runtime.services.interfaces.IDebugService#attach(java.lang.Object, org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
*/
@Override
public void attach(final Object context, final IPropertiesContainer data, final ICallback callback) {
if (!Protocol.isDispatchThread()) {
internalAttach(context, data, callback);
}
else {
ExecutorsUtil.execute(new Runnable() {
@Override
public void run() {
internalAttach(context, data, callback);
}
});
}
}
protected void internalAttach(final Object context, final IPropertiesContainer data, final ICallback callback) {
Assert.isTrue(!Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(context);
Assert.isNotNull(data);
Assert.isNotNull(callback);
if (context instanceof IModelNode) {
ILaunchConfigurationType launchConfigType = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(ILaunchTypes.ATTACH);
try {
ILaunchSelection launchSelection = new LaunchSelection(ILaunchManager.DEBUG_MODE, new RemoteSelectionContext((IModelNode)context, true));
ILaunchManagerDelegate delegate = LaunchManager.getInstance().getLaunchManagerDelegate(launchConfigType, ILaunchManager.DEBUG_MODE);
if (delegate != null) {
// create an empty launch configuration specification to initialize all attributes with their default defaults.
ILaunchSpecification launchSpec = delegate.getLaunchSpecification(launchConfigType.getIdentifier(), launchSelection);
for (String key : data.getProperties().keySet()) {
launchSpec.addAttribute(key, data.getProperty(key));
}
delegate.validate(launchSpec);
if (launchSpec != null && launchSpec.isValid()) {
ILaunchConfiguration[] launchConfigs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(launchConfigType);
launchConfigs = delegate.getMatchingLaunchConfigurations(launchSpec, launchConfigs);
ILaunchConfiguration config = launchConfigs != null && launchConfigs.length > 0 ? launchConfigs[0] : null;
boolean skip = false;
if (config != null) {
ILaunch[] launches = DebugPlugin.getDefault().getLaunchManager().getLaunches();
for (ILaunch launch : launches) {
- if (launch.getLaunchConfiguration().getType().getIdentifier().equals(ILaunchTypes.ATTACH)) {
+ if (launch.getLaunchConfiguration().getType().getIdentifier().equals(ILaunchTypes.ATTACH) && !launch.isTerminated()) {
IModelNode[] contexts = LaunchContextsPersistenceDelegate.getLaunchContexts(launch.getLaunchConfiguration());
if (contexts != null && contexts.length == 1 && contexts[0].equals(context)) {
skip = true;
}
}
}
}
if (!skip) {
config = LaunchManager.getInstance().createOrUpdateLaunchConfiguration(config, launchSpec);
delegate.validate(ILaunchManager.DEBUG_MODE, config);
DebugUITools.launch(config, ILaunchManager.DEBUG_MODE);
}
}
}
callback.done(this, Status.OK_STATUS);
}
catch (Exception e) {
callback.done(this, StatusHelper.getStatus(e));
}
}
else {
callback.done(this, Status.OK_STATUS);
}
}
}
| true | true | protected void internalAttach(final Object context, final IPropertiesContainer data, final ICallback callback) {
Assert.isTrue(!Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(context);
Assert.isNotNull(data);
Assert.isNotNull(callback);
if (context instanceof IModelNode) {
ILaunchConfigurationType launchConfigType = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(ILaunchTypes.ATTACH);
try {
ILaunchSelection launchSelection = new LaunchSelection(ILaunchManager.DEBUG_MODE, new RemoteSelectionContext((IModelNode)context, true));
ILaunchManagerDelegate delegate = LaunchManager.getInstance().getLaunchManagerDelegate(launchConfigType, ILaunchManager.DEBUG_MODE);
if (delegate != null) {
// create an empty launch configuration specification to initialize all attributes with their default defaults.
ILaunchSpecification launchSpec = delegate.getLaunchSpecification(launchConfigType.getIdentifier(), launchSelection);
for (String key : data.getProperties().keySet()) {
launchSpec.addAttribute(key, data.getProperty(key));
}
delegate.validate(launchSpec);
if (launchSpec != null && launchSpec.isValid()) {
ILaunchConfiguration[] launchConfigs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(launchConfigType);
launchConfigs = delegate.getMatchingLaunchConfigurations(launchSpec, launchConfigs);
ILaunchConfiguration config = launchConfigs != null && launchConfigs.length > 0 ? launchConfigs[0] : null;
boolean skip = false;
if (config != null) {
ILaunch[] launches = DebugPlugin.getDefault().getLaunchManager().getLaunches();
for (ILaunch launch : launches) {
if (launch.getLaunchConfiguration().getType().getIdentifier().equals(ILaunchTypes.ATTACH)) {
IModelNode[] contexts = LaunchContextsPersistenceDelegate.getLaunchContexts(launch.getLaunchConfiguration());
if (contexts != null && contexts.length == 1 && contexts[0].equals(context)) {
skip = true;
}
}
}
}
if (!skip) {
config = LaunchManager.getInstance().createOrUpdateLaunchConfiguration(config, launchSpec);
delegate.validate(ILaunchManager.DEBUG_MODE, config);
DebugUITools.launch(config, ILaunchManager.DEBUG_MODE);
}
}
}
callback.done(this, Status.OK_STATUS);
}
catch (Exception e) {
callback.done(this, StatusHelper.getStatus(e));
}
}
else {
callback.done(this, Status.OK_STATUS);
}
}
| protected void internalAttach(final Object context, final IPropertiesContainer data, final ICallback callback) {
Assert.isTrue(!Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(context);
Assert.isNotNull(data);
Assert.isNotNull(callback);
if (context instanceof IModelNode) {
ILaunchConfigurationType launchConfigType = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(ILaunchTypes.ATTACH);
try {
ILaunchSelection launchSelection = new LaunchSelection(ILaunchManager.DEBUG_MODE, new RemoteSelectionContext((IModelNode)context, true));
ILaunchManagerDelegate delegate = LaunchManager.getInstance().getLaunchManagerDelegate(launchConfigType, ILaunchManager.DEBUG_MODE);
if (delegate != null) {
// create an empty launch configuration specification to initialize all attributes with their default defaults.
ILaunchSpecification launchSpec = delegate.getLaunchSpecification(launchConfigType.getIdentifier(), launchSelection);
for (String key : data.getProperties().keySet()) {
launchSpec.addAttribute(key, data.getProperty(key));
}
delegate.validate(launchSpec);
if (launchSpec != null && launchSpec.isValid()) {
ILaunchConfiguration[] launchConfigs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(launchConfigType);
launchConfigs = delegate.getMatchingLaunchConfigurations(launchSpec, launchConfigs);
ILaunchConfiguration config = launchConfigs != null && launchConfigs.length > 0 ? launchConfigs[0] : null;
boolean skip = false;
if (config != null) {
ILaunch[] launches = DebugPlugin.getDefault().getLaunchManager().getLaunches();
for (ILaunch launch : launches) {
if (launch.getLaunchConfiguration().getType().getIdentifier().equals(ILaunchTypes.ATTACH) && !launch.isTerminated()) {
IModelNode[] contexts = LaunchContextsPersistenceDelegate.getLaunchContexts(launch.getLaunchConfiguration());
if (contexts != null && contexts.length == 1 && contexts[0].equals(context)) {
skip = true;
}
}
}
}
if (!skip) {
config = LaunchManager.getInstance().createOrUpdateLaunchConfiguration(config, launchSpec);
delegate.validate(ILaunchManager.DEBUG_MODE, config);
DebugUITools.launch(config, ILaunchManager.DEBUG_MODE);
}
}
}
callback.done(this, Status.OK_STATUS);
}
catch (Exception e) {
callback.done(this, StatusHelper.getStatus(e));
}
}
else {
callback.done(this, Status.OK_STATUS);
}
}
|
diff --git a/app/controllers/Jobs.java b/app/controllers/Jobs.java
index f48c2af..52dc881 100755
--- a/app/controllers/Jobs.java
+++ b/app/controllers/Jobs.java
@@ -1,427 +1,430 @@
package controllers;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipException;
import javax.management.RuntimeErrorException;
import models.Job;
import models.Notification;
import models.Setting;
import models.Upload;
import models.User;
import org.w3c.dom.Node;
import pipeline2.Pipeline2WS;
import pipeline2.Pipeline2WSResponse;
import pipeline2.models.script.Argument;
import pipeline2.models.script.arguments.*;
import pipeline2.models.Script;
import play.Logger;
import play.api.libs.json.Json;
import play.db.ebean.Transactional;
import play.libs.XPath;
import play.mvc.*;
import scala.actors.threadpool.Arrays;
public class Jobs extends Controller {
public static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Result getJobs() {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null || user.id < 0)
return redirect(routes.Login.login());
Pipeline2WSResponse jobs = pipeline2.Jobs.get(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"));
if (jobs.status != 200) {
return Application.error(jobs.status, jobs.statusName, jobs.statusDescription, jobs.asText());
}
List<Job> jobList = new ArrayList<Job>();
List<Node> jobNodes = XPath.selectNodes("//d:job", jobs.asXml(), Pipeline2WS.ns);
for (Node jobNode : jobNodes) {
Job job = Job.findById(XPath.selectText("@id", jobNode, Pipeline2WS.ns));
if (job == null) {
Logger.warn("No job with id "+XPath.selectText("@id", jobNode, Pipeline2WS.ns)+" was found.");
} else {
job.href = XPath.selectText("@href", jobNode, Pipeline2WS.ns);
job.status = XPath.selectText("@status", jobNode, Pipeline2WS.ns);
if (user.admin || user.id == job.user)
jobList.add(job);
}
}
Collections.sort(jobList);
Collections.reverse(jobList);
if (user.admin)
flash("showOwner", "true");
flash("browserId",""+new Random().nextLong());
return ok(views.html.Jobs.getJobs.render(jobList));
}
public static Result getJob(String id) {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
if (id.startsWith("guest")) {
Logger.debug(">>> guest");
Long userId = Long.parseLong("-"+id.split("-", 3)[1]);
Logger.debug(">>> "+userId);
id = id.substring(6+(userId+"").length());
Logger.debug(">>> "+id);
if (userId < 0) {
Logger.debug(">>> "+userId+" < 0");
Logger.debug("userid parameter set; logging in as given guest user");
session("userid", ""+userId);
session("name", models.Setting.get("guest.name"));
session("email", "");
session("password", "");
session("admin", "false");
}
}
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null)
return redirect(routes.Login.login());
Pipeline2WSResponse response = pipeline2.Jobs.get(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"), id, null);
if (response.status != 200 && response.status != 201) {
return Application.error(response.status, response.statusName, response.statusDescription, response.asText());
}
pipeline2.models.Job job = new pipeline2.models.Job(response.asXml());
Logger.debug(utils.XML.toString(response.asXml()));
Job webuiJob = Job.findById(job.id);
if (webuiJob == null) {
Logger.debug("Job #"+job.id+" was not found.");
return notFound("Sorry; something seems to have gone wrong. The job was not found.");
}
if (!webuiJob.user.equals(user.id))
return forbidden();
if (!Job.lastMessageSequence.containsKey(job.id) && job.messages.size() > 0) {
Collections.sort(job.messages);
Job.lastMessageSequence.put(job.id, job.messages.get(job.messages.size()-1).sequence);
}
if (!Job.lastStatus.containsKey(job.id)) {
Job.lastStatus.put(job.id, job.status);
}
flash("browserId",""+new Random().nextLong());
return ok(views.html.Jobs.getJob.render(job, webuiJob));
}
public static Result getResult(String id) {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
if (request().queryString().containsKey("userid") && request().queryString().get("userid").length > 0) {
Long userId = Long.parseLong(request().queryString().get("userid")[0]);
if (userId < 0) {
session("userid", ""+userId);
session("name", models.Setting.get("guest.name"));
session("email", "");
session("password", "");
session("admin", "false");
}
}
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null)
return redirect(routes.Login.login());
Pipeline2WSResponse result = pipeline2.Jobs.getResult(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"), id);
// TODO: check content type of incoming stream? Implement result.getContentType() ?
response().setHeader("Content-Disposition", "attachment; filename=\"result-"+id+".zip\"");
response().setContentType("application/zip");
return ok(result.asStream());
}
public static Result getLog(final String id) {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
if (request().queryString().containsKey("userid") && request().queryString().get("userid").length > 0) {
Long userId = Long.parseLong(request().queryString().get("userid")[0]);
if (userId < 0) {
session("userid", ""+userId);
session("name", models.Setting.get("guest.name"));
session("email", "");
session("password", "");
session("admin", "false");
}
}
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null)
return redirect(routes.Login.login());
Pipeline2WSResponse jobLog = pipeline2.Jobs.getLog(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"), id);
if (jobLog.status != 200 && jobLog.status != 201 && jobLog.status != 204) {
return Application.error(jobLog.status, jobLog.statusName, jobLog.statusDescription, jobLog.asText());
}
if (jobLog.status == 204) {
return ok(views.html.Jobs.emptyLog.render(id));
} else {
String[] lines = jobLog.asText().split("\n");
return ok(views.html.Jobs.getLog.render(id, Arrays.asList(lines)));
}
}
@Transactional
public static Result postJob() {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null)
return redirect(routes.Login.login());
Logger.debug("------------------------------ Posting job... ------------------------------");
Map<String, String[]> params = request().body().asFormUrlEncoded();
if (params == null) {
return Application.error(500, "Internal Server Error", "Could not read form data", request().body().asText());
}
String id = params.get("id")[0];
// Get a description of the script from Pipeline 2 Web Service
Pipeline2WSResponse scriptResponse = pipeline2.Scripts.get(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"), id);
if (scriptResponse.status != 200) { return Application.error(scriptResponse.status, scriptResponse.statusName, scriptResponse.statusDescription, scriptResponse.asText()); }
Script script = new Script(scriptResponse);
// Parse and validate the submitted form (also create any necessary output directories in case of local mode)
Scripts.ScriptForm scriptForm = new Scripts.ScriptForm(user.id, script, params);
String timeString = new Date().getTime()+"";
for (Argument arg : script.arguments) {
if ("result".equals(arg.output)) {
File href = new File(Setting.get("dp2ws.resultDir")+timeString+"/"+arg.kind+"-"+arg.name+"/");
href.mkdirs();
script.arguments.set(script.arguments.indexOf(arg), new ArgFile(arg, href.toURI().toString()));
} else if ("temp".equals(arg.output)) {
File href = new File(Setting.get("dp2ws.tempDir")+timeString+"/"+arg.kind+"-"+arg.name+"/");
href.mkdirs();
script.arguments.set(script.arguments.indexOf(arg), new ArgFile(arg, href.toURI().toString()));
}
}
scriptForm.validate();
File contextZipFile = null;
if (scriptForm.uploads.size() > 0) {
// ---------- See if there's an existing ZIP we can use as the context ----------
// models.Upload contextZipUpload = null;
// Long biggestZipSoFar = 0L;
//
// for (Long uploadId : uploads.keySet()) {
// Upload upload = uploads.get(uploadId);
// if (upload.isZip()) {
// File file = upload.getFile();
// if (file.length() > biggestZipSoFar) {
// biggestZipSoFar = file.length();
// contextZipUpload = upload;
// }
// }
// }
//
// if (contextZipUpload == null)
// Logger.debug("There's no ZIP files available to use as context");
// else
// Logger.debug("The ZIP file '"+contextZipUpload.getFile().getAbsolutePath()+"' is the biggest ZIP file available and will be used as context");
// ---------- Create a temporary directory ("the context") ----------
File contextDir = null;
try {
contextDir = File.createTempFile("jobContext", "");
if (!(contextDir.delete())) {
Logger.error("Could not delete contextDir file: " + contextDir.getAbsolutePath());
} if (!(contextDir.mkdir())) {
Logger.error("Could not create contextDir directory: " + contextDir.getAbsolutePath());
}
} catch (IOException e) {
Logger.error("Could not create temporary file (context directory): "+e.getMessage(), e);
return internalServerError("Could not create temporary file (context directory)");
}
Logger.debug("Created context directory: "+contextDir.getAbsolutePath());
// ---------- Copy or unzip all uploads to a common directory ----------
Logger.debug("number of uploads: "+scriptForm.uploads.size());
for (Long uploadId : scriptForm.uploads.keySet()) {
Upload upload = scriptForm.uploads.get(uploadId);
if (upload.isZip()) {
// if (contextZipUpload != null && contextZipUpload.id == upload.id) {
// Logger.debug("not unzipping context zip ("+upload.getFile().getAbsolutePath()+")");
// continue;
// }
Logger.debug("unzipping "+upload.getFile()+" to contextDir");
try {
utils.Files.unzip(upload.getFile(), contextDir);
} catch (IOException e) {
Logger.error("Unable to unzip files into context directory.", e);
return Application.error(500, "Internal Server Error", "Unable to unzip uploaded ZIP file", "");
}
} else {
File from = upload.getFile();
File to = new File(contextDir, from.getName());
Logger.debug("copying "+from+" to "+to);
try {
utils.Files.copy(from, to); // We could do file.renameTo here to move it instead of making a copy, but copying makes it easier in case we need to re-run a job
} catch (IOException e) {
Logger.error("Unable to copy files to context directory.", e);
throw new RuntimeErrorException(new Error(e), "Unable to copy files to context directory.");
}
}
}
if ("true".equals(Setting.get("dp2ws.sameFilesystem"))) {
Logger.debug("Running the Web UI and fwk on the same filesystem, no need to ZIP files...");
for (Argument arg : script.arguments) {
- if (arg.output != null)
+ if (arg.output != null) {
+ Logger.debug(arg.name+" is output; don't resolve URI");
continue;
+ }
if (arg instanceof ArgFile) {
+ Logger.debug(arg.name+" is file; resolve URI");
((ArgFile)arg).href = contextDir.toURI().resolve(((ArgFile)arg).href).toString();
}
if (arg instanceof ArgFiles) {
- for (String href : ((ArgFiles)arg).hrefs) {
- href = contextDir.toURI().resolve(href).toString();
+ Logger.debug(arg.name+" is files; resolve URIs");
+ List<String> hrefs = ((ArgFiles)arg).hrefs;
+ for (int i = 0; i < hrefs.size(); i++) {
+ hrefs.set(i, contextDir.toURI().resolve(hrefs.get(i)).toString());
}
}
}
} else {
// if (contextZipUpload == null) {
if (contextDir.list().length == 0) {
contextZipFile = null;
} else {
try {
contextZipFile = File.createTempFile("jobContext", ".zip");
Logger.debug("Created job context zip file: "+contextZipFile);
} catch (IOException e) {
Logger.error("Unable to create temporary job context ZIP file.", e);
throw new RuntimeErrorException(new Error(e), "Unable to create temporary job context ZIP file.");
}
try {
utils.Files.zip(contextDir, contextZipFile);
} catch (IOException e) {
Logger.error("Unable to zip context directory.", e);
throw new RuntimeErrorException(new Error(e), "Unable to zip context directory.");
}
}
// } else {
// contextZipFile = contextZipUpload.getFile();
// try {
// Logger.debug("adding contents of '"+contextDir+"' to the ZIP '"+contextZipFile+"'");
// utils.Files.addDirectoryContentsToZip(contextZipFile, contextDir);
// } catch (IOException e) {
// Logger.error("Unable to add files to existing context ZIP file.", e);
// throw new RuntimeErrorException(new Error(e), "Unable to add files to existing context ZIP file.");
// }
// }
}
}
Map<String,String> callbacks = new HashMap<String,String>();
if (play.Play.isDev()) { // TODO: only in dev until the callback API is fully implemented
callbacks.put("messages", routes.Callbacks.postCallback("messages").absoluteURL(request()));
callbacks.put("status", routes.Callbacks.postCallback("status").absoluteURL(request()));
}
if (contextZipFile == null)
Logger.debug("No files in context, submitting job without context ZIP file");
else
Logger.debug("Context ZIP file is present, submitting job with context ZIP file");
Pipeline2WSResponse job = pipeline2.Jobs.post(
Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"),
scriptForm.script.href, scriptForm.script.arguments, contextZipFile, callbacks
);
if (job.status != 200 && job.status != 201) {
return Application.error(job.status, job.statusName, job.statusDescription, job.asText());
}
String jobId = XPath.selectText("/*/@id", job.asXml(), Pipeline2WS.ns);
Job webUiJob = new Job(jobId, user);
webUiJob.nicename = id;
if (scriptForm.uploads != null && scriptForm.uploads.size() > 0) {
String filenames = "";
int i = 0;
for (Long uploadId : scriptForm.uploads.keySet()) {
if (i > 0)
filenames += ", ";
if (i++ >= 3) {
filenames += "...";
break;
}
filenames += scriptForm.uploads.get(uploadId).getFile().getName();
}
if (filenames.length() > 0)
webUiJob.nicename = id + " ("+filenames+")";
}
webUiJob.started = new Date();
webUiJob.save();
User.push(webUiJob.user, new Notification("job-started-"+webUiJob.id, webUiJob.started.toString()));
for (Long uploadId : scriptForm.uploads.keySet()) {
// associate uploads with job
scriptForm.uploads.get(uploadId).job = jobId;
scriptForm.uploads.get(uploadId).save();
}
webUiJob.pushNotifications();
if (user.id < 0) {
jobId = "guest" + user.id + "-" + jobId;
if (scriptForm.guestEmail != null) {
- Account.sendEmail(
- "Job started: "+webUiJob.nicename,
- "To view your Pipeline 2 job, go to this web address: <a href=\""+controllers.routes.Jobs.getJob(jobId).absoluteURL(request())+"\">"+controllers.routes.Jobs.getJob(jobId).absoluteURL(request())+"</a>.",
- "To view your Pipeline 2 job, go to this web address: "+controllers.routes.Jobs.getJob(jobId).absoluteURL(request())+".",
- scriptForm.guestEmail,
- scriptForm.guestEmail
- );
+ String jobUrl = routes.Jobs.getJob(jobId).absoluteURL(request());
+ String html = views.html.Account.emailJobCreated.render(jobUrl, webUiJob.nicename).body();
+ String text = "To view your Pipeline 2 job, go to this web address: " + jobUrl;
+ if (!Account.sendEmail("Job started: "+webUiJob.nicename, html, text, scriptForm.guestEmail, scriptForm.guestEmail))
+ flash("error", "Was unable to send the e-mail.");
}
}
return redirect(controllers.routes.Jobs.getJob(jobId));
}
}
| false | true | public static Result postJob() {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null)
return redirect(routes.Login.login());
Logger.debug("------------------------------ Posting job... ------------------------------");
Map<String, String[]> params = request().body().asFormUrlEncoded();
if (params == null) {
return Application.error(500, "Internal Server Error", "Could not read form data", request().body().asText());
}
String id = params.get("id")[0];
// Get a description of the script from Pipeline 2 Web Service
Pipeline2WSResponse scriptResponse = pipeline2.Scripts.get(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"), id);
if (scriptResponse.status != 200) { return Application.error(scriptResponse.status, scriptResponse.statusName, scriptResponse.statusDescription, scriptResponse.asText()); }
Script script = new Script(scriptResponse);
// Parse and validate the submitted form (also create any necessary output directories in case of local mode)
Scripts.ScriptForm scriptForm = new Scripts.ScriptForm(user.id, script, params);
String timeString = new Date().getTime()+"";
for (Argument arg : script.arguments) {
if ("result".equals(arg.output)) {
File href = new File(Setting.get("dp2ws.resultDir")+timeString+"/"+arg.kind+"-"+arg.name+"/");
href.mkdirs();
script.arguments.set(script.arguments.indexOf(arg), new ArgFile(arg, href.toURI().toString()));
} else if ("temp".equals(arg.output)) {
File href = new File(Setting.get("dp2ws.tempDir")+timeString+"/"+arg.kind+"-"+arg.name+"/");
href.mkdirs();
script.arguments.set(script.arguments.indexOf(arg), new ArgFile(arg, href.toURI().toString()));
}
}
scriptForm.validate();
File contextZipFile = null;
if (scriptForm.uploads.size() > 0) {
// ---------- See if there's an existing ZIP we can use as the context ----------
// models.Upload contextZipUpload = null;
// Long biggestZipSoFar = 0L;
//
// for (Long uploadId : uploads.keySet()) {
// Upload upload = uploads.get(uploadId);
// if (upload.isZip()) {
// File file = upload.getFile();
// if (file.length() > biggestZipSoFar) {
// biggestZipSoFar = file.length();
// contextZipUpload = upload;
// }
// }
// }
//
// if (contextZipUpload == null)
// Logger.debug("There's no ZIP files available to use as context");
// else
// Logger.debug("The ZIP file '"+contextZipUpload.getFile().getAbsolutePath()+"' is the biggest ZIP file available and will be used as context");
// ---------- Create a temporary directory ("the context") ----------
File contextDir = null;
try {
contextDir = File.createTempFile("jobContext", "");
if (!(contextDir.delete())) {
Logger.error("Could not delete contextDir file: " + contextDir.getAbsolutePath());
} if (!(contextDir.mkdir())) {
Logger.error("Could not create contextDir directory: " + contextDir.getAbsolutePath());
}
} catch (IOException e) {
Logger.error("Could not create temporary file (context directory): "+e.getMessage(), e);
return internalServerError("Could not create temporary file (context directory)");
}
Logger.debug("Created context directory: "+contextDir.getAbsolutePath());
// ---------- Copy or unzip all uploads to a common directory ----------
Logger.debug("number of uploads: "+scriptForm.uploads.size());
for (Long uploadId : scriptForm.uploads.keySet()) {
Upload upload = scriptForm.uploads.get(uploadId);
if (upload.isZip()) {
// if (contextZipUpload != null && contextZipUpload.id == upload.id) {
// Logger.debug("not unzipping context zip ("+upload.getFile().getAbsolutePath()+")");
// continue;
// }
Logger.debug("unzipping "+upload.getFile()+" to contextDir");
try {
utils.Files.unzip(upload.getFile(), contextDir);
} catch (IOException e) {
Logger.error("Unable to unzip files into context directory.", e);
return Application.error(500, "Internal Server Error", "Unable to unzip uploaded ZIP file", "");
}
} else {
File from = upload.getFile();
File to = new File(contextDir, from.getName());
Logger.debug("copying "+from+" to "+to);
try {
utils.Files.copy(from, to); // We could do file.renameTo here to move it instead of making a copy, but copying makes it easier in case we need to re-run a job
} catch (IOException e) {
Logger.error("Unable to copy files to context directory.", e);
throw new RuntimeErrorException(new Error(e), "Unable to copy files to context directory.");
}
}
}
if ("true".equals(Setting.get("dp2ws.sameFilesystem"))) {
Logger.debug("Running the Web UI and fwk on the same filesystem, no need to ZIP files...");
for (Argument arg : script.arguments) {
if (arg.output != null)
continue;
if (arg instanceof ArgFile) {
((ArgFile)arg).href = contextDir.toURI().resolve(((ArgFile)arg).href).toString();
}
if (arg instanceof ArgFiles) {
for (String href : ((ArgFiles)arg).hrefs) {
href = contextDir.toURI().resolve(href).toString();
}
}
}
} else {
// if (contextZipUpload == null) {
if (contextDir.list().length == 0) {
contextZipFile = null;
} else {
try {
contextZipFile = File.createTempFile("jobContext", ".zip");
Logger.debug("Created job context zip file: "+contextZipFile);
} catch (IOException e) {
Logger.error("Unable to create temporary job context ZIP file.", e);
throw new RuntimeErrorException(new Error(e), "Unable to create temporary job context ZIP file.");
}
try {
utils.Files.zip(contextDir, contextZipFile);
} catch (IOException e) {
Logger.error("Unable to zip context directory.", e);
throw new RuntimeErrorException(new Error(e), "Unable to zip context directory.");
}
}
// } else {
// contextZipFile = contextZipUpload.getFile();
// try {
// Logger.debug("adding contents of '"+contextDir+"' to the ZIP '"+contextZipFile+"'");
// utils.Files.addDirectoryContentsToZip(contextZipFile, contextDir);
// } catch (IOException e) {
// Logger.error("Unable to add files to existing context ZIP file.", e);
// throw new RuntimeErrorException(new Error(e), "Unable to add files to existing context ZIP file.");
// }
// }
}
}
Map<String,String> callbacks = new HashMap<String,String>();
if (play.Play.isDev()) { // TODO: only in dev until the callback API is fully implemented
callbacks.put("messages", routes.Callbacks.postCallback("messages").absoluteURL(request()));
callbacks.put("status", routes.Callbacks.postCallback("status").absoluteURL(request()));
}
if (contextZipFile == null)
Logger.debug("No files in context, submitting job without context ZIP file");
else
Logger.debug("Context ZIP file is present, submitting job with context ZIP file");
Pipeline2WSResponse job = pipeline2.Jobs.post(
Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"),
scriptForm.script.href, scriptForm.script.arguments, contextZipFile, callbacks
);
if (job.status != 200 && job.status != 201) {
return Application.error(job.status, job.statusName, job.statusDescription, job.asText());
}
String jobId = XPath.selectText("/*/@id", job.asXml(), Pipeline2WS.ns);
Job webUiJob = new Job(jobId, user);
webUiJob.nicename = id;
if (scriptForm.uploads != null && scriptForm.uploads.size() > 0) {
String filenames = "";
int i = 0;
for (Long uploadId : scriptForm.uploads.keySet()) {
if (i > 0)
filenames += ", ";
if (i++ >= 3) {
filenames += "...";
break;
}
filenames += scriptForm.uploads.get(uploadId).getFile().getName();
}
if (filenames.length() > 0)
webUiJob.nicename = id + " ("+filenames+")";
}
webUiJob.started = new Date();
webUiJob.save();
User.push(webUiJob.user, new Notification("job-started-"+webUiJob.id, webUiJob.started.toString()));
for (Long uploadId : scriptForm.uploads.keySet()) {
// associate uploads with job
scriptForm.uploads.get(uploadId).job = jobId;
scriptForm.uploads.get(uploadId).save();
}
webUiJob.pushNotifications();
if (user.id < 0) {
jobId = "guest" + user.id + "-" + jobId;
if (scriptForm.guestEmail != null) {
Account.sendEmail(
"Job started: "+webUiJob.nicename,
"To view your Pipeline 2 job, go to this web address: <a href=\""+controllers.routes.Jobs.getJob(jobId).absoluteURL(request())+"\">"+controllers.routes.Jobs.getJob(jobId).absoluteURL(request())+"</a>.",
"To view your Pipeline 2 job, go to this web address: "+controllers.routes.Jobs.getJob(jobId).absoluteURL(request())+".",
scriptForm.guestEmail,
scriptForm.guestEmail
);
}
}
return redirect(controllers.routes.Jobs.getJob(jobId));
}
| public static Result postJob() {
if (FirstUse.isFirstUse())
return redirect(routes.FirstUse.getFirstUse());
User user = User.authenticate(session("userid"), session("email"), session("password"));
if (user == null)
return redirect(routes.Login.login());
Logger.debug("------------------------------ Posting job... ------------------------------");
Map<String, String[]> params = request().body().asFormUrlEncoded();
if (params == null) {
return Application.error(500, "Internal Server Error", "Could not read form data", request().body().asText());
}
String id = params.get("id")[0];
// Get a description of the script from Pipeline 2 Web Service
Pipeline2WSResponse scriptResponse = pipeline2.Scripts.get(Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"), id);
if (scriptResponse.status != 200) { return Application.error(scriptResponse.status, scriptResponse.statusName, scriptResponse.statusDescription, scriptResponse.asText()); }
Script script = new Script(scriptResponse);
// Parse and validate the submitted form (also create any necessary output directories in case of local mode)
Scripts.ScriptForm scriptForm = new Scripts.ScriptForm(user.id, script, params);
String timeString = new Date().getTime()+"";
for (Argument arg : script.arguments) {
if ("result".equals(arg.output)) {
File href = new File(Setting.get("dp2ws.resultDir")+timeString+"/"+arg.kind+"-"+arg.name+"/");
href.mkdirs();
script.arguments.set(script.arguments.indexOf(arg), new ArgFile(arg, href.toURI().toString()));
} else if ("temp".equals(arg.output)) {
File href = new File(Setting.get("dp2ws.tempDir")+timeString+"/"+arg.kind+"-"+arg.name+"/");
href.mkdirs();
script.arguments.set(script.arguments.indexOf(arg), new ArgFile(arg, href.toURI().toString()));
}
}
scriptForm.validate();
File contextZipFile = null;
if (scriptForm.uploads.size() > 0) {
// ---------- See if there's an existing ZIP we can use as the context ----------
// models.Upload contextZipUpload = null;
// Long biggestZipSoFar = 0L;
//
// for (Long uploadId : uploads.keySet()) {
// Upload upload = uploads.get(uploadId);
// if (upload.isZip()) {
// File file = upload.getFile();
// if (file.length() > biggestZipSoFar) {
// biggestZipSoFar = file.length();
// contextZipUpload = upload;
// }
// }
// }
//
// if (contextZipUpload == null)
// Logger.debug("There's no ZIP files available to use as context");
// else
// Logger.debug("The ZIP file '"+contextZipUpload.getFile().getAbsolutePath()+"' is the biggest ZIP file available and will be used as context");
// ---------- Create a temporary directory ("the context") ----------
File contextDir = null;
try {
contextDir = File.createTempFile("jobContext", "");
if (!(contextDir.delete())) {
Logger.error("Could not delete contextDir file: " + contextDir.getAbsolutePath());
} if (!(contextDir.mkdir())) {
Logger.error("Could not create contextDir directory: " + contextDir.getAbsolutePath());
}
} catch (IOException e) {
Logger.error("Could not create temporary file (context directory): "+e.getMessage(), e);
return internalServerError("Could not create temporary file (context directory)");
}
Logger.debug("Created context directory: "+contextDir.getAbsolutePath());
// ---------- Copy or unzip all uploads to a common directory ----------
Logger.debug("number of uploads: "+scriptForm.uploads.size());
for (Long uploadId : scriptForm.uploads.keySet()) {
Upload upload = scriptForm.uploads.get(uploadId);
if (upload.isZip()) {
// if (contextZipUpload != null && contextZipUpload.id == upload.id) {
// Logger.debug("not unzipping context zip ("+upload.getFile().getAbsolutePath()+")");
// continue;
// }
Logger.debug("unzipping "+upload.getFile()+" to contextDir");
try {
utils.Files.unzip(upload.getFile(), contextDir);
} catch (IOException e) {
Logger.error("Unable to unzip files into context directory.", e);
return Application.error(500, "Internal Server Error", "Unable to unzip uploaded ZIP file", "");
}
} else {
File from = upload.getFile();
File to = new File(contextDir, from.getName());
Logger.debug("copying "+from+" to "+to);
try {
utils.Files.copy(from, to); // We could do file.renameTo here to move it instead of making a copy, but copying makes it easier in case we need to re-run a job
} catch (IOException e) {
Logger.error("Unable to copy files to context directory.", e);
throw new RuntimeErrorException(new Error(e), "Unable to copy files to context directory.");
}
}
}
if ("true".equals(Setting.get("dp2ws.sameFilesystem"))) {
Logger.debug("Running the Web UI and fwk on the same filesystem, no need to ZIP files...");
for (Argument arg : script.arguments) {
if (arg.output != null) {
Logger.debug(arg.name+" is output; don't resolve URI");
continue;
}
if (arg instanceof ArgFile) {
Logger.debug(arg.name+" is file; resolve URI");
((ArgFile)arg).href = contextDir.toURI().resolve(((ArgFile)arg).href).toString();
}
if (arg instanceof ArgFiles) {
Logger.debug(arg.name+" is files; resolve URIs");
List<String> hrefs = ((ArgFiles)arg).hrefs;
for (int i = 0; i < hrefs.size(); i++) {
hrefs.set(i, contextDir.toURI().resolve(hrefs.get(i)).toString());
}
}
}
} else {
// if (contextZipUpload == null) {
if (contextDir.list().length == 0) {
contextZipFile = null;
} else {
try {
contextZipFile = File.createTempFile("jobContext", ".zip");
Logger.debug("Created job context zip file: "+contextZipFile);
} catch (IOException e) {
Logger.error("Unable to create temporary job context ZIP file.", e);
throw new RuntimeErrorException(new Error(e), "Unable to create temporary job context ZIP file.");
}
try {
utils.Files.zip(contextDir, contextZipFile);
} catch (IOException e) {
Logger.error("Unable to zip context directory.", e);
throw new RuntimeErrorException(new Error(e), "Unable to zip context directory.");
}
}
// } else {
// contextZipFile = contextZipUpload.getFile();
// try {
// Logger.debug("adding contents of '"+contextDir+"' to the ZIP '"+contextZipFile+"'");
// utils.Files.addDirectoryContentsToZip(contextZipFile, contextDir);
// } catch (IOException e) {
// Logger.error("Unable to add files to existing context ZIP file.", e);
// throw new RuntimeErrorException(new Error(e), "Unable to add files to existing context ZIP file.");
// }
// }
}
}
Map<String,String> callbacks = new HashMap<String,String>();
if (play.Play.isDev()) { // TODO: only in dev until the callback API is fully implemented
callbacks.put("messages", routes.Callbacks.postCallback("messages").absoluteURL(request()));
callbacks.put("status", routes.Callbacks.postCallback("status").absoluteURL(request()));
}
if (contextZipFile == null)
Logger.debug("No files in context, submitting job without context ZIP file");
else
Logger.debug("Context ZIP file is present, submitting job with context ZIP file");
Pipeline2WSResponse job = pipeline2.Jobs.post(
Setting.get("dp2ws.endpoint"), Setting.get("dp2ws.authid"), Setting.get("dp2ws.secret"),
scriptForm.script.href, scriptForm.script.arguments, contextZipFile, callbacks
);
if (job.status != 200 && job.status != 201) {
return Application.error(job.status, job.statusName, job.statusDescription, job.asText());
}
String jobId = XPath.selectText("/*/@id", job.asXml(), Pipeline2WS.ns);
Job webUiJob = new Job(jobId, user);
webUiJob.nicename = id;
if (scriptForm.uploads != null && scriptForm.uploads.size() > 0) {
String filenames = "";
int i = 0;
for (Long uploadId : scriptForm.uploads.keySet()) {
if (i > 0)
filenames += ", ";
if (i++ >= 3) {
filenames += "...";
break;
}
filenames += scriptForm.uploads.get(uploadId).getFile().getName();
}
if (filenames.length() > 0)
webUiJob.nicename = id + " ("+filenames+")";
}
webUiJob.started = new Date();
webUiJob.save();
User.push(webUiJob.user, new Notification("job-started-"+webUiJob.id, webUiJob.started.toString()));
for (Long uploadId : scriptForm.uploads.keySet()) {
// associate uploads with job
scriptForm.uploads.get(uploadId).job = jobId;
scriptForm.uploads.get(uploadId).save();
}
webUiJob.pushNotifications();
if (user.id < 0) {
jobId = "guest" + user.id + "-" + jobId;
if (scriptForm.guestEmail != null) {
String jobUrl = routes.Jobs.getJob(jobId).absoluteURL(request());
String html = views.html.Account.emailJobCreated.render(jobUrl, webUiJob.nicename).body();
String text = "To view your Pipeline 2 job, go to this web address: " + jobUrl;
if (!Account.sendEmail("Job started: "+webUiJob.nicename, html, text, scriptForm.guestEmail, scriptForm.guestEmail))
flash("error", "Was unable to send the e-mail.");
}
}
return redirect(controllers.routes.Jobs.getJob(jobId));
}
|
diff --git a/src/commands/Flee.java b/src/commands/Flee.java
index 5087aa8..ef531c5 100644
--- a/src/commands/Flee.java
+++ b/src/commands/Flee.java
@@ -1,25 +1,25 @@
package commands;
import actors.Actor;
/**
* Flee.java
* @author nhydock
*
* Flee command tries to end the battle early
*/
public class Flee extends Command {
public Flee(Actor a)
{
- name = "Flee";
+ name = "Run";
}
@Override
public void execute() {
// TODO Auto-generated method stub
}
}
| true | true | public Flee(Actor a)
{
name = "Flee";
}
| public Flee(Actor a)
{
name = "Run";
}
|
diff --git a/src/net/slipcor/pvparena/managers/ConfigurationManager.java b/src/net/slipcor/pvparena/managers/ConfigurationManager.java
index 90b51797..5702ffba 100644
--- a/src/net/slipcor/pvparena/managers/ConfigurationManager.java
+++ b/src/net/slipcor/pvparena/managers/ConfigurationManager.java
@@ -1,315 +1,315 @@
package net.slipcor.pvparena.managers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.Arena;
import net.slipcor.pvparena.arena.ArenaTeam;
import net.slipcor.pvparena.commands.PAA_Edit;
import net.slipcor.pvparena.core.Config;
import net.slipcor.pvparena.core.Config.CFG;
import net.slipcor.pvparena.core.Debug;
import net.slipcor.pvparena.core.StringParser;
import net.slipcor.pvparena.loadables.ArenaGoal;
import net.slipcor.pvparena.loadables.ArenaRegionShape;
/**
* <pre>Configuration Manager class</pre>
*
* Provides static methods to manage Configurations
*
* @author slipcor
*
* @version v0.9.1
*/
public class ConfigurationManager {
private static Debug db = new Debug(25);
/**
* create a config manager instance
*
* @param arena
* the arena to load
* @param cfg
* the configuration
*/
public static void configParse(Arena arena, Config cfg) {
cfg.load();
YamlConfiguration config = cfg.getYamlConfiguration();
if (cfg.getString(CFG.GENERAL_TYPE, "null") != null && !cfg.getString(CFG.GENERAL_TYPE, "null").equals("null")) {
// opening existing arena
arena.setFree(cfg.getString(CFG.GENERAL_TYPE).equals("free"));
if (cfg.getUnsafe(CFG.MODULES_STANDARDSPECTATE_ACTIVE.getNode()) == null) {
cfg.createDefaults();
}
List<String> list = cfg.getStringList(CFG.LISTS_GOALS.getNode(), new ArrayList<String>());
for (String type : list) {
ArenaGoal aType = PVPArena.instance.getAgm().getType(type);
aType = aType.clone();
aType.setArena(arena);
arena.goalAdd(aType);
}
} else {
cfg.createDefaults();
}
if (config.get("classitems") == null) {
if (PVPArena.instance.getConfig().get("classitems") != null) {
for (String key : PVPArena.instance.getConfig().getKeys(false)) {
config.addDefault("classitems."+key, PVPArena.instance.getConfig().get("classitems."+key));
}
} else {
config.addDefault("classitems.Ranger", "261,262:64,298,299,300,301");
config.addDefault("classitems.Swordsman", "276,306,307,308,309");
config.addDefault("classitems.Tank", "272,310,311,312,313");
config.addDefault("classitems.Pyro", "259,46:3,298,299,300,301");
}
}
/*
config.addDefault("tp.win", "old");
config.addDefault("tp.lose", "old");
config.addDefault("tp.exit", "exit");
config.addDefault("tp.death", "spectator");
config.addDefault("setup.wand", Integer.valueOf(280));
config.addDefault("game.allowDrops", Boolean.valueOf(true));
config.addDefault("game.dropSpawn", Boolean.valueOf(false));
config.addDefault("game.lives", Integer.valueOf(3));
config.addDefault("game.preventDeath", Boolean.valueOf(true));
config.addDefault("game.teamKill", Boolean.valueOf(arena.isFreeForAll()));
config.addDefault("game.refillInventory", Boolean.valueOf(false));
config.addDefault("game.weaponDamage", Boolean.valueOf(true));
config.addDefault("game.mustbesafe", Boolean.valueOf(false));
config.addDefault("game.woolFlagHead", Boolean.valueOf(false));
config.addDefault("messages.language", "en");
config.addDefault("messages.chat", Boolean.valueOf(true));
config.addDefault("messages.defaultChat", Boolean.valueOf(false));
config.addDefault("messages.onlyChat", Boolean.valueOf(false));
config.addDefault("general.classperms", Boolean.valueOf(false));
config.addDefault("general.enabled", Boolean.valueOf(true));
config.addDefault("general.restoreChests", Boolean.valueOf(false));
config.addDefault("general.signs", Boolean.valueOf(true));
config.addDefault("general.type", arena.isFreeForAll()?"free":"team");
config.addDefault("general.item-rewards", "none");
config.addDefault("general.random-reward", Boolean.valueOf(false));
config.addDefault("general.prefix", "PVP Arena");
config.addDefault("general.cmdfailjoin", Boolean.valueOf(true));
config.addDefault("region.spawncampdamage", Integer.valueOf(1));
config.addDefault("region.timer", Integer.valueOf(20));
config.addDefault("join.explicitPermission", Boolean.valueOf(false));
config.addDefault("join.manual", Boolean.valueOf(!arena.isFreeForAll()));
config.addDefault("join.random", Boolean.valueOf(true));
config.addDefault("join.onCountdown", Boolean.valueOf(false));
config.addDefault("join.forceeven", Boolean.valueOf(false));
config.addDefault("join.inbattle", Boolean.valueOf(false));
config.addDefault("join.range", Integer.valueOf(0));
config.addDefault("join.warmup", Integer.valueOf(0));
config.addDefault("arenatype.randomSpawn", arena.isFreeForAll());
config.addDefault("goal.timed", Integer.valueOf(0));
config.addDefault("goal.endtimer", Integer.valueOf(20));
config.addDefault("periphery.checkRegions", Boolean.valueOf(false));
config.addDefault("protection.spawn", Integer.valueOf(3));
config.addDefault("protection.restore", Boolean.valueOf(true));
config.addDefault("protection.enabled", Boolean.valueOf(true));
config.addDefault("protection.blockplace", Boolean.valueOf(true));
config.addDefault("protection.blockdamage", Boolean.valueOf(true));
config.addDefault("protection.blocktntdamage", Boolean.valueOf(true));
config.addDefault("protection.decay", Boolean.valueOf(true));
config.addDefault("protection.drop", Boolean.valueOf(true));
config.addDefault("protection.fade", Boolean.valueOf(true));
config.addDefault("protection.form", Boolean.valueOf(true));
config.addDefault("protection.fluids", Boolean.valueOf(true));
config.addDefault("protection.firespread", Boolean.valueOf(true));
config.addDefault("protection.grow", Boolean.valueOf(true));
config.addDefault("protection.lavafirespread", Boolean.valueOf(true));
config.addDefault("protection.lighter", Boolean.valueOf(true));
config.addDefault("protection.painting", Boolean.valueOf(true));
config.addDefault("protection.piston", Boolean.valueOf(true));
config.addDefault("protection.punish", Boolean.valueOf(false));
config.addDefault("protection.tnt", Boolean.valueOf(true));
config.addDefault("protection.checkExit", Boolean.valueOf(false));
config.addDefault("protection.checkSpectator", Boolean.valueOf(false));
config.addDefault("protection.checkLounges", Boolean.valueOf(false));
config.addDefault("protection.inventory", Boolean.valueOf(false));
config.addDefault("delays.giveitems", Integer.valueOf(0));
config.addDefault("delays.inventorysave", Integer.valueOf(0));
config.addDefault("delays.inventoryprepare", Integer.valueOf(0));
config.addDefault("delays.playerdestroy", Integer.valueOf(0));
config.addDefault("start.countdown", Integer.valueOf(5));
config.addDefault("start.health", Integer.valueOf(20));
config.addDefault("start.foodLevel", Integer.valueOf(20));
config.addDefault("start.saturation", Integer.valueOf(20));
config.addDefault("start.exhaustion", Float.valueOf(0));
config.addDefault("ready.startRatio", Float.valueOf((float) 0.5));
config.addDefault("ready.block", "IRON_BLOCK");
config.addDefault("ready.checkEach", Boolean.valueOf(true));
config.addDefault("ready.checkEachTeam", Boolean.valueOf(true));
config.addDefault("ready.min", Integer.valueOf(2));
config.addDefault("ready.max", Integer.valueOf(0));
config.addDefault("ready.minTeam", Integer.valueOf(1));
config.addDefault("ready.maxTeam", Integer.valueOf(0));
config.addDefault("ready.autoclass", "none");
config.addDefault("ready.startRatio", Float.valueOf((float) 0.5));
config.addDefault("lang.youjoin", "Welcome to the Arena!");
config.addDefault("lang.playerjoin", "Player %1% joined team %2%");
*/
PVPArena.instance.getAgm().setDefaults(arena, config);
config.options().copyDefaults(true);
cfg.set(CFG.Z, "0.9.0.65");
cfg.save();
cfg.load();
Map<String, Object> classes = config.getConfigurationSection(
"classitems").getValues(false);
arena.getClasses().clear();
db.i("reading class items");
for (String className : classes.keySet()) {
String s = "";
try {
s = (String) classes.get(className);
} catch (Exception e) {
Bukkit.getLogger().severe("[PVP Arena] Error while parsing class, skipping: " + className);
continue;
}
String[] ss = s.split(",");
ItemStack[] items = new ItemStack[ss.length];
for (int i = 0; i < ss.length; i++) {
items[i] = StringParser.getItemStackFromString(ss[i]);
if (items[i] == null) {
db.w("unrecognized item: " + items[i]);
}
}
arena.addClass(className, items);
db.i("adding class items to class " + className);
}
arena.addClass("custom", StringParser.getItemStacksFromString("0"));
arena.setOwner(cfg.getString(CFG.GENERAL_OWNER));
- arena.setLocked(cfg.getString(CFG.GENERAL_ENABLED).equalsIgnoreCase("false"));
+ arena.setLocked(!cfg.getBoolean(CFG.GENERAL_ENABLED));
if (config.getConfigurationSection("arenaregion") != null) {
Map<String, Object> regs = config
.getConfigurationSection("arenaregion").getValues(false);
for (String rName : regs.keySet()) {
ArenaRegionShape region = Config.parseRegion(arena, config, rName);
if (region == null) {
PVPArena.instance.getLogger().severe("Error while loading arena, region null: " + rName);
} else if (region.getWorld() == null) {
PVPArena.instance.getLogger().severe("Error while loading arena, world null: " + rName);
} else {
arena.getRegions().add(region);
}
}
}
arena.setRoundMap(null);
cfg.save();
PVPArena.instance.getAgm().configParse(arena, config);
PVPArena.instance.getAmm().configParse(arena, config);
if (cfg.getYamlConfiguration().getConfigurationSection("teams") == null) {
if (arena.isFreeForAll()) {
config.set("teams.free", "WHITE");
} else {
config.set("teams.red", "RED");
config.set("teams.blue", "BLUE");
}
}
cfg.reloadMaps();
Map<String, Object> tempMap = (Map<String, Object>) cfg
.getYamlConfiguration().getConfigurationSection("teams")
.getValues(true);
if (arena.isFreeForAll()) {
arena.getTeams().add(new ArenaTeam("free", "WHITE"));
arena.getArenaConfig().set(CFG.PERMS_TEAMKILL, true);
arena.getArenaConfig().save();
} else {
for (String sTeam : tempMap.keySet()) {
ArenaTeam team = new ArenaTeam(sTeam, (String) tempMap.get(sTeam));
arena.getTeams().add(team);
db.i("added team " + team.getName() + " => "
+ team.getColorCodeString());
}
}
arena.setPrefix(cfg.getString(CFG.GENERAL_PREFIX));
}
/**
* check if an arena is configured completely
*
* @param arena
* the arena to check
* @return an error string if there is something missing, null otherwise
*/
public static String isSetup(Arena arena) {
arena.getArenaConfig().load();
if (arena.getArenaConfig().getUnsafe("spawns") == null) {
return "no spawns set";
}
if (PAA_Edit.activeEdits.containsValue(arena)) {
return "edit mode!";
}
Set<String> list = arena.getArenaConfig().getYamlConfiguration()
.getConfigurationSection("spawns").getValues(false).keySet();
String sExit = arena.getArenaConfig().getString(CFG.TP_EXIT);
if (!sExit.equals("old") && !list.contains(sExit))
return "Exit Spawn ('"+sExit+"') not set!";
String sWin = arena.getArenaConfig().getString(CFG.TP_WIN);
if (!sWin.equals("old") && !list.contains(sWin))
return "Win Spawn ('"+sWin+"') not set!";
String sLose = arena.getArenaConfig().getString(CFG.TP_LOSE);
if (!sLose.equals("old") && !list.contains(sLose))
return "Lose Spawn ('"+sLose+"') not set!";
String sDeath = arena.getArenaConfig().getString(CFG.TP_DEATH);
if (!sDeath.equals("old") && !list.contains(sDeath))
return "Death Spawn ('"+sDeath+"') not set!";
String error = PVPArena.instance.getAmm().checkForMissingSpawns(arena, list);
if (error != null) {
return error;
}
return PVPArena.instance.getAgm().checkForMissingSpawns(arena, list);
}
}
| true | true | public static void configParse(Arena arena, Config cfg) {
cfg.load();
YamlConfiguration config = cfg.getYamlConfiguration();
if (cfg.getString(CFG.GENERAL_TYPE, "null") != null && !cfg.getString(CFG.GENERAL_TYPE, "null").equals("null")) {
// opening existing arena
arena.setFree(cfg.getString(CFG.GENERAL_TYPE).equals("free"));
if (cfg.getUnsafe(CFG.MODULES_STANDARDSPECTATE_ACTIVE.getNode()) == null) {
cfg.createDefaults();
}
List<String> list = cfg.getStringList(CFG.LISTS_GOALS.getNode(), new ArrayList<String>());
for (String type : list) {
ArenaGoal aType = PVPArena.instance.getAgm().getType(type);
aType = aType.clone();
aType.setArena(arena);
arena.goalAdd(aType);
}
} else {
cfg.createDefaults();
}
if (config.get("classitems") == null) {
if (PVPArena.instance.getConfig().get("classitems") != null) {
for (String key : PVPArena.instance.getConfig().getKeys(false)) {
config.addDefault("classitems."+key, PVPArena.instance.getConfig().get("classitems."+key));
}
} else {
config.addDefault("classitems.Ranger", "261,262:64,298,299,300,301");
config.addDefault("classitems.Swordsman", "276,306,307,308,309");
config.addDefault("classitems.Tank", "272,310,311,312,313");
config.addDefault("classitems.Pyro", "259,46:3,298,299,300,301");
}
}
/*
config.addDefault("tp.win", "old");
config.addDefault("tp.lose", "old");
config.addDefault("tp.exit", "exit");
config.addDefault("tp.death", "spectator");
config.addDefault("setup.wand", Integer.valueOf(280));
config.addDefault("game.allowDrops", Boolean.valueOf(true));
config.addDefault("game.dropSpawn", Boolean.valueOf(false));
config.addDefault("game.lives", Integer.valueOf(3));
config.addDefault("game.preventDeath", Boolean.valueOf(true));
config.addDefault("game.teamKill", Boolean.valueOf(arena.isFreeForAll()));
config.addDefault("game.refillInventory", Boolean.valueOf(false));
config.addDefault("game.weaponDamage", Boolean.valueOf(true));
config.addDefault("game.mustbesafe", Boolean.valueOf(false));
config.addDefault("game.woolFlagHead", Boolean.valueOf(false));
config.addDefault("messages.language", "en");
config.addDefault("messages.chat", Boolean.valueOf(true));
config.addDefault("messages.defaultChat", Boolean.valueOf(false));
config.addDefault("messages.onlyChat", Boolean.valueOf(false));
config.addDefault("general.classperms", Boolean.valueOf(false));
config.addDefault("general.enabled", Boolean.valueOf(true));
config.addDefault("general.restoreChests", Boolean.valueOf(false));
config.addDefault("general.signs", Boolean.valueOf(true));
config.addDefault("general.type", arena.isFreeForAll()?"free":"team");
config.addDefault("general.item-rewards", "none");
config.addDefault("general.random-reward", Boolean.valueOf(false));
config.addDefault("general.prefix", "PVP Arena");
config.addDefault("general.cmdfailjoin", Boolean.valueOf(true));
config.addDefault("region.spawncampdamage", Integer.valueOf(1));
config.addDefault("region.timer", Integer.valueOf(20));
config.addDefault("join.explicitPermission", Boolean.valueOf(false));
config.addDefault("join.manual", Boolean.valueOf(!arena.isFreeForAll()));
config.addDefault("join.random", Boolean.valueOf(true));
config.addDefault("join.onCountdown", Boolean.valueOf(false));
config.addDefault("join.forceeven", Boolean.valueOf(false));
config.addDefault("join.inbattle", Boolean.valueOf(false));
config.addDefault("join.range", Integer.valueOf(0));
config.addDefault("join.warmup", Integer.valueOf(0));
config.addDefault("arenatype.randomSpawn", arena.isFreeForAll());
config.addDefault("goal.timed", Integer.valueOf(0));
config.addDefault("goal.endtimer", Integer.valueOf(20));
config.addDefault("periphery.checkRegions", Boolean.valueOf(false));
config.addDefault("protection.spawn", Integer.valueOf(3));
config.addDefault("protection.restore", Boolean.valueOf(true));
config.addDefault("protection.enabled", Boolean.valueOf(true));
config.addDefault("protection.blockplace", Boolean.valueOf(true));
config.addDefault("protection.blockdamage", Boolean.valueOf(true));
config.addDefault("protection.blocktntdamage", Boolean.valueOf(true));
config.addDefault("protection.decay", Boolean.valueOf(true));
config.addDefault("protection.drop", Boolean.valueOf(true));
config.addDefault("protection.fade", Boolean.valueOf(true));
config.addDefault("protection.form", Boolean.valueOf(true));
config.addDefault("protection.fluids", Boolean.valueOf(true));
config.addDefault("protection.firespread", Boolean.valueOf(true));
config.addDefault("protection.grow", Boolean.valueOf(true));
config.addDefault("protection.lavafirespread", Boolean.valueOf(true));
config.addDefault("protection.lighter", Boolean.valueOf(true));
config.addDefault("protection.painting", Boolean.valueOf(true));
config.addDefault("protection.piston", Boolean.valueOf(true));
config.addDefault("protection.punish", Boolean.valueOf(false));
config.addDefault("protection.tnt", Boolean.valueOf(true));
config.addDefault("protection.checkExit", Boolean.valueOf(false));
config.addDefault("protection.checkSpectator", Boolean.valueOf(false));
config.addDefault("protection.checkLounges", Boolean.valueOf(false));
config.addDefault("protection.inventory", Boolean.valueOf(false));
config.addDefault("delays.giveitems", Integer.valueOf(0));
config.addDefault("delays.inventorysave", Integer.valueOf(0));
config.addDefault("delays.inventoryprepare", Integer.valueOf(0));
config.addDefault("delays.playerdestroy", Integer.valueOf(0));
config.addDefault("start.countdown", Integer.valueOf(5));
config.addDefault("start.health", Integer.valueOf(20));
config.addDefault("start.foodLevel", Integer.valueOf(20));
config.addDefault("start.saturation", Integer.valueOf(20));
config.addDefault("start.exhaustion", Float.valueOf(0));
config.addDefault("ready.startRatio", Float.valueOf((float) 0.5));
config.addDefault("ready.block", "IRON_BLOCK");
config.addDefault("ready.checkEach", Boolean.valueOf(true));
config.addDefault("ready.checkEachTeam", Boolean.valueOf(true));
config.addDefault("ready.min", Integer.valueOf(2));
config.addDefault("ready.max", Integer.valueOf(0));
config.addDefault("ready.minTeam", Integer.valueOf(1));
config.addDefault("ready.maxTeam", Integer.valueOf(0));
config.addDefault("ready.autoclass", "none");
config.addDefault("ready.startRatio", Float.valueOf((float) 0.5));
config.addDefault("lang.youjoin", "Welcome to the Arena!");
config.addDefault("lang.playerjoin", "Player %1% joined team %2%");
*/
PVPArena.instance.getAgm().setDefaults(arena, config);
config.options().copyDefaults(true);
cfg.set(CFG.Z, "0.9.0.65");
cfg.save();
cfg.load();
Map<String, Object> classes = config.getConfigurationSection(
"classitems").getValues(false);
arena.getClasses().clear();
db.i("reading class items");
for (String className : classes.keySet()) {
String s = "";
try {
s = (String) classes.get(className);
} catch (Exception e) {
Bukkit.getLogger().severe("[PVP Arena] Error while parsing class, skipping: " + className);
continue;
}
String[] ss = s.split(",");
ItemStack[] items = new ItemStack[ss.length];
for (int i = 0; i < ss.length; i++) {
items[i] = StringParser.getItemStackFromString(ss[i]);
if (items[i] == null) {
db.w("unrecognized item: " + items[i]);
}
}
arena.addClass(className, items);
db.i("adding class items to class " + className);
}
arena.addClass("custom", StringParser.getItemStacksFromString("0"));
arena.setOwner(cfg.getString(CFG.GENERAL_OWNER));
arena.setLocked(cfg.getString(CFG.GENERAL_ENABLED).equalsIgnoreCase("false"));
if (config.getConfigurationSection("arenaregion") != null) {
Map<String, Object> regs = config
.getConfigurationSection("arenaregion").getValues(false);
for (String rName : regs.keySet()) {
ArenaRegionShape region = Config.parseRegion(arena, config, rName);
if (region == null) {
PVPArena.instance.getLogger().severe("Error while loading arena, region null: " + rName);
} else if (region.getWorld() == null) {
PVPArena.instance.getLogger().severe("Error while loading arena, world null: " + rName);
} else {
arena.getRegions().add(region);
}
}
}
arena.setRoundMap(null);
cfg.save();
PVPArena.instance.getAgm().configParse(arena, config);
PVPArena.instance.getAmm().configParse(arena, config);
if (cfg.getYamlConfiguration().getConfigurationSection("teams") == null) {
if (arena.isFreeForAll()) {
config.set("teams.free", "WHITE");
} else {
config.set("teams.red", "RED");
config.set("teams.blue", "BLUE");
}
}
cfg.reloadMaps();
Map<String, Object> tempMap = (Map<String, Object>) cfg
.getYamlConfiguration().getConfigurationSection("teams")
.getValues(true);
if (arena.isFreeForAll()) {
arena.getTeams().add(new ArenaTeam("free", "WHITE"));
arena.getArenaConfig().set(CFG.PERMS_TEAMKILL, true);
arena.getArenaConfig().save();
} else {
for (String sTeam : tempMap.keySet()) {
ArenaTeam team = new ArenaTeam(sTeam, (String) tempMap.get(sTeam));
arena.getTeams().add(team);
db.i("added team " + team.getName() + " => "
+ team.getColorCodeString());
}
}
arena.setPrefix(cfg.getString(CFG.GENERAL_PREFIX));
}
| public static void configParse(Arena arena, Config cfg) {
cfg.load();
YamlConfiguration config = cfg.getYamlConfiguration();
if (cfg.getString(CFG.GENERAL_TYPE, "null") != null && !cfg.getString(CFG.GENERAL_TYPE, "null").equals("null")) {
// opening existing arena
arena.setFree(cfg.getString(CFG.GENERAL_TYPE).equals("free"));
if (cfg.getUnsafe(CFG.MODULES_STANDARDSPECTATE_ACTIVE.getNode()) == null) {
cfg.createDefaults();
}
List<String> list = cfg.getStringList(CFG.LISTS_GOALS.getNode(), new ArrayList<String>());
for (String type : list) {
ArenaGoal aType = PVPArena.instance.getAgm().getType(type);
aType = aType.clone();
aType.setArena(arena);
arena.goalAdd(aType);
}
} else {
cfg.createDefaults();
}
if (config.get("classitems") == null) {
if (PVPArena.instance.getConfig().get("classitems") != null) {
for (String key : PVPArena.instance.getConfig().getKeys(false)) {
config.addDefault("classitems."+key, PVPArena.instance.getConfig().get("classitems."+key));
}
} else {
config.addDefault("classitems.Ranger", "261,262:64,298,299,300,301");
config.addDefault("classitems.Swordsman", "276,306,307,308,309");
config.addDefault("classitems.Tank", "272,310,311,312,313");
config.addDefault("classitems.Pyro", "259,46:3,298,299,300,301");
}
}
/*
config.addDefault("tp.win", "old");
config.addDefault("tp.lose", "old");
config.addDefault("tp.exit", "exit");
config.addDefault("tp.death", "spectator");
config.addDefault("setup.wand", Integer.valueOf(280));
config.addDefault("game.allowDrops", Boolean.valueOf(true));
config.addDefault("game.dropSpawn", Boolean.valueOf(false));
config.addDefault("game.lives", Integer.valueOf(3));
config.addDefault("game.preventDeath", Boolean.valueOf(true));
config.addDefault("game.teamKill", Boolean.valueOf(arena.isFreeForAll()));
config.addDefault("game.refillInventory", Boolean.valueOf(false));
config.addDefault("game.weaponDamage", Boolean.valueOf(true));
config.addDefault("game.mustbesafe", Boolean.valueOf(false));
config.addDefault("game.woolFlagHead", Boolean.valueOf(false));
config.addDefault("messages.language", "en");
config.addDefault("messages.chat", Boolean.valueOf(true));
config.addDefault("messages.defaultChat", Boolean.valueOf(false));
config.addDefault("messages.onlyChat", Boolean.valueOf(false));
config.addDefault("general.classperms", Boolean.valueOf(false));
config.addDefault("general.enabled", Boolean.valueOf(true));
config.addDefault("general.restoreChests", Boolean.valueOf(false));
config.addDefault("general.signs", Boolean.valueOf(true));
config.addDefault("general.type", arena.isFreeForAll()?"free":"team");
config.addDefault("general.item-rewards", "none");
config.addDefault("general.random-reward", Boolean.valueOf(false));
config.addDefault("general.prefix", "PVP Arena");
config.addDefault("general.cmdfailjoin", Boolean.valueOf(true));
config.addDefault("region.spawncampdamage", Integer.valueOf(1));
config.addDefault("region.timer", Integer.valueOf(20));
config.addDefault("join.explicitPermission", Boolean.valueOf(false));
config.addDefault("join.manual", Boolean.valueOf(!arena.isFreeForAll()));
config.addDefault("join.random", Boolean.valueOf(true));
config.addDefault("join.onCountdown", Boolean.valueOf(false));
config.addDefault("join.forceeven", Boolean.valueOf(false));
config.addDefault("join.inbattle", Boolean.valueOf(false));
config.addDefault("join.range", Integer.valueOf(0));
config.addDefault("join.warmup", Integer.valueOf(0));
config.addDefault("arenatype.randomSpawn", arena.isFreeForAll());
config.addDefault("goal.timed", Integer.valueOf(0));
config.addDefault("goal.endtimer", Integer.valueOf(20));
config.addDefault("periphery.checkRegions", Boolean.valueOf(false));
config.addDefault("protection.spawn", Integer.valueOf(3));
config.addDefault("protection.restore", Boolean.valueOf(true));
config.addDefault("protection.enabled", Boolean.valueOf(true));
config.addDefault("protection.blockplace", Boolean.valueOf(true));
config.addDefault("protection.blockdamage", Boolean.valueOf(true));
config.addDefault("protection.blocktntdamage", Boolean.valueOf(true));
config.addDefault("protection.decay", Boolean.valueOf(true));
config.addDefault("protection.drop", Boolean.valueOf(true));
config.addDefault("protection.fade", Boolean.valueOf(true));
config.addDefault("protection.form", Boolean.valueOf(true));
config.addDefault("protection.fluids", Boolean.valueOf(true));
config.addDefault("protection.firespread", Boolean.valueOf(true));
config.addDefault("protection.grow", Boolean.valueOf(true));
config.addDefault("protection.lavafirespread", Boolean.valueOf(true));
config.addDefault("protection.lighter", Boolean.valueOf(true));
config.addDefault("protection.painting", Boolean.valueOf(true));
config.addDefault("protection.piston", Boolean.valueOf(true));
config.addDefault("protection.punish", Boolean.valueOf(false));
config.addDefault("protection.tnt", Boolean.valueOf(true));
config.addDefault("protection.checkExit", Boolean.valueOf(false));
config.addDefault("protection.checkSpectator", Boolean.valueOf(false));
config.addDefault("protection.checkLounges", Boolean.valueOf(false));
config.addDefault("protection.inventory", Boolean.valueOf(false));
config.addDefault("delays.giveitems", Integer.valueOf(0));
config.addDefault("delays.inventorysave", Integer.valueOf(0));
config.addDefault("delays.inventoryprepare", Integer.valueOf(0));
config.addDefault("delays.playerdestroy", Integer.valueOf(0));
config.addDefault("start.countdown", Integer.valueOf(5));
config.addDefault("start.health", Integer.valueOf(20));
config.addDefault("start.foodLevel", Integer.valueOf(20));
config.addDefault("start.saturation", Integer.valueOf(20));
config.addDefault("start.exhaustion", Float.valueOf(0));
config.addDefault("ready.startRatio", Float.valueOf((float) 0.5));
config.addDefault("ready.block", "IRON_BLOCK");
config.addDefault("ready.checkEach", Boolean.valueOf(true));
config.addDefault("ready.checkEachTeam", Boolean.valueOf(true));
config.addDefault("ready.min", Integer.valueOf(2));
config.addDefault("ready.max", Integer.valueOf(0));
config.addDefault("ready.minTeam", Integer.valueOf(1));
config.addDefault("ready.maxTeam", Integer.valueOf(0));
config.addDefault("ready.autoclass", "none");
config.addDefault("ready.startRatio", Float.valueOf((float) 0.5));
config.addDefault("lang.youjoin", "Welcome to the Arena!");
config.addDefault("lang.playerjoin", "Player %1% joined team %2%");
*/
PVPArena.instance.getAgm().setDefaults(arena, config);
config.options().copyDefaults(true);
cfg.set(CFG.Z, "0.9.0.65");
cfg.save();
cfg.load();
Map<String, Object> classes = config.getConfigurationSection(
"classitems").getValues(false);
arena.getClasses().clear();
db.i("reading class items");
for (String className : classes.keySet()) {
String s = "";
try {
s = (String) classes.get(className);
} catch (Exception e) {
Bukkit.getLogger().severe("[PVP Arena] Error while parsing class, skipping: " + className);
continue;
}
String[] ss = s.split(",");
ItemStack[] items = new ItemStack[ss.length];
for (int i = 0; i < ss.length; i++) {
items[i] = StringParser.getItemStackFromString(ss[i]);
if (items[i] == null) {
db.w("unrecognized item: " + items[i]);
}
}
arena.addClass(className, items);
db.i("adding class items to class " + className);
}
arena.addClass("custom", StringParser.getItemStacksFromString("0"));
arena.setOwner(cfg.getString(CFG.GENERAL_OWNER));
arena.setLocked(!cfg.getBoolean(CFG.GENERAL_ENABLED));
if (config.getConfigurationSection("arenaregion") != null) {
Map<String, Object> regs = config
.getConfigurationSection("arenaregion").getValues(false);
for (String rName : regs.keySet()) {
ArenaRegionShape region = Config.parseRegion(arena, config, rName);
if (region == null) {
PVPArena.instance.getLogger().severe("Error while loading arena, region null: " + rName);
} else if (region.getWorld() == null) {
PVPArena.instance.getLogger().severe("Error while loading arena, world null: " + rName);
} else {
arena.getRegions().add(region);
}
}
}
arena.setRoundMap(null);
cfg.save();
PVPArena.instance.getAgm().configParse(arena, config);
PVPArena.instance.getAmm().configParse(arena, config);
if (cfg.getYamlConfiguration().getConfigurationSection("teams") == null) {
if (arena.isFreeForAll()) {
config.set("teams.free", "WHITE");
} else {
config.set("teams.red", "RED");
config.set("teams.blue", "BLUE");
}
}
cfg.reloadMaps();
Map<String, Object> tempMap = (Map<String, Object>) cfg
.getYamlConfiguration().getConfigurationSection("teams")
.getValues(true);
if (arena.isFreeForAll()) {
arena.getTeams().add(new ArenaTeam("free", "WHITE"));
arena.getArenaConfig().set(CFG.PERMS_TEAMKILL, true);
arena.getArenaConfig().save();
} else {
for (String sTeam : tempMap.keySet()) {
ArenaTeam team = new ArenaTeam(sTeam, (String) tempMap.get(sTeam));
arena.getTeams().add(team);
db.i("added team " + team.getName() + " => "
+ team.getColorCodeString());
}
}
arena.setPrefix(cfg.getString(CFG.GENERAL_PREFIX));
}
|
diff --git a/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java b/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java
index ca95820d..28587f8b 100644
--- a/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java
+++ b/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java
@@ -1,749 +1,750 @@
/*
Copyright (C) 2010 Haowen Ning
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 org.liberty.android.fantastischmemo.cardscreen;
import org.liberty.android.fantastischmemo.*;
import org.liberty.android.fantastischmemo.tts.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Date;
import java.util.List;
import android.graphics.Color;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.os.Environment;
import android.content.Context;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ContextMenu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Display;
import android.view.WindowManager;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageButton;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import android.os.SystemClock;
import android.net.Uri;
import android.database.SQLException;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
public class EditScreen extends AMActivity{
private final static String TAG = "org.liberty.android.fantastischmemo.cardscreen.EditScreen";
private AnyMemoTTS questionTTS = null;
private AnyMemoTTS answerTTS = null;
private boolean searchInflated = false;
private final int DIALOG_LOADING_PROGRESS = 100;
private final int ACTIVITY_FILTER = 10;
private final int ACTIVITY_EDIT = 11;
private final int ACTIVITY_CARD_TOOLBOX = 12;
private final int ACTIVITY_DB_TOOLBOX = 13;
private final int ACTIVITY_GOTO_PREV = 14;
private final int ACTIVITY_SETTINGS = 15;
private final int ACTIVITY_LIST = 16;
private final int ACTIVITY_MERGE = 17;
private final int ACTIVITY_DETAIL = 18;
private final static String WEBSITE_HELP_EDIT = "http://anymemo.org/wiki/index.php?title=Editing_screen";
Handler mHandler;
Item currentItem = null;
Item savedItem = null;
Item prevItem = null;
String dbPath = "";
String dbName = "";
String activeFilter = "";
FlashcardDisplay flashcardDisplay;
SettingManager settingManager;
ControlButtons controlButtons;
DatabaseUtility databaseUtility;
private GestureDetector gestureDetector;
ItemManager itemManager;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.memo_screen_layout);
mHandler = new Handler();
Bundle extras = getIntent().getExtras();
int currentId = 1;
if (extras != null) {
dbPath = extras.getString("dbpath");
dbName = extras.getString("dbname");
activeFilter = extras.getString("filter");
currentId = extras.getInt("id", 1);
}
try{
settingManager = new SettingManager(this, dbPath, dbName);
if(settingManager.getCardStyle() == SettingManager.CardStyle.DOUBLE_SIDED){
flashcardDisplay = new DoubleSidedCardDisplay(this, settingManager);
}
else{
flashcardDisplay = new SingleSidedCardDisplay(this, settingManager);
}
controlButtons = new EditScreenButtons(this);
/* databaseUtility is for global db operations */
databaseUtility = new DatabaseUtility(this, dbPath, dbName);
itemManager = new ItemManager.Builder(this, dbPath, dbName)
.setFilter(activeFilter)
.build();
initTTS();
composeViews();
currentItem = itemManager.getItem(currentId);
if(currentItem == null){
itemManager.getItem(1);
}
updateCardFrontSide();
updateTitle();
setViewListeners();
/* Double sided card can't use the flip gesture*/
if(settingManager.getCardStyle() != SettingManager.CardStyle.DOUBLE_SIDED){
gestureDetector= new GestureDetector(EditScreen.this, gestureListener);
flashcardDisplay.setScreenOnTouchListener(viewTouchListener);
}
registerForContextMenu(flashcardDisplay.getView());
}
catch(Exception e){
Log.e(TAG, "Error in the onCreate()", e);
AMGUIUtility.displayError(this, getString(R.string.open_database_error_title), getString(R.string.open_database_error_message), e);
}
/*
* Currently always set the result to OK
* to assume there are always some changes.
* This may be changed in the future to reflect the
* real changes
*/
setResult(Activity.RESULT_OK);
}
@Override
public void onDestroy(){
if(itemManager != null){
itemManager.close();
}
if(settingManager != null){
settingManager.close();
}
if(questionTTS != null){
questionTTS.shutdown();
}
if(answerTTS != null){
answerTTS.shutdown();
}
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode ==Activity.RESULT_CANCELED){
return;
}
/* Refresh the activity according to activities */
switch(requestCode){
case ACTIVITY_EDIT:
{
Bundle extras = data.getExtras();
Item item = extras.getParcelable("item");
if(item != null){
currentItem = item;
}
restartActivity();
break;
}
case ACTIVITY_FILTER:
{
Bundle extras = data.getExtras();
activeFilter = extras.getString("filter");
restartActivity();
break;
}
case ACTIVITY_SETTINGS:
{
restartActivity();
break;
}
case ACTIVITY_LIST:
{
Bundle extras = data.getExtras();
currentItem = extras.getParcelable("item");
restartActivity();
break;
}
case ACTIVITY_MERGE:
{
restartActivity();
break;
}
case ACTIVITY_DETAIL:
{
restartActivity();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_screen_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuspeakquestion:
{
if(questionTTS != null && currentItem != null){
questionTTS.sayText(currentItem.getQuestion());
}
return true;
}
case R.id.menuspeakanswer:
{
if(answerTTS != null && currentItem != null){
answerTTS.sayText(currentItem.getAnswer());
}
return true;
}
case R.id.editmenu_settings_id:
{
Intent myIntent = new Intent(this, SettingsScreen.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
startActivityForResult(myIntent, ACTIVITY_SETTINGS);
return true;
}
case R.id.editmenu_delete_id:
{
deleteCurrent();
return true;
}
case R.id.editmenu_detail_id:
{
if(currentItem != null){
Intent myIntent = new Intent(this, DetailScreen.class);
myIntent.putExtra("dbname", this.dbName);
myIntent.putExtra("dbpath", this.dbPath);
myIntent.putExtra("itemid", currentItem.getId());
startActivityForResult(myIntent, ACTIVITY_DETAIL);
}
return true;
}
case R.id.editmenu_list_id:
{
Intent myIntent = new Intent(this, SettingsScreen.class);
myIntent.setClass(this, ListEditScreen.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
if(currentItem != null){
myIntent.putExtra("openid", currentItem.getId());
}
startActivityForResult(myIntent, ACTIVITY_LIST);
return true;
}
case R.id.menu_edit_filter:
{
Intent myIntent = new Intent(this, Filter.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
startActivityForResult(myIntent, ACTIVITY_FILTER);
return true;
}
case R.id.editmenu_search_id:
{
createSearchOverlay();
+ return true;
}
case R.id.editmenu_help:
{
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.addCategory(Intent.CATEGORY_BROWSABLE);
myIntent.setData(Uri.parse(WEBSITE_HELP_EDIT));
startActivity(myIntent);
return true;
}
}
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.editscreen_context_menu, menu);
menu.setHeaderTitle(R.string.menu_text);
}
@Override
public boolean onContextItemSelected(MenuItem menuitem) {
switch(menuitem.getItemId()) {
case R.id.menu_context_copy:
{
if(currentItem != null){
savedItem = new Item.Builder()
.setId(currentItem.getId())
.setQuestion(currentItem.getQuestion())
.setAnswer(currentItem.getAnswer())
.setCategory(currentItem.getCategory())
.build();
}
return true;
}
case R.id.menu_context_paste:
{
if(savedItem != null){
itemManager.insert(savedItem, currentItem.getId());
/* Set the Id to the current one */
currentItem = new Item.Builder(savedItem)
.setId(currentItem.getId() + 1)
.build();
updateCardFrontSide();
updateTitle();
}
return true;
}
case R.id.menu_context_swap_current:
{
if(currentItem != null){
databaseUtility.swapSingelItem(currentItem);
}
return true;
}
case R.id.menu_context_reset_current:
{
if(currentItem != null){
databaseUtility.resetCurrentLearningData(currentItem);
}
return true;
}
case R.id.menu_context_wipe:
{
databaseUtility.wipeLearningData();
return true;
}
case R.id.menu_context_swap:
{
databaseUtility.swapAllQA();
return true;
}
case R.id.menu_context_remove_dup:
{
databaseUtility.removeDuplicates();
return true;
}
case R.id.menu_context_merge_db:
{
Intent myIntent = new Intent(this, DatabaseMerger.class);
myIntent.putExtra("dbpath", dbPath);
myIntent.putExtra("dbname", dbName);
startActivityForResult(myIntent, ACTIVITY_MERGE);
return true;
}
case R.id.menu_context_shuffle:
{
databaseUtility.shuffleDatabase();
return true;
}
default:
{
return super.onContextItemSelected(menuitem);
}
}
}
private void initTTS(){
String audioDir = Environment.getExternalStorageDirectory().getAbsolutePath() + getString(R.string.default_audio_dir);
Locale ql = settingManager.getQuestionAudioLocale();
Locale al = settingManager.getAnswerAudioLocale();
if(settingManager.getQuestionUserAudio()){
questionTTS = new AudioFileTTS(audioDir, dbName);
}
else if(ql != null){
questionTTS = new AnyMemoTTSPlatform(this, ql);
}
else{
questionTTS = null;
}
if(settingManager.getAnswerUserAudio()){
answerTTS = new AudioFileTTS(audioDir, dbName);
}
else if(al != null){
answerTTS = new AnyMemoTTSPlatform(this, al);
}
else{
answerTTS = null;
}
}
@Override
public void restartActivity(){
Intent myIntent = new Intent(this, EditScreen.class);
if(currentItem != null){
myIntent.putExtra("id", currentItem.getId());
}
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
myIntent.putExtra("filter", activeFilter);
finish();
startActivity(myIntent);
}
private void composeViews(){
LinearLayout memoRoot = (LinearLayout)findViewById(R.id.memo_screen_root);
LinearLayout flashcardDisplayView = (LinearLayout)flashcardDisplay.getView();
LinearLayout controlButtonsView = (LinearLayout)controlButtons.getView();
/* This li is make the background of buttons the same as answer */
LinearLayout li = new LinearLayout(this);
li.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT));
List<Integer> colors = settingManager.getColors();
if(colors != null){
li.setBackgroundColor(settingManager.getColors().get(3));
}
/*
* -1: Match parent -2: Wrap content
* This is necessary or the view will not be
* stetched
*/
memoRoot.addView(flashcardDisplayView, -1, -1);
li.addView(controlButtonsView, -1, -2);
memoRoot.addView(li, -1, -2);
flashcardDisplayView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f));
}
void setViewListeners(){
Map<String, Button> bm = controlButtons.getButtons();
Button newButton = bm.get("new");
Button editButton = bm.get("edit");
Button prevButton = bm.get("prev");
Button nextButton = bm.get("next");
/* Set button listeners */
newButton.setOnClickListener(newButtonListener);
editButton.setOnClickListener(editButtonListener);
prevButton.setOnClickListener(prevButtonListener);
nextButton.setOnClickListener(nextButtonListener);
/* For double sided card, the view can be toggled */
if(settingManager.getCardStyle() == SettingManager.CardStyle.DOUBLE_SIDED){
flashcardDisplay.setQuestionLayoutClickListener(toggleCardSideListener);
flashcardDisplay.setAnswerLayoutClickListener(toggleCardSideListener);
flashcardDisplay.setQuestionTextClickListener(toggleCardSideListener);
flashcardDisplay.setAnswerTextClickListener(toggleCardSideListener);
flashcardDisplay.setQuestionLayoutLongClickListener(popupContextMenuListener);
flashcardDisplay.setAnswerLayoutLongClickListener(popupContextMenuListener);
}
}
private View.OnLongClickListener popupContextMenuListener = new View.OnLongClickListener(){
public boolean onLongClick(View v){
closeContextMenu();
EditScreen.this.openContextMenu(flashcardDisplay.getView());
return true;
}
};
private View.OnClickListener newButtonListener = new View.OnClickListener(){
public void onClick(View v){
Intent myIntent = new Intent(EditScreen.this, CardEditor.class);
myIntent.putExtra("item", currentItem);
myIntent.putExtra("dbpath", dbPath);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("new", true);
startActivityForResult(myIntent, ACTIVITY_EDIT);
}
};
private View.OnClickListener editButtonListener = new View.OnClickListener(){
public void onClick(View v){
Intent myIntent = new Intent(EditScreen.this, CardEditor.class);
myIntent.putExtra("item", currentItem);
myIntent.putExtra("dbpath", dbPath);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("new", false);
startActivityForResult(myIntent, ACTIVITY_EDIT);
}
};
private void updateTitle(){
if(currentItem != null){
int total = itemManager.getStatInfo()[0];
String titleString = getString(R.string.stat_total) + total + " " + getString(R.string.memo_current_id) + " " + currentItem.getId();
if(currentItem != null && currentItem.getCategory() != null){
titleString += " " + currentItem.getCategory();
}
setTitle(titleString);
}
}
private void gotoNext(){
currentItem = itemManager.getNextItem(currentItem);
updateCardFrontSide();
updateTitle();
}
private void deleteCurrent(){
if(currentItem != null){
new AlertDialog.Builder(EditScreen.this)
.setTitle(getString(R.string.detail_delete))
.setMessage(getString(R.string.delete_warning))
.setPositiveButton(getString(R.string.yes_text),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
currentItem = itemManager.deleteItem(currentItem);
restartActivity();
}
})
.setNegativeButton(getString(R.string.no_text), null)
.create()
.show();
}
}
private void gotoPrev(){
currentItem = itemManager.getPreviousItem(currentItem);
updateCardFrontSide();
updateTitle();
}
/*
* Show the front side of the current card
* This method is called instead directly update the flashcard
* so both single and double sided card will work.
*/
private void updateCardFrontSide(){
if(currentItem != null){
if(settingManager.getCardStyle() == SettingManager.CardStyle.DOUBLE_SIDED){
/* Double sided card, show front */
flashcardDisplay.updateView(currentItem, false);
}
else{
/* Single sided, show both answer and questjion. */
flashcardDisplay.updateView(currentItem, true);
}
}
}
private void createSearchOverlay(){
if(searchInflated == false){
LinearLayout root = (LinearLayout)findViewById(R.id.memo_screen_root);
LayoutInflater.from(this).inflate(R.layout.search_overlay, root);
ImageButton close = (ImageButton)findViewById(R.id.search_close_btn);
close.setOnClickListener(closeSearchButtonListener);
ImageButton prev = (ImageButton)findViewById(R.id.search_previous_btn);
prev.setOnClickListener(searchPrevButtonListener);
ImageButton next = (ImageButton)findViewById(R.id.search_next_btn);
next.setOnClickListener(searchNextButtonListener);
EditText editEntry = (EditText)findViewById(R.id.search_entry);
editEntry.requestFocus();
searchInflated = true;
}
else{
LinearLayout layout = (LinearLayout)findViewById(R.id.search_root);
layout.setVisibility(View.VISIBLE);
}
}
private void dismissSearchOverlay(){
if(searchInflated == true){
LinearLayout layout = (LinearLayout)findViewById(R.id.search_root);
layout.setVisibility(View.GONE);
}
}
private View.OnClickListener prevButtonListener = new View.OnClickListener(){
public void onClick(View v){
gotoPrev();
if(questionTTS != null){
questionTTS.stop();
}
}
};
private View.OnClickListener nextButtonListener = new View.OnClickListener(){
public void onClick(View v){
gotoNext();
if(answerTTS != null){
answerTTS.stop();
}
}
};
private View.OnClickListener closeSearchButtonListener = new View.OnClickListener(){
public void onClick(View v){
dismissSearchOverlay();
}
};
private View.OnClickListener searchNextButtonListener = new View.OnClickListener(){
public void onClick(View v){
EditText editEntry = (EditText)findViewById(R.id.search_entry);
String text = editEntry.getText().toString();
Item item = itemManager.search(text, true, currentItem);
if(item != null){
currentItem = item;
updateCardFrontSide();
updateTitle();
}
}
};
private View.OnClickListener searchPrevButtonListener = new View.OnClickListener(){
public void onClick(View v){
EditText editEntry = (EditText)findViewById(R.id.search_entry);
String text = editEntry.getText().toString();
Item item = itemManager.search(text, false, currentItem);
if(item != null){
currentItem = item;
updateCardFrontSide();
updateTitle();
}
}
};
private View.OnTouchListener viewTouchListener = new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event){
return gestureDetector.onTouchEvent(event);
}
};
private View.OnClickListener toggleCardSideListener = new View.OnClickListener(){
public void onClick(View v){
if(currentItem != null){
/* Double sided card, the click will toggle question and answer */
if(settingManager.getCardStyle() == SettingManager.CardStyle.DOUBLE_SIDED){
if(flashcardDisplay.isAnswerShown()){
flashcardDisplay.updateView(currentItem, false);
}
else{
flashcardDisplay.updateView(currentItem, true);
}
}
}
}
};
private GestureDetector.OnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener(){
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDown(MotionEvent e){
/* Trick: Prevent the menu to popup twice */
return true;
}
@Override
public void onLongPress(MotionEvent e){
closeContextMenu();
EditScreen.this.openContextMenu(flashcardDisplay.getView());
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
/* Swipe Right to Left event */
gotoNext();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
/* Swipe Left to Right event */
gotoPrev();
}
} catch (Exception e) {
Log.e(TAG, "Error handling gesture left/right event", e);
}
return false;
}
};
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuspeakquestion:
{
if(questionTTS != null && currentItem != null){
questionTTS.sayText(currentItem.getQuestion());
}
return true;
}
case R.id.menuspeakanswer:
{
if(answerTTS != null && currentItem != null){
answerTTS.sayText(currentItem.getAnswer());
}
return true;
}
case R.id.editmenu_settings_id:
{
Intent myIntent = new Intent(this, SettingsScreen.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
startActivityForResult(myIntent, ACTIVITY_SETTINGS);
return true;
}
case R.id.editmenu_delete_id:
{
deleteCurrent();
return true;
}
case R.id.editmenu_detail_id:
{
if(currentItem != null){
Intent myIntent = new Intent(this, DetailScreen.class);
myIntent.putExtra("dbname", this.dbName);
myIntent.putExtra("dbpath", this.dbPath);
myIntent.putExtra("itemid", currentItem.getId());
startActivityForResult(myIntent, ACTIVITY_DETAIL);
}
return true;
}
case R.id.editmenu_list_id:
{
Intent myIntent = new Intent(this, SettingsScreen.class);
myIntent.setClass(this, ListEditScreen.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
if(currentItem != null){
myIntent.putExtra("openid", currentItem.getId());
}
startActivityForResult(myIntent, ACTIVITY_LIST);
return true;
}
case R.id.menu_edit_filter:
{
Intent myIntent = new Intent(this, Filter.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
startActivityForResult(myIntent, ACTIVITY_FILTER);
return true;
}
case R.id.editmenu_search_id:
{
createSearchOverlay();
}
case R.id.editmenu_help:
{
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.addCategory(Intent.CATEGORY_BROWSABLE);
myIntent.setData(Uri.parse(WEBSITE_HELP_EDIT));
startActivity(myIntent);
return true;
}
}
return false;
}
| public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuspeakquestion:
{
if(questionTTS != null && currentItem != null){
questionTTS.sayText(currentItem.getQuestion());
}
return true;
}
case R.id.menuspeakanswer:
{
if(answerTTS != null && currentItem != null){
answerTTS.sayText(currentItem.getAnswer());
}
return true;
}
case R.id.editmenu_settings_id:
{
Intent myIntent = new Intent(this, SettingsScreen.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
startActivityForResult(myIntent, ACTIVITY_SETTINGS);
return true;
}
case R.id.editmenu_delete_id:
{
deleteCurrent();
return true;
}
case R.id.editmenu_detail_id:
{
if(currentItem != null){
Intent myIntent = new Intent(this, DetailScreen.class);
myIntent.putExtra("dbname", this.dbName);
myIntent.putExtra("dbpath", this.dbPath);
myIntent.putExtra("itemid", currentItem.getId());
startActivityForResult(myIntent, ACTIVITY_DETAIL);
}
return true;
}
case R.id.editmenu_list_id:
{
Intent myIntent = new Intent(this, SettingsScreen.class);
myIntent.setClass(this, ListEditScreen.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
if(currentItem != null){
myIntent.putExtra("openid", currentItem.getId());
}
startActivityForResult(myIntent, ACTIVITY_LIST);
return true;
}
case R.id.menu_edit_filter:
{
Intent myIntent = new Intent(this, Filter.class);
myIntent.putExtra("dbname", dbName);
myIntent.putExtra("dbpath", dbPath);
startActivityForResult(myIntent, ACTIVITY_FILTER);
return true;
}
case R.id.editmenu_search_id:
{
createSearchOverlay();
return true;
}
case R.id.editmenu_help:
{
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.addCategory(Intent.CATEGORY_BROWSABLE);
myIntent.setData(Uri.parse(WEBSITE_HELP_EDIT));
startActivity(myIntent);
return true;
}
}
return false;
}
|
diff --git a/stm1/src/exercises/PeriodicTimerMachine.java b/stm1/src/exercises/PeriodicTimerMachine.java
index 0341503..66a872e 100644
--- a/stm1/src/exercises/PeriodicTimerMachine.java
+++ b/stm1/src/exercises/PeriodicTimerMachine.java
@@ -1,47 +1,47 @@
package exercises;
import runtime.EventWindow;
import runtime.IStateMachine;
import runtime.Scheduler;
import runtime.Timer;
public class PeriodicTimerMachine implements IStateMachine {
private static final String START = "Start", STOP = "Stop", TIMER_1 = "t1";
public static final String[] EVENTS = {START, STOP};
private enum STATES {IDLE, ACTIVE, FINAL}
private Timer t1 = new Timer("t1");
protected STATES state = STATES.IDLE;
public int fire(String event, Scheduler scheduler) {
if(state==STATES.IDLE) {
if(event.equals(START)) {
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
}
} else if(state==STATES.ACTIVE) {
if(event.equals(STOP)) {
- t1.start(scheduler, 1000);
- state = STATES.ACTIVE;
+ t1.stop();
+ state = STATES.IDLE;
return EXECUTE_TRANSITION;
} else if (event.equals(TIMER_1)) {
System.out.println("tick");
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
}
}
return DISCARD_EVENT;
}
public static void main(String[] args) {
IStateMachine stm = new PeriodicTimerMachine();
Scheduler s = new Scheduler(stm);
EventWindow w = new EventWindow(EVENTS, s);
w.show();
s.run();
}
}
| true | true | public int fire(String event, Scheduler scheduler) {
if(state==STATES.IDLE) {
if(event.equals(START)) {
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
}
} else if(state==STATES.ACTIVE) {
if(event.equals(STOP)) {
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
} else if (event.equals(TIMER_1)) {
System.out.println("tick");
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
}
}
return DISCARD_EVENT;
}
| public int fire(String event, Scheduler scheduler) {
if(state==STATES.IDLE) {
if(event.equals(START)) {
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
}
} else if(state==STATES.ACTIVE) {
if(event.equals(STOP)) {
t1.stop();
state = STATES.IDLE;
return EXECUTE_TRANSITION;
} else if (event.equals(TIMER_1)) {
System.out.println("tick");
t1.start(scheduler, 1000);
state = STATES.ACTIVE;
return EXECUTE_TRANSITION;
}
}
return DISCARD_EVENT;
}
|
diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearcherPersonToRoleGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearcherPersonToRoleGenerator.java
index f721879..f26faf8 100644
--- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearcherPersonToRoleGenerator.java
+++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearcherPersonToRoleGenerator.java
@@ -1,45 +1,45 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.HashMap;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
public class AddResearcherPersonToRoleGenerator extends AddPersonToRoleTwoStageGenerator {
private static String template = "addResearcherPersonToRole.ftl";
@Override
String getTemplate() {
return template;
}
@Override
public String getRoleType() {
return "http://vivoweb.org/ontology/core#ResearcherRole";
}
@Override
RoleActivityOptionTypes getRoleActivityTypeOptionsType() {
return RoleActivityOptionTypes.HARDCODED_LITERALS;
}
@Override
String getRoleActivityTypeObjectClassUri(VitroRequest vreq) {
return null;
}
//Researcher role involves hard-coded options for the "right side" of the role or activity
@Override
HashMap<String, String> getRoleActivityTypeLiteralOptions() {
HashMap<String, String> literalOptions = new HashMap<String, String>();
literalOptions.put("", "Select one");
- literalOptions.put("http://vivoweb.org/ontology/core#Person", "Person");
+ literalOptions.put("http://vivoweb.org/ontology/core#FacultyMember", "Person");
//literalOptions.put("http://vivoweb.org/ontology/core#Project","Project");
return literalOptions;
}
@Override
boolean isShowRoleLabelField() { return true; }
}
| true | true | HashMap<String, String> getRoleActivityTypeLiteralOptions() {
HashMap<String, String> literalOptions = new HashMap<String, String>();
literalOptions.put("", "Select one");
literalOptions.put("http://vivoweb.org/ontology/core#Person", "Person");
//literalOptions.put("http://vivoweb.org/ontology/core#Project","Project");
return literalOptions;
}
| HashMap<String, String> getRoleActivityTypeLiteralOptions() {
HashMap<String, String> literalOptions = new HashMap<String, String>();
literalOptions.put("", "Select one");
literalOptions.put("http://vivoweb.org/ontology/core#FacultyMember", "Person");
//literalOptions.put("http://vivoweb.org/ontology/core#Project","Project");
return literalOptions;
}
|
diff --git a/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java b/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java
index 6faef4a..5319d97 100644
--- a/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java
+++ b/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java
@@ -1,117 +1,117 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.slidellrobotics.reboundrumble.commands;
import com.slidellrobotics.reboundrumble.subsystems.TrackingCamera;
/**
*
* @author 10491477
*/
public class FindDistance extends CommandBase {
double tgtHght = TrackingCamera.targetHeight; // Create a few necesarry local variables
double tgtWdth = TrackingCamera.targetWidth; // for concise code and calcs.
double tgtHghtFt; // Target Height in Feet
double tgtWdthFt; // Target Width in Feet
double ttlHght; // Total Height in Pixels
double ttlWdth; // Total Width imn Pixels
double vertFOV; // Vertical Field of View in Feet
double horFOV; // Horizontal Field of View in Feet
double vertVA; // Vertical Camera Viewing Angle
double horVA; // Horizontal Camera Viewing Angle
double leftRight; // Horizontal off-centerness of center of goal
double upDown; // Vertical off-centerness of center of goal
double wdth1Px; // Distance from the center of a Goal to the nearest Horizontal edge
double hght1Px; // Distance from the center of a Goal to the nearest Vertical edge
double horThet1; // Horizontal Angle from the Edge to Camera to center of Goal
double vertThet1; // Verticle Angle from the Edge to Camera to center of Goal
double d = 0; // Distance Variable to be used in firing Calculation
double pi = Math.PI; // Slightly shorter version using Pi
public FindDistance() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(leftShootingMotors); // Sets requires for Left Shooting Motors
requires(rightShootingMotors); // Sets requires for Right hooting Motors
}
// Called just before this Command runs the first time
protected void initialize() {
ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
ttlWdth = TrackingCamera.totalWidth; // Target Width from the Tracking Camera's static variable
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (TrackingCamera.targetGoal == null){ // If no target is found
leftShootingMotors.setSetpoint(1000); // Set Left shooting Motors to Full Speed
rightShootingMotors.setSetpoint(1000); // Set Right Shooting Motors to Full Speed
System.out.println("No target set"); // Debug Print Statement
return;
}
- ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
- ttlWdth = TrackingCamera.totalWidth;
+ ttlHght = 480; // Target Height
+ ttlWdth = 640; // Target Width
tgtHght = TrackingCamera.targetGoal.boundingRectHeight; // Sets the height of our target.
tgtHghtFt = 1.5; // Defines goal's constant ft height
vertFOV = tgtHghtFt / tgtHght * ttlHght; // Gets the Foot Value of our Vertical Field of View
vertVA = 47*pi/180; // Defines the Viewing
horVA = 47*pi/180; // Angles of our camera
tgtWdth = TrackingCamera.targetGoal.boundingRectWidth; // Sets the width of our target.
tgtWdthFt = 2.0; // Defines goal's constant ft width
horFOV = tgtWdthFt / tgtWdth * ttlWdth; // Gets the ft value of our horizontal Field of View
leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlWdth/2)); // Finds the horizontal off-centerness
upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlHght/2)); // Finds the vertical off-ceneterness
wdth1Px = (ttlWdth/2) - leftRight; // Defines the distance from the Horizontal Edge to center of Goal in Pixels
hght1Px = (ttlHght/2) - upDown; // Defines the distance from the Vertical Edge to center of Goal in Pixels
horThet1 = horVA * wdth1Px/ttlWdth; // Finds the angle from Horizontal Edge<>camera<>center of goal
vertThet1 = vertVA * hght1Px/ttlHght; // Finds the angle from Vertical Edge<>camera<>center of goal
TrackingCamera.d1 = (hght1Px) / Math.tan(vertThet1); // Gets a distance from the center of our goal using Horizontal Theta
TrackingCamera.d2 = (wdth1Px) / Math.tan(horThet1); // Double checks distance with a Vertcial Theta
TrackingCamera.distanceToTarget = (TrackingCamera.d1 + TrackingCamera.d2) / 2; // Take the average to try get a more accurate measurement
//if distance to target is invalid, justset it to some number
if (TrackingCamera.distanceToTarget > 60 || TrackingCamera.distanceToTarget <= 0)
TrackingCamera.distanceToTarget = 60;
d = TrackingCamera.distanceToTarget; // See below Calculation for conciseness
TrackingCamera.launchSpeed = 60 * (d / Math.sqrt((11 / 6 - d) / -16.1) / (2 / 3 * pi)); //Calcs the required rpms for firing
leftShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the shooting Left Shooting Motors
rightShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the Right Shooting Motors
/* A String of Debug Print Statements */
System.out.println();
System.out.println("D1: "+TrackingCamera.d1);
System.out.println("D2: "+TrackingCamera.d2);
System.out.println("D: "+d);
System.out.println("Camera Launch Speed: "+TrackingCamera.launchSpeed);
System.out.println();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return true;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| true | true | protected void execute() {
if (TrackingCamera.targetGoal == null){ // If no target is found
leftShootingMotors.setSetpoint(1000); // Set Left shooting Motors to Full Speed
rightShootingMotors.setSetpoint(1000); // Set Right Shooting Motors to Full Speed
System.out.println("No target set"); // Debug Print Statement
return;
}
ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
ttlWdth = TrackingCamera.totalWidth;
tgtHght = TrackingCamera.targetGoal.boundingRectHeight; // Sets the height of our target.
tgtHghtFt = 1.5; // Defines goal's constant ft height
vertFOV = tgtHghtFt / tgtHght * ttlHght; // Gets the Foot Value of our Vertical Field of View
vertVA = 47*pi/180; // Defines the Viewing
horVA = 47*pi/180; // Angles of our camera
tgtWdth = TrackingCamera.targetGoal.boundingRectWidth; // Sets the width of our target.
tgtWdthFt = 2.0; // Defines goal's constant ft width
horFOV = tgtWdthFt / tgtWdth * ttlWdth; // Gets the ft value of our horizontal Field of View
leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlWdth/2)); // Finds the horizontal off-centerness
upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlHght/2)); // Finds the vertical off-ceneterness
wdth1Px = (ttlWdth/2) - leftRight; // Defines the distance from the Horizontal Edge to center of Goal in Pixels
hght1Px = (ttlHght/2) - upDown; // Defines the distance from the Vertical Edge to center of Goal in Pixels
horThet1 = horVA * wdth1Px/ttlWdth; // Finds the angle from Horizontal Edge<>camera<>center of goal
vertThet1 = vertVA * hght1Px/ttlHght; // Finds the angle from Vertical Edge<>camera<>center of goal
TrackingCamera.d1 = (hght1Px) / Math.tan(vertThet1); // Gets a distance from the center of our goal using Horizontal Theta
TrackingCamera.d2 = (wdth1Px) / Math.tan(horThet1); // Double checks distance with a Vertcial Theta
TrackingCamera.distanceToTarget = (TrackingCamera.d1 + TrackingCamera.d2) / 2; // Take the average to try get a more accurate measurement
//if distance to target is invalid, justset it to some number
if (TrackingCamera.distanceToTarget > 60 || TrackingCamera.distanceToTarget <= 0)
TrackingCamera.distanceToTarget = 60;
d = TrackingCamera.distanceToTarget; // See below Calculation for conciseness
TrackingCamera.launchSpeed = 60 * (d / Math.sqrt((11 / 6 - d) / -16.1) / (2 / 3 * pi)); //Calcs the required rpms for firing
leftShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the shooting Left Shooting Motors
rightShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the Right Shooting Motors
/* A String of Debug Print Statements */
System.out.println();
System.out.println("D1: "+TrackingCamera.d1);
System.out.println("D2: "+TrackingCamera.d2);
System.out.println("D: "+d);
System.out.println("Camera Launch Speed: "+TrackingCamera.launchSpeed);
System.out.println();
}
| protected void execute() {
if (TrackingCamera.targetGoal == null){ // If no target is found
leftShootingMotors.setSetpoint(1000); // Set Left shooting Motors to Full Speed
rightShootingMotors.setSetpoint(1000); // Set Right Shooting Motors to Full Speed
System.out.println("No target set"); // Debug Print Statement
return;
}
ttlHght = 480; // Target Height
ttlWdth = 640; // Target Width
tgtHght = TrackingCamera.targetGoal.boundingRectHeight; // Sets the height of our target.
tgtHghtFt = 1.5; // Defines goal's constant ft height
vertFOV = tgtHghtFt / tgtHght * ttlHght; // Gets the Foot Value of our Vertical Field of View
vertVA = 47*pi/180; // Defines the Viewing
horVA = 47*pi/180; // Angles of our camera
tgtWdth = TrackingCamera.targetGoal.boundingRectWidth; // Sets the width of our target.
tgtWdthFt = 2.0; // Defines goal's constant ft width
horFOV = tgtWdthFt / tgtWdth * ttlWdth; // Gets the ft value of our horizontal Field of View
leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlWdth/2)); // Finds the horizontal off-centerness
upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlHght/2)); // Finds the vertical off-ceneterness
wdth1Px = (ttlWdth/2) - leftRight; // Defines the distance from the Horizontal Edge to center of Goal in Pixels
hght1Px = (ttlHght/2) - upDown; // Defines the distance from the Vertical Edge to center of Goal in Pixels
horThet1 = horVA * wdth1Px/ttlWdth; // Finds the angle from Horizontal Edge<>camera<>center of goal
vertThet1 = vertVA * hght1Px/ttlHght; // Finds the angle from Vertical Edge<>camera<>center of goal
TrackingCamera.d1 = (hght1Px) / Math.tan(vertThet1); // Gets a distance from the center of our goal using Horizontal Theta
TrackingCamera.d2 = (wdth1Px) / Math.tan(horThet1); // Double checks distance with a Vertcial Theta
TrackingCamera.distanceToTarget = (TrackingCamera.d1 + TrackingCamera.d2) / 2; // Take the average to try get a more accurate measurement
//if distance to target is invalid, justset it to some number
if (TrackingCamera.distanceToTarget > 60 || TrackingCamera.distanceToTarget <= 0)
TrackingCamera.distanceToTarget = 60;
d = TrackingCamera.distanceToTarget; // See below Calculation for conciseness
TrackingCamera.launchSpeed = 60 * (d / Math.sqrt((11 / 6 - d) / -16.1) / (2 / 3 * pi)); //Calcs the required rpms for firing
leftShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the shooting Left Shooting Motors
rightShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the Right Shooting Motors
/* A String of Debug Print Statements */
System.out.println();
System.out.println("D1: "+TrackingCamera.d1);
System.out.println("D2: "+TrackingCamera.d2);
System.out.println("D: "+d);
System.out.println("Camera Launch Speed: "+TrackingCamera.launchSpeed);
System.out.println();
}
|
diff --git a/src/main/java/com/craftminecraft/plugins/bansync/plugins/WorldGuardHook.java b/src/main/java/com/craftminecraft/plugins/bansync/plugins/WorldGuardHook.java
index 009f716..2c92526 100644
--- a/src/main/java/com/craftminecraft/plugins/bansync/plugins/WorldGuardHook.java
+++ b/src/main/java/com/craftminecraft/plugins/bansync/plugins/WorldGuardHook.java
@@ -1,67 +1,80 @@
package com.craftminecraft.plugins.bansync.plugins;
import java.util.List;
import java.util.Map;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import com.craftminecraft.plugins.bansync.BanSync;
import com.craftminecraft.plugins.bansync.log.LogLevels;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class WorldGuardHook {
private BanSync bansyncinterface = null;
private Boolean pluginHooked = false;
public static WorldGuardPlugin wg = null;
public WorldGuardHook (BanSync p) {
bansyncinterface = p;
}
public Boolean isHooked()
{
return pluginHooked;
}
public Boolean HookWorldGuard()
{
Plugin p = bansyncinterface.getServer().getPluginManager().getPlugin("WorldGuard");
if (p != null && p instanceof WorldGuardPlugin) {
pluginHooked = true;
bansyncinterface.logger.log(LogLevels.INFO, "WorldGuard Found, hooking into WorldGuard.");
wg = (WorldGuardPlugin) p;
return true;
} else {
pluginHooked = false;
bansyncinterface.logger.log(LogLevels.INFO, "WorldGuard not Found");
return false;
}
}
public void ClearWorldGuardRegions(String playerName)
{
// Do Something...
List<World> worlds = bansyncinterface.getServer().getWorlds();
for (World w : worlds) {
RegionManager rm = wg.getRegionManager(w);
Map<String, ProtectedRegion> regions = rm.getRegions();
for (String id : regions.keySet()) {
if (regions.get(id).getOwners().getPlayers().contains(playerName)) {
- bansyncinterface.logger.log(LogLevels.INFO, "Found region " + id + ", Removing it");
- rm.removeRegion(id);
- try {
- rm.save();
- } catch (ProtectionDatabaseException e) {
- bansyncinterface.logger.log(LogLevels.INFO, "Error removing region " + id + ", " + e.getMessage());
+ if (regions.get(id).getOwners().getPlayers().size() > 1)
+ {
+ bansyncinterface.logger.log(LogLevels.INFO, "Found region " + id + ", Removing player as an owner");
+ rm.getRegionExact(id).getOwners().removePlayer(playerName);
+ try {
+ rm.save();
+ } catch (ProtectionDatabaseException e) {
+ bansyncinterface.logger.log(LogLevels.INFO, "Error removing region " + id + ", " + e.getMessage());
+ }
+ }
+ else
+ {
+ bansyncinterface.logger.log(LogLevels.INFO, "Found region " + id + ", Removing it");
+ rm.removeRegion(id);
+ try {
+ rm.save();
+ } catch (ProtectionDatabaseException e) {
+ bansyncinterface.logger.log(LogLevels.INFO, "Error removing region " + id + ", " + e.getMessage());
+ }
}
}
}
}
}
}
| true | true | public void ClearWorldGuardRegions(String playerName)
{
// Do Something...
List<World> worlds = bansyncinterface.getServer().getWorlds();
for (World w : worlds) {
RegionManager rm = wg.getRegionManager(w);
Map<String, ProtectedRegion> regions = rm.getRegions();
for (String id : regions.keySet()) {
if (regions.get(id).getOwners().getPlayers().contains(playerName)) {
bansyncinterface.logger.log(LogLevels.INFO, "Found region " + id + ", Removing it");
rm.removeRegion(id);
try {
rm.save();
} catch (ProtectionDatabaseException e) {
bansyncinterface.logger.log(LogLevels.INFO, "Error removing region " + id + ", " + e.getMessage());
}
}
}
}
}
| public void ClearWorldGuardRegions(String playerName)
{
// Do Something...
List<World> worlds = bansyncinterface.getServer().getWorlds();
for (World w : worlds) {
RegionManager rm = wg.getRegionManager(w);
Map<String, ProtectedRegion> regions = rm.getRegions();
for (String id : regions.keySet()) {
if (regions.get(id).getOwners().getPlayers().contains(playerName)) {
if (regions.get(id).getOwners().getPlayers().size() > 1)
{
bansyncinterface.logger.log(LogLevels.INFO, "Found region " + id + ", Removing player as an owner");
rm.getRegionExact(id).getOwners().removePlayer(playerName);
try {
rm.save();
} catch (ProtectionDatabaseException e) {
bansyncinterface.logger.log(LogLevels.INFO, "Error removing region " + id + ", " + e.getMessage());
}
}
else
{
bansyncinterface.logger.log(LogLevels.INFO, "Found region " + id + ", Removing it");
rm.removeRegion(id);
try {
rm.save();
} catch (ProtectionDatabaseException e) {
bansyncinterface.logger.log(LogLevels.INFO, "Error removing region " + id + ", " + e.getMessage());
}
}
}
}
}
}
|
diff --git a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java
index 4c7f414ca..10cdd512e 100644
--- a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java
+++ b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java
@@ -1,333 +1,334 @@
/**
* Copyright 2011 JogAmp Community. 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.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
package jogamp.opengl;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import javax.media.nativewindow.NativeWindowException;
import javax.media.opengl.GL2GL3;
import javax.media.opengl.GLDebugListener;
import javax.media.opengl.GLDebugMessage;
import javax.media.opengl.GLException;
import com.jogamp.common.os.Platform;
import com.jogamp.gluegen.runtime.ProcAddressTable;
import com.jogamp.opengl.GLExtensions;
/**
* The GLDebugMessageHandler, handling <i>GL_ARB_debug_output</i> or <i>GL_AMD_debug_output</i>
* debug messages.<br>
*
* <p>An instance must be bound to the current thread's GLContext to achieve thread safety.</p>
*
* <p>A native callback function is registered at {@link #enable(boolean) enable(true)},
* which forwards received messages to the added {@link GLDebugListener} directly.
* Hence the {@link GLDebugListener#messageSent(GLDebugMessage)} implementation shall
* return as fast as possible.</p>
*
* <p>In case no <i>GL_ARB_debug_output</i> is available, but <i>GL_AMD_debug_output</i>,
* the messages are translated to <i>ARB</i> {@link GLDebugMessage}, using {@link GLDebugMessage#translateAMDEvent(javax.media.opengl.GLContext, long, int, int, int, String)}.</p>
*/
public class GLDebugMessageHandler {
private static final boolean DEBUG = Debug.debug("GLDebugMessageHandler");
private static final int EXT_ARB = 1;
private static final int EXT_AMD = 2;
static {
if ( !initIDs0() ) {
throw new NativeWindowException("Failed to initialize GLDebugMessageHandler jmethodIDs");
}
}
private final GLContextImpl ctx;
private final ListenerSyncedImplStub<GLDebugListener> listenerImpl;
// licefycle: init - EOL
private String extName;
private int extType;
private long glDebugMessageCallbackProcAddress;
private boolean extAvailable;
private boolean synchronous;
// licefycle: enable - disable/EOL
private long handle;
/**
* @param ctx the associated GLContext
* @param glDebugExtension chosen extension to use
*/
public GLDebugMessageHandler(GLContextImpl ctx) {
this.ctx = ctx;
this.listenerImpl = new ListenerSyncedImplStub<GLDebugListener>();
this.glDebugMessageCallbackProcAddress = 0;
this.extName = null;
this.extType = 0;
this.extAvailable = false;
this.handle = 0;
this.synchronous = true;
}
public void init(boolean enable) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler.init("+enable+")");
}
init();
if(isAvailable()) {
enableImpl(enable);
} else if(DEBUG) {
System.err.println("GLDebugMessageHandler.init("+enable+") .. n/a");
}
}
private final long getAddressFor(final ProcAddressTable table, final String functionName) {
return AccessController.doPrivileged(new PrivilegedAction<Long>() {
public Long run() {
try {
return Long.valueOf( table.getAddressFor(functionName) );
} catch (IllegalArgumentException iae) {
return Long.valueOf(0);
}
}
} ).longValue();
}
public void init() {
ctx.validateCurrent();
if( isAvailable()) {
return;
}
if( !ctx.isGLDebugEnabled() ) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: GL DEBUG not set in ARB ctx options: "+ctx.getGLVersion());
}
return;
}
if(Platform.OS_TYPE == Platform.OSType.WINDOWS && Platform.is32Bit()) {
// Currently buggy, ie. throws an exception after leaving the native callback.
// Probably a 32bit on 64bit JVM / OpenGL-driver issue.
if(DEBUG) {
System.err.println("GLDebugMessageHandler: Windows 32bit currently not supported!");
}
return;
}
if( ctx.isExtensionAvailable(GLExtensions.ARB_debug_output) ) {
extName = GLExtensions.ARB_debug_output;
extType = EXT_ARB;
} else if( ctx.isExtensionAvailable(GLExtensions.AMD_debug_output) ) {
extName = GLExtensions.AMD_debug_output;
extType = EXT_AMD;
}
if(DEBUG) {
System.err.println("GLDebugMessageHandler: Using extension: <"+extName+">");
}
if(0 == extType) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: No extension available! "+ctx.getGLVersion());
System.err.println("GL_EXTENSIONS "+ctx.getGLExtensionCount());
System.err.println(ctx.getGLExtensionsString());
}
return;
}
final ProcAddressTable procAddressTable = ctx.getGLProcAddressTable();
- if( ctx.isGL4() ) {
+ if( !ctx.isGLES1() && !ctx.isGLES2() ) {
switch(extType) {
case EXT_ARB:
glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackARB");
break;
case EXT_AMD:
glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackAMD");
break;
}
} else {
+ glDebugMessageCallbackProcAddress = 0;
if(DEBUG) {
System.err.println("Non desktop context not supported");
}
}
extAvailable = 0 < extType && null != extName && 0 != glDebugMessageCallbackProcAddress;
if(DEBUG) {
System.err.println("GLDebugMessageHandler: extAvailable: "+extAvailable+", glDebugMessageCallback* : 0x"+Long.toHexString(glDebugMessageCallbackProcAddress));
}
if(!extAvailable) {
glDebugMessageCallbackProcAddress = 0;
}
handle = 0;
}
public final boolean isAvailable() { return extAvailable; }
/**
* @return The extension implementing the GLDebugMessage feature,
* either {@link #GL_ARB_debug_output} or {@link #GL_AMD_debug_output}.
* If unavailable <i>null</i> is returned.
*/
public final String getExtension() {
return extName;
}
public final boolean isExtensionARB() {
return extName == GLExtensions.ARB_debug_output;
}
public final boolean isExtensionAMD() {
return extName == GLExtensions.AMD_debug_output;
}
/**
* @see javax.media.opengl.GLContext#isGLDebugSynchronous()
*/
public final boolean isSynchronous() { return synchronous; }
/**
* @see javax.media.opengl.GLContext#setGLDebugSynchronous(boolean)
*/
public final void setSynchronous(boolean synchronous) {
this.synchronous = synchronous;
if( isEnabled() ) {
setSynchronousImpl();
}
}
private final void setSynchronousImpl() {
if(isExtensionARB()) {
if(synchronous) {
ctx.getGL().glEnable(GL2GL3.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
} else {
ctx.getGL().glDisable(GL2GL3.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
if(DEBUG) {
System.err.println("GLDebugMessageHandler: synchronous "+synchronous);
}
}
}
/**
* @see javax.media.opengl.GLContext#enableGLDebugMessage(boolean)
*/
public final void enable(boolean enable) throws GLException {
ctx.validateCurrent();
if(!isAvailable()) {
return;
}
enableImpl(enable);
}
final void enableImpl(boolean enable) throws GLException {
if(enable) {
if(0 == handle) {
setSynchronousImpl();
handle = register0(glDebugMessageCallbackProcAddress, extType);
if(0 == handle) {
throw new GLException("Failed to register via \"glDebugMessageCallback*\" using "+extName);
}
}
} else {
if(0 != handle) {
unregister0(glDebugMessageCallbackProcAddress, handle);
handle = 0;
}
}
if(DEBUG) {
System.err.println("GLDebugMessageHandler: enable("+enable+") -> 0x" + Long.toHexString(handle));
}
}
public final boolean isEnabled() { return 0 != handle; }
public final int listenerSize() {
return listenerImpl.size();
}
public final void addListener(GLDebugListener listener) {
listenerImpl.addListener(-1, listener);
}
public final void addListener(int index, GLDebugListener listener) {
listenerImpl.addListener(index, listener);
}
public final void removeListener(GLDebugListener listener) {
listenerImpl.removeListener(listener);
}
private final void sendMessage(GLDebugMessage msg) {
synchronized(listenerImpl) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: "+msg);
}
final ArrayList<GLDebugListener> listeners = listenerImpl.getListeners();
for(int i=0; i<listeners.size(); i++) {
listeners.get(i).messageSent(msg);
}
}
}
public static class StdErrGLDebugListener implements GLDebugListener {
boolean threadDump;
public StdErrGLDebugListener(boolean threadDump) {
this.threadDump = threadDump;
}
public void messageSent(GLDebugMessage event) {
System.err.println(event);
if(threadDump) {
Thread.dumpStack();
}
}
}
//
// native -> java
//
protected final void glDebugMessageARB(int source, int type, int id, int severity, String msg) {
final GLDebugMessage event = new GLDebugMessage(ctx, System.currentTimeMillis(), source, type, id, severity, msg);
sendMessage(event);
}
protected final void glDebugMessageAMD(int id, int category, int severity, String msg) {
final GLDebugMessage event = GLDebugMessage.translateAMDEvent(ctx, System.currentTimeMillis(), id, category, severity, msg);
sendMessage(event);
}
//
// java -> native
//
private static native boolean initIDs0();
private native long register0(long glDebugMessageCallbackProcAddress, int extType);
private native void unregister0(long glDebugMessageCallbackProcAddress, long handle);
}
| false | true | public void init() {
ctx.validateCurrent();
if( isAvailable()) {
return;
}
if( !ctx.isGLDebugEnabled() ) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: GL DEBUG not set in ARB ctx options: "+ctx.getGLVersion());
}
return;
}
if(Platform.OS_TYPE == Platform.OSType.WINDOWS && Platform.is32Bit()) {
// Currently buggy, ie. throws an exception after leaving the native callback.
// Probably a 32bit on 64bit JVM / OpenGL-driver issue.
if(DEBUG) {
System.err.println("GLDebugMessageHandler: Windows 32bit currently not supported!");
}
return;
}
if( ctx.isExtensionAvailable(GLExtensions.ARB_debug_output) ) {
extName = GLExtensions.ARB_debug_output;
extType = EXT_ARB;
} else if( ctx.isExtensionAvailable(GLExtensions.AMD_debug_output) ) {
extName = GLExtensions.AMD_debug_output;
extType = EXT_AMD;
}
if(DEBUG) {
System.err.println("GLDebugMessageHandler: Using extension: <"+extName+">");
}
if(0 == extType) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: No extension available! "+ctx.getGLVersion());
System.err.println("GL_EXTENSIONS "+ctx.getGLExtensionCount());
System.err.println(ctx.getGLExtensionsString());
}
return;
}
final ProcAddressTable procAddressTable = ctx.getGLProcAddressTable();
if( ctx.isGL4() ) {
switch(extType) {
case EXT_ARB:
glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackARB");
break;
case EXT_AMD:
glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackAMD");
break;
}
} else {
if(DEBUG) {
System.err.println("Non desktop context not supported");
}
}
extAvailable = 0 < extType && null != extName && 0 != glDebugMessageCallbackProcAddress;
if(DEBUG) {
System.err.println("GLDebugMessageHandler: extAvailable: "+extAvailable+", glDebugMessageCallback* : 0x"+Long.toHexString(glDebugMessageCallbackProcAddress));
}
if(!extAvailable) {
glDebugMessageCallbackProcAddress = 0;
}
handle = 0;
}
| public void init() {
ctx.validateCurrent();
if( isAvailable()) {
return;
}
if( !ctx.isGLDebugEnabled() ) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: GL DEBUG not set in ARB ctx options: "+ctx.getGLVersion());
}
return;
}
if(Platform.OS_TYPE == Platform.OSType.WINDOWS && Platform.is32Bit()) {
// Currently buggy, ie. throws an exception after leaving the native callback.
// Probably a 32bit on 64bit JVM / OpenGL-driver issue.
if(DEBUG) {
System.err.println("GLDebugMessageHandler: Windows 32bit currently not supported!");
}
return;
}
if( ctx.isExtensionAvailable(GLExtensions.ARB_debug_output) ) {
extName = GLExtensions.ARB_debug_output;
extType = EXT_ARB;
} else if( ctx.isExtensionAvailable(GLExtensions.AMD_debug_output) ) {
extName = GLExtensions.AMD_debug_output;
extType = EXT_AMD;
}
if(DEBUG) {
System.err.println("GLDebugMessageHandler: Using extension: <"+extName+">");
}
if(0 == extType) {
if(DEBUG) {
System.err.println("GLDebugMessageHandler: No extension available! "+ctx.getGLVersion());
System.err.println("GL_EXTENSIONS "+ctx.getGLExtensionCount());
System.err.println(ctx.getGLExtensionsString());
}
return;
}
final ProcAddressTable procAddressTable = ctx.getGLProcAddressTable();
if( !ctx.isGLES1() && !ctx.isGLES2() ) {
switch(extType) {
case EXT_ARB:
glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackARB");
break;
case EXT_AMD:
glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackAMD");
break;
}
} else {
glDebugMessageCallbackProcAddress = 0;
if(DEBUG) {
System.err.println("Non desktop context not supported");
}
}
extAvailable = 0 < extType && null != extName && 0 != glDebugMessageCallbackProcAddress;
if(DEBUG) {
System.err.println("GLDebugMessageHandler: extAvailable: "+extAvailable+", glDebugMessageCallback* : 0x"+Long.toHexString(glDebugMessageCallbackProcAddress));
}
if(!extAvailable) {
glDebugMessageCallbackProcAddress = 0;
}
handle = 0;
}
|
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/renderer/se/graphic/ViewBox.java b/orbisgis-core/src/main/java/org/orbisgis/core/renderer/se/graphic/ViewBox.java
index 073a1a8b5..7375e083e 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/core/renderer/se/graphic/ViewBox.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/core/renderer/se/graphic/ViewBox.java
@@ -1,250 +1,251 @@
/**
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.renderer.se.graphic;
import java.awt.geom.Point2D;
import java.util.HashSet;
import java.util.Map;
import net.opengis.se._2_0.core.ViewBoxType;
import org.gdms.data.values.Value;
import org.orbisgis.core.renderer.se.AbstractSymbolizerNode;
import org.orbisgis.core.renderer.se.SeExceptions.InvalidStyle;
import org.orbisgis.core.renderer.se.UomNode;
import org.orbisgis.core.renderer.se.common.Uom;
import org.orbisgis.core.renderer.se.parameter.ParameterException;
import org.orbisgis.core.renderer.se.parameter.SeParameterFactory;
import org.orbisgis.core.renderer.se.parameter.UsedAnalysis;
import org.orbisgis.core.renderer.se.parameter.real.RealParameter;
import org.orbisgis.core.renderer.se.parameter.real.RealParameterContext;
/**
* {@code ViewBox} supplies a simplen and convenient method to change the view box of a graphic,
* in a {@link MarkGraphic} for instance.
* {@code ViewBox} is bult using the following parameters :
* <ul><li>X : the width of the box.</li>
* <li>Y : the height of the box.</li></ul>
* If only one of these two is given, they are considered to be equal.</p>
* <p>The main difference between this class and {@link Scale} is that a {@code Scale}
* will use a reference graphic, that already has a size, and process an affine transformation
* on it, while here the size of the graphic will be defined directly using its height
* and width.</p>
* <p>The values given for the height and the width can be negative. If that
* happens, the coordinate of the rendered graphic will be flipped.
* @author Alexis Guéganno, Maxence Laurent
*/
public final class ViewBox extends AbstractSymbolizerNode {
private RealParameter x;
private RealParameter y;
/**
* Build a new {@code ViewBox}, with empty parameters.
*/
public ViewBox() {
setWidth(null);
setHeight(null);
}
/**
* Build a new {@code ViewBox}, using the given width.
*/
public ViewBox(RealParameter width) {
setWidth(width);
}
/**
* Build a new {@code ViewBox} using the given JAXB type.
* @param viewBox
* @throws org.orbisgis.core.renderer.se.SeExceptions.InvalidStyle
*/
public ViewBox(ViewBoxType viewBox) throws InvalidStyle {
if (viewBox.getHeight() != null) {
this.setHeight(SeParameterFactory.createRealParameter(viewBox.getHeight()));
}
if (viewBox.getWidth() != null) {
this.setWidth(SeParameterFactory.createRealParameter(viewBox.getWidth()));
}
}
/**
* A {@code ViewBox} can be used if and only if one, at least, of its two parameters
* has been set.
* @return
*/
public boolean usable() {
return this.x != null || this.y != null;
}
/**
* Set the wifth of this {@code ViewBox}.
* @param width
*/
public void setWidth(RealParameter width) {
x = width;
if (x != null) {
x.setContext(RealParameterContext.REAL_CONTEXT);
x.setParent(this);
}
}
/**
* Get the wifth of this {@code ViewBox}.
* @return
*/
public RealParameter getWidth() {
return x;
//return x == null ? y : x;
}
/**
* Set the height of this {@code ViewBox}.
* @param height
*/
public void setHeight(RealParameter height) {
y = height;
if (y != null) {
y.setContext(RealParameterContext.REAL_CONTEXT);
y.setParent(this);
}
}
/**
* Get the height of this {@code ViewBox}.
* @return
*/
public RealParameter getHeight() {
return y;
//return y == null ? x : y;
}
@Override
public HashSet<String> dependsOnFeature() {
HashSet<String> hs = null;
if (x != null) {
hs = x.dependsOnFeature();
}
if (y != null) {
if(hs == null) {
hs = y.dependsOnFeature();
} else {
hs.addAll(y.dependsOnFeature());
}
}
return hs;
}
@Override
public UsedAnalysis getUsedAnalysis() {
UsedAnalysis ua = new UsedAnalysis();
if(x!=null){
ua.merge(x.getUsedAnalysis());
}
if(y!=null){
ua.merge(y.getUsedAnalysis());
}
return ua;
}
/**
* Return the final dimension described by this view box, in [px].
* @param ds map
* @param ratio required final ratio (if either width or height isn't defined)
* @return
* @throws ParameterException
*/
public Point2D getDimensionInPixel(Map<String,Value> map, double height,
double width, Double scale, Double dpi) throws ParameterException {
double dx, dy;
double ratio = height / width;
if (x != null && y != null) {
dx = x.getValue(map);
dy = y.getValue(map);
} else if (x != null) {
dx = x.getValue(map);
dy = dx * ratio;
} else if (y != null) {
dy = y.getValue(map);
dx = dy / ratio;
} else { // nothing is defined
dx = width;
dy = height;
//return null;
}
dx = Uom.toPixel(dx, ((UomNode)getParent()).getUom(), dpi, scale, width);
dy = Uom.toPixel(dy, ((UomNode)getParent()).getUom(), dpi, scale, height);
if (dx <= 0.00021 || dy <= 0.00021) {
- throw new ParameterException("View-box is too small: (" + dx + ";" + dy + ")");
+ dx=0;
+ dy=0;
}
return new Point2D.Double(dx, dy);
}
/**
* Retrieve this {@code ViewBox} as a JAXB type.
* @return
*/
public ViewBoxType getJAXBType() {
ViewBoxType v = new ViewBoxType();
if (x != null) {
v.setWidth(x.getJAXBParameterValueType());
}
if (y != null) {
v.setHeight(y.getJAXBParameterValueType());
}
return v;
}
/**
* Gets a String representation of this {@code ViewBox}.
* @return
* A String containing the wifth and height of the {@code ViewBox}..
*/
@Override
public String toString() {
String result = "ViewBox:";
if (this.x != null) {
result += " Width: " + x.toString();
}
if (this.y != null) {
result += " Height: " + y.toString();
}
return result;
}
}
| true | true | public Point2D getDimensionInPixel(Map<String,Value> map, double height,
double width, Double scale, Double dpi) throws ParameterException {
double dx, dy;
double ratio = height / width;
if (x != null && y != null) {
dx = x.getValue(map);
dy = y.getValue(map);
} else if (x != null) {
dx = x.getValue(map);
dy = dx * ratio;
} else if (y != null) {
dy = y.getValue(map);
dx = dy / ratio;
} else { // nothing is defined
dx = width;
dy = height;
//return null;
}
dx = Uom.toPixel(dx, ((UomNode)getParent()).getUom(), dpi, scale, width);
dy = Uom.toPixel(dy, ((UomNode)getParent()).getUom(), dpi, scale, height);
if (dx <= 0.00021 || dy <= 0.00021) {
throw new ParameterException("View-box is too small: (" + dx + ";" + dy + ")");
}
return new Point2D.Double(dx, dy);
}
| public Point2D getDimensionInPixel(Map<String,Value> map, double height,
double width, Double scale, Double dpi) throws ParameterException {
double dx, dy;
double ratio = height / width;
if (x != null && y != null) {
dx = x.getValue(map);
dy = y.getValue(map);
} else if (x != null) {
dx = x.getValue(map);
dy = dx * ratio;
} else if (y != null) {
dy = y.getValue(map);
dx = dy / ratio;
} else { // nothing is defined
dx = width;
dy = height;
//return null;
}
dx = Uom.toPixel(dx, ((UomNode)getParent()).getUom(), dpi, scale, width);
dy = Uom.toPixel(dy, ((UomNode)getParent()).getUom(), dpi, scale, height);
if (dx <= 0.00021 || dy <= 0.00021) {
dx=0;
dy=0;
}
return new Point2D.Double(dx, dy);
}
|
diff --git a/core/tern.core.tests/src/tern/server/nodejs/process/PathHelper.java b/core/tern.core.tests/src/tern/server/nodejs/process/PathHelper.java
index c1e88615..46faccb9 100644
--- a/core/tern.core.tests/src/tern/server/nodejs/process/PathHelper.java
+++ b/core/tern.core.tests/src/tern/server/nodejs/process/PathHelper.java
@@ -1,48 +1,48 @@
package tern.server.nodejs.process;
import java.io.File;
public class PathHelper {
/**
* Returns nodejs base dir switch OS.
*
* @return
*/
public static File getNodejsBasedir() {
/*
* String s = "name: " + System.getProperty ("os.name"); s +=
* ", version: " + System.getProperty ("os.version"); s += ", arch: " +
* System.getProperty ("os.arch"); System.out.println ("OS=" + s);
*/
String os =System.getProperty ("osgi.os");
System.out.println("os "+os);
String arch=System.getProperty ("osgi.arch");
System.out.println("arch "+arch);
String ws =System.getProperty ("osgi.ws");
System.out.println("ws "+ws);
//System.out.println(System.getProperties());
- os = "win32";
+ /*os = "win32";
ws = "win32";
- arch = "x86";
+ arch = "x86";*/
// TODO : manage the patch switch OS.
File file= new File(
"../../eclipse/tern.eclipse.ide.server.nodejs.embed."+os+"."+ws+"."+arch+"/nodejs/node-v0.10.22-"+os+"-"+arch);
System.out.println("file path "+file.getAbsolutePath());
System.out.println("file path exists ? "+file.exists());
return file;
}
/**
* Return tern base dir.
*
* @return
*/
public static File getNodejsTernBaseDir() {
return new File("../tern.server.nodejs");
}
}
| false | true | public static File getNodejsBasedir() {
/*
* String s = "name: " + System.getProperty ("os.name"); s +=
* ", version: " + System.getProperty ("os.version"); s += ", arch: " +
* System.getProperty ("os.arch"); System.out.println ("OS=" + s);
*/
String os =System.getProperty ("osgi.os");
System.out.println("os "+os);
String arch=System.getProperty ("osgi.arch");
System.out.println("arch "+arch);
String ws =System.getProperty ("osgi.ws");
System.out.println("ws "+ws);
//System.out.println(System.getProperties());
os = "win32";
ws = "win32";
arch = "x86";
// TODO : manage the patch switch OS.
File file= new File(
"../../eclipse/tern.eclipse.ide.server.nodejs.embed."+os+"."+ws+"."+arch+"/nodejs/node-v0.10.22-"+os+"-"+arch);
System.out.println("file path "+file.getAbsolutePath());
System.out.println("file path exists ? "+file.exists());
return file;
}
| public static File getNodejsBasedir() {
/*
* String s = "name: " + System.getProperty ("os.name"); s +=
* ", version: " + System.getProperty ("os.version"); s += ", arch: " +
* System.getProperty ("os.arch"); System.out.println ("OS=" + s);
*/
String os =System.getProperty ("osgi.os");
System.out.println("os "+os);
String arch=System.getProperty ("osgi.arch");
System.out.println("arch "+arch);
String ws =System.getProperty ("osgi.ws");
System.out.println("ws "+ws);
//System.out.println(System.getProperties());
/*os = "win32";
ws = "win32";
arch = "x86";*/
// TODO : manage the patch switch OS.
File file= new File(
"../../eclipse/tern.eclipse.ide.server.nodejs.embed."+os+"."+ws+"."+arch+"/nodejs/node-v0.10.22-"+os+"-"+arch);
System.out.println("file path "+file.getAbsolutePath());
System.out.println("file path exists ? "+file.exists());
return file;
}
|
diff --git a/src/framework/testng/report/mail/HtmlMailReporter.java b/src/framework/testng/report/mail/HtmlMailReporter.java
index fc209903..14440b27 100644
--- a/src/framework/testng/report/mail/HtmlMailReporter.java
+++ b/src/framework/testng/report/mail/HtmlMailReporter.java
@@ -1,110 +1,110 @@
package framework.testng.report.mail;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import com.gigaspaces.dashboard.DashboardDBReporter;
import framework.report.MailReporterProperties;
import framework.testng.report.wiki.WikiUtils;
import framework.testng.report.xml.SummaryReport;
import framework.tools.SimpleMail;
public class HtmlMailReporter {
public HtmlMailReporter() {
}
public void sendHtmlMailReport(SummaryReport summaryReport, String wikiPageUrl, Properties extProperties) {
String buildNumber = extProperties.getProperty("buildVersion");
String majorVersion = extProperties.getProperty("majorVersion");
String minorVersion = extProperties.getProperty("minorVersion");
String buildLogUrl = extProperties.getProperty("buildLogUrl");
String suiteName = summaryReport.getSuiteName();
List<String> mailRecipients = null;
if (buildNumber == null)
return;
Properties props = new Properties();
InputStream in = this.getClass().getResourceAsStream("mailreporter.properties");
try {
props.load(in);
in.close();
System.out.println("mailreporter.properties: " + props);
} catch (IOException e) {
throw new RuntimeException("failed to read mailreporter.properties file - " + e, e);
}
MailReporterProperties mailProperties = new MailReporterProperties(props);
String link = "<a href=" + wikiPageUrl + ">"
+ buildNumber + " " + majorVersion + " " + minorVersion + " </a>";
StringBuilder sb = new StringBuilder();
sb.append("<html>").append("\n");
sb.append("<h1>SGTest Cloudify Results </h1></br></br></br>").append("\n");
sb.append("<h2>Suite Name: " + summaryReport.getSuiteName() + " </h2></br>").append("\n");
sb.append("<h4>Duration: " + WikiUtils.formatDuration(summaryReport.getDuration()) + " </h4></br>").append("\n");
sb.append("<h4>Full Suite Report: " + link + " </h4></br>").append("\n");
sb.append("<h4>Full build log: " + getFullBuildLog(buildLogUrl) + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:blue\">Total run: " + summaryReport.getTotalTestsRun() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:red\">Failed Tests: " + summaryReport.getFailed() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:green\">Passed Tests: " + summaryReport.getSuccess() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:orange\">Skipped: " + summaryReport.getSkipped() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:coral\">Suspected: " + summaryReport.getSuspected() + " </h4></br>").append("\n");
sb.append("</html>");
try {
mailRecipients = mailProperties.getRecipients();
if (suiteName.contains("webui")) mailRecipients = mailProperties.getWebUIRecipients();
if (suiteName.contains("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
System.out.println("sending mail to recipients: " + mailRecipients);
SimpleMail.send(mailProperties.getMailHost(), mailProperties.getUsername(), mailProperties.getPassword(),
"SGTest Suite " + summaryReport.getSuiteName() + " results " + buildNumber + " " + majorVersion
+ " " + minorVersion, sb.toString(), mailRecipients);
} catch (Exception e) {
throw new RuntimeException("failed to send mail - " + e, e);
}
DashboardDBReporter.writeToDB(summaryReport.getSuiteName(), buildNumber, majorVersion, minorVersion,
summaryReport.getDuration(), buildLogUrl, summaryReport.getTotalTestsRun(), summaryReport.getFailed(),
- summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), link);
+ summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), wikiPageUrl);
}
static String getFullBuildLog(String buildLog) {
StringTokenizer tokenizer = new StringTokenizer(buildLog, "/");
List<String> tokens = new ArrayList<String>();
while (tokenizer.hasMoreTokens()) {
tokens.add(tokenizer.nextToken());
}
return tokens.get(0) + "//" + tokens.get(1) + "/download/" + tokens.get(3) + "/" + tokens.get(2);
}
// /*
// * Test this!
// */
// public static void main(String[] args) {
//
// System.setProperty("sgtest.buildNumber", "1234-123");
// System.setProperty("sgtest.suiteName", "ServiceGrid");
// System.setProperty("sgtest.majorVersion", "9.0.0");
// System.setProperty("sgtest.minorVersion", "m1");
//
// HtmlMailReporter mailReporter = new HtmlMailReporter();
// TestsReport testsReport = TestsReport.newEmptyReport();
// testsReport.setSuiteName("ServiceGrid");
// TestReport report = new TestReport("test");
// report.setDuration(10L);
// testsReport.getReports().add(report);
// SummaryReport summaryReport = new SummaryReport(testsReport);
// mailReporter.sendHtmlMailReport(summaryReport, "some-url");
// }
}
| true | true | public void sendHtmlMailReport(SummaryReport summaryReport, String wikiPageUrl, Properties extProperties) {
String buildNumber = extProperties.getProperty("buildVersion");
String majorVersion = extProperties.getProperty("majorVersion");
String minorVersion = extProperties.getProperty("minorVersion");
String buildLogUrl = extProperties.getProperty("buildLogUrl");
String suiteName = summaryReport.getSuiteName();
List<String> mailRecipients = null;
if (buildNumber == null)
return;
Properties props = new Properties();
InputStream in = this.getClass().getResourceAsStream("mailreporter.properties");
try {
props.load(in);
in.close();
System.out.println("mailreporter.properties: " + props);
} catch (IOException e) {
throw new RuntimeException("failed to read mailreporter.properties file - " + e, e);
}
MailReporterProperties mailProperties = new MailReporterProperties(props);
String link = "<a href=" + wikiPageUrl + ">"
+ buildNumber + " " + majorVersion + " " + minorVersion + " </a>";
StringBuilder sb = new StringBuilder();
sb.append("<html>").append("\n");
sb.append("<h1>SGTest Cloudify Results </h1></br></br></br>").append("\n");
sb.append("<h2>Suite Name: " + summaryReport.getSuiteName() + " </h2></br>").append("\n");
sb.append("<h4>Duration: " + WikiUtils.formatDuration(summaryReport.getDuration()) + " </h4></br>").append("\n");
sb.append("<h4>Full Suite Report: " + link + " </h4></br>").append("\n");
sb.append("<h4>Full build log: " + getFullBuildLog(buildLogUrl) + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:blue\">Total run: " + summaryReport.getTotalTestsRun() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:red\">Failed Tests: " + summaryReport.getFailed() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:green\">Passed Tests: " + summaryReport.getSuccess() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:orange\">Skipped: " + summaryReport.getSkipped() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:coral\">Suspected: " + summaryReport.getSuspected() + " </h4></br>").append("\n");
sb.append("</html>");
try {
mailRecipients = mailProperties.getRecipients();
if (suiteName.contains("webui")) mailRecipients = mailProperties.getWebUIRecipients();
if (suiteName.contains("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
System.out.println("sending mail to recipients: " + mailRecipients);
SimpleMail.send(mailProperties.getMailHost(), mailProperties.getUsername(), mailProperties.getPassword(),
"SGTest Suite " + summaryReport.getSuiteName() + " results " + buildNumber + " " + majorVersion
+ " " + minorVersion, sb.toString(), mailRecipients);
} catch (Exception e) {
throw new RuntimeException("failed to send mail - " + e, e);
}
DashboardDBReporter.writeToDB(summaryReport.getSuiteName(), buildNumber, majorVersion, minorVersion,
summaryReport.getDuration(), buildLogUrl, summaryReport.getTotalTestsRun(), summaryReport.getFailed(),
summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), link);
}
| public void sendHtmlMailReport(SummaryReport summaryReport, String wikiPageUrl, Properties extProperties) {
String buildNumber = extProperties.getProperty("buildVersion");
String majorVersion = extProperties.getProperty("majorVersion");
String minorVersion = extProperties.getProperty("minorVersion");
String buildLogUrl = extProperties.getProperty("buildLogUrl");
String suiteName = summaryReport.getSuiteName();
List<String> mailRecipients = null;
if (buildNumber == null)
return;
Properties props = new Properties();
InputStream in = this.getClass().getResourceAsStream("mailreporter.properties");
try {
props.load(in);
in.close();
System.out.println("mailreporter.properties: " + props);
} catch (IOException e) {
throw new RuntimeException("failed to read mailreporter.properties file - " + e, e);
}
MailReporterProperties mailProperties = new MailReporterProperties(props);
String link = "<a href=" + wikiPageUrl + ">"
+ buildNumber + " " + majorVersion + " " + minorVersion + " </a>";
StringBuilder sb = new StringBuilder();
sb.append("<html>").append("\n");
sb.append("<h1>SGTest Cloudify Results </h1></br></br></br>").append("\n");
sb.append("<h2>Suite Name: " + summaryReport.getSuiteName() + " </h2></br>").append("\n");
sb.append("<h4>Duration: " + WikiUtils.formatDuration(summaryReport.getDuration()) + " </h4></br>").append("\n");
sb.append("<h4>Full Suite Report: " + link + " </h4></br>").append("\n");
sb.append("<h4>Full build log: " + getFullBuildLog(buildLogUrl) + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:blue\">Total run: " + summaryReport.getTotalTestsRun() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:red\">Failed Tests: " + summaryReport.getFailed() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:green\">Passed Tests: " + summaryReport.getSuccess() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:orange\">Skipped: " + summaryReport.getSkipped() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:coral\">Suspected: " + summaryReport.getSuspected() + " </h4></br>").append("\n");
sb.append("</html>");
try {
mailRecipients = mailProperties.getRecipients();
if (suiteName.contains("webui")) mailRecipients = mailProperties.getWebUIRecipients();
if (suiteName.contains("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
System.out.println("sending mail to recipients: " + mailRecipients);
SimpleMail.send(mailProperties.getMailHost(), mailProperties.getUsername(), mailProperties.getPassword(),
"SGTest Suite " + summaryReport.getSuiteName() + " results " + buildNumber + " " + majorVersion
+ " " + minorVersion, sb.toString(), mailRecipients);
} catch (Exception e) {
throw new RuntimeException("failed to send mail - " + e, e);
}
DashboardDBReporter.writeToDB(summaryReport.getSuiteName(), buildNumber, majorVersion, minorVersion,
summaryReport.getDuration(), buildLogUrl, summaryReport.getTotalTestsRun(), summaryReport.getFailed(),
summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), wikiPageUrl);
}
|
diff --git a/libraries/javalib/java/io/ObjectInputStream.java b/libraries/javalib/java/io/ObjectInputStream.java
index 30f6ac5c2..4857e068e 100644
--- a/libraries/javalib/java/io/ObjectInputStream.java
+++ b/libraries/javalib/java/io/ObjectInputStream.java
@@ -1,1925 +1,1930 @@
/* ObjectInputStream.java -- Class used to read serialized objects
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. 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
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.io;
import gnu.classpath.Configuration;
import gnu.java.io.ObjectIdentityWrapper;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
public class ObjectInputStream extends InputStream
implements ObjectInput, ObjectStreamConstants
{
/**
* Creates a new <code>ObjectInputStream</code> that will do all of
* its reading from <code>in</code>. This method also checks
* the stream by reading the header information (stream magic number
* and stream version).
*
* @exception IOException Reading stream header from underlying
* stream cannot be completed.
*
* @exception StreamCorruptedException An invalid stream magic
* number or stream version was read from the stream.
*
* @see #readStreamHeader()
*/
public ObjectInputStream(InputStream in)
throws IOException, StreamCorruptedException
{
if (Configuration.DEBUG)
{
String val = System.getProperty("gcj.dumpobjects");
if (dump == false && val != null && !val.equals(""))
{
dump = true;
System.out.println ("Serialization debugging enabled");
}
else if (dump == true && (val == null || val.equals("")))
{
dump = false;
System.out.println ("Serialization debugging disabled");
}
}
this.resolveEnabled = false;
this.isDeserializing = false;
this.blockDataPosition = 0;
this.blockDataBytes = 0;
this.blockData = new byte[BUFFER_SIZE];
this.blockDataInput = new DataInputStream(this);
this.realInputStream = new DataInputStream(in);
this.nextOID = baseWireHandle;
this.objectLookupTable = new Hashtable();
this.validators = new Vector();
this.classLookupTable = new Hashtable();
setBlockDataMode(true);
readStreamHeader();
}
/**
* Returns the next deserialized object read from the underlying stream.
*
* This method can be overriden by a class by implementing
* <code>private void readObject (ObjectInputStream)</code>.
*
* If an exception is thrown from this method, the stream is left in
* an undefined state.
*
* @exception ClassNotFoundException The class that an object being
* read in belongs to cannot be found.
*
* @exception IOException Exception from underlying
* <code>InputStream</code>.
*/
public final Object readObject() throws ClassNotFoundException, IOException
{
if (this.useSubclassMethod)
return readObjectOverride();
boolean was_deserializing;
Object ret_val;
was_deserializing = this.isDeserializing;
boolean is_consumed = false;
boolean old_mode = setBlockDataMode(false);
this.isDeserializing = true;
byte marker = this.realInputStream.readByte();
depth += 2;
if(dump) dumpElement("MARKER: 0x" + Integer.toHexString(marker) + " ");
try
{
switch (marker)
{
case TC_ENDBLOCKDATA:
{
ret_val = null;
is_consumed = true;
break;
}
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
{
if (marker == TC_BLOCKDATALONG)
{ if(dump) dumpElementln("BLOCKDATALONG"); }
else
{ if(dump) dumpElementln("BLOCKDATA"); }
readNextBlock(marker);
throw new StreamCorruptedException("Unexpected blockData");
}
case TC_NULL:
{
if(dump) dumpElementln("NULL");
ret_val = null;
break;
}
case TC_REFERENCE:
{
if(dump) dumpElement("REFERENCE ");
Integer oid = new Integer(this.realInputStream.readInt());
if(dump) dumpElementln(Integer.toHexString(oid.intValue()));
ret_val = ((ObjectIdentityWrapper)
this.objectLookupTable.get(oid)).object;
break;
}
case TC_CLASS:
{
if(dump) dumpElementln("CLASS");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
assignNewHandle(clazz);
ret_val = clazz;
break;
}
case TC_PROXYCLASSDESC:
{
if(dump) dumpElementln("PROXYCLASS");
int n_intf = this.realInputStream.readInt();
String[] intfs = new String[n_intf];
for (int i = 0; i < n_intf; i++)
{
intfs[i] = this.realInputStream.readUTF();
System.out.println(intfs[i]);
}
boolean oldmode = setBlockDataMode(true);
Class cl = resolveProxyClass(intfs);
setBlockDataMode(oldmode);
ObjectStreamClass osc = lookupClass(cl);
assignNewHandle(osc);
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
ObjectStreamClass superosc = (ObjectStreamClass)readObject();
osc.setSuperclass(superosc);
ret_val = osc;
break;
}
case TC_CLASSDESC:
{
ObjectStreamClass osc = readClassDescriptor();
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
osc.setSuperclass ((ObjectStreamClass)readObject());
ret_val = osc;
break;
}
case TC_STRING:
case TC_LONGSTRING:
{
if(dump) dumpElement("STRING=");
String s = this.realInputStream.readUTF();
if(dump) dumpElementln(s);
ret_val = processResolution(null, s, assignNewHandle(s));
break;
}
case TC_ARRAY:
{
if(dump) dumpElementln("ARRAY");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class componentType = osc.forClass().getComponentType();
if(dump) dumpElement("ARRAY LENGTH=");
int length = this.realInputStream.readInt();
if(dump) dumpElementln (length + "; COMPONENT TYPE=" + componentType);
Object array = Array.newInstance(componentType, length);
int handle = assignNewHandle(array);
readArrayElements(array, componentType);
if(dump)
for (int i = 0, len = Array.getLength(array); i < len; i++)
dumpElementln(" ELEMENT[" + i + "]=" + Array.get(array, i));
ret_val = processResolution(null, array, handle);
break;
}
case TC_OBJECT:
{
if(dump) dumpElementln("OBJECT");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
if (!osc.realClassIsSerializable)
throw new NotSerializableException
(clazz + " is not Serializable, and thus cannot be deserialized.");
if (osc.realClassIsExternalizable)
{
Externalizable obj = osc.newInstance();
int handle = assignNewHandle(obj);
boolean read_from_blocks = ((osc.getFlags() & SC_BLOCK_DATA) != 0);
boolean oldmode = this.readDataFromBlock;
if (read_from_blocks)
setBlockDataMode(true);
obj.readExternal(this);
if (read_from_blocks)
- setBlockDataMode(oldmode);
+ {
+ setBlockDataMode(oldmode);
+ if (!oldmode)
+ if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
+ throw new IOException("No end of block data seen for class with readExternal (ObjectInputStream) method.");
+ }
ret_val = processResolution(osc, obj, handle);
break;
} // end if (osc.realClassIsExternalizable)
Object obj = newObject(clazz, osc.firstNonSerializableParentConstructor);
int handle = assignNewHandle(obj);
Object prevObject = this.currentObject;
ObjectStreamClass prevObjectStreamClass = this.currentObjectStreamClass;
this.currentObject = obj;
ObjectStreamClass[] hierarchy =
inputGetObjectStreamClasses(clazz);
for (int i = 0; i < hierarchy.length; i++)
{
this.currentObjectStreamClass = hierarchy[i];
if(dump) dumpElementln("Reading fields of " + this.currentObjectStreamClass.getName ());
// XXX: should initialize fields in classes in the hierarchy
// that aren't in the stream
// should skip over classes in the stream that aren't in the
// real classes hierarchy
Method readObjectMethod = this.currentObjectStreamClass.readObjectMethod;
if (readObjectMethod != null)
{
fieldsAlreadyRead = false;
boolean oldmode = setBlockDataMode(true);
callReadMethod(readObjectMethod, this.currentObjectStreamClass.forClass(), obj);
setBlockDataMode(oldmode);
}
else
{
readFields(obj, currentObjectStreamClass);
}
if (this.currentObjectStreamClass.hasWriteMethod())
{
if(dump) dumpElement("ENDBLOCKDATA? ");
try
{
// FIXME: XXX: This try block is to
// catch EOF which is thrown for some
// objects. That indicates a bug in
// the logic.
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException
("No end of block data seen for class with readObject (ObjectInputStream) method.");
if(dump) dumpElementln("yes");
}
// catch (EOFException e)
// {
// if(dump) dumpElementln("no, got EOFException");
// }
catch (IOException e)
{
if(dump) dumpElementln("no, got IOException");
}
}
}
this.currentObject = prevObject;
this.currentObjectStreamClass = prevObjectStreamClass;
ret_val = processResolution(osc, obj, handle);
break;
}
case TC_RESET:
if(dump) dumpElementln("RESET");
clearHandles();
ret_val = readObject();
break;
case TC_EXCEPTION:
{
if(dump) dumpElement("EXCEPTION=");
Exception e = (Exception)readObject();
if(dump) dumpElementln(e.toString());
clearHandles();
throw new WriteAbortedException("Exception thrown during writing of stream", e);
}
default:
throw new IOException("Unknown marker on stream: " + marker);
}
}
finally
{
setBlockDataMode(old_mode);
this.isDeserializing = was_deserializing;
depth -= 2;
if (! was_deserializing)
{
if (validators.size() > 0)
invokeValidators();
}
}
return ret_val;
}
/**
* This method makes a partial check of types for the fields
* contained given in arguments. It checks primitive types of
* fields1 against non primitive types of fields2. This method
* assumes the two lists has already been sorted according to
* the Java specification.
*
* @param name Name of the class owning the given fields.
* @param fields1 First list to check.
* @param fields2 Second list to check.
* @throws InvalidClassException if a field in fields1, which has a primitive type, is a present
* in the non primitive part in fields2.
*/
private void checkTypeConsistency(String name, ObjectStreamField[] fields1, ObjectStreamField[] fields2)
throws InvalidClassException
{
int nonPrimitive = 0;
for (nonPrimitive = 0;
nonPrimitive < fields1.length
&& fields1[nonPrimitive].isPrimitive(); nonPrimitive++)
{
}
if (nonPrimitive == fields1.length)
return;
int i = 0;
ObjectStreamField f1;
ObjectStreamField f2;
while (i < fields2.length
&& nonPrimitive < fields1.length)
{
f1 = fields1[nonPrimitive];
f2 = fields2[i];
if (!f2.isPrimitive())
break;
int compVal = f1.getName().compareTo (f2.getName());
if (compVal < 0)
{
nonPrimitive++;
}
else if (compVal > 0)
{
i++;
}
else
{
throw new InvalidClassException
("invalid field type for " + f2.getName() +
" in class " + name);
}
}
}
/**
* This method reads a class descriptor from the real input stream
* and use these data to create a new instance of ObjectStreamClass.
* Fields are sorted and ordered for the real read which occurs for
* each instance of the described class. Be aware that if you call that
* method you must ensure that the stream is synchronized, in the other
* case it may be completely desynchronized.
*
* @return A new instance of ObjectStreamClass containing the freshly
* created descriptor.
* @throws ClassNotFoundException if the required class to build the
* descriptor has not been found in the system.
* @throws IOException An input/output error occured.
* @throws InvalidClassException If there was a compatibility problem
* between the class present in the system and the serialized class.
*/
protected ObjectStreamClass readClassDescriptor()
throws ClassNotFoundException, IOException
{
if(dump) dumpElement("CLASSDESC NAME=");
String name = this.realInputStream.readUTF();
if(dump) dumpElement(name + "; UID=");
long uid = this.realInputStream.readLong ();
if(dump) dumpElement(Long.toHexString(uid) + "; FLAGS=");
byte flags = this.realInputStream.readByte ();
if(dump) dumpElement(Integer.toHexString(flags) + "; FIELD COUNT=");
short field_count = this.realInputStream.readShort();
if(dump) dumpElementln(Short.toString(field_count));
ObjectStreamField[] fields = new ObjectStreamField[field_count];
ObjectStreamClass osc = new ObjectStreamClass(name, uid,
flags, fields);
assignNewHandle(osc);
ClassLoader currentLoader = currentLoader();
for (int i = 0; i < field_count; i++)
{
if(dump) dumpElement(" TYPE CODE=");
char type_code = (char)this.realInputStream.readByte();
if(dump) dumpElement(type_code + "; FIELD NAME=");
String field_name = this.realInputStream.readUTF();
if(dump) dumpElementln(field_name);
String class_name;
// If the type code is an array or an object we must
// decode a String here. In the other case we convert
// the type code and pass it to ObjectStreamField.
// Type codes are decoded by gnu.java.lang.reflect.TypeSignature.
if (type_code == 'L' || type_code == '[')
class_name = (String)readObject();
else
class_name = String.valueOf(type_code);
fields[i] =
new ObjectStreamField(field_name, class_name, currentLoader);
}
/* Now that fields have been read we may resolve the class
* (and read annotation if needed). */
Class clazz = resolveClass(osc);
boolean oldmode = setBlockDataMode(true);
osc.setClass(clazz, lookupClass(clazz.getSuperclass()));
classLookupTable.put(clazz, osc);
setBlockDataMode(oldmode);
// find the first non-serializable, non-abstract
// class in clazz's inheritance hierarchy
Class first_nonserial = clazz.getSuperclass();
while (Serializable.class.isAssignableFrom(first_nonserial)
|| Modifier.isAbstract(first_nonserial.getModifiers()))
first_nonserial = first_nonserial.getSuperclass();
final Class local_constructor_class = first_nonserial;
osc.firstNonSerializableParentConstructor =
(Constructor)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
Constructor c = local_constructor_class.
getDeclaredConstructor(new Class[0]);
if (Modifier.isPrivate(c.getModifiers()))
return null;
return c;
}
catch (NoSuchMethodException e)
{
// error will be reported later, in newObject()
return null;
}
}
});
osc.realClassIsSerializable = Serializable.class.isAssignableFrom(clazz);
osc.realClassIsExternalizable = Externalizable.class.isAssignableFrom(clazz);
ObjectStreamField[] stream_fields = osc.fields;
ObjectStreamField[] real_fields = ObjectStreamClass.lookup(clazz).fields;
ObjectStreamField[] fieldmapping = new ObjectStreamField[2 * Math.max(stream_fields.length, real_fields.length)];
int stream_idx = 0;
int real_idx = 0;
int map_idx = 0;
/*
* Check that there is no type inconsistencies between the lists.
* A special checking must be done for the two groups: primitive types and
* not primitive types.
*/
checkTypeConsistency(name, real_fields, stream_fields);
checkTypeConsistency(name, stream_fields, real_fields);
while (stream_idx < stream_fields.length
|| real_idx < real_fields.length)
{
ObjectStreamField stream_field = null;
ObjectStreamField real_field = null;
if (stream_idx == stream_fields.length)
{
real_field = real_fields[real_idx++];
}
else if (real_idx == real_fields.length)
{
stream_field = stream_fields[stream_idx++];
}
else
{
int comp_val =
real_fields[real_idx].compareTo (stream_fields[stream_idx]);
if (comp_val < 0)
{
real_field = real_fields[real_idx++];
}
else if (comp_val > 0)
{
stream_field = stream_fields[stream_idx++];
}
else
{
stream_field = stream_fields[stream_idx++];
real_field = real_fields[real_idx++];
if (stream_field.getType() != real_field.getType())
throw new InvalidClassException
("invalid field type for " + real_field.getName() +
" in class " + name);
}
}
/* If some of stream_fields does not correspond to any of real_fields,
* or the opposite, then fieldmapping will go short.
*/
if (map_idx == fieldmapping.length)
{
ObjectStreamField[] newfieldmapping =
new ObjectStreamField[fieldmapping.length + 2];
System.arraycopy(fieldmapping, 0,
newfieldmapping, 0, fieldmapping.length);
fieldmapping = newfieldmapping;
}
fieldmapping[map_idx++] = stream_field;
fieldmapping[map_idx++] = real_field;
}
osc.fieldMapping = fieldmapping;
return osc;
}
/**
* Reads the current objects non-transient, non-static fields from
* the current class from the underlying output stream.
*
* This method is intended to be called from within a object's
* <code>private void readObject (ObjectInputStream)</code>
* method.
*
* @exception ClassNotFoundException The class that an object being
* read in belongs to cannot be found.
*
* @exception NotActiveException This method was called from a
* context other than from the current object's and current class's
* <code>private void readObject (ObjectInputStream)</code>
* method.
*
* @exception IOException Exception from underlying
* <code>OutputStream</code>.
*/
public void defaultReadObject()
throws ClassNotFoundException, IOException, NotActiveException
{
if (this.currentObject == null || this.currentObjectStreamClass == null)
throw new NotActiveException("defaultReadObject called by non-active"
+ " class and/or object");
if (fieldsAlreadyRead)
throw new NotActiveException("defaultReadObject called but fields "
+ "already read from stream (by "
+ "defaultReadObject or readFields)");
boolean oldmode = setBlockDataMode(false);
readFields(this.currentObject, this.currentObjectStreamClass);
setBlockDataMode(oldmode);
fieldsAlreadyRead = true;
}
/**
* Registers a <code>ObjectInputValidation</code> to be carried out
* on the object graph currently being deserialized before it is
* returned to the original caller of <code>readObject ()</code>.
* The order of validation for multiple
* <code>ObjectInputValidation</code>s can be controled using
* <code>priority</code>. Validators with higher priorities are
* called first.
*
* @see java.io.ObjectInputValidation
*
* @exception InvalidObjectException <code>validator</code> is
* <code>null</code>
*
* @exception NotActiveException an attempt was made to add a
* validator outside of the <code>readObject</code> method of the
* object currently being deserialized
*/
public void registerValidation(ObjectInputValidation validator,
int priority)
throws InvalidObjectException, NotActiveException
{
if (this.currentObject == null || this.currentObjectStreamClass == null)
throw new NotActiveException("registerValidation called by non-active "
+ "class and/or object");
if (validator == null)
throw new InvalidObjectException("attempt to add a null "
+ "ObjectInputValidation object");
this.validators.addElement(new ValidatorAndPriority (validator,
priority));
}
/**
* Called when a class is being deserialized. This is a hook to
* allow subclasses to read in information written by the
* <code>annotateClass (Class)</code> method of an
* <code>ObjectOutputStream</code>.
*
* This implementation looks up the active call stack for a
* <code>ClassLoader</code>; if a <code>ClassLoader</code> is found,
* it is used to load the class associated with <code>osc</code>,
* otherwise, the default system <code>ClassLoader</code> is used.
*
* @exception IOException Exception from underlying
* <code>OutputStream</code>.
*
* @see java.io.ObjectOutputStream#annotateClass (java.lang.Class)
*/
protected Class resolveClass(ObjectStreamClass osc)
throws ClassNotFoundException, IOException
{
return Class.forName(osc.getName(), true, currentLoader());
}
/**
* This method invokes the method currentClassLoader for the
* current security manager (or build an empty one if it is not
* present).
*
* @return The most recent non-system ClassLoader on the execution stack.
* @see java.lang.SecurityManager#currentClassLoader()
*/
private ClassLoader currentLoader()
{
SecurityManager sm = System.getSecurityManager();
if (sm == null)
sm = new SecurityManager () {};
return currentClassLoader(sm);
}
/**
* Lookup a class stored in the local hashtable. If it is not
* use the global lookup function in ObjectStreamClass to build
* the ObjectStreamClass. This method is requested according to
* the behaviour detected in the JDK by Kaffe's team.
*
* @param clazz Class to lookup in the hash table or for which
* we must build a descriptor.
* @return A valid instance of ObjectStreamClass corresponding
* to the specified class.
*/
private ObjectStreamClass lookupClass(Class clazz)
{
ObjectStreamClass oclazz;
oclazz = (ObjectStreamClass)classLookupTable.get(clazz);
if (oclazz == null)
return ObjectStreamClass.lookup(clazz);
else
return oclazz;
}
/**
* Reconstruct class hierarchy the same way
* {@link java.io.ObjectStreamClass.getObjectStreamClasses(java.lang.Class)} does
* but using lookupClass instead of ObjectStreamClass.lookup. This
* dup is necessary localize the lookup table. Hopefully some future
* rewritings will be able to prevent this.
*
* @param clazz This is the class for which we want the hierarchy.
*
* @return An array of valid {@link java.io.ObjectStreamClass} instances which
* represent the class hierarchy for clazz.
*/
private ObjectStreamClass[] inputGetObjectStreamClasses(Class clazz)
{
ObjectStreamClass osc = lookupClass(clazz);
if (osc == null)
return new ObjectStreamClass[0];
else
{
Vector oscs = new Vector();
while (osc != null)
{
oscs.addElement(osc);
osc = osc.getSuper();
}
int count = oscs.size();
ObjectStreamClass[] sorted_oscs = new ObjectStreamClass[count];
for (int i = count - 1; i >= 0; i--)
sorted_oscs[count - i - 1] = (ObjectStreamClass) oscs.elementAt(i);
return sorted_oscs;
}
}
/**
* Allows subclasses to resolve objects that are read from the
* stream with other objects to be returned in their place. This
* method is called the first time each object is encountered.
*
* This method must be enabled before it will be called in the
* serialization process.
*
* @exception IOException Exception from underlying
* <code>OutputStream</code>.
*
* @see #enableResolveObject(boolean)
*/
protected Object resolveObject(Object obj) throws IOException
{
return obj;
}
protected Class resolveProxyClass(String[] intfs)
throws IOException, ClassNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm == null)
sm = new SecurityManager() {};
ClassLoader cl = currentClassLoader(sm);
Class[] clss = new Class[intfs.length];
if(cl == null)
{
for (int i = 0; i < intfs.length; i++)
clss[i] = Class.forName(intfs[i]);
cl = ClassLoader.getSystemClassLoader();
}
else
for (int i = 0; i < intfs.length; i++)
clss[i] = cl.loadClass(intfs[i]);
try
{
return Proxy.getProxyClass(cl, clss);
}
catch (IllegalArgumentException e)
{
throw new ClassNotFoundException(null, e);
}
}
/**
* If <code>enable</code> is <code>true</code> and this object is
* trusted, then <code>resolveObject (Object)</code> will be called
* in subsequent calls to <code>readObject (Object)</code>.
* Otherwise, <code>resolveObject (Object)</code> will not be called.
*
* @exception SecurityException This class is not trusted.
*/
protected boolean enableResolveObject (boolean enable)
throws SecurityException
{
if (enable)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new SerializablePermission("enableSubstitution"));
}
boolean old_val = this.resolveEnabled;
this.resolveEnabled = enable;
return old_val;
}
/**
* Reads stream magic and stream version information from the
* underlying stream.
*
* @exception IOException Exception from underlying stream.
*
* @exception StreamCorruptedException An invalid stream magic
* number or stream version was read from the stream.
*/
protected void readStreamHeader()
throws IOException, StreamCorruptedException
{
if(dump) dumpElement("STREAM MAGIC ");
if (this.realInputStream.readShort() != STREAM_MAGIC)
throw new StreamCorruptedException("Invalid stream magic number");
if(dump) dumpElementln("STREAM VERSION ");
if (this.realInputStream.readShort() != STREAM_VERSION)
throw new StreamCorruptedException("Invalid stream version number");
}
public int read() throws IOException
{
if (this.readDataFromBlock)
{
if (this.blockDataPosition >= this.blockDataBytes)
readNextBlock();
return (this.blockData[this.blockDataPosition++] & 0xff);
}
else
return this.realInputStream.read();
}
public int read(byte[] data, int offset, int length) throws IOException
{
if (this.readDataFromBlock)
{
if (this.blockDataPosition + length > this.blockDataBytes)
{
int remain = this.blockDataBytes - this.blockDataPosition;
if (remain != 0)
{
System.arraycopy(this.blockData, this.blockDataPosition,
data, offset, remain);
offset += remain;
length -= remain;
}
readNextBlock ();
}
System.arraycopy(this.blockData, this.blockDataPosition,
data, offset, length);
this.blockDataPosition += length;
return length;
}
else
return this.realInputStream.read(data, offset, length);
}
public int available() throws IOException
{
if (this.readDataFromBlock)
{
if (this.blockDataPosition >= this.blockDataBytes)
readNextBlock ();
return this.blockDataBytes - this.blockDataPosition;
}
else
return this.realInputStream.available();
}
public void close() throws IOException
{
this.realInputStream.close();
}
public boolean readBoolean() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 1)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode (true);
boolean value = this.dataInputStream.readBoolean ();
if (switchmode)
setBlockDataMode (oldmode);
return value;
}
public byte readByte() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 1)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
byte value = this.dataInputStream.readByte();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public int readUnsignedByte() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 1)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
int value = this.dataInputStream.readUnsignedByte();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public short readShort() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 2)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
short value = this.dataInputStream.readShort();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public int readUnsignedShort() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 2)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
int value = this.dataInputStream.readUnsignedShort();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public char readChar() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 2)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
char value = this.dataInputStream.readChar();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public int readInt() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 4)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
int value = this.dataInputStream.readInt();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public long readLong() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 8)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
long value = this.dataInputStream.readLong();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public float readFloat() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 4)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
float value = this.dataInputStream.readFloat();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public double readDouble() throws IOException
{
boolean switchmode = true;
boolean oldmode = this.readDataFromBlock;
if (!oldmode || this.blockDataBytes - this.blockDataPosition >= 8)
switchmode = false;
if (switchmode)
oldmode = setBlockDataMode(true);
double value = this.dataInputStream.readDouble();
if (switchmode)
setBlockDataMode(oldmode);
return value;
}
public void readFully(byte data[]) throws IOException
{
this.dataInputStream.readFully(data);
}
public void readFully(byte data[], int offset, int size)
throws IOException
{
this.dataInputStream.readFully(data, offset, size);
}
public int skipBytes(int len) throws IOException
{
return this.dataInputStream.skipBytes(len);
}
/**
* @deprecated
* @see java.io.DataInputStream#readLine ()
*/
public String readLine() throws IOException
{
return this.dataInputStream.readLine();
}
public String readUTF() throws IOException
{
return this.dataInputStream.readUTF();
}
/**
* This class allows a class to specify exactly which fields should
* be read, and what values should be read for these fields.
*
* XXX: finish up comments
*/
public abstract static class GetField
{
public abstract ObjectStreamClass getObjectStreamClass();
public abstract boolean defaulted(String name)
throws IOException, IllegalArgumentException;
public abstract boolean get(String name, boolean defvalue)
throws IOException, IllegalArgumentException;
public abstract char get(String name, char defvalue)
throws IOException, IllegalArgumentException;
public abstract byte get(String name, byte defvalue)
throws IOException, IllegalArgumentException;
public abstract short get(String name, short defvalue)
throws IOException, IllegalArgumentException;
public abstract int get(String name, int defvalue)
throws IOException, IllegalArgumentException;
public abstract long get(String name, long defvalue)
throws IOException, IllegalArgumentException;
public abstract float get(String name, float defvalue)
throws IOException, IllegalArgumentException;
public abstract double get(String name, double defvalue)
throws IOException, IllegalArgumentException;
public abstract Object get(String name, Object defvalue)
throws IOException, IllegalArgumentException;
}
/**
* This method should be called by a method called 'readObject' in the
* deserializing class (if present). It cannot (and should not)be called
* outside of it. Its goal is to read all fields in the real input stream
* and keep them accessible through the {@link #GetField} class. Calling
* this method will not alter the deserializing object.
*
* @return A valid freshly created 'GetField' instance to get access to
* the deserialized stream.
* @throws IOException An input/output exception occured.
* @throws ClassNotFoundException
* @throws NotActiveException
*/
public GetField readFields()
throws IOException, ClassNotFoundException, NotActiveException
{
if (this.currentObject == null || this.currentObjectStreamClass == null)
throw new NotActiveException("readFields called by non-active class and/or object");
if (prereadFields != null)
return prereadFields;
if (fieldsAlreadyRead)
throw new NotActiveException("readFields called but fields already read from"
+ " stream (by defaultReadObject or readFields)");
final ObjectStreamClass clazz = this.currentObjectStreamClass;
final byte[] prim_field_data = new byte[clazz.primFieldSize];
final Object[] objs = new Object[clazz.objectFieldCount];
// Apparently Block data is not used with GetField as per
// empirical evidence against JDK 1.2. Also see Mauve test
// java.io.ObjectInputOutput.Test.GetPutField.
boolean oldmode = setBlockDataMode(false);
readFully(prim_field_data);
for (int i = 0; i < objs.length; ++ i)
objs[i] = readObject();
setBlockDataMode(oldmode);
prereadFields = new GetField()
{
public ObjectStreamClass getObjectStreamClass()
{
return clazz;
}
public boolean defaulted(String name)
throws IOException, IllegalArgumentException
{
ObjectStreamField f = clazz.getField(name);
/* First if we have a serialized field use the descriptor */
if (f != null)
{
/* It is in serialPersistentFields but setClass tells us
* it should not be set. This value is defaulted.
*/
if (f.isPersistent() && !f.isToSet())
return true;
return false;
}
/* This is not a serialized field. There should be
* a default value only if the field really exists.
*/
try
{
return (clazz.forClass().getDeclaredField (name) != null);
}
catch (NoSuchFieldException e)
{
throw new IllegalArgumentException(e.getMessage());
}
}
public boolean get(String name, boolean defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Boolean.TYPE);
if (field == null)
return defvalue;
return prim_field_data[field.getOffset()] == 0 ? false : true;
}
public char get(String name, char defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Character.TYPE);
if (field == null)
return defvalue;
int off = field.getOffset();
return (char)(((prim_field_data[off++] & 0xFF) << 8)
| (prim_field_data[off] & 0xFF));
}
public byte get(String name, byte defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Byte.TYPE);
if (field == null)
return defvalue;
return prim_field_data[field.getOffset()];
}
public short get(String name, short defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Short.TYPE);
if (field == null)
return defvalue;
int off = field.getOffset();
return (short)(((prim_field_data[off++] & 0xFF) << 8)
| (prim_field_data[off] & 0xFF));
}
public int get(String name, int defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Integer.TYPE);
if (field == null)
return defvalue;
int off = field.getOffset();
return ((prim_field_data[off++] & 0xFF) << 24)
| ((prim_field_data[off++] & 0xFF) << 16)
| ((prim_field_data[off++] & 0xFF) << 8)
| (prim_field_data[off] & 0xFF);
}
public long get(String name, long defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Long.TYPE);
if (field == null)
return defvalue;
int off = field.getOffset();
return (long)(((prim_field_data[off++] & 0xFFL) << 56)
| ((prim_field_data[off++] & 0xFFL) << 48)
| ((prim_field_data[off++] & 0xFFL) << 40)
| ((prim_field_data[off++] & 0xFFL) << 32)
| ((prim_field_data[off++] & 0xFF) << 24)
| ((prim_field_data[off++] & 0xFF) << 16)
| ((prim_field_data[off++] & 0xFF) << 8)
| (prim_field_data[off] & 0xFF));
}
public float get(String name, float defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Float.TYPE);
if (field == null)
return defvalue;
int off = field.getOffset();
return Float.intBitsToFloat(((prim_field_data[off++] & 0xFF) << 24)
| ((prim_field_data[off++] & 0xFF) << 16)
| ((prim_field_data[off++] & 0xFF) << 8)
| (prim_field_data[off] & 0xFF));
}
public double get(String name, double defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field = getField(name, Double.TYPE);
if (field == null)
return defvalue;
int off = field.getOffset();
return Double.longBitsToDouble
( (long) (((prim_field_data[off++] & 0xFFL) << 56)
| ((prim_field_data[off++] & 0xFFL) << 48)
| ((prim_field_data[off++] & 0xFFL) << 40)
| ((prim_field_data[off++] & 0xFFL) << 32)
| ((prim_field_data[off++] & 0xFF) << 24)
| ((prim_field_data[off++] & 0xFF) << 16)
| ((prim_field_data[off++] & 0xFF) << 8)
| (prim_field_data[off] & 0xFF)));
}
public Object get(String name, Object defvalue)
throws IOException, IllegalArgumentException
{
ObjectStreamField field =
getField(name, defvalue == null ? null : defvalue.getClass ());
if (field == null)
return defvalue;
return objs[field.getOffset()];
}
private ObjectStreamField getField(String name, Class type)
throws IllegalArgumentException
{
ObjectStreamField field = clazz.getField(name);
boolean illegal = false;
try
{
try
{
Class field_type = field.getType();
if (type == field_type ||
(type == null && !field_type.isPrimitive()))
{
/* See defaulted */
return field;
}
illegal = true;
throw new IllegalArgumentException
("Field requested is of type "
+ field_type.getName()
+ ", but requested type was "
+ (type == null ? "Object" : type.getName()));
}
catch (NullPointerException _)
{
/* Here we catch NullPointerException, because it may
only come from the call 'field.getType()'. If field
is null, we have to return null and classpath ethic
say we must try to avoid 'if (xxx == null)'.
*/
}
catch (IllegalArgumentException e)
{
throw e;
}
return null;
}
finally
{
/* If this is an unassigned field we should return
* the default value.
*/
if (!illegal && field != null && !field.isToSet() && field.isPersistent())
return null;
/* We do not want to modify transient fields. They should
* be left to 0.
*/
try
{
Field f = clazz.forClass().getDeclaredField(name);
if (Modifier.isTransient(f.getModifiers()))
throw new IllegalArgumentException
("no such field (non transient) " + name);
if (field == null && f.getType() != type)
throw new IllegalArgumentException
("Invalid requested type for field " + name);
}
catch (NoSuchFieldException e)
{
if (field == null)
throw new IllegalArgumentException(e.getMessage());
}
}
}
};
fieldsAlreadyRead = true;
return prereadFields;
}
/**
* Protected constructor that allows subclasses to override
* deserialization. This constructor should be called by subclasses
* that wish to override <code>readObject (Object)</code>. This
* method does a security check <i>NOTE: currently not
* implemented</i>, then sets a flag that informs
* <code>readObject (Object)</code> to call the subclasses
* <code>readObjectOverride (Object)</code> method.
*
* @see #readObjectOverride()
*/
protected ObjectInputStream()
throws IOException, SecurityException
{
SecurityManager sec_man = System.getSecurityManager();
if (sec_man != null)
sec_man.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
this.useSubclassMethod = true;
}
/**
* This method allows subclasses to override the default
* de serialization mechanism provided by
* <code>ObjectInputStream</code>. To make this method be used for
* writing objects, subclasses must invoke the 0-argument
* constructor on this class from their constructor.
*
* @see #ObjectInputStream()
*/
protected Object readObjectOverride()
throws ClassNotFoundException, IOException, OptionalDataException
{
throw new IOException("Subclass of ObjectInputStream must implement readObjectOverride");
}
/**
* Assigns the next available handle to <code>obj</code>.
*
* @param obj The object for which we want a new handle.
* @return A valid handle for the specified object.
*/
private int assignNewHandle(Object obj)
{
this.objectLookupTable.put(new Integer(this.nextOID),
new ObjectIdentityWrapper(obj));
return this.nextOID++;
}
private Object processResolution(ObjectStreamClass osc, Object obj, int handle)
throws IOException
{
if (osc != null && obj instanceof Serializable)
{
try
{
Method m = osc.readResolveMethod;
if(m != null)
{
obj = m.invoke(obj, new Object[] {});
}
}
catch (IllegalAccessException ignore)
{
}
catch (InvocationTargetException ignore)
{
}
}
if (this.resolveEnabled)
obj = resolveObject(obj);
this.objectLookupTable.put(new Integer(handle),
new ObjectIdentityWrapper(obj));
return obj;
}
private void clearHandles()
{
this.objectLookupTable.clear();
this.nextOID = baseWireHandle;
}
private void readNextBlock() throws IOException
{
readNextBlock(this.realInputStream.readByte());
}
private void readNextBlock(byte marker) throws IOException
{
if (marker == TC_BLOCKDATA)
{
if(dump) dumpElement("BLOCK DATA SIZE=");
this.blockDataBytes = this.realInputStream.readUnsignedByte();
if(dump) dumpElementln (Integer.toString(this.blockDataBytes));
}
else if (marker == TC_BLOCKDATALONG)
{
if(dump) dumpElement("BLOCK DATA LONG SIZE=");
this.blockDataBytes = this.realInputStream.readInt();
if(dump) dumpElementln (Integer.toString(this.blockDataBytes));
}
else
{
throw new EOFException("Attempt to read primitive data, but no data block is active.");
}
if (this.blockData.length < this.blockDataBytes)
this.blockData = new byte[this.blockDataBytes];
this.realInputStream.readFully (this.blockData, 0, this.blockDataBytes);
this.blockDataPosition = 0;
}
private void readArrayElements (Object array, Class clazz)
throws ClassNotFoundException, IOException
{
if (clazz.isPrimitive())
{
if (clazz == Boolean.TYPE)
{
boolean[] cast_array = (boolean[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readBoolean();
return;
}
if (clazz == Byte.TYPE)
{
byte[] cast_array = (byte[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readByte();
return;
}
if (clazz == Character.TYPE)
{
char[] cast_array = (char[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readChar();
return;
}
if (clazz == Double.TYPE)
{
double[] cast_array = (double[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readDouble();
return;
}
if (clazz == Float.TYPE)
{
float[] cast_array = (float[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readFloat();
return;
}
if (clazz == Integer.TYPE)
{
int[] cast_array = (int[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readInt();
return;
}
if (clazz == Long.TYPE)
{
long[] cast_array = (long[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readLong();
return;
}
if (clazz == Short.TYPE)
{
short[] cast_array = (short[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = this.realInputStream.readShort();
return;
}
}
else
{
Object[] cast_array = (Object[])array;
for (int i=0; i < cast_array.length; i++)
cast_array[i] = readObject();
}
}
private void readFields (Object obj, ObjectStreamClass stream_osc)
throws ClassNotFoundException, IOException
{
ObjectStreamField[] fields = stream_osc.fieldMapping;
for (int i = 0; i < fields.length; i += 2)
{
ObjectStreamField stream_field = fields[i];
ObjectStreamField real_field = fields[i + 1];
boolean read_value = (stream_field != null && stream_field.getOffset() >= 0 && stream_field.isToSet());
boolean set_value = (real_field != null && real_field.isToSet());
String field_name;
char type;
if (stream_field != null)
{
field_name = stream_field.getName();
type = stream_field.getTypeCode();
}
else
{
field_name = real_field.getName();
type = real_field.getTypeCode();
}
switch(type)
{
case 'Z':
{
boolean value =
read_value ? this.realInputStream.readBoolean() : false;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setBooleanField(obj, value);
break;
}
case 'B':
{
byte value =
read_value ? this.realInputStream.readByte() : 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setByteField(obj, value);
break;
}
case 'C':
{
char value =
read_value ? this.realInputStream.readChar(): 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setCharField(obj, value);
break;
}
case 'D':
{
double value =
read_value ? this.realInputStream.readDouble() : 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setDoubleField(obj, value);
break;
}
case 'F':
{
float value =
read_value ? this.realInputStream.readFloat() : 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setFloatField(obj, value);
break;
}
case 'I':
{
int value =
read_value ? this.realInputStream.readInt() : 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setIntField(obj, value);
break;
}
case 'J':
{
long value =
read_value ? this.realInputStream.readLong() : 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setLongField(obj, value);
break;
}
case 'S':
{
short value =
read_value ? this.realInputStream.readShort() : 0;
if (dump && read_value && set_value)
dumpElementln(" " + field_name + ": " + value);
if (set_value)
real_field.setShortField(obj, value);
break;
}
case 'L':
case '[':
{
Object value =
read_value ? readObject() : null;
if (set_value)
real_field.setObjectField(obj, value);
break;
}
default:
throw new InternalError("Invalid type code: " + type);
}
}
}
// Toggles writing primitive data to block-data buffer.
private boolean setBlockDataMode (boolean on)
{
boolean oldmode = this.readDataFromBlock;
this.readDataFromBlock = on;
if (on)
this.dataInputStream = this.blockDataInput;
else
this.dataInputStream = this.realInputStream;
return oldmode;
}
// returns a new instance of REAL_CLASS that has been constructed
// only to the level of CONSTRUCTOR_CLASS (a super class of REAL_CLASS)
private Object newObject (Class real_class, Constructor constructor)
throws ClassNotFoundException, IOException
{
if (constructor == null)
throw new InvalidClassException("Missing accessible no-arg base class constructor for " + real_class.getName());
try
{
return allocateObject(real_class, constructor.getDeclaringClass(), constructor);
}
catch (InstantiationException e)
{
throw new ClassNotFoundException
("Instance of " + real_class + " could not be created");
}
}
// runs all registered ObjectInputValidations in prioritized order
// on OBJ
private void invokeValidators() throws InvalidObjectException
{
Object[] validators = new Object[this.validators.size()];
this.validators.copyInto (validators);
Arrays.sort (validators);
try
{
for (int i=0; i < validators.length; i++)
((ObjectInputValidation)validators[i]).validateObject();
}
finally
{
this.validators.removeAllElements();
}
}
/**
* This native method is used to get access to the protected method
* of the same name in SecurityManger.
*
* @param sm SecurityManager instance which should be called.
* @return The current class loader in the calling stack.
*/
private static native ClassLoader currentClassLoader (SecurityManager sm);
private void callReadMethod (Method readObject, Class klass, Object obj)
throws ClassNotFoundException, IOException
{
try
{
readObject.invoke(obj, new Object[] { this });
}
catch (InvocationTargetException x)
{
/* Rethrow if possible. */
Throwable exception = x.getTargetException();
if (exception instanceof RuntimeException)
throw (RuntimeException) exception;
if (exception instanceof IOException)
throw (IOException) exception;
if (exception instanceof ClassNotFoundException)
throw (ClassNotFoundException) exception;
throw new IOException("Exception thrown from readObject() on " +
klass + ": " + exception.getClass().getName());
}
catch (Exception x)
{
throw new IOException("Failure invoking readObject() on " +
klass + ": " + x.getClass().getName());
}
// Invalidate fields which has been read through readFields.
prereadFields = null;
}
private native Object allocateObject(Class clazz, Class constr_clazz, Constructor constructor)
throws InstantiationException;
private static final int BUFFER_SIZE = 1024;
private DataInputStream realInputStream;
private DataInputStream dataInputStream;
private DataInputStream blockDataInput;
private int blockDataPosition;
private int blockDataBytes;
private byte[] blockData;
private boolean useSubclassMethod;
private int nextOID;
private boolean resolveEnabled;
private Hashtable objectLookupTable;
private Object currentObject;
private ObjectStreamClass currentObjectStreamClass;
private boolean readDataFromBlock;
private boolean isDeserializing;
private boolean fieldsAlreadyRead;
private Vector validators;
private Hashtable classLookupTable;
private GetField prereadFields;
private static boolean dump;
// The nesting depth for debugging output
private int depth = 0;
private void dumpElement (String msg)
{
System.out.print(msg);
}
private void dumpElementln (String msg)
{
System.out.println(msg);
for (int i = 0; i < depth; i++)
System.out.print (" ");
System.out.print (Thread.currentThread() + ": ");
}
static
{
if (Configuration.INIT_LOAD_LIBRARY)
{
System.loadLibrary ("io");
}
}
}
// used to keep a prioritized list of object validators
class ValidatorAndPriority implements Comparable
{
int priority;
ObjectInputValidation validator;
ValidatorAndPriority (ObjectInputValidation validator, int priority)
{
this.priority = priority;
this.validator = validator;
}
public int compareTo (Object o)
{
ValidatorAndPriority vap = (ValidatorAndPriority)o;
return this.priority - vap.priority;
}
}
| true | true | public final Object readObject() throws ClassNotFoundException, IOException
{
if (this.useSubclassMethod)
return readObjectOverride();
boolean was_deserializing;
Object ret_val;
was_deserializing = this.isDeserializing;
boolean is_consumed = false;
boolean old_mode = setBlockDataMode(false);
this.isDeserializing = true;
byte marker = this.realInputStream.readByte();
depth += 2;
if(dump) dumpElement("MARKER: 0x" + Integer.toHexString(marker) + " ");
try
{
switch (marker)
{
case TC_ENDBLOCKDATA:
{
ret_val = null;
is_consumed = true;
break;
}
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
{
if (marker == TC_BLOCKDATALONG)
{ if(dump) dumpElementln("BLOCKDATALONG"); }
else
{ if(dump) dumpElementln("BLOCKDATA"); }
readNextBlock(marker);
throw new StreamCorruptedException("Unexpected blockData");
}
case TC_NULL:
{
if(dump) dumpElementln("NULL");
ret_val = null;
break;
}
case TC_REFERENCE:
{
if(dump) dumpElement("REFERENCE ");
Integer oid = new Integer(this.realInputStream.readInt());
if(dump) dumpElementln(Integer.toHexString(oid.intValue()));
ret_val = ((ObjectIdentityWrapper)
this.objectLookupTable.get(oid)).object;
break;
}
case TC_CLASS:
{
if(dump) dumpElementln("CLASS");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
assignNewHandle(clazz);
ret_val = clazz;
break;
}
case TC_PROXYCLASSDESC:
{
if(dump) dumpElementln("PROXYCLASS");
int n_intf = this.realInputStream.readInt();
String[] intfs = new String[n_intf];
for (int i = 0; i < n_intf; i++)
{
intfs[i] = this.realInputStream.readUTF();
System.out.println(intfs[i]);
}
boolean oldmode = setBlockDataMode(true);
Class cl = resolveProxyClass(intfs);
setBlockDataMode(oldmode);
ObjectStreamClass osc = lookupClass(cl);
assignNewHandle(osc);
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
ObjectStreamClass superosc = (ObjectStreamClass)readObject();
osc.setSuperclass(superosc);
ret_val = osc;
break;
}
case TC_CLASSDESC:
{
ObjectStreamClass osc = readClassDescriptor();
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
osc.setSuperclass ((ObjectStreamClass)readObject());
ret_val = osc;
break;
}
case TC_STRING:
case TC_LONGSTRING:
{
if(dump) dumpElement("STRING=");
String s = this.realInputStream.readUTF();
if(dump) dumpElementln(s);
ret_val = processResolution(null, s, assignNewHandle(s));
break;
}
case TC_ARRAY:
{
if(dump) dumpElementln("ARRAY");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class componentType = osc.forClass().getComponentType();
if(dump) dumpElement("ARRAY LENGTH=");
int length = this.realInputStream.readInt();
if(dump) dumpElementln (length + "; COMPONENT TYPE=" + componentType);
Object array = Array.newInstance(componentType, length);
int handle = assignNewHandle(array);
readArrayElements(array, componentType);
if(dump)
for (int i = 0, len = Array.getLength(array); i < len; i++)
dumpElementln(" ELEMENT[" + i + "]=" + Array.get(array, i));
ret_val = processResolution(null, array, handle);
break;
}
case TC_OBJECT:
{
if(dump) dumpElementln("OBJECT");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
if (!osc.realClassIsSerializable)
throw new NotSerializableException
(clazz + " is not Serializable, and thus cannot be deserialized.");
if (osc.realClassIsExternalizable)
{
Externalizable obj = osc.newInstance();
int handle = assignNewHandle(obj);
boolean read_from_blocks = ((osc.getFlags() & SC_BLOCK_DATA) != 0);
boolean oldmode = this.readDataFromBlock;
if (read_from_blocks)
setBlockDataMode(true);
obj.readExternal(this);
if (read_from_blocks)
setBlockDataMode(oldmode);
ret_val = processResolution(osc, obj, handle);
break;
} // end if (osc.realClassIsExternalizable)
Object obj = newObject(clazz, osc.firstNonSerializableParentConstructor);
int handle = assignNewHandle(obj);
Object prevObject = this.currentObject;
ObjectStreamClass prevObjectStreamClass = this.currentObjectStreamClass;
this.currentObject = obj;
ObjectStreamClass[] hierarchy =
inputGetObjectStreamClasses(clazz);
for (int i = 0; i < hierarchy.length; i++)
{
this.currentObjectStreamClass = hierarchy[i];
if(dump) dumpElementln("Reading fields of " + this.currentObjectStreamClass.getName ());
// XXX: should initialize fields in classes in the hierarchy
// that aren't in the stream
// should skip over classes in the stream that aren't in the
// real classes hierarchy
Method readObjectMethod = this.currentObjectStreamClass.readObjectMethod;
if (readObjectMethod != null)
{
fieldsAlreadyRead = false;
boolean oldmode = setBlockDataMode(true);
callReadMethod(readObjectMethod, this.currentObjectStreamClass.forClass(), obj);
setBlockDataMode(oldmode);
}
else
{
readFields(obj, currentObjectStreamClass);
}
if (this.currentObjectStreamClass.hasWriteMethod())
{
if(dump) dumpElement("ENDBLOCKDATA? ");
try
{
// FIXME: XXX: This try block is to
// catch EOF which is thrown for some
// objects. That indicates a bug in
// the logic.
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException
("No end of block data seen for class with readObject (ObjectInputStream) method.");
if(dump) dumpElementln("yes");
}
// catch (EOFException e)
// {
// if(dump) dumpElementln("no, got EOFException");
// }
catch (IOException e)
{
if(dump) dumpElementln("no, got IOException");
}
}
}
this.currentObject = prevObject;
this.currentObjectStreamClass = prevObjectStreamClass;
ret_val = processResolution(osc, obj, handle);
break;
}
case TC_RESET:
if(dump) dumpElementln("RESET");
clearHandles();
ret_val = readObject();
break;
case TC_EXCEPTION:
{
if(dump) dumpElement("EXCEPTION=");
Exception e = (Exception)readObject();
if(dump) dumpElementln(e.toString());
clearHandles();
throw new WriteAbortedException("Exception thrown during writing of stream", e);
}
default:
throw new IOException("Unknown marker on stream: " + marker);
}
}
finally
{
setBlockDataMode(old_mode);
this.isDeserializing = was_deserializing;
depth -= 2;
if (! was_deserializing)
{
if (validators.size() > 0)
invokeValidators();
}
}
return ret_val;
}
| public final Object readObject() throws ClassNotFoundException, IOException
{
if (this.useSubclassMethod)
return readObjectOverride();
boolean was_deserializing;
Object ret_val;
was_deserializing = this.isDeserializing;
boolean is_consumed = false;
boolean old_mode = setBlockDataMode(false);
this.isDeserializing = true;
byte marker = this.realInputStream.readByte();
depth += 2;
if(dump) dumpElement("MARKER: 0x" + Integer.toHexString(marker) + " ");
try
{
switch (marker)
{
case TC_ENDBLOCKDATA:
{
ret_val = null;
is_consumed = true;
break;
}
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
{
if (marker == TC_BLOCKDATALONG)
{ if(dump) dumpElementln("BLOCKDATALONG"); }
else
{ if(dump) dumpElementln("BLOCKDATA"); }
readNextBlock(marker);
throw new StreamCorruptedException("Unexpected blockData");
}
case TC_NULL:
{
if(dump) dumpElementln("NULL");
ret_val = null;
break;
}
case TC_REFERENCE:
{
if(dump) dumpElement("REFERENCE ");
Integer oid = new Integer(this.realInputStream.readInt());
if(dump) dumpElementln(Integer.toHexString(oid.intValue()));
ret_val = ((ObjectIdentityWrapper)
this.objectLookupTable.get(oid)).object;
break;
}
case TC_CLASS:
{
if(dump) dumpElementln("CLASS");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
assignNewHandle(clazz);
ret_val = clazz;
break;
}
case TC_PROXYCLASSDESC:
{
if(dump) dumpElementln("PROXYCLASS");
int n_intf = this.realInputStream.readInt();
String[] intfs = new String[n_intf];
for (int i = 0; i < n_intf; i++)
{
intfs[i] = this.realInputStream.readUTF();
System.out.println(intfs[i]);
}
boolean oldmode = setBlockDataMode(true);
Class cl = resolveProxyClass(intfs);
setBlockDataMode(oldmode);
ObjectStreamClass osc = lookupClass(cl);
assignNewHandle(osc);
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
ObjectStreamClass superosc = (ObjectStreamClass)readObject();
osc.setSuperclass(superosc);
ret_val = osc;
break;
}
case TC_CLASSDESC:
{
ObjectStreamClass osc = readClassDescriptor();
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
osc.setSuperclass ((ObjectStreamClass)readObject());
ret_val = osc;
break;
}
case TC_STRING:
case TC_LONGSTRING:
{
if(dump) dumpElement("STRING=");
String s = this.realInputStream.readUTF();
if(dump) dumpElementln(s);
ret_val = processResolution(null, s, assignNewHandle(s));
break;
}
case TC_ARRAY:
{
if(dump) dumpElementln("ARRAY");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class componentType = osc.forClass().getComponentType();
if(dump) dumpElement("ARRAY LENGTH=");
int length = this.realInputStream.readInt();
if(dump) dumpElementln (length + "; COMPONENT TYPE=" + componentType);
Object array = Array.newInstance(componentType, length);
int handle = assignNewHandle(array);
readArrayElements(array, componentType);
if(dump)
for (int i = 0, len = Array.getLength(array); i < len; i++)
dumpElementln(" ELEMENT[" + i + "]=" + Array.get(array, i));
ret_val = processResolution(null, array, handle);
break;
}
case TC_OBJECT:
{
if(dump) dumpElementln("OBJECT");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
if (!osc.realClassIsSerializable)
throw new NotSerializableException
(clazz + " is not Serializable, and thus cannot be deserialized.");
if (osc.realClassIsExternalizable)
{
Externalizable obj = osc.newInstance();
int handle = assignNewHandle(obj);
boolean read_from_blocks = ((osc.getFlags() & SC_BLOCK_DATA) != 0);
boolean oldmode = this.readDataFromBlock;
if (read_from_blocks)
setBlockDataMode(true);
obj.readExternal(this);
if (read_from_blocks)
{
setBlockDataMode(oldmode);
if (!oldmode)
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException("No end of block data seen for class with readExternal (ObjectInputStream) method.");
}
ret_val = processResolution(osc, obj, handle);
break;
} // end if (osc.realClassIsExternalizable)
Object obj = newObject(clazz, osc.firstNonSerializableParentConstructor);
int handle = assignNewHandle(obj);
Object prevObject = this.currentObject;
ObjectStreamClass prevObjectStreamClass = this.currentObjectStreamClass;
this.currentObject = obj;
ObjectStreamClass[] hierarchy =
inputGetObjectStreamClasses(clazz);
for (int i = 0; i < hierarchy.length; i++)
{
this.currentObjectStreamClass = hierarchy[i];
if(dump) dumpElementln("Reading fields of " + this.currentObjectStreamClass.getName ());
// XXX: should initialize fields in classes in the hierarchy
// that aren't in the stream
// should skip over classes in the stream that aren't in the
// real classes hierarchy
Method readObjectMethod = this.currentObjectStreamClass.readObjectMethod;
if (readObjectMethod != null)
{
fieldsAlreadyRead = false;
boolean oldmode = setBlockDataMode(true);
callReadMethod(readObjectMethod, this.currentObjectStreamClass.forClass(), obj);
setBlockDataMode(oldmode);
}
else
{
readFields(obj, currentObjectStreamClass);
}
if (this.currentObjectStreamClass.hasWriteMethod())
{
if(dump) dumpElement("ENDBLOCKDATA? ");
try
{
// FIXME: XXX: This try block is to
// catch EOF which is thrown for some
// objects. That indicates a bug in
// the logic.
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException
("No end of block data seen for class with readObject (ObjectInputStream) method.");
if(dump) dumpElementln("yes");
}
// catch (EOFException e)
// {
// if(dump) dumpElementln("no, got EOFException");
// }
catch (IOException e)
{
if(dump) dumpElementln("no, got IOException");
}
}
}
this.currentObject = prevObject;
this.currentObjectStreamClass = prevObjectStreamClass;
ret_val = processResolution(osc, obj, handle);
break;
}
case TC_RESET:
if(dump) dumpElementln("RESET");
clearHandles();
ret_val = readObject();
break;
case TC_EXCEPTION:
{
if(dump) dumpElement("EXCEPTION=");
Exception e = (Exception)readObject();
if(dump) dumpElementln(e.toString());
clearHandles();
throw new WriteAbortedException("Exception thrown during writing of stream", e);
}
default:
throw new IOException("Unknown marker on stream: " + marker);
}
}
finally
{
setBlockDataMode(old_mode);
this.isDeserializing = was_deserializing;
depth -= 2;
if (! was_deserializing)
{
if (validators.size() > 0)
invokeValidators();
}
}
return ret_val;
}
|
diff --git a/src/aurelienribon/tweenengine/Tween.java b/src/aurelienribon/tweenengine/Tween.java
index de8ac0a..fda8368 100644
--- a/src/aurelienribon/tweenengine/Tween.java
+++ b/src/aurelienribon/tweenengine/Tween.java
@@ -1,564 +1,562 @@
package aurelienribon.tweenengine;
import aurelienribon.tweenengine.callbacks.TweenCompleteCallback;
import aurelienribon.tweenengine.callbacks.TweenIterationCompleteCallback;
import java.util.ArrayList;
public class Tween {
// -------------------------------------------------------------------------
// Static
// -------------------------------------------------------------------------
public static final int INFINITY = -1;
private static final int MODE_UNKNOWN= -1;
private static final int MODE_TO = 0;
private static final int MODE_FROM = 1;
private static final int MODE_SET = 2;
private static final int MAX_COMBINED_TWEENS = 3;
private static final ArrayList<Tween> runningTweens;
private static final Pool<Tween> pool;
private static final float[] tmp = new float[MAX_COMBINED_TWEENS];
static {
runningTweens = new ArrayList<Tween>(20);
pool = new Pool<Tween>(20) {
@Override
protected Tween getNew() {
return new Tween();
}
};
}
// -------------------------------------------------------------------------
// STATIC ENGINE
// -------------------------------------------------------------------------
/**
* Updates every running interpolation.
*/
public static void update() {
int currentMillis = (int) System.currentTimeMillis();
for (int i=0; i<runningTweens.size(); i++) {
Tween tween = runningTweens.get(i);
boolean shoudRepeat = (tween.repeatCnt < 0) || (tween.iteration < tween.repeatCnt);
if (tween.isEnded && !shoudRepeat) {
for (int ii=0; ii<tween.completeCallbacks.size(); ii++)
tween.completeCallbacks.get(ii).tweenComplete(tween);
runningTweens.remove(i);
pool.free(tween);
i -= 1;
} else {
tween.update(currentMillis);
}
}
}
/**
* Resets every static resource.
*/
public static void dispose() {
pool.clear();
runningTweens.clear();
}
/**
* Gets the count of currently running tweens.
*/
public static int getRunningTweenCount() {
return runningTweens.size();
}
// -------------------------------------------------------------------------
// TWEEN.TO
// -------------------------------------------------------------------------
/**
* Starts a new tween.
* @param target The target of the interpolation.
* @param tweenType The type of interpolation desired.
* @param equation The equation used during the interpolation.
* @param durationMillis The duration of the interpolation, in milliseconds.
* @param targetValue The ending value for the interpolation.
* @return The generated Tween.
*/
public static Tween to(Tweenable target, int tweenType,
TweenEquation equation, int durationMillis, float targetValue) {
Tween newTween = pool.get();
tmp[0] = targetValue;
newTween.reset(MODE_TO, target, tweenType, equation, durationMillis, tmp);
runningTweens.add(newTween);
return newTween;
}
/**
* Starts a new tween.
* @param target The target of the interpolation.
* @param tweenType The type of interpolation desired.
* @param equation The equation used during the interpolation.
* @param durationMillis The duration of the interpolation, in milliseconds.
* @param targetValue1 The 1st ending value for the interpolation.
* @param targetValue2 The 2nd ending value for the interpolation.
* @return The generated Tween.
*/
public static Tween to(Tweenable target, int tweenType,
TweenEquation equation, int durationMillis, float targetValue1, float targetValue2) {
Tween newTween = pool.get();
tmp[0] = targetValue1;
tmp[1] = targetValue2;
newTween.reset(MODE_TO, target, tweenType, equation, durationMillis, tmp);
runningTweens.add(newTween);
return newTween;
}
/**
* Starts a new tween.
* @param target The target of the interpolation.
* @param tweenType The type of interpolation desired.
* @param equation The equation used during the interpolation.
* @param durationMillis The duration of the interpolation, in milliseconds.
* @param targetValue1 The 1st ending value for the interpolation.
* @param targetValue2 The 2nd ending value for the interpolation.
* @param targetValue3 The 3rd ending value for the interpolation.
* @return The generated Tween.
*/
public static Tween to(Tweenable target, int tweenType,
TweenEquation equation, int durationMillis, float targetValue1, float targetValue2, float targetValue3) {
Tween newTween = pool.get();
tmp[0] = targetValue1;
tmp[1] = targetValue2;
tmp[2] = targetValue3;
newTween.reset(MODE_TO, target, tweenType, equation, durationMillis, tmp);
runningTweens.add(newTween);
return newTween;
}
// -------------------------------------------------------------------------
// TWEEN.FROM
// -------------------------------------------------------------------------
/**
* Starts a new tween.
* @param target The target of the interpolation.
* @param tweenType The type of interpolation desired.
* @param equation The equation used during the interpolation.
* @param durationMillis The duration of the interpolation, in milliseconds.
* @param startValue The starting value for the interpolation.
* @return The generated Tween.
*/
public static Tween from(Tweenable target, int tweenType,
TweenEquation equation, int durationMillis, float startValue) {
Tween newTween = pool.get();
tmp[0] = startValue;
newTween.reset(MODE_FROM, target, tweenType, equation, durationMillis, tmp);
runningTweens.add(newTween);
return newTween;
}
/**
* Starts a new tween.
* @param target The target of the interpolation.
* @param tweenType The type of interpolation desired.
* @param equation The equation used during the interpolation.
* @param durationMillis The duration of the interpolation, in milliseconds.
* @param startValue1 The 1st starting value for the interpolation.
* @param startValue2 The 2nd starting value for the interpolation.
* @return The generated Tween.
*/
public static Tween from(Tweenable target, int tweenType,
TweenEquation equation, int durationMillis, float startValue1, float startValue2) {
Tween newTween = pool.get();
tmp[0] = startValue1;
tmp[1] = startValue2;
newTween.reset(MODE_FROM, target, tweenType, equation, durationMillis, tmp);
runningTweens.add(newTween);
return newTween;
}
/**
* Starts a new tween.
* @param target The target of the interpolation.
* @param tweenType The type of interpolation desired.
* @param equation The equation used during the interpolation.
* @param durationMillis The duration of the interpolation, in milliseconds.
* @param startValue1 The 1st starting value for the interpolation.
* @param startValue2 The 2nd starting value for the interpolation.
* @param startValue3 The 3rd starting value for the interpolation.
* @return The generated Tween.
*/
public static Tween from(Tweenable target, int tweenType,
TweenEquation equation, int durationMillis, float startValue1, float startValue2, float startValue3) {
Tween newTween = pool.get();
tmp[0] = startValue1;
tmp[1] = startValue2;
tmp[2] = startValue3;
newTween.reset(MODE_FROM, target, tweenType, equation, durationMillis, tmp);
runningTweens.add(newTween);
return newTween;
}
// -------------------------------------------------------------------------
// TWEEN.IMPULSE
// -------------------------------------------------------------------------
/**
* Starts a new impulse tween (the target is set to the targetValue without
* interpolation, right after the delay).
* @param target The target of the impulse.
* @param tweenType The type of interpolation desired.
* @param targetValue The target value for the impulse.
* @return The generated Tween.
*/
public static Tween impulse(Tweenable target, int tweenType, float targetValue) {
Tween newTween = pool.get();
tmp[0] = targetValue;
newTween.reset(MODE_SET, target, tweenType, null, 0, tmp);
runningTweens.add(newTween);
return newTween;
}
/**
* Starts a new impulse tween (the target is set to the targetValue without
* interpolation, right after the delay).
* @param target The target of the impulse.
* @param tweenType The type of interpolation desired.
* @param targetValue1 The 1st target value for the impulse.
* @param targetValue2 The 2nd target value for the impulse.
* @return The generated Tween.
*/
public static Tween impulse(Tweenable target, int tweenType, float targetValue1, float targetValue2) {
Tween newTween = pool.get();
tmp[0] = targetValue1;
tmp[1] = targetValue2;
newTween.reset(MODE_SET, target, tweenType, null, 0, tmp);
runningTweens.add(newTween);
return newTween;
}
/**
* Starts a new impulse tween (the target is set to the targetValue without
* interpolation, right after the delay).
* @param target The target of the impulse.
* @param tweenType The type of interpolation desired.
* @param targetValue1 The 1st target value for the impulse.
* @param targetValue2 The 2nd target value for the impulse.
* @param targetValue3 The 3rd target value for the impulse.
* @return The generated Tween.
*/
public static Tween impulse(Tweenable target, int tweenType, float targetValue1, float targetValue2, float targetValue3) {
Tween newTween = pool.get();
tmp[0] = targetValue1;
tmp[1] = targetValue2;
tmp[2] = targetValue3;
newTween.reset(MODE_SET, target, tweenType, null, 0, tmp);
runningTweens.add(newTween);
return newTween;
}
// -------------------------------------------------------------------------
// Tween
// -------------------------------------------------------------------------
// Main
private Tweenable target;
private int tweenType;
private TweenEquation equation;
// General
private int mode = MODE_UNKNOWN;
private int id = -1;
// Values
private int combinedTweenCount;
private final float[] startValues;
private final float[] addedValues;
private final float[] targetValues;
// Timings
private int startMillis;
private int durationMillis;
private int delayMillis;
private int endDelayMillis;
private int endMillis;
private boolean isStarted = false;
private boolean isDelayEnded = false;
private boolean isEnded = false;
// Callbacks
private final ArrayList<TweenCompleteCallback> completeCallbacks;
private final ArrayList<TweenIterationCompleteCallback> iterationCompleteCallbacks;
// Repeat
private int repeatCnt;
private int iteration;
private int repeatDelayMillis;
private int endRepeatDelayMillis;
// Misc
private final float[] localTmp = new float[MAX_COMBINED_TWEENS];
private Tween() {
startValues = new float[MAX_COMBINED_TWEENS];
addedValues = new float[MAX_COMBINED_TWEENS];
targetValues = new float[MAX_COMBINED_TWEENS];
completeCallbacks = new ArrayList<TweenCompleteCallback>();
iterationCompleteCallbacks = new ArrayList<TweenIterationCompleteCallback>();
}
/**
* Starts or restart the interpolation.
*/
public void start() {
startMillis = (int) System.currentTimeMillis();
endDelayMillis = startMillis + delayMillis;
if (iteration > 0 && repeatDelayMillis < 0)
endDelayMillis = Math.max(endDelayMillis + repeatDelayMillis, startMillis);
endMillis = endDelayMillis + durationMillis;
endRepeatDelayMillis = Math.max(endMillis, endMillis + repeatDelayMillis);
isStarted = true;
isDelayEnded = false;
isEnded = false;
}
/**
* Kills this interpolation.
* Stops it and removes it from the running tween list.
*/
public void kill() {
isEnded = true;
repeatCnt = 0;
}
/**
* Delays the tween. Time has to be specified as milliseconds.
* Returns the current tween for chaining instructions.
*/
public Tween delay(int delayMillis) {
this.delayMillis += delayMillis;
this.endDelayMillis += delayMillis;
this.endMillis += delayMillis;
return this;
}
/**
* Adds a callback triggered at the end of the interpolation (including
* repeats). Returns the current tween for chaining instructions.
*/
public Tween onComplete(TweenCompleteCallback callback) {
completeCallbacks.add(callback);
return this;
}
/**
* Adds a callback triggered at the end each repeat iteration.
* Returns the current tween for chaining instructions.
*/
public Tween onComplete(TweenIterationCompleteCallback callback) {
iterationCompleteCallbacks.add(callback);
return this;
}
/**
* Gets an idle copy of this tween.
*/
public Tween copy() {
Tween tween = pool.get();
tween.reset(mode, target, tweenType, equation, durationMillis, targetValues);
tween.delay(delayMillis);
tween.repeat(repeatCnt, repeatDelayMillis);
runningTweens.add(tween);
return tween;
}
/**
* Sets an id to the tween. It can be used to test if the tween has not
* been reset, since ids are reset to -1 on each tween reuse.
*/
public Tween setId(int id) {
this.id = id;
return this;
}
/**
* Repeats the tween for a given number of times. For infinity repeats,
* use Tween.INFINITY.
*/
public Tween repeat(int count) {
return repeat(count, 0);
}
/**
* Repeats the tween for a given number of times. For infinity repeats,
* use Tween.INFINITY. A delay before the repeat occurs can be specified.
*/
public Tween repeat(int count, int delayMillis) {
repeatDelayMillis = delayMillis;
repeatCnt = count;
return this;
}
private void reset(int mode, Tweenable target, int tweenType, TweenEquation equation,
int durationMillis, float[] targetValues) {
this.target = target;
this.tweenType = tweenType;
this.equation = equation;
this.id = -1;
this.mode = mode;
this.combinedTweenCount = target.getTweenedAttributeCount(tweenType);
if (this.combinedTweenCount < 1 || this.combinedTweenCount > MAX_COMBINED_TWEENS)
throw new RuntimeException("Min combined tweens = 1, max = " + MAX_COMBINED_TWEENS);
System.arraycopy(targetValues, 0, this.targetValues, 0, MAX_COMBINED_TWEENS);
this.durationMillis = durationMillis;
this.delayMillis = 0;
this.isStarted = false;
this.isDelayEnded = false;
this.isEnded = false;
this.completeCallbacks.clear();
this.iterationCompleteCallbacks.clear();
this.repeatCnt = 0;
this.iteration = 0;
this.repeatDelayMillis = 0;
}
private void update(int currentMillis) {
// Are we started ?
if (!isStarted)
return;
// Shall we repeat ?
if ((repeatCnt < 0 || iteration < repeatCnt) && currentMillis >= endRepeatDelayMillis) {
iteration += 1;
start();
return;
}
// Wait for the end of the delay then either grab the start or end
// values if it is the first iteration, or restart from those values
// if the animation is replaying.
if (!isDelayEnded && currentMillis >= endDelayMillis) {
isDelayEnded = true;
if (iteration > 0) {
target.tweenUpdated(tweenType, startValues);
} else {
switch (mode) {
case MODE_TO:
target.getTweenValues(tweenType, startValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] = targetValues[i] - startValues[i];
break;
case MODE_FROM:
System.arraycopy(targetValues, 0, startValues, 0, MAX_COMBINED_TWEENS);
target.getTweenValues(tweenType, addedValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] -= targetValues[i];
break;
case MODE_SET:
target.getTweenValues(tweenType, startValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] = targetValues[i] - startValues[i];
break;
- case MODE_UNKNOWN:
- assert false;
- break;
+ default: assert false; break;
}
}
} else if (!isDelayEnded) {
return;
}
// Test for the end of the tween. If true, set the target values to
// their final values (to avoid precision loss when moving fast), and
// call the callbacks.
if (isEnded) {
return;
} else if (currentMillis >= endMillis) {
for (int i=0; i<combinedTweenCount; i++)
localTmp[i] = startValues[i] + addedValues[i];
target.tweenUpdated(tweenType, localTmp);
for (int k=0; k<iterationCompleteCallbacks.size(); k++)
iterationCompleteCallbacks.get(k).iterationComplete(this);
isEnded = true;
return;
}
// New values computation
for (int i=0; i<combinedTweenCount; i++)
localTmp[i] = equation.compute(
currentMillis - endDelayMillis,
startValues[i],
addedValues[i],
durationMillis);
target.tweenUpdated(tweenType, localTmp);
}
public int getMode() {
return mode;
}
public Tweenable getTarget() {
return target;
}
public int getTweenType() {
return tweenType;
}
public TweenEquation getEquation() {
return equation;
}
public float[] getTargetValues() {
return targetValues;
}
public int getDurationMillis() {
return durationMillis;
}
public int getDelayMillis() {
return delayMillis;
}
public int getCombinedTweenCount() {
return combinedTweenCount;
}
public int getId() {
return id;
}
}
| true | true | private void update(int currentMillis) {
// Are we started ?
if (!isStarted)
return;
// Shall we repeat ?
if ((repeatCnt < 0 || iteration < repeatCnt) && currentMillis >= endRepeatDelayMillis) {
iteration += 1;
start();
return;
}
// Wait for the end of the delay then either grab the start or end
// values if it is the first iteration, or restart from those values
// if the animation is replaying.
if (!isDelayEnded && currentMillis >= endDelayMillis) {
isDelayEnded = true;
if (iteration > 0) {
target.tweenUpdated(tweenType, startValues);
} else {
switch (mode) {
case MODE_TO:
target.getTweenValues(tweenType, startValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] = targetValues[i] - startValues[i];
break;
case MODE_FROM:
System.arraycopy(targetValues, 0, startValues, 0, MAX_COMBINED_TWEENS);
target.getTweenValues(tweenType, addedValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] -= targetValues[i];
break;
case MODE_SET:
target.getTweenValues(tweenType, startValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] = targetValues[i] - startValues[i];
break;
case MODE_UNKNOWN:
assert false;
break;
}
}
} else if (!isDelayEnded) {
return;
}
// Test for the end of the tween. If true, set the target values to
// their final values (to avoid precision loss when moving fast), and
// call the callbacks.
if (isEnded) {
return;
} else if (currentMillis >= endMillis) {
for (int i=0; i<combinedTweenCount; i++)
localTmp[i] = startValues[i] + addedValues[i];
target.tweenUpdated(tweenType, localTmp);
for (int k=0; k<iterationCompleteCallbacks.size(); k++)
iterationCompleteCallbacks.get(k).iterationComplete(this);
isEnded = true;
return;
}
// New values computation
for (int i=0; i<combinedTweenCount; i++)
localTmp[i] = equation.compute(
currentMillis - endDelayMillis,
startValues[i],
addedValues[i],
durationMillis);
target.tweenUpdated(tweenType, localTmp);
}
| private void update(int currentMillis) {
// Are we started ?
if (!isStarted)
return;
// Shall we repeat ?
if ((repeatCnt < 0 || iteration < repeatCnt) && currentMillis >= endRepeatDelayMillis) {
iteration += 1;
start();
return;
}
// Wait for the end of the delay then either grab the start or end
// values if it is the first iteration, or restart from those values
// if the animation is replaying.
if (!isDelayEnded && currentMillis >= endDelayMillis) {
isDelayEnded = true;
if (iteration > 0) {
target.tweenUpdated(tweenType, startValues);
} else {
switch (mode) {
case MODE_TO:
target.getTweenValues(tweenType, startValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] = targetValues[i] - startValues[i];
break;
case MODE_FROM:
System.arraycopy(targetValues, 0, startValues, 0, MAX_COMBINED_TWEENS);
target.getTweenValues(tweenType, addedValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] -= targetValues[i];
break;
case MODE_SET:
target.getTweenValues(tweenType, startValues);
for (int i=0; i<MAX_COMBINED_TWEENS; i++)
addedValues[i] = targetValues[i] - startValues[i];
break;
default: assert false; break;
}
}
} else if (!isDelayEnded) {
return;
}
// Test for the end of the tween. If true, set the target values to
// their final values (to avoid precision loss when moving fast), and
// call the callbacks.
if (isEnded) {
return;
} else if (currentMillis >= endMillis) {
for (int i=0; i<combinedTweenCount; i++)
localTmp[i] = startValues[i] + addedValues[i];
target.tweenUpdated(tweenType, localTmp);
for (int k=0; k<iterationCompleteCallbacks.size(); k++)
iterationCompleteCallbacks.get(k).iterationComplete(this);
isEnded = true;
return;
}
// New values computation
for (int i=0; i<combinedTweenCount; i++)
localTmp[i] = equation.compute(
currentMillis - endDelayMillis,
startValues[i],
addedValues[i],
durationMillis);
target.tweenUpdated(tweenType, localTmp);
}
|
diff --git a/src/practica3/Cavall.java b/src/practica3/Cavall.java
index 8459281..7b7f617 100644
--- a/src/practica3/Cavall.java
+++ b/src/practica3/Cavall.java
@@ -1,31 +1,32 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practica3;
/**
*
* @author Jaume
*/
public class Cavall extends Peça {
public Cavall(int x, int y) {
super(x, y);
}
@Override
public boolean mataPeça(Peça peça) {
return (this.getX() - 1 == peça.getX() && this.getY() - 2 == peça.getY()) ||
(this.getX() - 1 == peça.getX() && this.getY() + 2 == peça.getY()) ||
(this.getX() + 1 == peça.getX() && this.getY() - 2 == peça.getY()) ||
(this.getX() + 1 == peça.getX() && this.getY() + 2 == peça.getY()) ||
(this.getX() - 2 == peça.getX() && this.getY() - 1 == peça.getY()) ||
(this.getX() - 2 == peça.getX() && this.getY() + 1 == peça.getY()) ||
(this.getX() + 2 == peça.getX() && this.getY() - 1 == peça.getY()) ||
- (this.getX() + 2 == peça.getX() && this.getY() + 1 == peça.getY());
+ (this.getX() + 2 == peça.getX() && this.getY() + 1 == peça.getY()) ||
+ (this.getX() == peça.getX() && this.getY() == peça.getY());
}
}
| true | true | public boolean mataPeça(Peça peça) {
return (this.getX() - 1 == peça.getX() && this.getY() - 2 == peça.getY()) ||
(this.getX() - 1 == peça.getX() && this.getY() + 2 == peça.getY()) ||
(this.getX() + 1 == peça.getX() && this.getY() - 2 == peça.getY()) ||
(this.getX() + 1 == peça.getX() && this.getY() + 2 == peça.getY()) ||
(this.getX() - 2 == peça.getX() && this.getY() - 1 == peça.getY()) ||
(this.getX() - 2 == peça.getX() && this.getY() + 1 == peça.getY()) ||
(this.getX() + 2 == peça.getX() && this.getY() - 1 == peça.getY()) ||
(this.getX() + 2 == peça.getX() && this.getY() + 1 == peça.getY());
}
| public boolean mataPeça(Peça peça) {
return (this.getX() - 1 == peça.getX() && this.getY() - 2 == peça.getY()) ||
(this.getX() - 1 == peça.getX() && this.getY() + 2 == peça.getY()) ||
(this.getX() + 1 == peça.getX() && this.getY() - 2 == peça.getY()) ||
(this.getX() + 1 == peça.getX() && this.getY() + 2 == peça.getY()) ||
(this.getX() - 2 == peça.getX() && this.getY() - 1 == peça.getY()) ||
(this.getX() - 2 == peça.getX() && this.getY() + 1 == peça.getY()) ||
(this.getX() + 2 == peça.getX() && this.getY() - 1 == peça.getY()) ||
(this.getX() + 2 == peça.getX() && this.getY() + 1 == peça.getY()) ||
(this.getX() == peça.getX() && this.getY() == peça.getY());
}
|
diff --git a/Core/GrupyPWR/src/main/java/com/project/form/LoginController.java b/Core/GrupyPWR/src/main/java/com/project/form/LoginController.java
index 76ce4c0..3842f88 100644
--- a/Core/GrupyPWR/src/main/java/com/project/form/LoginController.java
+++ b/Core/GrupyPWR/src/main/java/com/project/form/LoginController.java
@@ -1,303 +1,305 @@
package com.project.form;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.project.dao.PobierzGrupyDAO;
import com.project.data.GrupyZajeciowe;
import com.project.data.Kursy;
import com.project.data.Prowadzacy;
import com.project.service.LoginService;
import com.project.service.PobierzGrupyService;
import com.project.service.PobranieGrupZajService;
import com.project.Utils.Encryption;
import com.project.Utils.ImportCSV;
import com.project.Utils.RandomPassword;
import com.project.Utils.SendMail;
import com.project.Json.*;
@Controller
public class LoginController extends SendMail {
@Autowired
private LoginService loginService;
@Autowired
private PobierzGrupyService pobierzGrupyService;
@Autowired
private PobranieGrupZajService pobierzGrupyZajService;
@Autowired
private HttpServletRequest context;
@Autowired
private ImportCSV importcsv;
@RequestMapping("/")
public String przelacz() {
return "*/index";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public @ResponseBody
Integer addProwadzacy(
@RequestParam(value = "firstname", required = true) String imie,
@RequestParam(value = "surname", required = true) String nazwisko,
@RequestParam(value = "email", required = true) String mail,
@RequestParam(value = "user", required = true) String login,
Model model) {
String from = "grupy.pwr.wroc@gmail.com";
String subject = "Przesłanie hasła do logowania!";
Date data = new Date();
Prowadzacy prowadzacy = new Prowadzacy();
prowadzacy.setImiona(imie);
prowadzacy.setNazwisko(nazwisko);
prowadzacy.setEmail(mail);
prowadzacy.setLogin(login);
prowadzacy.setDataDodania(data);
prowadzacy.setWaznosc(true);
prowadzacy.setAktywowany(false);
String haslo = RandomPassword.Random();
prowadzacy.setHaslo(Encryption.encrypt(haslo));
loginService.addProwadzacy(prowadzacy);
Wyslij_maila(mail, subject, haslo, from);
List<Prowadzacy> registerlist = loginService.validateRegister(imie,
nazwisko, mail, login);
if (registerlist.size() > 0) {
return 1;
} else {
return 0;
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody
String loginAuthentication(
@RequestParam(value = "user", required = true) String login,
@RequestParam(value = "pass", required = true) String haslo,
Model model) {
List<Prowadzacy> loginlist = loginService.validateLogin(login, haslo);
System.out.println("Hasło: " + haslo + " Login: " + login);
System.out.println("\nRozmiar loginlist: " + loginlist.size());
if (loginlist.size() > 0) {
return loginlist.get(0).getIdProwadzacy().toString();
} else {
return "-1";
}
}
/*@RequestMapping(value = "/getgroups", method = RequestMethod.POST, produces="application/json")
public @ResponseBody
JsonGroupWyzej wyslijGrupy(
@RequestParam(value = "dateid", required = true) int idGrupyZaj,
Model model) {
JsonMarksAndPresence jsonmarks = new JsonMarksAndPresence();
JsonStudents jsonstudent = new JsonStudents();
JsonSpotkania jsonspotkania = new JsonSpotkania();
JsonNotes jsonnotatki = new JsonNotes();
JsonGrupyProjektowe jsongrup = new JsonGrupyProjektowe();
JsonNieWGrupie jsonniewgrupie = new JsonNieWGrupie();
JsonGroupZajeciowe jsonGroupZajeciowe = new JsonGroupZajeciowe();
JsonGroupWyzej jsonGroupWyzej = new JsonGroupWyzej();
List<GrupyZajeciowe> grupzajeciowe = pobierzGrupyZajService.pobierzGrupyZajeciowe(idGrupyZaj);
int i;
int idgrupyZaj;
List<JsonGroupZajeciowe> dates = new ArrayList<JsonGroupZajeciowe>();
for(i=0; i<grupzajeciowe.size(); i++) {
idgrupyZaj = grupzajeciowe.get(i).getIdGrupyZajeciowe();
for(){
for() {
for(){
for() {
}
}
for() {
}
for() {
}
}
for() {
}
}
jsonGroupWyzej.setDates(dates);
}
return jsonGroupWyzej;
/*
* List<GrupyZajeciowe> grupyzajeciowe = pobierzGrupyService
* .pobierzGrupyZajeciowe(login);
*/
/*
* int idKursu ; int i; JsonKursy jsonKursy = new JsonKursy(); JsonGrupy
* jsonGrupy = new JsonGrupy(); JsonGrupyZajeciowe jsonGrupyZajeciowe =
* new JsonGrupyZajeciowe(); List<JsonGrupy> courses = new
* ArrayList<JsonGrupy>();
* for( i = 0; i<= grupyzajeciowe.size()-1;
* i++){
* idKursu = grupyzajeciowe.get(i).getIdKursu().getIdKursy();
*
* List<Kursy> kurslist = pobierzGrupyService.pobierzKursy(idKursu);
*
* for(Kursy kurs : kurslist) { List<JsonGrupyZajeciowe> name = new
* ArrayList<JsonGrupyZajeciowe>(); for(GrupyZajeciowe grupa :
* grupyzajeciowe) { // set dla JsonGrupyZajeciowe
* jsonGrupyZajeciowe.setId(grupa.getIdKursu().getIdKursy());
* jsonGrupyZajeciowe.setCode(grupa.getKodGrupy());
* jsonGrupyZajeciowe.setName(grupa.getNazwa()); }
* jsonGrupy.setName(kurs.getNazwaKursu());
* jsonGrupy.setId(kurs.getIdKursy()); jsonGrupy.setDates(name); }
* jsonKursy.setCourses(courses); }
*
* return jsonKursy;
*/
// }*/
@RequestMapping(value = "/getcourses", method = RequestMethod.POST, produces="application/json")
public @ResponseBody
JsonKursy wyslijKursy(
@RequestParam(value = "userid", required = true) int login,
Model model) {
List<GrupyZajeciowe> grupyzajeciowe = pobierzGrupyService
.pobierzGrupyZajeciowe(login);
int idKursu;
int i;
JsonKursy jsonKursy = new JsonKursy();
JsonGrupy jsonGrupy = new JsonGrupy();
JsonGrupyZajeciowe jsonGrupyZajeciowe = new JsonGrupyZajeciowe();
List<JsonGrupy> courses = new ArrayList<JsonGrupy>();
for (i = 0; i < grupyzajeciowe.size(); i++) {
idKursu = grupyzajeciowe.get(i).getIdKursu().getIdKursy();
List<Kursy> kurslist = pobierzGrupyService.pobierzKursy(idKursu);
for (Kursy kurs : kurslist) {
List<JsonGrupyZajeciowe> name = new ArrayList<JsonGrupyZajeciowe>();
for(GrupyZajeciowe grupa : grupyzajeciowe) {
// set dla JsonGrupyZajeciowe
jsonGrupyZajeciowe.setId(grupa.getIdKursu().getIdKursy());
jsonGrupyZajeciowe.setCode(grupa.getKodGrupy());
- jsonGrupyZajeciowe.setName(grupa.getNazwa());
+ jsonGrupyZajeciowe.setName(grupa.getTermin());
}
+ name.add(jsonGrupyZajeciowe);
jsonGrupy.setName(kurs.getNazwaKursu());
jsonGrupy.setId(kurs.getIdKursy());
jsonGrupy.setDates(name);
}
+ courses.add(jsonGrupy);
jsonKursy.setCourses(courses);
System.out.println("Test wydruk"+ jsonKursy);
}
return jsonKursy;
}
@RequestMapping(value = "/logout", method = RequestMethod.POST)
public @ResponseBody
int logout(@RequestParam(value = "userid", required = true) int login,
Model model) {
List<Prowadzacy> loglist = loginService.logout(login);
if (loglist.size() > 0) {
return 1;
}
return 0;
}
@RequestMapping(value = "/changepass", method = RequestMethod.POST)
public @ResponseBody
int zmien_haslo(
@RequestParam(value = "userid", required = true) int login,
@RequestParam(value = "oldpass", required = true) String stareHaslo,
@RequestParam(value = "newpass", required = true) String noweHaslo,
Model model) {
List<Prowadzacy> passlist = loginService
.validatePass(login, stareHaslo);
String zmienHaslo;
if (passlist.size() > 0) {
zmienHaslo = passlist.get(0).getHaslo();
if (zmienHaslo == stareHaslo) {
loginService.zmienPass(login, noweHaslo);
return 1;
}
}
return 0;
}
@RequestMapping(value = "/importcsv", method = RequestMethod.POST)
public @ResponseBody
String upload(
@RequestParam(value = "filecontent", required = false) CommonsMultipartFile file,
@RequestParam(value = "userid", required = true) int login,
Model model) {
InputStream is = null;
StringBuilder sb = new StringBuilder();
try {
is = file.getFileItem().getInputStream();
Reader reader = new InputStreamReader(is);
int data = reader.read();
while (data != -1) {
char theChar = (char) data;
sb.append(theChar);
data = reader.read();
}
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println(file.getFileItem().getFieldName());
if (file.isEmpty()) {
return "0";
} else {
importcsv.do_import(sb.toString(), login);
return "1";
}
}
}
| false | true | JsonKursy wyslijKursy(
@RequestParam(value = "userid", required = true) int login,
Model model) {
List<GrupyZajeciowe> grupyzajeciowe = pobierzGrupyService
.pobierzGrupyZajeciowe(login);
int idKursu;
int i;
JsonKursy jsonKursy = new JsonKursy();
JsonGrupy jsonGrupy = new JsonGrupy();
JsonGrupyZajeciowe jsonGrupyZajeciowe = new JsonGrupyZajeciowe();
List<JsonGrupy> courses = new ArrayList<JsonGrupy>();
for (i = 0; i < grupyzajeciowe.size(); i++) {
idKursu = grupyzajeciowe.get(i).getIdKursu().getIdKursy();
List<Kursy> kurslist = pobierzGrupyService.pobierzKursy(idKursu);
for (Kursy kurs : kurslist) {
List<JsonGrupyZajeciowe> name = new ArrayList<JsonGrupyZajeciowe>();
for(GrupyZajeciowe grupa : grupyzajeciowe) {
// set dla JsonGrupyZajeciowe
jsonGrupyZajeciowe.setId(grupa.getIdKursu().getIdKursy());
jsonGrupyZajeciowe.setCode(grupa.getKodGrupy());
jsonGrupyZajeciowe.setName(grupa.getNazwa());
}
jsonGrupy.setName(kurs.getNazwaKursu());
jsonGrupy.setId(kurs.getIdKursy());
jsonGrupy.setDates(name);
}
jsonKursy.setCourses(courses);
System.out.println("Test wydruk"+ jsonKursy);
}
return jsonKursy;
}
| JsonKursy wyslijKursy(
@RequestParam(value = "userid", required = true) int login,
Model model) {
List<GrupyZajeciowe> grupyzajeciowe = pobierzGrupyService
.pobierzGrupyZajeciowe(login);
int idKursu;
int i;
JsonKursy jsonKursy = new JsonKursy();
JsonGrupy jsonGrupy = new JsonGrupy();
JsonGrupyZajeciowe jsonGrupyZajeciowe = new JsonGrupyZajeciowe();
List<JsonGrupy> courses = new ArrayList<JsonGrupy>();
for (i = 0; i < grupyzajeciowe.size(); i++) {
idKursu = grupyzajeciowe.get(i).getIdKursu().getIdKursy();
List<Kursy> kurslist = pobierzGrupyService.pobierzKursy(idKursu);
for (Kursy kurs : kurslist) {
List<JsonGrupyZajeciowe> name = new ArrayList<JsonGrupyZajeciowe>();
for(GrupyZajeciowe grupa : grupyzajeciowe) {
// set dla JsonGrupyZajeciowe
jsonGrupyZajeciowe.setId(grupa.getIdKursu().getIdKursy());
jsonGrupyZajeciowe.setCode(grupa.getKodGrupy());
jsonGrupyZajeciowe.setName(grupa.getTermin());
}
name.add(jsonGrupyZajeciowe);
jsonGrupy.setName(kurs.getNazwaKursu());
jsonGrupy.setId(kurs.getIdKursy());
jsonGrupy.setDates(name);
}
courses.add(jsonGrupy);
jsonKursy.setCourses(courses);
System.out.println("Test wydruk"+ jsonKursy);
}
return jsonKursy;
}
|
diff --git a/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/InvokeGenerator.java b/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/InvokeGenerator.java
index 88b99a4c..b9e13a0d 100644
--- a/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/InvokeGenerator.java
+++ b/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/InvokeGenerator.java
@@ -1,161 +1,161 @@
/*
* 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.ode.bpel.compiler;
import org.apache.ode.bom.api.Activity;
import org.apache.ode.bom.api.Constants;
import org.apache.ode.bom.api.Correlation;
import org.apache.ode.bom.api.InvokeActivity;
import org.apache.ode.bpel.capi.CompilationException;
import org.apache.ode.bpel.o.OActivity;
import org.apache.ode.bpel.o.OInvoke;
import org.apache.ode.bpel.o.FailureHandling;
import org.apache.ode.bpel.o.OProcess;
import org.apache.ode.bpel.o.OScope;
import org.apache.ode.utils.msg.MessageBundle;
import org.apache.ode.utils.DOMUtils;
import java.util.Collection;
import java.util.List;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
/**
* Generates code for <code><invoke></code> activities.
*/
class InvokeGenerator extends DefaultActivityGenerator {
private static final CommonCompilationMessages __cmsgs = MessageBundle.getMessages(CommonCompilationMessages.class);
private static final InvokeGeneratorMessages __imsgs = MessageBundle.getMessages(InvokeGeneratorMessages.class);
public OActivity newInstance(Activity src) {
return new OInvoke(_context.getOProcess());
}
public void compile(OActivity output, Activity srcx) {
InvokeActivity src = (InvokeActivity)srcx;
OInvoke oinvoke = (OInvoke) output;
oinvoke.partnerLink = _context.resolvePartnerLink(src.getPartnerLink());
oinvoke.operation = _context.resolvePartnerRoleOperation(oinvoke.partnerLink, src.getOperation());
assert oinvoke.operation.getInput() != null; // ensured by resolvePartnerRoleOperation
assert oinvoke.operation.getInput().getMessage() != null; // ensured by resolvePartnerRoleOperation
//TODO: Add portType checking if specified by user
// if (portType != null && !portType.equals(onMessage.partnerLink.myRolePortType.getQName()))
// throw new CompilationException(CMSGSG.errPortTypeMismatch(portType, onMessage.partnerLink.myRolePortType.getQName()));
if (oinvoke.operation.getInput() != null && oinvoke.operation.getInput().getMessage() != null) {
if (src.getInputVar() == null)
throw new CompilationException(__imsgs.errInvokeNoInputMessageForInputOp(oinvoke.operation.getName()));
oinvoke.inputVar = _context.resolveMessageVariable(src.getInputVar(), oinvoke.operation.getInput().getMessage().getQName());
}
if (oinvoke.operation.getOutput() != null && oinvoke.operation.getOutput().getMessage() != null) {
if (src.getOutputVar() == null)
throw new CompilationException(__imsgs.errInvokeNoOutputMessageForOutputOp(oinvoke.operation.getName()));
oinvoke.outputVar = _context.resolveMessageVariable(src.getOutputVar(), oinvoke.operation.getOutput().getMessage().getQName());
}
if (oinvoke.inputVar != null)
doCorrelations(src.getCorrelations(Correlation.CORRPATTERN_OUT), oinvoke.inputVar, oinvoke.assertCorrelationsInput, oinvoke.initCorrelationsInput);
if (oinvoke.outputVar != null)
doCorrelations(src.getCorrelations(Correlation.CORRPATTERN_IN), oinvoke.outputVar, oinvoke.assertCorrelationsOutput, oinvoke.initCorrelationsOutput);
if (!oinvoke.getOwner().version.equals(Constants.NS_BPEL4WS_2003_03)) {
if (!oinvoke.partnerLink.initializePartnerRole && !_context.isPartnerLinkAssigned(oinvoke.partnerLink.getName())) {
throw new CompilationException(__cmsgs.errUninitializedPartnerLinkInInvoke(oinvoke.partnerLink.getName()));
}
}
// Failure handling extensibility element.
Element failure = srcx.getExtensibilityElements().get(FailureHandling.FAILURE_EXT_ELEMENT);
if (failure != null) {
oinvoke.failureHandling = new FailureHandling();
String textValue;
Element element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "retryFor"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null) {
try {
oinvoke.failureHandling.retryFor = Integer.valueOf(textValue);
if (oinvoke.failureHandling.retryFor < 0)
throw new CompilationException(__cmsgs.errInvalidRetryForValue(textValue));
} catch (NumberFormatException except) {
throw new CompilationException(__cmsgs.errInvalidRetryForValue(textValue));
}
}
}
- element = DOMUtils.findChildByName(failure, new QName(null, "retryDelay"));
+ element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "retryDelay"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null) {
try {
oinvoke.failureHandling.retryDelay = Integer.valueOf(textValue);
if (oinvoke.failureHandling.retryDelay < 0)
throw new CompilationException(__cmsgs.errInvalidRetryDelayValue(textValue));
} catch (NumberFormatException except) {
throw new CompilationException(__cmsgs.errInvalidRetryDelayValue(textValue));
}
}
}
- element = DOMUtils.findChildByName(failure, new QName(null, "faultOnFailure"));
+ element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "faultOnFailure"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null)
oinvoke.failureHandling.faultOnFailure = Boolean.valueOf(textValue);
}
}
}
private void doCorrelations(List<Correlation> correlations, OScope.Variable var, Collection<OScope.CorrelationSet> assertCorrelations, Collection<OScope.CorrelationSet> initCorrelations) {
for (Correlation correlation : correlations) {
OScope.CorrelationSet cset = _context.resolveCorrelationSet(correlation.getCorrelationSet());
switch (correlation.getInitiate()) {
case Correlation.INITIATE_NO:
assertCorrelations.add(cset);
break;
case Correlation.INITIATE_YES:
initCorrelations.add(cset);
break;
case Correlation.INITIATE_RENDEZVOUS:
// TODO: fixe errror
throw new UnsupportedOperationException();
}
for (OProcess.OProperty property : cset.properties) {
// Force resolution of alias, to make sure that we have one for this variable-property pair.
try {
_context.resolvePropertyAlias(var, property.name);
} catch (CompilationException ce) {
if (ce.getCompilationMessage().source == null) {
ce.getCompilationMessage().source = correlation;
}
throw ce;
}
//onMessage.
}
}
}
}
| false | true | public void compile(OActivity output, Activity srcx) {
InvokeActivity src = (InvokeActivity)srcx;
OInvoke oinvoke = (OInvoke) output;
oinvoke.partnerLink = _context.resolvePartnerLink(src.getPartnerLink());
oinvoke.operation = _context.resolvePartnerRoleOperation(oinvoke.partnerLink, src.getOperation());
assert oinvoke.operation.getInput() != null; // ensured by resolvePartnerRoleOperation
assert oinvoke.operation.getInput().getMessage() != null; // ensured by resolvePartnerRoleOperation
//TODO: Add portType checking if specified by user
// if (portType != null && !portType.equals(onMessage.partnerLink.myRolePortType.getQName()))
// throw new CompilationException(CMSGSG.errPortTypeMismatch(portType, onMessage.partnerLink.myRolePortType.getQName()));
if (oinvoke.operation.getInput() != null && oinvoke.operation.getInput().getMessage() != null) {
if (src.getInputVar() == null)
throw new CompilationException(__imsgs.errInvokeNoInputMessageForInputOp(oinvoke.operation.getName()));
oinvoke.inputVar = _context.resolveMessageVariable(src.getInputVar(), oinvoke.operation.getInput().getMessage().getQName());
}
if (oinvoke.operation.getOutput() != null && oinvoke.operation.getOutput().getMessage() != null) {
if (src.getOutputVar() == null)
throw new CompilationException(__imsgs.errInvokeNoOutputMessageForOutputOp(oinvoke.operation.getName()));
oinvoke.outputVar = _context.resolveMessageVariable(src.getOutputVar(), oinvoke.operation.getOutput().getMessage().getQName());
}
if (oinvoke.inputVar != null)
doCorrelations(src.getCorrelations(Correlation.CORRPATTERN_OUT), oinvoke.inputVar, oinvoke.assertCorrelationsInput, oinvoke.initCorrelationsInput);
if (oinvoke.outputVar != null)
doCorrelations(src.getCorrelations(Correlation.CORRPATTERN_IN), oinvoke.outputVar, oinvoke.assertCorrelationsOutput, oinvoke.initCorrelationsOutput);
if (!oinvoke.getOwner().version.equals(Constants.NS_BPEL4WS_2003_03)) {
if (!oinvoke.partnerLink.initializePartnerRole && !_context.isPartnerLinkAssigned(oinvoke.partnerLink.getName())) {
throw new CompilationException(__cmsgs.errUninitializedPartnerLinkInInvoke(oinvoke.partnerLink.getName()));
}
}
// Failure handling extensibility element.
Element failure = srcx.getExtensibilityElements().get(FailureHandling.FAILURE_EXT_ELEMENT);
if (failure != null) {
oinvoke.failureHandling = new FailureHandling();
String textValue;
Element element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "retryFor"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null) {
try {
oinvoke.failureHandling.retryFor = Integer.valueOf(textValue);
if (oinvoke.failureHandling.retryFor < 0)
throw new CompilationException(__cmsgs.errInvalidRetryForValue(textValue));
} catch (NumberFormatException except) {
throw new CompilationException(__cmsgs.errInvalidRetryForValue(textValue));
}
}
}
element = DOMUtils.findChildByName(failure, new QName(null, "retryDelay"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null) {
try {
oinvoke.failureHandling.retryDelay = Integer.valueOf(textValue);
if (oinvoke.failureHandling.retryDelay < 0)
throw new CompilationException(__cmsgs.errInvalidRetryDelayValue(textValue));
} catch (NumberFormatException except) {
throw new CompilationException(__cmsgs.errInvalidRetryDelayValue(textValue));
}
}
}
element = DOMUtils.findChildByName(failure, new QName(null, "faultOnFailure"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null)
oinvoke.failureHandling.faultOnFailure = Boolean.valueOf(textValue);
}
}
}
| public void compile(OActivity output, Activity srcx) {
InvokeActivity src = (InvokeActivity)srcx;
OInvoke oinvoke = (OInvoke) output;
oinvoke.partnerLink = _context.resolvePartnerLink(src.getPartnerLink());
oinvoke.operation = _context.resolvePartnerRoleOperation(oinvoke.partnerLink, src.getOperation());
assert oinvoke.operation.getInput() != null; // ensured by resolvePartnerRoleOperation
assert oinvoke.operation.getInput().getMessage() != null; // ensured by resolvePartnerRoleOperation
//TODO: Add portType checking if specified by user
// if (portType != null && !portType.equals(onMessage.partnerLink.myRolePortType.getQName()))
// throw new CompilationException(CMSGSG.errPortTypeMismatch(portType, onMessage.partnerLink.myRolePortType.getQName()));
if (oinvoke.operation.getInput() != null && oinvoke.operation.getInput().getMessage() != null) {
if (src.getInputVar() == null)
throw new CompilationException(__imsgs.errInvokeNoInputMessageForInputOp(oinvoke.operation.getName()));
oinvoke.inputVar = _context.resolveMessageVariable(src.getInputVar(), oinvoke.operation.getInput().getMessage().getQName());
}
if (oinvoke.operation.getOutput() != null && oinvoke.operation.getOutput().getMessage() != null) {
if (src.getOutputVar() == null)
throw new CompilationException(__imsgs.errInvokeNoOutputMessageForOutputOp(oinvoke.operation.getName()));
oinvoke.outputVar = _context.resolveMessageVariable(src.getOutputVar(), oinvoke.operation.getOutput().getMessage().getQName());
}
if (oinvoke.inputVar != null)
doCorrelations(src.getCorrelations(Correlation.CORRPATTERN_OUT), oinvoke.inputVar, oinvoke.assertCorrelationsInput, oinvoke.initCorrelationsInput);
if (oinvoke.outputVar != null)
doCorrelations(src.getCorrelations(Correlation.CORRPATTERN_IN), oinvoke.outputVar, oinvoke.assertCorrelationsOutput, oinvoke.initCorrelationsOutput);
if (!oinvoke.getOwner().version.equals(Constants.NS_BPEL4WS_2003_03)) {
if (!oinvoke.partnerLink.initializePartnerRole && !_context.isPartnerLinkAssigned(oinvoke.partnerLink.getName())) {
throw new CompilationException(__cmsgs.errUninitializedPartnerLinkInInvoke(oinvoke.partnerLink.getName()));
}
}
// Failure handling extensibility element.
Element failure = srcx.getExtensibilityElements().get(FailureHandling.FAILURE_EXT_ELEMENT);
if (failure != null) {
oinvoke.failureHandling = new FailureHandling();
String textValue;
Element element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "retryFor"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null) {
try {
oinvoke.failureHandling.retryFor = Integer.valueOf(textValue);
if (oinvoke.failureHandling.retryFor < 0)
throw new CompilationException(__cmsgs.errInvalidRetryForValue(textValue));
} catch (NumberFormatException except) {
throw new CompilationException(__cmsgs.errInvalidRetryForValue(textValue));
}
}
}
element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "retryDelay"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null) {
try {
oinvoke.failureHandling.retryDelay = Integer.valueOf(textValue);
if (oinvoke.failureHandling.retryDelay < 0)
throw new CompilationException(__cmsgs.errInvalidRetryDelayValue(textValue));
} catch (NumberFormatException except) {
throw new CompilationException(__cmsgs.errInvalidRetryDelayValue(textValue));
}
}
}
element = DOMUtils.findChildByName(failure, new QName(FailureHandling.EXTENSION_NS_URI, "faultOnFailure"));
if (element != null) {
textValue = DOMUtils.getTextContent(element);
if (textValue != null)
oinvoke.failureHandling.faultOnFailure = Boolean.valueOf(textValue);
}
}
}
|
diff --git a/PagingSystem/src/gui/PagingProgressPanel.java b/PagingSystem/src/gui/PagingProgressPanel.java
index 210a7af..b301244 100644
--- a/PagingSystem/src/gui/PagingProgressPanel.java
+++ b/PagingSystem/src/gui/PagingProgressPanel.java
@@ -1,42 +1,42 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
/**
*
* @author Shawn
*/
public class PagingProgressPanel extends JPanel {
private JProgressBar bar;
private JLabel label;
public PagingProgressPanel() {
super(new BorderLayout());
init();
}
private void init() {
bar = new JProgressBar(0, 100);
- label = new JLabel();
+ label = new JLabel("No running pages");
this.add(label, BorderLayout.NORTH);
this.add(bar, BorderLayout.SOUTH);
}
public JProgressBar getProgressBar() {
return bar;
}
public JLabel getLabel() {
return label;
}
}
| true | true | private void init() {
bar = new JProgressBar(0, 100);
label = new JLabel();
this.add(label, BorderLayout.NORTH);
this.add(bar, BorderLayout.SOUTH);
}
| private void init() {
bar = new JProgressBar(0, 100);
label = new JLabel("No running pages");
this.add(label, BorderLayout.NORTH);
this.add(bar, BorderLayout.SOUTH);
}
|
diff --git a/src/org/connectbot/service/TerminalKeyListener.java b/src/org/connectbot/service/TerminalKeyListener.java
index 952f3cd..dca7d37 100644
--- a/src/org/connectbot/service/TerminalKeyListener.java
+++ b/src/org/connectbot/service/TerminalKeyListener.java
@@ -1,578 +1,578 @@
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 Kenny Root, Jeffrey Sharkey
*
* 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.connectbot.service;
import java.io.IOException;
import org.connectbot.TerminalView;
import org.connectbot.bean.SelectionArea;
import org.connectbot.util.PreferenceConstants;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import de.mud.terminal.VDUBuffer;
import de.mud.terminal.vt320;
/**
* @author kenny
*
*/
@SuppressWarnings("deprecation") // for ClipboardManager
public class TerminalKeyListener implements OnKeyListener, OnSharedPreferenceChangeListener {
private static final String TAG = "ConnectBot.OnKeyListener";
public final static int META_CTRL_ON = 0x01;
public final static int META_CTRL_LOCK = 0x02;
public final static int META_ALT_ON = 0x04;
public final static int META_ALT_LOCK = 0x08;
public final static int META_SHIFT_ON = 0x10;
public final static int META_SHIFT_LOCK = 0x20;
public final static int META_SLASH = 0x40;
public final static int META_TAB = 0x80;
// The bit mask of momentary and lock states for each
public final static int META_CTRL_MASK = META_CTRL_ON | META_CTRL_LOCK;
public final static int META_ALT_MASK = META_ALT_ON | META_ALT_LOCK;
public final static int META_SHIFT_MASK = META_SHIFT_ON | META_SHIFT_LOCK;
// backport constants from api level 11
public final static int KEYCODE_ESCAPE = 111;
public final static int HC_META_CTRL_ON = 4096;
// All the transient key codes
public final static int META_TRANSIENT = META_CTRL_ON | META_ALT_ON
| META_SHIFT_ON;
private final TerminalManager manager;
private final TerminalBridge bridge;
private final VDUBuffer buffer;
private String keymode = null;
private boolean hardKeyboard = false;
private int metaState = 0;
private int mDeadKey = 0;
// TODO add support for the new API.
private ClipboardManager clipboard = null;
private boolean selectingForCopy = false;
private final SelectionArea selectionArea;
private String encoding;
private final SharedPreferences prefs;
public TerminalKeyListener(TerminalManager manager,
TerminalBridge bridge,
VDUBuffer buffer,
String encoding) {
this.manager = manager;
this.bridge = bridge;
this.buffer = buffer;
this.encoding = encoding;
selectionArea = new SelectionArea();
prefs = PreferenceManager.getDefaultSharedPreferences(manager);
prefs.registerOnSharedPreferenceChangeListener(this);
hardKeyboard = (manager.res.getConfiguration().keyboard
== Configuration.KEYBOARD_QWERTY);
updateKeymode();
}
/**
* Handle onKey() events coming down from a {@link TerminalView} above us.
* Modify the keys to make more sense to a host then pass it to the transport.
*/
public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
if (keyCode == KeyEvent.KEYCODE_UNKNOWN &&
event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
int curMetaState = event.getMetaState();
final int orgMetaState = curMetaState;
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
}
int key = event.getUnicodeChar(curMetaState);
// no hard keyboard? ALT-k should pass through to below
if ((orgMetaState & KeyEvent.META_ALT_ON) != 0 &&
(!hardKeyboard || hardKeyboardHidden)) {
key = 0;
}
if ((key & KeyCharacterMap.COMBINING_ACCENT) != 0) {
mDeadKey = key & KeyCharacterMap.COMBINING_ACCENT_MASK;
return true;
}
if (mDeadKey != 0) {
key = KeyCharacterMap.getDeadChar(mDeadKey, keyCode);
mDeadKey = 0;
}
- final boolean printing = (key != 0);
+ final boolean printing = (key != 0 && keyCode != KeyEvent.KEYCODE_ENTER);
// otherwise pass through to existing session
// print normal keys
if (printing) {
metaState &= ~(META_SLASH | META_TAB);
// Remove shift and alt modifiers
final int lastMetaState = metaState;
metaState &= ~(META_SHIFT_ON | META_ALT_ON);
if (metaState != lastMetaState) {
bridge.redraw();
}
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
// If there is no hard keyboard or there is a hard keyboard currently hidden,
// CTRL-1 through CTRL-9 will send F1 through F9
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
key = keyAsControl(key);
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80)
bridge.transport.write(key);
else
// TODO write encoding routine that doesn't allocate each time
bridge.transport.write(new String(Character.toChars(key))
.getBytes(encoding));
return true;
}
// send ctrl and meta-keys as appropriate
if (!hardKeyboard || hardKeyboardHidden) {
int k = event.getUnicodeChar(0);
int k0 = k;
boolean sendCtrl = false;
boolean sendMeta = false;
if (k != 0) {
if ((orgMetaState & HC_META_CTRL_ON) != 0) {
k = keyAsControl(k);
if (k != k0)
sendCtrl = true;
// send F1-F10 via CTRL-1 through CTRL-0
if (!sendCtrl && sendFunctionKey(keyCode))
return true;
} else if ((orgMetaState & KeyEvent.META_ALT_ON) != 0) {
sendMeta = true;
sendEscape();
}
if (sendMeta || sendCtrl) {
bridge.transport.write(k);
return true;
}
}
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KEYCODE_ESCAPE:
sendEscape();
return true;
case KeyEvent.KEYCODE_TAB:
bridge.transport.write(0x09);
return true;
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
public int keyAsControl(int key) {
// Support CTRL-a through CTRL-z
if (key >= 0x61 && key <= 0x7A)
key -= 0x60;
// Support CTRL-A through CTRL-_
else if (key >= 0x41 && key <= 0x5F)
key -= 0x40;
// CTRL-space sends NULL
else if (key == 0x20)
key = 0x00;
// CTRL-? sends DEL
else if (key == 0x3F)
key = 0x7F;
return key;
}
public void sendEscape() {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
}
/**
* @param key
* @return successful
*/
private boolean sendFunctionKey(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_1:
((vt320) buffer).keyPressed(vt320.KEY_F1, ' ', 0);
return true;
case KeyEvent.KEYCODE_2:
((vt320) buffer).keyPressed(vt320.KEY_F2, ' ', 0);
return true;
case KeyEvent.KEYCODE_3:
((vt320) buffer).keyPressed(vt320.KEY_F3, ' ', 0);
return true;
case KeyEvent.KEYCODE_4:
((vt320) buffer).keyPressed(vt320.KEY_F4, ' ', 0);
return true;
case KeyEvent.KEYCODE_5:
((vt320) buffer).keyPressed(vt320.KEY_F5, ' ', 0);
return true;
case KeyEvent.KEYCODE_6:
((vt320) buffer).keyPressed(vt320.KEY_F6, ' ', 0);
return true;
case KeyEvent.KEYCODE_7:
((vt320) buffer).keyPressed(vt320.KEY_F7, ' ', 0);
return true;
case KeyEvent.KEYCODE_8:
((vt320) buffer).keyPressed(vt320.KEY_F8, ' ', 0);
return true;
case KeyEvent.KEYCODE_9:
((vt320) buffer).keyPressed(vt320.KEY_F9, ' ', 0);
return true;
case KeyEvent.KEYCODE_0:
((vt320) buffer).keyPressed(vt320.KEY_F10, ' ', 0);
return true;
default:
return false;
}
}
/**
* Handle meta key presses where the key can be locked on.
* <p>
* 1st press: next key to have meta state<br />
* 2nd press: meta state is locked on<br />
* 3rd press: disable meta state
*
* @param code
*/
public void metaPress(int code) {
if ((metaState & (code << 1)) != 0) {
metaState &= ~(code << 1);
} else if ((metaState & code) != 0) {
metaState &= ~code;
metaState |= code << 1;
} else
metaState |= code;
bridge.redraw();
}
public void setTerminalKeyMode(String keymode) {
this.keymode = keymode;
}
private int getStateForBuffer() {
int bufferState = 0;
if ((metaState & META_CTRL_MASK) != 0)
bufferState |= vt320.KEY_CONTROL;
if ((metaState & META_SHIFT_MASK) != 0)
bufferState |= vt320.KEY_SHIFT;
if ((metaState & META_ALT_MASK) != 0)
bufferState |= vt320.KEY_ALT;
return bufferState;
}
public int getMetaState() {
return metaState;
}
public int getDeadKey() {
return mDeadKey;
}
public void setClipboardManager(ClipboardManager clipboard) {
this.clipboard = clipboard;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PreferenceConstants.KEYMODE.equals(key)) {
updateKeymode();
}
}
private void updateKeymode() {
keymode = prefs.getString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
}
public void setCharset(String encoding) {
this.encoding = encoding;
}
}
| true | true | public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
if (keyCode == KeyEvent.KEYCODE_UNKNOWN &&
event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
int curMetaState = event.getMetaState();
final int orgMetaState = curMetaState;
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
}
int key = event.getUnicodeChar(curMetaState);
// no hard keyboard? ALT-k should pass through to below
if ((orgMetaState & KeyEvent.META_ALT_ON) != 0 &&
(!hardKeyboard || hardKeyboardHidden)) {
key = 0;
}
if ((key & KeyCharacterMap.COMBINING_ACCENT) != 0) {
mDeadKey = key & KeyCharacterMap.COMBINING_ACCENT_MASK;
return true;
}
if (mDeadKey != 0) {
key = KeyCharacterMap.getDeadChar(mDeadKey, keyCode);
mDeadKey = 0;
}
final boolean printing = (key != 0);
// otherwise pass through to existing session
// print normal keys
if (printing) {
metaState &= ~(META_SLASH | META_TAB);
// Remove shift and alt modifiers
final int lastMetaState = metaState;
metaState &= ~(META_SHIFT_ON | META_ALT_ON);
if (metaState != lastMetaState) {
bridge.redraw();
}
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
// If there is no hard keyboard or there is a hard keyboard currently hidden,
// CTRL-1 through CTRL-9 will send F1 through F9
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
key = keyAsControl(key);
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80)
bridge.transport.write(key);
else
// TODO write encoding routine that doesn't allocate each time
bridge.transport.write(new String(Character.toChars(key))
.getBytes(encoding));
return true;
}
// send ctrl and meta-keys as appropriate
if (!hardKeyboard || hardKeyboardHidden) {
int k = event.getUnicodeChar(0);
int k0 = k;
boolean sendCtrl = false;
boolean sendMeta = false;
if (k != 0) {
if ((orgMetaState & HC_META_CTRL_ON) != 0) {
k = keyAsControl(k);
if (k != k0)
sendCtrl = true;
// send F1-F10 via CTRL-1 through CTRL-0
if (!sendCtrl && sendFunctionKey(keyCode))
return true;
} else if ((orgMetaState & KeyEvent.META_ALT_ON) != 0) {
sendMeta = true;
sendEscape();
}
if (sendMeta || sendCtrl) {
bridge.transport.write(k);
return true;
}
}
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KEYCODE_ESCAPE:
sendEscape();
return true;
case KeyEvent.KEYCODE_TAB:
bridge.transport.write(0x09);
return true;
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
| public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
if (keyCode == KeyEvent.KEYCODE_UNKNOWN &&
event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
int curMetaState = event.getMetaState();
final int orgMetaState = curMetaState;
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
}
int key = event.getUnicodeChar(curMetaState);
// no hard keyboard? ALT-k should pass through to below
if ((orgMetaState & KeyEvent.META_ALT_ON) != 0 &&
(!hardKeyboard || hardKeyboardHidden)) {
key = 0;
}
if ((key & KeyCharacterMap.COMBINING_ACCENT) != 0) {
mDeadKey = key & KeyCharacterMap.COMBINING_ACCENT_MASK;
return true;
}
if (mDeadKey != 0) {
key = KeyCharacterMap.getDeadChar(mDeadKey, keyCode);
mDeadKey = 0;
}
final boolean printing = (key != 0 && keyCode != KeyEvent.KEYCODE_ENTER);
// otherwise pass through to existing session
// print normal keys
if (printing) {
metaState &= ~(META_SLASH | META_TAB);
// Remove shift and alt modifiers
final int lastMetaState = metaState;
metaState &= ~(META_SHIFT_ON | META_ALT_ON);
if (metaState != lastMetaState) {
bridge.redraw();
}
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
// If there is no hard keyboard or there is a hard keyboard currently hidden,
// CTRL-1 through CTRL-9 will send F1 through F9
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
key = keyAsControl(key);
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80)
bridge.transport.write(key);
else
// TODO write encoding routine that doesn't allocate each time
bridge.transport.write(new String(Character.toChars(key))
.getBytes(encoding));
return true;
}
// send ctrl and meta-keys as appropriate
if (!hardKeyboard || hardKeyboardHidden) {
int k = event.getUnicodeChar(0);
int k0 = k;
boolean sendCtrl = false;
boolean sendMeta = false;
if (k != 0) {
if ((orgMetaState & HC_META_CTRL_ON) != 0) {
k = keyAsControl(k);
if (k != k0)
sendCtrl = true;
// send F1-F10 via CTRL-1 through CTRL-0
if (!sendCtrl && sendFunctionKey(keyCode))
return true;
} else if ((orgMetaState & KeyEvent.META_ALT_ON) != 0) {
sendMeta = true;
sendEscape();
}
if (sendMeta || sendCtrl) {
bridge.transport.write(k);
return true;
}
}
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KEYCODE_ESCAPE:
sendEscape();
return true;
case KeyEvent.KEYCODE_TAB:
bridge.transport.write(0x09);
return true;
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
|
diff --git a/src/edu/ucsb/cs56/projects/utilities/TSA_Encryption/Cryptography.java b/src/edu/ucsb/cs56/projects/utilities/TSA_Encryption/Cryptography.java
index bd0be68..f155847 100644
--- a/src/edu/ucsb/cs56/projects/utilities/TSA_Encryption/Cryptography.java
+++ b/src/edu/ucsb/cs56/projects/utilities/TSA_Encryption/Cryptography.java
@@ -1,69 +1,70 @@
package edu.ucsb.cs56.projects.utilities.TSA_Encryption;
/**
Cryptography class. Only 2 methods: the constructor, and encrypt.
@author Callum Steele, Miranda Aperghis, Trevor Adelman
@version CS56 S13, 05/09/2013
*/
public class Cryptography{
private long totalCheck = 0;
private long total = 1;
/**
basic class constructor
@return nothing (void function)
*/
public Cryptography() {}
/**
The encrypt function receives an array of integers and transforms it into a long value.
@return a long with the resulting value
@param numlist an int[] (list on integers) that gets iterated through throughout the function, the integers must be greater than or equal to 1 and less than or equal to 1000, and the length of the list must be greater than or equal to 2 and less than or equal to 50.
*/
public long encrypt(int[] numList) {
for (int r=0; r < numList.length; r++){
if (numList[r] < 1 || numList[r] > 1000){
System.out.println("Number Error; Integer x must follow: 1 <= x <= 1000");
- return totalCheck;}
+ return totalCheck;
+ }
}
if (numList.length > 50 || numList.length < 2){
System.out.println("Number List Error; List length must be between 2 and 50 inclusive");
return totalCheck;
}
for (int i=0; i < numList.length; i++){
numList[i]++;
total = 1;
for (int t=0; t < numList.length; t++){
total = total * numList[t];
if (total > totalCheck){
totalCheck = total;
}
}
numList[i]--;
}
return totalCheck;
}
/**
Sets up a Cryptography object and uses it to encrypt an int array of {1,2,3}, outputting the result
@param args the command line arguments
*/
public static void main(String[] args){
Cryptography c1 = new Cryptography();
int[] ex1 = {1,2,3};
long output = c1.encrypt(ex1);
System.out.println(output);
}
}
| true | true | public long encrypt(int[] numList) {
for (int r=0; r < numList.length; r++){
if (numList[r] < 1 || numList[r] > 1000){
System.out.println("Number Error; Integer x must follow: 1 <= x <= 1000");
return totalCheck;}
}
if (numList.length > 50 || numList.length < 2){
System.out.println("Number List Error; List length must be between 2 and 50 inclusive");
return totalCheck;
}
for (int i=0; i < numList.length; i++){
numList[i]++;
total = 1;
for (int t=0; t < numList.length; t++){
total = total * numList[t];
if (total > totalCheck){
totalCheck = total;
}
}
numList[i]--;
}
return totalCheck;
}
| public long encrypt(int[] numList) {
for (int r=0; r < numList.length; r++){
if (numList[r] < 1 || numList[r] > 1000){
System.out.println("Number Error; Integer x must follow: 1 <= x <= 1000");
return totalCheck;
}
}
if (numList.length > 50 || numList.length < 2){
System.out.println("Number List Error; List length must be between 2 and 50 inclusive");
return totalCheck;
}
for (int i=0; i < numList.length; i++){
numList[i]++;
total = 1;
for (int t=0; t < numList.length; t++){
total = total * numList[t];
if (total > totalCheck){
totalCheck = total;
}
}
numList[i]--;
}
return totalCheck;
}
|
diff --git a/examples/rtest.java b/examples/rtest.java
index 8c6a6ff..6ea31b2 100644
--- a/examples/rtest.java
+++ b/examples/rtest.java
@@ -1,233 +1,238 @@
import java.io.*;
import java.awt.Frame;
import java.awt.FileDialog;
import java.util.Enumeration;
import org.rosuda.JRI.Rengine;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.RList;
import org.rosuda.JRI.RVector;
import org.rosuda.JRI.RMainLoopCallbacks;
class TextConsole implements RMainLoopCallbacks
{
public void rWriteConsole(Rengine re, String text) {
System.out.print(text);
}
public void rBusy(Rengine re, int which) {
System.out.println("rBusy("+which+")");
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
System.out.print(prompt);
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
return (s==null||s.length()==0)?s:s+"\n";
} catch (Exception e) {
System.out.println("jriReadConsole exception: "+e.getMessage());
}
return null;
}
public void rShowMessage(Rengine re, String message) {
System.out.println("rShowMessage \""+message+"\"");
}
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(new Frame(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
fd.show();
String res=null;
if (fd.getDirectory()!=null) res=fd.getDirectory();
if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
return res;
}
public void rFlushConsole (Rengine re) {
}
public void rLoadHistory (Rengine re, String filename) {
}
public void rSaveHistory (Rengine re, String filename) {
}
}
public class rtest {
public static void main(String[] args) {
+ // just making sure we have the right version of everything
+ if (!Rengine.versionCheck()) {
+ System.err.println("** Version mismatch - Java files don't match library version.");
+ System.exit(1);
+ }
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
Rengine re=new Rengine(args, false, new TextConsole());
System.out.println("Rengine created, waiting for R");
// the engine creates R is a new thread, so we should wait until it's ready
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
/* High-level API - do not use RNI methods unless there is no other way
to accomplish what you want */
try {
REXP x;
re.eval("data(iris)",false);
System.out.println(x=re.eval("iris"));
// generic vectors are RVector to accomodate names
RVector v = x.asVector();
if (v.getNames()!=null) {
System.out.println("has names:");
for (Enumeration e = v.getNames().elements() ; e.hasMoreElements() ;) {
System.out.println(e.nextElement());
}
}
// for compatibility with Rserve we allow casting of vectors to lists
RList vl = x.asList();
String[] k = vl.keys();
if (k!=null) {
System.out.println("and once again from the list:");
int i=0; while (i<k.length) System.out.println(k[i++]);
}
// get boolean array
System.out.println(x=re.eval("iris[[1]]>mean(iris[[1]])"));
// R knows about TRUE/FALSE/NA, so we cannot use boolean[] this way
// instead, we use int[] which is more convenient (and what R uses internally anyway)
int[] bi = x.asIntArray();
{
int i = 0; while (i<bi.length) { System.out.print(bi[i]==0?"F ":(bi[i]==1?"T ":"NA ")); i++; }
System.out.println("");
}
// push a boolean array
boolean by[] = { true, false, false };
re.assign("bool", by);
System.out.println(x=re.eval("bool"));
// asBool returns the first element of the array as RBool
// (mostly useful for boolean arrays of the length 1). is should return true
System.out.println("isTRUE? "+x.asBool().isTRUE());
// now for a real dotted-pair list:
System.out.println(x=re.eval("pairlist(a=1,b='foo',c=1:5)"));
RList l = x.asList();
if (l!=null) {
int i=0;
String [] a = l.keys();
System.out.println("Keys:");
while (i<a.length) System.out.println(a[i++]);
System.out.println("Contents:");
i=0;
while (i<a.length) System.out.println(l.at(i++));
}
System.out.println(re.eval("sqrt(36)"));
} catch (Exception e) {
System.out.println("EX:"+e);
e.printStackTrace();
}
// Part 2 - low-level API - for illustration purposes only!
//System.exit(0);
// simple assignment like a<-"hello" (env=0 means use R_GlobalEnv)
long xp1 = re.rniPutString("hello");
re.rniAssign("a", xp1, 0);
// Example: how to create a named list or data.frame
double da[] = {1.2, 2.3, 4.5};
double db[] = {1.4, 2.6, 4.2};
long xp3 = re.rniPutDoubleArray(da);
long xp4 = re.rniPutDoubleArray(db);
// now build a list (generic vector is how that's called in R)
long la[] = {xp3, xp4};
long xp5 = re.rniPutVector(la);
// now let's add names
String sa[] = {"a","b"};
long xp2 = re.rniPutStringArray(sa);
re.rniSetAttr(xp5, "names", xp2);
// ok, we have a proper list now
// we could use assign and then eval "b<-data.frame(b)", but for now let's build it by hand:
String rn[] = {"1", "2", "3"};
long xp7 = re.rniPutStringArray(rn);
re.rniSetAttr(xp5, "row.names", xp7);
long xp6 = re.rniPutString("data.frame");
re.rniSetAttr(xp5, "class", xp6);
// assign the whole thing to the "b" variable
re.rniAssign("b", xp5, 0);
{
System.out.println("Parsing");
long e=re.rniParse("data(iris)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
}
{
System.out.println("Parsing");
long e=re.rniParse("iris", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
}
{
System.out.println("Parsing");
long e=re.rniParse("names(iris)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
String s[]=x.asStringArray();
if (s!=null) {
int i=0; while (i<s.length) { System.out.println("["+i+"] \""+s[i]+"\""); i++; }
}
}
{
System.out.println("Parsing");
long e=re.rniParse("rnorm(10)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
double d[]=x.asDoubleArray();
if (d!=null) {
int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
System.out.println("");
}
System.out.println("");
}
{
REXP x=re.eval("1:10");
System.out.println("REXP result = "+x);
int d[]=x.asIntArray();
if (d!=null) {
int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
System.out.println("");
}
}
re.eval("print(1:10/3)");
if (true) {
// so far we used R as a computational slave without REPL
// now we start the loop, so the user can use the console
System.out.println("Now the console is yours ... have fun");
re.startMainLoop();
} else {
re.end();
System.out.println("end");
}
}
}
| true | true | public static void main(String[] args) {
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
Rengine re=new Rengine(args, false, new TextConsole());
System.out.println("Rengine created, waiting for R");
// the engine creates R is a new thread, so we should wait until it's ready
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
/* High-level API - do not use RNI methods unless there is no other way
to accomplish what you want */
try {
REXP x;
re.eval("data(iris)",false);
System.out.println(x=re.eval("iris"));
// generic vectors are RVector to accomodate names
RVector v = x.asVector();
if (v.getNames()!=null) {
System.out.println("has names:");
for (Enumeration e = v.getNames().elements() ; e.hasMoreElements() ;) {
System.out.println(e.nextElement());
}
}
// for compatibility with Rserve we allow casting of vectors to lists
RList vl = x.asList();
String[] k = vl.keys();
if (k!=null) {
System.out.println("and once again from the list:");
int i=0; while (i<k.length) System.out.println(k[i++]);
}
// get boolean array
System.out.println(x=re.eval("iris[[1]]>mean(iris[[1]])"));
// R knows about TRUE/FALSE/NA, so we cannot use boolean[] this way
// instead, we use int[] which is more convenient (and what R uses internally anyway)
int[] bi = x.asIntArray();
{
int i = 0; while (i<bi.length) { System.out.print(bi[i]==0?"F ":(bi[i]==1?"T ":"NA ")); i++; }
System.out.println("");
}
// push a boolean array
boolean by[] = { true, false, false };
re.assign("bool", by);
System.out.println(x=re.eval("bool"));
// asBool returns the first element of the array as RBool
// (mostly useful for boolean arrays of the length 1). is should return true
System.out.println("isTRUE? "+x.asBool().isTRUE());
// now for a real dotted-pair list:
System.out.println(x=re.eval("pairlist(a=1,b='foo',c=1:5)"));
RList l = x.asList();
if (l!=null) {
int i=0;
String [] a = l.keys();
System.out.println("Keys:");
while (i<a.length) System.out.println(a[i++]);
System.out.println("Contents:");
i=0;
while (i<a.length) System.out.println(l.at(i++));
}
System.out.println(re.eval("sqrt(36)"));
} catch (Exception e) {
System.out.println("EX:"+e);
e.printStackTrace();
}
// Part 2 - low-level API - for illustration purposes only!
//System.exit(0);
// simple assignment like a<-"hello" (env=0 means use R_GlobalEnv)
long xp1 = re.rniPutString("hello");
re.rniAssign("a", xp1, 0);
// Example: how to create a named list or data.frame
double da[] = {1.2, 2.3, 4.5};
double db[] = {1.4, 2.6, 4.2};
long xp3 = re.rniPutDoubleArray(da);
long xp4 = re.rniPutDoubleArray(db);
// now build a list (generic vector is how that's called in R)
long la[] = {xp3, xp4};
long xp5 = re.rniPutVector(la);
// now let's add names
String sa[] = {"a","b"};
long xp2 = re.rniPutStringArray(sa);
re.rniSetAttr(xp5, "names", xp2);
// ok, we have a proper list now
// we could use assign and then eval "b<-data.frame(b)", but for now let's build it by hand:
String rn[] = {"1", "2", "3"};
long xp7 = re.rniPutStringArray(rn);
re.rniSetAttr(xp5, "row.names", xp7);
long xp6 = re.rniPutString("data.frame");
re.rniSetAttr(xp5, "class", xp6);
// assign the whole thing to the "b" variable
re.rniAssign("b", xp5, 0);
{
System.out.println("Parsing");
long e=re.rniParse("data(iris)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
}
{
System.out.println("Parsing");
long e=re.rniParse("iris", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
}
{
System.out.println("Parsing");
long e=re.rniParse("names(iris)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
String s[]=x.asStringArray();
if (s!=null) {
int i=0; while (i<s.length) { System.out.println("["+i+"] \""+s[i]+"\""); i++; }
}
}
{
System.out.println("Parsing");
long e=re.rniParse("rnorm(10)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
double d[]=x.asDoubleArray();
if (d!=null) {
int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
System.out.println("");
}
System.out.println("");
}
{
REXP x=re.eval("1:10");
System.out.println("REXP result = "+x);
int d[]=x.asIntArray();
if (d!=null) {
int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
System.out.println("");
}
}
re.eval("print(1:10/3)");
if (true) {
// so far we used R as a computational slave without REPL
// now we start the loop, so the user can use the console
System.out.println("Now the console is yours ... have fun");
re.startMainLoop();
} else {
re.end();
System.out.println("end");
}
}
| public static void main(String[] args) {
// just making sure we have the right version of everything
if (!Rengine.versionCheck()) {
System.err.println("** Version mismatch - Java files don't match library version.");
System.exit(1);
}
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
Rengine re=new Rengine(args, false, new TextConsole());
System.out.println("Rengine created, waiting for R");
// the engine creates R is a new thread, so we should wait until it's ready
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
/* High-level API - do not use RNI methods unless there is no other way
to accomplish what you want */
try {
REXP x;
re.eval("data(iris)",false);
System.out.println(x=re.eval("iris"));
// generic vectors are RVector to accomodate names
RVector v = x.asVector();
if (v.getNames()!=null) {
System.out.println("has names:");
for (Enumeration e = v.getNames().elements() ; e.hasMoreElements() ;) {
System.out.println(e.nextElement());
}
}
// for compatibility with Rserve we allow casting of vectors to lists
RList vl = x.asList();
String[] k = vl.keys();
if (k!=null) {
System.out.println("and once again from the list:");
int i=0; while (i<k.length) System.out.println(k[i++]);
}
// get boolean array
System.out.println(x=re.eval("iris[[1]]>mean(iris[[1]])"));
// R knows about TRUE/FALSE/NA, so we cannot use boolean[] this way
// instead, we use int[] which is more convenient (and what R uses internally anyway)
int[] bi = x.asIntArray();
{
int i = 0; while (i<bi.length) { System.out.print(bi[i]==0?"F ":(bi[i]==1?"T ":"NA ")); i++; }
System.out.println("");
}
// push a boolean array
boolean by[] = { true, false, false };
re.assign("bool", by);
System.out.println(x=re.eval("bool"));
// asBool returns the first element of the array as RBool
// (mostly useful for boolean arrays of the length 1). is should return true
System.out.println("isTRUE? "+x.asBool().isTRUE());
// now for a real dotted-pair list:
System.out.println(x=re.eval("pairlist(a=1,b='foo',c=1:5)"));
RList l = x.asList();
if (l!=null) {
int i=0;
String [] a = l.keys();
System.out.println("Keys:");
while (i<a.length) System.out.println(a[i++]);
System.out.println("Contents:");
i=0;
while (i<a.length) System.out.println(l.at(i++));
}
System.out.println(re.eval("sqrt(36)"));
} catch (Exception e) {
System.out.println("EX:"+e);
e.printStackTrace();
}
// Part 2 - low-level API - for illustration purposes only!
//System.exit(0);
// simple assignment like a<-"hello" (env=0 means use R_GlobalEnv)
long xp1 = re.rniPutString("hello");
re.rniAssign("a", xp1, 0);
// Example: how to create a named list or data.frame
double da[] = {1.2, 2.3, 4.5};
double db[] = {1.4, 2.6, 4.2};
long xp3 = re.rniPutDoubleArray(da);
long xp4 = re.rniPutDoubleArray(db);
// now build a list (generic vector is how that's called in R)
long la[] = {xp3, xp4};
long xp5 = re.rniPutVector(la);
// now let's add names
String sa[] = {"a","b"};
long xp2 = re.rniPutStringArray(sa);
re.rniSetAttr(xp5, "names", xp2);
// ok, we have a proper list now
// we could use assign and then eval "b<-data.frame(b)", but for now let's build it by hand:
String rn[] = {"1", "2", "3"};
long xp7 = re.rniPutStringArray(rn);
re.rniSetAttr(xp5, "row.names", xp7);
long xp6 = re.rniPutString("data.frame");
re.rniSetAttr(xp5, "class", xp6);
// assign the whole thing to the "b" variable
re.rniAssign("b", xp5, 0);
{
System.out.println("Parsing");
long e=re.rniParse("data(iris)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
}
{
System.out.println("Parsing");
long e=re.rniParse("iris", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
}
{
System.out.println("Parsing");
long e=re.rniParse("names(iris)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
String s[]=x.asStringArray();
if (s!=null) {
int i=0; while (i<s.length) { System.out.println("["+i+"] \""+s[i]+"\""); i++; }
}
}
{
System.out.println("Parsing");
long e=re.rniParse("rnorm(10)", 1);
System.out.println("Result = "+e+", running eval");
long r=re.rniEval(e, 0);
System.out.println("Result = "+r+", building REXP");
REXP x=new REXP(re, r);
System.out.println("REXP result = "+x);
double d[]=x.asDoubleArray();
if (d!=null) {
int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
System.out.println("");
}
System.out.println("");
}
{
REXP x=re.eval("1:10");
System.out.println("REXP result = "+x);
int d[]=x.asIntArray();
if (d!=null) {
int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
System.out.println("");
}
}
re.eval("print(1:10/3)");
if (true) {
// so far we used R as a computational slave without REPL
// now we start the loop, so the user can use the console
System.out.println("Now the console is yours ... have fun");
re.startMainLoop();
} else {
re.end();
System.out.println("end");
}
}
|
diff --git a/src/main/java/tconstruct/util/TEventHandler.java b/src/main/java/tconstruct/util/TEventHandler.java
index 51457333b..84ed6937c 100644
--- a/src/main/java/tconstruct/util/TEventHandler.java
+++ b/src/main/java/tconstruct/util/TEventHandler.java
@@ -1,632 +1,634 @@
package tconstruct.util;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EntityLivingData;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.monster.EntityGhast;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.world.GameRules;
import net.minecraft.world.World;
import net.minecraftforge.event.Event;
import net.minecraftforge.event.Event.Result;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.living.LivingSpawnEvent;
import net.minecraftforge.event.entity.player.BonemealEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action;
import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent;
import tconstruct.*;
import tconstruct.achievements.*;
import tconstruct.blocks.*;
import tconstruct.common.*;
import tconstruct.items.tools.*;
import tconstruct.library.*;
import tconstruct.library.crafting.*;
import tconstruct.library.event.*;
import tconstruct.library.tools.*;
import tconstruct.modifiers.*;
import tconstruct.util.config.*;
import tconstruct.util.player.*;
public class TEventHandler
{
Random random = new Random();
private Object evt;
/* Crafting */
@ForgeSubscribe
public void craftTool (ToolCraftEvent.NormalTool event)
{
NBTTagCompound toolTag = event.toolTag.getCompoundTag("InfiTool");
if (PHConstruct.denyMattock && event.tool == TContent.mattock)
{
int head = toolTag.getInteger("Head");
int handle = toolTag.getInteger("Handle");
int accessory = toolTag.getInteger("Accessory");
if (!allowCrafting(head, handle, accessory))
{
event.setResult(Result.DENY);
return;
}
}
int thaum = 0;
if (toolTag.getInteger("Head") == 31)
thaum++;
if (toolTag.getInteger("Handle") == 31)
thaum++;
if (toolTag.getInteger("Accessory") == 31)
thaum++;
if (toolTag.getInteger("Extra") == 31)
thaum++;
if ((thaum >= 3) || (!toolTag.hasKey("Accessory") && thaum >= 2))
{
int modifiers = toolTag.getInteger("Modifiers");
modifiers += 2;
toolTag.setInteger("Modifiers", modifiers);
}
else if (thaum >= 1)
{
int modifiers = toolTag.getInteger("Modifiers");
modifiers += 1;
toolTag.setInteger("Modifiers", modifiers);
}
if (event.tool == TContent.shortbow)
{
BowMaterial top = TConstructRegistry.getBowMaterial(toolTag.getInteger("Head"));
BowMaterial bottom = TConstructRegistry.getBowMaterial(toolTag.getInteger("Accessory"));
BowstringMaterial string = (BowstringMaterial) TConstructRegistry.getCustomMaterial(toolTag.getInteger("Handle"), BowstringMaterial.class);
if (top != null && bottom != null && string != null)
{
if (toolTag.getInteger("Handle") == 1)
{
int modifiers = toolTag.getInteger("Modifiers");
modifiers += 1;
toolTag.setInteger("Modifiers", modifiers);
}
int durability = (int) ((top.durability + bottom.durability) / 2 * string.durabilityModifier);
toolTag.setInteger("TotalDurability", durability);
toolTag.setInteger("BaseDurability", durability);
int drawSpeed = (int) ((top.drawspeed + bottom.drawspeed) / 2 * string.drawspeedModifier);
toolTag.setInteger("DrawSpeed", drawSpeed);
toolTag.setInteger("BaseDrawSpeed", drawSpeed);
float flightSpeed = (top.flightSpeedMax + bottom.flightSpeedMax) / 2f * string.flightSpeedModifier;
toolTag.setFloat("FlightSpeed", flightSpeed);
}
}
if (event.tool == TContent.arrow)
{
ArrowMaterial head = TConstructRegistry.getArrowMaterial(toolTag.getInteger("Head"));
ArrowMaterial shaft = TConstructRegistry.getArrowMaterial(toolTag.getInteger("Handle"));
FletchingMaterial fletching = (FletchingMaterial) TConstructRegistry.getCustomMaterial(toolTag.getInteger("Accessory"), FletchingMaterial.class);
if (head != null && shaft != null && fletching != null)
{
float mass = head.mass / 5f + shaft.mass + fletching.mass;
float shatter = (head.breakChance + shaft.breakChance + fletching.breakChance) / 4f;
float accuracy = (head.accuracy + shaft.accuracy + fletching.accuracy) / 3;
ItemStack arrow = new ItemStack(event.tool, 4);
toolTag.setInteger("TotalDurability", 0);
toolTag.setFloat("Mass", mass);
toolTag.setFloat("BreakChance", shatter);
toolTag.setFloat("Accuracy", accuracy);
toolTag.setInteger("Unbreaking", 10);
arrow.setTagCompound(event.toolTag);
event.overrideResult(arrow);
}
}
}
private boolean allowCrafting (int head, int handle, int accessory)
{
int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 };
for (int i = 0; i < nonMetals.length; i++)
{
if (head == nonMetals[i] || handle == nonMetals[i] || accessory == nonMetals[i])
return false;
}
return true;
}
@ForgeSubscribe
public void craftPart (PartBuilderEvent.NormalPart event)
{
if (event.pattern.getItem() == TContent.woodPattern && event.pattern.getItemDamage() == 23)
{
ItemStack result = craftBowString(event.material);
if (result != null)
{
event.overrideResult(new ItemStack[] { result, null });
}
}
if (event.pattern.getItem() == TContent.woodPattern && event.pattern.getItemDamage() == 24)
{
ItemStack result = craftFletching(event.material);
if (result != null)
{
event.overrideResult(new ItemStack[] { result, null });
}
}
}
public static ItemStack craftBowString (ItemStack stack)
{
if (stack.stackSize < 3)
return null;
BowstringMaterial mat = (BowstringMaterial) TConstructRegistry.getCustomMaterial(stack, BowstringMaterial.class);
if (mat != null)
return mat.craftingItem.copy();
return null;
}
public static ItemStack craftFletching (ItemStack stack)
{
if (matchesLeaves(stack))
{
FletchingMaterial leaves = (FletchingMaterial) TConstructRegistry.getCustomMaterial(new ItemStack(Block.leaves), FletchingMaterial.class);
return leaves.craftingItem.copy();
}
FletchingMaterial mat = (FletchingMaterial) TConstructRegistry.getCustomMaterial(stack, FletchingMaterial.class);
if (mat != null)
return mat.craftingItem.copy();
return null;
}
public static boolean matchesLeaves (ItemStack stack)
{
if (stack.itemID >= 4096)
return false;
Block block = Block.blocksList[stack.itemID];
if (block != null)
{
if (block.isLeaves(null, 0, 0, 0))
return true;
}
return false;
}
/* Damage */
@ForgeSubscribe
public void onHurt (LivingHurtEvent event)
{
//System.out.println("Damage: "+event.ammount);
if (event.entityLiving instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.entityLiving;
//Cutlass
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.getItem() == TContent.cutlass && player.isUsingItem())
{
player.addPotionEffect(new PotionEffect(Potion.moveSpeed.id, 3 * 20, 1));
}
}
}
/* Drops */
@ForgeSubscribe
public void onLivingDrop (LivingDropsEvent event)
{
if (event.entityLiving == null)
return;
if (event.source.getEntity() != null && event.source.getEntity() instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof FryingPan)
{
for (int i = 0; i < event.drops.size(); i++)
{
ItemStack is = event.drops.get(i).getEntityItem();
if (FurnaceRecipes.smelting().getSmeltingResult(is) != null && FurnaceRecipes.smelting().getSmeltingResult(is).getItem() instanceof ItemFood)
{
NBTTagCompound stackCompound = is.getTagCompound();
if (stackCompound == null)
{
stackCompound = new NBTTagCompound();
}
stackCompound.setBoolean("frypanKill", true);
is.setTagCompound(stackCompound);
}
}
}
}
if (random.nextInt(500) == 0 && event.entityLiving instanceof IMob)
{
ItemStack dropStack = new ItemStack(TContent.heartCanister, 1, 1);
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
if (event.entityLiving instanceof EntityWither && random.nextInt(5) == 0)
{
ItemStack dropStack = new ItemStack(TContent.heartCanister, 1, 1);
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
//if (event.entityLiving.worldObj.getGameRules().getGameRuleBooleanValue("doMobLoot"))
//{
if (!event.entityLiving.isChild())
{
/*if (event.entityLiving.getClass() == EntityCow.class)
{
int amount = random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + 1;
for (int iter = 0; iter < amount; ++iter)
{
addDrops(event, new ItemStack(Item.leather, 1));
}
}*/
if (event.entityLiving.getClass() == EntityChicken.class)
{
int amount = random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + 1;
for (int iter = 0; iter < amount; ++iter)
{
addDrops(event, new ItemStack(Item.feather, 1));
}
}
}
if (event.recentlyHit)
{
if (event.entityLiving.getClass() == EntitySkeleton.class)
{
EntitySkeleton enemy = (EntitySkeleton) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 10)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, enemy.getSkeletonType()));
}
}
}
if (enemy.getSkeletonType() == 1 && random.nextInt(Math.max(1, 5 - event.lootingLevel)) == 0)
{
addDrops(event, new ItemStack(TContent.materials, 1, 8));
}
}
if (event.entityLiving.getClass() == EntityZombie.class)
{
EntityZombie enemy = (EntityZombie) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 10)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 2));
}
}
/*if (stack.getItem() == TContent.breakerBlade && random.nextInt(100) < 10) //Swap out for real beheading
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 2));
}*/
}
}
if (event.entityLiving.getClass() == EntityCreeper.class)
{
EntityCreeper enemy = (EntityCreeper) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 5)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 4));
}
}
}
}
}
if (event.entityLiving.getClass() == EntityGhast.class)
{
if (PHConstruct.uhcGhastDrops)
{
for (EntityItem o : event.drops)
{
if (o.getEntityItem().itemID == Item.ghastTear.itemID)
{
o.setEntityItemStack(new ItemStack(Item.ingotGold, 1));
}
}
}
else
{
addDrops(event, new ItemStack(Item.ghastTear, 1));
}
}
//}
if (event.entityLiving instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.entityLiving;
if (PHConstruct.dropPlayerHeads)
{
ItemStack dropStack = new ItemStack(Item.skull.itemID, 1, 3);
NBTTagCompound nametag = new NBTTagCompound();
nametag.setString("SkullOwner", player.username);
+ dropStack.setTagCompound(nametag);
addDrops(event, dropStack);
}
else if (event.source.damageType.equals("player"))
{
EntityPlayer source = (EntityPlayer) event.source.getEntity();
ItemStack stack = source.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 50)
{
ItemStack dropStack = new ItemStack(Item.skull.itemID, 1, 3);
NBTTagCompound nametag = new NBTTagCompound();
nametag.setString("SkullOwner", player.username);
+ dropStack.setTagCompound(nametag);
addDrops(event, dropStack);
}
}
}
GameRules rules = player.worldObj.getGameRules(); //Player is null if this crashes
if (rules == null || !rules.getGameRuleBooleanValue("keepInventory"))
{
TPlayerStats stats = TConstruct.playerTracker.getPlayerStats(player.username);
if (stats != null)
{
stats.armor.dropItems();
stats.knapsack.dropItems();
}
}
}
}
@ForgeSubscribe
public void onLivingDeath (LivingDeathEvent event)
{
Entity cause = event.source.getSourceOfDamage();
if (cause != null && cause instanceof EntityPlayer)
{
EntityPlayer murderer = (EntityPlayer) cause;
ItemStack stack = murderer.getHeldItem();
if (stack != null && stack.getItem() instanceof Weapon)
{
murderer.addStat(TAchievements.achievements.get("tconstruct.enemySlayer"), 1);
}
}
}
void addDrops (LivingDropsEvent event, ItemStack dropStack)
{
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
/*@ForgeSubscribe
public void onLivingSpawn (EntityJoinWorldEvent event)
{
if (event.entity instanceof EntityXPOrb)
{
TConstruct.logger.info("Entity: " + event.entity);
}
}*/
@ForgeSubscribe
public void onLivingSpawn (LivingSpawnEvent.SpecialSpawn event)
{
EntityLivingBase living = event.entityLiving;
if (living.getClass() == EntitySpider.class && random.nextInt(100) == 0)
{
EntityCreeper creeper = new EntityCreeper(living.worldObj);
spawnEntityLiving(living.posX, living.posY + 1, living.posZ, creeper, living.worldObj);
if (living.riddenByEntity != null)
creeper.mountEntity(living.riddenByEntity);
else
creeper.mountEntity(living);
EntityXPOrb orb = new EntityXPOrb(living.worldObj, living.posX, living.posY, living.posZ, random.nextInt(20) + 20);
orb.mountEntity(creeper);
}
}
public static void spawnEntityLiving (double x, double y, double z, EntityLiving entity, World world)
{
if (!world.isRemote)
{
entity.setPosition(x, y, z);
entity.onSpawnWithEgg((EntityLivingData) null);
world.spawnEntityInWorld(entity);
}
}
/* Bonemeal */
@ForgeSubscribe
public void bonemealEvent (BonemealEvent event)
{
if (!event.world.isRemote)
{
if (event.ID == TContent.slimeSapling.blockID)
{
if (TContent.slimeSapling.boneFertilize(event.world, event.X, event.Y, event.Z, event.world.rand, event.entityPlayer))
event.setResult(Event.Result.ALLOW);
}
}
}
/* Ore Dictionary */
@ForgeSubscribe
public void registerOre (OreRegisterEvent evt)
{
if (evt.Name == "crystalQuartz")
{
TContent.modAttack.addStackToMatchList(evt.Ore, 2);
}
else if (evt.Name == "crystalCerusQuartz")
{
TContent.modAttack.addStackToMatchList(evt.Ore, 24);
}
}
@ForgeSubscribe
public void bucketFill (FillBucketEvent evt)
{
if (evt.current.getItem() == Item.bucketEmpty && evt.target.typeOfHit == EnumMovingObjectType.TILE)
{
int hitX = evt.target.blockX;
int hitY = evt.target.blockY;
int hitZ = evt.target.blockZ;
if (evt.entityPlayer != null && !evt.entityPlayer.canPlayerEdit(hitX, hitY, hitZ, evt.target.sideHit, evt.current))
{
return;
}
int bID = evt.world.getBlockId(hitX, hitY, hitZ);
for (int id = 0; id < TContent.fluidBlocks.length; id++)
{
if (bID == TContent.fluidBlocks[id].blockID)
{
if (evt.entityPlayer.capabilities.isCreativeMode)
{
evt.world.setBlockToAir(hitX, hitY, hitZ);
}
else
{
if (TContent.fluidBlocks[id] instanceof LiquidMetalFinite)
{
evt.world.setBlockToAir(hitX, hitY, hitZ);
/*int quanta = 0;
for (int posX = -1; posX <= 1; posX++)
{
for (int posZ = -1; posZ <= 1; posZ++)
{
int localID = evt.world.getBlockId(hitX + posX, hitY, hitZ + posZ);
if (localID == bID)
{
quanta += evt.world.getBlockMetadata(hitX + posX, hitY, hitZ + posZ) + 1;
}
}
}
if (quanta >= 8)
{
while (quanta > 0)
{
for (int posX = -1; posX <= 1; posX++)
{
for (int posZ = -1; posZ <= 1; posZ++)
{
int localID = evt.world.getBlockId(hitX + posX, hitY, hitZ + posZ);
if (localID == bID)
{
quanta -= 1;
int meta = evt.world.getBlockMetadata(hitX + posX, hitY, hitZ + posZ);
if (meta > 0)
evt.world.setBlockMetadataWithNotify(hitX + posX, hitY, hitZ + posZ, meta - 1, 3);
else
evt.world.setBlockToAir(hitX + posX, hitY, hitZ + posZ);
}
}
}
}
}*/
}
else
{
evt.world.setBlockToAir(hitX, hitY, hitZ);
}
evt.setResult(Result.ALLOW);
evt.result = new ItemStack(TContent.buckets, 1, id);
}
}
}
}
}
//Player interact event - prevent breaking of tank air blocks in creative
@ForgeSubscribe
public void playerInteract (PlayerInteractEvent event)
{
if (event.action == Action.LEFT_CLICK_BLOCK)
{
Block block = Block.blocksList[event.entity.worldObj.getBlockId(event.x, event.y, event.z)];
if (block instanceof TankAirBlock)
{
event.setCanceled(true);
}
}
}
}
| false | true | public void onLivingDrop (LivingDropsEvent event)
{
if (event.entityLiving == null)
return;
if (event.source.getEntity() != null && event.source.getEntity() instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof FryingPan)
{
for (int i = 0; i < event.drops.size(); i++)
{
ItemStack is = event.drops.get(i).getEntityItem();
if (FurnaceRecipes.smelting().getSmeltingResult(is) != null && FurnaceRecipes.smelting().getSmeltingResult(is).getItem() instanceof ItemFood)
{
NBTTagCompound stackCompound = is.getTagCompound();
if (stackCompound == null)
{
stackCompound = new NBTTagCompound();
}
stackCompound.setBoolean("frypanKill", true);
is.setTagCompound(stackCompound);
}
}
}
}
if (random.nextInt(500) == 0 && event.entityLiving instanceof IMob)
{
ItemStack dropStack = new ItemStack(TContent.heartCanister, 1, 1);
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
if (event.entityLiving instanceof EntityWither && random.nextInt(5) == 0)
{
ItemStack dropStack = new ItemStack(TContent.heartCanister, 1, 1);
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
//if (event.entityLiving.worldObj.getGameRules().getGameRuleBooleanValue("doMobLoot"))
//{
if (!event.entityLiving.isChild())
{
/*if (event.entityLiving.getClass() == EntityCow.class)
{
int amount = random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + 1;
for (int iter = 0; iter < amount; ++iter)
{
addDrops(event, new ItemStack(Item.leather, 1));
}
}*/
if (event.entityLiving.getClass() == EntityChicken.class)
{
int amount = random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + 1;
for (int iter = 0; iter < amount; ++iter)
{
addDrops(event, new ItemStack(Item.feather, 1));
}
}
}
if (event.recentlyHit)
{
if (event.entityLiving.getClass() == EntitySkeleton.class)
{
EntitySkeleton enemy = (EntitySkeleton) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 10)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, enemy.getSkeletonType()));
}
}
}
if (enemy.getSkeletonType() == 1 && random.nextInt(Math.max(1, 5 - event.lootingLevel)) == 0)
{
addDrops(event, new ItemStack(TContent.materials, 1, 8));
}
}
if (event.entityLiving.getClass() == EntityZombie.class)
{
EntityZombie enemy = (EntityZombie) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 10)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 2));
}
}
/*if (stack.getItem() == TContent.breakerBlade && random.nextInt(100) < 10) //Swap out for real beheading
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 2));
}*/
}
}
if (event.entityLiving.getClass() == EntityCreeper.class)
{
EntityCreeper enemy = (EntityCreeper) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 5)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 4));
}
}
}
}
}
if (event.entityLiving.getClass() == EntityGhast.class)
{
if (PHConstruct.uhcGhastDrops)
{
for (EntityItem o : event.drops)
{
if (o.getEntityItem().itemID == Item.ghastTear.itemID)
{
o.setEntityItemStack(new ItemStack(Item.ingotGold, 1));
}
}
}
else
{
addDrops(event, new ItemStack(Item.ghastTear, 1));
}
}
//}
if (event.entityLiving instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.entityLiving;
if (PHConstruct.dropPlayerHeads)
{
ItemStack dropStack = new ItemStack(Item.skull.itemID, 1, 3);
NBTTagCompound nametag = new NBTTagCompound();
nametag.setString("SkullOwner", player.username);
addDrops(event, dropStack);
}
else if (event.source.damageType.equals("player"))
{
EntityPlayer source = (EntityPlayer) event.source.getEntity();
ItemStack stack = source.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 50)
{
ItemStack dropStack = new ItemStack(Item.skull.itemID, 1, 3);
NBTTagCompound nametag = new NBTTagCompound();
nametag.setString("SkullOwner", player.username);
addDrops(event, dropStack);
}
}
}
GameRules rules = player.worldObj.getGameRules(); //Player is null if this crashes
if (rules == null || !rules.getGameRuleBooleanValue("keepInventory"))
{
TPlayerStats stats = TConstruct.playerTracker.getPlayerStats(player.username);
if (stats != null)
{
stats.armor.dropItems();
stats.knapsack.dropItems();
}
}
}
}
| public void onLivingDrop (LivingDropsEvent event)
{
if (event.entityLiving == null)
return;
if (event.source.getEntity() != null && event.source.getEntity() instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof FryingPan)
{
for (int i = 0; i < event.drops.size(); i++)
{
ItemStack is = event.drops.get(i).getEntityItem();
if (FurnaceRecipes.smelting().getSmeltingResult(is) != null && FurnaceRecipes.smelting().getSmeltingResult(is).getItem() instanceof ItemFood)
{
NBTTagCompound stackCompound = is.getTagCompound();
if (stackCompound == null)
{
stackCompound = new NBTTagCompound();
}
stackCompound.setBoolean("frypanKill", true);
is.setTagCompound(stackCompound);
}
}
}
}
if (random.nextInt(500) == 0 && event.entityLiving instanceof IMob)
{
ItemStack dropStack = new ItemStack(TContent.heartCanister, 1, 1);
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
if (event.entityLiving instanceof EntityWither && random.nextInt(5) == 0)
{
ItemStack dropStack = new ItemStack(TContent.heartCanister, 1, 1);
EntityItem entityitem = new EntityItem(event.entityLiving.worldObj, event.entityLiving.posX, event.entityLiving.posY, event.entityLiving.posZ, dropStack);
entityitem.delayBeforeCanPickup = 10;
event.drops.add(entityitem);
}
//if (event.entityLiving.worldObj.getGameRules().getGameRuleBooleanValue("doMobLoot"))
//{
if (!event.entityLiving.isChild())
{
/*if (event.entityLiving.getClass() == EntityCow.class)
{
int amount = random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + 1;
for (int iter = 0; iter < amount; ++iter)
{
addDrops(event, new ItemStack(Item.leather, 1));
}
}*/
if (event.entityLiving.getClass() == EntityChicken.class)
{
int amount = random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + random.nextInt(3) + random.nextInt(1 + event.lootingLevel) + 1;
for (int iter = 0; iter < amount; ++iter)
{
addDrops(event, new ItemStack(Item.feather, 1));
}
}
}
if (event.recentlyHit)
{
if (event.entityLiving.getClass() == EntitySkeleton.class)
{
EntitySkeleton enemy = (EntitySkeleton) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 10)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, enemy.getSkeletonType()));
}
}
}
if (enemy.getSkeletonType() == 1 && random.nextInt(Math.max(1, 5 - event.lootingLevel)) == 0)
{
addDrops(event, new ItemStack(TContent.materials, 1, 8));
}
}
if (event.entityLiving.getClass() == EntityZombie.class)
{
EntityZombie enemy = (EntityZombie) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 10)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 2));
}
}
/*if (stack.getItem() == TContent.breakerBlade && random.nextInt(100) < 10) //Swap out for real beheading
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 2));
}*/
}
}
if (event.entityLiving.getClass() == EntityCreeper.class)
{
EntityCreeper enemy = (EntityCreeper) event.entityLiving;
if (event.source.damageType.equals("player"))
{
EntityPlayer player = (EntityPlayer) event.source.getEntity();
ItemStack stack = player.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 5)
{
addDrops(event, new ItemStack(Item.skull.itemID, 1, 4));
}
}
}
}
}
if (event.entityLiving.getClass() == EntityGhast.class)
{
if (PHConstruct.uhcGhastDrops)
{
for (EntityItem o : event.drops)
{
if (o.getEntityItem().itemID == Item.ghastTear.itemID)
{
o.setEntityItemStack(new ItemStack(Item.ingotGold, 1));
}
}
}
else
{
addDrops(event, new ItemStack(Item.ghastTear, 1));
}
}
//}
if (event.entityLiving instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) event.entityLiving;
if (PHConstruct.dropPlayerHeads)
{
ItemStack dropStack = new ItemStack(Item.skull.itemID, 1, 3);
NBTTagCompound nametag = new NBTTagCompound();
nametag.setString("SkullOwner", player.username);
dropStack.setTagCompound(nametag);
addDrops(event, dropStack);
}
else if (event.source.damageType.equals("player"))
{
EntityPlayer source = (EntityPlayer) event.source.getEntity();
ItemStack stack = source.getCurrentEquippedItem();
if (stack != null && stack.hasTagCompound() && stack.getItem() instanceof ToolCore)
{
int beheading = stack.getTagCompound().getCompoundTag("InfiTool").getInteger("Beheading");
if (stack.getItem() == TContent.cleaver)
beheading += 2;
if (beheading > 0 && random.nextInt(100) < beheading * 50)
{
ItemStack dropStack = new ItemStack(Item.skull.itemID, 1, 3);
NBTTagCompound nametag = new NBTTagCompound();
nametag.setString("SkullOwner", player.username);
dropStack.setTagCompound(nametag);
addDrops(event, dropStack);
}
}
}
GameRules rules = player.worldObj.getGameRules(); //Player is null if this crashes
if (rules == null || !rules.getGameRuleBooleanValue("keepInventory"))
{
TPlayerStats stats = TConstruct.playerTracker.getPlayerStats(player.username);
if (stats != null)
{
stats.armor.dropItems();
stats.knapsack.dropItems();
}
}
}
}
|