diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/bundle/command/src/main/java/org/apache/karaf/bundle/command/Capabilities.java b/bundle/command/src/main/java/org/apache/karaf/bundle/command/Capabilities.java
index e3ad9a539..dff5dcf0c 100644
--- a/bundle/command/src/main/java/org/apache/karaf/bundle/command/Capabilities.java
+++ b/bundle/command/src/main/java/org/apache/karaf/bundle/command/Capabilities.java
@@ -1,238 +1,237 @@
/*
* 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.karaf.bundle.command;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.util.ShellUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
@Command(scope = "bundle", name = "capabilities", description = "Displays OSGi capabilities of a given bundles.")
public class Capabilities extends BundlesCommand {
public static final String NONSTANDARD_SERVICE_NAMESPACE = "service";
private static final String EMPTY_MESSAGE = "[EMPTY]";
private static final String UNUSED_MESSAGE = "[UNUSED]";
- private static final String UNRESOLVED_MESSAGE = "[UNRESOLVED]";
@Option(name = "--namespace")
String namespace = "*";
public Capabilities() {
super(true);
}
@Override
protected void doExecute(List<Bundle> bundles) throws Exception {
boolean separatorNeeded = false;
Pattern ns = Pattern.compile(namespace.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"));
for (Bundle b : bundles)
{
if (separatorNeeded)
{
System.out.println("");
}
// Print out any matching generic capabilities.
BundleWiring wiring = b.adapt(BundleWiring.class);
if (wiring != null)
{
String title = b + " provides:";
System.out.println(title);
System.out.println(ShellUtil.getUnderlineString(title));
// Print generic capabilities for matching namespaces.
boolean matches = printMatchingCapabilities(wiring, ns);
// Handle service capabilities separately, since they aren't part
// of the generic model in OSGi.
if (matchNamespace(ns, NONSTANDARD_SERVICE_NAMESPACE))
{
matches |= printServiceCapabilities(b);
}
// If there were no capabilities for the specified namespace,
// then say so.
if (!matches)
{
System.out.println(namespace + " " + EMPTY_MESSAGE);
}
}
else
{
System.out.println("Bundle " + b.getBundleId() + " is not resolved.");
}
separatorNeeded = true;
}
}
private static boolean printMatchingCapabilities(BundleWiring wiring, Pattern namespace)
{
List<BundleWire> wires = wiring.getProvidedWires(null);
Map<BundleCapability, List<BundleWire>> aggregateCaps =
aggregateCapabilities(namespace, wires);
List<BundleCapability> allCaps = wiring.getCapabilities(null);
boolean matches = false;
for (BundleCapability cap : allCaps)
{
if (matchNamespace(namespace, cap.getNamespace()))
{
matches = true;
List<BundleWire> dependents = aggregateCaps.get(cap);
Object keyAttr =
cap.getAttributes().get(cap.getNamespace());
if (dependents != null)
{
String msg;
if (keyAttr != null)
{
msg = cap.getNamespace()
+ "; "
+ keyAttr
+ " "
+ getVersionFromCapability(cap);
}
else
{
msg = cap.toString();
}
msg = msg + " required by:";
System.out.println(msg);
for (BundleWire wire : dependents)
{
System.out.println(" " + wire.getRequirerWiring().getBundle());
}
}
else if (keyAttr != null)
{
System.out.println(cap.getNamespace()
+ "; "
+ cap.getAttributes().get(cap.getNamespace())
+ " "
+ getVersionFromCapability(cap)
+ " "
+ UNUSED_MESSAGE);
}
else
{
System.out.println(cap + " " + UNUSED_MESSAGE);
}
}
}
return matches;
}
private static Map<BundleCapability, List<BundleWire>> aggregateCapabilities(
Pattern namespace, List<BundleWire> wires)
{
// Aggregate matching capabilities.
Map<BundleCapability, List<BundleWire>> map =
new HashMap<BundleCapability, List<BundleWire>>();
for (BundleWire wire : wires)
{
if (matchNamespace(namespace, wire.getCapability().getNamespace()))
{
List<BundleWire> dependents = map.get(wire.getCapability());
if (dependents == null)
{
dependents = new ArrayList<BundleWire>();
map.put(wire.getCapability(), dependents);
}
dependents.add(wire);
}
}
return map;
}
static boolean printServiceCapabilities(Bundle b)
{
boolean matches = false;
try
{
- ServiceReference[] refs = b.getRegisteredServices();
+ ServiceReference<?>[] refs = b.getRegisteredServices();
if ((refs != null) && (refs.length > 0))
{
matches = true;
// Print properties for each service.
- for (ServiceReference ref : refs)
+ for (ServiceReference<?> ref : refs)
{
// Print object class with "namespace".
System.out.println(
NONSTANDARD_SERVICE_NAMESPACE
+ "; "
+ ShellUtil.getValueString(ref.getProperty("objectClass"))
+ " with properties:");
// Print service properties.
String[] keys = ref.getPropertyKeys();
for (String key : keys)
{
if (!key.equalsIgnoreCase(Constants.OBJECTCLASS))
{
Object v = ref.getProperty(key);
System.out.println(" "
+ key + " = " + ShellUtil.getValueString(v));
}
}
Bundle[] users = ref.getUsingBundles();
if ((users != null) && (users.length > 0))
{
System.out.println(" Used by:");
for (Bundle user : users)
{
System.out.println(" " + user);
}
}
}
}
}
catch (Exception ex)
{
System.err.println(ex.toString());
}
return matches;
}
private static String getVersionFromCapability(BundleCapability c)
{
Object o = c.getAttributes().get(Constants.VERSION_ATTRIBUTE);
if (o == null)
{
o = c.getAttributes().get(Constants.BUNDLE_VERSION_ATTRIBUTE);
}
return (o == null) ? "" : o.toString();
}
private static boolean matchNamespace(Pattern namespace, String actual)
{
return namespace.matcher(actual).matches();
}
}
diff --git a/bundle/command/src/main/java/org/apache/karaf/bundle/command/Install.java b/bundle/command/src/main/java/org/apache/karaf/bundle/command/Install.java
index 8721d1fc9..06aeb0861 100644
--- a/bundle/command/src/main/java/org/apache/karaf/bundle/command/Install.java
+++ b/bundle/command/src/main/java/org/apache/karaf/bundle/command/Install.java
@@ -1,92 +1,73 @@
/*
* 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.karaf.bundle.command;
-import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.console.MultiException;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleException;
@Command(scope = "bundle", name = "install", description = "Installs one or more bundles.")
public class Install extends OsgiCommandSupport {
@Argument(index = 0, name = "urls", description = "Bundle URLs separated by whitespaces", required = true, multiValued = true)
List<String> urls;
@Option(name = "-s", aliases={"--start"}, description="Starts the bundles after installation", required = false, multiValued = false)
boolean start;
protected Object doExecute() throws Exception {
List<Exception> exceptions = new ArrayList<Exception>();
List<Bundle> bundles = new ArrayList<Bundle>();
for (String url : urls) {
try {
bundles.add(getBundleContext().installBundle(url, null));
} catch (Exception e) {
exceptions.add(new Exception("Unable to install bundle " + url, e));
}
}
if (start) {
for (Bundle bundle : bundles) {
try {
bundle.start();
} catch (Exception e) {
exceptions.add(new Exception("Unable to start bundle " + bundle.getLocation(), e));
}
}
}
if (bundles.size() == 1) {
System.out.println("Bundle ID: " + bundles.get(0).getBundleId());
} else {
StringBuffer sb = new StringBuffer("Bundle IDs: ");
for (Bundle bundle : bundles) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(bundle.getBundleId());
}
System.out.println(sb);
}
MultiException.throwIf("Error installing bundles", exceptions);
return null;
}
- private Bundle install(String location, PrintStream out, PrintStream err) {
- try {
- return getBundleContext().installBundle(location, null);
- } catch (IllegalStateException ex) {
- err.println(ex.toString());
- } catch (BundleException ex) {
- if (ex.getNestedException() != null) {
- err.println(ex.getNestedException().toString());
- } else {
- err.println(ex.toString());
- }
- } catch (Exception ex) {
- err.println(ex.toString());
- }
- return null;
- }
-
}
diff --git a/bundle/command/src/main/java/org/apache/karaf/bundle/command/Requirements.java b/bundle/command/src/main/java/org/apache/karaf/bundle/command/Requirements.java
index f5166cc32..06e3000cc 100644
--- a/bundle/command/src/main/java/org/apache/karaf/bundle/command/Requirements.java
+++ b/bundle/command/src/main/java/org/apache/karaf/bundle/command/Requirements.java
@@ -1,176 +1,175 @@
/*
* 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.karaf.bundle.command;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.util.ShellUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
@Command(scope = "bundle", name = "requirements", description = "Displays OSGi requirements of a given bundles.")
public class Requirements extends BundlesCommand {
public static final String NONSTANDARD_SERVICE_NAMESPACE = "service";
private static final String EMPTY_MESSAGE = "[EMPTY]";
- private static final String UNUSED_MESSAGE = "[UNUSED]";
private static final String UNRESOLVED_MESSAGE = "[UNRESOLVED]";
@Option(name = "--namespace")
String namespace = "*";
public Requirements() {
super(true);
}
@Override
protected void doExecute(List<Bundle> bundles) throws Exception {
boolean separatorNeeded = false;
Pattern ns = Pattern.compile(namespace.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"));
for (Bundle b : bundles) {
if (separatorNeeded) {
System.out.println("");
}
// Print out any matching generic requirements.
BundleWiring wiring = b.adapt(BundleWiring.class);
if (wiring != null) {
String title = b + " requires:";
System.out.println(title);
System.out.println(ShellUtil.getUnderlineString(title));
boolean matches = printMatchingRequirements(wiring, ns);
// Handle service requirements separately, since they aren't part
// of the generic model in OSGi.
if (matchNamespace(ns, NONSTANDARD_SERVICE_NAMESPACE)) {
matches |= printServiceRequirements(b);
}
// If there were no requirements for the specified namespace,
// then say so.
if (!matches) {
System.out.println(namespace + " " + EMPTY_MESSAGE);
}
} else {
System.out.println("Bundle " + b.getBundleId() + " is not resolved.");
}
separatorNeeded = true;
}
}
private static boolean printMatchingRequirements(BundleWiring wiring, Pattern namespace) {
List<BundleWire> wires = wiring.getRequiredWires(null);
Map<BundleRequirement, List<BundleWire>> aggregateReqs = aggregateRequirements(namespace, wires);
List<BundleRequirement> allReqs = wiring.getRequirements(null);
boolean matches = false;
for (BundleRequirement req : allReqs) {
if (matchNamespace(namespace, req.getNamespace())) {
matches = true;
List<BundleWire> providers = aggregateReqs.get(req);
if (providers != null) {
System.out.println(req.getNamespace() + "; "
+ req.getDirectives().get(Constants.FILTER_DIRECTIVE) + " resolved by:");
for (BundleWire wire : providers) {
String msg;
Object keyAttr = wire.getCapability().getAttributes().get(wire.getCapability().getNamespace());
if (keyAttr != null) {
msg = wire.getCapability().getNamespace() + "; "
+ keyAttr + " " + getVersionFromCapability(wire.getCapability());
} else {
msg = wire.getCapability().toString();
}
msg = " " + msg + " from " + wire.getProviderWiring().getBundle();
System.out.println(msg);
}
} else {
System.out.println(req.getNamespace() + "; "
+ req.getDirectives().get(Constants.FILTER_DIRECTIVE) + " " + UNRESOLVED_MESSAGE);
}
}
}
return matches;
}
private static Map<BundleRequirement, List<BundleWire>> aggregateRequirements(
Pattern namespace, List<BundleWire> wires) {
// Aggregate matching capabilities.
Map<BundleRequirement, List<BundleWire>> map = new HashMap<BundleRequirement, List<BundleWire>>();
for (BundleWire wire : wires) {
if (matchNamespace(namespace, wire.getRequirement().getNamespace())) {
List<BundleWire> providers = map.get(wire.getRequirement());
if (providers == null) {
providers = new ArrayList<BundleWire>();
map.put(wire.getRequirement(), providers);
}
providers.add(wire);
}
}
return map;
}
static boolean printServiceRequirements(Bundle b) {
boolean matches = false;
try {
ServiceReference<?>[] refs = b.getServicesInUse();
if ((refs != null) && (refs.length > 0)) {
matches = true;
// Print properties for each service.
for (ServiceReference<?> ref : refs) {
// Print object class with "namespace".
System.out.println(
NONSTANDARD_SERVICE_NAMESPACE
+ "; "
+ ShellUtil.getValueString(ref.getProperty("objectClass"))
+ " provided by:");
System.out.println(" " + ref.getBundle());
}
}
} catch (Exception ex) {
System.err.println(ex.toString());
}
return matches;
}
private static String getVersionFromCapability(BundleCapability c) {
Object o = c.getAttributes().get(Constants.VERSION_ATTRIBUTE);
if (o == null) {
o = c.getAttributes().get(Constants.BUNDLE_VERSION_ATTRIBUTE);
}
return (o == null) ? "" : o.toString();
}
private static boolean matchNamespace(Pattern namespace, String actual) {
return namespace.matcher(actual).matches();
}
}
| false | false | null | null |
diff --git a/dexlib2/src/main/java/org/jf/dexlib2/Opcodes.java b/dexlib2/src/main/java/org/jf/dexlib2/Opcodes.java
index e52db0b4..d6e5532e 100644
--- a/dexlib2/src/main/java/org/jf/dexlib2/Opcodes.java
+++ b/dexlib2/src/main/java/org/jf/dexlib2/Opcodes.java
@@ -1,75 +1,78 @@
/*
* Copyright 2013, Google Inc.
* 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
import java.util.HashMap;
public class Opcodes {
private final Opcode[] opcodesByValue;
private final HashMap<String, Opcode> opcodesByName;
public Opcodes(int api) {
opcodesByValue = new Opcode[256];
opcodesByName = Maps.newHashMap();
for (Opcode opcode: Opcode.values()) {
if (!opcode.format.isPayloadFormat) {
if (api <= opcode.getMaxApi() && api >= opcode.getMinApi()) {
opcodesByValue[opcode.value] = opcode;
opcodesByName.put(opcode.name.toLowerCase(), opcode);
}
}
}
}
@Nullable
public Opcode getOpcodeByName(String opcodeName) {
return opcodesByName.get(opcodeName.toLowerCase());
}
@Nullable
public Opcode getOpcodeByValue(int opcodeValue) {
switch (opcodeValue) {
case 0x100:
return Opcode.PACKED_SWITCH_PAYLOAD;
case 0x200:
return Opcode.SPARSE_SWITCH_PAYLOAD;
case 0x300:
return Opcode.ARRAY_PAYLOAD;
default:
- return opcodesByValue[opcodeValue];
+ if (opcodeValue >= 0 && opcodeValue < opcodesByValue.length) {
+ return opcodesByValue[opcodeValue];
+ }
+ return null;
}
}
}
diff --git a/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedUnknownInstruction.java b/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedUnknownInstruction.java
index 4ab892ee..08d5d507 100644
--- a/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedUnknownInstruction.java
+++ b/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedUnknownInstruction.java
@@ -1,49 +1,54 @@
/*
* Copyright 2013, Google Inc.
* 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.dexbacked.instruction;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.instruction.formats.UnknownInstruction;
import javax.annotation.Nonnull;
public class DexBackedUnknownInstruction extends DexBackedInstruction implements UnknownInstruction {
public DexBackedUnknownInstruction(@Nonnull DexBackedDexFile dexFile,
int instructionStart) {
super(dexFile, Opcode.NOP, instructionStart);
}
- @Override public short getOriginalOpcode() {
- return (short)dexFile.readUbyte(instructionStart);
+ @Override public int getOriginalOpcode() {
+ int opcode = dexFile.readUbyte(instructionStart);
+ if (opcode == 0) {
+ opcode = dexFile.readUshort(instructionStart);
+ }
+
+ return opcode;
}
}
diff --git a/dexlib2/src/main/java/org/jf/dexlib2/iface/instruction/formats/UnknownInstruction.java b/dexlib2/src/main/java/org/jf/dexlib2/iface/instruction/formats/UnknownInstruction.java
index f98f00a8..45975d9e 100644
--- a/dexlib2/src/main/java/org/jf/dexlib2/iface/instruction/formats/UnknownInstruction.java
+++ b/dexlib2/src/main/java/org/jf/dexlib2/iface/instruction/formats/UnknownInstruction.java
@@ -1,36 +1,36 @@
/*
* Copyright 2013, Google Inc.
* 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.iface.instruction.formats;
public interface UnknownInstruction extends Instruction10x {
- short getOriginalOpcode();
+ int getOriginalOpcode();
}
diff --git a/dexlib2/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableUnknownInstruction.java b/dexlib2/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableUnknownInstruction.java
index f971775c..79798574 100644
--- a/dexlib2/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableUnknownInstruction.java
+++ b/dexlib2/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableUnknownInstruction.java
@@ -1,57 +1,57 @@
/*
* Copyright 2013, Google Inc.
* 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.immutable.instruction;
import org.jf.dexlib2.Format;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.iface.instruction.formats.UnknownInstruction;
public class ImmutableUnknownInstruction extends ImmutableInstruction implements UnknownInstruction {
public static final Format FORMAT = Format.Format10x;
- protected final short originalOpcode;
+ protected final int originalOpcode;
- public ImmutableUnknownInstruction(short originalOpcode) {
+ public ImmutableUnknownInstruction(int originalOpcode) {
super(Opcode.NOP);
this.originalOpcode = originalOpcode;
}
public static ImmutableUnknownInstruction of(UnknownInstruction instruction) {
if (instruction instanceof ImmutableUnknownInstruction) {
return (ImmutableUnknownInstruction)instruction;
}
return new ImmutableUnknownInstruction(instruction.getOriginalOpcode());
}
@Override public Format getFormat() { return FORMAT; }
- @Override public short getOriginalOpcode() { return originalOpcode; }
+ @Override public int getOriginalOpcode() { return originalOpcode; }
}
| false | false | null | null |
diff --git a/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java b/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java
index d28691d2..dc9e80ed 100644
--- a/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java
+++ b/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java
@@ -1,440 +1,447 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.utils;
import java.io.File;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.model.Topic;
import org.jamwiki.model.WikiFile;
import org.jamwiki.model.WikiImage;
/**
* General utility methods for handling both wiki topic links such as
* "Topic?query=param#Section", as well as HTML links of the form
* http://example.com/.
*/
public class LinkUtil {
private static final WikiLogger logger = WikiLogger.getLogger(LinkUtil.class.getName());
/**
*
*/
private LinkUtil() {
}
/**
* Build a query parameter. If root is empty, this method returns
* "?param=value". If root is not empty this method returns root +
* "&param=value". Note that param and value will be URL encoded,
* and if "query" does not start with a "?" then one will be pre-pended.
*
* @param query The existing query parameter, if one is available. If the
* query parameter does not start with "?" then one will be pre-pended.
* @param param The name of the query parameter being appended. This
* value will be URL encoded.
* @param value The value of the query parameter being appended. This
* value will be URL encoded.
* @return The full query string generated using the input parameters.
*/
public static String appendQueryParam(String query, String param, String value) {
String url = "";
if (!StringUtils.isBlank(query)) {
if (!query.startsWith("?")) {
query = "?" + query;
}
url = query + "&";
} else {
url = "?";
}
if (StringUtils.isBlank(param)) {
return query;
}
url += Utilities.encodeAndEscapeTopicName(param) + "=";
if (!StringUtils.isBlank(value)) {
url += Utilities.encodeAndEscapeTopicName(value);
}
return url;
}
/**
* Utility method for building a URL link to a wiki edit page for a
* specified topic.
*
* @param context The servlet context for the link that is being created.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param topic The name of the topic for which an edit link is being
* created.
* @param query Any existing query parameters to append to the edit link.
* This value may be either <code>null</code> or empty.
* @param section The section defined by the name parameter within the
* HTML page for the topic being edited. If provided then the edit link
* will allow editing of only the specified section.
* @return A url that links to the edit page for the specified topic.
* Note that this method returns only the URL, not a fully-formed HTML
* anchor tag.
* @throws Exception Thrown if any error occurs while builing the link URL.
*/
public static String buildEditLinkUrl(String context, String virtualWiki, String topic, String query, int section) throws Exception {
query = LinkUtil.appendQueryParam(query, "topic", topic);
if (section > 0) {
query += "&section=" + section;
}
WikiLink wikiLink = new WikiLink();
// FIXME - hard coding
wikiLink.setDestination("Special:Edit");
wikiLink.setQuery(query);
return LinkUtil.buildInternalLinkUrl(context, virtualWiki, wikiLink);
}
/**
* Utility method for building an anchor tag that links to an image page
* and includes the HTML image tag to display the image.
*
* @param context The servlet context for the link that is being created.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param topicName The name of the image for which a link is being
* created.
* @param frame Set to <code>true</code> if the image should display with
* a frame border.
* @param thumb Set to <code>true</code> if the image should display as a
* thumbnail.
* @param align Indicates how the image should horizontally align on the
* page. Valid values are "left", "right" and "center".
* @param caption An optional text caption to display for the image. If
* no caption is used then this value should be either empty or
* <code>null</code>.
* @param maxDimension A value in pixels indicating the maximum width or
* height value allowed for the image. Images will be resized so that
* neither the width or height exceeds this value.
* @param suppressLink If this value is <code>true</code> then the
* generated HTML will include the image tag without a link to the image
* topic page.
* @param style The CSS class to use with the img HTML tag. This value
* can be <code>null</code> or empty if no custom style is used.
* @param escapeHtml Set to <code>true</code> if the caption should be
* HTML escaped. This value should be <code>true</code> in any case
* where the caption is not guaranteed to be free from potentially
* malicious HTML code.
* @return The full HTML required to display an image enclosed within an
* HTML anchor tag that links to the image topic page.
* @throws Exception Thrown if any error occurs while builing the image
* HTML.
*/
public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, int maxDimension, boolean suppressLink, String style, boolean escapeHtml) throws Exception {
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
WikiLink uploadLink = LinkUtil.parseWikiLink("Special:Upload");
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, uploadLink, topicName, "edit", null, true);
}
WikiFile wikiFile = WikiBase.getDataHandler().lookupWikiFile(virtualWiki, topicName);
+ String html = "";
if (topic.getTopicType() == Topic.TYPE_FILE) {
// file, not an image
if (StringUtils.isBlank(caption)) {
caption = topicName.substring(NamespaceHandler.NAMESPACE_IMAGE.length() + 1);
}
String url = FilenameUtils.normalize(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH) + "/" + wikiFile.getUrl());
url = FilenameUtils.separatorsToUnix(url);
- return "<a href=\"" + url + "\">" + StringEscapeUtils.escapeHtml(caption) + "</a>";
+ html += "<a href=\"" + url + "\">";
+ if (escapeHtml) {
+ html += StringEscapeUtils.escapeHtml(caption);
+ } else {
+ html += caption;
+ }
+ html += "</a>";
+ return html;
}
- String html = "";
WikiImage wikiImage = ImageUtil.initializeImage(wikiFile, maxDimension);
if (caption == null) {
caption = "";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "<div class=\"";
if (thumb || frame) {
html += "imgthumb ";
}
if (align != null && align.equalsIgnoreCase("left")) {
html += "imgleft ";
} else if (align != null && align.equalsIgnoreCase("center")) {
html += "imgcenter ";
} else if ((align != null && align.equalsIgnoreCase("right")) || thumb || frame) {
html += "imgright ";
} else {
// default alignment
html += "image ";
}
html = html.trim() + "\">";
}
if (wikiImage.getWidth() > 0) {
html += "<div style=\"width:" + (wikiImage.getWidth() + 2) + "px\">";
}
if (!suppressLink) {
html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
}
if (StringUtils.isBlank(style)) {
style = "wikiimg";
}
html += "<img class=\"" + style + "\" src=\"";
String url = new File(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH), wikiImage.getUrl()).getPath();
url = FilenameUtils.separatorsToUnix(url);
html += url;
html += "\"";
html += " width=\"" + wikiImage.getWidth() + "\"";
html += " height=\"" + wikiImage.getHeight() + "\"";
html += " alt=\"" + StringEscapeUtils.escapeHtml(caption) + "\"";
html += " />";
if (!suppressLink) {
html += "</a>";
}
if (!StringUtils.isBlank(caption)) {
html += "<div class=\"imgcaption\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</div>";
}
if (wikiImage.getWidth() > 0) {
html += "</div>";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "</div>";
}
return html;
}
/**
* Build the HTML anchor link to a topic page for a given WikLink object.
*
* @param context The servlet context for the link that is being created.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param wikiLink The WikiLink object containing all relevant information
* about the link being generated.
* @param text The text to display as the link content.
* @param style The CSS class to use with the anchor HTML tag. This value
* can be <code>null</code> or empty if no custom style is used.
* @param target The anchor link target, or <code>null</code> or empty if
* no target is needed.
* @param escapeHtml Set to <code>true</code> if the link caption should
* be HTML escaped. This value should be <code>true</code> in any case
* where the caption is not guaranteed to be free from potentially
* malicious HTML code.
* @return An HTML anchor link that matches the given input parameters.
* @throws Exception Thrown if any error occurs while builing the link
* HTML.
*/
public static String buildInternalLinkHtml(String context, String virtualWiki, WikiLink wikiLink, String text, String style, String target, boolean escapeHtml) throws Exception {
String url = LinkUtil.buildInternalLinkUrl(context, virtualWiki, wikiLink);
String topic = wikiLink.getDestination();
if (StringUtils.isBlank(text)) {
text = topic;
}
if (!StringUtils.isBlank(topic) && StringUtils.isBlank(style)) {
if (InterWikiHandler.isInterWiki(virtualWiki)) {
style = "interwiki";
} else if (!LinkUtil.isExistingArticle(virtualWiki, topic)) {
style = "edit";
}
}
if (!StringUtils.isBlank(style)) {
style = " class=\"" + style + "\"";
} else {
style = "";
}
if (!StringUtils.isBlank(target)) {
target = " target=\"" + target + "\"";
} else {
target = "";
}
if (StringUtils.isBlank(topic) && !StringUtils.isBlank(wikiLink.getSection())) {
topic = wikiLink.getSection();
}
String html = "<a href=\"" + url + "\"" + style + " title=\"" + StringEscapeUtils.escapeHtml(topic) + "\"" + target + ">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(text);
} else {
html += text;
}
html += "</a>";
return html;
}
/**
* Build a URL to the topic page for a given topic.
*
* @param context The servlet context path. If this value is
* <code>null</code> then the resulting URL will NOT include context path,
* which breaks HTML links but is useful for servlet redirection URLs.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param topic The topic name for the URL that is being generated.
* @throws Exception Thrown if any error occurs while builing the link
* URL.
*/
public static String buildInternalLinkUrl(String context, String virtualWiki, String topic) throws Exception {
if (StringUtils.isBlank(topic)) {
return null;
}
WikiLink wikiLink = LinkUtil.parseWikiLink(topic);
return LinkUtil.buildInternalLinkUrl(context, virtualWiki, wikiLink);
}
/**
* Build a URL to the topic page for a given topic.
*
* @param context The servlet context path. If this value is
* <code>null</code> then the resulting URL will NOT include context path,
* which breaks HTML links but is useful for servlet redirection URLs.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param wikiLink The WikiLink object containing all relevant information
* about the link being generated.
* @throws Exception Thrown if any error occurs while builing the link
* URL.
*/
public static String buildInternalLinkUrl(String context, String virtualWiki, WikiLink wikiLink) throws Exception {
String topic = wikiLink.getDestination();
String section = wikiLink.getSection();
String query = wikiLink.getQuery();
if (StringUtils.isBlank(topic) && !StringUtils.isBlank(section)) {
return "#" + Utilities.encodeAndEscapeTopicName(section);
}
if (!LinkUtil.isExistingArticle(virtualWiki, topic)) {
return LinkUtil.buildEditLinkUrl(context, virtualWiki, topic, query, -1);
}
String url = "";
if (context != null) {
url += context;
}
// context never ends with a "/" per servlet specification
url += "/";
// get the virtual wiki, which should have been set by the parent servlet
url += Utilities.encodeAndEscapeTopicName(virtualWiki);
url += "/";
url += Utilities.encodeAndEscapeTopicName(topic);
if (!StringUtils.isBlank(query)) {
if (!query.startsWith("?")) {
url += "?";
}
url += query;
}
if (!StringUtils.isBlank(section)) {
if (!section.startsWith("#")) {
url += "#";
}
url += Utilities.encodeAndEscapeTopicName(section);
}
return url;
}
/**
* Generate the HTML for an interwiki anchor link.
*
* @param wikiLink The WikiLink object containing all relevant information
* about the link being generated.
* @return The HTML anchor tag for the interwiki link.
*/
public static String interWiki(WikiLink wikiLink) {
// remove namespace from link destination
String destination = wikiLink.getDestination();
String namespace = wikiLink.getNamespace();
destination = destination.substring(wikiLink.getNamespace().length() + NamespaceHandler.NAMESPACE_SEPARATOR.length());
String url = InterWikiHandler.formatInterWiki(namespace, destination);
String text = (!StringUtils.isBlank(wikiLink.getText())) ? wikiLink.getText() : wikiLink.getDestination();
return "<a class=\"interwiki\" rel=\"nofollow\" title=\"" + text + "\" href=\"" + url + "\">" + text + "</a>";
}
/**
* Utility method for determining if an article name corresponds to a valid
* wiki link. In this case an "article name" could be an existing topic, a
* "Special:" page, a user page, an interwiki link, etc. This method will
* return true if the given name corresponds to a valid special page, user
* page, topic, or other existing article.
*
* @param virtualWiki The virtual wiki for the topic being checked.
* @param articleName The name of the article that is being checked.
* @return <code>true</code> if there is an article that exists for the given
* name and virtual wiki.
* @throws Exception Thrown if any error occurs during lookup.
*/
public static boolean isExistingArticle(String virtualWiki, String articleName) throws Exception {
if (StringUtils.isBlank(virtualWiki) || StringUtils.isBlank(articleName)) {
return false;
}
if (PseudoTopicHandler.isPseudoTopic(articleName)) {
return true;
}
if (InterWikiHandler.isInterWiki(articleName)) {
return true;
}
if (StringUtils.isBlank(Environment.getValue(Environment.PROP_BASE_FILE_DIR)) || !Environment.getBooleanValue(Environment.PROP_BASE_INITIALIZED)) {
// not initialized yet
return false;
}
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, articleName, false, null);
return (topic != null);
}
/**
* Parse a topic name of the form "Topic?Query#Section", and return a WikiLink
* object representing the link.
*
* @param raw The raw topic link text.
* @return A WikiLink object that represents the link.
*/
public static WikiLink parseWikiLink(String raw) {
// note that this functionality was previously handled with a regular
// expression, but the expression caused CPU usage to spike to 100%
// with topics such as "Urnordisch oder Nordwestgermanisch?"
String processed = raw.trim();
WikiLink wikiLink = new WikiLink();
if (StringUtils.isBlank(processed)) {
return new WikiLink();
}
// first look for a section param - "#..."
int sectionPos = processed.indexOf('#');
if (sectionPos != -1 && sectionPos < processed.length()) {
String sectionString = processed.substring(sectionPos + 1);
wikiLink.setSection(sectionString);
if (sectionPos == 0) {
// link is of the form #section, no more to process
return wikiLink;
}
processed = processed.substring(0, sectionPos);
}
// now see if the link ends with a query param - "?..."
int queryPos = processed.indexOf('?', 1);
if (queryPos != -1 && queryPos < processed.length()) {
String queryString = processed.substring(queryPos + 1);
wikiLink.setQuery(queryString);
processed = processed.substring(0, queryPos);
}
// since we're having so much fun, let's find a namespace (default empty).
String namespaceString = "";
int namespacePos = processed.indexOf(':', 1);
if (namespacePos != -1 && namespacePos < processed.length()) {
namespaceString = processed.substring(0, namespacePos);
}
wikiLink.setNamespace(namespaceString);
String topic = processed;
if (namespacePos > 0 && (namespacePos + 1) < processed.length()) {
// get namespace, unless topic ends with a colon
topic = processed.substring(namespacePos + 1);
}
wikiLink.setArticle(Utilities.decodeTopicName(topic, true));
// destination is namespace + topic
wikiLink.setDestination(Utilities.decodeTopicName(processed, true));
return wikiLink;
}
}
| false | true | public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, int maxDimension, boolean suppressLink, String style, boolean escapeHtml) throws Exception {
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
WikiLink uploadLink = LinkUtil.parseWikiLink("Special:Upload");
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, uploadLink, topicName, "edit", null, true);
}
WikiFile wikiFile = WikiBase.getDataHandler().lookupWikiFile(virtualWiki, topicName);
if (topic.getTopicType() == Topic.TYPE_FILE) {
// file, not an image
if (StringUtils.isBlank(caption)) {
caption = topicName.substring(NamespaceHandler.NAMESPACE_IMAGE.length() + 1);
}
String url = FilenameUtils.normalize(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH) + "/" + wikiFile.getUrl());
url = FilenameUtils.separatorsToUnix(url);
return "<a href=\"" + url + "\">" + StringEscapeUtils.escapeHtml(caption) + "</a>";
}
String html = "";
WikiImage wikiImage = ImageUtil.initializeImage(wikiFile, maxDimension);
if (caption == null) {
caption = "";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "<div class=\"";
if (thumb || frame) {
html += "imgthumb ";
}
if (align != null && align.equalsIgnoreCase("left")) {
html += "imgleft ";
} else if (align != null && align.equalsIgnoreCase("center")) {
html += "imgcenter ";
} else if ((align != null && align.equalsIgnoreCase("right")) || thumb || frame) {
html += "imgright ";
} else {
// default alignment
html += "image ";
}
html = html.trim() + "\">";
}
if (wikiImage.getWidth() > 0) {
html += "<div style=\"width:" + (wikiImage.getWidth() + 2) + "px\">";
}
if (!suppressLink) {
html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
}
if (StringUtils.isBlank(style)) {
style = "wikiimg";
}
html += "<img class=\"" + style + "\" src=\"";
String url = new File(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH), wikiImage.getUrl()).getPath();
url = FilenameUtils.separatorsToUnix(url);
html += url;
html += "\"";
html += " width=\"" + wikiImage.getWidth() + "\"";
html += " height=\"" + wikiImage.getHeight() + "\"";
html += " alt=\"" + StringEscapeUtils.escapeHtml(caption) + "\"";
html += " />";
if (!suppressLink) {
html += "</a>";
}
if (!StringUtils.isBlank(caption)) {
html += "<div class=\"imgcaption\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</div>";
}
if (wikiImage.getWidth() > 0) {
html += "</div>";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "</div>";
}
return html;
}
| public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, int maxDimension, boolean suppressLink, String style, boolean escapeHtml) throws Exception {
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
WikiLink uploadLink = LinkUtil.parseWikiLink("Special:Upload");
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, uploadLink, topicName, "edit", null, true);
}
WikiFile wikiFile = WikiBase.getDataHandler().lookupWikiFile(virtualWiki, topicName);
String html = "";
if (topic.getTopicType() == Topic.TYPE_FILE) {
// file, not an image
if (StringUtils.isBlank(caption)) {
caption = topicName.substring(NamespaceHandler.NAMESPACE_IMAGE.length() + 1);
}
String url = FilenameUtils.normalize(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH) + "/" + wikiFile.getUrl());
url = FilenameUtils.separatorsToUnix(url);
html += "<a href=\"" + url + "\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</a>";
return html;
}
WikiImage wikiImage = ImageUtil.initializeImage(wikiFile, maxDimension);
if (caption == null) {
caption = "";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "<div class=\"";
if (thumb || frame) {
html += "imgthumb ";
}
if (align != null && align.equalsIgnoreCase("left")) {
html += "imgleft ";
} else if (align != null && align.equalsIgnoreCase("center")) {
html += "imgcenter ";
} else if ((align != null && align.equalsIgnoreCase("right")) || thumb || frame) {
html += "imgright ";
} else {
// default alignment
html += "image ";
}
html = html.trim() + "\">";
}
if (wikiImage.getWidth() > 0) {
html += "<div style=\"width:" + (wikiImage.getWidth() + 2) + "px\">";
}
if (!suppressLink) {
html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
}
if (StringUtils.isBlank(style)) {
style = "wikiimg";
}
html += "<img class=\"" + style + "\" src=\"";
String url = new File(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH), wikiImage.getUrl()).getPath();
url = FilenameUtils.separatorsToUnix(url);
html += url;
html += "\"";
html += " width=\"" + wikiImage.getWidth() + "\"";
html += " height=\"" + wikiImage.getHeight() + "\"";
html += " alt=\"" + StringEscapeUtils.escapeHtml(caption) + "\"";
html += " />";
if (!suppressLink) {
html += "</a>";
}
if (!StringUtils.isBlank(caption)) {
html += "<div class=\"imgcaption\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</div>";
}
if (wikiImage.getWidth() > 0) {
html += "</div>";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "</div>";
}
return html;
}
|
diff --git a/src/main/java/water/ValueArray.java b/src/main/java/water/ValueArray.java
index 57d6953ed..af3f97a85 100644
--- a/src/main/java/water/ValueArray.java
+++ b/src/main/java/water/ValueArray.java
@@ -1,524 +1,524 @@
package water;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import water.H2O.H2OCountedCompleter;
import water.Job.ProgressMonitor;
import water.util.Log;
/**
* Large Arrays & Arraylets
*
* Large arrays are broken into 4Meg chunks (except the last chunk which may be
* from 4 to 8Megs). Large arrays have a metadata section in this ValueArray.
*
* @author <a href="mailto:[email protected]"></a>
* @version 1.0
*/
public class ValueArray extends Iced implements Cloneable {
public static final int LOG_CHK = 22; // Chunks are 1<<22, or 4Meg
public static final long CHUNK_SZ = 1L << LOG_CHK;
// --------------------------------------------------------
// Large datasets need metadata. :-)
//
// We describe datasets as either being "raw" ascii or unformatted binary
// data, or as being "structured binary" data - i.e., binary, floats, or
// ints. Structured data is efficient for doing math & matrix manipulation.
//
// Structured data is limited to being 2-D, a collection of rows and columns.
// The count of columns is expected to be small - from 1 to 1000. The count
// of rows is unlimited and could be more than 2^32. We expect data in
// columns to be highly compressable within a column, as data with a dynamic
// range of less than 1 byte is common (or equivalently, floating point data
// with only 2 or 3 digits of accuracy). Because data volumes matter (when
// you have billions of rows!), we want to compress the data while leaving it
// in an efficient-to-use format.
//
// The primary compression is to use 1-byte, 2-byte, or 4-byte columns, with
// an optional offset & scale factor. These are described in the meta-data.
public transient Key _key; // Main Array Key
public final Column[] _cols; // The array of column descriptors; the X dimension
public long[] _rpc; // Row# for start of each chunk
public long _numrows; // Number of rows; the Y dimension. Can be >>2^32
public final int _rowsize; // Size in bytes for an entire row
public ValueArray(Key key, long numrows, int rowsize, Column[] cols ) {
// Always some kind of rowsize. For plain unstructured data use a single
// byte column format.
assert rowsize > 0;
_numrows = numrows;
_rowsize = rowsize;
_cols = cols;
init(key);
}
// Plain unstructured data wrapper. Just a vast byte array
public ValueArray(Key key, long len ) { this(key,len,1,new Column[]{new Column(len)}); }
// Variable-sized chunks. Pass in the number of whole rows in each chunk.
public ValueArray(Key key, int[] rows, int rowsize, Column[] cols ) {
assert rowsize > 0;
_rowsize = rowsize;
_cols = cols;
_key = key;
// Roll-up summary the number rows in each chunk, to the starting row# per chunk.
_rpc = new long[rows.length+1];
long sum = 0;
for( int i=0; i<rows.length; i++ ) { // Variable-sized chunks
int r = rows[i]; // Rows in chunk# i
assert r*rowsize < (CHUNK_SZ*4); // Keep them reasonably sized please
_rpc[i] = sum; // Starting row# for chunk i
sum += r;
}
_rpc[_rpc.length-1] = _numrows = sum;
assert rpc(0) == rows[0]; // Some quicky sanity checks
assert rpc(chunks()-1) == rows[(int)(chunks()-1)];
}
public int [] getColumnIds(String [] colNames){
HashMap<String,Integer> colMap = new HashMap<String,Integer>();
for(int i = 0; i < colNames.length; ++i)colMap.put(colNames[i],i);
int [] res = new int [colNames.length];
Arrays.fill(res, -1);
Integer idx = null;
for(int i = 0; i < _cols.length; ++i)
if((idx = colMap.get(_cols[i]._name)) != null)
res[idx] = i;
return res;
}
/** Return the key that denotes this entire ValueArray in the K/V store. */
public final Key getKey() { return _key; }
@Override public ValueArray clone() { return (ValueArray)super.clone(); }
// Init of transient fields from deserialization calls
@Override public final ValueArray init( Key key ) {
_key = key;
return this;
}
/** Pretty print! */
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("VA[").append(_numrows).append("][").append(_cols.length).append("]{");
sb.append("bpr=").append(_rowsize).append(", rpc=").append(_rpc).append(", ");
sb.append("chunks=").append(chunks()).append(", key=").append(_key);
sb.append("}");
return sb.toString();
}
private String toStr( long idx, int col ) {
return _cols[col]._name+"="+(isNA(idx,col) ? "NA" : datad(idx,col));
}
public String toString( long idx ) {
String s="{"+toStr(idx,0);
for( int i=1; i<_cols.length; i++ )
s += ","+toStr(idx,i);
return s+"}";
}
/** An array of column names */
public final String[] colNames() {
String[] names = new String[_cols.length];
for( int i=0; i<names.length; i++ )
names[i] = _cols[i]._name;
return names;
}
/**Returns the width of a row.*/
public int rowSize() { return _rowsize; }
public long numRows() { return _numrows; }
public int numCols() { return _cols.length; }
public long length() { return _numrows*_rowsize; }
public boolean hasInvalidRows(int colnum) { return _cols[colnum]._n != _numrows; }
/** Rows in this chunk */
@SuppressWarnings("cast")
public int rpc(long chunknum) {
if( (long)(int)chunknum!=chunknum ) throw H2O.unimpl(); // more than 2^31 chunks?
if( _rpc != null ) return (int)(_rpc[(int)chunknum+1]-_rpc[(int)chunknum]);
int rpc = (int)(CHUNK_SZ/_rowsize);
return rpc(chunknum, rpc, _numrows);
}
public static int rpc(long chunknum, int rpc, long numrows) {
long chunks = Math.max(1,numrows/rpc);
assert chunknum < chunks;
if( chunknum < chunks-1 ) // Not last chunk?
return rpc; // Rows per chunk
return (int)(numrows - (chunks-1)*rpc);
}
/** Row number at the start of this chunk */
@SuppressWarnings("cast")
public long startRow( long chunknum) {
if( (long)(int)chunknum!=chunknum ) throw H2O.unimpl(); // more than 2^31 chunks?
if( _rpc != null ) return _rpc[(int)chunknum];
int rpc = (int)(CHUNK_SZ/_rowsize); // Rows per chunk
return rpc*chunknum;
}
// Which row in the chunk?
public int rowInChunk( long chknum, long rownum ) {
return (int)(rownum - startRow(chknum));
}
/** Number of chunks */
public long chunks() {
if( _rpc != null ) return _rpc.length-1; // one row# per chunk
// Else uniform-size chunks
int rpc = (int)(CHUNK_SZ/_rowsize); // Rows per chunk
return Math.max(1,_numrows/rpc);
}
/** Chunk number containing a row */
public long chknum( long rownum ) {
if( _rpc == null )
return chknum(rownum, _numrows, _rowsize);
int bs = Arrays.binarySearch(_rpc,rownum);
if( bs < 0 ) bs = -bs-2;
while( _rpc[bs+1]==rownum ) bs++;
return bs;
}
public static long chknum( long rownum, long numrows, int rowsize ) {
int rpc = (int)(CHUNK_SZ/rowsize);
return Math.min(rownum/rpc,Math.max(1,numrows/rpc)-1);
}
// internal convenience class for building structured ValueArrays
static public class Column extends Iced implements Cloneable {
public String _name;
// Domain of the column - all the strings which represents the column's
// domain. The order of the strings corresponds to numbering utilized in
// dataset. Null for numeric columns.
public String[] _domain;
public double _min, _max, _mean; // Min/Max/mean/var per column; requires a 1st pass
public double _sigma; // Requires a 2nd pass
// Number of valid values; different than the rows for the entire ValueArray in some rows
// have bad data
public long _n;
public int _base; // Base
public char _scale; // Actual value is (((double)(stored_value+base))/scale); 1,10,100,1000
- public char _off; // Offset within a row
+ public int _off; // Offset within a row
public byte _size; // Size is 1,2,4 or 8 bytes, or -4,-8 for float/double data
public Column() { _min = Double.MAX_VALUE; _max = -Double.MAX_VALUE; _scale = 1; }
// Plain unstructured byte array; min/max/mean/sigma are all bogus.
// No 'NA' options, e.g. 255 is a valid datum.
public Column(long len) {
_min=0; _max=255; _mean=128; _n = len; _scale=1; _size=1;
}
public final boolean isFloat() { return _size < 0 || _scale != 1; }
public final boolean isEnum() { return _domain != null; }
public final boolean isScaled() { return _scale != 1; }
/** Compute size of numeric integer domain */
public final long numDomainSize() { return (long) ((_max - _min)+1); }
@Override public Column clone() { return (Column)super.clone(); }
private static boolean eq(double x, double y, double precision){
return (Math.abs(x-y) < precision);
}
@Override
public boolean equals(Object other){
if(!(other instanceof Column)) return false;
Column c = (Column)other;
return
_base == c._base &&
_scale == c._scale &&
_max == c._max &&
_min == c._min &&
(eq(_mean,c._mean,1e-5) || Double.isNaN(_mean) && Double.isNaN(c._mean)) &&
(eq(_sigma,c._sigma,1e-5)|| Double.isNaN(_sigma)&& Double.isNaN(c._sigma)) &&
_n == c._n &&
_size == c._size &&
(_name == null && c._name == null || _name != null && c._name != null && _name.equals(c._name));
}
}
// Get a usable pile-o-bits
public AutoBuffer getChunk( long chknum ) { return getChunk(getChunkKey(chknum)); }
public AutoBuffer getChunk( Key key ) {
byte[] b = DKV.get(key).getBytes();
assert b.length == rpc(getChunkIndex(key))*_rowsize : "actual="+b.length+" expected="+rpc(getChunkIndex(key))*_rowsize;
return new AutoBuffer(b);
}
// Value extracted, then scaled & based - the double version. Note that this
// is not terrible efficient, and that 99% of this code I expect to be loop-
// invariant when run inside real numeric loops... but that the compiler will
// probably need help pulling out the loop invariants.
public double datad(long rownum, int colnum) {
long chknum = chknum(rownum);
return datad(getChunk(chknum),rowInChunk(chknum,rownum),colnum);
}
// This is a version where the column data is not yet pulled out.
public double datad(AutoBuffer ab, int row_in_chunk, int colnum) {
return datad(ab,row_in_chunk,_cols[colnum]);
}
// This is a version where all the loop-invariants are hoisted already.
public double datad(AutoBuffer ab, int row_in_chunk, Column col) {
int off = (row_in_chunk * _rowsize) + col._off;
double res=0;
switch( col._size ) {
case 1: res = ab.get1 (off); break;
case 2: res = ab.get2 (off); break;
case 4: res = ab.get4 (off); break;
case 8:return ab.get8 (off); // No scale/offset for long data
case -4:return ab.get4f(off); // No scale/offset for float data
case -8:return ab.get8d(off); // No scale/offset for double data
}
// Apply scale & base for the smaller numbers
return (res+col._base)/col._scale;
}
// Value extracted, then scaled & based - the integer version.
public long data(long rownum, int colnum) {
long chknum = chknum(rownum);
return data(getChunk(chknum),rowInChunk(chknum,rownum),colnum);
}
public long data(AutoBuffer ab, int row_in_chunk, int colnum) {
return data(ab,row_in_chunk,_cols[colnum]);
}
// This is a version where all the loop-invariants are hoisted already.
public long data(AutoBuffer ab, int row_in_chunk, Column col) {
int off = (row_in_chunk * _rowsize) + col._off;
long res=0;
switch( col._size ) {
case 1: res = ab.get1 (off); break;
case 2: res = ab.get2 (off); break;
case 4: res = ab.get4 (off); break;
case 8:return ab.get8 (off); // No scale/offset for long data
case -4:return (long)ab.get4f(off); // No scale/offset for float data
case -8:return (long)ab.get8d(off); // No scale/offset for double data
}
// Apply scale & base for the smaller numbers
assert col._scale==1;
return (res + col._base);
}
// Test if the value is valid, or was missing in the orginal dataset
public boolean isNA(long rownum, int colnum) {
long chknum = chknum(rownum);
return isNA(getChunk(chknum),rowInChunk(chknum,rownum),colnum);
}
public boolean isNA(AutoBuffer ab, int row_in_chunk, int colnum ) {
return isNA(ab,row_in_chunk,_cols[colnum]);
}
// Test if the value is valid, or was missing in the orginal dataset
// This is a version where all the loop-invariants are hoisted already.
public boolean isNA(AutoBuffer ab, int row_in_chunk, Column col ) {
int off = (row_in_chunk * _rowsize) + col._off;
switch( col._size ) {
case 1: return ab.get1(off) == 255;
case 2: return ab.get2(off) == 65535;
case 4: return ab.get4(off) == Integer.MIN_VALUE;
case 8: return ab.get8(off) == Long.MIN_VALUE;
case -4: return Float.isNaN(ab.get4f(off));
case -8: return Double.isNaN(ab.get8d(off));
}
return true;
}
// Get the proper Key for a given chunk number
public Key getChunkKey( long chknum ) {
assert 0 <= chknum && chknum < chunks() : "AIOOB "+chknum+" < "+chunks();
return getChunkKey(chknum,_key);
}
public static Key getChunkKey( long chknum, Key arrayKey ) {
byte[] buf = new AutoBuffer().put1(Key.ARRAYLET_CHUNK).put1(0)
.put8(chknum<<LOG_CHK).putA1(arrayKey._kb,arrayKey._kb.length).buf();
return Key.make(buf,(byte)arrayKey.desired());
}
/** Get the root array Key from a random arraylet sub-key */
public static Key getArrayKey( Key k ) { return Key.make(getArrayKeyBytes(k)); }
public static byte[] getArrayKeyBytes( Key k ) {
assert k._kb[0] == Key.ARRAYLET_CHUNK;
return Arrays.copyOfRange(k._kb,2+8,k._kb.length);
}
/** Get the chunk-index from a random arraylet sub-key */
public static long getChunkIndex(Key k) {
assert k._kb[0] == Key.ARRAYLET_CHUNK;
return UDP.get8(k._kb, 2) >> LOG_CHK;
}
public static long getChunkOffset(Key k) { return getChunkIndex(k)<<LOG_CHK; }
// ---
// Read a (possibly VERY large file) and put it in the K/V store and return a
// Value for it. Files larger than 2Meg are broken into arraylets of 1Meg each.
static public Key readPut(String keyname, InputStream is) throws IOException {
return readPut(Key.make(keyname), is);
}
static public Key readPut(Key k, InputStream is) throws IOException {
return readPut(k, is, null);
}
static public Key readPut(Key k, InputStream is, Job job) throws IOException {
readPut(k,is,job,new Futures()).blockForPending();
return k;
}
static private Futures readPut(Key key, InputStream is, Job job, final Futures fs) throws IOException {
UKV.remove(key);
byte[] oldbuf, buf = null;
int off = 0, sz = 0;
long szl = off;
long cidx = 0;
Futures dkv_fs = new Futures();
H2OCountedCompleter f_last = null;
while( true ) {
oldbuf = buf;
buf = MemoryManager.malloc1((int)CHUNK_SZ);
off=0;
while( off<CHUNK_SZ && (sz = is.read(buf,off,(int)(CHUNK_SZ-off))) != -1 )
off+=sz;
szl += off;
if( off<CHUNK_SZ ) break;
if( job != null && job.cancelled() ) break;
final Key ckey = getChunkKey(cidx++,key);
final Value val = new Value(ckey,buf);
// Do the 'DKV.put' in a F/J task. For multi-JVM setups, this step often
// means network I/O pushing the Value to a new Node. Putting it in a
// subtask allows the I/O to overlap with the read from the InputStream.
// Especially if the InputStream is a (g)unzip, its useful to overlap the
// write with read.
H2OCountedCompleter subtask = new H2OCountedCompleter() {
@Override public void compute2() {
DKV.put(val._key,val,fs,!val._key.home() && H2O.get(val._key) == null); // The only exciting thing in this innerclass!
tryComplete();
}
@Override public byte priority() { return H2O.ATOMIC_PRIORITY; }
};
H2O.submitTask(subtask);
// Also add the DKV task to the blocking list (not just the TaskPutKey
// buried inside the DKV!)
dkv_fs.add(subtask);
f_last = subtask;
}
assert is.read(new byte[1]) == -1 || job.cancelled();
// Last chunk is short, read it; combine buffers and make the last chunk larger
if( cidx > 0 ) {
Key ckey = getChunkKey(cidx-1,key); // Get last chunk written out
byte[] newbuf = MemoryManager.arrayCopyOf(oldbuf,(int)(off+CHUNK_SZ));
System.arraycopy(buf,0,newbuf,(int)CHUNK_SZ,off);
// Block for the last DKV to happen, because we're overwriting the last one
// with final size bits.
try { f_last.get(); }
catch( InterruptedException e ) { throw Log.errRTExcept(e); }
catch( ExecutionException e ) { throw Log.errRTExcept(e); }
DKV.put(ckey,new Value(ckey,newbuf),fs); // Overwrite the old too-small Value
} else {
Key ckey = getChunkKey(cidx,key);
DKV.put(ckey,new Value(ckey,Arrays.copyOf(buf,off)),fs);
}
UKV.put(key,new ValueArray(key,szl),fs);
// Block for all pending DKV puts, which will in turn add blocking requests
// to the passed-in Future list 'fs'.
dkv_fs.blockForPending();
return fs;
}
public static class VAStream extends InputStream {
protected AutoBuffer _ab;
protected long _chkidx;
protected final ValueArray _ary;
protected final ProgressMonitor _pm;
protected long _currentChunkSz;
public VAStream(ValueArray ary, ProgressMonitor pm){_ary = ary; _pm = pm;}
@Override public int available() throws IOException {
if( _ab==null || _ab.remaining()==0 ) {
if( _chkidx >= _ary.chunks() ) return 0;
_ab = _ary.getChunk(_chkidx++);
if(_pm != null)_pm.update(_currentChunkSz);
_currentChunkSz = _ab.remaining();
}
return _ab.remaining();
}
@Override public void close() { _chkidx = _ary.chunks(); _ab = null; }
@Override public int read() throws IOException {
return available() > 0 ? _ab.get1():-1;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
return available() > 0 ? _ab.read(b,off,len):-1;
}
}
public static class CsvVAStream extends VAStream {
private byte[] _currentLine;
private int _i,_rid, _numrows;
public CsvVAStream(ValueArray ary, ProgressMonitor pm){
this(ary,pm,true);
}
public CsvVAStream(ValueArray ary, ProgressMonitor pm, boolean header){
super(ary,pm);
StringBuilder sb = new StringBuilder('"' + ary._cols[0]._name + '"');
for(int i = 1; i < ary._cols.length; ++i)
sb.append(',').append('"' + ary._cols[i]._name + '"');
sb.append('\n');
_currentLine = sb.toString().getBytes();
_numrows = 1;
}
@Override
public int available() throws IOException{
if(_i == _currentLine.length){
if(++_rid == _numrows){
_ab = null;
int abytes = super.available();
if(abytes <= 0) return abytes;
_numrows = _ary.rpc(_chkidx-1);
_rid = 0;
}
StringBuilder sb = new StringBuilder();
boolean f = true;
for(Column c:_ary._cols){
if(f) f = false; else sb.append(',');
if(!_ary.isNA(_ab, _rid, c)){
if(c.isEnum()) sb.append('"' + c._domain[(int)_ary.data(_ab, _rid, c)] + '"');
else if(!c.isFloat()) sb.append(_ary.data(_ab, _rid, c));
else sb.append(_ary.datad(_ab,_rid,c));
}
}
sb.append('\n');
_currentLine = sb.toString().getBytes();
_i = 0;
}
return _currentLine.length - _i;
}
@Override public void close() { super.close(); _currentLine = null;}
@Override public int read() throws IOException {
return available() <= 0 ? -1 : _currentLine[_i++];
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int n = available();
if(n <= 0)return n;
n = Math.min(n, len);
System.arraycopy(_currentLine, _i, b, off, n);
_i += n;
return n;
}
}
// Wrap a InputStream over this ValueArray
public InputStream openStream() {return openStream(null);}
public InputStream openStream(ProgressMonitor p) {return new VAStream(this, p);}
}
diff --git a/src/main/java/water/parser/DParseTask.java b/src/main/java/water/parser/DParseTask.java
index ba9fc337c..75b8a67ea 100644
--- a/src/main/java/water/parser/DParseTask.java
+++ b/src/main/java/water/parser/DParseTask.java
@@ -1,1100 +1,1100 @@
package water.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import water.*;
import water.ValueArray.Column;
import water.parser.ParseDataset.FileInfo;
import water.util.Log;
/** Class responsible for actual parsing of the datasets.
*
* Works in two phases, first phase collects basic statistics and determines
* the column encodings of the dataset.
*
* Second phase the goes over all data again, encodes them and writes them to
* the result VA.
*
* The parser works distributed for CSV parsing, but is one node only for the
* XLS and XLSX formats (they are not fully our code).
*/
public class DParseTask extends MRTask<DParseTask> implements CustomParser.DataOut {
static enum Pass { ONE, TWO }
// pass 1 types
private static final byte UCOL = 0; // unknown
private static final byte ECOL = 11; // enum column
private static final byte ICOL = 12; // integer column
private static final byte FCOL = 13; // float column
private static final byte DCOL = 14; // double column
private static final byte TCOL = 15; // time column
// pass 2 types
private static final byte BYTE = 1;
private static final byte SHORT = 2;
private static final byte INT = 3;
private static final byte LONG = 4;
private static final byte DBYTE = 5;
private static final byte DSHORT = 6;
private static final byte FLOAT = 7;
private static final byte DOUBLE = 8;
private static final byte STRINGCOL = 9; // string column (too many enum values)
private static final int [] COL_SIZES = new int[]{0,1,2,4,8,1,2,-4,-8,1};
public void addColumns(int ncols){
_colTypes = Arrays.copyOf(_colTypes, ncols);
_min = Arrays.copyOf(_min, ncols);
_max = Arrays.copyOf(_max, ncols);
for(int i = _ncolumns; i < ncols; ++i){
_min[i] = Double.POSITIVE_INFINITY;
_max[i] = Double.NEGATIVE_INFINITY;
}
_scale = Arrays.copyOf(_scale, ncols);
_mean = Arrays.copyOf(_mean, ncols);
_invalidValues = Arrays.copyOf(_invalidValues, ncols);
_ncolumns = ncols;
createEnums();
}
// scalar variables
Pass _phase;
long _numRows;
transient int _myrows;
int _ncolumns;
int _rpc;
int _rowsize;
ParseDataset _job;
String _error;
CustomParser _parser;
boolean _streamMode;
protected boolean _map;
// arrays
byte [] _colTypes;
int [] _scale;
int [] _bases;
long [] _invalidValues;
double [] _min;
double [] _max;
double [] _mean;
double [] _sigma;
long [] _nrows;
Enum [] _enums;
// transient
transient int _chunkId;
// create and used only on the task caller's side
transient String[][] _colDomains;
@Override
public long memOverheadPerChunk(){
// double memory for phase2 should be safe upper limit here (and too far off from the actual either)
return (_phase == Pass.TWO)?2*ValueArray.CHUNK_SZ:ValueArray.CHUNK_SZ;
}
public DParseTask clone2(){
DParseTask t = newInstance();
t._ncolumns = _ncolumns;
t._parser = (_parser == null)?null:_parser.clone();
t._sourceDataset = _sourceDataset;
t._enums = _enums;
t._colTypes = _colTypes;
t._nrows = _nrows;
t._job = _job;
t._numRows = _numRows;
t._scale = _scale;
t._bases = _bases;
t._ncolumns = _ncolumns;
t._min = _min;
t._max = _max;
t._mean = _mean;
t._sigma = _sigma;
t._colNames = _colNames;
t._error = _error;
t._invalidValues = _invalidValues;
t._phase = _phase;
assert t._colTypes == null || t._ncolumns == t._colTypes.length;
return t;
}
private static final class VAChunkDataIn implements CustomParser.DataIn {
final Key _key;
public VAChunkDataIn(Key k) {_key = k;}
// Fetch chunk data on demand
public byte[] getChunkData( int cidx ) {
Key key = _key;
if( key._kb[0] == Key.ARRAYLET_CHUNK ) { // Chunked data?
Key aryKey = ValueArray.getArrayKey(key);
ValueArray ary = DKV.get(aryKey).get();
if( cidx >= ary.chunks() ) return null;
key = ary.getChunkKey(cidx); // Return requested chunk
} else {
if( cidx > 0 ) return null; // Single chunk? No next chunk
}
Value v = DKV.get(key);
return v == null ? null : v.memOrLoad();
}
}
/** Manages the chunk parts of the result hex varray.
*
* Second pass parse encodes the data from the source file to the sequence
* of these stream objects. Each stream object will always go to a single
* chunk (but a single chunk can contain more stream objects). To manage
* this situation, the list of stream records is created upfront and then
* filled automatically.
*
* Stream record then knows its chunkIndex, that is which chunk it will be
* written to, the offset into that chunk it will be written and the number
* of input rows that will be parsed to it.
*/
private final class OutputStreamRecord {
final int _chunkIndex;
final int _chunkOffset;
final int _numRows;
AutoBuffer _abs;
/** Allocates the stream for the chunk. Streams should only be allocated
* right before the record will be used and should be stored immediately
* after that.
*/
public AutoBuffer initialize() {
assert _abs == null;
return (_abs = new AutoBuffer(_numRows * _rowsize));
}
/** Stores the stream to its chunk using the atomic union. After the data
* from the stream is stored, its memory is freed up.
*/
public void store() {
assert _abs.eof():"expected eof, position=" + _abs.position() + ", size=" + _abs._size;
Key k = ValueArray.getChunkKey(_chunkIndex, _job.dest());
AtomicUnion u = new AtomicUnion(_abs.bufClose(),_chunkOffset);
alsoBlockFor(u.fork(k));
_abs = null; // free mem
}
// You are not expected to create record streams yourself, use the
// createRecords method of the DParseTask.
protected OutputStreamRecord(int chunkIndex, int chunkOffset, int numRows) {
_chunkIndex = chunkIndex;
_chunkOffset = chunkOffset;
_numRows = numRows;
}
}
public static class AtomicUnion extends Atomic {
byte [] _bits;
int _dst_off;
public AtomicUnion(byte[] buf, int dstOff){
_dst_off = dstOff;
_bits = buf;
}
@Override public Value atomic( Value val1 ) {
byte[] mem = _bits;
int len = Math.max(_dst_off + mem.length,val1==null?0:val1._max);
byte[] bits2 = MemoryManager.malloc1(len);
if( val1 != null ) System.arraycopy(val1.memOrLoad(),0,bits2,0,val1._max);
System.arraycopy(mem,0,bits2,_dst_off,mem.length);
return new Value(_key,bits2);
}
@Override public void onSuccess(){
_bits = null; // Do not return the bits
}
}
/** Returns the list of streams that should be used to store the given rows.
*
* None of the returned streams is initialized.
*/
protected OutputStreamRecord[] createRecords(long firstRow, int rowsToParse) {
assert (_rowsize != 0);
ArrayList<OutputStreamRecord> result = new ArrayList();
int rpc = (int) ValueArray.CHUNK_SZ / _rowsize;
int rowInChunk = (int)firstRow % rpc;
long lastChunk = Math.max(1,this._numRows / rpc) - 1; // index of the last chunk in the VA
int chunkIndex = (int)firstRow/rpc; // index of the chunk I am writing to
if (chunkIndex > lastChunk) { // we can be writing to the second chunk after its real boundary
assert (chunkIndex == lastChunk + 1);
rowInChunk += rpc;
--chunkIndex;
}
do {
// number of rows that go the the current chunk - all remaining rows for the
// last chunk, or the number of rows that can go to the chunk
int rowsToChunk = (chunkIndex == lastChunk) ? rowsToParse : Math.min(rowsToParse, rpc - rowInChunk);
// add the output stream reacord
result.add(new OutputStreamRecord(chunkIndex, rowInChunk * _rowsize, rowsToChunk));
// update the running variables
if (chunkIndex < lastChunk) {
rowInChunk = 0;
++chunkIndex;
}
rowsToParse -= rowsToChunk;
assert (rowsToParse >= 0);
} while (rowsToParse > 0);
_outputIdx = 0;
_colIdx = _ncolumns; // skip first line
// return all output streams
return result.toArray(new OutputStreamRecord[result.size()]);
}
transient OutputStreamRecord[] _outputStreams2;
transient AutoBuffer _ab;
transient int _outputIdx;
transient String[] _colNames;
transient Value _sourceDataset;
transient int _colIdx;
public boolean isString(int idx) {
// in case of idx which is oob, pretend it is a string col (it will be dropped anyways)
return idx >= _ncolumns || _colTypes[idx]==STRINGCOL;
}
// As this is only used for distributed CSV parser we initialize the values
// for the CSV parser itself.
public DParseTask() {
_sourceDataset = null;
_phase = Pass.ONE;
_parser = null;
}
protected DParseTask makePhase2Clone(FileInfo finfo){
DParseTask t = clone2();
t._nrows = finfo._nrows;
t._sourceDataset = DKV.get(finfo._ikey);
t._parser._setup._header = finfo._header;
return t;
}
/** Private constructor for phase two, copy constructor from phase one.
*
* Use createPhaseTwo() static method instead.
*
* @param other
*/
private DParseTask(DParseTask other) {
assert (other._phase == Pass.ONE);
// copy the phase one data
// don't pass invalid values, we do not need them 2nd pass
_parser = other._parser;
_sourceDataset = other._sourceDataset;
_enums = other._enums;
_colTypes = other._colTypes;
_nrows = other._nrows;
_job = other._job;
_numRows = other._numRows;
_scale = other._scale;
_ncolumns = other._ncolumns;
_min = other._min;
_max = other._max;
_mean = other._mean;
_sigma = other._sigma;
_colNames = other._colNames;
_error = other._error;
_invalidValues = other._invalidValues;
_phase = Pass.TWO;
}
/** Creates a phase one dparse task.
*
* @param dataset Dataset to parse.
* @param resultKey VA to store results to.
* @param parserType Parser type to use.
* @return Phase one DRemoteTask object.
*/
public DParseTask createPassOne(Value dataset, ParseDataset job, CustomParser parser) {
DParseTask t = clone2();
t._sourceDataset = dataset;
t._job = job;
t._phase = Pass.ONE;
t._parser = parser;
if(t._parser._setup != null)
t._ncolumns = parser._setup._ncols;
return t;
}
/** Executes the phase one of the parser.
*
* First phase detects the encoding and basic statistics of the parsed
* dataset.
*
* For CSV parsers it detects the parser setup and then launches the
* distributed computation on per chunk basis.
*
* For XLS and XLSX parsers that do not work in distrubuted way parses the
* whole datasets.
*
* @throws Exception
*/
public void passOne() {
boolean arraylet;
if((arraylet = _sourceDataset.isArray())) {
ValueArray ary = _sourceDataset.get();
_nrows = new long[(int)ary.chunks()+1];
} else
_nrows = new long[2];
// launch the distributed parser on its chunks.
if(_parser.parallelParseSupported()){
dfork(_sourceDataset._key);
} else {
createEnums(); // otherwise called in init()
phaseOneInitialize(); // otherwise called in map
try{
_streamMode = true;
_parser.streamParse(DKV.get(_sourceDataset._key).openStream(), this);
_numRows = _myrows;
_map = true;
// TODO,do I have to call tryComplete here?
tryComplete();
} catch(Exception e){throw new RuntimeException(e);}
}
}
/**
* Creates the second pass dparse task from a first phase one.
*/
public DParseTask createPassTwo() {
assert _map:"creating pass two on an instance which did not have any map result from pass 1 stored in.";
DParseTask t = clone2();
t._phase = Pass.TWO;
// calculate proper numbers of rows for the chunks
// normalize mean
for(int i = 0; i < t._ncolumns; ++i)
t._mean[i] = t._mean[i]/(t._numRows - t._invalidValues[i]);
// create new data for phase two
t._colDomains = new String[t._ncolumns][];
t._bases = new int[t._ncolumns];
// calculate the column domains
if(_enums != null)
for(int i = 0; i < t._enums.length; ++i){
if(t._colTypes[i] == ECOL && t._enums[i] != null && !t._enums[i].isKilled())
t._colDomains[i] = t._enums[i].computeColumnDomain();
else
t._enums[i] = null;
}
t.calculateColumnEncodings();
assert t._bases != null;
return t;
}
/** Executes the phase two of the parser task.
*
* In phase two the data is encoded to the final VA, which is then created
* properly at the end.
*
* For CSV launches the distributed computation.
*
* For XLS and XLSX parsers computes all the chunks itself as there is no
* option for their distributed processing.
*/
public void passTwo() {
_phase = Pass.TWO;
_myrows = 0;
// make sure we delete previous array here, because we insert arraylet header after all chunks are stored in
// so if we do not delete it now, it will be deleted by UKV automatically later and destroy our values!
if(DKV.get(_job.dest()) != null)
UKV.remove(_job.dest());
if(_parser.parallelParseSupported())
this.invoke(_sourceDataset._key);
else {
// initialize statistics - invalid rows, sigma and row size
phaseTwoInitialize();
// create the output streams
_outputStreams2 = createRecords(0, (int)_numRows);
assert (_outputStreams2.length > 0);
_ab = _outputStreams2[0].initialize();
// perform the second parse pass
try{
_streamMode = true;
_parser.streamParse(DKV.get(_sourceDataset._key).openStream(),this);
} catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
// store the last stream if not stored during the parse
if (_ab != null)
_outputStreams2[_outputIdx].store();
}
normalizeSigma();
}
public void normalizeSigma() {
// normalize sigma
for(int i = 0; i < _ncolumns; ++i)
_sigma[i] = Math.sqrt(_sigma[i]/(_numRows - _invalidValues[i] - 1));
}
/** Creates the value header based on the calculated columns.
*
* Also stores the header to its appropriate key. This will be the VA header
* of the parsed dataset.
*/
protected void createValueArrayHeader() {
assert (_phase == Pass.TWO);
Column[] cols = new Column[_ncolumns];
int off = 0;
for( int i = 0; i < cols.length; ++i) {
cols[i] = new Column();
cols[i]._n = _numRows - _invalidValues[i];
cols[i]._base = _bases[i];
assert (char)pow10i(-_scale[i]) == pow10i(-_scale[i]):"scale out of bounds!, col = " + i + ", scale = " + _scale[i];
cols[i]._scale = (char)pow10i(-_scale[i]);
- cols[i]._off = (char)off;
+ cols[i]._off = off;
cols[i]._size = (byte)COL_SIZES[_colTypes[i]];
cols[i]._domain = _colDomains[i];
cols[i]._max = _max[i];
cols[i]._min = _min[i];
cols[i]._mean = _mean[i];
cols[i]._sigma = _sigma[i];
cols[i]._name = _colNames[i];
off += Math.abs(cols[i]._size);
}
// let any pending progress reports finish
DKV.write_barrier();
// finally make the value array header
ValueArray ary = new ValueArray(_job.dest(), _numRows, off, cols);
UKV.put(_job.dest(), ary);
}
protected void createEnums() {
_enums = new Enum[_ncolumns];
for(int i = 0; i < _ncolumns; ++i)
_enums[i] = new Enum();
}
@Override public void init(){
super.init();
if(_phase == Pass.ONE)createEnums();
}
/** Sets the column names and creates the array of the enums for each
* column.
*/
public void setColumnNames(String[] colNames) {
if (_phase == Pass.ONE) {
assert (colNames != null);
addColumns(colNames.length);
}
_colNames = colNames;
}
/** Initialize phase one data structures with the appropriate number of
* columns.
*/
public void phaseOneInitialize() {
if (_phase != Pass.ONE)
assert (_phase == Pass.ONE);
_invalidValues = new long[_ncolumns];
_min = new double [_ncolumns];
Arrays.fill(_min, Double.POSITIVE_INFINITY);
_max = new double[_ncolumns];
Arrays.fill(_max, Double.NEGATIVE_INFINITY);
_mean = new double[_ncolumns];
_scale = new int[_ncolumns];
_colTypes = new byte[_ncolumns];
}
/** Initializes the phase two data. */
public void phaseTwoInitialize() {
assert (_phase == Pass.TWO);
_invalidValues = new long[_ncolumns];
_sigma = new double[_ncolumns];
_rowsize = 0;
for(byte b:_colTypes) _rowsize += Math.abs(COL_SIZES[b]);
}
/** Map function for distributed parsing of the CSV files.
*
* In first phase it calculates the min, max, means, encodings and other
* statistics about the dataset, determines the number of columns.
*
* The second pass then encodes the parsed dataset to the result key,
* splitting it into equal sized chunks.
*/
@Override public void map(Key key) {
if(_job.cancelled())
return;
try{
_map = true;
Key aryKey = null;
boolean arraylet = key._kb[0] == Key.ARRAYLET_CHUNK;
if(arraylet) {
aryKey = ValueArray.getArrayKey(key);
_chunkId = (int)ValueArray.getChunkIndex(key);
}
switch (_phase) {
case ONE:
// initialize the column statistics
phaseOneInitialize();
// perform the parse
_parser.clone().parallelParse(_chunkId, new VAChunkDataIn(key), this);
if(arraylet) {
long idx = _chunkId+1;
int idx2 = (int)idx;
assert idx2 == idx;
if(idx2 >= _nrows.length){
System.err.println("incorrect index/array size for key = " + key + ": " + _nrows.length + " <= " + idx2 + ", aryKey = " + aryKey + ", chunks# = " + DKV.get(aryKey).get(ValueArray.class).chunks());
assert false;
}
assert (_nrows[idx2] == 0) : idx+": "+Arrays.toString(_nrows)+" ("+_nrows[idx2]+" -- "+_numRows+")";
_nrows[idx2] = _myrows;
} else
_nrows[1] = _myrows;
_numRows = _myrows;
break;
case TWO:
assert (_ncolumns != 0);
assert (_phase == Pass.TWO);
// initialize statistics - invalid rows, sigma and row size
phaseTwoInitialize();
// calculate the first row and the number of rows to parse
long firstRow = _nrows[_chunkId];
long lastRow = _nrows[_chunkId+1];
int rowsToParse = (int)(lastRow - firstRow);
// create the output streams
_outputStreams2 = createRecords(firstRow, rowsToParse);
assert (_outputStreams2.length > 0);
_ab = _outputStreams2[0].initialize();
// perform the second parse pass
_parser.clone().parallelParse(_chunkId, new VAChunkDataIn(key), this);
// store the last stream if not stored during the parse
if( _ab != null )
_outputStreams2[_outputIdx].store();
getFutures().blockForPending();
break;
default:
assert (false);
}
assert _ncolumns == _colTypes.length;
ParseDataset.onProgress(key,_job._progress);
}catch(Throwable t){
t.printStackTrace();
}
}
@Override
public void reduce(DParseTask dpt) {
if(_job.cancelled())
return;
assert dpt._map;
if(_sigma == null)_sigma = dpt._sigma;
if(!_map){
_map = dpt._map;
_enums = dpt._enums;
_min = dpt._min;
_max = dpt._max;
_mean = dpt._mean;
_sigma = dpt._sigma;
_scale = dpt._scale;
_colTypes = dpt._colTypes;
_ncolumns = dpt._ncolumns;
_nrows = dpt._nrows;
_invalidValues = dpt._invalidValues;
} else {
assert _ncolumns >= dpt._ncolumns;
if (_phase == Pass.ONE) {
if (_nrows != dpt._nrows)
for (int i = 0; i < dpt._nrows.length; ++i)
_nrows[i] |= dpt._nrows[i];
if(_enums != null) for(int i = 0; i < dpt._ncolumns; ++i)
if(_enums[i] != dpt._enums[i])
_enums[i].merge(dpt._enums[i]);
for(int i = 0; i < dpt._ncolumns; ++i) {
if(dpt._min[i] < _min[i])_min[i] = dpt._min[i];
if(dpt._max[i] > _max[i])_max[i] = dpt._max[i];
if(dpt._scale[i] < _scale[i])_scale[i] = dpt._scale[i];
if(dpt._colTypes[i] > _colTypes[i])_colTypes[i] = dpt._colTypes[i];
_mean[i] += dpt._mean[i];
}
} else if(_phase == Pass.TWO) {
for(int i = 0; i < dpt._ncolumns; ++i)
_sigma[i] += dpt._sigma[i];
} else
assert false:"unexpected _phase value:" + _phase;
for(int i = 0; i < dpt._ncolumns; ++i)
_invalidValues[i] += dpt._invalidValues[i];
}
_numRows += dpt._numRows;
if(_error == null)_error = dpt._error;
else if(dpt._error != null) _error = _error + "\n" + dpt._error;
assert _colTypes.length == _ncolumns;
}
static double [] powers10 = new double[]{
0.0000000001,
0.000000001,
0.00000001,
0.0000001,
0.000001,
0.00001,
0.0001,
0.001,
0.01,
0.1,
1.0,
10.0,
100.0,
1000.0,
10000.0,
100000.0,
1000000.0,
10000000.0,
100000000.0,
1000000000.0,
10000000000.0,
};
static long [] powers10i = new long[]{
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000l
};
public static double pow10(int exp){
return ((exp >= -10 && exp <= 10)?powers10[exp+10]:Math.pow(10, exp));
}
public static long pow10i(int exp){
assert 10 >= exp && exp >= 0:"unexpected exponent " + exp;
return powers10i[exp];
}
public static final boolean fitsIntoInt(double d){
return Math.abs((int)d - d) < 1e-8;
}
@SuppressWarnings("fallthrough")
private void calculateColumnEncodings() {
assert (_bases != null);
assert _scale != null;
assert (_min != null);
assert _ncolumns == _colTypes.length:"ncols=" + _ncolumns + ", colTypes.length=" + _colTypes.length;
for(int i = 0; i < _ncolumns; ++i){
// Entirely toss out numeric columns which are largely broken.
if( (_colTypes[i]==ICOL || _colTypes[i]==DCOL || _colTypes[i]==FCOL ) &&
(double)_invalidValues[i]/_numRows > 0.2 ) {
_enums[i] = null;
_max[i] = _min[i] = 0;
_scale[i] = 0;
_bases[i] = 0;
_colTypes[i] = STRINGCOL;
continue;
}
switch(_colTypes[i]){
case UCOL: // only missing values
_colTypes[i] = BYTE;
break;
case ECOL: // enum
if(_enums[i] == null || _enums[i].isKilled()){
_max[i] = 0;
_min[i] = 0;
_colTypes[i] = STRINGCOL;
} else {
_max[i] = _colDomains[i].length-1;
_min[i] = 0;
if(_max[i] < 256)_colTypes[i] = BYTE;
else if(_max[i] < 65536)_colTypes[i] = SHORT;
else _colTypes[i] = INT;
}
break;
case ICOL: // number
if (_max[i] - _min[i] < 255) {
_colTypes[i] = BYTE;
_bases[i] = (int)_min[i];
} else if ((_max[i] - _min[i]) < 65535) {
_colTypes[i] = SHORT;
_bases[i] = (int)_min[i];
} else if (_max[i] - _min[i] < (1L << 32) &&
_min[i] > Integer.MIN_VALUE && _min[i] < Integer.MAX_VALUE) {
_colTypes[i] = INT;
_bases[i] = (int)_min[i];
} else
_colTypes[i] = LONG;
break;
case FCOL:
case DCOL:
if(_scale[i] >= -4 && (_max[i] <= powers10i[powers10i.length-1]) && (_min[i] >= -powers10i[powers10i.length-1])){
double s = pow10(-_scale[i]);
double range = s*(_max[i]-_min[i]);
double base = s*_min[i];
if(range < 256){
if(fitsIntoInt(base)) { // check if base fits into int!
_colTypes[i] = DBYTE;
_bases[i] = (int)base;
break;
}
} else if(range < 65535){
if(fitsIntoInt(base)){
_colTypes[i] = DSHORT;
_bases[i] = (int)(base);
break;
}
}
}
_scale[i] = 0;
_bases[i] = 0;
_colTypes[i] = (_colTypes[i] == FCOL)?FLOAT:DOUBLE;
break;
case TCOL: // Time; millis since jan 1, 1970
_scale[i] = -1;
_bases[i] = 0;
_colTypes[i] = LONG;
break;
default: throw H2O.unimpl();
}
}
_invalidValues = null;
}
/** Advances to new line. In phase two it also must make sure that the
*
*/
public void newLine() {
++_myrows;
if (_phase == Pass.TWO) {
while (_colIdx < _ncolumns)
addInvalidCol(_colIdx);
_colIdx = 0;
// if we are at the end of current stream, move to the next one
if (_ab.eof()) {
assert _outputStreams2[_outputIdx]._abs == _ab;
_outputStreams2[_outputIdx++].store();
if (_outputIdx < _outputStreams2.length) {
_ab = _outputStreams2[_outputIdx].initialize();
} else {
_ab = null; // just to be sure we throw a NPE if there is a problem
}
}
}
}
/** Rolls back parsed line. Useful for CsvParser when it parses new line
* that should not be added. It can easily revert it by this.
*/
public void rollbackLine() {
--_myrows;
assert (_phase == Pass.ONE || _ab == null) : "p="+_phase+" ab="+_ab+" oidx="+_outputIdx+" chk#"+_chunkId+" myrow"+_myrows+" ";//+_sourceDataset._key;
}
/** Adds double value to the column.
*
* @param colIdx
* @param value
*/
public void addNumCol(int colIdx, double value) {
if (Double.isNaN(value)) {
addInvalidCol(colIdx);
} else {
double d= value;
int exp = 0;
long number = (long)d;
while (number != d) {
d = d * 10;
--exp;
number = (long)d;
}
addNumCol(colIdx, number, exp);
}
}
/** Adds invalid value to the column. */
public void addInvalidCol(int colIdx){
++_colIdx;
if(colIdx >= _ncolumns)
return;
++_invalidValues[colIdx];
if(_phase == Pass.ONE)
return;
switch (_colTypes[colIdx]) {
case BYTE:
case DBYTE:
_ab.put1(-1);
break;
case SHORT:
case DSHORT:
_ab.put2((short)-1);
break;
case INT:
_ab.put4(Integer.MIN_VALUE);
break;
case LONG:
_ab.put8(Long.MIN_VALUE);
break;
case FLOAT:
_ab.put4f(Float.NaN);
break;
case DOUBLE:
_ab.put8d(Double.NaN);
break;
case STRINGCOL:
// TODO, replace with empty space!
_ab.put1(-1);
break;
default:
assert false:"illegal case: " + _colTypes[colIdx];
}
}
/** Adds string (enum) value to the column. */
public void addStrCol( int colIdx, ValueString str ) {
if( colIdx >= _ncolumns )
return;
switch (_phase) {
case ONE:
++_colIdx;
// If this is a yet unspecified but non-numeric column, attempt a time-parse
if( _colTypes[colIdx] == UCOL &&
attemptTimeParse(str) != Long.MIN_VALUE )
_colTypes[colIdx] = TCOL; // Passed a time-parse, so assume a time-column
if( _colTypes[colIdx] == TCOL ) {
long time = attemptTimeParse(str);
if( time != Long.MIN_VALUE ) {
if(time < _min[colIdx])_min[colIdx] = time;
if(time > _max[colIdx])_max[colIdx] = time;
_mean[colIdx] += time;
} else {
++_invalidValues[colIdx];
}
return;
}
// Now attempt to make this an Enum col
Enum e = _enums[colIdx];
if( e == null || e.isKilled() ) return;
if( _colTypes[colIdx] == UCOL )
_colTypes[colIdx] = ECOL;
e.addKey(str);
++_invalidValues[colIdx]; // invalid count in phase0 is in fact number of non-numbers (it is used for mean computation, is recomputed in 2nd pass)
break;
case TWO:
if(_enums[colIdx] != null) {
++_colIdx;
int id = _enums[colIdx].getTokenId(str);
// we do not expect any misses here
assert 0 <= id && id < _enums[colIdx].size();
switch (_colTypes[colIdx]) {
case BYTE: _ab.put1( id); break;
case SHORT: _ab.put2((char)id); break;
case INT: _ab.put4( id); break;
default: assert false:"illegal case: " + _colTypes[colIdx];
}
} else if( _colTypes[colIdx] == LONG ) {
++_colIdx;
// Times are strings with a numeric column type of LONG
long time = attemptTimeParse(str);
_ab.put8(time);
// Update sigma
if( !Double.isNaN(_mean[colIdx])) {
double d = time - _mean[colIdx];
_sigma[colIdx] += d*d;
}
} else {
addInvalidCol(colIdx);
}
break;
default:
assert (false);
}
}
/** Adds number value to the column parsed with mantissa and exponent. */
static final int MAX_FLOAT_MANTISSA = 0x7FFFFF;
@SuppressWarnings("fallthrough")
public void addNumCol(int colIdx, long number, int exp) {
++_colIdx;
if(colIdx >= _ncolumns)
return;
switch (_phase) {
case ONE:
double d = number*pow10(exp);
if(d < _min[colIdx])_min[colIdx] = d;
if(d > _max[colIdx])_max[colIdx] = d;
_mean[colIdx] += d;
if(exp != 0) {
if(exp < _scale[colIdx])_scale[colIdx] = exp;
if(_colTypes[colIdx] != DCOL){
if(Math.abs(number) > MAX_FLOAT_MANTISSA || exp < -35 || exp > 35)
_colTypes[colIdx] = DCOL;
else
_colTypes[colIdx] = FCOL;
}
} else if(_colTypes[colIdx] < ICOL) {
_colTypes[colIdx] = ICOL;
}
break;
case TWO:
assert _ab != null;
switch (_colTypes[colIdx]) {
case BYTE:
_ab.put1((byte)(number*pow10i(exp - _scale[colIdx]) - _bases[colIdx]));
break;
case SHORT:
_ab.put2((short)(number*pow10i(exp - _scale[colIdx]) - _bases[colIdx]));
break;
case INT:
_ab.put4((int)(number*pow10i(exp - _scale[colIdx]) - _bases[colIdx]));
break;
case LONG:
_ab.put8(number*pow10i(exp - _scale[colIdx]));
break;
case FLOAT:
_ab.put4f((float)(number * pow10(exp)));
break;
case DOUBLE:
_ab.put8d(number * pow10(exp));
break;
case DBYTE:
_ab.put1((short)(number*pow10i(exp - _scale[colIdx]) - _bases[colIdx]));
break;
case DSHORT:
// scale is computed as negative in the first pass,
// therefore to compute the positive exponent after scale, we add scale and the original exponent
_ab.put2((short)(number*pow10i(exp - _scale[colIdx]) - _bases[colIdx]));
break;
case STRINGCOL:
break;
}
// update sigma
if(!Double.isNaN(_mean[colIdx])) {
d = number*pow10(exp) - _mean[colIdx];
_sigma[colIdx] += d*d;
}
break;
default:
assert (false);
}
}
// Deduce if we are looking at a Date/Time value, or not.
// If so, return time as msec since Jan 1, 1970 or Long.MIN_VALUE.
// I tried java.util.SimpleDateFormat, but it just throws too many
// exceptions, including ParseException, NumberFormatException, and
// ArrayIndexOutOfBoundsException... and the Piece de resistance: a
// ClassCastException deep in the SimpleDateFormat code:
// "sun.util.calendar.Gregorian$Date cannot be cast to sun.util.calendar.JulianCalendar$Date"
private static int digit( int x, int c ) {
if( x < 0 || c < '0' || c > '9' ) return -1;
return x*10+(c-'0');
}
private long attemptTimeParse( ValueString str ) {
long t0 = attemptTimeParse_0(str); // "yyyy-MM-dd HH:mm:ss.SSS"
if( t0 != Long.MIN_VALUE ) return t0;
long t1 = attemptTimeParse_1(str); // "dd-MMM-yy"
if( t1 != Long.MIN_VALUE ) return t1;
return Long.MIN_VALUE;
}
// So I just brutally parse "yyyy-MM-dd HH:mm:ss.SSS"
private long attemptTimeParse_0( ValueString str ) {
final byte[] buf = str._buf;
int i=str._off;
final int end = i+str._length;
while( i < end && buf[i] == ' ' ) i++;
if ( i < end && buf[i] == '"' ) i++;
if( (end-i) < 19 ) return Long.MIN_VALUE;
int yy=0, MM=0, dd=0, HH=0, mm=0, ss=0, SS=0;
yy = digit(yy,buf[i++]);
yy = digit(yy,buf[i++]);
yy = digit(yy,buf[i++]);
yy = digit(yy,buf[i++]);
if( yy < 1970 ) return Long.MIN_VALUE;
if( buf[i++] != '-' ) return Long.MIN_VALUE;
MM = digit(MM,buf[i++]);
MM = digit(MM,buf[i++]);
if( MM < 1 || MM > 12 ) return Long.MIN_VALUE;
if( buf[i++] != '-' ) return Long.MIN_VALUE;
dd = digit(dd,buf[i++]);
dd = digit(dd,buf[i++]);
if( dd < 1 || dd > 31 ) return Long.MIN_VALUE;
if( buf[i++] != ' ' ) return Long.MIN_VALUE;
HH = digit(HH,buf[i++]);
HH = digit(HH,buf[i++]);
if( HH < 0 || HH > 23 ) return Long.MIN_VALUE;
if( buf[i++] != ':' ) return Long.MIN_VALUE;
mm = digit(mm,buf[i++]);
mm = digit(mm,buf[i++]);
if( mm < 0 || mm > 59 ) return Long.MIN_VALUE;
if( buf[i++] != ':' ) return Long.MIN_VALUE;
ss = digit(ss,buf[i++]);
ss = digit(ss,buf[i++]);
if( ss < 0 || ss > 59 ) return Long.MIN_VALUE;
if( i<end && buf[i] == '.' ) {
i++;
if( i<end ) SS = digit(SS,buf[i++]);
if( i<end ) SS = digit(SS,buf[i++]);
if( i<end ) SS = digit(SS,buf[i++]);
if( SS < 0 || SS > 999 ) return Long.MIN_VALUE;
}
if( i<end && buf[i] == '"' ) i++;
if( i<end ) return Long.MIN_VALUE;
return new GregorianCalendar(yy,MM,dd,HH,mm,ss).getTimeInMillis()+SS;
}
// So I just brutally parse "dd-MMM-yy".
public static final byte MMS[][][] = new byte[][][] {
{"jan".getBytes(),null},
{"feb".getBytes(),null},
{"mar".getBytes(),null},
{"apr".getBytes(),null},
{"may".getBytes(),null},
{"jun".getBytes(),"june".getBytes()},
{"jul".getBytes(),"july".getBytes()},
{"aug".getBytes(),null},
{"sep".getBytes(),"sept".getBytes()},
{"oct".getBytes(),null},
{"nov".getBytes(),null},
{"dec".getBytes(),null}
};
private long attemptTimeParse_1( ValueString str ) {
final byte[] buf = str._buf;
int i=str._off;
final int end = i+str._length;
while( i < end && buf[i] == ' ' ) i++;
if ( i < end && buf[i] == '"' ) i++;
if( (end-i) < 8 ) return Long.MIN_VALUE;
int yy=0, MM=0, dd=0;
dd = digit(dd,buf[i++]);
if( buf[i] != '-' ) dd = digit(dd,buf[i++]);
if( dd < 1 || dd > 31 ) return Long.MIN_VALUE;
if( buf[i++] != '-' ) return Long.MIN_VALUE;
byte[]mm=null;
OUTER: for( ; MM<MMS.length; MM++ ) {
byte[][] mms = MMS[MM];
INNER: for( int k=0; k<mms.length; k++ ) {
mm = mms[k];
if( mm == null ) continue;
for( int j=0; j<mm.length; j++ )
if( mm[j] != Character.toLowerCase(buf[i+j]) )
continue INNER;
break OUTER;
}
}
if( MM == MMS.length ) return Long.MIN_VALUE; // No matching month
i += mm.length; // Skip month bytes
MM++; // 1-based month
if( buf[i++] != '-' ) return Long.MIN_VALUE;
yy = digit(yy,buf[i++]);
yy = digit(yy,buf[i++]);
yy += 2000; // Y2K bug
if( i<end && buf[i] == '"' ) i++;
if( i<end ) return Long.MIN_VALUE;
return new GregorianCalendar(yy,MM,dd).getTimeInMillis();
}
@Override public void invalidLine(int lineNum) {} //TODO
@Override public void invalidValue(int line, int col) {} //TODO
}
| false | false | null | null |
diff --git a/src/org/gridsphere/portlets/core/admin/users/UserManagerPortlet.java b/src/org/gridsphere/portlets/core/admin/users/UserManagerPortlet.java
index c0a3f8f08..3fc0c3dca 100644
--- a/src/org/gridsphere/portlets/core/admin/users/UserManagerPortlet.java
+++ b/src/org/gridsphere/portlets/core/admin/users/UserManagerPortlet.java
@@ -1,653 +1,655 @@
/*
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id: UserManagerPortlet.java 5088 2006-08-18 22:53:27Z novotny $
*/
package org.gridsphere.portlets.core.admin.users;
import org.gridsphere.portlet.service.PortletServiceException;
import org.gridsphere.provider.event.jsr.ActionFormEvent;
import org.gridsphere.provider.event.jsr.RenderFormEvent;
import org.gridsphere.provider.portlet.jsr.ActionPortlet;
import org.gridsphere.provider.portletui.beans.*;
import org.gridsphere.provider.portletui.model.DefaultTableModel;
import org.gridsphere.services.core.mail.MailMessage;
import org.gridsphere.services.core.mail.MailService;
import org.gridsphere.services.core.persistence.QueryFilter;
import org.gridsphere.services.core.portal.PortalConfigService;
import org.gridsphere.services.core.security.password.PasswordEditor;
import org.gridsphere.services.core.security.password.PasswordManagerService;
import org.gridsphere.services.core.security.role.PortletRole;
import org.gridsphere.services.core.security.role.RoleManagerService;
import org.gridsphere.services.core.user.User;
import org.gridsphere.services.core.user.UserManagerService;
import javax.portlet.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
public class UserManagerPortlet extends ActionPortlet {
// JSP pages used by this portlet
public static final String DO_VIEW_USER_LIST = "admin/users/doViewUserList.jsp";
public static final String DO_VIEW_USER_VIEW = "admin/users/doViewUserView.jsp";
public static final String DO_VIEW_USER_EDIT = "admin/users/doViewUserEdit.jsp";
public static final String DO_SEND_EMAIL = "admin/users/doSendEmail.jsp";
// Portlet services
private UserManagerService userManagerService = null;
private PasswordManagerService passwordManagerService = null;
private RoleManagerService roleManagerService = null;
private PortalConfigService portalConfigService = null;
private MailService mailService = null;
private String NUM_PAGES = getClass() + ".NUM_PAGES";
private String EMAIL_QUERY = getClass() + ".EMAIL_QUERY";
private String ORG_QUERY = getClass() + ".ORG_QUERY";
public void init(PortletConfig config) throws PortletException {
super.init(config);
this.userManagerService = (UserManagerService) createPortletService(UserManagerService.class);
this.roleManagerService = (RoleManagerService) createPortletService(RoleManagerService.class);
this.passwordManagerService = (PasswordManagerService) createPortletService(PasswordManagerService.class);
this.mailService = (MailService) createPortletService(MailService.class);
this.portalConfigService = (PortalConfigService) createPortletService(PortalConfigService.class);
DEFAULT_HELP_PAGE = "admin/users/help.jsp";
DEFAULT_VIEW_PAGE = "doListUsers";
}
public void doListUsers(ActionFormEvent evt)
throws PortletException {
setNextState(evt.getActionRequest(), DEFAULT_VIEW_PAGE);
}
public void doListUsers(RenderFormEvent evt)
throws PortletException {
PortletRequest req = evt.getRenderRequest();
String numPages = (String) req.getPortletSession().getAttribute(NUM_PAGES);
numPages = (numPages != null) ? numPages : "10";
String[] itemList = {"10", "20", "50", "100"};
ListBoxBean usersPageLB = evt.getListBoxBean("usersPageLB");
usersPageLB.clear();
for (int i = 0; i < itemList.length; i++) {
ListBoxItemBean item = new ListBoxItemBean();
item.setName(itemList[i]);
item.setValue(itemList[i]);
if (numPages.equals(itemList[i])) item.setSelected(true);
usersPageLB.addBean(item);
}
String likeEmail = (String) req.getPortletSession().getAttribute(EMAIL_QUERY);
likeEmail = (likeEmail != null) ? likeEmail : "";
String likeOrganization = (String) req.getPortletSession().getAttribute(ORG_QUERY);
likeOrganization = (likeOrganization != null) ? likeOrganization : "";
Integer maxRows = Integer.parseInt(numPages);
int numUsers = userManagerService.getNumUsers();
QueryFilter filter = evt.getQueryFilter(maxRows, numUsers);
List userList = userManagerService.getUsersByFullName(likeEmail, likeOrganization, filter);
req.setAttribute("userList", userList);
int dispPages = (numUsers / Integer.valueOf(numPages).intValue());
//System.err.println("numUsers= " + numUsers + " numPages= " + numPages + " dispPages= " + dispPages);
req.setAttribute("dispPages", Integer.valueOf(dispPages));
//System.err.println("sizeof users=" + userList.size());
//req.setAttribute("numUsers", Integer.valueOf(numUsers));
//req.setAttribute("maxRows", Integer.valueOf(maxRows));
TableBean userTable = evt.getTableBean("userTable");
userTable.setQueryFilter(filter);
//userTable.setMaxRows(maxRows);
//userTable.setNumEntries(numUsers);
setNextState(req, DO_VIEW_USER_LIST);
}
public void doReturn(ActionFormEvent event) {
setNextState(event.getActionRequest(), "doListUsers");
}
public void doViewUser(ActionFormEvent evt)
throws PortletException {
PortletRequest req = evt.getActionRequest();
String userID = evt.getAction().getParameter("userID");
User user = userManagerService.getUser(userID);
if (user != null) {
// should check for non-null user !
req.setAttribute("user", user);
HiddenFieldBean hf = evt.getHiddenFieldBean("userID");
hf.setValue(user.getID());
List userRoles = roleManagerService.getRolesForUser(user);
Iterator it = userRoles.iterator();
String userRole = "";
while (it.hasNext()) {
userRole += ((PortletRole) it.next()).getName() + ", ";
}
if (userRole.length() > 2) {
req.setAttribute("role", userRole.substring(0, userRole.length() - 2));
} else {
req.setAttribute("role", this.getLocalizedText(req, "ROLES_HASNOROLES"));
}
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d yyyy hh:mm a");
String createtime = (String) user.getAttribute(User.CREATEDATE);
String createdate;
if (createtime == null) {
createdate = "Unknown";
} else {
createdate = dateFormat.format(Long.valueOf(createtime));
}
req.setAttribute("createdate", createdate);
CheckBoxBean accountCB = evt.getCheckBoxBean("accountCB");
String disabled = (String) user.getAttribute(User.DISABLED);
if ((disabled != null) && ("TRUE".equalsIgnoreCase(disabled))) {
accountCB.setSelected(true);
}
accountCB.setDisabled(true);
setNextState(req, DO_VIEW_USER_VIEW);
} else {
setNextState(req, DEFAULT_VIEW_PAGE);
}
}
public void doNewUser(ActionFormEvent evt)
throws PortletException {
PortletRequest req = evt.getActionRequest();
req.setAttribute("newuser", "true");
// indicate to edit JSP this is a new user
HiddenFieldBean hf = evt.getHiddenFieldBean("newuser");
hf.setValue("true");
String savePasswd = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS);
if (savePasswd.equals(Boolean.TRUE.toString())) {
req.setAttribute("savePass", "true");
}
makeRoleFrame(evt, null);
setNextState(req, DO_VIEW_USER_EDIT);
log.debug("in doNewUser");
}
/**
* Creates the role table
*
* @param evt the action form event
* @param user the user if this is editing an existing user, null if a new user
*/
private void makeRoleFrame(ActionFormEvent evt, User user) {
FrameBean roleFrame = evt.getFrameBean("roleFrame");
DefaultTableModel model = new DefaultTableModel();
TableRowBean tr = new TableRowBean();
tr.setHeader(true);
TableCellBean tc = new TableCellBean();
TextBean text = new TextBean();
text.setKey("USER_SELECT_ROLES");
tc.addBean(text);
tc.setWidth("100");
tr.addBean(tc);
tc = new TableCellBean();
text = new TextBean();
text.setKey("USER_ROLE_NAME");
tc.setWidth("200");
tc.addBean(text);
tr.addBean(tc);
model.addTableRowBean(tr);
List<PortletRole> roles = roleManagerService.getRoles();
List myroles = new ArrayList<PortletRole>();
List defaultRoles = roleManagerService.getDefaultRoles();
if (user != null) myroles = roleManagerService.getRolesForUser(user);
for (PortletRole role : roles) {
tr = new TableRowBean();
tc = new TableCellBean();
CheckBoxBean cb = new CheckBoxBean();
if (myroles.contains(role)) {
cb.setSelected(true);
}
if ((user == null) && (defaultRoles.contains(role))) cb.setSelected(true);
cb.setBeanId(role.getName() + "CB");
tc.addBean(cb);
tr.addBean(tc);
tc = new TableCellBean();
text = new TextBean();
text.setValue(role.getName());
tc.addBean(text);
tr.addBean(tc);
model.addTableRowBean(tr);
}
roleFrame.setTableModel(model);
}
public void doEditUser(ActionFormEvent evt)
throws PortletException {
PortletRequest req = evt.getActionRequest();
// indicate to edit JSP this is an existing user
HiddenFieldBean newuserHF = evt.getHiddenFieldBean("newuser");
newuserHF.setValue("false");
String userID = evt.getAction().getParameter("userID");
+ HiddenFieldBean userHF = evt.getHiddenFieldBean("userID");
+ userHF.setValue(userID);
// get user
User user = this.userManagerService.getUser(userID);
if (user == null) {
doReturn(evt);
return;
}
makeRoleFrame(evt, user);
setUserValues(evt, user);
String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS);
if (savePasswds.equals(Boolean.TRUE.toString())) {
req.setAttribute("savePass", "true");
}
String supportX509 = portalConfigService.getProperty(PortalConfigService.SUPPORT_X509_AUTH);
if (supportX509.equals(Boolean.TRUE.toString())) {
req.setAttribute("certSupport", "true");
}
CheckBoxBean accountCB = evt.getCheckBoxBean("accountCB");
String disabled = (String) user.getAttribute(User.DISABLED);
if ((disabled != null) && ("TRUE".equalsIgnoreCase(disabled))) {
accountCB.setSelected(true);
}
setNextState(req, DO_VIEW_USER_EDIT);
}
public void doConfirmEditUser(ActionFormEvent evt)
throws PortletException {
PortletRequest req = evt.getActionRequest();
HiddenFieldBean hf = evt.getHiddenFieldBean("newuser");
String newuser = hf.getValue();
try {
User user;
log.debug("in doConfirmEditUser: " + newuser);
if (newuser.equals("true")) {
validateUser(evt, true);
user = saveUser(evt, null);
HiddenFieldBean userHF = evt.getHiddenFieldBean("userID");
userHF.setValue(user.getID());
CheckBoxBean cb = evt.getCheckBoxBean("emailUserCB");
if (cb.isSelected()) mailUserConfirmation(evt, user);
createSuccessMessage(evt, this.getLocalizedText(req, "USER_NEW_SUCCESS"));
} else {
validateUser(evt, false);
// load in User values
HiddenFieldBean userHF = evt.getHiddenFieldBean("userID");
String userID = userHF.getValue();
User thisuser = this.userManagerService.getUser(userID);
user = saveUser(evt, thisuser);
createSuccessMessage(evt, this.getLocalizedText(req, "USER_EDIT_SUCCESS"));
}
req.setAttribute("user", user);
setNextState(req, "doListUsers");
} catch (PortletException e) {
createErrorMessage(evt, e.getMessage());
String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS);
if (savePasswds.equals(Boolean.TRUE.toString())) {
req.setAttribute("savePass", "true");
}
if (newuser.equals("true")) {
// setNextState(req, "doNewUser");
} else {
}
setNextState(req, DO_VIEW_USER_EDIT);
}
}
public void doDeleteUser(ActionFormEvent event)
throws PortletException {
ActionRequest req = event.getActionRequest();
String[] users = req.getParameterValues("usersCB");
if (users != null) {
for (int i = 0; i < users.length; i++) {
User user = this.userManagerService.getUser(users[i]);
this.passwordManagerService.deletePassword(user);
List<PortletRole> userRoles = this.roleManagerService.getRolesForUser(user);
for (PortletRole role : userRoles) {
this.roleManagerService.deleteUserInRole(user, role);
}
this.userManagerService.deleteUser(user);
}
}
createSuccessMessage(event, this.getLocalizedText(req, "USER_DELETE_SUCCESS"));
/*
HiddenFieldBean hf = evt.getHiddenFieldBean("userID");
String userId = hf.getValue();
User user = this.userManagerService.getUser(userId);
if (user != null) {
req.setAttribute("user", user);
this.passwordManagerService.deletePassword(user);
List<PortletRole> userRoles = this.roleManagerService.getRolesForUser(user);
for (PortletRole role : userRoles) {
this.roleManagerService.deleteUserInRole(user, role);
}
this.userManagerService.deleteUser(user);
createSuccessMessage(evt, this.getLocalizedText(req, "USER_DELETE_SUCCESS"));
}
setNextState(req, "doListUsers");
*/
}
public void doComposeEmail(ActionFormEvent event) {
ActionRequest req = event.getActionRequest();
String[] users = req.getParameterValues("usersCB");
if (users == null) return;
req.getPortletSession().setAttribute("emails", users);
setNextState(req, "doComposeEmail");
}
public void doComposeEmail(RenderFormEvent event) {
RenderRequest req = event.getRenderRequest();
String[] users = (String[]) req.getPortletSession().getAttribute("emails");
StringBuffer emails = new StringBuffer();
for (int i = 0; i < users.length; i++) {
User user = this.userManagerService.getUser(users[i]);
System.err.println(user.getEmailAddress());
emails.append(user.getEmailAddress()).append(", ");
}
String mailFrom = portalConfigService.getProperty(PortalConfigService.MAIL_FROM);
TextFieldBean senderTF = event.getTextFieldBean("senderTF");
senderTF.setValue(mailFrom);
TextFieldBean emailAddressTF = event.getTextFieldBean("emailAddressTF");
// chop off last , from emails CSV
emailAddressTF.setValue(emails.substring(0, emails.length() - 2));
req.getPortletSession().removeAttribute("emails");
setNextState(req, DO_SEND_EMAIL);
}
public void doSendEmail(ActionFormEvent event) {
ActionRequest req = event.getActionRequest();
MailMessage msg = new MailMessage();
msg.setEmailAddress(event.getTextFieldBean("emailAddressTF").getValue());
msg.setSender(event.getTextFieldBean("senderTF").getValue());
msg.setSubject(event.getTextFieldBean("subjectTF").getValue());
msg.setBody(event.getTextAreaBean("bodyTA").getValue());
RadioButtonBean toRB = event.getRadioButtonBean("toRB");
if (toRB.getValue().equals("TO")) {
msg.setRecipientType(MailMessage.TO);
} else {
msg.setRecipientType(MailMessage.BCC);
}
try {
mailService.sendMail(msg);
createErrorMessage(event, "Successfully sent message");
setNextState(req, "doListUsers");
} catch (PortletServiceException e) {
log.error("Unable to send mail message!", e);
createErrorMessage(event, getLocalizedText(req, "LOGIN_FAILURE_MAIL"));
setNextState(req, "doSendEmail");
}
}
private void setUserValues(ActionFormEvent event, User user) {
event.getTextFieldBean("userName").setValue(user.getUserName());
event.getTextFieldBean("lastName").setValue(user.getLastName());
event.getTextFieldBean("firstName").setValue(user.getFirstName());
//event.getTextFieldBean("fullName").setValue(user.getFullName());
event.getTextFieldBean("emailAddress").setValue(user.getEmailAddress());
event.getTextFieldBean("organization").setValue(user.getOrganization());
event.getPasswordBean("password").setValue("");
event.getTextFieldBean("certificate").setValue((String) user.getAttribute("user.certificate"));
}
private void validateUser(ActionFormEvent event, boolean newuser)
throws PortletException {
log.debug("Entering validateUser()");
PortletRequest req = event.getActionRequest();
StringBuffer message = new StringBuffer();
boolean isInvalid = false;
// Validate user name
String userName = event.getTextFieldBean("userName").getValue();
if (userName.equals("")) {
createErrorMessage(event, this.getLocalizedText(req, "USER_NAME_BLANK") + "<br />");
isInvalid = true;
} else if (newuser) {
if (this.userManagerService.existsUserName(userName)) {
createErrorMessage(event, this.getLocalizedText(req, "USER_EXISTS") + "<br />");
isInvalid = true;
}
}
// Validate first and last name
String firstName = event.getTextFieldBean("firstName").getValue();
if (firstName.equals("")) {
createErrorMessage(event, this.getLocalizedText(req, "USER_GIVENNAME_BLANK") + "<br />");
isInvalid = true;
}
String lastName = event.getTextFieldBean("lastName").getValue();
if (lastName.equals("")) {
createErrorMessage(event, this.getLocalizedText(req, "USER_FAMILYNAME_BLANK") + "<br />");
isInvalid = true;
}
// Validate e-mail
String eMail = event.getTextFieldBean("emailAddress").getValue();
if (eMail.equals("")) {
createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />");
isInvalid = true;
} else if ((eMail.indexOf("@") < 0)) {
createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />");
isInvalid = true;
} else if ((eMail.indexOf(".") < 0)) {
createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />");
isInvalid = true;
}
String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS);
if (savePasswds.equals(Boolean.TRUE.toString())) {
if (isInvalidPassword(event, newuser)) {
isInvalid = true;
}
}
// Throw exception if error was found
if (isInvalid) {
throw new PortletException(message.toString());
}
log.debug("Exiting validateUser()");
}
private boolean isInvalidPassword(ActionFormEvent event, boolean newuser) {
// Validate password
PortletRequest req = event.getActionRequest();
String passwordValue = event.getPasswordBean("password").getValue();
String confirmPasswordValue = event.getPasswordBean("confirmPassword").getValue();
// If user already exists and password unchanged, no problem
if (passwordValue.length() == 0 &&
confirmPasswordValue.length() == 0) {
if (newuser) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_BLANK") + "<br />");
return true;
}
return false;
}
// Otherwise, password must match confirmation
if (!passwordValue.equals(confirmPasswordValue)) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_MISMATCH") + "<br />");
return true;
// If they do match, then validate password with our service
} else {
if (passwordValue.length() == 0) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_BLANK"));
return true;
}
if (passwordValue.length() < 5) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_TOOSHORT"));
return true;
}
}
return false;
}
private User saveUser(ActionFormEvent event, User user) {
log.debug("Entering saveUser()");
// Account request
boolean newuserflag = false;
// Create edit account request
if (user == null) {
user = this.userManagerService.createUser();
long now = Calendar.getInstance().getTime().getTime();
user.setAttribute(User.CREATEDATE, String.valueOf(now));
newuserflag = true;
}
String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS);
if (savePasswds.equals(Boolean.TRUE.toString())) {
PasswordEditor editor = passwordManagerService.editPassword(user);
String password = event.getPasswordBean("password").getValue();
boolean isgood = this.isInvalidPassword(event, newuserflag);
if (isgood) {
setNextState(event.getActionRequest(), DO_VIEW_USER_EDIT);
return user;
} else {
if (!password.equals("")) {
editor.setValue(password);
passwordManagerService.savePassword(editor);
}
}
}
// Edit account attributes
editAccountRequest(event, user);
// Submit changes
this.userManagerService.saveUser(user);
// Save user role
saveUserRole(event, user);
log.debug("Exiting saveUser()");
return user;
}
private void editAccountRequest(ActionFormEvent event, User accountRequest) {
log.debug("Entering editAccountRequest()");
accountRequest.setUserName(event.getTextFieldBean("userName").getValue());
accountRequest.setFirstName(event.getTextFieldBean("firstName").getValue());
accountRequest.setLastName(event.getTextFieldBean("lastName").getValue());
accountRequest.setFullName(event.getTextFieldBean("lastName").getValue() + ", " + event.getTextFieldBean("firstName").getValue());
accountRequest.setEmailAddress(event.getTextFieldBean("emailAddress").getValue());
accountRequest.setOrganization(event.getTextFieldBean("organization").getValue());
if (event.getCheckBoxBean("accountCB").isSelected()) {
accountRequest.setAttribute(User.DISABLED, "true");
} else {
accountRequest.setAttribute(User.DISABLED, "false");
}
String certval = event.getTextFieldBean("certificate").getValue();
if (certval != null) accountRequest.setAttribute("user.certificate", certval);
}
private void saveUserRole(ActionFormEvent event, User user) {
log.debug("Entering saveUserRole()");
List<PortletRole> roles = roleManagerService.getRoles();
for (PortletRole role : roles) {
CheckBoxBean cb = event.getCheckBoxBean(role.getName() + "CB");
if (cb.isSelected()) {
roleManagerService.addUserToRole(user, role);
} else {
if (roleManagerService.isUserInRole(user, role))
if ((!role.equals(PortletRole.ADMIN)) || (roleManagerService.getUsersInRole(PortletRole.ADMIN).size() > 1)) {
roleManagerService.deleteUserInRole(user, role);
} else {
log.warn("Can't delete user, one user in role ADMIN necessary");
createErrorMessage(event, "Unable to delete user! One user with ADMIN role is necessary");
}
}
log.debug("Exiting saveUserRole()");
}
}
public void filterUserList(ActionFormEvent event) {
PortletRequest req = event.getActionRequest();
ListBoxBean usersPageLB = event.getListBoxBean("usersPageLB");
String numPages = usersPageLB.getSelectedValue();
try {
Integer.parseInt(numPages);
} catch (Exception e) {
numPages = "10";
}
TextFieldBean userEmailTF = event.getTextFieldBean("userEmailTF");
TextFieldBean userOrgTF = event.getTextFieldBean("userOrgTF");
req.getPortletSession().setAttribute(NUM_PAGES, numPages);
req.getPortletSession().setAttribute(EMAIL_QUERY, userEmailTF.getValue());
req.getPortletSession().setAttribute(ORG_QUERY, userOrgTF.getValue());
}
private void mailUserConfirmation(ActionFormEvent evt, User user) {
PortletRequest req = evt.getActionRequest();
MailMessage mailToUser = new MailMessage();
String body = portalConfigService.getProperty("LOGIN_APPROVED_BODY");
if (body == null) body = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED");
StringBuffer message = new StringBuffer(body);
String subject = portalConfigService.getProperty("LOGIN_APPROVED_SUBJECT");
if (subject == null) subject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED");
mailToUser.setSubject(subject);
message.append("\n\n");
message.append(getLocalizedText(req, "USERNAME")).append("\t");
message.append(user.getUserName()).append("\n");
message.append(getLocalizedText(req, "GIVENNAME")).append("\t");
message.append(user.getFirstName()).append("\n");
message.append(getLocalizedText(req, "FAMILYNAME")).append("\t");
message.append(user.getLastName()).append("\n");
message.append(getLocalizedText(req, "ORGANIZATION")).append("\t");
message.append(user.getOrganization()).append("\n");
message.append(getLocalizedText(req, "EMAILADDRESS")).append("\t");
message.append(user.getEmailAddress()).append("\n");
message.append("\n");
message.append(getLocalizedText(req, "USER_PASSWD_MSG"));
message.append("\t").append(evt.getPasswordBean("password").getValue());
mailToUser.setBody(message.toString());
mailToUser.setEmailAddress(user.getEmailAddress());
mailToUser.setSender(portalConfigService.getProperty(PortalConfigService.MAIL_FROM));
try {
mailService.sendMail(mailToUser);
} catch (PortletServiceException e) {
log.error("Unable to send mail message!", e);
createErrorMessage(evt, getLocalizedText(req, "LOGIN_FAILURE_MAIL"));
}
}
}
| true | false | null | null |
diff --git a/components/bio-formats/src/loci/formats/tools/ImageConverter.java b/components/bio-formats/src/loci/formats/tools/ImageConverter.java
index 7fdf2104e..c03e5e17f 100644
--- a/components/bio-formats/src/loci/formats/tools/ImageConverter.java
+++ b/components/bio-formats/src/loci/formats/tools/ImageConverter.java
@@ -1,324 +1,319 @@
//
// ImageConverter.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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.formats.tools;
import java.awt.image.IndexColorModel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import loci.common.DebugTools;
import loci.common.Location;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.ChannelFiller;
import loci.formats.ChannelMerger;
import loci.formats.ChannelSeparator;
+import loci.formats.FilePattern;
import loci.formats.FileStitcher;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.IFormatReader;
import loci.formats.IFormatWriter;
import loci.formats.ImageReader;
import loci.formats.ImageWriter;
import loci.formats.MetadataTools;
import loci.formats.MissingLibraryException;
import loci.formats.ReaderWrapper;
import loci.formats.in.OMETiffReader;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.out.TiffWriter;
import loci.formats.services.OMEXMLService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ImageConverter is a utility class for converting a file between formats.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/tools/ImageConverter.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/tools/ImageConverter.java">SVN</a></dd></dl>
*/
public final class ImageConverter {
// -- Constants --
private static final Logger LOGGER =
LoggerFactory.getLogger(ImageConverter.class);
// -- Constructor --
private ImageConverter() { }
// -- Utility methods --
/** A utility method for converting a file from the command line. */
public static boolean testConvert(IFormatWriter writer, String[] args)
throws FormatException, IOException
{
DebugTools.enableLogging("INFO");
String in = null, out = null;
String map = null;
String compression = null;
boolean stitch = false, separate = false, merge = false, fill = false;
boolean bigtiff = false;
int series = -1;
if (args != null) {
for (int i=0; i<args.length; i++) {
if (args[i].startsWith("-") && args.length > 1) {
if (args[i].equals("-debug")) {
DebugTools.enableLogging("DEBUG");
}
else if (args[i].equals("-stitch")) stitch = true;
else if (args[i].equals("-separate")) separate = true;
else if (args[i].equals("-merge")) merge = true;
else if (args[i].equals("-expand")) fill = true;
else if (args[i].equals("-bigtiff")) bigtiff = true;
else if (args[i].equals("-map")) map = args[++i];
else if (args[i].equals("-compression")) compression = args[++i];
else if (args[i].equals("-series")) {
try {
series = Integer.parseInt(args[++i]);
}
catch (NumberFormatException exc) { }
}
else {
LOGGER.error("Found unknown command flag: {}; exiting.", args[i]);
return false;
}
}
else {
if (in == null) in = args[i];
else if (out == null) out = args[i];
else {
LOGGER.error("Found unknown argument: {}; exiting.", args[i]);
LOGGER.error("You should specify exactly one input file and " +
"exactly one output file.");
return false;
}
}
}
}
if (in == null || out == null) {
String[] s = {
"To convert a file between formats, run:",
" bfconvert [-debug] [-stitch] [-separate] [-merge] [-expand]",
" [-bigtiff] [-compression codec] [-series series] [-map id]",
" in_file out_file",
"",
" -debug: turn on debugging output",
" -stitch: stitch input files with similar names",
" -separate: split RGB images into separate channels",
" -merge: combine separate channels into RGB image",
" -expand: expand indexed color to RGB",
" -bigtiff: force BigTIFF files to be written",
"-compression: specify the codec to use when saving images",
" -series: specify which image series to convert",
" -map: specify file on disk to which name should be mapped",
"",
"If any of the following patterns are present in out_file, they will",
"be replaced with the indicated metadata value from the input file.",
"",
" Pattern:\tMetadata value:",
" ---------------------------",
" " + FormatTools.SERIES_NUM + "\t\tseries index",
" " + FormatTools.SERIES_NAME + "\t\tseries name",
" " + FormatTools.CHANNEL_NUM + "\t\tchannel index",
" " + FormatTools.CHANNEL_NAME +"\t\tchannel name",
" " + FormatTools.Z_NUM + "\t\tZ index",
" " + FormatTools.T_NUM + "\t\tT index",
"",
"If any of these patterns are present, then the images to be saved",
"will be split into multiple files. For example, if the input file",
"contains 5 Z sections and 3 timepoints, and out_file is",
"",
" converted_Z" + FormatTools.Z_NUM + "_T" +
FormatTools.T_NUM + ".tiff",
"",
"then 15 files will be created, with the names",
"",
" converted_Z0_T0.tiff",
" converted_Z0_T1.tiff",
" converted_Z0_T2.tiff",
" converted_Z1_T0.tiff",
" ...",
" converted_Z4_T2.tiff",
"",
"Each file would have a single image plane."
};
for (int i=0; i<s.length; i++) LOGGER.info(s[i]);
return false;
}
if (new Location(out).exists()) {
LOGGER.warn("Output file {} exists.", out);
LOGGER.warn("Do you want to overwrite it? ([y]/n)");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String choice = r.readLine().trim().toLowerCase();
boolean overwrite = !choice.startsWith("n");
if (!overwrite) {
LOGGER.warn("Exiting; next time, please specify an output file that " +
"does not exist.");
return false;
}
else {
new Location(out).delete();
}
}
if (map != null) Location.mapId(in, map);
long start = System.currentTimeMillis();
LOGGER.info(in);
IFormatReader reader = new ImageReader();
- if (stitch) reader = new FileStitcher(reader);
+ if (stitch) {
+ reader = new FileStitcher(reader);
+ String pat = FilePattern.findPattern(new Location(in));
+ if (pat != null) in = pat;
+ }
if (separate) reader = new ChannelSeparator(reader);
if (merge) reader = new ChannelMerger(reader);
if (fill) reader = new ChannelFiller(reader);
reader.setMetadataFiltered(true);
reader.setOriginalMetadataPopulated(true);
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
reader.setMetadataStore(service.createOMEXMLMetadata());
}
catch (DependencyException de) {
throw new MissingLibraryException(OMETiffReader.NO_OME_XML_MSG, de);
}
catch (ServiceException se) {
throw new FormatException(se);
}
reader.setId(in);
MetadataStore store = reader.getMetadataStore();
- IFormatReader base = reader;
- if (base instanceof ReaderWrapper) {
- base = ((ReaderWrapper) base).unwrap();
- }
- if (base instanceof FileStitcher) {
- base = ((FileStitcher) base).getReader();
- }
- if (base instanceof ImageReader) {
- base = ((ImageReader) base).getReader();
- }
MetadataTools.populatePixels(store, reader, false, false);
if (store instanceof MetadataRetrieve) {
writer.setMetadataRetrieve((MetadataRetrieve) store);
}
if (writer instanceof TiffWriter) {
((TiffWriter) writer).setBigTiff(bigtiff);
((TiffWriter) writer).setWriteSequentially(true);
}
else if (writer instanceof ImageWriter) {
IFormatWriter w = ((ImageWriter) writer).getWriter(out);
if (w instanceof TiffWriter) {
((TiffWriter) w).setBigTiff(bigtiff);
((TiffWriter) w).setWriteSequentially(true);
}
}
String format = writer.getFormat();
LOGGER.info("[{}] -> {} [{}]",
new Object[] {reader.getFormat(), out, format});
long mid = System.currentTimeMillis();
int total = 0;
int num = writer.canDoStacks() ? reader.getSeriesCount() : 1;
long read = 0, write = 0;
int first = series == -1 ? 0 : series;
int last = series == -1 ? num : series + 1;
long timeLastLogged = System.currentTimeMillis();
for (int q=first; q<last; q++) {
reader.setSeries(q);
writer.setSeries(q);
writer.setInterleaved(reader.isInterleaved());
int numImages = writer.canDoStacks() ? reader.getImageCount() : 1;
total += numImages;
for (int i=0; i<numImages; i++) {
writer.setId(FormatTools.getFilename(q, i, reader, out));
if (compression != null) writer.setCompression(compression);
long s = System.currentTimeMillis();
byte[] buf = reader.openBytes(i);
byte[][] lut = reader.get8BitLookupTable();
if (lut != null) {
IndexColorModel model = new IndexColorModel(8, lut[0].length,
lut[0], lut[1], lut[2]);
writer.setColorModel(model);
}
long m = System.currentTimeMillis();
writer.saveBytes(i, buf);
long e = System.currentTimeMillis();
read += m - s;
write += e - m;
// log number of planes processed every second or so
if (i == numImages - 1 || (e - timeLastLogged) / 1000 > 0) {
int current = i + 1;
int percent = 100 * current / numImages;
StringBuilder sb = new StringBuilder();
sb.append("\t");
int numSeries = last - first;
if (numSeries > 1) {
sb.append("Series ");
sb.append(q);
sb.append(": converted ");
}
else sb.append("Converted ");
LOGGER.info(sb.toString() + "{}/{} planes ({}%)",
new Object[] {current, numImages, percent});
timeLastLogged = e;
}
}
}
writer.close();
long end = System.currentTimeMillis();
LOGGER.info("[done]");
// output timing results
float sec = (end - start) / 1000f;
long initial = mid - start;
float readAvg = (float) read / total;
float writeAvg = (float) write / total;
LOGGER.info("{}s elapsed ({}+{}ms per plane, {}ms overhead)",
new Object[] {sec, readAvg, writeAvg, initial});
return true;
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
if (!testConvert(new ImageWriter(), args)) System.exit(1);
System.exit(0);
}
}
| false | false | null | null |
diff --git a/modules/foundation/sasxremwin/src/classes/org/jdesktop/wonderland/modules/sasxremwin/provider/SasXrwProviderMain.java b/modules/foundation/sasxremwin/src/classes/org/jdesktop/wonderland/modules/sasxremwin/provider/SasXrwProviderMain.java
index 26a360790..1d55a27da 100644
--- a/modules/foundation/sasxremwin/src/classes/org/jdesktop/wonderland/modules/sasxremwin/provider/SasXrwProviderMain.java
+++ b/modules/foundation/sasxremwin/src/classes/org/jdesktop/wonderland/modules/sasxremwin/provider/SasXrwProviderMain.java
@@ -1,288 +1,298 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.sasxremwin.provider;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.jdesktop.wonderland.common.ExperimentalAPI;
import org.jdesktop.wonderland.modules.appbase.client.ProcessReporterFactory;
import org.jdesktop.wonderland.modules.sas.provider.SasProvider;
import org.jdesktop.wonderland.modules.sas.provider.SasProviderConnection;
import org.jdesktop.wonderland.modules.sas.provider.SasProviderConnectionListener;
import org.jdesktop.wonderland.modules.sas.provider.SasProviderSession;
import org.jdesktop.wonderland.modules.xremwin.client.AppXrwMaster;
import org.jdesktop.wonderland.common.messages.MessageID;
import java.util.logging.Logger;
import java.util.HashMap;
import java.util.logging.Level;
import org.jdesktop.wonderland.common.cell.CellID;
+import org.jdesktop.wonderland.common.login.CredentialManager;
/**
* The main logic for the SAS Xremwin provider client.
*
* @author deronj
*/
@ExperimentalAPI
public class SasXrwProviderMain
implements SasProviderConnectionListener, AppXrwMaster.ExitListener {
static final Logger logger = Logger.getLogger(SasXrwProviderMain.class.getName());
/** The property for enabling user-specified app commands */
private static final String ENABLE_USER_COMMANDS_PROP =
SasXrwProviderMain.class.getSimpleName() + ".enable.user.commands";
/** The URL to map app names to user commands */
private static final String COMMAND_URL_PROP =
SasXrwProviderMain.class.getSimpleName() + ".command.url";
/** The default URL for user commands */
private static final String COMMAND_URL_DEFAULT =
"/xapps-config/wonderland-xapps-config/browse?action=check&app=";
/** The property to set with the username */
private static final String USERNAME_PROP = "sas.user";
/** The default username */
private static final String USERNAME_DEFAULT = "sasxprovider";
/** The property to set with the password file location */
private static final String PASSWORD_FILE_PROP = "sas.password.file";
/** The URL of the Wonderland server */
private final String serverUrl;
/** Whether user commands are allowed */
private final boolean userCommands;
/** The command URL to query */
private final String commandURL;
/** The session associated with this provider. */
private SasProviderSession session;
/** An entry which holds information needed to notify the SasServer of app exit. */
private class AppInfo {
private SasProviderConnection connection;
private MessageID launchMessageID;
private AppInfo (SasProviderConnection connection, MessageID launchMessageID) {
this.connection = connection;
this.launchMessageID = launchMessageID;
}
}
/** Information about the apps which are running in this provider. */
private final HashMap<AppXrwMaster,AppInfo> runningAppInfos = new HashMap<AppXrwMaster,AppInfo>();
/** The xremwin-specific provider object. */
private static SasXrwProvider provider;
// Register the sas provider shutdown hook
static {
Runtime.getRuntime().addShutdownHook(new Thread("SasXrw Shutdown Hook") {
@Override
public void run() {
if (provider != null) {
provider.cleanup();
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SasXrwProviderMain providerMain = new SasXrwProviderMain();
}
private SasXrwProviderMain () {
checkPlatform();
// parse username from the system property
String username = System.getProperty(USERNAME_PROP, USERNAME_DEFAULT);
// parse the password file from the system property. This may be
// null if no password file is specified (for insecure deployments)
String passwordFileName = System.getProperty(PASSWORD_FILE_PROP);
File passwordFile = null;
if (passwordFileName != null && passwordFileName.trim().length() > 0) {
passwordFile = new File(passwordFileName);
}
// read the server URL property
serverUrl = System.getProperty("wonderland.web.server.url", "http://localhost:8080");
logger.warning("Connecting to server " + serverUrl);
// Read the userCommands property. The default is false unless the
// property is specified and is equal to "true"
userCommands = Boolean.parseBoolean(System.getProperty(ENABLE_USER_COMMANDS_PROP));
// Read the commandURL property
commandURL = System.getProperty(COMMAND_URL_PROP, COMMAND_URL_DEFAULT);
try {
provider = new SasXrwProvider(username, passwordFile, serverUrl, this, this);
} catch (Exception ex) {
logger.severe("Exception " + ex);
logger.severe("Cannot connect to server " + serverUrl);
System.exit(1);
}
}
/**
* SAS can only run on a Unix platform. Exit if this is not the case.
*/
private void checkPlatform() {
String osName = System.getProperty("os.name");
if (!"Linux".equals(osName) &&
!"SunOS".equals(osName)) {
logger.severe("SasXrwProviderMain cannot run on platform " + osName);
logger.severe("Program terminated.");
System.exit(1);
}
}
/**
* {@inheritDoc}
*/
public void setSession (SasProviderSession session) {
this.session = session;
}
/**
* {@inheritDoc}
*/
public String launch (String appName, String command, SasProviderConnection connection,
MessageID launchMessageID, CellID cellID) {
AppXrwMaster app = null;
// resolve the command based on the app name. A command value of null
// indicates that the given appName could not be resolved
command = resolveCommand(appName, command);
if (command == null) {
return null;
}
logger.warning("Resolved command = " + command);
try {
app = new AppXrwMaster(appName, command, cellID, null,
ProcessReporterFactory.getFactory().create(appName), session, true);
} catch (InstantiationException ex) {
return null;
}
app.setExitListener(this);
synchronized (runningAppInfos) {
runningAppInfos.put(app, new AppInfo(connection, launchMessageID));
}
// Now it is time to enable the master client loop
app.getClient().enable();
return app.getConnectionInfo().toString();
}
/**
* Called when an app exits.
*/
public void appExitted (AppXrwMaster app) {
logger.warning("App Exitted: " + app.getName());
synchronized (runningAppInfos) {
AppInfo appInfo = runningAppInfos.get(app);
if (appInfo != null) {
runningAppInfos.remove(app);
appInfo.connection.appExitted(appInfo.launchMessageID, app.getExitValue());
}
}
}
/**
* {@inheritDoc}
*/
public void appStop (SasProviderConnection connection, MessageID launchMessageID) {
synchronized (runningAppInfos) {
for (AppXrwMaster app : runningAppInfos.keySet()) {
AppInfo appInfo = runningAppInfos.get(app);
if (appInfo.connection == connection && appInfo.launchMessageID == launchMessageID) {
runningAppInfos.remove(app);
app.cleanup();
}
}
}
}
/**
* Resolve an app name into a command using a web service.
* @param appName the app name to resolve
* @param command the command the user specified (may be null)
* @return the command to execute for the given app, or null
* to return an error
*/
protected String resolveCommand(String appName, String command) {
// if the user specified a command, check if that command is
// allowed
if (command != null) {
if (userCommands) {
return command;
} else {
logger.warning("User-specified command " + command + " for " +
appName + " when user commands are disabled. " +
"Set " + ENABLE_USER_COMMANDS_PROP + " to " +
"enable user commands.");
return null;
}
}
// if we get here, it means the user did not specify a command. In
// that case, use the web service to try to find the command
try {
// construct the service request URL by adding the server
// URL, the command URL and the app name (URL encoded) together.
URL url = new URL(new URL(serverUrl), commandURL +
URLEncoder.encode(appName, "UTF-8"));
URLConnection uc = url.openConnection();
// if this was an HTTP URL connection, check the return value
if (uc instanceof HttpURLConnection) {
HttpURLConnection huc = (HttpURLConnection) uc;
+
+ // don't redirect to the login page if there is a login failure
+ huc.setRequestProperty("Redirect", "false");
+
+ // secure the connection with the credentials for our session
+ // (we can only do this for an http connection)
+ CredentialManager cm = session.getSessionManager().getCredentialManager();
+ cm.secureURLConnection(huc);
+
if (huc.getResponseCode() != HttpURLConnection.HTTP_OK) {
logger.warning("Connection to " + url + " returns " +
huc.getResponseCode() + " : " +
huc.getResponseMessage());
return null;
}
}
// read the command name from the web service
BufferedReader br = new BufferedReader(
new InputStreamReader(uc.getInputStream()));
return br.readLine();
} catch (IOException ioe) {
logger.log(Level.WARNING, "Error resolving command for " + appName,
ioe);
return null;
}
}
}
| false | false | null | null |
diff --git a/src/com/android/launcher2/Launcher.java b/src/com/android/launcher2/Launcher.java
index ee540f82..b3ce9688 100644
--- a/src/com/android/launcher2/Launcher.java
+++ b/src/com/android/launcher2/Launcher.java
@@ -1,3603 +1,3607 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.BounceInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Advanceable;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.common.Search;
import com.android.launcher.R;
import com.android.launcher2.DropTarget.DragObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Default launcher application.
*/
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
AllAppsView.Watcher, View.OnTouchListener {
static final String TAG = "Launcher";
static final boolean LOGD = false;
static final boolean PROFILE_STARTUP = false;
static final boolean DEBUG_WIDGETS = false;
private static final int MENU_GROUP_WALLPAPER = 1;
private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
private static final int REQUEST_CREATE_SHORTCUT = 1;
private static final int REQUEST_CREATE_APPWIDGET = 5;
private static final int REQUEST_PICK_APPLICATION = 6;
private static final int REQUEST_PICK_SHORTCUT = 7;
private static final int REQUEST_PICK_APPWIDGET = 9;
private static final int REQUEST_PICK_WALLPAPER = 10;
static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
static final int SCREEN_COUNT = 5;
static final int DEFAULT_SCREEN = 2;
static final int DIALOG_CREATE_SHORTCUT = 1;
static final int DIALOG_RENAME_FOLDER = 2;
private static final String PREFERENCES = "launcher.preferences";
static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher.force_enable_rotation";
// Type: int
private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
// Type: int
private static final String RUNTIME_STATE = "launcher.state";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
// Type: boolean
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
// Type: long
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
/** The different states that Launcher can be in. */
private enum State { WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
private State mState = State.WORKSPACE;
private AnimatorSet mStateAnimation;
private AnimatorSet mDividerAnimator;
static final int APPWIDGET_HOST_ID = 1024;
private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
private static final int SHOW_CLING_DURATION = 550;
private static final int DISMISS_CLING_DURATION = 250;
private static final Object sLock = new Object();
private static int sScreen = DEFAULT_SCREEN;
private final BroadcastReceiver mCloseSystemDialogsReceiver
= new CloseSystemDialogsIntentReceiver();
private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
private LayoutInflater mInflater;
private Workspace mWorkspace;
private View mQsbDivider;
private View mDockDivider;
private DragLayer mDragLayer;
private DragController mDragController;
private AppWidgetManager mAppWidgetManager;
private LauncherAppWidgetHost mAppWidgetHost;
private ItemInfo mPendingAddInfo = new ItemInfo();
private int[] mTmpAddItemCellCoordinates = new int[2];
private FolderInfo mFolderInfo;
private Hotseat mHotseat;
private View mAllAppsButton;
private SearchDropTargetBar mSearchDropTargetBar;
private AppsCustomizeTabHost mAppsCustomizeTabHost;
private AppsCustomizePagedView mAppsCustomizeContent;
private boolean mAutoAdvanceRunning = false;
private Bundle mSavedState;
private SpannableStringBuilder mDefaultKeySsb = null;
private boolean mWorkspaceLoading = true;
private boolean mPaused = true;
private boolean mRestoring;
private boolean mWaitingForResult;
private boolean mOnResumeNeedsLoad;
private Bundle mSavedInstanceState;
private LauncherModel mModel;
private IconCache mIconCache;
private boolean mUserPresent = true;
private boolean mVisible = false;
private boolean mAttached = false;
private static LocaleConfiguration sLocaleConfiguration = null;
private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
private Intent mAppMarketIntent = null;
// Related to the auto-advancing of widgets
private final int ADVANCE_MSG = 1;
private final int mAdvanceInterval = 20000;
private final int mAdvanceStagger = 250;
private long mAutoAdvanceSentTime;
private long mAutoAdvanceTimeLeft = -1;
private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
new HashMap<View, AppWidgetProviderInfo>();
// Determines how long to wait after a rotation before restoring the screen orientation to
// match the sensor state.
private final int mRestoreScreenOrientationDelay = 500;
// External icons saved in case of resource changes, orientation, etc.
private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
static final ArrayList<String> sDumpLogs = new ArrayList<String>();
PendingAddWidgetInfo mWidgetBeingConfigured = null;
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
private SharedPreferences mSharedPrefs;
// Holds the page that we need to animate to, and the icon views that we need to animate up
// when we scroll to that page on resume.
private int mNewShortcutAnimatePage = -1;
private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>();
private BubbleTextView mWaitingForResume;
private Runnable mBuildLayersRunnable = new Runnable() {
public void run() {
if (mWorkspace != null) {
mWorkspace.buildPageHardwareLayers();
}
}
};
private static ArrayList<PendingAddArguments> sPendingAddList
= new ArrayList<PendingAddArguments>();
private static class PendingAddArguments {
int requestCode;
Intent intent;
long container;
int screen;
int cellX;
int cellY;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LauncherApplication app = ((LauncherApplication)getApplication());
mSharedPrefs = getSharedPreferences(LauncherApplication.getSharedPreferencesKey(),
Context.MODE_PRIVATE);
mModel = app.setLauncher(this);
mIconCache = app.getIconCache();
mDragController = new DragController(this);
mInflater = getLayoutInflater();
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
mAppWidgetHost.startListening();
if (PROFILE_STARTUP) {
android.os.Debug.startMethodTracing(
Environment.getExternalStorageDirectory() + "/launcher");
}
checkForLocaleChange();
setContentView(R.layout.launcher);
setupViews();
showFirstRunWorkspaceCling();
registerContentObservers();
lockAllApps();
mSavedState = savedInstanceState;
restoreState(mSavedState);
// Update customization drawer _after_ restoring the states
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated();
}
if (PROFILE_STARTUP) {
android.os.Debug.stopMethodTracing();
}
if (!mRestoring) {
mModel.startLoader(true);
}
if (!mModel.isAllAppsLoaded()) {
ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent();
mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent);
}
// For handling default keys
mDefaultKeySsb = new SpannableStringBuilder();
Selection.setSelection(mDefaultKeySsb, 0);
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mCloseSystemDialogsReceiver, filter);
boolean searchVisible = false;
boolean voiceVisible = false;
// If we have a saved version of these external icons, we load them up immediately
int coi = getCurrentOrientationIndexForGlobalIcons();
if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
sAppMarketIcon[coi] == null) {
updateAppMarketIcon();
searchVisible = updateGlobalSearchIcon();
voiceVisible = updateVoiceSearchIcon(searchVisible);
}
if (sGlobalSearchIcon[coi] != null) {
updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
searchVisible = true;
}
if (sVoiceSearchIcon[coi] != null) {
updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
voiceVisible = true;
}
if (sAppMarketIcon[coi] != null) {
updateAppMarketIcon(sAppMarketIcon[coi]);
}
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
final String forceEnableRotation =
SystemProperties.get(FORCE_ENABLE_ROTATION_PROPERTY, "false");
// On large interfaces, we want the screen to auto-rotate based on the current orientation
if (LauncherApplication.isScreenLarge() || "true".equalsIgnoreCase(forceEnableRotation)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
private void checkForLocaleChange() {
if (sLocaleConfiguration == null) {
new AsyncTask<Void, Void, LocaleConfiguration>() {
@Override
protected LocaleConfiguration doInBackground(Void... unused) {
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
}
@Override
protected void onPostExecute(LocaleConfiguration result) {
sLocaleConfiguration = result;
checkForLocaleChange(); // recursive, but now with a locale configuration
}
}.execute();
return;
}
final Configuration configuration = getResources().getConfiguration();
final String previousLocale = sLocaleConfiguration.locale;
final String locale = configuration.locale.toString();
final int previousMcc = sLocaleConfiguration.mcc;
final int mcc = configuration.mcc;
final int previousMnc = sLocaleConfiguration.mnc;
final int mnc = configuration.mnc;
boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
if (localeChanged) {
sLocaleConfiguration.locale = locale;
sLocaleConfiguration.mcc = mcc;
sLocaleConfiguration.mnc = mnc;
mIconCache.flush();
final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
new Thread("WriteLocaleConfiguration") {
@Override
public void run() {
writeConfiguration(Launcher.this, localeConfiguration);
}
}.start();
}
}
private static class LocaleConfiguration {
public String locale;
public int mcc = -1;
public int mnc = -1;
}
private static void readConfiguration(Context context, LocaleConfiguration configuration) {
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
DataOutputStream out = null;
try {
out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
out.writeUTF(configuration.locale);
out.writeInt(configuration.mcc);
out.writeInt(configuration.mnc);
out.flush();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
//noinspection ResultOfMethodCallIgnored
context.getFileStreamPath(PREFERENCES).delete();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public DragLayer getDragLayer() {
return mDragLayer;
}
static int getScreen() {
synchronized (sLock) {
return sScreen;
}
}
static void setScreen(int screen) {
synchronized (sLock) {
sScreen = screen;
}
}
/**
* Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
* a configuration step, this allows the proper animations to run after other transitions.
*/
private boolean completeAdd(PendingAddArguments args) {
boolean result = false;
switch (args.requestCode) {
case REQUEST_PICK_APPLICATION:
completeAddApplication(args.intent, args.container, args.screen, args.cellX,
args.cellY);
break;
case REQUEST_PICK_SHORTCUT:
processShortcut(args.intent);
break;
case REQUEST_CREATE_SHORTCUT:
completeAddShortcut(args.intent, args.container, args.screen, args.cellX,
args.cellY);
result = true;
break;
case REQUEST_PICK_APPWIDGET:
addAppWidgetFromPick(args.intent);
break;
case REQUEST_CREATE_APPWIDGET:
int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
completeAddAppWidget(appWidgetId, args.container, args.screen, null, null);
result = true;
break;
case REQUEST_PICK_WALLPAPER:
// We just wanted the activity result here so we can clear mWaitingForResult
break;
}
+ // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
+ // if you turned the screen off and then back while in All Apps, Launcher would not
+ // return to the workspace. Clearing mAddInfo.container here fixes this issue
+ resetAddInfo();
return result;
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
boolean delayExitSpringLoadedMode = false;
boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
requestCode == REQUEST_CREATE_APPWIDGET);
mWaitingForResult = false;
// We have special handling for widgets
if (isWidgetDrop) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
completeTwoStageWidgetDrop(resultCode, appWidgetId);
return;
}
// The pattern used here is that a user PICKs a specific application,
// which, depending on the target, might need to CREATE the actual target.
// For example, the user would PICK_SHORTCUT for "Music playlist", and we
// launch over to the Music app to actually CREATE_SHORTCUT.
if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
final PendingAddArguments args = new PendingAddArguments();
args.requestCode = requestCode;
args.intent = data;
args.container = mPendingAddInfo.container;
args.screen = mPendingAddInfo.screen;
args.cellX = mPendingAddInfo.cellX;
args.cellY = mPendingAddInfo.cellY;
if (isWorkspaceLocked()) {
sPendingAddList.add(args);
} else {
delayExitSpringLoadedMode = completeAdd(args);
}
}
mDragLayer.clearAnimatedView();
// Exit spring loaded mode if necessary after cancelling the configuration of a widget
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
null);
}
private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
CellLayout cellLayout = (CellLayout) mWorkspace.getChildAt(mWidgetBeingConfigured.screen);
Runnable onCompleteRunnable = null;
int animationType = 0;
if (resultCode == RESULT_OK) {
animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
mWidgetBeingConfigured.info);
mWidgetBeingConfigured.boundWidget = layout;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
mPendingAddInfo.screen, layout, null);
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
} else if (resultCode == RESULT_CANCELED) {
animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
}
mWorkspace.animateWidgetDrop(mWidgetBeingConfigured, cellLayout,
(DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
animationType, mWidgetBeingConfigured.boundWidget, true);
mWidgetBeingConfigured = null;
}
@Override
protected void onResume() {
super.onResume();
mPaused = false;
if (mRestoring || mOnResumeNeedsLoad) {
mWorkspaceLoading = true;
mModel.startLoader(true);
mRestoring = false;
mOnResumeNeedsLoad = false;
}
// Reset the pressed state of icons that were locked in the press state while activities
// were launching
if (mWaitingForResume != null) {
// Resets the previous workspace icon press state
mWaitingForResume.setStayPressed(false);
}
if (mAppsCustomizeContent != null) {
// Resets the previous all apps icon press state
mAppsCustomizeContent.resetDrawableState();
}
}
@Override
protected void onPause() {
super.onPause();
mPaused = true;
mDragController.cancelDrag();
}
@Override
public Object onRetainNonConfigurationInstance() {
// Flag the loader to stop early before switching
mModel.stopLoader();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.surrender();
}
return Boolean.TRUE;
}
// We can't hide the IME if it was forced open. So don't bother
/*
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
WindowManager.LayoutParams lp = getWindow().getAttributes();
inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
android.os.Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
}
});
Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
}
}
*/
private boolean acceptFilter() {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
return !inputManager.isFullscreenMode();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final int uniChar = event.getUnicodeChar();
final boolean handled = super.onKeyDown(keyCode, event);
final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
if (!handled && acceptFilter() && isKeyNotWhitespace) {
boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
keyCode, event);
if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
// something usable has been typed - start a search
// the typed text will be retrieved and cleared by
// showSearchDialog()
// If there are multiple keystrokes before the search dialog takes focus,
// onSearchRequested() will be called for every keystroke,
// but it is idempotent, so it's fine.
return onSearchRequested();
}
}
// Eat the long press event so the keyboard doesn't come up.
if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
return true;
}
return handled;
}
private String getTypedText() {
return mDefaultKeySsb.toString();
}
private void clearTypedText() {
mDefaultKeySsb.clear();
mDefaultKeySsb.clearSpans();
Selection.setSelection(mDefaultKeySsb, 0);
}
/**
* Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
* State
*/
private static State intToState(int stateOrdinal) {
State state = State.WORKSPACE;
final State[] stateValues = State.values();
for (int i = 0; i < stateValues.length; i++) {
if (stateValues[i].ordinal() == stateOrdinal) {
state = stateValues[i];
break;
}
}
return state;
}
/**
* Restores the previous state, if it exists.
*
* @param savedState The previous state.
*/
private void restoreState(Bundle savedState) {
if (savedState == null) {
return;
}
State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
if (state == State.APPS_CUSTOMIZE) {
showAllApps(false);
}
int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
if (currentScreen > -1) {
mWorkspace.setCurrentPage(currentScreen);
}
final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
mPendingAddInfo.container = pendingAddContainer;
mPendingAddInfo.screen = pendingAddScreen;
mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
mRestoring = true;
}
boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
if (renameFolder) {
long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
mFolderInfo = mModel.getFolderById(this, sFolders, id);
mRestoring = true;
}
// Restore the AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String curTab = savedState.getString("apps_customize_currentTab");
if (curTab != null) {
// We set this directly so that there is no delay before the tab is set
mAppsCustomizeContent.setContentType(
mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
mAppsCustomizeTabHost.setCurrentTabByTag(curTab);
mAppsCustomizeContent.loadAssociatedPages(
mAppsCustomizeContent.getCurrentPage());
}
int currentIndex = savedState.getInt("apps_customize_currentIndex");
mAppsCustomizeContent.restorePageForIndex(currentIndex);
}
}
/**
* Finds all the views we need and configure them properly.
*/
private void setupViews() {
final DragController dragController = mDragController;
mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
mQsbDivider = (ImageView) findViewById(R.id.qsb_divider);
mDockDivider = (ImageView) findViewById(R.id.dock_divider);
// Setup the drag layer
mDragLayer.setup(this, dragController);
// Setup the hotseat
mHotseat = (Hotseat) findViewById(R.id.hotseat);
if (mHotseat != null) {
mHotseat.setup(this);
}
// Setup the workspace
mWorkspace.setHapticFeedbackEnabled(false);
mWorkspace.setOnLongClickListener(this);
mWorkspace.setup(dragController);
dragController.addDragListener(mWorkspace);
// Get the search/delete bar
mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
// Setup AppsCustomize
mAppsCustomizeTabHost = (AppsCustomizeTabHost)
findViewById(R.id.apps_customize_pane);
mAppsCustomizeContent = (AppsCustomizePagedView)
mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
mAppsCustomizeContent.setup(this, dragController);
// Get the all apps button
mAllAppsButton = findViewById(R.id.all_apps_button);
if (mAllAppsButton != null) {
mAllAppsButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
onTouchDownAllAppsButton(v);
}
return false;
}
});
}
// Setup the drag controller (drop targets have to be added in reverse order in priority)
dragController.setDragScoller(mWorkspace);
dragController.setScrollView(mDragLayer);
dragController.setMoveTarget(mWorkspace);
dragController.addDropTarget(mWorkspace);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.setup(this, dragController);
}
}
/**
* Creates a view representing a shortcut.
*
* @param info The data structure describing the shortcut.
*
* @return A View inflated from R.layout.application.
*/
View createShortcut(ShortcutInfo info) {
return createShortcut(R.layout.application,
(ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
}
/**
* Creates a view representing a shortcut inflated from the specified resource.
*
* @param layoutResId The id of the XML layout used to create the shortcut.
* @param parent The group the shortcut belongs to.
* @param info The data structure describing the shortcut.
*
* @return A View inflated from layoutResId.
*/
View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
favorite.applyFromShortcutInfo(info, mIconCache);
favorite.setOnClickListener(this);
return favorite;
}
/**
* Add an application shortcut to the workspace.
*
* @param data The intent describing the application.
* @param cellInfo The position on screen where to create the shortcut.
*/
void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
final int[] cellXY = mTmpAddItemCellCoordinates;
final CellLayout layout = getCellLayout(container, screen);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
} else if (!layout.findCellForSpan(cellXY, 1, 1)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
if (info != null) {
info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
info.container = ItemInfo.NO_ID;
mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
isWorkspaceLocked(), cellX, cellY);
} else {
Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
}
}
/**
* Add a shortcut to the workspace.
*
* @param data The intent describing the shortcut.
* @param cellInfo The position on screen where to create the shortcut.
*/
private void completeAddShortcut(Intent data, long container, int screen, int cellX,
int cellY) {
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
CellLayout layout = getCellLayout(container, screen);
boolean foundCellSpan = false;
ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
if (info == null) {
return;
}
final View view = createShortcut(info);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
foundCellSpan = true;
// If appropriate, either create a folder or add to an existing folder
if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
true, null,null)) {
return;
}
DragObject dragObject = new DragObject();
dragObject.dragInfo = info;
if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
true)) {
return;
}
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
}
if (!foundCellSpan) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
LauncherModel.addItemToDatabase(this, info, container, screen, cellXY[0], cellXY[1], false);
if (!mRestoring) {
mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1,
isWorkspaceLocked());
}
}
int[] getSpanForWidget(ComponentName component, int minWidth, int minHeight, int[] spanXY) {
if (spanXY == null) {
spanXY = new int[2];
}
Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(this, component, null);
// We want to account for the extra amount of padding that we are adding to the widget
// to ensure that it gets the full amount of space that it has requested
int requiredWidth = minWidth + padding.left + padding.right;
int requiredHeight = minHeight + padding.top + padding.bottom;
return CellLayout.rectToCell(getResources(), requiredWidth, requiredHeight, null);
}
int[] getSpanForWidget(AppWidgetProviderInfo info, int[] spanXY) {
return getSpanForWidget(info.provider, info.minWidth, info.minHeight, spanXY);
}
int[] getMinSpanForWidget(AppWidgetProviderInfo info, int[] spanXY) {
return getSpanForWidget(info.provider, info.minResizeWidth, info.minResizeHeight, spanXY);
}
int[] getSpanForWidget(PendingAddWidgetInfo info, int[] spanXY) {
return getSpanForWidget(info.componentName, info.minWidth, info.minHeight, spanXY);
}
int[] getMinSpanForWidget(PendingAddWidgetInfo info, int[] spanXY) {
return getSpanForWidget(info.componentName, info.minResizeWidth,
info.minResizeHeight, spanXY);
}
/**
* Add a widget to the workspace.
*
* @param appWidgetId The app widget id
* @param cellInfo The position on screen where to create the widget.
*/
private void completeAddAppWidget(final int appWidgetId, long container, int screen,
AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null) {
appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
}
// Calculate the grid spans needed to fit this widget
CellLayout layout = getCellLayout(container, screen);
int[] minSpanXY = getMinSpanForWidget(appWidgetInfo, null);
int[] spanXY = getSpanForWidget(appWidgetInfo, null);
// Try finding open space on Launcher screen
// We have saved the position to which the widget was dragged-- this really only matters
// if we are placing widgets on a "spring-loaded" screen
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
int[] finalSpan = new int[2];
boolean foundCellSpan = false;
if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
cellXY[0] = mPendingAddInfo.cellX;
cellXY[1] = mPendingAddInfo.cellY;
spanXY[0] = mPendingAddInfo.spanX;
spanXY[1] = mPendingAddInfo.spanY;
foundCellSpan = true;
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(
touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
spanXY[1], cellXY, finalSpan);
spanXY[0] = finalSpan[0];
spanXY[1] = finalSpan[1];
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
}
if (!foundCellSpan) {
if (appWidgetId != -1) {
// Deleting an app widget ID is a void call but writes to disk before returning
// to the caller...
new Thread("deleteAppWidgetId") {
public void run() {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}.start();
}
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
// Build Launcher-specific widget info and save to database
LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
launcherInfo.spanX = spanXY[0];
launcherInfo.spanY = spanXY[1];
launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
LauncherModel.addItemToDatabase(this, launcherInfo,
container, screen, cellXY[0], cellXY[1], false);
if (!mRestoring) {
if (hostView == null) {
// Perform actual inflation because we're live
launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
} else {
// The AppWidgetHostView has already been inflated and instantiated
launcherInfo.hostView = hostView;
}
launcherInfo.hostView.setTag(launcherInfo);
launcherInfo.hostView.setVisibility(View.VISIBLE);
mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
}
resetAddInfo();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
mUserPresent = false;
mDragLayer.clearAllResizeFrames();
updateRunning();
// Reset AllApps to its initial state only if we are not in the middle of
// processing a multi-step drop
if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
mAppsCustomizeTabHost.reset();
showWorkspace(false);
}
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
mUserPresent = true;
updateRunning();
}
}
};
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Listen for broadcasts related to user-presence
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
mAttached = true;
mVisible = true;
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mVisible = false;
mDragLayer.clearAllResizeFrames();
if (mAttached) {
unregisterReceiver(mReceiver);
mAttached = false;
}
updateRunning();
}
public void onWindowVisibilityChanged(int visibility) {
mVisible = visibility == View.VISIBLE;
updateRunning();
// The following code used to be in onResume, but it turns out onResume is called when
// you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
// is a more appropriate event to handle
if (mVisible) {
mAppsCustomizeTabHost.onWindowVisible();
if (!mWorkspaceLoading) {
final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
// We want to let Launcher draw itself at least once before we force it to build
// layers on all the workspace pages, so that transitioning to Launcher from other
// apps is nice and speedy. Usually the first call to preDraw doesn't correspond to
// a true draw so we wait until the second preDraw call to be safe
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
// We delay the layer building a bit in order to give
// other message processing a time to run. In particular
// this avoids a delay in hiding the IME if it was
// currently shown, because doing that may involve
// some communication back with the app.
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
observer.removeOnPreDrawListener(this);
return true;
}
});
}
// When Launcher comes back to foreground, a different Activity might be responsible for
// the app market intent, so refresh the icon
updateAppMarketIcon();
clearTypedText();
}
}
private void sendAdvanceMessage(long delay) {
mHandler.removeMessages(ADVANCE_MSG);
Message msg = mHandler.obtainMessage(ADVANCE_MSG);
mHandler.sendMessageDelayed(msg, delay);
mAutoAdvanceSentTime = System.currentTimeMillis();
}
private void updateRunning() {
boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
if (autoAdvanceRunning != mAutoAdvanceRunning) {
mAutoAdvanceRunning = autoAdvanceRunning;
if (autoAdvanceRunning) {
long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
sendAdvanceMessage(delay);
} else {
if (!mWidgetsToAdvance.isEmpty()) {
mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
(System.currentTimeMillis() - mAutoAdvanceSentTime));
}
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0); // Remove messages sent using postDelayed()
}
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == ADVANCE_MSG) {
int i = 0;
for (View key: mWidgetsToAdvance.keySet()) {
final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
final int delay = mAdvanceStagger * i;
if (v instanceof Advanceable) {
postDelayed(new Runnable() {
public void run() {
((Advanceable) v).advance();
}
}, delay);
}
i++;
}
sendAdvanceMessage(mAdvanceInterval);
}
}
};
void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
if (v instanceof Advanceable) {
mWidgetsToAdvance.put(hostView, appWidgetInfo);
((Advanceable) v).fyiWillBeAdvancedByHostKThx();
updateRunning();
}
}
void removeWidgetToAutoAdvance(View hostView) {
if (mWidgetsToAdvance.containsKey(hostView)) {
mWidgetsToAdvance.remove(hostView);
updateRunning();
}
}
public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
removeWidgetToAutoAdvance(launcherInfo.hostView);
launcherInfo.hostView = null;
}
void showOutOfSpaceMessage(boolean isHotseatLayout) {
int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
}
public LauncherAppWidgetHost getAppWidgetHost() {
return mAppWidgetHost;
}
public LauncherModel getModel() {
return mModel;
}
void closeSystemDialogs() {
getWindow().closeAllPanels();
/**
* We should remove this code when we remove all the dialog code.
try {
dismissDialog(DIALOG_CREATE_SHORTCUT);
// Unlock the workspace if the dialog was showing
} catch (Exception e) {
// An exception is thrown if the dialog is not visible, which is fine
}
try {
dismissDialog(DIALOG_RENAME_FOLDER);
// Unlock the workspace if the dialog was showing
} catch (Exception e) {
// An exception is thrown if the dialog is not visible, which is fine
}
*/
// Whatever we were doing is hereby canceled.
mWaitingForResult = false;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Close the menu
if (Intent.ACTION_MAIN.equals(intent.getAction())) {
// also will cancel mWaitingForResult.
closeSystemDialogs();
boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
!= Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
Folder openFolder = mWorkspace.getOpenFolder();
// In all these cases, only animate if we're already on home
mWorkspace.exitWidgetResizeMode();
if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
openFolder == null) {
mWorkspace.moveToDefaultScreen(true);
}
closeFolder();
exitSpringLoadedDragMode();
showWorkspace(alreadyOnHome);
final View v = getWindow().peekDecorView();
if (v != null && v.getWindowToken() != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
// Reset AllApps to its initial state
if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
mAppsCustomizeTabHost.reset();
}
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// Do not call super here
mSavedInstanceState = savedInstanceState;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage());
super.onSaveInstanceState(outState);
outState.putInt(RUNTIME_STATE, mState.ordinal());
// We close any open folder since it will not be re-opened, and we need to make sure
// this state is reflected.
closeFolder();
if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
mWaitingForResult) {
outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
}
if (mFolderInfo != null && mWaitingForResult) {
outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
}
// Save the current AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
if (currentTabTag != null) {
outState.putString("apps_customize_currentTab", currentTabTag);
}
int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
outState.putInt("apps_customize_currentIndex", currentIndex);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove all pending runnables
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0);
mWorkspace.removeCallbacks(mBuildLayersRunnable);
// Stop callbacks from LauncherModel
LauncherApplication app = ((LauncherApplication) getApplication());
mModel.stopLoader();
app.setLauncher(null);
try {
mAppWidgetHost.stopListening();
} catch (NullPointerException ex) {
Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
}
mAppWidgetHost = null;
mWidgetsToAdvance.clear();
TextKeyListener.getInstance().release();
unbindWorkspaceAndHotseatItems();
getContentResolver().unregisterContentObserver(mWidgetObserver);
unregisterReceiver(mCloseSystemDialogsReceiver);
((ViewGroup) mWorkspace.getParent()).removeAllViews();
mWorkspace.removeAllViews();
mWorkspace = null;
mDragController = null;
ValueAnimator.clearAllAnimations();
}
public DragController getDragController() {
return mDragController;
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode >= 0) mWaitingForResult = true;
super.startActivityForResult(intent, requestCode);
}
/**
* Indicates that we want global search for this activity by setting the globalSearch
* argument for {@link #startSearch} to true.
*/
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
showWorkspace(true);
if (initialQuery == null) {
// Use any text typed in the launcher as the initial query
initialQuery = getTypedText();
}
if (appSearchData == null) {
appSearchData = new Bundle();
appSearchData.putString(Search.SOURCE, "launcher-search");
}
Rect sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
appSearchData, globalSearch, sourceBounds);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (isWorkspaceLocked()) {
return false;
}
super.onCreateOptionsMenu(menu);
Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
String helpUrl = getString(R.string.help_url);
Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
.setIcon(android.R.drawable.ic_menu_gallery)
.setAlphabeticShortcut('W');
menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
.setIcon(android.R.drawable.ic_menu_manage)
.setIntent(manageApps)
.setAlphabeticShortcut('M');
menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
.setIcon(android.R.drawable.ic_menu_preferences)
.setIntent(settings)
.setAlphabeticShortcut('P');
if (!helpUrl.isEmpty()) {
menu.add(0, MENU_HELP, 0, R.string.menu_help)
.setIcon(android.R.drawable.ic_menu_help)
.setIntent(help)
.setAlphabeticShortcut('H');
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mAppsCustomizeTabHost.isTransitioning()) {
return false;
}
boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_WALLPAPER_SETTINGS:
startWallpaper();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSearchRequested() {
startSearch(null, false, null, true);
// Use a custom animation for launching search
overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
return true;
}
public boolean isWorkspaceLocked() {
return mWorkspaceLoading || mWaitingForResult;
}
private void resetAddInfo() {
mPendingAddInfo.container = ItemInfo.NO_ID;
mPendingAddInfo.screen = -1;
mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
mPendingAddInfo.dropPos = null;
}
void addAppWidgetFromPick(Intent data) {
// TODO: catch bad widget exception when sent
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
// TODO: Is this log message meaningful?
if (LOGD) Log.d(TAG, "dumping extras content=" + data.getExtras());
addAppWidgetImpl(appWidgetId, null);
}
void addAppWidgetImpl(final int appWidgetId, final PendingAddWidgetInfo info) {
final AppWidgetProviderInfo appWidget = info.info;
Runnable configurationActivity = null;
if (appWidget.configure != null) {
// Launch over to configure widget, if needed
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidget.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
if (info != null) {
if (info.mimeType != null && !info.mimeType.isEmpty()) {
intent.putExtra(InstallWidgetReceiver.
EXTRA_APPWIDGET_CONFIGURATION_DATA_MIME_TYPE, info.mimeType);
final String mimeType = info.mimeType;
final ClipData clipData = (ClipData) info.configurationData;
final ClipDescription clipDesc = clipData.getDescription();
for (int i = 0; i < clipDesc.getMimeTypeCount(); ++i) {
if (clipDesc.getMimeType(i).equals(mimeType)) {
final ClipData.Item item = clipData.getItemAt(i);
final CharSequence stringData = item.getText();
final Uri uriData = item.getUri();
final Intent intentData = item.getIntent();
final String key = InstallWidgetReceiver.
EXTRA_APPWIDGET_CONFIGURATION_DATA;
if (uriData != null) {
intent.putExtra(key, uriData);
} else if (intentData != null) {
intent.putExtra(key, intentData);
} else if (stringData != null) {
intent.putExtra(key, stringData);
}
break;
}
}
}
}
startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
mWidgetBeingConfigured = info;
} else {
// Otherwise just add it
completeAddAppWidget(appWidgetId, info.container, info.screen, info.boundWidget, appWidget);
// Exit spring loaded mode if necessary after adding the widget
exitSpringLoadedDragModeDelayed(true, false, null);
}
}
/**
* Process a shortcut drop.
*
* @param componentName The name of the component
* @param screen The screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void processShortcutFromDrop(ComponentName componentName, long container, int screen,
int[] cell, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = container;
mPendingAddInfo.screen = screen;
mPendingAddInfo.dropPos = loc;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
createShortcutIntent.setComponent(componentName);
processShortcut(createShortcutIntent);
}
/**
* Process a widget drop.
*
* @param info The PendingAppWidgetInfo of the widget being added.
* @param screen The screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
int[] cell, int[] span, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = info.container = container;
mPendingAddInfo.screen = info.screen = screen;
mPendingAddInfo.dropPos = loc;
mPendingAddInfo.minSpanX = info.minSpanX;
mPendingAddInfo.minSpanY = info.minSpanY;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
if (span != null) {
mPendingAddInfo.spanX = span[0];
mPendingAddInfo.spanY = span[1];
}
AppWidgetHostView hostView = info.boundWidget;
int appWidgetId;
if (hostView != null) {
appWidgetId = hostView.getAppWidgetId();
} else {
appWidgetId = getAppWidgetHost().allocateAppWidgetId();
AppWidgetManager.getInstance(this).bindAppWidgetId(appWidgetId, info.componentName);
}
addAppWidgetImpl(appWidgetId, info);
}
void processShortcut(Intent intent) {
// Handle case where user selected "Applications"
String applicationName = getResources().getString(R.string.group_applications);
String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (applicationName != null && applicationName.equals(shortcutName)) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
} else {
startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
}
}
void processWallpaper(Intent intent) {
startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
}
FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
int cellY) {
final FolderInfo folderInfo = new FolderInfo();
folderInfo.title = getText(R.string.folder_name);
// Update the model
LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
false);
sFolders.put(folderInfo.id, folderInfo);
// Create the view
FolderIcon newFolder =
FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
isWorkspaceLocked());
return newFolder;
}
void removeFolder(FolderInfo folder) {
sFolders.remove(folder.id);
}
private void startWallpaper() {
showWorkspace(true);
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper,
getText(R.string.chooser_wallpaper));
// NOTE: Adds a configure option to the chooser if the wallpaper supports it
// Removed in Eclair MR1
// WallpaperManager wm = (WallpaperManager)
// getSystemService(Context.WALLPAPER_SERVICE);
// WallpaperInfo wi = wm.getWallpaperInfo();
// if (wi != null && wi.getSettingsActivity() != null) {
// LabeledIntent li = new LabeledIntent(getPackageName(),
// R.string.configure_wallpaper, 0);
// li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
// }
startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
}
/**
* Registers various content observers. The current implementation registers
* only a favorites observer to keep track of the favorites applications.
*/
private void registerContentObservers() {
ContentResolver resolver = getContentResolver();
resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
true, mWidgetObserver);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
dumpState();
return true;
}
break;
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void onBackPressed() {
if (mState == State.APPS_CUSTOMIZE) {
showWorkspace(true);
} else if (mWorkspace.getOpenFolder() != null) {
Folder openFolder = mWorkspace.getOpenFolder();
if (openFolder.isEditingName()) {
openFolder.dismissEditingName();
} else {
closeFolder();
}
} else {
mWorkspace.exitWidgetResizeMode();
// Back button is a no-op here, but give at least some feedback for the button press
mWorkspace.showOutlinesTemporarily();
}
}
/**
* Re-listen when widgets are reset.
*/
private void onAppWidgetReset() {
if (mAppWidgetHost != null) {
mAppWidgetHost.startListening();
}
}
/**
* Go through the and disconnect any of the callbacks in the drawables and the views or we
* leak the previous Home screen on orientation change.
*/
private void unbindWorkspaceAndHotseatItems() {
if (mModel != null) {
mModel.unbindWorkspaceItems();
}
}
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
// Make sure that rogue clicks don't get through while allapps is launching, or after the
// view has detached (it's possible for this to happen if the view is removed mid touch).
if (v.getWindowToken() == null) {
return;
}
if (!mWorkspace.isFinishedSwitchingState()) {
return;
}
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
// Open shortcut
final Intent intent = ((ShortcutInfo) tag).intent;
int[] pos = new int[2];
v.getLocationOnScreen(pos);
intent.setSourceBounds(new Rect(pos[0], pos[1],
pos[0] + v.getWidth(), pos[1] + v.getHeight()));
boolean success = startActivitySafely(intent, tag);
if (success && v instanceof BubbleTextView) {
mWaitingForResume = (BubbleTextView) v;
mWaitingForResume.setStayPressed(true);
}
} else if (tag instanceof FolderInfo) {
if (v instanceof FolderIcon) {
FolderIcon fi = (FolderIcon) v;
handleFolderClick(fi);
}
} else if (v == mAllAppsButton) {
if (mState == State.APPS_CUSTOMIZE) {
showWorkspace(true);
} else {
onClickAllAppsButton(v);
}
}
}
public boolean onTouch(View v, MotionEvent event) {
// this is an intercepted event being forwarded from mWorkspace;
// clicking anywhere on the workspace causes the customization drawer to slide down
showWorkspace(true);
return false;
}
/**
* Event handler for the search button
*
* @param v The view that was clicked.
*/
public void onClickSearchButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
onSearchRequested();
}
/**
* Event handler for the voice button
*
* @param v The view that was clicked.
*/
public void onClickVoiceButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
/**
* Event handler for the "grid" button that appears on the home screen, which
* enters all apps mode.
*
* @param v The view that was clicked.
*/
public void onClickAllAppsButton(View v) {
showAllApps(true);
}
public void onTouchDownAllAppsButton(View v) {
// Provide the same haptic feedback that the system offers for virtual keys.
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
public void onClickAppMarketButton(View v) {
if (mAppMarketIntent != null) {
startActivitySafely(mAppMarketIntent, "app market");
} else {
Log.e(TAG, "Invalid app market intent.");
}
}
void startApplicationDetailsActivity(ComponentName componentName) {
String packageName = componentName.getPackageName();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
void startApplicationUninstallActivity(ApplicationInfo appInfo) {
if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
// System applications cannot be installed. For now, show a toast explaining that.
// We may give them the option of disabling apps this way.
int messageId = R.string.uninstall_system_app_text;
Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
} else {
String packageName = appInfo.componentName.getPackageName();
String className = appInfo.componentName.getClassName();
Intent intent = new Intent(
Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}
boolean startActivitySafely(Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity. "
+ "tag="+ tag + " intent=" + intent, e);
}
return false;
}
void startActivityForResultSafely(Intent intent, int requestCode) {
try {
startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity.", e);
}
}
private void handleFolderClick(FolderIcon folderIcon) {
final FolderInfo info = folderIcon.mInfo;
Folder openFolder = mWorkspace.getFolderForTag(info);
// If the folder info reports that the associated folder is open, then verify that
// it is actually opened. There have been a few instances where this gets out of sync.
if (info.opened && openFolder == null) {
Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
+ info.screen + " (" + info.cellX + ", " + info.cellY + ")");
info.opened = false;
}
if (!info.opened) {
// Close any open folder
closeFolder();
// Open the requested folder
openFolder(folderIcon);
} else {
// Find the open folder...
int folderScreen;
if (openFolder != null) {
folderScreen = mWorkspace.getPageForView(openFolder);
// .. and close it
closeFolder(openFolder);
if (folderScreen != mWorkspace.getCurrentPage()) {
// Close any folder open on the current screen
closeFolder();
// Pull the folder onto this screen
openFolder(folderIcon);
}
}
}
}
private void growAndFadeOutFolderIcon(FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
FolderInfo info = (FolderInfo) fi.getTag();
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
CellLayout cl = (CellLayout) fi.getParent().getParent();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
}
ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.start();
}
private void shrinkAndFadeInFolderIcon(FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
FolderInfo info = (FolderInfo) fi.getTag();
CellLayout cl = null;
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
cl = (CellLayout) fi.getParent().getParent();
}
final CellLayout layout = cl;
ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (layout != null) {
layout.clearFolderLeaveBehind();
}
}
});
oa.start();
}
/**
* Opens the user folder described by the specified tag. The opening of the folder
* is animated relative to the specified View. If the View is null, no animation
* is played.
*
* @param folderInfo The FolderInfo describing the folder to open.
*/
public void openFolder(FolderIcon folderIcon) {
Folder folder = folderIcon.mFolder;
FolderInfo info = folder.mInfo;
growAndFadeOutFolderIcon(folderIcon);
info.opened = true;
// Just verify that the folder hasn't already been added to the DragLayer.
// There was a one-off crash where the folder had a parent already.
if (folder.getParent() == null) {
mDragLayer.addView(folder);
mDragController.addDropTarget((DropTarget) folder);
} else {
Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
folder.getParent() + ").");
}
folder.animateOpen();
}
public void closeFolder() {
Folder folder = mWorkspace.getOpenFolder();
if (folder != null) {
if (folder.isEditingName()) {
folder.dismissEditingName();
}
closeFolder(folder);
// Dismiss the folder cling
dismissFolderCling(null);
}
}
void closeFolder(Folder folder) {
folder.getInfo().opened = false;
ViewGroup parent = (ViewGroup) folder.getParent().getParent();
if (parent != null) {
FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
shrinkAndFadeInFolderIcon(fi);
}
folder.animateClosed();
}
public boolean onLongClick(View v) {
if (mState != State.WORKSPACE) {
return false;
}
if (isWorkspaceLocked()) {
return false;
}
if (!(v instanceof CellLayout)) {
v = (View) v.getParent().getParent();
}
resetAddInfo();
CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
// This happens when long clicking an item with the dpad/trackball
if (longClickCellInfo == null) {
return true;
}
// The hotseat touch handling does not go through Workspace, and we always allow long press
// on hotseat items.
final View itemUnderLongClick = longClickCellInfo.cell;
boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
if (allowLongPress && !mDragController.isDragging()) {
if (itemUnderLongClick == null) {
// User long pressed on empty space
mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
startWallpaper();
} else {
if (!(itemUnderLongClick instanceof Folder)) {
// User long pressed on an item
mWorkspace.startDrag(longClickCellInfo);
}
}
}
return true;
}
boolean isHotseatLayout(View layout) {
return mHotseat != null && layout != null &&
(layout instanceof CellLayout) && (layout == mHotseat.getLayout());
}
Hotseat getHotseat() {
return mHotseat;
}
SearchDropTargetBar getSearchBar() {
return mSearchDropTargetBar;
}
/**
* Returns the CellLayout of the specified container at the specified screen.
*/
CellLayout getCellLayout(long container, int screen) {
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (mHotseat != null) {
return mHotseat.getLayout();
} else {
return null;
}
} else {
return (CellLayout) mWorkspace.getChildAt(screen);
}
}
Workspace getWorkspace() {
return mWorkspace;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CREATE_SHORTCUT:
return new CreateShortcut().createDialog();
case DIALOG_RENAME_FOLDER:
return new RenameFolder().createDialog();
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_CREATE_SHORTCUT:
break;
case DIALOG_RENAME_FOLDER:
if (mFolderInfo != null) {
EditText input = (EditText) dialog.findViewById(R.id.folder_name);
final CharSequence text = mFolderInfo.title;
input.setText(text);
input.setSelection(0, text.length());
}
break;
}
}
void showRenameDialog(FolderInfo info) {
mFolderInfo = info;
mWaitingForResult = true;
showDialog(DIALOG_RENAME_FOLDER);
}
private void showAddDialog() {
resetAddInfo();
mPendingAddInfo.container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
mPendingAddInfo.screen = mWorkspace.getCurrentPage();
mWaitingForResult = true;
showDialog(DIALOG_CREATE_SHORTCUT);
}
private class RenameFolder {
private EditText mInput;
Dialog createDialog() {
final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
mInput = (EditText) layout.findViewById(R.id.folder_name);
AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
builder.setIcon(0);
builder.setTitle(getString(R.string.rename_folder_title));
builder.setCancelable(true);
builder.setOnCancelListener(new Dialog.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cleanup();
}
});
builder.setNegativeButton(getString(R.string.cancel_action),
new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cleanup();
}
}
);
builder.setPositiveButton(getString(R.string.rename_action),
new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
changeFolderName();
}
}
);
builder.setView(layout);
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
mWaitingForResult = true;
mInput.requestFocus();
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(mInput, 0);
}
});
return dialog;
}
private void changeFolderName() {
final String name = mInput.getText().toString();
if (!TextUtils.isEmpty(name)) {
// Make sure we have the right folder info
mFolderInfo = sFolders.get(mFolderInfo.id);
mFolderInfo.title = name;
LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
if (mWorkspaceLoading) {
lockAllApps();
mModel.startLoader(false);
} else {
final FolderIcon folderIcon = (FolderIcon)
mWorkspace.getViewForTag(mFolderInfo);
if (folderIcon != null) {
// TODO: At some point we'll probably want some version of setting
// the text for a folder icon.
//folderIcon.setText(name);
getWorkspace().requestLayout();
} else {
lockAllApps();
mWorkspaceLoading = true;
mModel.startLoader(false);
}
}
}
cleanup();
}
private void cleanup() {
dismissDialog(DIALOG_RENAME_FOLDER);
mWaitingForResult = false;
mFolderInfo = null;
}
}
// Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
public boolean isAllAppsVisible() {
return (mState == State.APPS_CUSTOMIZE);
}
public boolean isAllAppsButtonRank(int rank) {
return mHotseat.isAllAppsButtonRank(rank);
}
// AllAppsView.Watcher
public void zoomed(float zoom) {
if (zoom == 1.0f) {
mWorkspace.setVisibility(View.GONE);
}
}
/**
* Helper method for the cameraZoomIn/cameraZoomOut animations
* @param view The view being animated
* @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
* @param scaleFactor The scale factor used for the zoom
*/
private void setPivotsForZoom(View view, float scaleFactor) {
view.setPivotX(view.getWidth() / 2.0f);
view.setPivotY(view.getHeight() / 2.0f);
}
void updateWallpaperVisibility(boolean visible) {
int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
int curflags = getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
if (wpflags != curflags) {
getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
}
}
private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 0f);
}
private void dispatchOnLauncherTransitionStep(View v, float t) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
}
}
private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 1f);
}
/**
* Things to test when changing the following seven functions.
* - Home from workspace
* - from center screen
* - from other screens
* - Home from all apps
* - from center screen
* - from other screens
* - Back from all apps
* - from center screen
* - from other screens
* - Launch app from workspace and quit
* - with back
* - with home
* - Launch app from all apps and quit
* - with back
* - with home
* - Go to a screen that's not the default, then all
* apps, and launch and app, and go back
* - with back
* -with home
* - On workspace, long press power and go back
* - with back
* - with home
* - On all apps, long press power and go back
* - with back
* - with home
* - On workspace, power off
* - On all apps, power off
* - Launch an app and turn off the screen while in that app
* - Go back with home key
* - Go back with back key TODO: make this not go to workspace
* - From all apps
* - From workspace
* - Enter and exit car mode (becuase it causes an extra configuration changed)
* - From all apps
* - From the center workspace
* - From another workspace
*/
/**
* Zoom the camera out from the workspace to reveal 'toView'.
* Assumes that the view to show is anchored at either the very top or very bottom
* of the screen.
*/
private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final Launcher instance = this;
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final View toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = new AnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
if (delayAnim) {
final AnimatorSet stateAnimation = mStateAnimation;
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
mWorkspace.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout pass
if (mStateAnimation == stateAnimation) {
// Need to update pivots for zoom if layout changed
setPivotsForZoom(toView, scale);
mStateAnimation.start();
}
}
});
observer.removeGlobalOnLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
setPivotsForZoom(toView, scale);
mStateAnimation.start();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
/**
* Zoom the camera back into the workspace, hiding 'fromView'.
* This is the opposite of showAppsCustomizeHelper.
* @param animated If true, the transition will be animated.
*/
private void hideAppsCustomizeHelper(State toState, final boolean animated,
final boolean springLoaded, final Runnable onCompleteRunnable) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
final int fadeOutDuration =
res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
final float scaleFactor = (float)
res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mAppsCustomizeTabHost;
final View toView = mWorkspace;
Animator workspaceAnim = null;
if (toState == State.WORKSPACE) {
int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.NORMAL, animated, stagger);
} else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.SPRING_LOADED, animated);
}
setPivotsForZoom(fromView, scaleFactor);
updateWallpaperVisibility(true);
showHotseat(animated);
if (animated) {
final float oldScaleX = fromView.getScaleX();
final float oldScaleY = fromView.getScaleY();
final LauncherViewPropertyAnimator scaleAnim =
new LauncherViewPropertyAnimator(fromView);
scaleAnim.
scaleX(scaleFactor).scaleY(scaleFactor).
setDuration(duration).
setInterpolator(new Workspace.ZoomInInterpolator());
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(fromView, "alpha", 1f, 0f)
.setDuration(fadeOutDuration);
alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float t = 1f - (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
mStateAnimation = new AnimatorSet();
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
updateWallpaperVisibility(true);
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
mWorkspace.hideScrollingIndicator(false);
if (onCompleteRunnable != null) {
onCompleteRunnable.run();
}
}
});
mStateAnimation.playTogether(scaleAnim, alphaAnim);
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
mStateAnimation.start();
} else {
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
mWorkspace.hideScrollingIndicator(false);
}
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
mAppsCustomizeTabHost.onTrimMemory();
}
}
void showWorkspace(boolean animated) {
showWorkspace(animated, null);
}
void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
if (mState != State.WORKSPACE) {
mWorkspace.setVisibility(View.VISIBLE);
hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
// Show the search bar and hotseat
mSearchDropTargetBar.showSearchBar(animated);
// We only need to animate in the dock divider if we're going from spring loaded mode
showDockDivider(animated && mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
// Set focus to the AppsCustomize button
if (mAllAppsButton != null) {
mAllAppsButton.requestFocus();
}
}
mWorkspace.flashScrollingIndicator(animated);
// Change the state *after* we've called all the transition code
mState = State.WORKSPACE;
// Resume the auto-advance of widgets
mUserPresent = true;
updateRunning();
// send an accessibility event to announce the context change
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
void showAllApps(boolean animated) {
if (mState != State.WORKSPACE) return;
showAppsCustomizeHelper(animated, false);
mAppsCustomizeTabHost.requestFocus();
// Hide the search bar and hotseat
mSearchDropTargetBar.hideSearchBar(animated);
// Change the state *after* we've called all the transition code
mState = State.APPS_CUSTOMIZE;
// Pause the auto-advance of widgets until we are out of AllApps
mUserPresent = false;
updateRunning();
closeFolder();
// Send an accessibility event to announce the context change
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
void enterSpringLoadedDragMode() {
if (mState == State.APPS_CUSTOMIZE) {
hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
hideDockDivider();
mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
}
}
void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
final Runnable onCompleteRunnable) {
if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (successfulDrop) {
// Before we show workspace, hide all apps again because
// exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
// clean up our state transition functions
mAppsCustomizeTabHost.setVisibility(View.GONE);
mSearchDropTargetBar.showSearchBar(true);
showWorkspace(true, onCompleteRunnable);
} else {
exitSpringLoadedDragMode();
}
}
}, (extendedDelay ?
EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
}
void exitSpringLoadedDragMode() {
if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
final boolean animated = true;
final boolean springLoaded = true;
showAppsCustomizeHelper(animated, springLoaded);
mState = State.APPS_CUSTOMIZE;
}
// Otherwise, we are not in spring loaded mode, so don't do anything.
}
void hideDockDivider() {
if (mQsbDivider != null && mDockDivider != null) {
mQsbDivider.setVisibility(View.INVISIBLE);
mDockDivider.setVisibility(View.INVISIBLE);
}
}
void showDockDivider(boolean animated) {
if (mQsbDivider != null && mDockDivider != null) {
mQsbDivider.setVisibility(View.VISIBLE);
mDockDivider.setVisibility(View.VISIBLE);
if (mDividerAnimator != null) {
mDividerAnimator.cancel();
mQsbDivider.setAlpha(1f);
mDockDivider.setAlpha(1f);
mDividerAnimator = null;
}
if (animated) {
mDividerAnimator = new AnimatorSet();
mDividerAnimator.playTogether(ObjectAnimator.ofFloat(mQsbDivider, "alpha", 1f),
ObjectAnimator.ofFloat(mDockDivider, "alpha", 1f));
mDividerAnimator.setDuration(mSearchDropTargetBar.getTransitionInDuration());
mDividerAnimator.start();
}
}
}
void lockAllApps() {
// TODO
}
void unlockAllApps() {
// TODO
}
public boolean isAllAppsCustomizeOpen() {
return mState == State.APPS_CUSTOMIZE;
}
/**
* Shows the hotseat area.
*/
void showHotseat(boolean animated) {
if (!LauncherApplication.isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 1f) {
int duration = mSearchDropTargetBar.getTransitionInDuration();
mHotseat.animate().alpha(1f).setDuration(duration);
}
} else {
mHotseat.setAlpha(1f);
}
}
}
/**
* Hides the hotseat area.
*/
void hideHotseat(boolean animated) {
if (!LauncherApplication.isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 0f) {
int duration = mSearchDropTargetBar.getTransitionOutDuration();
mHotseat.animate().alpha(0f).setDuration(duration);
}
} else {
mHotseat.setAlpha(0f);
}
}
}
/**
* Add an item from all apps or customize onto the given workspace screen.
* If layout is null, add to the current screen.
*/
void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
}
}
/** Maps the current orientation to an index for referencing orientation correct global icons */
private int getCurrentOrientationIndexForGlobalIcons() {
// default - 0, landscape - 1
switch (getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
return 1;
default:
return 0;
}
}
private Drawable getExternalPackageToolbarIcon(ComponentName activityName) {
try {
PackageManager packageManager = getPackageManager();
// Look for the toolbar icon specified in the activity meta-data
Bundle metaData = packageManager.getActivityInfo(
activityName, PackageManager.GET_META_DATA).metaData;
if (metaData != null) {
int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME);
if (iconResId != 0) {
Resources res = packageManager.getResourcesForActivity(activityName);
return res.getDrawable(iconResId);
}
}
} catch (NameNotFoundException e) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
" not found", e);
} catch (Resources.NotFoundException nfe) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
nfe);
}
return null;
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId) {
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
Resources r = getResources();
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
TextView button = (TextView) findViewById(buttonId);
// If we were unable to find the icon via the meta-data, use a generic one
if (toolbarIcon == null) {
toolbarIcon = r.getDrawable(fallbackDrawableId);
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return null;
} else {
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return toolbarIcon.getConstantState();
}
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId) {
ImageView button = (ImageView) findViewById(buttonId);
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
if (button != null) {
// If we were unable to find the icon via the meta-data, use a
// generic one
if (toolbarIcon == null) {
button.setImageResource(fallbackDrawableId);
} else {
button.setImageDrawable(toolbarIcon);
}
}
return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
}
private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
TextView button = (TextView) findViewById(buttonId);
button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null);
}
private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
ImageView button = (ImageView) findViewById(buttonId);
button.setImageDrawable(d.newDrawable(getResources()));
}
private void invalidatePressedFocusedStates(View container, View button) {
if (container instanceof HolographicLinearLayout) {
HolographicLinearLayout layout = (HolographicLinearLayout) container;
layout.invalidatePressedFocusedStates();
} else if (button instanceof HolographicImageView) {
HolographicImageView view = (HolographicImageView) button;
view.invalidatePressedFocusedStates();
}
}
private boolean updateGlobalSearchIcon() {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
final View searchDivider = findViewById(R.id.search_divider);
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo);
if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
searchButton.setVisibility(View.VISIBLE);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
return true;
} else {
// We disable both search and voice search when there is no global search provider
if (searchDivider != null) searchDivider.setVisibility(View.GONE);
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
searchButton.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
return false;
}
}
private void updateGlobalSearchIcon(Drawable.ConstantState d) {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final View searchButton = (ImageView) findViewById(R.id.search_button);
updateButtonWithDrawable(R.id.search_button, d);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
}
private boolean updateVoiceSearchIcon(boolean searchVisible) {
final View searchDivider = findViewById(R.id.search_divider);
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
// We only show/update the voice search icon if the search icon is enabled as well
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
ComponentName activityName = intent.resolveActivity(getPackageManager());
if (searchVisible && activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo);
if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
voiceButton.setVisibility(View.VISIBLE);
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
return true;
} else {
if (searchDivider != null) searchDivider.setVisibility(View.GONE);
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
return false;
}
}
private void updateVoiceSearchIcon(Drawable.ConstantState d) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
updateButtonWithDrawable(R.id.voice_button, d);
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
}
/**
* Sets the app market icon
*/
private void updateAppMarketIcon() {
final View marketButton = findViewById(R.id.market_button);
Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
// Find the app market activity by resolving an intent.
// (If multiple app markets are installed, it will return the ResolverActivity.)
ComponentName activityName = intent.resolveActivity(getPackageManager());
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
mAppMarketIntent = intent;
sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
R.id.market_button, activityName, R.drawable.ic_launcher_market_holo);
marketButton.setVisibility(View.VISIBLE);
} else {
// We should hide and disable the view so that we don't try and restore the visibility
// of it when we swap between drag & normal states from IconDropTarget subclasses.
marketButton.setVisibility(View.GONE);
marketButton.setEnabled(false);
}
}
private void updateAppMarketIcon(Drawable.ConstantState d) {
updateTextButtonWithDrawable(R.id.market_button, d);
}
/**
* Displays the shortcut creation dialog and launches, if necessary, the
* appropriate activity.
*/
private class CreateShortcut implements DialogInterface.OnClickListener,
DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
DialogInterface.OnShowListener {
private AddAdapter mAdapter;
Dialog createDialog() {
mAdapter = new AddAdapter(Launcher.this);
final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this,
AlertDialog.THEME_HOLO_DARK);
builder.setAdapter(mAdapter, this);
AlertDialog dialog = builder.create();
dialog.setOnCancelListener(this);
dialog.setOnDismissListener(this);
dialog.setOnShowListener(this);
return dialog;
}
public void onCancel(DialogInterface dialog) {
mWaitingForResult = false;
cleanup();
}
public void onDismiss(DialogInterface dialog) {
mWaitingForResult = false;
cleanup();
}
private void cleanup() {
try {
dismissDialog(DIALOG_CREATE_SHORTCUT);
} catch (Exception e) {
// An exception is thrown if the dialog is not visible, which is fine
}
}
/**
* Handle the action clicked in the "Add to home" dialog.
*/
public void onClick(DialogInterface dialog, int which) {
cleanup();
AddAdapter.ListItem item = (AddAdapter.ListItem) mAdapter.getItem(which);
switch (item.actionTag) {
case AddAdapter.ITEM_APPLICATION: {
if (mAppsCustomizeTabHost != null) {
mAppsCustomizeTabHost.selectAppsTab();
}
showAllApps(true);
break;
}
case AddAdapter.ITEM_APPWIDGET: {
if (mAppsCustomizeTabHost != null) {
mAppsCustomizeTabHost.selectWidgetsTab();
}
showAllApps(true);
break;
}
case AddAdapter.ITEM_WALLPAPER: {
startWallpaper();
break;
}
}
}
public void onShow(DialogInterface dialog) {
mWaitingForResult = true;
}
}
/**
* Receives notifications when system dialogs are to be closed.
*/
private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
closeSystemDialogs();
}
}
/**
* Receives notifications whenever the appwidgets are reset.
*/
private class AppWidgetResetObserver extends ContentObserver {
public AppWidgetResetObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
onAppWidgetReset();
}
}
/**
* If the activity is currently paused, signal that we need to re-run the loader
* in onResume.
*
* This needs to be called from incoming places where resources might have been loaded
* while we are paused. That is becaues the Configuration might be wrong
* when we're not running, and if it comes back to what it was when we
* were paused, we are not restarted.
*
* Implementation of the method from LauncherModel.Callbacks.
*
* @return true if we are currently paused. The caller might be able to
* skip some work in that case since we will come back again.
*/
public boolean setLoadOnResume() {
if (mPaused) {
Log.i(TAG, "setLoadOnResume");
mOnResumeNeedsLoad = true;
return true;
} else {
return false;
}
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public int getCurrentWorkspaceScreen() {
if (mWorkspace != null) {
return mWorkspace.getCurrentPage();
} else {
return SCREEN_COUNT / 2;
}
}
/**
* Refreshes the shortcuts shown on the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void startBinding() {
final Workspace workspace = mWorkspace;
mNewShortcutAnimatePage = -1;
mNewShortcutAnimateViews.clear();
mWorkspace.clearDropTargets();
int count = workspace.getChildCount();
for (int i = 0; i < count; i++) {
// Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
layoutParent.removeAllViewsInLayout();
}
mWidgetsToAdvance.clear();
if (mHotseat != null) {
mHotseat.resetLayout();
}
}
/**
* Bind the items start-end from the list.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
setLoadOnResume();
// Get the list of added shortcuts and intersect them with the set of shortcuts here
Set<String> newApps = new HashSet<String>();
newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps);
Workspace workspace = mWorkspace;
for (int i = start; i < end; i++) {
final ItemInfo item = shortcuts.get(i);
// Short circuit if we are loading dock items for a configuration which has no dock
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
mHotseat == null) {
continue;
}
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
ShortcutInfo info = (ShortcutInfo) item;
String uri = info.intent.toUri(0).toString();
View shortcut = createShortcut(info);
workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
item.cellY, 1, 1, false);
if (newApps.contains(uri)) {
newApps.remove(uri);
// Prepare the view to be animated up
shortcut.setAlpha(0f);
shortcut.setScaleX(0f);
shortcut.setScaleY(0f);
mNewShortcutAnimatePage = item.screen;
if (!mNewShortcutAnimateViews.contains(shortcut)) {
mNewShortcutAnimateViews.add(shortcut);
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
(ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
(FolderInfo) item, mIconCache);
workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
item.cellY, 1, 1, false);
break;
}
}
workspace.requestLayout();
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindFolders(HashMap<Long, FolderInfo> folders) {
setLoadOnResume();
sFolders.clear();
sFolders.putAll(folders);
}
/**
* Add the views for a widget to the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppWidget(LauncherAppWidgetInfo item) {
setLoadOnResume();
final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: " + item);
}
final Workspace workspace = mWorkspace;
final int appWidgetId = item.appWidgetId;
final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
}
item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
item.hostView.setTag(item);
workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
item.cellY, item.spanX, item.spanY, false);
addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
workspace.requestLayout();
if (DEBUG_WIDGETS) {
Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
+ (SystemClock.uptimeMillis()-start) + "ms");
}
}
/**
* Callback saying that there aren't any more items to bind.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void finishBindingItems() {
setLoadOnResume();
if (mSavedState != null) {
if (!mWorkspace.hasFocus()) {
mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
}
mSavedState = null;
}
if (mSavedInstanceState != null) {
super.onRestoreInstanceState(mSavedInstanceState);
mSavedInstanceState = null;
}
// If we received the result of any pending adds while the loader was running (e.g. the
// widget configuration forced an orientation change), process them now.
for (int i = 0; i < sPendingAddList.size(); i++) {
completeAdd(sPendingAddList.get(i));
}
sPendingAddList.clear();
// Update the market app icon as necessary (the other icons will be managed in response to
// package changes in bindSearchablesChanged()
updateAppMarketIcon();
// Animate up any icons as necessary
if (mVisible || mWorkspaceLoading) {
Runnable newAppsRunnable = new Runnable() {
@Override
public void run() {
runNewAppsAnimation();
}
};
if (mNewShortcutAnimatePage > -1 &&
mNewShortcutAnimatePage != mWorkspace.getCurrentPage()) {
mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable);
} else {
newAppsRunnable.run();
}
}
mWorkspaceLoading = false;
}
/**
* Runs a new animation that scales up icons that were added while Launcher was in the
* background.
*/
private void runNewAppsAnimation() {
AnimatorSet anim = new AnimatorSet();
Collection<Animator> bounceAnims = new ArrayList<Animator>();
Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() {
@Override
public int compare(View a, View b) {
CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams();
CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams();
int cellCountX = LauncherModel.getCellCountX();
return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX);
}
});
for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) {
View v = mNewShortcutAnimateViews.get(i);
ValueAnimator bounceAnim = ObjectAnimator.ofPropertyValuesHolder(v,
PropertyValuesHolder.ofFloat("alpha", 1f),
PropertyValuesHolder.ofFloat("scaleX", 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f));
bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
bounceAnims.add(bounceAnim);
}
anim.playTogether(bounceAnims);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
}
});
anim.start();
// Clean up
mNewShortcutAnimatePage = -1;
mNewShortcutAnimateViews.clear();
new Thread("clearNewAppsThread") {
public void run() {
mSharedPrefs.edit()
.putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1)
.putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null)
.commit();
}
}.start();
}
@Override
public void bindSearchablesChanged() {
boolean searchVisible = updateGlobalSearchIcon();
boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
/**
* Add the icons for all apps.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
// Remove the progress bar entirely; we could also make it GONE
// but better to remove it since we know it's not going to be used
View progressBar = mAppsCustomizeTabHost.
findViewById(R.id.apps_customize_progress_bar);
if (progressBar != null) {
((ViewGroup)progressBar.getParent()).removeView(progressBar);
}
// We just post the call to setApps so the user sees the progress bar
// disappear-- otherwise, it just looks like the progress bar froze
// which doesn't look great
mAppsCustomizeTabHost.post(new Runnable() {
public void run() {
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.setApps(apps);
}
}
});
}
/**
* A package was installed.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
setLoadOnResume();
removeDialog(DIALOG_CREATE_SHORTCUT);
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.addApps(apps);
}
}
/**
* A package was updated.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
setLoadOnResume();
removeDialog(DIALOG_CREATE_SHORTCUT);
if (mWorkspace != null) {
mWorkspace.updateShortcuts(apps);
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.updateApps(apps);
}
}
/**
* A package was uninstalled.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
removeDialog(DIALOG_CREATE_SHORTCUT);
if (permanent) {
mWorkspace.removeItems(apps);
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.removeApps(apps);
}
// Notify the drag controller
mDragController.onAppsRemoved(apps, this);
}
/**
* A number of packages were updated.
*/
public void bindPackagesUpdated() {
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated();
}
}
private int mapConfigurationOriActivityInfoOri(int configOri) {
final Display d = getWindowManager().getDefaultDisplay();
int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
switch (d.getRotation()) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
// We are currently in the same basic orientation as the natural orientation
naturalOri = configOri;
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
// We are currently in the other basic orientation to the natural orientation
naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
break;
}
int[] oriMap = {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
};
// Since the map starts at portrait, we need to offset if this device's natural orientation
// is landscape.
int indexOffset = 0;
if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
indexOffset = 1;
}
return oriMap[(d.getRotation() + indexOffset) % 4];
}
public void lockScreenOrientationOnLargeUI() {
if (LauncherApplication.isScreenLarge()) {
setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
.getConfiguration().orientation));
}
}
public void unlockScreenOrientationOnLargeUI() {
if (LauncherApplication.isScreenLarge()) {
mHandler.postDelayed(new Runnable() {
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}, mRestoreScreenOrientationDelay);
}
}
/* Cling related */
private boolean isClingsEnabled() {
// disable clings when running in a test harness
if(ActivityManager.isRunningInTestHarness()) return false;
return true;
}
private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
Cling cling = (Cling) findViewById(clingId);
if (cling != null) {
cling.init(this, positionData);
cling.setVisibility(View.VISIBLE);
cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
if (animate) {
cling.buildLayer();
cling.setAlpha(0f);
cling.animate()
.alpha(1f)
.setInterpolator(new AccelerateInterpolator())
.setDuration(SHOW_CLING_DURATION)
.setStartDelay(delay)
.start();
} else {
cling.setAlpha(1f);
}
}
return cling;
}
private void dismissCling(final Cling cling, final String flag, int duration) {
if (cling != null) {
ObjectAnimator anim = ObjectAnimator.ofFloat(cling, "alpha", 0f);
anim.setDuration(duration);
anim.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
cling.setVisibility(View.GONE);
cling.cleanup();
// We should update the shared preferences on a background thread
new Thread("dismissClingThread") {
public void run() {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean(flag, true);
editor.commit();
}
}.start();
};
});
anim.start();
}
}
private void removeCling(int id) {
final View cling = findViewById(id);
if (cling != null) {
final ViewGroup parent = (ViewGroup) cling.getParent();
parent.post(new Runnable() {
@Override
public void run() {
parent.removeView(cling);
}
});
}
}
public void showFirstRunWorkspaceCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false)) {
initCling(R.id.workspace_cling, null, false, 0);
} else {
removeCling(R.id.workspace_cling);
}
}
public void showFirstRunAllAppsCling(int[] position) {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
initCling(R.id.all_apps_cling, position, true, 0);
} else {
removeCling(R.id.all_apps_cling);
}
}
public Cling showFirstRunFoldersCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
return initCling(R.id.folder_cling, null, true, 0);
} else {
removeCling(R.id.folder_cling);
return null;
}
}
public boolean isFolderClingVisible() {
Cling cling = (Cling) findViewById(R.id.folder_cling);
if (cling != null) {
return cling.getVisibility() == View.VISIBLE;
}
return false;
}
public void dismissWorkspaceCling(View v) {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissAllAppsCling(View v) {
Cling cling = (Cling) findViewById(R.id.all_apps_cling);
dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissFolderCling(View v) {
Cling cling = (Cling) findViewById(R.id.folder_cling);
dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
/**
* Prints out out state for debugging.
*/
public void dumpState() {
Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
Log.d(TAG, "mSavedState=" + mSavedState);
Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
Log.d(TAG, "mRestoring=" + mRestoring);
Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
Log.d(TAG, "sFolders.size=" + sFolders.size());
mModel.dumpState();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.dumpState();
}
Log.d(TAG, "END launcher2 dump state");
}
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.println(" ");
writer.println("Debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
writer.println(" " + sDumpLogs.get(i));
}
}
}
interface LauncherTransitionable {
View getContent();
void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStep(Launcher l, float t);
void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
}
| true | false | null | null |
diff --git a/src/sphinx4/edu/cmu/sphinx/linguist/flat/FlatLinguist.java b/src/sphinx4/edu/cmu/sphinx/linguist/flat/FlatLinguist.java
index 939c754a..ce7f4744 100644
--- a/src/sphinx4/edu/cmu/sphinx/linguist/flat/FlatLinguist.java
+++ b/src/sphinx4/edu/cmu/sphinx/linguist/flat/FlatLinguist.java
@@ -1,1735 +1,1735 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.linguist.flat;
import edu.cmu.sphinx.linguist.Linguist;
import edu.cmu.sphinx.linguist.SearchGraph;
import edu.cmu.sphinx.linguist.SearchState;
import edu.cmu.sphinx.linguist.SearchStateArc;
import edu.cmu.sphinx.linguist.acoustic.*;
import edu.cmu.sphinx.linguist.dictionary.Dictionary;
import edu.cmu.sphinx.linguist.dictionary.Pronunciation;
import edu.cmu.sphinx.linguist.dictionary.Word;
import edu.cmu.sphinx.linguist.language.grammar.Grammar;
import edu.cmu.sphinx.linguist.language.grammar.GrammarArc;
import edu.cmu.sphinx.linguist.language.grammar.GrammarNode;
import edu.cmu.sphinx.util.LogMath;
import edu.cmu.sphinx.util.StatisticsVariable;
import edu.cmu.sphinx.util.TimerPool;
import edu.cmu.sphinx.util.props.*;
import java.io.IOException;
import java.util.*;
/**
* A simple form of the linguist.
* <p/>
* The flat linguist takes a Grammar graph (as returned by the underlying, configurable grammar), and generates a search
* graph for this grammar.
* <p/>
* It makes the following simplifying assumptions:
* <p/>
* <ul> <li>Zero or one word per grammar node <li> No fan-in allowed ever <li> No composites (yet) <li> Only Unit,
* HMMState, and pronunciation states (and the initial/final grammar state are in the graph (no word, alternative or
* grammar states attached). <li> Only valid tranisitions (matching contexts) are allowed <li> No tree organization of
* units <li> Branching grammar states are allowed </ul>
* <p/>
* <p/>
* Note that all probabilties are maintained in the log math domain
*/
public class FlatLinguist implements Linguist, Configurable {
/** A sphinx property used to define the grammar to use when building the search graph */
@S4Component(type = Grammar.class)
public final static String PROP_GRAMMAR = "grammar";
/** A sphinx property used to define the unit manager to use when building the search graph */
@S4Component(type = UnitManager.class)
public final static String PROP_UNIT_MANAGER = "unitManager";
/** A sphinx property used to define the acoustic model to use when building the search graph */
@S4Component(type = AcousticModel.class)
public final static String PROP_ACOUSTIC_MODEL = "acousticModel";
/** Sphinx property that defines the name of the logmath to be used by this search manager. */
@S4Component(type = LogMath.class)
public final static String PROP_LOG_MATH = "logMath";
/** Sphinx property used to determine whether or not the gstates are dumped. */
@S4Boolean(defaultValue = false)
public final static String PROP_DUMP_GSTATES = "dumpGstates";
/** The default value for the PROP_DUMP_GSTATES property */
public final static boolean PROP_DUMP_GSTATES_DEFAULT = false;
/** Sphinx property that specifies whether to add a branch for detecting out-of-grammar utterances. */
@S4Boolean(defaultValue = false)
public final static String PROP_ADD_OUT_OF_GRAMMAR_BRANCH = "addOutOfGrammarBranch";
/** Default value of PROP_ADD_OUT_OF_GRAMMAR_BRANCH. */
public final static boolean PROP_ADD_OUT_OF_GRAMMAR_BRANCH_DEFAULT = false;
/** Sphinx property for the probability of entering the out-of-grammar branch. */
@S4Double(defaultValue = 1.0)
public final static String PROP_OUT_OF_GRAMMAR_PROBABILITY = "outOfGrammarProbability";
/** Sphinx property for the acoustic model used for the CI phone loop. */
@S4Component(type = AcousticModel.class)
public static final String PROP_PHONE_LOOP_ACOUSTIC_MODEL = "phoneLoopAcousticModel";
/** Sphinx property for the probability of inserting a CI phone in the out-of-grammar ci phone loop */
@S4Double(defaultValue = 1.0)
public static final String PROP_PHONE_INSERTION_PROBABILITY = "phoneInsertionProbability";
/**
* Property to control whether compilation progress is displayed on stdout. If this property is true, a 'dot' is
* displayed for every 1000 search states added to the search space
*/
@S4Boolean(defaultValue = false)
public final static String PROP_SHOW_COMPILATION_PROGRESS = "showCompilationProgress";
/** Property that controls whether word probabilities are spread across all pronunciations. */
@S4Boolean(defaultValue = false)
public final static String PROP_SPREAD_WORD_PROBABILITIES_ACROSS_PRONUNCIATIONS =
"spreadWordProbabilitiesAcrossPronunciations";
/** Default value for PROP_PHONE_INSERTION_PROBABILITY */
public static final double PROP_PHONE_INSERTION_PROBABILITY_DEFAULT = 1.0;
/** The default value for PROP_OUT_OF_GRAMMAR_PROBABILITY. */
public final static double PROP_OUT_OF_GRAMMAR_PROBABILITY_DEFAULT = 1.0;
protected final static float logOne = LogMath.getLogOne();
// note: some fields are protected to allow to override FlatLinguist.compileGrammar()
// ----------------------------------
// Subcomponents that are configured
// by the property sheet
// -----------------------------------
private Grammar grammar;
private AcousticModel acousticModel;
private UnitManager unitManager;
protected LogMath logMath;
// ------------------------------------
// Fields that define the OOV-behavior
// ------------------------------------
protected AcousticModel phoneLoopAcousticModel;
protected boolean addOutOfGrammarBranch;
protected float logOutOfGrammarBranchProbability;
protected float logPhoneInsertionProbability;
// ------------------------------------
// Data that is configured by the
// property sheet
// ------------------------------------
private float logWordInsertionProbability;
private float logSilenceInsertionProbability;
private float logUnitInsertionProbability;
private boolean showCompilationProgress = true;
private boolean spreadWordProbabilitiesAcrossPronunciations;
private boolean dumpGStates;
private float languageWeight;
// -----------------------------------
// Data for monitoring performance
// ------------------------------------
private StatisticsVariable totalStates;
private StatisticsVariable totalArcs;
private StatisticsVariable actualArcs;
private transient int totalStateCounter = 0;
private final static boolean tracing = false;
// ------------------------------------
// Data used for building and maintaining
// the search graph
// -------------------------------------
private transient Collection stateSet = null;
private String name;
protected Map<GrammarNode, GState> nodeStateMap;
protected Map<SearchStateArc, SearchStateArc> arcPool;
protected GrammarNode initialGrammarState = null;
protected SearchGraph searchGraph;
/**
* Returns the search graph
*
* @return the search graph
*/
public SearchGraph getSearchGraph() {
return searchGraph;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet)
*/
public void newProperties(PropertySheet ps) throws PropertyException {
// hookup to all of the components
setupAcousticModel(ps);
logMath = (LogMath) ps.getComponent(PROP_LOG_MATH);
grammar = (Grammar) ps.getComponent(PROP_GRAMMAR);
unitManager = (UnitManager) ps.getComponent(PROP_UNIT_MANAGER);
// get the rest of the configuration data
logWordInsertionProbability = logMath.linearToLog(ps.getDouble(PROP_WORD_INSERTION_PROBABILITY));
logSilenceInsertionProbability = logMath.linearToLog(ps.getDouble(PROP_SILENCE_INSERTION_PROBABILITY));
logUnitInsertionProbability = logMath.linearToLog(ps.getDouble(PROP_UNIT_INSERTION_PROBABILITY));
languageWeight = ps.getFloat(Linguist.PROP_LANGUAGE_WEIGHT);
dumpGStates = ps.getBoolean(PROP_DUMP_GSTATES);
showCompilationProgress = ps.getBoolean(PROP_SHOW_COMPILATION_PROGRESS);
spreadWordProbabilitiesAcrossPronunciations = ps.getBoolean(PROP_SPREAD_WORD_PROBABILITIES_ACROSS_PRONUNCIATIONS);
addOutOfGrammarBranch = ps.getBoolean(PROP_ADD_OUT_OF_GRAMMAR_BRANCH);
if (addOutOfGrammarBranch) {
logOutOfGrammarBranchProbability = logMath.linearToLog
(ps.getDouble(PROP_OUT_OF_GRAMMAR_PROBABILITY));
logPhoneInsertionProbability = logMath.linearToLog
(ps.getDouble(PROP_PHONE_INSERTION_PROBABILITY));
phoneLoopAcousticModel = (AcousticModel)
ps.getComponent(PROP_PHONE_LOOP_ACOUSTIC_MODEL);
}
name = ps.getInstanceName();
}
/**
* Sets up the acoustic model.
*
* @param ps the PropertySheet from which to obtain the acoustic model
*/
protected void setupAcousticModel(PropertySheet ps)
throws PropertyException {
acousticModel = (AcousticModel) ps.getComponent(PROP_ACOUSTIC_MODEL
);
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#getName()
*/
public String getName() {
return name;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.Linguist#allocate()
*/
public void allocate() throws IOException {
allocateAcousticModel();
grammar.allocate();
totalStates = StatisticsVariable.getStatisticsVariable(getName(),
"totalStates");
totalArcs = StatisticsVariable.getStatisticsVariable(getName(),
"totalArcs");
actualArcs = StatisticsVariable.getStatisticsVariable(getName(),
"actualArcs");
stateSet = compileGrammar();
totalStates.value = stateSet.size();
}
/** Allocates the acoustic model. */
protected void allocateAcousticModel() throws IOException {
acousticModel.allocate();
if (addOutOfGrammarBranch) {
phoneLoopAcousticModel.allocate();
}
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.Linguist#deallocate()
*/
public void deallocate() {
if (acousticModel != null) {
acousticModel.deallocate();
}
grammar.deallocate();
}
/** Called before a recognition */
public void startRecognition() {
if (grammarHasChanged()) {
stateSet = compileGrammar();
totalStates.value = stateSet.size();
}
}
/** Called after a recognition */
public void stopRecognition() {
}
/**
* Returns the LogMath used.
*
* @return the logMath used
*/
public LogMath getLogMath() {
return logMath;
}
/**
* Returns the log silence insertion probability.
*
* @return the log silence insertion probability.
*/
public float getLogSilenceInsertionProbability() {
return logSilenceInsertionProbability;
}
/**
* Compiles the grammar into a sentence hmm. A GrammarJob is created for
* the initial grammar node and added to the GrammarJob queue. While there
* are jobs left on the grammar job queue, a job is removed from the queue
* and the associated grammar node is expanded and attached to the tails.
* GrammarJobs for the successors are added to the grammar job queue.
*/
/**
* Compiles the grammar into a sentence hmm. A GrammarJob is created for the initial grammar node and added to the
* GrammarJob queue. While there are jobs left on the grammar job queue, a job is removed from the queue and the
* associated grammar node is expanded and attached to the tails. GrammarJobs for the successors are added to the
* grammar job queue.
*/
protected Collection compileGrammar() {
initialGrammarState = grammar.getInitialNode();
nodeStateMap = new HashMap<GrammarNode, GState>();
arcPool = new HashMap<SearchStateArc, SearchStateArc>();
List<GState> gstateList = new ArrayList<GState>();
TimerPool.getTimer(this, "compile").start();
// get the nodes from the grammar and create states
// for them. Add the non-empty gstates to the gstate list.
TimerPool.getTimer(this, "createGStates").start();
for (GrammarNode grammarNode : grammar.getGrammarNodes()) {
GState gstate = createGState(grammarNode);
gstateList.add(gstate);
}
- TimerPool.getTimer(this, "createGStates").start();
+ TimerPool.getTimer(this, "createGStates").stop();
addStartingPath();
// ensures an initial path to the start state
// Prep all the gstates, by gathering all of the contexts up
// this allows each gstate to know about its surrounding
// contexts
- TimerPool.getTimer(this, " collectContexts").start();
+ TimerPool.getTimer(this, "collectContexts").start();
for (GState gstate : gstateList)
gstate.collectContexts();
TimerPool.getTimer(this, "collectContexts").stop();
// now all gstates know all about their contexts, we can
// expand them fully
TimerPool.getTimer(this, "expandStates").start();
for (GState gstate : gstateList)
gstate.expand();
TimerPool.getTimer(this, "expandStates").stop();
// now that all states are expanded fully, we can connect all
// the states up
TimerPool.getTimer(this, "connectNodes").start();
for (GState gstate : gstateList)
gstate.connect();
TimerPool.getTimer(this, "connectNodes").stop();
SentenceHMMState initialState = findStartingState();
// add an out-of-grammar branch if configured to do so
if (addOutOfGrammarBranch) {
CIPhoneLoop phoneLoop = new CIPhoneLoop(phoneLoopAcousticModel,
logPhoneInsertionProbability);
SentenceHMMState firstBranchState = (SentenceHMMState)
phoneLoop.getSearchGraph().getInitialState();
initialState.connect(getArc(firstBranchState, logOne, logOne,
logOutOfGrammarBranchProbability));
}
searchGraph = new FlatSearchGraph(initialState);
TimerPool.getTimer(this, "compile").stop();
// Now that we are all done, dump out some interesting
// information about the process
if (dumpGStates) {
for (GrammarNode grammarNode : grammar.getGrammarNodes()) {
GState gstate = getGState(grammarNode);
gstate.dumpInfo();
}
}
nodeStateMap = null;
arcPool = null;
return SentenceHMMState.collectStates(initialState);
}
/**
* Returns a new GState for the given GrammarNode.
*
* @return a new GState for the given GrammarNode
*/
protected GState createGState(GrammarNode grammarNode) {
return (new GState(grammarNode));
}
/** Ensures that there is a starting path by adding an empty left context to the strating gstate */
// TODO: Currently the FlatLinguist requires that the initial
// grammar node returned by the Grammar contains a "sil" word
protected void addStartingPath() {
// guarantees a starting path into the initial node by
// adding an empty left context to the starting gstate
GrammarNode node = grammar.getInitialNode();
GState gstate = getGState(node);
gstate.addLeftContext(UnitContext.SILENCE);
}
/**
* Determines if the underlying grammar has changed since we last compiled the search graph
*
* @return true if the grammar has changed
*/
private boolean grammarHasChanged() {
return initialGrammarState == null ||
initialGrammarState != grammar.getInitialNode();
}
/**
* Finds the starting state
*
* @return the starting state
*/
protected SentenceHMMState findStartingState() {
GrammarNode node = grammar.getInitialNode();
GState gstate = getGState(node);
return gstate.getEntryPoint();
}
/**
* Gets a SentenceHMMStateArc. The arc is drawn from a pool of arcs.
*
* @param nextState the next state
* @param logAcousticProbability the log acoustic probability
* @param logLanguageProbability the log language probability
* @param logInsertionProbability the log insertion probability
*/
protected SentenceHMMStateArc getArc(SentenceHMMState nextState,
float logAcousticProbability, float logLanguageProbability,
float logInsertionProbability) {
SentenceHMMStateArc arc = new SentenceHMMStateArc(nextState,
logAcousticProbability,
logLanguageProbability * languageWeight,
logInsertionProbability);
SentenceHMMStateArc pooledArc = (SentenceHMMStateArc) arcPool.get(arc);
if (pooledArc == null) {
arcPool.put(arc, arc);
pooledArc = arc;
actualArcs.value++;
}
totalArcs.value++;
return pooledArc;
}
/**
* Given a grammar node, retrieve the grammar state
*
* @param node the grammar node
* @return the grammar state associated with the node
*/
private GState getGState(GrammarNode node) {
return nodeStateMap.get(node);
}
/** The search graph that is produced by the flat linguist. */
class FlatSearchGraph implements SearchGraph {
/** An array of classes that represents the order in which the states will be returned. */
private SearchState initialState;
/**
* Constructs a flast search graph with the given initial state
*
* @param initialState the initial state
*/
FlatSearchGraph(SearchState initialState) {
this.initialState = initialState;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.SearchGraph#getInitialState()
*/
public SearchState getInitialState() {
return initialState;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.linguist.SearchGraph#getNumStateOrder()
*/
public int getNumStateOrder() {
return 7;
}
}
/**
* This is a nested class that is used to manage the construction of the states in a grammar node. There is one
* GState created for each grammar node. The GState is used to collect the entry and exit points for the grammar
* node and for connecting up the grammar nodes to each other.
*/
protected class GState {
private Map<ContextPair, List<SearchState>> entryPoints = new HashMap<ContextPair, List<SearchState>>();
private Map<ContextPair, List<SearchState>> exitPoints = new HashMap<ContextPair, List<SearchState>>();
private Map<String, SentenceHMMState> existingStates = new HashMap<String, SentenceHMMState>();
private GrammarNode node;
private Set<UnitContext> rightContexts = new HashSet<UnitContext>();
private Set<UnitContext> leftContexts = new HashSet<UnitContext>();
private Set<UnitContext> startingContexts;
private int exitConnections = 0;
// private GrammarArc[] successors = null;
/**
* Creates a GState for a grammar ndoe
*
* @param node the grammar node
*/
protected GState(GrammarNode node) {
this.node = node;
nodeStateMap.put(node, this);
}
/**
* Retrieves the set of starting contexts for this node. The starting contexts are the set of Unit[] with a size
* equal to the maximum right context size.
*
* @return the set of starting contexts acrosss nodes.
*/
private Set<UnitContext> getStartingContexts() {
if (startingContexts == null) {
startingContexts = new HashSet<UnitContext>();
// if this is an empty node, the starting context is
// the set of starting contexts for all successor
// nodes, otherwise, it is built up from each
// pronunciation of this word
if (node.isEmpty()) {
GrammarArc[] arcs = getSuccessors();
for (GrammarArc arc : arcs) {
GState gstate = getGState(arc.getGrammarNode());
startingContexts.addAll(gstate.getStartingContexts());
}
} else {
// int maxSize = getRightContextSize();
Word word = node.getWord();
Pronunciation[] prons = word.getPronunciations(null);
for (Pronunciation pron : prons) {
UnitContext startingContext = getStartingContext(pron);
startingContexts.add(startingContext);
}
}
}
return startingContexts;
}
/**
* Retrieves the starting UnitContext for the given pronunciation
*
* @param pronunciation the pronunciation
* @return a UnitContext representing the starting context of the pronunciation
*/
private UnitContext getStartingContext(Pronunciation pronunciation) {
int maxSize = getRightContextSize();
Unit[] units = pronunciation.getUnits();
int actualSize = Math.min(units.length, maxSize);
Unit[] context = new Unit[actualSize];
System.arraycopy(units, 0, context, 0, context.length);
return UnitContext.get(context);
}
/**
* Retrieves the set of trailing contexts for this node. the trailing contexts are the set of Unit[] with a size
* equal to the maximum left context size that align with the end of the node
*/
Collection<UnitContext> getEndingContexts() {
Collection<UnitContext> endingContexts = new ArrayList<UnitContext>();
if (!node.isEmpty()) {
int maxSize = getLeftContextSize();
Word word = node.getWord();
Pronunciation[] prons = word.getPronunciations(null);
for (Pronunciation pron : prons) {
Unit[] units = pron.getUnits();
int actualSize = Math.min(units.length, maxSize);
Unit[] context = new Unit[actualSize];
int unitIndex = units.length - actualSize;
for (int j = 0; j < context.length; j++) {
context[j] = units[unitIndex++];
}
endingContexts.add(UnitContext.get(context));
}
// add a silence to the ending context since we want to
// include an optional transition to a silence unit at
// the end of all words
endingContexts.add(UnitContext.SILENCE);
}
return endingContexts;
}
/** Visit all of the successor states, and gather their starting contexts into this gstates right context */
private void pullRightContexts() {
GrammarArc[] arcs = getSuccessors();
for (GrammarArc arc : arcs) {
GState gstate = getGState(arc.getGrammarNode());
rightContexts.addAll(gstate.getStartingContexts());
}
}
/**
* Returns the set of succesor arcs for this grammar node. If a successor grammar node has no words we'll
* substitute the successors for that node (avoiding loops of course)
*
* @return an array of successors for this GState
*/
private GrammarArc[] getSuccessors() {
return node.getSuccessors();
}
/** Visit all of the successor states, and push our ending context into the successors left context */
void pushLeftContexts() {
Collection<UnitContext> endingContext = getEndingContexts();
Set<GrammarNode> visitedSet = new HashSet<GrammarNode>();
pushLeftContexts(visitedSet, endingContext);
}
/**
* Pushes the given left context into the successor states. If a successor state is empty, continue to push into
* this empty states successors
*
* @param leftContext the context to push
*/
void pushLeftContexts(Set<GrammarNode> visitedSet, Collection<UnitContext> leftContext) {
if (visitedSet.contains(getNode())) {
return;
} else {
visitedSet.add(getNode());
}
GrammarArc[] arcs = getSuccessors();
for (GrammarArc arc : arcs) {
GState gstate = getGState(arc.getGrammarNode());
gstate.addLeftContext(leftContext);
// if our successor state is empty, also push our
// ending context into the empty nodes successors
if (gstate.getNode().isEmpty()) {
gstate.pushLeftContexts(visitedSet, leftContext);
}
}
}
/**
* Add the given left contexts to the set of left contexts for this state
*
* @param context the set of contexts to add
*/
private void addLeftContext(Collection<UnitContext> context) {
leftContexts.addAll(context);
}
/**
* Adds the given context to the set of left contexts for this state
*
* @param context the context to add
*/
private void addLeftContext(UnitContext context) {
leftContexts.add(context);
}
/** Returns the entry points for a given context pair */
private List getEntryPoints(ContextPair contextPair) {
return entryPoints.get(contextPair);
}
/**
* Gets the context-free entry point to this state
*
* @return the entry point to the state
*/
// TODO: ideally we'll look for entry points with no left
// context, but those don't exist yet so we just take
// the first entry point with an SILENCE left context
// note that this assumes that the first node in a grammar has a
// word and that word is a SIL. Not always a valid assumption.
public SentenceHMMState getEntryPoint() {
ContextPair cp = ContextPair.get(UnitContext.SILENCE,
UnitContext.SILENCE);
List list = getEntryPoints(cp);
if (list != null && list.size() > 0) {
return (SentenceHMMState) list.get(0);
} else {
return null;
}
}
/**
* Returns the exit points for a given context pair
*
* @param contextPair the context pair of interest
* @return the list of exit points
*/
private List getExitPoints(ContextPair contextPair) {
return exitPoints.get(contextPair);
}
/**
* Add the items on the newContexts list to the dest list. Duplicate items are not added.
*
* @param dest where the contexts are added
* @param newContexts the list of new contexts
*/
private void addWithNoDuplicates(List dest, List newContexts) {
// this could potentially be a bottleneck, but the contexts
// lists should be fairly small (<100) items, so this approach
// should be fast enough.
for (Object newContext : newContexts) {
Unit[] context = (Unit[]) newContext;
if (!listContains(dest, context)) {
dest.add(context);
}
}
}
/**
* Deterimes if the give list contains the given context
*
* @param list the list of contexts
* @param context the context to check
*/
private boolean listContains(List list, Unit[] context) {
for (Object aList : list) {
Unit[] item = (Unit[]) aList;
if (Unit.isContextMatch(item, context)) {
return true;
}
}
return false;
}
/**
* Collects the right contexts for this node and pushes this nodes ending context into the next next set of
* nodes.
*/
void collectContexts() {
pullRightContexts();
pushLeftContexts();
}
/** Expands each GState into the sentence HMM States */
void expand() {
// for each left context/starting context pair create a list
// of starting states.
for (UnitContext leftContext : leftContexts) {
for (UnitContext startingContext : getStartingContexts()) {
ContextPair contextPair = ContextPair.get(leftContext, startingContext);
entryPoints.put(contextPair, new ArrayList<SearchState>());
}
}
// if this is a final node don't expand it, just create a
// state and add it to all entry points
if (node.isFinalNode()) {
GrammarState gs = new GrammarState(node);
for (List<SearchState> epList : entryPoints.values()) {
epList.add(gs);
}
} else if (!node.isEmpty()) {
// its a full fledged node with a word
// so expand it. Nodes without words don't need
// to be expanded.
for (UnitContext leftContext : leftContexts) {
expandWord(leftContext);
}
} else {
//if the node is empty, populate the set of entry and exit
//points with a branch state. The branch state
// branches to the succesor entry points for this
// state
// the exit point should consist of the set of
// incoming left contexts and outgoing right contexts
// the 'entryPoint' table already consists of such
// pairs so we can use that
for (ContextPair cp : entryPoints.keySet()) {
List<SearchState> epList = entryPoints.get(cp);
SentenceHMMState bs = new BranchState(cp.getLeftContext().toString(),
cp.getRightContext().toString(), node.getID());
epList.add(bs);
addExitPoint(cp, bs);
}
}
addEmptyEntryPoints();
}
/**
* Adds the set of empty entry points. The list of entry points are tagged with a context pair. The context pair
* represent the left context for the state and the starting contesxt for the state, this allows states to be
* hooked up properly. However, we may be transitioning from states that have no right hand context (CI units
* such as SIL fall into this category). In this case we'd normally have no place to transition to since we add
* entry points for each starting context. To make sure that there are entry points for empty contexts if
* necesary, we go through the list of entry points and find all left contexts that have a right hand context
* size of zero. These entry points will need an entry point with an empty starting context. These entries are
* synthesized and added to the the list of entry points.
*/
private void addEmptyEntryPoints() {
Map<ContextPair, List<SearchState>> emptyEntryPoints = new HashMap<ContextPair, List<SearchState>>();
for (ContextPair cp : entryPoints.keySet()) {
if (needsEmptyVersion(cp)) {
ContextPair emptyContextPair = ContextPair.get(cp
.getLeftContext(), UnitContext.EMPTY);
List<SearchState> epList = emptyEntryPoints.get(emptyContextPair);
if (epList == null) {
epList = new ArrayList<SearchState>();
emptyEntryPoints.put(emptyContextPair, epList);
}
epList.addAll(entryPoints.get(cp));
}
}
entryPoints.putAll(emptyEntryPoints);
}
/**
* Determines if the context pair needs an empty version. A context pair needs an empty version if the left
* context has a max size of zero.
*
* @param cp the contex pair to check
* @return <code>true</code> if the pair needs an empt version
*/
private boolean needsEmptyVersion(ContextPair cp) {
UnitContext left = cp.getLeftContext();
Unit[] units = left.getUnits();
if (units.length > 0) {
return (getRightContextSize(units[0]) < getRightContextSize());
}
return false;
}
/**
* Returns the grammar node of the gstate
*
* @return the grammar node
*/
private GrammarNode getNode() {
return node;
}
/**
* Expand the the word given the left context
*
* @param leftContext the left context
*/
private void expandWord(UnitContext leftContext) {
Word word = node.getWord();
T(" Expanding word " + word + " for lc " + leftContext);
Pronunciation[] pronunciations = word.getPronunciations(null);
for (int i = 0; i < pronunciations.length; i++) {
expandPronunciation(leftContext, pronunciations[i], i);
}
}
/**
* Expand the pronunciation given the left context
*
* @param leftContext the left context
* @param pronunciation the pronunciation to expand
* @param which unique ID for this pronunciation
*/
// Each GState maintains a list of entry points. This list of
// entry points is used when connecting up the end states of
// one GState to the beginning states in another GState. The
// entry points are tagged by a ContextPair which represents
// the left context upon entering the state (the left context
// of the initial units of the state), and the right context
// of the previous states (corresponding to the starting
// contexts for this state).
//
// When expanding a proununciation, the following steps are
// taken:
// 1) Get the starting context for the pronunciation.
// This is the set of units that correspond to the start
// of the pronunciation.
//
// 2) Create a new PronunciationState for the
// pronunciation.
//
// 3) Add the PronunciationState to the entry point table
// (a hash table keyed by the ContextPair(LeftContext,
// StartingContext).
//
// 4) Generate the set of context dependent units, using
// the left and right context of the GState as necessary.
// Note that there will be fan out at the end of the
// pronunciation to allow for units with all of the
// various right contexts. The point where the fan-out
// occurs is the (length of the pronunciation - the max
// right context size).
//
// 5) Attach each cd unit to the tree
//
// 6) Expand each cd unit into the set of HMM states
//
// 7) Attach the optional and looping back silence cd
// unit
//
// 8) Collect the leaf states of the tree and add them to
// the exitStates list.
private void expandPronunciation(UnitContext leftContext,
Pronunciation pronunciation, int which) {
UnitContext startingContext = getStartingContext(pronunciation);
// Add the pronunciation state to the entry point list
// (based upon its left and right context)
String pname = "P(" + pronunciation.getWord() + "[" + leftContext
+ "," + startingContext + "])-G" + getNode().getID();
PronunciationState ps = new PronunciationState(pname,
pronunciation, which);
T(" Expanding " + ps.getPronunciation() + " for lc "
+ leftContext);
ContextPair cp = ContextPair.get(leftContext, startingContext);
List<SearchState> epList = entryPoints.get(cp);
if (epList == null) {
throw new Error("No EP list for context pair " + cp);
} else {
epList.add(ps);
}
Unit[] units = pronunciation.getUnits();
int fanOutPoint = units.length - getRightContextSize();
if (fanOutPoint < 0) {
fanOutPoint = 0;
}
SentenceHMMState tail = ps;
for (int i = 0; tail != null && i < fanOutPoint; i++) {
tail = attachUnit(ps, tail, units, i, leftContext,
UnitContext.EMPTY);
}
SentenceHMMState branchTail = tail;
for (UnitContext finalRightContext : rightContexts) {
tail = branchTail;
for (int i = fanOutPoint; tail != null && i < units.length; i++) {
tail = attachUnit(ps, tail, units, i, leftContext, finalRightContext);
}
}
}
/**
* Attaches the given unit to the given tail, expanding the unit if necessary. If an identical unit is already
* attached, then this path is folded into the existing path.
*
* @param parent the parent state
* @param tail the place to attach the unit to
* @param units the set of units
* @param which the index into the set of units
* @param leftContext the left context for the unit
* @param rightContext the right context for the unit
* @return the tail of the added unit (or null if the path was folded onto an already expanded path.
*/
private SentenceHMMState attachUnit(PronunciationState parent,
SentenceHMMState tail, Unit[] units, int which,
UnitContext leftContext, UnitContext rightContext) {
Unit[] lc = getLC(leftContext, units, which);
Unit[] rc = getRC(units, which, rightContext);
UnitContext actualRightContext = UnitContext.get(rc);
LeftRightContext context = LeftRightContext.get(lc, rc);
Unit cdUnit = unitManager.getUnit(units[which].getName(), units[which]
.isFiller(), context);
UnitState unitState = new ExtendedUnitState(parent, which, cdUnit);
float logInsertionProbability;
if (unitState.getUnit().isFiller()) {
logInsertionProbability = logSilenceInsertionProbability;
} else if (unitState.getWhich() == 0) {
logInsertionProbability = logWordInsertionProbability;
} else {
logInsertionProbability = logUnitInsertionProbability;
}
// check to see if this state already exists, if so
// branch to it and we are done, otherwise, branch to
// the new state and expand it.
SentenceHMMState existingState = getExistingState(unitState);
if (existingState != null) {
attachState(tail, existingState, logOne, logOne,
logInsertionProbability);
// T(" Folding " + existingState);
return null;
} else {
attachState(tail, unitState, logOne, logOne,
logInsertionProbability);
addStateToCache(unitState);
// T(" Attaching " + unitState);
tail = expandUnit(unitState);
// if we are attaching the last state of a word, then
// we add it to the exitPoints table. the exit points
// table is indexed by a ContextPair, consisting of
// the exiting left context and the right context.
if (unitState.isLast()) {
UnitContext nextLeftContext = generateNextLeftContext(
leftContext, units[which]);
ContextPair cp = ContextPair.get(nextLeftContext,
actualRightContext);
// T(" Adding to exitPoints " + cp);
addExitPoint(cp, tail);
// if we have encountered a last unit with a right
// context of silence, then we add a silence unit
// to this unit. the silence unit has a self
// loopback.
if (actualRightContext == UnitContext.SILENCE) {
SentenceHMMState silTail;
UnitState silUnit = new ExtendedUnitState(parent,
which + 1, UnitManager.SILENCE);
SentenceHMMState silExistingState = getExistingState(silUnit);
if (silExistingState != null) {
attachState(tail, silExistingState, logOne, logOne,
logSilenceInsertionProbability);
} else {
attachState(tail, silUnit, logOne, logOne,
logSilenceInsertionProbability);
addStateToCache(silUnit);
silTail = expandUnit(silUnit);
ContextPair silCP = ContextPair.get(
UnitContext.SILENCE, UnitContext.EMPTY);
addExitPoint(silCP, silTail);
}
}
}
return tail;
}
}
/**
* Adds an exit point to this gstate
*
* @param cp the context tag for the state
* @param state the state associated with the tag
*/
private void addExitPoint(ContextPair cp, SentenceHMMState state) {
List<SearchState> list = exitPoints.get(cp);
if (list == null) {
list = new ArrayList<SearchState>();
exitPoints.put(cp, list);
}
list.add(state);
}
/**
* Get the left context for a unit based upon the left context size, the entry left context and the current
* unit.
*
* @param left the entry left context
* @param units the set of units
* @param index the index of the current unit
*/
private Unit[] getLC(UnitContext left, Unit[] units, int index) {
Unit[] leftUnits = left.getUnits();
int maxSize = getLeftContextSize(units[index]);
int curSize = index + leftUnits.length;
int actSize = Math.min(curSize, maxSize);
Unit[] lc = new Unit[actSize];
for (int i = 0; i < lc.length; i++) {
int lcIndex = (index - lc.length) + i;
if (lcIndex < 0) {
lc[i] = leftUnits[leftUnits.length + lcIndex];
} else {
lc[i] = units[lcIndex];
}
}
return lc;
}
/**
* Get the right context for a unit based upon the right context size, the exit right context and the current
* unit.
*
* @param units the set of units
* @param index the index of the current unit
* @param right the exiting right context
*/
private Unit[] getRC(Unit[] units, int index, UnitContext right) {
Unit[] rightUnits = right.getUnits();
int maxSize = getRightContextSize(units[index]);
int curSize = (units.length - (index + 1)) + rightUnits.length;
int actSize = Math.min(curSize, maxSize);
Unit[] rc = new Unit[actSize];
for (int i = 0; i < rc.length; i++) {
int rcIndex = index + i + 1;
if (rcIndex >= units.length) {
rc[i] = rightUnits[rcIndex - units.length];
} else {
rc[i] = units[rcIndex];
}
}
return rc;
}
/**
* Gets the maximum context size for the given unit
*
* @param unit the unit of interest
* @return the maximum left context size for the unit
*/
private int getLeftContextSize(Unit unit) {
if (unit.isFiller()) {
return 0;
} else {
return getLeftContextSize();
}
}
/**
* Gets the maximum context size for the given unit
*
* @param unit the unit of interest
* @return the maximum right context size for the unit
*/
private int getRightContextSize(Unit unit) {
if (unit.isFiller()) {
return 0;
} else {
return getRightContextSize();
}
}
/**
* Returns the size of the left context.
*
* @return the size of the left context
*/
protected int getLeftContextSize() {
return acousticModel.getLeftContextSize();
}
/**
* Returns the size of the right context.
*
* @return the size of the right context
*/
protected int getRightContextSize() {
return acousticModel.getRightContextSize();
}
/**
* Generates the next left context based upon a previous context and a unit
*
* @param prevLeftContext the previous left context
* @param unit the current unit
*/
UnitContext generateNextLeftContext(UnitContext prevLeftContext,
Unit unit) {
Unit[] prevUnits = prevLeftContext.getUnits();
int maxSize = getLeftContextSize();
int curSize = prevUnits.length;
int actSize = Math.min(maxSize, curSize);
Unit[] leftUnits = new Unit[actSize];
System.arraycopy(prevUnits, 1, leftUnits, 0, leftUnits.length - 1);
if (leftUnits.length > 0) {
leftUnits[leftUnits.length - 1] = unit;
}
return UnitContext.get(leftUnits);
}
/**
* Expands the unit into a set of HMMStates. If the unit is a silence unit add an optional loopback to the
* tail.
*
* @param unit the unit to expand
* @return the head of the hmm tree
*/
protected SentenceHMMState expandUnit(UnitState unit) {
SentenceHMMState tail = getHMMStates(unit);
// if the unit is a silence unit add a loop back from the
// tail silence unit
if (unit.getUnit().isSilence()) {
// add the loopback, but don't expand it // anymore
attachState(tail, unit, logOne, logOne,
logSilenceInsertionProbability);
}
return tail;
}
/**
* Given a unit state, return the set of sentence hmm states associated with the unit
*
* @param unitState the unit state of intereset
* @return the hmm tree for the unit
*/
private HMMStateState getHMMStates(UnitState unitState) {
HMMStateState hmmTree;
HMMStateState finalState;
Unit unit = unitState.getUnit();
HMMPosition position = unitState.getPosition();
HMM hmm = acousticModel.lookupNearestHMM(unit, position, false);
HMMState initialState = hmm.getInitialState();
hmmTree = new HMMStateState(unitState, initialState);
attachState(unitState, hmmTree, logOne, logOne, logOne);
addStateToCache(hmmTree);
finalState = expandHMMTree(unitState, hmmTree);
return finalState;
}
/**
* Expands the given hmm state tree
*
* @param parent the parent of the tree
* @param tree the tree to expand
* @return the final state in the tree
*/
private HMMStateState expandHMMTree(UnitState parent, HMMStateState tree) {
HMMStateState retState = tree;
HMMStateArc[] arcs = tree.getHMMState().getSuccessors();
for (HMMStateArc arc : arcs) {
HMMStateState newState;
if (arc.getHMMState().isEmitting()) {
newState = new HMMStateState(parent, arc.getHMMState());
} else {
newState = new NonEmittingHMMState(parent, arc
.getHMMState());
}
SentenceHMMState existingState = getExistingState(newState);
float logProb = arc.getLogProbability();
if (existingState != null) {
attachState(tree, existingState, logProb, logOne, logOne);
} else {
attachState(tree, newState, logProb, logOne, logOne);
addStateToCache(newState);
retState = expandHMMTree(parent, newState);
}
}
return retState;
}
/**
* Connect up all of the GStates. Each state now has a table of exit points. These exit points represent tail
* states for the node. Each of these tail states is tagged with a ContextPair, that indicates what the left
* context is (the exiting context) and the right context (the entering context) for the transition. To connect
* up a state, the connect does the following: 1) Iterate through all of the grammar successors for this state
* 2) Get the 'entry points' for the successor that match the exit points. 3) Hook them up.
* <p/>
* Note that for a task with 1000 words this will involve checking on the order of 35,000,000 connections and
* making about 2,000,000 connections
*/
void connect() {
GrammarArc[] arcs = getSuccessors();
// T("Connecting " + node.getWord());
for (GrammarArc arc : arcs) {
GState gstate = getGState(arc.getGrammarNode());
if (!gstate.getNode().isEmpty()
&& gstate.getNode().getWord().getSpelling().equals(
Dictionary.SENTENCE_START_SPELLING)) {
continue;
}
float probability = arc.getProbability();
// adjust the language probability by the number of
// pronunciations. If there are 3 ways to say the
// word, then each pronunciation gets 1/3 of the total
// probability.
if (spreadWordProbabilitiesAcrossPronunciations
&& !gstate.getNode().isEmpty()) {
int numPronunciations = gstate.getNode().getWord()
.getPronunciations(null).length;
probability -= logMath.linearToLog(numPronunciations);
}
float fprob = probability;
for (ContextPair contextPair : exitPoints.keySet()) {
List destEntryPoints = gstate.getEntryPoints(contextPair);
if (destEntryPoints != null) {
List srcExitPoints = getExitPoints(contextPair);
connect(srcExitPoints, destEntryPoints, fprob);
}
}
}
}
/**
* connect all the states in the source list to the states in the destination list
*
* @param sourceList the set of source states
* @param destList the set of destinatin states.
*/
private void connect(List sourceList, List destList, float logLangProb) {
for (Object aSourceList : sourceList) {
SentenceHMMState sourceState = (SentenceHMMState) aSourceList;
for (Object aDestList : destList) {
SentenceHMMState destState = (SentenceHMMState) aDestList;
sourceState.connect(getArc(destState, logOne, logLangProb,
logOne));
exitConnections++;
}
}
}
/**
* Attaches one SentenceHMMState as a child to another, the transition has the given probability
*
* @param prevState the parent state
* @param nextState the child state
* @param logAcousticProbability the acoustic probability of transition in the LogMath log domain
* @param logLanguageProbablity the language probability of transition in the LogMath log domain
* @param logInsertionProbablity insertion probability of transition in the LogMath log domain
*/
protected void attachState(SentenceHMMState prevState,
SentenceHMMState nextState, float logAcousticProbability,
float logLanguageProbablity, float logInsertionProbablity) {
prevState.connect(getArc(nextState, logAcousticProbability,
logLanguageProbablity, logInsertionProbablity));
if (showCompilationProgress && totalStateCounter++ % 1000 == 0) {
System.out.print(".");
}
}
/**
* Returns all of the states maintained by this gstate
*
* @return the set of all states
*/
public Collection getStates() {
// since pstates are not placed in the cache we have to
// gather those states. All other states are found in the
// existingStates cache.
List<SearchState> allStates = new ArrayList<SearchState>();
allStates.addAll(existingStates.values());
for (List<SearchState> list : entryPoints.values()) {
allStates.addAll(list);
}
return allStates;
}
/**
* Checks to see if a state that matches the given state already exists
*
* @param state the state to check
* @return true if a state with an identical signature already exists.
*/
private SentenceHMMState getExistingState(SentenceHMMState state) {
return existingStates.get(state.getSignature());
}
/**
* Adds the given state to the cache of states
*
* @param state the state to add
*/
private void addStateToCache(SentenceHMMState state) {
existingStates.put(state.getSignature(), state);
}
/** Prints info about this GState */
void dumpInfo() {
System.out.println(" ==== " + this + " ========");
System.out.print("Node: " + node);
if (node.isEmpty()) {
System.out.print(" (Empty)");
} else {
System.out.print(" " + node.getWord());
}
System.out.print(" ep: " + entryPoints.size());
System.out.print(" exit: " + exitPoints.size());
System.out.print(" cons: " + exitConnections);
System.out.print(" tot: " + getStates().size());
System.out.print(" sc: " + getStartingContexts().size());
System.out.print(" rc: " + leftContexts.size());
System.out.println(" lc: " + rightContexts.size());
dumpDetails();
}
/** Dumps the details for a gstate */
void dumpDetails() {
dumpCollection(" entryPoints", entryPoints.keySet());
dumpCollection(" entryPoints states", entryPoints.values());
dumpCollection(" exitPoints", exitPoints.keySet());
dumpCollection(" exitPoints states", exitPoints.values());
dumpNextNodes();
dumpExitPoints(exitPoints.values());
dumpCollection(" startingContexts", getStartingContexts());
dumpCollection(" branchingInFrom", leftContexts);
dumpCollection(" branchingOutTo", rightContexts);
dumpCollection(" existingStates", existingStates.keySet());
}
/** Dumps out the names of the next set of grammar nodes */
private void dumpNextNodes() {
System.out.println(" Next Grammar Nodes: ");
GrammarArc[] arcs = node.getSuccessors();
for (GrammarArc arc : arcs) {
System.out.println(" " + arc.getGrammarNode());
}
}
/**
* Dumps the exit points and their destination states
*
* @param eps the collection of exit points
*/
private void dumpExitPoints(Collection eps) {
for (Object ep : eps) {
List epList = (List) ep;
for (Object anEpList : epList) {
SentenceHMMState state = (SentenceHMMState) anEpList;
System.out.println(" Arcs from: " + state);
SearchStateArc[] arcs = state.getSuccessors();
for (SearchStateArc arc : arcs) {
System.out.println(" " + arc.getState());
}
}
}
}
/**
* Dumps the given collection
*
* @param name the name of the collection
* @param collection the collection to dump
*/
private void dumpCollection(String name, Collection collection) {
System.out.println(" " + name);
for (Object aCollection : collection) {
System.out.println(" " + aCollection.toString());
}
}
/**
* Dumps the given map
*
* @param name the name of the map
* @param map the map to dump
*/
private void dumpMap(String name, Map map) {
System.out.println(" " + name);
for (Object key : map.keySet()) {
Object value = map.get(key);
System.out.println(" key:" + key + " val: " + value);
}
}
/**
* Returns the string representation of the object
*
* @return the string representation of the object
*/
public String toString() {
if (node.isEmpty()) {
return "GState " + node + "(empty)";
} else {
return "GState " + node + " word " + node.getWord();
}
}
}
/**
* Quick and dirty tracing. Traces the string if 'tracing' is true
*
* @param s the string to trace.
*/
private void T(String s) {
if (tracing) {
System.out.println(s);
}
}
}
/** A class that represents a set of units used as a context */
class UnitContext {
private static Map<UnitContext, UnitContext> unitContextMap = new HashMap<UnitContext, UnitContext>();
private Unit[] context;
private int hashCode = 12;
private static int foldedCount = 0;
public final static UnitContext EMPTY = new UnitContext(new Unit[0]);
public final static UnitContext SILENCE;
static {
Unit[] silenceUnit = new Unit[1];
silenceUnit[0] = UnitManager.SILENCE;
SILENCE = new UnitContext(silenceUnit);
unitContextMap.put(EMPTY, EMPTY);
unitContextMap.put(SILENCE, SILENCE);
}
/**
* Creates a UnitContext for the given context. This constructor is not directly accessible, use the factory method
* instead.
*
* @param context the context to wrap with this UnitContext
*/
private UnitContext(Unit[] context) {
this.context = context;
hashCode = 12;
for (int i = 0; i < context.length; i++) {
hashCode += context[i].getName().hashCode() * ((i + 1) * 34);
}
}
/**
* Gets the unit context for the given units. There is a single unit context for each unit combination.
*
* @param units the units of interest
* @return the unit context.
*/
static UnitContext get(Unit[] units) {
UnitContext newUC = new UnitContext(units);
UnitContext oldUC = unitContextMap.get(newUC);
if (oldUC == null) {
unitContextMap.put(newUC, newUC);
} else {
foldedCount++;
newUC = oldUC;
}
return newUC;
}
/**
* Retrieves the units for this context
*
* @return the units associated with this context
*/
public Unit[] getUnits() {
return context;
}
/**
* Determines if the given object is equal to this UnitContext
*
* @param o the object to compare to
* @return <code>true</code> if the objects are equal
*/
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof UnitContext) {
UnitContext other = (UnitContext) o;
if (this.context.length != other.context.length) {
return false;
} else {
for (int i = 0; i < this.context.length; i++) {
if (this.context[i] != other.context[i]) {
return false;
}
}
return true;
}
} else {
return false;
}
}
/**
* Returns a hashcode for this object
*
* @return the hashCode
*/
public int hashCode() {
return hashCode;
}
/** Dumps information about the total number of UnitContext objects */
public static void dumpInfo() {
System.out.println("Total number of UnitContexts : "
+ unitContextMap.size() + " folded: " + foldedCount);
}
/**
* Returns a string representation of this object
*
* @return a string representation
*/
public String toString() {
return LeftRightContext.getContextName(context);
}
}
/**
* A context pair hold a left and starting context. It is used as a hash into the set of starting points for a
* particular gstate
*/
class ContextPair {
static Map<ContextPair, ContextPair> contextPairMap = new HashMap<ContextPair, ContextPair>();
private UnitContext left;
private UnitContext right;
private int hashCode;
/**
* Creates a UnitContext for the given context. This constructor is not directly accessible, use the factory method
* instead.
*
* @param left the left context
* @param right the right context
*/
private ContextPair(UnitContext left, UnitContext right) {
this.left = left;
this.right = right;
hashCode = 99 + left.hashCode() * 113 + right.hashCode();
}
/**
* Gets the ContextPair for the given set of contexts. This is a factory method. If the ContextPair already exists,
* return that one, othewise, create it and store it so it can be reused.
*
* @param left the left context
* @param right the right context
* @return the unit context.
*/
static ContextPair get(UnitContext left, UnitContext right) {
ContextPair newCP = new ContextPair(left, right);
ContextPair oldCP = contextPairMap.get(newCP);
if (oldCP == null) {
contextPairMap.put(newCP, newCP);
} else {
newCP = oldCP;
}
return newCP;
}
/**
* Determines if the given object is equal to this UnitContext
*
* @param o the object to compare to
* @return <code>true</code> if the objects are equal return;
*/
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof ContextPair) {
ContextPair other = (ContextPair) o;
return this.left.equals(other.left)
&& this.right.equals(other.right);
} else {
return false;
}
}
/**
* Returns a hashcode for this object
*
* @return the hashCode
*/
public int hashCode() {
return hashCode;
}
/** Returns a string representation of the object */
public String toString() {
return "CP left: " + left + " right: " + right;
}
/**
* Gets the left unit context
*
* @return the left unit context
*/
public UnitContext getLeftContext() {
return left;
}
/**
* Gets the right unit context
*
* @return the right unit context
*/
public UnitContext getRightContext() {
return right;
}
}
| false | false | null | null |
diff --git a/framework/src/play/src/main/java/play/libs/F.java b/framework/src/play/src/main/java/play/libs/F.java
index 6c4e9297f..ab97f3b3b 100644
--- a/framework/src/play/src/main/java/play/libs/F.java
+++ b/framework/src/play/src/main/java/play/libs/F.java
@@ -1,1015 +1,1015 @@
/*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
package play.libs;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.Arrays;
import play.core.j.FPromiseHelper;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
/**
* Defines a set of functional programming style helpers.
*/
public class F {
/**
* A Callback with no arguments.
*/
public static interface Callback0 {
public void invoke() throws Throwable;
}
/**
* A Callback with a single argument.
*/
public static interface Callback<A> {
public void invoke(A a) throws Throwable;
}
/**
* A Callback with 2 arguments.
*/
public static interface Callback2<A,B> {
public void invoke(A a, B b) throws Throwable;
}
/**
* A Callback with 3 arguments.
*/
public static interface Callback3<A,B,C> {
public void invoke(A a, B b, C c) throws Throwable;
}
/**
* A Function with no arguments.
*/
public static interface Function0<R> {
public R apply() throws Throwable;
}
/**
* A Function with a single argument.
*/
public static interface Function<A,R> {
public R apply(A a) throws Throwable;
}
/**
* A Function with 2 arguments.
*/
public static interface Function2<A,B,R> {
public R apply(A a, B b) throws Throwable;
}
/**
* A Function with 3 arguments.
*/
public static interface Function3<A,B,C,R> {
public R apply(A a, B b, C c) throws Throwable;
}
/**
* A Predicate (boolean-valued function) with a single argument.
*/
public static interface Predicate<A> {
public boolean test(A a) throws Throwable;
}
/**
* A promise to produce a result of type <code>A</code>.
*/
public static class Promise<A> {
private final Future<A> future;
/**
* Creates a Promise that wraps a Scala Future.
*
* @param future The Scala Future to wrap
* @deprecated Since 2.2. Use {@link #wrap(Future)} instead.
*/
@Deprecated
public Promise(Future<A> future) {
this.future = future;
}
/**
* Creates a Promise that wraps a Scala Future.
*
* @param future The Scala Future to wrap
*/
@SuppressWarnings("deprecation")
public static <A> Promise<A> wrap(Future<A> future) {
return new Promise<A>(future);
}
/**
* Combine the given promises into a single promise for the list of results.
*
* The sequencing operations are performed in the default ExecutionContext.
*
* @param promises The promises to combine
* @return A single promise whose methods act on the list of redeemed promises
*/
- public static <A> Promise<List<A>> sequence(Promise<? extends A>... promises){
+ public static <A> Promise<List<A>> sequence(Promise<A>... promises){
return FPromiseHelper.<A>sequence(java.util.Arrays.asList(promises), HttpExecution.defaultContext());
}
/**
* Combine the given promises into a single promise for the list of results.
*
* @param ec Used to execute the sequencing operations.
* @param promises The promises to combine
* @return A single promise whose methods act on the list of redeemed promises
*/
- public static <A> Promise<List<A>> sequence(ExecutionContext ec, Promise<? extends A>... promises){
+ public static <A> Promise<List<A>> sequence(ExecutionContext ec, Promise<A>... promises){
return FPromiseHelper.<A>sequence(java.util.Arrays.asList(promises), ec);
}
/**
* Create a Promise that is redeemed after a timeout.
*
* @param message The message to use to redeem the Promise.
* @param delay The delay (expressed with the corresponding unit).
* @param unit The Unit.
*/
public static <A> Promise<A> timeout(A message, long delay, TimeUnit unit) {
return FPromiseHelper.timeout(message, delay, unit);
}
/**
* Create a Promise that is redeemed after a timeout.
*
* @param message The message to use to redeem the Promise.
* @param delay The delay expressed in milliseconds.
*/
public static <A> Promise<A> timeout(A message, long delay) {
return timeout(message, delay, TimeUnit.MILLISECONDS);
}
/**
* Create a Promise timer that throws a TimeoutException after a
* given timeout.
*
* The returned Promise is usually combined with other Promises.
*
* @return a promise without a real value
* @param delay The delay expressed in milliseconds.
*/
public static <A> Promise<scala.Unit> timeout(long delay) {
return timeout(delay, TimeUnit.MILLISECONDS);
}
/**
* Create a Promise timer that throws a TimeoutException after a
* given timeout.
*
* The returned Promise is usually combined with other Promises.
*
* @param delay The delay (expressed with the corresponding unit).
* @param unit The Unit.
* @return a promise without a real value
*/
public static <A> Promise<scala.Unit> timeout(long delay, TimeUnit unit) {
return FPromiseHelper.timeout(delay, unit);
}
/**
* Combine the given promises into a single promise for the list of results.
*
* The sequencing operations are performed in the default ExecutionContext.
*
* @param promises The promises to combine
* @return A single promise whose methods act on the list of redeemed promises
*/
- public static <A> Promise<List<A>> sequence(Iterable<Promise<? extends A>> promises){
+ public static <A> Promise<List<A>> sequence(Iterable<Promise<A>> promises){
return FPromiseHelper.<A>sequence(promises, HttpExecution.defaultContext());
}
/**
* Combine the given promises into a single promise for the list of results.
*
* @param promises The promises to combine
* @param ec Used to execute the sequencing operations.
* @return A single promise whose methods act on the list of redeemed promises
*/
- public static <A> Promise<List<A>> sequence(Iterable<Promise<? extends A>> promises, ExecutionContext ec){
+ public static <A> Promise<List<A>> sequence(Iterable<Promise<A>> promises, ExecutionContext ec){
return FPromiseHelper.<A>sequence(promises, ec);
}
/**
* Create a new pure promise, that is, a promise with a constant value from the start.
*
* @param a the value for the promise
*/
public static <A> Promise<A> pure(final A a) {
return FPromiseHelper.pure(a);
}
/**
* Create a new promise throwing an exception.
* @param throwable Value to throw
*/
public static <A> Promise<A> throwing(Throwable throwable) {
return FPromiseHelper.throwing(throwable);
}
/**
* Create a Promise which will be redeemed with the result of a given function.
*
* The Function0 will be run in the default ExecutionContext.
*
* @param function Used to fulfill the Promise.
*/
public static <A> Promise<A> promise(Function0<A> function) {
return FPromiseHelper.promise(function, HttpExecution.defaultContext());
}
/**
* Create a Promise which will be redeemed with the result of a given Function0.
*
* @param function Used to fulfill the Promise.
* @param ec The ExecutionContext to run the function in.
*/
public static <A> Promise<A> promise(Function0<A> function, ExecutionContext ec) {
return FPromiseHelper.promise(function, ec);
}
/**
* Create a Promise which, after a delay, will be redeemed with the result of a
* given function. The function will be called after the delay.
*
* The function will be run in the default ExecutionContext.
*
* @param function The function to call to fulfill the Promise.
* @param delay The time to wait.
* @param unit The units to use for the delay.
*/
public static <A> Promise<A> delayed(Function0<A> function, long delay, TimeUnit unit) {
return FPromiseHelper.delayed(function, delay, unit, HttpExecution.defaultContext());
}
/**
* Create a Promise which, after a delay, will be redeemed with the result of a
* given function. The function will be called after the delay.
*
* @param function The function to call to fulfill the Promise.
* @param delay The time to wait.
* @param unit The units to use for the delay.
* @param ec The ExecutionContext to run the Function0 in.
*/
public static <A> Promise<A> delayed(Function0<A> function, long delay, TimeUnit unit, ExecutionContext ec) {
return FPromiseHelper.delayed(function, delay, unit, ec);
}
/**
* Awaits for the promise to get the result.<br>
* Throws a Throwable if the calculation providing the promise threw an exception
*
* @param timeout A user defined timeout
* @param unit timeout for timeout
* @return The promised result
*
*/
public A get(long timeout, TimeUnit unit) {
return FPromiseHelper.get(this, timeout, unit);
}
/**
* Awaits for the promise to get the result.<br>
* Throws a Throwable if the calculation providing the promise threw an exception
*
* @param timeout A user defined timeout in milliseconds
* @return The promised result
*/
public A get(long timeout) {
return FPromiseHelper.get(this, timeout, TimeUnit.MILLISECONDS);
}
/**
* combines the current promise with <code>another</code> promise using `or`
* @param another
*/
public <B> Promise<Either<A,B>> or(Promise<B> another) {
return FPromiseHelper.or(this, another);
}
/**
* Perform the given <code>action</code> callback when the Promise is redeemed.
*
* The callback will be run in the default execution context.
*
* @param action The action to perform.
*/
public void onRedeem(final Callback<A> action) {
FPromiseHelper.onRedeem(this, action, HttpExecution.defaultContext());
}
/**
* Perform the given <code>action</code> callback when the Promise is redeemed.
*
* @param action The action to perform.
* @param ec The ExecutionContext to execute the action in.
*/
public void onRedeem(final Callback<A> action, ExecutionContext ec) {
FPromiseHelper.onRedeem(this, action, ec);
}
/**
* Maps this promise to a promise of type <code>B</code>. The function <code>function</code> is applied as
* soon as the promise is redeemed.
*
* The function will be run in the default execution context.
*
* @param function The function to map <code>A</code> to <code>B</code>.
* @return A wrapped promise that maps the type from <code>A</code> to <code>B</code>.
*/
public <B> Promise<B> map(final Function<? super A, B> function) {
return FPromiseHelper.map(this, function, HttpExecution.defaultContext());
}
/**
* Maps this promise to a promise of type <code>B</code>. The function <code>function</code> is applied as
* soon as the promise is redeemed.
*
* @param function The function to map <code>A</code> to <code>B</code>.
* @param ec The ExecutionContext to execute the function in.
* @return A wrapped promise that maps the type from <code>A</code> to <code>B</code>.
*/
public <B> Promise<B> map(final Function<? super A, B> function, ExecutionContext ec) {
return FPromiseHelper.map(this, function, ec);
}
/**
* Wraps this promise in a promise that will handle exceptions thrown by this Promise.
*
* The function will be run in the default execution context.
*
* @param function The function to handle the exception. This may, for example, convert the exception into something
* of type <code>T</code>, or it may throw another exception, or it may do some other handling.
* @return A wrapped promise that will only throw an exception if the supplied <code>function</code> throws an
* exception.
*/
public Promise<A> recover(final Function<Throwable,A> function) {
return FPromiseHelper.recover(this, function, HttpExecution.defaultContext());
}
/**
* Wraps this promise in a promise that will handle exceptions thrown by this Promise.
*
* @param function The function to handle the exception. This may, for example, convert the exception into something
* of type <code>T</code>, or it may throw another exception, or it may do some other handling.
* @param ec The ExecutionContext to execute the function in.
* @return A wrapped promise that will only throw an exception if the supplied <code>function</code> throws an
* exception.
*/
public Promise<A> recover(final Function<Throwable,A> function, ExecutionContext ec) {
return FPromiseHelper.recover(this, function, ec);
}
/**
* Perform the given <code>action</code> callback if the promise encounters an exception.
*
* This action will be run in the default exceution context.
*
* @param action The action to perform.
*/
public void onFailure(final Callback<Throwable> action) {
FPromiseHelper.onFailure(this, action, HttpExecution.defaultContext());
}
/**
* Perform the given <code>action</code> callback if the promise encounters an exception.
*
* @param action The action to perform.
* @param ec The ExecutionContext to execute the callback in.
*/
public void onFailure(final Callback<Throwable> action, ExecutionContext ec) {
FPromiseHelper.onFailure(this, action, ec);
}
/**
* Maps the result of this promise to a promise for a result of type <code>B</code>, and flattens that to be
* a single promise for <code>B</code>.
*
* The function will be run in the default execution context.
*
* @param function The function to map <code>A</code> to a promise for <code>B</code>.
* @return A wrapped promise for a result of type <code>B</code>
*/
public <B> Promise<B> flatMap(final Function<? super A,Promise<B>> function) {
return FPromiseHelper.flatMap(this, function, HttpExecution.defaultContext());
}
/**
* Maps the result of this promise to a promise for a result of type <code>B</code>, and flattens that to be
* a single promise for <code>B</code>.
*
* @param function The function to map <code>A</code> to a promise for <code>B</code>.
* @param ec The ExecutionContext to execute the function in.
* @return A wrapped promise for a result of type <code>B</code>
*/
public <B> Promise<B> flatMap(final Function<? super A,Promise<B>> function, ExecutionContext ec) {
return FPromiseHelper.flatMap(this, function, ec);
}
/**
* Creates a new promise by filtering the value of the current promise with a predicate.
* If the predicate fails, the resulting promise will fail with a `NoSuchElementException`.
*
* @param predicate The predicate to test the current value.
* @return A new promise with the current value, if the predicate is satisfied.
*/
public Promise<A> filter(final Predicate<? super A> predicate) {
return FPromiseHelper.filter(this, predicate, HttpExecution.defaultContext());
}
/**
* Creates a new promise by filtering the value of the current promise with a predicate.
* If the predicate fails, the resulting promise will fail with a `NoSuchElementException`.
*
* @param predicate The predicate to test the current value.
* @param ec The ExecutionContext to execute the filtering in.
* @return A new promise with the current value, if the predicate is satisfied.
*/
public Promise<A> filter(final Predicate<? super A> predicate, ExecutionContext ec) {
return FPromiseHelper.filter(this, predicate, ec);
}
/**
* Zips the values of this promise with <code>another</code>, and creates a new promise holding the tuple of their results
* @param another
*/
public <B> Promise<Tuple<A, B>> zip(Promise<B> another) {
return wrap(wrapped().zip(another.wrapped())).map(
new Function<scala.Tuple2<A, B>, Tuple<A, B>>() {
public Tuple<A, B> apply(scala.Tuple2<A, B> scalaTuple) {
return new Tuple(scalaTuple._1, scalaTuple._2);
}
}
);
}
/**
* Gets the Scala Future wrapped by this Promise.
*
* @return The Scala Future
*/
public Future<A> wrapped() {
return future;
}
}
/**
* RedeemablePromise is an object which can be completed with a value or failed with an exception.
*
* <pre>
* {@code
* RedeemablePromise<Integer> someFutureInt = RedeemablePromise.empty();
*
* someFutureInt.map(new Function<Integer, Result>() {
* public Result apply(Integer i) {
* // This would apply once the redeemable promise succeed
* return Results.ok("" + i);
* }
* });
*
* // In another thread, you now may complete the RedeemablePromise.
* someFutureInt.success(42);
* }
* </pre>
*/
public static class RedeemablePromise<A> extends Promise<A>{
private final scala.concurrent.Promise<A> promise;
private RedeemablePromise(scala.concurrent.Promise<A> promise) {
super(FPromiseHelper.getFuture(promise));
this.promise = promise;
}
/**
* Creates a new Promise with no value
*/
public static <A> RedeemablePromise<A> empty() {
scala.concurrent.Promise<A> p = FPromiseHelper.empty();
return new RedeemablePromise(p);
}
/**
* Completes the promise with a value.
*
* @param a The value to complete with
*/
public void success(A a) {
this.promise.success(a);
}
/**
* Completes the promise with an exception
*
* @param t The exception to fail the promise with
*/
public void failure(Throwable t) {
this.promise.failure(t);
}
/**
* Completes this promise with the specified Promise, once that Promise is completed.
*
* @param other The value to complete with
* @return A promise giving the result of attempting to complete this promise with the other
* promise. If the completion was successful then the result will be a null value,
* if the completion failed then the result will be an IllegalStateException.
*/
public Promise<Void> completeWith(Promise other) {
return this.completeWith(other, HttpExecution.defaultContext());
}
/**
* Completes this promise with the specified Promise, once that Promise is completed.
*
* @param other The value to complete with
* @param ec An execution context
* @return A promise giving the result of attempting to complete this promise with the other
* promise. If the completion was successful then the result will be a null value,
* if the completion failed then the result will be an IllegalStateException.
*/
public Promise<Void> completeWith(Promise other, ExecutionContext ec) {
Promise<Void> r = Promise.wrap(FPromiseHelper.completeWith(this.promise, other.future, ec));
return r;
}
/**
* Completes this promise with the specified Promise, once that Promise is completed.
*
* @param other The value to complete with
* @return A promise giving the result of attempting to complete this promise with the other
* promise. If the completion was successful then the result will be true, if the
* completion couldn't occur then the result will be false.
*/
public Promise<Boolean> tryCompleteWith(Promise other) {
return this.tryCompleteWith(other, HttpExecution.defaultContext());
}
/**
* Completes this promise with the specified Promise, once that Promise is completed.
*
* @param other The value to complete with
* @param ec An execution context
* @return A promise giving the result of attempting to complete this promise with the other
* promise. If the completion was successful then the result will be true, if the
* completion couldn't occur then the result will be false.
*/
public Promise<Boolean> tryCompleteWith(Promise other, ExecutionContext ec) {
Promise<Boolean> r = Promise.wrap(FPromiseHelper.tryCompleteWith(this.promise, other.future, ec));
return r;
}
}
/**
* Represents optional values. Instances of <code>Option</code> are either an instance of <code>Some</code> or the object <code>None</code>.
*/
public static abstract class Option<T> implements Collection<T> {
/**
* Is the value of this option defined?
*
* @return <code>true</code> if the value is defined, otherwise <code>false</code>.
*/
public abstract boolean isDefined();
@Override
public boolean isEmpty() {
return !isDefined();
}
/**
* Returns the value if defined.
*
* @return The value if defined, otherwise <code>null</code>.
*/
public abstract T get();
/**
* Constructs a <code>None</code> value.
*
* @return None
*/
public static <T> None<T> None() {
return new None<T>();
}
/**
* Construct a <code>Some</code> value.
*
* @param value The value to make optional
* @return Some <code>T</code>.
*/
public static <T> Some<T> Some(T value) {
return new Some<T>(value);
}
/**
* Get the value if defined, otherwise return the supplied <code>defaultValue</code>.
*
* @param defaultValue The value to return if the value of this option is not defined
* @return The value of this option, or <code>defaultValue</code>.
*/
public T getOrElse(T defaultValue) {
if(isDefined()) {
return get();
} else {
return defaultValue;
}
}
/**
* Map this option to another value.
*
* @param function The function to map the option using.
* @return The mapped option.
* @throws RuntimeException if <code>function</code> threw an Exception. If the exception is a
* <code>RuntimeException</code>, it will be rethrown as is, otherwise it will be wrapped in a
* <code>RuntimeException</code>.
*/
public <A> Option<A> map(Function<T,A> function) {
if(isDefined()) {
try {
return Some(function.apply(get()));
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
} else {
return None();
}
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new UnsupportedOperationException();
}
}
/**
* Construct a <code>Some</code> value.
*
* @param value The value
* @return Some value.
*/
public static <A> Some<A> Some(A value) {
return new Some<A>(value);
}
/**
* Constructs a <code>None</code> value.
*
* @return None.
*/
public static None None() {
return new None();
}
/**
* Represents non-existent values.
*/
public static class None<T> extends Option<T> {
@Override
public boolean isDefined() {
return false;
}
@Override
public int size() {
return 0;
}
@Override
public T get() {
throw new IllegalStateException("No value");
}
public Iterator<T> iterator() {
return Collections.<T>emptyList().iterator();
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return c.size() == 0;
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <R> R[] toArray(R[] r) {
Arrays.fill(r, null);
return r;
}
@Override
public String toString() {
return "None";
}
}
/**
* Represents existing values of type <code>T</code>.
*/
public static class Some<T> extends Option<T> {
final T value;
public Some(T value) {
this.value = value;
}
@Override
public boolean isDefined() {
return true;
}
@Override
public int size() {
return 1;
}
@Override
public T get() {
return value;
}
public Iterator<T> iterator() {
return Collections.singletonList(value).iterator();
}
@Override
public boolean contains(Object o) {
return o != null && o.equals(value);
}
@Override
public boolean containsAll(Collection<?> c) {
return (c.size() == 1) && (c.toArray()[0].equals(value));
}
@Override
public Object[] toArray() {
Object[] result = new Object[1];
result[0] = value;
return result;
}
@Override
public <R> R[] toArray(R[] r) {
if(r.length == 0){
R[] array = (R[])Arrays.copyOf(r, 1);
array[0] = (R)value;
return array;
}else{
Arrays.fill(r, 1, r.length, null);
r[0] = (R)value;
return r;
}
}
@Override
public String toString() {
return "Some(" + value + ")";
}
}
/**
* Represents a value of one of two possible types (a disjoint union)
*/
public static class Either<A, B> {
/**
* The left value.
*/
final public Option<A> left;
/**
* The right value.
*/
final public Option<B> right;
private Either(Option<A> left, Option<B> right) {
this.left = left;
this.right = right;
}
/**
* Constructs a left side of the disjoint union, as opposed to the Right side.
*
* @param value The value of the left side
* @return A left sided disjoint union
*/
public static <A, B> Either<A, B> Left(A value) {
return new Either<A, B>(Some(value), None());
}
/**
* Constructs a right side of the disjoint union, as opposed to the Left side.
*
* @param value The value of the right side
* @return A right sided disjoint union
*/
public static <A, B> Either<A, B> Right(B value) {
return new Either<A, B>(None(), Some(value));
}
@Override
public String toString() {
return "Either(left: " + left + ", right: " + right + ")";
}
}
/**
* A pair - a tuple of the types <code>A</code> and <code>B</code>.
*/
public static class Tuple<A, B> {
final public A _1;
final public B _2;
public Tuple(A _1, B _2) {
this._1 = _1;
this._2 = _2;
}
@Override
public String toString() {
return "Tuple2(_1: " + _1 + ", _2: " + _2 + ")";
}
}
/**
* Constructs a tuple of A,B
*
* @param a The a value
* @param b The b value
* @return The tuple
*/
public static <A, B> Tuple<A, B> Tuple(A a, B b) {
return new Tuple<A, B>(a, b);
}
/**
* A tuple of A,B,C
*/
public static class Tuple3<A, B, C> {
final public A _1;
final public B _2;
final public C _3;
public Tuple3(A _1, B _2, C _3) {
this._1 = _1;
this._2 = _2;
this._3 = _3;
}
@Override
public String toString() {
return "Tuple3(_1: " + _1 + ", _2: " + _2 + ", _3:" + _3 + ")";
}
}
/**
* Constructs a tuple of A,B,C
*
* @param a The a value
* @param b The b value
* @param c The c value
* @return The tuple
*/
public static <A, B, C> Tuple3<A, B, C> Tuple3(A a, B b, C c) {
return new Tuple3<A, B, C>(a, b, c);
}
/**
* A tuple of A,B,C,D
*/
public static class Tuple4<A, B, C, D> {
final public A _1;
final public B _2;
final public C _3;
final public D _4;
public Tuple4(A _1, B _2, C _3, D _4) {
this._1 = _1;
this._2 = _2;
this._3 = _3;
this._4 = _4;
}
@Override
public String toString() {
return "Tuple4(_1: " + _1 + ", _2: " + _2 + ", _3:" + _3 + ", _4:" + _4 + ")";
}
}
/**
* Constructs a tuple of A,B,C,D
*
* @param a The a value
* @param b The b value
* @param c The c value
* @param d The d value
* @return The tuple
*/
public static <A, B, C, D> Tuple4<A, B, C, D> Tuple4(A a, B b, C c, D d) {
return new Tuple4<A, B, C, D>(a, b, c, d);
}
/**
* A tuple of A,B,C,D,E
*/
public static class Tuple5<A, B, C, D, E> {
final public A _1;
final public B _2;
final public C _3;
final public D _4;
final public E _5;
public Tuple5(A _1, B _2, C _3, D _4, E _5) {
this._1 = _1;
this._2 = _2;
this._3 = _3;
this._4 = _4;
this._5 = _5;
}
@Override
public String toString() {
return "Tuple5(_1: " + _1 + ", _2: " + _2 + ", _3:" + _3 + ", _4:" + _4 + ", _5:" + _5 + ")";
}
}
/**
* Constructs a tuple of A,B,C,D,E
*
* @param a The a value
* @param b The b value
* @param c The c value
* @param d The d value
* @param e The e value
* @return The tuple
*/
public static <A, B, C, D, E> Tuple5<A, B, C, D, E> Tuple5(A a, B b, C c, D d, E e) {
return new Tuple5<A, B, C, D, E>(a, b, c, d, e);
}
}
diff --git a/framework/src/play/src/test/java/play/PromiseTest.java b/framework/src/play/src/test/java/play/PromiseTest.java
index 91248b524..41ff8e83b 100644
--- a/framework/src/play/src/test/java/play/PromiseTest.java
+++ b/framework/src/play/src/test/java/play/PromiseTest.java
@@ -1,120 +1,134 @@
/*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
package play;
+import java.util.Arrays;
+import java.util.List;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import play.libs.F;
import static org.fest.assertions.Assertions.assertThat;
public class PromiseTest {
// timeout
private Long t = 1000L;
@Test
public void testSupertypeMap() {
F.Promise<Integer> a = F.Promise.pure(1);
F.Promise<String> b = a.map(new F.Function<Object, String>() {
public String apply(Object o) {
return o.toString();
}
});
assertThat(b.get(t)).isEqualTo("1");
}
@Test
public void testSupertypeFlatMap() {
F.Promise<Integer> a = F.Promise.pure(1);
F.Promise<String> b = a.flatMap(new F.Function<Object, F.Promise<String>>() {
public F.Promise<String> apply(Object o) {
return F.Promise.pure(o.toString());
}
});
assertThat(b.get(t)).isEqualTo("1");
}
@Test
public void testEmptyPromise() {
F.RedeemablePromise<Integer> a = F.RedeemablePromise.empty();
F.Promise<String> b = a.map(new F.Function<Integer, String>() {
public String apply(Integer i) {
return i.toString();
}
});
a.success(1);
assertThat(a.get(t)).isEqualTo(1);
assertThat(b.get(t)).isEqualTo("1");
}
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testFailPromise() {
exception.expect(RuntimeException.class);
F.RedeemablePromise<Integer> a = F.RedeemablePromise.empty();
a.failure(new RuntimeException("test"));
a.get(t);
}
@Test
public void testDualSuccessPromise() {
exception.expect(IllegalStateException.class);
F.RedeemablePromise<Integer> a = F.RedeemablePromise.empty();
a.success(1);
a.success(2);
}
@Test
public void testCompleteWithPromise() {
F.RedeemablePromise<Integer> a = F.RedeemablePromise.empty();
F.RedeemablePromise<Integer> b = F.RedeemablePromise.empty();
a.success(1);
F.Promise<Void> c = b.completeWith(a);
assertThat(c.get(t)).isEqualTo(null);
assertThat(b.get(t)).isEqualTo(1);
// Complete a second time
F.Promise<Void> d = b.completeWith(a);
// And we should get an exception !
exception.expect(IllegalStateException.class);
exception.expectMessage("Promise already completed.");
d.get(t);
}
@Test
public void testTryCompleteWithPromise() {
F.RedeemablePromise<Integer> a = F.RedeemablePromise.empty();
F.RedeemablePromise<Integer> b = F.RedeemablePromise.empty();
a.success(1);
// Assertions not placed on bottom on this method to enforce
// the Promise to be completed and avoid raceconditions
F.Promise<Boolean> c = b.tryCompleteWith(a);
assertThat(c.get(t)).isEqualTo(true);
F.Promise<Boolean> d = b.tryCompleteWith(a);
assertThat(d.get(t)).isEqualTo(false);
assertThat(b.get(t)).isEqualTo(1);
}
+
+ @Test
+ public void testCombinePromiseSequence() {
+ F.Promise<Integer> a = F.Promise.pure(1);
+ F.Promise<Integer> b = F.Promise.pure(2);
+ F.Promise<Integer> c = F.Promise.pure(3);
+
+ F.Promise<List<Integer>> combined = F.Promise.sequence(Arrays.asList(a, b, c));
+
+ assertThat(combined.get(t)).isEqualTo(Arrays.asList(1, 2, 3));
+ }
}
| false | false | null | null |
diff --git a/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java b/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java
index 0cfbcf1..0feaa90 100644
--- a/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java
+++ b/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java
@@ -1,1090 +1,1090 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.db.api.SqlReader;
import org.sakaiproject.db.api.SqlService;
import org.sakaiproject.entity.api.Edit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.serialize.EntityParseException;
import org.sakaiproject.entity.api.serialize.EntityReader;
import org.sakaiproject.entity.api.serialize.EntityReaderHandler;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.time.cover.TimeService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <p>
* BaseDbSingleStorage is a class that stores Resources (of some type) in a database, <br />
* provides locked access, and generally implements a services "storage" class. The <br />
* service's storage class can extend this to provide covers to turn Resource and <br />
* Edit into something more type specific to the service.
* </p>
* <p>
* Note: the methods here are all "id" based, with the following assumptions: <br /> - just the Resource Id field is enough to distinguish one
* Resource from another <br /> - a resource's reference is based on no more than the resource id <br /> - a resource's id cannot change.
* </p>
* <p>
* In order to handle Unicode characters properly, the SQL statements executed by this class <br />
* should not embed Unicode characters into the SQL statement text; rather, Unicode values <br />
* should be inserted as fields in a PreparedStatement. Databases handle Unicode better in fields.
* </p>
*/
public class BaseDbSingleStorage implements DbSingleStorage
{
public static final String STORAGE_FIELDS = "XML";
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseDbSingleStorage.class);
/** Table name for resource records. */
protected String m_resourceTableName = null;
/** The field in the resource table that holds the resource id. */
protected String m_resourceTableIdField = null;
/** The additional field names in the resource table that go between the two ids and the xml */
protected String[] m_resourceTableOtherFields = null;
/** The xml tag name for the element holding each actual resource entry. */
protected String m_resourceEntryTagName = null;
/** If true, we do our locks in the remote database. */
protected boolean m_locksAreInDb = false;
/** If true, we do our locks in the remove database using a separate locking table. */
protected boolean m_locksAreInTable = true;
/** The StorageUser to callback for new Resource and Edit objects. */
protected StorageUser m_user = null;
/**
* Locks, keyed by reference, holding Connections (or, if locks are done locally, holding an Edit).
*/
protected Hashtable m_locks = null;
/** If set, we treat reasource ids as case insensitive. */
protected boolean m_caseInsensitive = false;
/** Injected (by constructor) SqlService. */
protected SqlService m_sql = null;
/** contains a map of the database dependent handlers. */
protected static Map<String, SingleStorageSql> databaseBeans;
/** The db handler we are using. */
protected SingleStorageSql singleStorageSql;
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#setDatabaseBeans(java.util.Map)
*/
public void setDatabaseBeans(Map databaseBeans)
{
this.databaseBeans = databaseBeans;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#setSingleStorageSql(java.lang.String)
*/
public void setSingleStorageSql(String vendor)
{
this.singleStorageSql = (databaseBeans.containsKey(vendor) ? databaseBeans.get(vendor) : databaseBeans.get("default"));
}
// since spring is not used and this class is instatiated directly, we need to "inject" these values ourselves
static
{
databaseBeans = new Hashtable<String, SingleStorageSql>();
databaseBeans.put("db2", new SingleStorageSqlDb2());
databaseBeans.put("default", new SingleStorageSqlDefault());
databaseBeans.put("hsql", new SingleStorageSqlHSql());
databaseBeans.put("mssql", new SingleStorageSqlMsSql());
databaseBeans.put("mysql", new SingleStorageSqlMySql());
databaseBeans.put("oracle", new SingleStorageSqlOracle());
}
/**
* Construct.
*
* @param resourceTableName
* Table name for resources.
* @param resourceTableIdField
* The field in the resource table that holds the id.
* @param resourceTableOtherFields
* The other fields in the resource table (between the two id and the xml fields).
* @param locksInDb
* If true, we do our locks in the remote database, otherwise we do them here.
* @param resourceEntryName
* The xml tag name for the element holding each actual resource entry.
* @param user
* The StorageUser class to call back for creation of Resource and Edit objects.
* @param sqlService
* The SqlService.
*/
public BaseDbSingleStorage(String resourceTableName, String resourceTableIdField, String[] resourceTableOtherFields, boolean locksInDb,
String resourceEntryName, StorageUser user, SqlService sqlService)
{
m_resourceTableName = resourceTableName;
m_resourceTableIdField = resourceTableIdField;
m_resourceTableOtherFields = resourceTableOtherFields;
m_locksAreInDb = locksInDb;
m_resourceEntryTagName = resourceEntryName;
m_user = user;
m_sql = sqlService;
setSingleStorageSql(m_sql.getVendor());
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#open()
*/
public void open()
{
// setup for locks
m_locks = new Hashtable();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#close()
*/
public void close()
{
if (!m_locks.isEmpty())
{
M_log.warn("close(): locks remain!");
// %%%
}
m_locks.clear();
m_locks = null;
}
/**
* Read one Resource from xml
*
* @param xml
* An string containing the xml which describes the resource.
* @return The Resource object created from the xml.
*/
protected Entity readResource(String xml)
{
try
{
if (m_user instanceof SAXEntityReader)
{
SAXEntityReader sm_user = (SAXEntityReader) m_user;
DefaultEntityHandler deh = sm_user.getDefaultHandler(sm_user
.getServices());
Xml.processString(xml, deh);
return deh.getEntity();
}
else
{
// read the xml
Document doc = Xml.readDocumentFromString(xml);
// verify the root element
Element root = doc.getDocumentElement();
if (!root.getTagName().equals(m_resourceEntryTagName))
{
M_log.warn("readResource(): not = " + m_resourceEntryTagName + " : "
+ root.getTagName());
return null;
}
// re-create a resource
Entity entry = m_user.newResource(null, root);
return entry;
}
}
catch (Exception e)
{
M_log.debug("readResource(): ", e);
return null;
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#checkResource(java.lang.String)
*/
public boolean checkResource(String id)
{
// just see if the record exists
String sql = singleStorageSql.getResourceIdSql(m_resourceTableIdField, m_resourceTableName);
Object fields[] = new Object[1];
fields[0] = caseId(id);
List ids = m_sql.dbRead(sql, fields, null);
return (!ids.isEmpty());
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getResource(java.lang.String)
*/
public Entity getResource(String id)
{
Entity entry = null;
// get the user from the db
String sql = singleStorageSql.getXmlSql(m_resourceTableIdField, m_resourceTableName);
Object fields[] = new Object[1];
fields[0] = caseId(id);
List xml = m_sql.dbRead(sql, fields, null);
if (!xml.isEmpty())
{
// create the Resource from the db xml
entry = readResource((String) xml.get(0));
}
return entry;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#isEmpty()
*/
public boolean isEmpty()
{
// count
int count = countAllResources();
return (count == 0);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResources()
*/
public List getAllResources()
{
List all = new Vector();
// read all users from the db
String sql = singleStorageSql.getXmlSql(m_resourceTableName);
// %%% + "order by " + m_resourceTableOrderField + " asc";
List xml = m_sql.dbRead(sql);
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) all.add(entry);
}
}
return all;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResources(int, int)
*/
public List getAllResources(int first, int last)
{
String sql = singleStorageSql.getXmlSql(m_resourceTableIdField, m_resourceTableName, first, last);
Object[] fields = singleStorageSql.getXmlFields(first, last);
List xml = m_sql.dbRead(sql, fields, null);
List rv = new Vector();
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) rv.add(entry);
}
}
return rv;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#countAllResources()
*/
public int countAllResources()
{
List all = new Vector();
// read all count
String sql = singleStorageSql.getNumRowsSql(m_resourceTableName);
List results = m_sql.dbRead(sql, null, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
int count = result.getInt(1);
return new Integer(count);
}
catch (SQLException ignore)
{
return null;
}
}
});
if (results.isEmpty()) return 0;
return ((Integer) results.get(0)).intValue();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#countSelectedResourcesWhere(java.lang.String)
*/
public int countSelectedResourcesWhere(String sqlWhere)
{
List all = new Vector();
// read all where count
String sql = singleStorageSql.getNumRowsSql(m_resourceTableName, sqlWhere);
List results = m_sql.dbRead(sql, null, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
int count = result.getInt(1);
return new Integer(count);
}
catch (SQLException ignore)
{
return null;
}
}
});
if (results.isEmpty()) return 0;
return ((Integer) results.get(0)).intValue();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResourcesWhere(java.lang.String, java.lang.String)
*/
public List getAllResourcesWhere(String field, String value)
{
// read all users from the db
String sql = singleStorageSql.getXmlSql(field, m_resourceTableName);
Object[] fields = new Object[1];
fields[0] = value;
// %%% + "order by " + m_resourceTableOrderField + " asc";
return loadResources(sql, fields);
}
protected List loadResources(String sql, Object[] fields)
{
List all = m_sql.dbRead(sql, fields, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
// create the Resource from the db xml
String xml = result.getString(1);
Entity entry = readResource(xml);
return entry;
}
catch (SQLException ignore)
{
return null;
}
}
});
return all;
}
/**
* Get a limited number of Resources a given field matches a given value, returned in ascending order
* by another field. The limit on the number of rows is specified by values for the first item to be
* retrieved (indexed from 0) and the maxCount.
* @param selectBy The name of a field to be used in selecting resources.
* @param selectByValue The value to select.
* @param orderBy The name of a field to be used in ordering the resources.
* @param tableName The table on which the query is to operate
* @param first A non-negative integer indicating the first record to return
* @param maxCount A positive integer indicating the maximum number of rows to return
* @return The list of all Resources that meet the criteria.
*/
public List getAllResourcesWhere(String selectBy, String selectByValue, String orderBy, int first, int maxCount)
{
// read all users from the db
String sql = singleStorageSql.getXmlWhereLimitSql(selectBy, orderBy, m_resourceTableName, first, maxCount);
Object[] fields = new Object[1];
fields[0] = selectByValue;
// %%% + "order by " + m_resourceTableOrderField + " asc";
return loadResources(sql, fields);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResourcesWhereLike(java.lang.String, java.lang.String)
*/
public List getAllResourcesWhereLike(String field, String value)
{
String sql = singleStorageSql.getXmlLikeSql(field, m_resourceTableName);
Object[] fields = new Object[1];
fields[0] = value;
// %%% + "order by " + m_resourceTableOrderField + " asc";
return loadResources(sql, fields);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getSelectedResources(org.sakaiproject.javax.Filter)
*/
public List getSelectedResources(final Filter filter)
{
List all = new Vector();
// read all users from the db
String sql = singleStorageSql.getXmlAndFieldSql(m_resourceTableIdField, m_resourceTableName);
// %%% + "order by " + m_resourceTableOrderField + " asc";
List xml = m_sql.dbRead(sql, null, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
// read the id m_resourceTableIdField
String id = result.getString(1);
// read the xml
String xml = result.getString(2);
if (!filter.accept(caseId(id))) return null;
return xml;
}
catch (SQLException ignore)
{
return null;
}
}
});
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) all.add(entry);
}
}
return all;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getSelectedResourcesWhere(java.lang.String)
*/
public List getSelectedResourcesWhere(String sqlWhere)
{
List all = new Vector();
// read all users from the db
String sql = singleStorageSql.getXmlWhereSql(m_resourceTableName, sqlWhere);
// %%% + "order by " + m_resourceTableOrderField + " asc";
List xml = m_sql.dbRead(sql);
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) all.add(entry);
}
}
return all;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#putResource(java.lang.String, java.lang.Object[])
*/
public Edit putResource(String id, Object[] others)
{
// create one with just the id, and perhaps some other fields as well
Entity entry = m_user.newResource(null, id, others);
// form the XML and SQL for the insert
Document doc = Xml.createDocument();
entry.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
String statement = // singleStorageSql.
"insert into " + m_resourceTableName + insertFields(m_resourceTableIdField, m_resourceTableOtherFields, "XML") + " values ( ?, "
+ valuesParams(m_resourceTableOtherFields) + " ? )";
Object[] flds = m_user.storageFields(entry);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 2];
System.arraycopy(flds, 0, fields, 1, flds.length);
fields[0] = caseId(entry.getId());
fields[fields.length - 1] = xml;
// process the insert
boolean ok = m_sql.dbWrite(statement, fields);
// if this failed, assume a key conflict (i.e. id in use)
if (!ok) return null;
// now get a lock on the record for edit
Edit edit = editResource(id);
if (edit == null)
{
M_log.warn("putResource(): didn't get a lock!");
return null;
}
return edit;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#putDeleteResource(java.lang.String, java.lang.String, java.lang.String, java.lang.Object[])
*/
public Edit putDeleteResource(String id, String uuid, String userId, Object[] others)
{
Entity entry = m_user.newResource(null, id, others);
// form the XML and SQL for the insert
Document doc = Xml.createDocument();
entry.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
String statement = "insert into " + m_resourceTableName
+ insertDeleteFields(m_resourceTableIdField, m_resourceTableOtherFields, "RESOURCE_UUID", "DELETE_DATE", "DELETE_USERID", "XML")
+ " values ( ?, " + valuesParams(m_resourceTableOtherFields) + " ? ,? ,? ,?)";
Object[] flds = m_user.storageFields(entry);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 5];
System.arraycopy(flds, 0, fields, 1, flds.length);
fields[0] = caseId(entry.getId());
// uuid added here
fields[fields.length - 4] = uuid;
// date added here
fields[fields.length - 3] = TimeService.newTime();// .toStringLocalDate();
// userId added here
fields[fields.length - 2] = userId;
fields[fields.length - 1] = xml;
// process the insert
boolean ok = m_sql.dbWrite(statement, fields);
// if this failed, assume a key conflict (i.e. id in use)
if (!ok) return null;
// now get a lock on the record for edit
Edit edit = editResource(id);
if (edit == null)
{
M_log.warn("putResourceDelete(): didn't get a lock!");
return null;
}
return edit;
}
/** Construct the SQL statement */
protected String insertDeleteFields(String before, String[] fields, String uuid, String date, String userId, String after)
{
StringBuilder buf = new StringBuilder();
buf.append(" (");
buf.append(before);
buf.append(",");
if (fields != null)
{
for (int i = 0; i < fields.length; i++)
{
buf.append(fields[i] + ",");
}
}
buf.append(uuid);
buf.append(",");
buf.append(date);
buf.append(",");
buf.append(userId);
buf.append(",");
buf.append(after);
buf.append(")");
return buf.toString();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#commitDeleteResource(org.sakaiproject.entity.api.Edit, java.lang.String)
*/
public void commitDeleteResource(Edit edit, String uuid)
{
// form the SQL statement and the var w/ the XML
Document doc = Xml.createDocument();
edit.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
Object[] flds = m_user.storageFields(edit);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 2];
System.arraycopy(flds, 0, fields, 0, flds.length);
fields[fields.length - 2] = xml;
fields[fields.length - 1] = uuid;// caseId(edit.getId());
String statement = "update " + m_resourceTableName + " set " + updateSet(m_resourceTableOtherFields) + " XML = ? where ( RESOURCE_UUID = ? )";
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("commitResource(): edit not in locks");
return;
}
// update, commit, release the lock's connection
m_sql.dbUpdateCommit(statement, fields, null, lock);
// remove the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// process the update
m_sql.dbWrite(statement, fields);
// remove the lock
statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("commit: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// just process the update
m_sql.dbWrite(statement, fields);
// remove the lock
m_locks.remove(edit.getReference());
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#editResource(java.lang.String)
*/
public Edit editResource(String id)
{
Edit edit = null;
if (m_locksAreInDb)
{
if ("oracle".equals(m_sql.getVendor()))
{
// read the record and get a lock on it (non blocking)
String statement = "select XML from " + m_resourceTableName + " where ( " + m_resourceTableIdField + " = '"
+ Validator.escapeSql(caseId(id)) + "' )" + " for update nowait";
StringBuilder result = new StringBuilder();
Connection lock = m_sql.dbReadLock(statement, result);
// for missing or already locked...
if ((lock == null) || (result.length() == 0)) return null;
// make first a Resource, then an Edit
Entity entry = readResource(result.toString());
edit = m_user.newResourceEdit(null, entry);
// store the lock for this object
m_locks.put(entry.getReference(), lock);
}
else
{
throw new UnsupportedOperationException("Record locking only available when configured with Oracle database");
}
}
// if the locks are in a separate table in the db
else if (m_locksAreInTable)
{
// read the record - fail if not there
Entity entry = getResource(id);
if (entry == null) return null;
// write a lock to the lock table - if we can do it, we get the lock
String statement = singleStorageSql.getInsertLocks();
// we need session id and user id
String sessionId = UsageSessionService.getSessionId();
if (sessionId == null)
{
- sessionId = "";
+ sessionId = ""; // TODO - "" gets converted to a null and will never be able to be cleaned up -AZ (SAK-11841)
}
// collect the fields
Object fields[] = new Object[4];
fields[0] = m_resourceTableName;
fields[1] = internalRecordId(caseId(id));
fields[2] = TimeService.newTime();
fields[3] = sessionId;
// add the lock - if fails, someone else has the lock
boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
if (!ok)
{
return null;
}
// we got the lock! - make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
}
// otherwise, get the lock locally
else
{
// get the entry, and check for existence
Entity entry = getResource(id);
if (entry == null) return null;
// we only sync this getting - someone may release a lock out of sync
synchronized (m_locks)
{
// if already locked
if (m_locks.containsKey(entry.getReference())) return null;
// make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
// store the edit in the locks by reference
m_locks.put(entry.getReference(), edit);
}
}
return edit;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#commitResource(org.sakaiproject.entity.api.Edit)
*/
public void commitResource(Edit edit)
{
// form the SQL statement and the var w/ the XML
Document doc = Xml.createDocument();
edit.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
Object[] flds = m_user.storageFields(edit);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 2];
System.arraycopy(flds, 0, fields, 0, flds.length);
fields[fields.length - 2] = xml;
fields[fields.length - 1] = caseId(edit.getId());
String statement = "update " + m_resourceTableName + " set " + updateSet(m_resourceTableOtherFields) + " XML = ? where ( "
+ m_resourceTableIdField + " = ? )";
// singleStorageSql.getUpdateXml(m_resourceTableIdField, m_resourceTableOtherFields, m_resourceTableName);
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("commitResource(): edit not in locks");
return;
}
// update, commit, release the lock's connection
m_sql.dbUpdateCommit(statement, fields, null, lock);
// remove the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// process the update
m_sql.dbWrite(statement, fields);
// remove the lock
statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("commit: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// just process the update
m_sql.dbWrite(statement, fields);
// remove the lock
m_locks.remove(edit.getReference());
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#cancelResource(org.sakaiproject.entity.api.Edit)
*/
public void cancelResource(Edit edit)
{
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("cancelResource(): edit not in locks");
return;
}
// rollback and release the lock's connection
m_sql.dbCancel(lock);
// release the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// remove the lock
String statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("cancel: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// release the lock
m_locks.remove(edit.getReference());
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#removeResource(org.sakaiproject.entity.api.Edit)
*/
public void removeResource(Edit edit)
{
// form the SQL delete statement
String statement = singleStorageSql.getDeleteSql(m_resourceTableIdField, m_resourceTableName);
Object fields[] = new Object[1];
fields[0] = caseId(edit.getId());
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("removeResource(): edit not in locks");
return;
}
// process the delete statement, commit, and release the lock's connection
m_sql.dbUpdateCommit(statement, fields, null, lock);
// release the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// process the delete statement
m_sql.dbWrite(statement, fields);
// remove the lock
statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("remove: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// process the delete statement
m_sql.dbWrite(statement, fields);
// release the lock
m_locks.remove(edit.getReference());
}
}
/**
* Form a string of n question marks with commas, for sql value statements, one for each item in the values array, or an empty string if null.
*
* @param values
* The values to be inserted into the sql statement.
* @return A sql statement fragment for the values part of an insert, one for each value in the array.
*/
protected String valuesParams(String[] fields)
{
if ((fields == null) || (fields.length == 0)) return "";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < fields.length; i++)
{
buf.append(" ?,");
}
return buf.toString();
}
/**
* Form a string of n name=?, for sql update set statements, one for each item in the values array, or an empty string if null.
*
* @param values
* The values to be inserted into the sql statement.
* @return A sql statement fragment for the values part of an insert, one for each value in the array.
*/
protected String updateSet(String[] fields)
{
if ((fields == null) || (fields.length == 0)) return "";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < fields.length; i++)
{
buf.append(fields[i] + " = ?,");
}
return buf.toString();
}
/**
* Form a string of (field, field, field), for sql insert statements, one for each item in the fields array, plus one before, and one after.
*
* @param before
* The first field name.
* @param values
* The extra field names, in the middle.
* @param after
* The last field name.
* @return A sql statement fragment for the insert fields.
*/
protected String insertFields(String before, String[] fields, String after)
{
StringBuilder buf = new StringBuilder();
buf.append(" (");
buf.append(before);
buf.append(",");
if (fields != null)
{
for (int i = 0; i < fields.length; i++)
{
buf.append(fields[i] + ",");
}
}
buf.append(after);
buf.append(")");
return buf.toString();
}
/**
* Fix the case of resource ids to support case insensitive ids if enabled
*
* @param The
* id to fix.
* @return The id, case modified as needed.
*/
protected String caseId(String id)
{
if (m_caseInsensitive)
{
return id.toLowerCase();
}
return id;
}
/**
* Enable / disable case insensitive ids.
*
* @param setting
* true to set case insensitivity, false to set case sensitivity.
*/
protected void setCaseInsensitivity(boolean setting)
{
m_caseInsensitive = setting;
}
/**
* Return a record ID to use internally in the database. This is needed for databases (MySQL) that have limits on key lengths. The hash code
* ensures that the record ID will be unique, even if the DB only considers a prefix of a very long record ID.
*
* @param recordId
* @return The record ID to use internally in the database
*/
private String internalRecordId(String recordId)
{
if ("mysql".equals(m_sql.getVendor()))
{
if (recordId == null) recordId = "null";
return recordId.hashCode() + " - " + recordId;
}
else
// oracle, hsqldb
{
return recordId;
}
}
}
| true | true | public Edit editResource(String id)
{
Edit edit = null;
if (m_locksAreInDb)
{
if ("oracle".equals(m_sql.getVendor()))
{
// read the record and get a lock on it (non blocking)
String statement = "select XML from " + m_resourceTableName + " where ( " + m_resourceTableIdField + " = '"
+ Validator.escapeSql(caseId(id)) + "' )" + " for update nowait";
StringBuilder result = new StringBuilder();
Connection lock = m_sql.dbReadLock(statement, result);
// for missing or already locked...
if ((lock == null) || (result.length() == 0)) return null;
// make first a Resource, then an Edit
Entity entry = readResource(result.toString());
edit = m_user.newResourceEdit(null, entry);
// store the lock for this object
m_locks.put(entry.getReference(), lock);
}
else
{
throw new UnsupportedOperationException("Record locking only available when configured with Oracle database");
}
}
// if the locks are in a separate table in the db
else if (m_locksAreInTable)
{
// read the record - fail if not there
Entity entry = getResource(id);
if (entry == null) return null;
// write a lock to the lock table - if we can do it, we get the lock
String statement = singleStorageSql.getInsertLocks();
// we need session id and user id
String sessionId = UsageSessionService.getSessionId();
if (sessionId == null)
{
sessionId = "";
}
// collect the fields
Object fields[] = new Object[4];
fields[0] = m_resourceTableName;
fields[1] = internalRecordId(caseId(id));
fields[2] = TimeService.newTime();
fields[3] = sessionId;
// add the lock - if fails, someone else has the lock
boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
if (!ok)
{
return null;
}
// we got the lock! - make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
}
// otherwise, get the lock locally
else
{
// get the entry, and check for existence
Entity entry = getResource(id);
if (entry == null) return null;
// we only sync this getting - someone may release a lock out of sync
synchronized (m_locks)
{
// if already locked
if (m_locks.containsKey(entry.getReference())) return null;
// make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
// store the edit in the locks by reference
m_locks.put(entry.getReference(), edit);
}
}
return edit;
}
| public Edit editResource(String id)
{
Edit edit = null;
if (m_locksAreInDb)
{
if ("oracle".equals(m_sql.getVendor()))
{
// read the record and get a lock on it (non blocking)
String statement = "select XML from " + m_resourceTableName + " where ( " + m_resourceTableIdField + " = '"
+ Validator.escapeSql(caseId(id)) + "' )" + " for update nowait";
StringBuilder result = new StringBuilder();
Connection lock = m_sql.dbReadLock(statement, result);
// for missing or already locked...
if ((lock == null) || (result.length() == 0)) return null;
// make first a Resource, then an Edit
Entity entry = readResource(result.toString());
edit = m_user.newResourceEdit(null, entry);
// store the lock for this object
m_locks.put(entry.getReference(), lock);
}
else
{
throw new UnsupportedOperationException("Record locking only available when configured with Oracle database");
}
}
// if the locks are in a separate table in the db
else if (m_locksAreInTable)
{
// read the record - fail if not there
Entity entry = getResource(id);
if (entry == null) return null;
// write a lock to the lock table - if we can do it, we get the lock
String statement = singleStorageSql.getInsertLocks();
// we need session id and user id
String sessionId = UsageSessionService.getSessionId();
if (sessionId == null)
{
sessionId = ""; // TODO - "" gets converted to a null and will never be able to be cleaned up -AZ (SAK-11841)
}
// collect the fields
Object fields[] = new Object[4];
fields[0] = m_resourceTableName;
fields[1] = internalRecordId(caseId(id));
fields[2] = TimeService.newTime();
fields[3] = sessionId;
// add the lock - if fails, someone else has the lock
boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
if (!ok)
{
return null;
}
// we got the lock! - make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
}
// otherwise, get the lock locally
else
{
// get the entry, and check for existence
Entity entry = getResource(id);
if (entry == null) return null;
// we only sync this getting - someone may release a lock out of sync
synchronized (m_locks)
{
// if already locked
if (m_locks.containsKey(entry.getReference())) return null;
// make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
// store the edit in the locks by reference
m_locks.put(entry.getReference(), edit);
}
}
return edit;
}
|
diff --git a/mifos/test/org/mifos/application/accounts/business/TestAccountActionDateEntity.java b/mifos/test/org/mifos/application/accounts/business/TestAccountActionDateEntity.java
index 37bf02d76..ebed97807 100644
--- a/mifos/test/org/mifos/application/accounts/business/TestAccountActionDateEntity.java
+++ b/mifos/test/org/mifos/application/accounts/business/TestAccountActionDateEntity.java
@@ -1,157 +1,161 @@
/**
*
*/
package org.mifos.application.accounts.business;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;
import org.mifos.application.accounts.TestAccount;
import org.mifos.application.accounts.loan.business.LoanBO;
import org.mifos.application.accounts.loan.business.LoanScheduleEntity;
import org.mifos.application.customer.business.CustomerScheduleEntity;
import org.mifos.application.customer.business.TestCustomerAccountBO;
import org.mifos.application.customer.center.business.CenterBO;
import org.mifos.application.customer.group.business.GroupBO;
import org.mifos.application.fees.business.AmountFeeBO;
import org.mifos.application.fees.business.FeeBO;
import org.mifos.application.fees.util.helpers.FeeCategory;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.framework.hibernate.helper.HibernateUtil;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
public class TestAccountActionDateEntity extends TestAccount {
public static void addAccountActionDate(
AccountActionDateEntity accountAction, AccountBO account) {
account.addAccountActionDate(accountAction);
}
public void testGetPrincipal() {
Set<AccountActionDateEntity> accountActionDates = accountBO
.getAccountActionDates();
for (AccountActionDateEntity accountActionDate : accountActionDates) {
Money principal = ((LoanScheduleEntity) accountActionDate)
.getPrincipal();
assertEquals(100.0, principal.getAmount().doubleValue());
}
}
public void testWaiveCharges() {
HibernateUtil.closeSession();
group = TestObjectFactory.getObject(GroupBO.class, group
.getCustomerId());
CustomerScheduleEntity accountActionDate = (CustomerScheduleEntity) group
.getCustomerAccount().getAccountActionDates().toArray()[0];
TestCustomerAccountBO.setMiscFee(accountActionDate,new Money("20"));
Money chargeWaived = TestCustomerAccountBO.waiveCharges(accountActionDate);
assertEquals(new Money(), accountActionDate.getMiscFee());
for (AccountFeesActionDetailEntity accountFeesActionDetailEntity : accountActionDate
.getAccountFeesActionDetails()) {
assertEquals(new Money(), accountFeesActionDetailEntity
.getFeeAmount());
}
assertEquals(new Money("120.0"), chargeWaived);
HibernateUtil.closeSession();
group = TestObjectFactory.getObject(GroupBO.class, group
.getCustomerId());
center = TestObjectFactory.getObject(CenterBO.class, center
.getCustomerId());
accountBO = TestObjectFactory.getObject(LoanBO.class,
accountBO.getAccountId());
}
public void testApplyPeriodicFees() {
FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee(
"Periodic Fee", FeeCategory.LOAN, "100", RecurrenceType.WEEKLY,
Short.valueOf("1"));
AccountFeesEntity accountFeesEntity = new AccountFeesEntity(group
.getCustomerAccount(), periodicFee, ((AmountFeeBO) periodicFee)
.getFeeAmount().getAmountDoubleValue(), null, null, new Date(
System.currentTimeMillis()));
group.getCustomerAccount().addAccountFees(accountFeesEntity);
TestObjectFactory.updateObject(group);
TestObjectFactory.flushandCloseSession();
group = TestObjectFactory.getObject(GroupBO.class, group
.getCustomerId());
CustomerScheduleEntity accountActionDateEntity = (CustomerScheduleEntity) group
.getCustomerAccount().getAccountActionDates().toArray()[0];
Set<AccountFeesActionDetailEntity> feeDetailsSet = accountActionDateEntity
.getAccountFeesActionDetails();
List<Integer> feeList = new ArrayList<Integer>();
for (AccountFeesActionDetailEntity accountFeesActionDetailEntity : feeDetailsSet) {
feeList.add(accountFeesActionDetailEntity
.getAccountFeesActionDetailId());
}
Set<AccountFeesEntity> accountFeeSet = group.getCustomerAccount()
.getAccountFees();
for (AccountFeesEntity accFeesEntity : accountFeeSet) {
if (accFeesEntity.getFees().getFeeName().equalsIgnoreCase(
"Periodic Fee")) {
TestCustomerAccountBO.applyPeriodicFees(accountActionDateEntity,accFeesEntity
.getFees().getFeeId(), new Money("100"));
break;
}
}
TestObjectFactory.updateObject(group);
TestObjectFactory.flushandCloseSession();
group = TestObjectFactory.getObject(GroupBO.class, group
.getCustomerId());
CustomerScheduleEntity firstInstallment = (CustomerScheduleEntity) group
.getCustomerAccount().getAccountActionDates().toArray()[0];
for (AccountFeesActionDetailEntity accountFeesActionDetailEntity : firstInstallment
.getAccountFeesActionDetails()) {
if (!feeList.contains(accountFeesActionDetailEntity
.getAccountFeesActionDetailId())) {
assertEquals("Periodic Fee", accountFeesActionDetailEntity
.getFee().getFeeName());
break;
}
}
HibernateUtil.closeSession();
accountBO = TestObjectFactory.getObject(LoanBO.class,
accountBO.getAccountId());
group = TestObjectFactory.getObject(GroupBO.class, group
.getCustomerId());
}
+ /**
+ * Changes <em>all</em> installment dates to yesterday. In production,
+ * multiple installments should never have the same ACTION_DATE.
+ */
public static void changeInstallmentDatesToPreviousDate(AccountBO accountBO) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day - 1);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
accountActionDateEntity.setActionDate(new java.sql.Date(
currentDateCalendar.getTimeInMillis()));
}
}
public static void changeInstallmentDatesToPreviousDateExceptLastInstallment(
AccountBO accountBO,int noOfInstallmentsToBeChanged) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day - 1);
for (int i = 1; i <=noOfInstallmentsToBeChanged; i++) {
AccountActionDateEntity accountActionDateEntity = accountBO
.getAccountActionDate(Integer.valueOf(i).shortValue());
accountActionDateEntity.setActionDate(new java.sql.Date(
currentDateCalendar.getTimeInMillis()));
}
}
}
| true | false | null | null |
diff --git a/Character_Equipment_Impl/test/net/sf/anathema/character/equipment/impl/item/model/gson/FilenameCleanerTest.java b/Character_Equipment_Impl/test/net/sf/anathema/character/equipment/impl/item/model/gson/FilenameCleanerTest.java
index a3ead560c3..fb148e83be 100644
--- a/Character_Equipment_Impl/test/net/sf/anathema/character/equipment/impl/item/model/gson/FilenameCleanerTest.java
+++ b/Character_Equipment_Impl/test/net/sf/anathema/character/equipment/impl/item/model/gson/FilenameCleanerTest.java
@@ -1,41 +1,41 @@
package net.sf.anathema.character.equipment.impl.item.model.gson;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class FilenameCleanerTest {
private FilenameCleaner cleaner = new FilenameCleaner();
@Test
public void replacesSlashes() throws Exception {
assertThat(cleaner.clean("x/x"), is("x_x"));
}
@Test
public void replacesBackslashes() throws Exception {
assertThat(cleaner.clean("x\\x"), is("x_x"));
}
@Test
public void replacesColon() throws Exception {
assertThat(cleaner.clean("x:x"), is("x_x"));
}
@Test
public void replacesTilde() throws Exception {
assertThat(cleaner.clean("x~x"), is("x_x"));
}
@Test
public void replacesTwoInARow() throws Exception {
assertThat(cleaner.clean("x~/x"), is("x__x"));
}
@Test
- public void replacesModifiedCharacters() throws Exception {
- assertThat(cleaner.clean("xáx"), is("x_x"));
+ public void replacesNonLatinCharacters() throws Exception {
+ assertThat(cleaner.clean("xäx"), is("x_x"));
}
}
| true | false | null | null |
diff --git a/collections/src/main/java/net/sf/javagimmicks/collections/bidimap/DualBidiMap.java b/collections/src/main/java/net/sf/javagimmicks/collections/bidimap/DualBidiMap.java
index bc19d3e..3f6f06a 100644
--- a/collections/src/main/java/net/sf/javagimmicks/collections/bidimap/DualBidiMap.java
+++ b/collections/src/main/java/net/sf/javagimmicks/collections/bidimap/DualBidiMap.java
@@ -1,224 +1,224 @@
package net.sf.javagimmicks.collections.bidimap;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A default implementation of {@link BidiMap} that internally works with two
* convenient {@link Map} (one for each "direction").
*/
public class DualBidiMap<K, V> extends AbstractMap<K, V> implements BidiMap<K, V>
{
protected final Map<K, V> _forwardMap;
protected final Map<V, K> _reverseMap;
/**
* Creates a new instance for the given forward and reverse {@link Map}
*
* @param forwardMap
* the forward {@link Map} used to map keys to values
* @param reverseMap
* the reverse {@link Map} used to map values to keys
*/
public DualBidiMap(final Map<K, V> forwardMap, final Map<V, K> reverseMap)
{
_forwardMap = forwardMap;
_reverseMap = reverseMap;
}
@Override
public Set<Entry<K, V>> entrySet()
{
return new DualBidiEntrySet(getForwardMap().entrySet());
}
@Override
public V put(final K key, final V value)
{
checkKey(key);
checkValue(value);
final V oldValue = getForwardMap().put(key, value);
postProcessPut(key, value, oldValue);
return oldValue;
}
@Override
public V remove(final Object key)
{
final V value = getForwardMap().remove(key);
getReverseMap().remove(value);
return value;
}
@Override
public BidiMap<V, K> inverseBidiMap()
{
return new InverseDualBidiMap(getReverseMap(), getForwardMap());
}
@Override
public V get(final Object key)
{
return getForwardMap().get(key);
}
@Override
public K getKey(final V value)
{
return getReverseMap().get(value);
}
protected Map<K, V> getForwardMap()
{
return _forwardMap;
}
protected Map<V, K> getReverseMap()
{
return _reverseMap;
}
protected void postProcessPut(final K key, final V newValue, final V oldValue)
{
final Map<V, K> reverseMap = getReverseMap();
// Put the new value to the reverse map
final K oldKey = reverseMap.put(newValue, key);
// Update to forward map might have invalidated a key in the reverse map
if (oldValue != null)
{
reverseMap.remove(oldValue);
}
// Update to reverse map might have invalidated a key in the forward map
if (oldKey != null)
{
getForwardMap().remove(oldKey);
}
}
protected static <K extends Object> void checkKey(final K value)
{
if (value == null)
{
throw new IllegalArgumentException("Null keys not allowed in BidiMaps!");
}
}
protected static <V extends Object> void checkValue(final V value)
{
if (value == null)
{
throw new IllegalArgumentException("Null values not allowed in BidiMaps!");
}
}
protected class DualBidiEntry implements Entry<K, V>
{
protected final Entry<K, V> _internalEntry;
protected DualBidiEntry(final Entry<K, V> internalEntry)
{
this._internalEntry = internalEntry;
}
@Override
public K getKey()
{
return _internalEntry.getKey();
}
@Override
public V getValue()
{
return _internalEntry.getValue();
}
@Override
public V setValue(final V value)
{
final V oldValue = _internalEntry.setValue(value);
// Attention!
// This might invalidate the Iterator that created this entry
// But there is no workaround possible - it's the bidirectional nature
postProcessPut(getKey(), value, oldValue);
return oldValue;
}
}
protected class DualBidiEntryIterator implements Iterator<Entry<K, V>>
{
- protected final Iterator<Entry<K, V>> internalIterator;
+ protected final Iterator<Entry<K, V>> _internalIterator;
protected Entry<K, V> _lastEntry;
protected DualBidiEntryIterator(final Iterator<Entry<K, V>> internalIterator)
{
- this.internalIterator = internalIterator;
+ this._internalIterator = internalIterator;
}
@Override
public boolean hasNext()
{
- return internalIterator.hasNext();
+ return _internalIterator.hasNext();
}
@Override
public Entry<K, V> next()
{
- _lastEntry = internalIterator.next();
+ _lastEntry = _internalIterator.next();
return new DualBidiEntry(_lastEntry);
}
@Override
public void remove()
{
- internalIterator.remove();
+ _internalIterator.remove();
_reverseMap.remove(_lastEntry.getValue());
}
}
protected class DualBidiEntrySet extends AbstractSet<Entry<K, V>>
{
private final Set<Entry<K, V>> internalEntrySet;
protected DualBidiEntrySet(final Set<Entry<K, V>> internalEntrySet)
{
this.internalEntrySet = internalEntrySet;
}
@Override
public Iterator<Entry<K, V>> iterator()
{
return new DualBidiEntryIterator(internalEntrySet.iterator());
}
@Override
public int size()
{
return internalEntrySet.size();
}
}
protected class InverseDualBidiMap extends DualBidiMap<V, K>
{
protected InverseDualBidiMap(final Map<V, K> reverseMap, final Map<K, V> forwardMap)
{
super(reverseMap, forwardMap);
}
@Override
public BidiMap<K, V> inverseBidiMap()
{
return DualBidiMap.this;
}
}
}
| false | false | null | null |
diff --git a/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java b/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java
index 23acffb4..f935c4d5 100755
--- a/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java
+++ b/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java
@@ -1,780 +1,755 @@
package org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.DSDataSet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.CSMicroarraySet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet;
import org.geworkbench.bison.datastructure.bioobjects.DSBioObject;
import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker;
import org.geworkbench.bison.datastructure.bioobjects.microarray.DSMicroarray;
import org.geworkbench.bison.datastructure.complex.panels.DSItemList;
import org.geworkbench.engine.preferences.PreferencesManager;
import org.geworkbench.engine.properties.PropertiesManager;
import org.geworkbench.util.CsvFileFilter;
import com.Ostermiller.util.CSVParser;
import com.Ostermiller.util.LabeledCSVParser;
import com.jgoodies.forms.builder.ButtonBarBuilder;
/**
*
* Description:This Class is for retrieving probe annotation information from
* default annotation files provided by Affymetrix.
*
* @author Xuegong Wang
* @author manjunath at genomecenter dot columbia dot edu
* @version $Id$
*/
public class AnnotationParser implements Serializable {
private static final long serialVersionUID = -117234619759135916L;
static Log log = LogFactory.getLog(AnnotationParser.class);
public static final String GENE_ONTOLOGY_BIOLOGICAL_PROCESS = "Gene Ontology Biological Process";
public static final String GENE_ONTOLOGY_CELLULAR_COMPONENT = "Gene Ontology Cellular Component";
public static final String GENE_ONTOLOGY_MOLECULAR_FUNCTION = "Gene Ontology Molecular Function";
public static final String GENE_SYMBOL = "Gene Symbol";
public static final String PROBE_SET_ID = "Probe Set ID";
public static final String MAIN_DELIMITER = "\\s*///\\s*";
// field names
public static final String DESCRIPTION = "Gene Title"; // (full name)
public static final String ABREV = GENE_SYMBOL; // title(short name)
public static final String PATHWAY = "Pathway"; // pathway
public static final String GOTERM = GENE_ONTOLOGY_BIOLOGICAL_PROCESS; // Goterms
public static final String UNIGENE = "UniGene ID"; // Unigene
public static final String UNIGENE_CLUSTER = "Archival UniGene Cluster";
public static final String LOCUSLINK = "Entrez Gene"; // LocusLink
public static final String SWISSPROT = "SwissProt"; // swissprot
public static final String REFSEQ = "RefSeq Transcript ID"; // RefSeq
public static final String TRANSCRIPT = "Transcript Assignments";
public static final String SCIENTIFIC_NAME = "Species Scientific Name";
public static final String GENOME_VERSION = "Genome Version";
public static final String ALIGNMENT = "Alignments";
// columns read into geWorkbench
// probe id must be first column read in, and the rest of the columns must
// follow the same order
// as the columns in the annotation file.
private static final String[] labels = {
PROBE_SET_ID // probe id must be the first item in this list
, SCIENTIFIC_NAME, UNIGENE_CLUSTER, UNIGENE, GENOME_VERSION,
ALIGNMENT, DESCRIPTION, GENE_SYMBOL, LOCUSLINK, SWISSPROT, REFSEQ,
GENE_ONTOLOGY_BIOLOGICAL_PROCESS, GENE_ONTOLOGY_CELLULAR_COMPONENT,
GENE_ONTOLOGY_MOLECULAR_FUNCTION, PATHWAY, TRANSCRIPT };
// TODO all the DSDataSets handled in this class should be DSMicroarraySet
// FIELDS
private static DSDataSet<? extends DSBioObject> currentDataSet = null;
private static Map<DSDataSet<? extends DSBioObject>, String> datasetToChipTypes = new HashMap<DSDataSet<? extends DSBioObject>, String>();
private static Map<String, MarkerAnnotation> chipTypeToAnnotation = new TreeMap<String, MarkerAnnotation>();
// END FIELDS
/* The reason that we need APSerializable is that the status fields are designed as static. */
public static APSerializable getSerializable() {
return new APSerializable(currentDataSet, datasetToChipTypes,
chipTypeToAnnotation);
}
public static void setFromSerializable(APSerializable aps) {
currentDataSet = aps.currentDataSet;
datasetToChipTypes = aps.datasetToChipTypes;
chipTypeToAnnotation = aps.chipTypeToAnnotation;
}
private static final String ANNOT_DIR = "annotDir";
public static DSDataSet<? extends DSBioObject> getCurrentDataSet() {
return currentDataSet;
}
public static void setCurrentDataSet(DSDataSet<DSBioObject> currentDataSet) {
if(!(currentDataSet instanceof CSMicroarraySet)) {
AnnotationParser.currentDataSet = null;
}
AnnotationParser.currentDataSet = currentDataSet;
}
public static String getCurrentChipType() {
if (currentDataSet != null) {
return datasetToChipTypes.get(currentDataSet);
} else {
return null;
}
}
public static String getChipType(DSDataSet<? extends DSBioObject> dataset) {
return datasetToChipTypes.get(dataset);
}
public static void setChipType(DSDataSet<? extends DSBioObject> dataset, String chiptype) {
datasetToChipTypes.put(dataset, chiptype);
currentDataSet = dataset;
}
/* this is used to handle annotation file when the real dataset is chosen after annotation. */
private static CSMicroarraySet<? extends DSBioObject> dummyMicroarraySet = new CSMicroarraySet<DSMicroarray>();
public static String getLastAnnotationFileName () {
return dummyMicroarraySet.getAnnotationFileName();
}
/* if the annotation file is given, this method is called directly without GUI involved */
public static void loadAnnotationFile(
DSDataSet<? extends DSBioObject> dataset, File annotationData) {
if (!annotationData.exists()) { // data file is found
log.error("Annotation file " + annotationData + " does not exist.");
return;
}
BufferedInputStream bis = null;
String chipType = annotationData.getName();
try {
bis = new BufferedInputStream(new FileInputStream(annotationData));
CSVParser cvsParser = new CSVParser(bis);
cvsParser.setCommentStart("#;!");// Skip all comments line.
// XQ. The bug is reported
// by Bernd.
LabeledCSVParser parser = new LabeledCSVParser(cvsParser);
MarkerAnnotation markerAnnotation = new MarkerAnnotation();
boolean ignoreAll = false;
boolean cancelAnnotationFileProcessing = false;
while ((parser.getLine() != null)
&& !cancelAnnotationFileProcessing) {
String affyId = parser.getValueByLabel(labels[0]);
if(affyId==null)
continue;
affyId = affyId.trim();
AnnotationFields fields = new AnnotationFields();
for (int i = 1; i < labels.length; i++) {
String label = labels[i];
String val = parser.getValueByLabel(label);
if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)
|| label.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)
|| label.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
// get rid of leading 0's
while (val.startsWith("0") && (val.length() > 0)) {
val = val.substring(1);
}
}
if (label.equals(GENE_SYMBOL))
fields.setGeneSymbol(val);
else if (label.equals(LOCUSLINK))
fields.setLocusLink(val);
else if (label.equals(SWISSPROT))
fields.setSwissProt(val);
else if (label.equals(DESCRIPTION))
fields.setDescription(val);
else if (label.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION))
fields.setMolecularFunction(val);
else if (label.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT))
fields.setCellularComponent(val);
else if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS))
fields.setBiologicalProcess(val);
else if (label.equals(UNIGENE))
fields.setUniGene(val);
else if (label.equals(REFSEQ))
fields.setRefSeq(val);
}
if (markerAnnotation.containsMarker(affyId)) {
if (!ignoreAll) {
String[] options = { "Skip duplicate",
"Skip all duplicates", "Cancel", };
int code = JOptionPane
.showOptionDialog(
null,
"Duplicate entry. Probe Set ID="
+ affyId
+ ".\n"
+ "Skip duplicate - will ignore this entry\n"
+ "Skip all duplicates - will ignore all duplicate entries.\n"
+ "Cancel - will cancel the annotation file processing.",
"Duplicate entry in annotation file",
0, JOptionPane.QUESTION_MESSAGE, null,
options, "Proceed");
if (code == 1) {
ignoreAll = true;
}
if (code == 2) {
cancelAnnotationFileProcessing = true;
}
}
} else {
markerAnnotation.addMarker(affyId, fields);
}
}
if (!cancelAnnotationFileProcessing) {
chipTypeToAnnotation.put(chipType, markerAnnotation);
}
// all fine.
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
datasetToChipTypes.put(dataset, chipType);
currentDataSet = dataset;
if (dataset == null) {
dummyMicroarraySet.setAnnotationFileName(annotationData
.getAbsolutePath());
}
if (dataset instanceof CSMicroarraySet) {
CSMicroarraySet<?> d = (CSMicroarraySet<?>) dataset;
d.setAnnotationFileName(annotationData.getAbsolutePath());
}
}
/* !!! return value of this method depends on currentDataSet, which could be suprising if not careful */
public static String getGeneName(String id) {
try {
String chipType = datasetToChipTypes.get(currentDataSet);
return chipTypeToAnnotation.get(chipType).getFields(id).getGeneSymbol();
} catch (NullPointerException e) {
return id;
}
}
/**
* This method returns required annotation field for a given affymatrix marker ID .
*
* @param affyid
* affyID as string
* @param fieldID
*
*/
// this method used to depend on chipTypeToAnnotations, which take unnecessary large memory
// the first step is to re-implement this method so it does not use chipTypeToAnnotations
static public String[] getInfo(String affyID, String fieldID) {
try {
String chipType = datasetToChipTypes.get(currentDataSet);
String field = "";
AnnotationFields fields = chipTypeToAnnotation.get(chipType).getFields(affyID);
// individual field to be process separately to eventually get rid of the large map
if(fieldID.equals(ABREV)) { // same as GENE_SYMBOL
field = fields.getGeneSymbol();
} else if(fieldID.equals(LOCUSLINK)) {
field = fields.getLocusLink();
} else if(fieldID.equals(DESCRIPTION)) {
field = fields.getDescription();
} else if(fieldID.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
field = fields.getMolecularFunction();
} else if(fieldID.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)) {
field = fields.getCellularComponent();
} else if(fieldID.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)) {
field = fields.getBiologicalProcess();
} else if(fieldID.equals(UNIGENE)) {
field = fields.getUniGene();
} else if(fieldID.equals(REFSEQ)) {
field = fields.getRefSeq();
} else if(fieldID.equals(SWISSPROT)) {
field = fields.getSwissProt();
} else {
log.error("trying to retreive unsupported field "+fieldID+" from marker annotation. null is returned.");
return null;
}
return field.split(MAIN_DELIMITER);
} catch (Exception e) {
if (affyID != null) {
log
.debug("Error getting info for affyId (" + affyID
+ "):" + e);
}
return null;
}
}
// this method is similar to the previous one except it take dataset instead
// of using currentDataSet
static public String[] getInfo(DSMicroarraySet<DSMicroarray> dataset,
String affyID, String fieldID) {
String chipType = datasetToChipTypes.get(dataset);
String field = null;
AnnotationFields fields = chipTypeToAnnotation.get(chipType).getFields(
affyID);
// individual field to be process separately to eventually get rid of
// the large map
if (fieldID.equals(ABREV)) { // same as GENE_SYMBOL
field = fields.getGeneSymbol();
} else if (fieldID.equals(LOCUSLINK)) {
field = fields.getLocusLink();
} else if (fieldID.equals(DESCRIPTION)) {
field = fields.getDescription();
} else if (fieldID.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
field = fields.getMolecularFunction();
} else if (fieldID.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)) {
field = fields.getCellularComponent();
} else if (fieldID.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)) {
field = fields.getBiologicalProcess();
} else if (fieldID.equals(UNIGENE)) {
field = fields.getUniGene();
} else if (fieldID.equals(REFSEQ)) {
field = fields.getRefSeq();
} else if (fieldID.equals(SWISSPROT)) {
field = fields.getSwissProt();
} else {
log.error("trying to retreive unsupported field " + fieldID
+ " from marker annotation. null is returned.");
return null;
}
return field.split(MAIN_DELIMITER);
}
public static Set<String> getSwissProtIDs(String markerID) {
String chipType = datasetToChipTypes.get(currentDataSet);
HashSet<String> set = new HashSet<String>();
String[] ids = chipTypeToAnnotation.get(chipType).getFields(markerID).getSwissProt().split("///");
for (String s : ids) {
set.add(s.trim());
}
return set;
}
public static Set<String> getGeneIDs(String markerID) {
HashSet<String> set = new HashSet<String>();
String chipType = datasetToChipTypes.get(currentDataSet);
// this happens when no annotation or bad annotation is loaded.
if(chipType==null) {
return set;
}
MarkerAnnotation annotation = chipTypeToAnnotation.get(chipType);
AnnotationFields fields = annotation.getFields(markerID);
if(fields==null) {
return set;
}
String locus = fields.getLocusLink();
if(locus==null) {
return set;
}
String[] ids = locus.split("///");
for (String s : ids) {
set.add(s.trim());
}
return set;
}
- public static Map<String, List<Integer>> getGeneIdToMarkerIDMapping(
- DSMicroarraySet<? extends DSMicroarray> microarraySet) {
- Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
- DSItemList<DSGeneMarker> markers = microarraySet.getMarkers();
- int index = 0;
- for (DSGeneMarker marker : markers) {
- if (marker != null && marker.getLabel() != null) {
- Set<String> geneIDs = getGeneIDs(marker.getLabel());
- for (String s : geneIDs) {
- List<Integer> list = map.get(s);
- if (list == null) {
- list = new ArrayList<Integer>();
- list.add(index);
- map.put(s, list);
- } else {
- list.add(index);
- }
- }
- index++;
- }
- }
- return map;
-
- }
-
public static Map<String, List<Integer>> getGeneNameToMarkerIDMapping(
DSMicroarraySet<? extends DSMicroarray> microarraySet) {
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
DSItemList<DSGeneMarker> markers = microarraySet.getMarkers();
int index = 0;
for (DSGeneMarker marker : markers) {
if (marker != null && marker.getLabel() != null) {
try {
Set<String> geneNames = getGeneNames(marker.getLabel());
for (String s : geneNames) {
List<Integer> list = map.get(s);
if(list==null) {
list = new ArrayList<Integer>();
list.add(index);
map.put(s, list);
} else {
list.add(index);
}
}
index++;
} catch (Exception e) {
continue;
}
}
}
return map;
}
public static Set<String> getGeneNames(String markerID) {
String chipType = datasetToChipTypes.get(currentDataSet);
HashSet<String> set = new HashSet<String>();
String[] ids = chipTypeToAnnotation.get(chipType).getFields(markerID).getGeneSymbol().split("///");
for (String s : ids) {
set.add(s.trim());
}
return set;
}
public static String matchChipType(final DSDataSet<? extends DSBioObject> dataset, String id,
boolean askIfNotFound) {
PreferencesManager preferencesManager = PreferencesManager
.getPreferencesManager();
File prefDir = preferencesManager.getPrefDir();
final File annotFile = new File(prefDir, "annotations.prefs");
if (!annotFile.exists()) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
boolean dontShowAgain = showAnnotationsMessage();
if (dontShowAgain) {
try {
annotFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
currentDataSet = dataset;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
userFile = selectUserDefinedAnnotation(dataset);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (userFile != null) {
loadAnnotationFile(dataset, userFile);
return userFile.getName();
} else {
return "Other";
}
}
private volatile static File userFile = null;
public static boolean showAnnotationsMessage() {
String message = "To process Affymetrix files many geWorkbench components require information from the associated chip annotation files. Annotation files can be downloaded from the Affymetrix web site, <a href='http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays' target='_blank'>http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays</a> (due to the Affymetrix license we are precluded from shipping these files with geWorkbench). Place downloaded files to a directory of your choice; when prompted by geWorkbench point to the appropriate annotation file to be associated with the microarray data you are about to load into the application. Your data will load even if you do not associate them with an annotation file; in that case, some geWorkbench components will not be fully functional.<br>\n"
+ "<br>\n"
+ "NOTE: Affymetrix requires users to register in order to download annotation files from its web site. Registration is a one time procedure. The credentials (user id and password) acquired via the registration process can then be used in subsequent interactions with the site.<br>\n"
+ "<br>\n"
+ "Each chip type in the Affymetrix site can have several associated annotation files (with names like \"...Annotations, BLAST\", \"...Annotations, MAGE-ML XML\", etc). Only annotation files named \"...Annotations, CSV\" need to be downloaded (these are the only files that geWorkbench can process).<br>";
final JDialog window = new JDialog((Frame) null,
"Annotations Information");
Container panel = window.getContentPane();
JEditorPane textarea = new JEditorPane("text/html", message);
textarea.setEditable(false);
textarea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
openURL("http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays");
}
}
});
// textarea.setLineWrap(true);
// textarea.setWrapStyleWord(true);
panel.add(textarea, BorderLayout.CENTER);
ButtonBarBuilder builder = ButtonBarBuilder.createLeftToRightBuilder();
JCheckBox dontShow = new JCheckBox("Don't show this again");
builder.addFixed(dontShow);
builder.addGlue();
JButton jButton = new JButton("Continue");
builder.addFixed(jButton);
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.dispose();
}
});
panel.add(builder.getPanel(), BorderLayout.SOUTH);
int width = 500;
int height = 450;
window.pack();
window.setSize(width, height);
window
.setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width - width) / 2,
(Toolkit.getDefaultToolkit().getScreenSize().height - height) / 2);
window.setModal(true);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
return dontShow.isSelected();
}
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class<?>[] { String.class });
openURL.invoke(null, new Object[] { url });
} else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
} else { // assume Unix or Linux
String[] browsers = { "firefox", "opera", "konqueror",
"epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(
new String[] { "which", browsers[count] })
.waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
else
Runtime.getRuntime().exec(new String[] { browser, url });
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to open browser"
+ ":\n" + e.getLocalizedMessage());
}
}
private static File selectUserDefinedAnnotation(DSDataSet<? extends DSBioObject> dataset) {
PropertiesManager properties = PropertiesManager.getInstance();
String annotationDir = System.getProperty("user.dir"); ;
try {
annotationDir = properties.getProperty(AnnotationParser.class,
ANNOT_DIR, annotationDir);
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
}
JFileChooser chooser = new JFileChooser(annotationDir);
chooser.setFileFilter(new CsvFileFilter());
chooser.setDialogTitle("Please select the annotation file");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File userAnnotations = chooser.getSelectedFile();
try {
properties.setProperty(AnnotationParser.class, ANNOT_DIR,
userAnnotations.getParent());
} catch (IOException e) {
e.printStackTrace();
}
return userAnnotations;
} else {
return null;
}
}
static private class AnnotationFields implements Serializable {
private static final long serialVersionUID = -3571880185587329070L;
String getMolecularFunction() {
return molecularFunction;
}
void setMolecularFunction(String molecularFunction) {
this.molecularFunction = molecularFunction;
}
String getCellularComponent() {
return cellularComponent;
}
void setCellularComponent(String cellularComponent) {
this.cellularComponent = cellularComponent;
}
String getBiologicalProcess() {
return biologicalProcess;
}
void setBiologicalProcess(String biologicalProcess) {
this.biologicalProcess = biologicalProcess;
}
String getUniGene() {
return uniGene;
}
void setUniGene(String uniGene) {
this.uniGene = uniGene;
}
String getDescription() {
return description;
}
void setDescription(String description) {
this.description = description;
}
String getGeneSymbol() {
return geneSymbol;
}
void setGeneSymbol(String geneSymbol) {
this.geneSymbol = geneSymbol;
}
String getLocusLink() {
return locusLink;
}
void setLocusLink(String locusLink) {
this.locusLink = locusLink;
}
String getSwissProt() {
return swissProt;
}
void setSwissProt(String swissProt) {
this.swissProt = swissProt;
}
public void setRefSeq(String refSeq) {
this.refSeq = refSeq;
}
public String getRefSeq() {
return refSeq;
}
private String molecularFunction, cellularComponent, biologicalProcess;
private String uniGene, description, geneSymbol, locusLink, swissProt;
private String refSeq;
}
static class MarkerAnnotation implements Serializable {
private static final long serialVersionUID = 1350873248604803043L;
private Map<String, AnnotationFields> annotationFields;
MarkerAnnotation() {
annotationFields = new TreeMap<String, AnnotationFields>();
}
void addMarker(String marker, AnnotationFields fields) {
annotationFields.put(marker, fields);
}
boolean containsMarker(String marker) {
return annotationFields.containsKey(marker);
}
AnnotationFields getFields(String marker) {
return annotationFields.get(marker);
}
Set<String> getMarkerSet() {
return annotationFields.keySet();
}
}
public static void cleanUpAnnotatioAfterUnload(DSDataSet<DSBioObject> dataset) {
String annotationName = datasetToChipTypes.get(dataset);
datasetToChipTypes.remove(dataset);
for(DSDataSet<? extends DSBioObject> dset: datasetToChipTypes.keySet() ) {
if(datasetToChipTypes.get(dset).equals(annotationName)) return;
}
// if not returned, then it is not used anymore, clean it up
if(annotationName!=null)
chipTypeToAnnotation.put(annotationName, null);
}
}
| true | false | null | null |
diff --git a/src/com/flaptor/util/Execute.java b/src/com/flaptor/util/Execute.java
index be5c6f8..f65f81f 100644
--- a/src/com/flaptor/util/Execute.java
+++ b/src/com/flaptor/util/Execute.java
@@ -1,298 +1,308 @@
/*
Copyright 2008 Flaptor (flaptor.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.flaptor.util;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* This class provides best-practice execution patterns to some common commands.
*/
public final class Execute {
private final static class ClassContextManager extends SecurityManager {
@Override
public Class<?>[] getClassContext() {
return super.getClassContext();
}
}
private static ClassContextManager classContextyManager = new ClassContextManager();
//so that it cannot be instantiated
private Execute() {}
private static final Logger defaultLogger = Logger.getLogger(Execute.whoAmI());
/**
* Configures Log4j
*/
public static void configureLog4j() {
String log4jConfigPath = FileUtil.getFilePathFromClasspath("log4j.properties");
if (null != log4jConfigPath ) {
PropertyConfigurator.configureAndWatch(log4jConfigPath);
} else {
defaultLogger.warn("log4j.properties not found on classpath! Logging configuration will not be reloaded.");
}
}
/**
* Executes the method close with no parameters on the object received. If
* the object is null, it does nothing (should this be logged?). Any
* exception thrown by the method invocation is logged as a warning (what
* else can we do?).
*
* Logs are logged by the default logger.
*
* @param o the object to be closed
* @todo use Closeable
*/
public static void close(Object o) {
close(o, defaultLogger);
}
/**
* Executes the method close with no parameters on the object received. If
* the object is null, it does nothing (should this be logged?). Any
* exception thrown by the method invocation is logged as a warning (what
* else can we do?).
*
* It allows the caller to specify a different logger.
*
* @param o the object to be closed
* @param logger logger to use
* @todo close discards null objects, see if this requires a warning
*/
public static void close(Object o, Logger logger) {
// discards null objects (exception thrown in object creation?)
if (o == null) {
return;
}
Class<?> c = o.getClass();
Method m = null;
try {
m = c.getMethod("close", new Class[0]);
} catch (Exception e) {
logger.error("Received object (of class " + c.getName()
+ ") doesn't implement close() method", e);
return;
}
try {
m.invoke(o, new Object[0]);
} catch (IllegalAccessException e) {
//ignore this. It's probably caused by an input stream from a file inside
//a jar.
} catch (Exception e) {
logger.warn("Error ocurred while closing object (of class "
+ c.getName() + ")", e);
return;
}
}
/**
* This method returns the fully qualified name of the class where it is invoked.
* The string returned is the same as the one returned by getClass().getName() on an
* instantiated object.
* It works even when invoked from a static code.
* Its main use is to identify the class using a log4j logger.
*
* This implementation's performance is not very good.
*
* The intended use is:
*
* private static final Logger logger = Logger.getLogger(Execute.whoAmI());
*/
public static String whoAmI() {
return new Throwable().getStackTrace()[1].getClassName();
}
/**
*
* @return the name of the method that calls this one
*/
public static String methodName() {
return new Throwable().getStackTrace()[1].getMethodName();
}
public static Class<?> myClass() {
return classContextyManager.getClassContext()[2];
}
/**
* Returns the unqualified name of the invoking class.
*/
public static String whatIsMyName() {
String name = whoCalledMe();
return name.substring(name.lastIndexOf(".")+1);
}
/**
* This method returns the fully qualified name of the class that invoked the caller.
* The string returned is the same as the one returned by getClass().getName() on an
* instantiated object.
*/
public static String whoCalledMe() {
return new Throwable().getStackTrace()[2].getClassName();
}
public static Class<?> myCallersClass() {
return classContextyManager.getClassContext()[3];
}
// Auxiliary object to synchronize a static method.
private static byte[] synchObj = new byte[1];
/**
* This method prints a stack trace.
*/
public static void printStackTrace() {
synchronized (synchObj) {
int level = 0;
System.out.println("Stack Trace:");
for (StackTraceElement e : new Throwable().getStackTrace()) {
if (level++>0) {
System.out.println(" ["+Thread.currentThread().getName()+"] "+e);
}
}
}
}
/**
* This method puts the invoker thread to sleep.
* This implementation wraps Thread.sleep() in a try catch exception, logging the
* InterruptedException in the default logger.
* @param millis the time in milliseconds to sleep
*/
public static void sleep(long millis) {
Execute.sleep(millis, defaultLogger);
}
/**
* This method puts the invoker thread to sleep.
* This implementation wraps Thread.sleep() in a try catch exception, logging the
* InterruptedException in the default logger.
* @param millis the time in milliseconds to sleep
* @param logger it logs the occurrence of an InterruptedException
*/
public static void sleep(long millis, Logger logger) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
logger.error("Interrupted ", e);
}
}
/**
* requests stop and waits til it actually stops
* @param s
*/
public static void stop(Stoppable s) {
s.requestStop();
while(!s.isStopped()) {
Execute.sleep(100);
}
}
/**
* Executes a task synchronously and if it takes longer than the specified timeout
* it gets interrupted and a TimeoutException is thrown.
*
* @param <T> the return type of the task
* @param callable the task to be executed
* @param timeout the maximum time in which the task should be completed
* @param unit the time unit of the given timeout.
* @return
* @throws ExecutionException if the task throws an exception
* @throws TimeoutException if the task doesn't complete before the timeout is reached
* @throws InterruptedException if this thread gets interrupted while waiting for the task to complete.
*/
public static <T> T executeWithTimeout(final Callable<T> callable, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException, InterruptedException {
return executeWithTimeout(callable, timeout, unit, "timeout");
}
/**
* Executes a task synchronously and if it takes longer than the specified timeout
* it gets interrupted and a TimeoutException is thrown.
*
* @param <T> the return type of the task
* @param callable the task to be executed
* @param timeout the maximum time in which the task should be completed
* @param unit the time unit of the given timeout.
* @param taskName the name of the task, the task will be executed in a thread with the same name as the
* current thread with "+taskName" appended to it.
* @return
* @throws ExecutionException if the task throws an exception
* @throws TimeoutException if the task doesn't complete before the timeout is reached
* @throws InterruptedException if this thread gets interrupted while waiting for the task to complete.
*/
public static <T> T executeWithTimeout(final Callable<T> callable, long timeout, TimeUnit unit, String taskName) throws ExecutionException, TimeoutException, InterruptedException {
final String newThreadName = Thread.currentThread().getName() + "+" + taskName;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<T> future = executor.submit(new Callable<T>() {
@Override
public T call() throws Exception {
Thread.currentThread().setName(newThreadName);
return callable.call();
}
});
executor.shutdown();
boolean completed;
try {
completed = executor.awaitTermination(timeout, unit);
} catch (InterruptedException e) {
// cancel the execution and propagate the interruption
future.cancel(true);
executor.shutdownNow();
throw e;
}
if (completed) {
return future.get();
} else {
future.cancel(true);
executor.shutdownNow();
throw new TimeoutException("Timed out");
}
}
/**
* Checks whether the given throwable is of the given type and if that's the case, it casts it
* and throws it.
*
* @param <T> the type to be checked
* @param throwableType a runtime instance of the type to be checked
* @param t the throwable to check
* @throws T if the given throwable was an instance of the given type
*/
public static <T extends Throwable> void checkAndThrow(Class<T> throwableType, Throwable t) throws T {
if (throwableType.isInstance(t)) {
throw throwableType.cast(t);
}
}
+ /**
+ * throws this exception if it is runtime or error, and throws a runtimeException
+ * if it is an Exception
+ * @param t
+ */
+ public static void runtimeOrError(Throwable t) {
+ if (t instanceof RuntimeException) throw (RuntimeException) t;
+ else if (t instanceof Error) throw (Error) t;
+ else throw new RuntimeException(t);
+ }
}
| true | false | null | null |
diff --git a/classes/com/sapienter/jbilling/client/user/MaintainAction.java b/classes/com/sapienter/jbilling/client/user/MaintainAction.java
index af9e4f38..88845285 100644
--- a/classes/com/sapienter/jbilling/client/user/MaintainAction.java
+++ b/classes/com/sapienter/jbilling/client/user/MaintainAction.java
@@ -1,358 +1,355 @@
/*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2009 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jbilling is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with jbilling. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sapienter.jbilling.client.user;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
import com.sapienter.jbilling.client.util.Constants;
import com.sapienter.jbilling.server.invoice.IInvoiceSessionBean;
import com.sapienter.jbilling.server.invoice.db.InvoiceDeliveryMethodDTO;
import com.sapienter.jbilling.server.order.db.OrderDTO;
import com.sapienter.jbilling.server.user.UserDTOEx;
import com.sapienter.jbilling.server.user.IUserSessionBean;
import com.sapienter.jbilling.server.user.db.CompanyDTO;
import com.sapienter.jbilling.server.user.db.CustomerDTO;
import com.sapienter.jbilling.server.user.db.UserDTO;
import com.sapienter.jbilling.server.user.partner.db.Partner;
import com.sapienter.jbilling.server.util.Context;
import com.sapienter.jbilling.server.util.db.CurrencyDTO;
import com.sapienter.jbilling.server.util.db.LanguageDTO;
import java.math.BigDecimal;
public class MaintainAction extends Action {
private static Logger LOG = Logger.getLogger(MaintainAction.class);
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
HttpSession session = request.getSession(false);
String action = request.getParameter("action");
if (action == null) {
LOG.error("action is required in maintain action");
throw new ServletException("action is required");
}
// this page requires a forward from, but not a forward to, as it
// always reders itself back with the result of the sumbision
String forward = (String) session.getAttribute(
Constants.SESSION_FORWARD_FROM);
Integer userId = (Integer) session.getAttribute(
Constants.SESSION_USER_ID);
Integer executorId = (Integer) session.getAttribute(
Constants.SESSION_LOGGED_USER_ID);
UserDTOEx userDto = (UserDTOEx) session.getAttribute(
Constants.SESSION_USER_DTO);
try {
IUserSessionBean userSession = (IUserSessionBean) Context.getBean(
Context.Name.USER_SESSION);
if (action.equals("setup")) {
String id = request.getParameter("id");
if (id != null) {
// called from anywhere to see a customer
userId = Integer.valueOf(id);
} else {
// called from the list when selectin a customer
userId = (Integer) session.getAttribute(
Constants.SESSION_LIST_ID_SELECTED);
}
// remove any cached list of sub-account, so they
// don't mixed up among parents
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_SUB_ACCOUNTS);
// now put the user data in the session for display
userDto = userSession.getUserDTOEx(userId);
session.setAttribute(Constants.SESSION_CUSTOMER_DTO,
userDto);
session.setAttribute(Constants.SESSION_USER_ID,
userId);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
// add the last invoice dto
IInvoiceSessionBean invoiceSession = (IInvoiceSessionBean)
Context.getBean(Context.Name.INVOICE_SESSION);
if (userDto.getLastInvoiceId() != null) {
LOG.debug("adding the latest inovoice: " +
userDto.getLastInvoiceId());
Integer languageId = (Integer) session.getAttribute(
Constants.SESSION_LANGUAGE);
session.setAttribute(Constants.SESSION_INVOICE_DTO,
invoiceSession.getInvoiceEx(userDto.getLastInvoiceId(),
languageId));
} else {
LOG.debug("there is no invoices.");
session.removeAttribute(Constants.SESSION_INVOICE_DTO);
}
return mapping.findForward("view");
}
if (forward == null) {
LOG.error("forward is required in the session");
throw new ServletException("forward is required in the session");
}
if (userId == null) {
LOG.error("userId is required in the session");
throw new ServletException("userId is required in the session");
}
// Validate and Confirm deletion
if (action.equals("confirmDelete")){
if( userSession.isParentCustomer(userId) && userSession.hasSubAccounts( userId) ){
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("user.delete.hasChild"));
forward = "edit";
} else {
userDto = userSession.getUserDTOEx(userId);
session.setAttribute("deleteUserName", userDto.getUserName());
forward = "confirmDelete";
}
} else if (action.equals("delete")) {
userSession.delete(executorId, userId);
// after deleting, it goes to the maintain page, showing the
// list of users
forward = Constants.FORWARD_USER_MAINTAIN;
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.delete.done", userId));
// get rid of the cached list of users
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER);
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER_SIMPLE);
} else if (action.equals("update")) {
DynaValidatorForm userForm = (DynaValidatorForm) form;
// get the info in its current status
UserDTOEx orgUser = (UserDTOEx) session.getAttribute(
Constants.SESSION_CUSTOMER_DTO);
LOG.debug("Updating user: ");
// general validation first
errors = userForm.validate(mapping, request);
// verify that the password and the verification password
// are the same, but only if the verify password has been
// entered, otherwise will consider that the password is not
// being changed
String vPassword = (String) userForm.get("verifyPassword");
String password = (String) userForm.get("password");
boolean updatePassword = false;
if ((vPassword != null && vPassword.trim().length() > 0) ||
(password != null && password.trim().length() > 0)) {
updatePassword = true;
}
if (updatePassword && (password == null ||
password.trim().length() == 0 || vPassword == null ||
vPassword.trim().length() == 0 ||
!password.equals(vPassword))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.password_match"));
}
//XXX
//Since passwords are stored encrypted, we can not do this check at client side anymore
//It should not be critical, because user is already authenticated
//and probably knows what to do.
//XXX: see commented block below
/**
* <code>
* // test that the old password is correct if this is a self-update
* if (updatePassword && userId.equals(executorId) &&
* !userDto.getPassword().equals((String) userForm.get(
* "oldPassword"))) {
*
* errors.add(ActionErrors.GLOBAL_ERROR,
* new ActionError("user.edit.error.invalidOldPassword"));
* }
* </code>
*/
String partnerId = (String) userForm.get("partnerId");
// validate the partnerId if present
if (errors.isEmpty() && partnerId != null && partnerId.length() > 0) {
if (userSession.getPartnerDTO(Integer.valueOf(partnerId)) ==
null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.badPartner"));
}
}
// the login name has to be unique across entities
// test only if it has changed
if (orgUser != null && !orgUser.getUserName().equals((String)
userForm.get("username"))) {
UserDTO testUser = userSession.getUserDTO(
(String) userForm.get("username"),
(Integer) userForm.get("entity"));
if (testUser != null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.taken",
(String) userForm.get("username")));
}
}
LOG.debug("balance type is " + userForm.get("balance_type") +
" credit limit is " + userForm.get("credit_limit"));
- if (((Integer) userForm.get("balance_type")).equals(Constants.BALANCE_CREDIT_LIMIT) &&
- ((String) userForm.get("credit_limit")).trim().length() == 0) {
- errors.add(ActionErrors.GLOBAL_ERROR,
- new ActionError("user.edit.error.invalidCreditLimit"));
+ if (Constants.BALANCE_CREDIT_LIMIT.equals((Integer) userForm.get("balance_type"))
+ && ((String) userForm.get("credit_limit")).trim().length() == 0) {
+ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("user.edit.error.invalidCreditLimit"));
}
- if (!((Integer) userForm.get("balance_type")).equals(Constants.BALANCE_CREDIT_LIMIT) &&
+ if (!Constants.BALANCE_CREDIT_LIMIT.equals((Integer) userForm.get("balance_type")) &&
((String) userForm.get("credit_limit")).trim().length() != 0) {
- errors.add(ActionErrors.GLOBAL_ERROR,
- new ActionError("user.edit.error.invalidNonCreditLimit"));
+ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("user.edit.error.invalidNonCreditLimit"));
}
- if (!((Integer) userForm.get("balance_type")).equals(Constants.BALANCE_PRE_PAID) &&
+ if (!Constants.BALANCE_PRE_PAID.equals((Integer) userForm.get("balance_type")) &&
((String) userForm.get("auto_recharge")).trim().length() != 0) {
- errors.add(ActionErrors.GLOBAL_ERROR,
- new ActionError("user.edit.error.invalidNonAutoRecharge"));
+ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("user.edit.error.invalidNonAutoRecharge"));
}
if (errors.isEmpty()) {
// create a dto with the info from the form
UserDTOEx dto = new UserDTOEx();
dto.setUserId(userId);
dto.setCompany(new CompanyDTO((Integer) userForm.get("entity")));
dto.setMainRoleId((Integer) userForm.get("type"));
dto.setUserName((String) userForm.get("username"));
if (updatePassword) {
dto.setPassword((String) userForm.get("password"));
} else {
dto.setPassword(null);
}
dto.setLanguage(new LanguageDTO((Integer) userForm.get("language")));
dto.setStatusId((Integer) userForm.get("status"));
dto.setCurrency(new CurrencyDTO((Integer) userForm.get("currencyId")));
dto.setSubscriptionStatusId((Integer)
userForm.get("subscriberStatus"));
if (dto.getMainRoleId().equals(Constants.TYPE_CUSTOMER)) {
dto.setCustomer(new CustomerDTO());
dto.getCustomer().setInvoiceDeliveryMethod(new InvoiceDeliveryMethodDTO(
(Integer) userForm.get("deliveryMethodId")));
dto.getCustomer().setDueDateUnitId(
(Integer) userForm.get("due_date_unit_id"));
String value = (String) userForm.get("due_date_value");
if (value != null && value.length() > 0) {
dto.getCustomer().setDueDateValue(
Integer.valueOf(value));
} else {
dto.getCustomer().setDueDateValue(null);
}
dto.getCustomer().setDfFm(new Integer(((Boolean)
userForm.get("chbx_df_fm")).booleanValue()
? 1 : 0));
dto.getCustomer().setExcludeAging(new Integer(((Boolean)
userForm.get("chbx_excludeAging")).booleanValue()
? 1 : 0));
dto.getCustomer().setBalanceType((Integer) userForm.get("balance_type"));
String cl = (String) userForm.get("credit_limit");
dto.getCustomer().setCreditLimit(cl.trim().length() == 0 ? null :
new BigDecimal(cl));
String recharge = (String) userForm.get("auto_recharge");
dto.getCustomer().setAutoRecharge(recharge.trim().length() == 0
? null
: new BigDecimal(recharge));
if (partnerId != null && partnerId.length() > 0) {
dto.getCustomer().setPartner(new Partner(Integer.valueOf(
partnerId)));
} else {
dto.getCustomer().setPartner(null);
}
}
// I pass who am I and the info to update
userSession.update(executorId, dto);
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.edit.done"));
}
} else if (action.equals("order")) {
OrderDTO summary = new OrderDTO();
session.setAttribute(Constants.SESSION_ORDER_SUMMARY,
summary);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
forward = "order";
// blacklist add/remove
} else if (action.equals("blacklist_add") || action.equals("blacklist_remove")) {
Integer blacklistUserId = Integer.parseInt(request.getParameter("userId"));
if (action.equals("blacklist_add")) {
userSession.setUserBlacklisted(executorId, userId, true);
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("blacklist.user.add.done"));
} else {
userSession.setUserBlacklisted(executorId, userId, false);
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("blacklist.user.remove.done"));
}
forward="userView";
} else {
LOG.error("action not supported" + action);
throw new ServletException("action is not supported :" + action);
}
saveMessages(request, messages);
} catch (Exception e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("all.internal"));
LOG.debug("Exception:", e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
return mapping.findForward(forward);
}
}
| false | false | null | null |
diff --git a/application/src/nl/sogeti/android/gpstracker/viewer/LoggerMap.java b/application/src/nl/sogeti/android/gpstracker/viewer/LoggerMap.java
index 6ba3b5ab..42fcb2cd 100644
--- a/application/src/nl/sogeti/android/gpstracker/viewer/LoggerMap.java
+++ b/application/src/nl/sogeti/android/gpstracker/viewer/LoggerMap.java
@@ -1,1560 +1,1564 @@
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.Statistics;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.Segments;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.logger.SettingsDialog;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import org.openintents.intents.AboutIntents;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
/**
* Main activity showing a track and allowing logging control
*
* @version $Id$
* @author rene (c) Jan 18, 2009, Sogeti B.V.
*/
public class LoggerMap extends MapActivity
{
private static final int ZOOM_LEVEL = 16;
// MENU'S
private static final int MENU_SETTINGS = 1;
private static final int MENU_TRACKING = 2;
private static final int MENU_TRACKLIST = 3;
private static final int MENU_STATS = 4;
private static final int MENU_ABOUT = 5;
private static final int MENU_LAYERS = 6;
private static final int MENU_NOTE = 7;
private static final int MENU_NAME = 8;
private static final int MENU_PICTURE = 9;
private static final int MENU_TEXT = 10;
private static final int MENU_VOICE = 11;
private static final int MENU_VIDEO = 12;
private static final int MENU_SHARE = 13;
private static final int DIALOG_TRACKNAME = 23;
private static final int DIALOG_NOTRACK = 24;
private static final int DIALOG_LOGCONTROL = 26;
private static final int DIALOG_INSTALL_ABOUT = 29;
private static final int DIALOG_LAYERS = 31;
private static final int DIALOG_TEXT = 32;
private static final int DIALOG_NAME = 33;
private static final int DIALOG_URIS = 34;
private static final String TAG = "OGT.LoggerMap";
private MapView mMapView = null;
private MyLocationOverlay mMylocation;
private CheckBox mSatellite;
private CheckBox mTraffic;
private CheckBox mSpeed;
private CheckBox mCompass;
private CheckBox mLocation;
private EditText mTrackNameView;
private TextView[] mSpeedtexts = null;
private TextView mLastGPSSpeedView = null;
private EditText mNoteNameView;
private EditText mNoteTextView;
private double mAverageSpeed = 33.33d / 2d;
private long mTrackId = -1;
private long mLastSegment = -1;
private long mLastWaypoint = -1;
private UnitsI18n mUnits;
private WakeLock mWakeLock = null;
private MapController mMapController = null;
private SharedPreferences mSharedPreferences;
private GPSLoggerServiceManager mLoggerServiceManager;
private final ContentObserver mTrackSegmentsObserver = new ContentObserver( new Handler() )
{
@Override
public void onChange( boolean selfUpdate )
{
if( !selfUpdate )
{
// Log.d( TAG, "mTrackSegmentsObserver "+ mTrackId );
LoggerMap.this.updateDataOverlays();
}
else
{
Log.d( TAG, "mTrackSegmentsObserver skipping change on "+ mLastSegment );
}
}
};
private final ContentObserver mSegmentWaypointsObserver = new ContentObserver( new Handler() )
{
@Override
public void onChange( boolean selfUpdate )
{
if( !selfUpdate )
{
// Log.d( TAG, "mSegmentWaypointsObserver "+ mLastSegment );
- LoggerMap.this.createSpeedDisplayNumbers();
+ LoggerMap.this.updateDisplayedSpeedViews();
if( mLastSegmentOverlay != null )
{
moveActiveViewWindow();
mLastSegmentOverlay.calculateTrack();
mMapView.postInvalidate();
}
}
else
{
Log.d( TAG, "mSegmentWaypointsObserver skipping change on "+ mLastSegment );
}
}
};
private final ContentObserver mTrackMediasObserver = new ContentObserver( new Handler() )
{
@Override
public void onChange( boolean selfUpdate )
{
if( !selfUpdate )
{
// Log.d( TAG, "mTrackMediasObserver "+ mTrackId );
if( mLastSegmentOverlay != null )
{
mLastSegmentOverlay.calculateMedia();
mMapView.postInvalidate();
}
}
else
{
Log.d( TAG, "mTrackMediasObserver skipping change on "+ mLastSegment );
}
}
};
private final DialogInterface.OnClickListener mNoTrackDialogListener = new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int which )
{
// Log.d( TAG, "mNoTrackDialogListener" + which);
Intent tracklistIntent = new Intent( LoggerMap.this, TrackList.class );
tracklistIntent.putExtra( Tracks._ID, LoggerMap.this.mTrackId );
startActivityForResult( tracklistIntent, MENU_TRACKLIST );
}
};
private final DialogInterface.OnClickListener mTrackNameDialogListener = new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int which )
{
String trackName = mTrackNameView.getText().toString();
ContentValues values = new ContentValues();
values.put( Tracks.NAME, trackName );
getContentResolver().update( ContentUris.withAppendedId( Tracks.CONTENT_URI, LoggerMap.this.mTrackId ), values, null, null );
updateTitleBar();
}
};
private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int which )
{
Uri oiDownload = Uri.parse( "market://details?id=org.openintents.about" );
Intent oiAboutIntent = new Intent( Intent.ACTION_VIEW, oiDownload );
try
{
startActivity( oiAboutIntent );
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse( "http://openintents.googlecode.com/files/AboutApp-1.0.0.apk" );
oiAboutIntent = new Intent( Intent.ACTION_VIEW, oiDownload );
startActivity( oiAboutIntent );
}
}
};
private final View.OnClickListener mLoggingControlListener = new View.OnClickListener()
{
public void onClick( View v )
{
int id = v.getId();
switch (id)
{
case R.id.logcontrol_start:
long loggerTrackId = mLoggerServiceManager.startGPSLogging( null );
moveToTrack( loggerTrackId, true );
showDialog( DIALOG_TRACKNAME );
break;
case R.id.logcontrol_pause:
mLoggerServiceManager.pauseGPSLogging();
break;
case R.id.logcontrol_resume:
mLoggerServiceManager.resumeGPSLogging();
break;
case R.id.logcontrol_stop:
mLoggerServiceManager.stopGPSLogging();
break;
default:
break;
}
updateBlankingBehavior();
dismissDialog( DIALOG_LOGCONTROL );
}
};
private final OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener()
{
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked )
{
int which = buttonView.getId();
switch (which)
{
case R.id.layer_satellite:
setSatelliteOverlay( isChecked );
break;
case R.id.layer_traffic:
setTrafficOverlay( isChecked );
break;
case R.id.layer_speed:
setSpeedOverlay( isChecked );
break;
case R.id.layer_compass:
setCompassOverlay( isChecked );
break;
case R.id.layer_location:
setLocationOverlay( isChecked );
break;
default:
break;
}
}
};
private final OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key )
{
if( key.equals( Constants.TRACKCOLORING ) )
{
int trackColoringMethod = new Integer( sharedPreferences.getString( Constants.TRACKCOLORING, "3" ) ).intValue();
updateSpeedbarVisibility();
List<Overlay> overlays = LoggerMap.this.mMapView.getOverlays();
for (Overlay overlay : overlays)
{
if( overlay instanceof SegmentOverlay )
{
( (SegmentOverlay) overlay ).setTrackColoringMethod( trackColoringMethod, mAverageSpeed );
}
}
}
else if( key.equals( Constants.DISABLEBLANKING ) )
{
updateBlankingBehavior();
}
else if( key.equals( Constants.SPEED ) )
{
updateSpeedDisplayVisibility();
}
else if( key.equals( Constants.COMPASS ) )
{
updateCompassDisplayVisibility();
}
else if( key.equals( Constants.TRAFFIC ) )
{
LoggerMap.this.mMapView.setTraffic( sharedPreferences.getBoolean( key, false ) );
}
else if( key.equals( Constants.SATELLITE ) )
{
LoggerMap.this.mMapView.setSatellite( sharedPreferences.getBoolean( key, false ) );
}
else if( key.equals( Constants.LOCATION ) )
{
updateLocationDisplayVisibility();
}
}
};
private final UnitsI18n.UnitsChangeListener mUnitsChangeListener = new UnitsI18n.UnitsChangeListener()
{
public void onUnitsChange()
{
- createSpeedDisplayNumbers();
+ updateDisplayedSpeedViews();
updateSpeedbarVisibility();
}
};
private final OnClickListener mNoteTextDialogListener = new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int which )
{
String noteText = mNoteTextView.getText().toString();
Calendar c = Calendar.getInstance();
String newName = String.format( "Textnote_%tY-%tm-%td_%tH%tM%tS.txt", c, c, c, c, c, c );
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File( sdcard + Constants.EXTERNAL_DIR + newName );
FileWriter filewriter = null;
try
{
file.getParentFile().mkdirs();
file.createNewFile();
filewriter = new FileWriter( file );
filewriter.append( noteText );
filewriter.flush();
}
catch (IOException e)
{
Log.e( TAG, "Note storing failed", e );
CharSequence text = e.getLocalizedMessage();
Toast toast = Toast.makeText( LoggerMap.this.getApplicationContext(), text, Toast.LENGTH_LONG );
toast.show();
}
finally
{
if( filewriter!=null){ try { filewriter.close(); } catch (IOException e){ /* */ } }
}
LoggerMap.this.mLoggerServiceManager.storeMediaUri( Uri.fromFile( file ) );
}
};
private final OnClickListener mNoteNameDialogListener = new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int which )
{
String name = mNoteNameView.getText().toString();
Uri media = Uri.withAppendedPath( Constants.NAME_URI, Uri.encode( name ) );
LoggerMap.this.mLoggerServiceManager.storeMediaUri( media );
}
};
private final OnClickListener mNoteSelectDialogListener = new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int which )
{
Uri selected = (Uri) mGallery.getSelectedItem();
SegmentOverlay.handleMedia( LoggerMap.this, selected );
}
};
private SegmentOverlay mLastSegmentOverlay;
private BaseAdapter mMediaAdapter;
private Gallery mGallery;
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate( Bundle load )
{
Log.d( TAG, "onCreate()" );
super.onCreate( load );
this.startService( new Intent( Constants.SERVICENAME ) );
Object previousInstanceData = getLastNonConfigurationInstance();
if( previousInstanceData != null && previousInstanceData instanceof GPSLoggerServiceManager )
{
mLoggerServiceManager = (GPSLoggerServiceManager) previousInstanceData;
}
else
{
mLoggerServiceManager = new GPSLoggerServiceManager( (Context) this );
}
mLoggerServiceManager.startup();
mUnits = new UnitsI18n( this, mUnitsChangeListener );
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences( this );
mSharedPreferences.registerOnSharedPreferenceChangeListener( mSharedPreferenceChangeListener );
setContentView( R.layout.map );
mMapView = (MapView) findViewById( R.id.myMapView );
mMylocation = new FixedMyLocationOverlay( this, mMapView );
mMapController = this.mMapView.getController();
mMapView.setBuiltInZoomControls( true );
mMapView.setClickable( true );
mMapView.setStreetView( false );
mMapView.setSatellite( mSharedPreferences.getBoolean( Constants.SATELLITE, false ) );
mMapView.setTraffic( mSharedPreferences.getBoolean( Constants.TRAFFIC, false ) );
TextView[] speeds = { (TextView) findViewById( R.id.speedview05 ), (TextView) findViewById( R.id.speedview04 ), (TextView) findViewById( R.id.speedview03 ),
(TextView) findViewById( R.id.speedview02 ), (TextView) findViewById( R.id.speedview01 ), (TextView) findViewById( R.id.speedview00 ) };
mSpeedtexts = speeds;
mLastGPSSpeedView = (TextView) findViewById( R.id.currentSpeed );
onRestoreInstanceState( load );
}
protected void onPause()
{
Log.d( TAG, "onPause()" );
super.onPause();
if( this.mWakeLock != null && this.mWakeLock.isHeld() )
{
this.mWakeLock.release();
Log.w( TAG, "onPause(): Released lock to keep screen on!" );
}
if( mTrackId > 0 )
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
resolver.unregisterContentObserver( this.mTrackSegmentsObserver );
resolver.unregisterContentObserver( this.mSegmentWaypointsObserver );
resolver.unregisterContentObserver( this.mTrackMediasObserver );
}
mMylocation.disableMyLocation();
mMylocation.disableCompass();
}
protected void onResume()
{
Log.d( TAG, "onResume" );
super.onResume();
updateTitleBar();
updateBlankingBehavior();
updateSpeedbarVisibility();
updateSpeedDisplayVisibility();
updateCompassDisplayVisibility();
updateLocationDisplayVisibility();
if( mTrackId >= 0 )
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Uri trackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, mTrackId+"/segments" );
Uri lastSegmentUri = Uri.withAppendedPath( Tracks.CONTENT_URI, mTrackId+"/segments/"+mLastSegment+"/waypoints" );
Uri mediaUri = ContentUris.withAppendedId( Media.CONTENT_URI, mTrackId );
resolver.unregisterContentObserver( this.mTrackSegmentsObserver );
resolver.unregisterContentObserver( this.mSegmentWaypointsObserver );
resolver.unregisterContentObserver( this.mTrackMediasObserver );
resolver.registerContentObserver( trackUri, false, this.mTrackSegmentsObserver );
resolver.registerContentObserver( lastSegmentUri, true, this.mSegmentWaypointsObserver );
resolver.registerContentObserver( mediaUri, true, this.mTrackMediasObserver );
}
updateDataOverlays();
}
/*
* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onDestroy()
{
Log.d( TAG, "onDestroy" );
this.mLoggerServiceManager.shutdown();
if( mWakeLock != null && mWakeLock.isHeld() )
{
mWakeLock.release();
Log.w( TAG, "onDestroy(): Released lock to keep screen on!" );
}
mSharedPreferences.unregisterOnSharedPreferenceChangeListener( this.mSharedPreferenceChangeListener );
if( mLoggerServiceManager.getLoggingState() == Constants.STOPPED )
{
stopService( new Intent( Constants.SERVICENAME ) );
}
super.onDestroy();
}
/*
* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onNewIntent(android.content.Intent)
*/
@Override
public void onNewIntent( Intent newIntent )
{
Log.d( TAG, "onNewIntent" );
Uri data = newIntent.getData();
if( data != null )
{
moveToTrack( Long.parseLong( data.getLastPathSegment() ), true );
}
}
@Override
protected void onRestoreInstanceState( Bundle load )
{
if( load != null )
{
// Log.d( TAG, "Restoring the prevoious map " );
super.onRestoreInstanceState( load );
}
Uri data = this.getIntent().getData();
if( load != null && load.containsKey( "track" ) ) // 1st track from a previous instance of this activity
{
long loadTrackId = load.getLong( "track" );
// Log.d( TAG, "Moving to restored track "+loadTrackId );
moveToTrack( loadTrackId, false );
}
else if( data != null ) // 2nd track ordered to make
{
long loadTrackId = Long.parseLong( data.getLastPathSegment() );
// Log.d( TAG, "Moving to intented track "+loadTrackId );
moveToTrack( loadTrackId, true );
}
else
{
// Log.d( TAG, "Moving to last track " );
moveToLastTrack(); // 3rd just try the last track
}
if( load != null && load.containsKey( "zoom" ) )
{
this.mMapController.setZoom( load.getInt( "zoom" ) );
}
else
{
this.mMapController.setZoom( LoggerMap.ZOOM_LEVEL );
}
if( load != null && load.containsKey( "e6lat" ) && load.containsKey( "e6long" ) )
{
GeoPoint storedPoint = new GeoPoint( load.getInt( "e6lat" ), load.getInt( "e6long" ) );
this.mMapView.getController().animateTo( storedPoint );
}
else
{
GeoPoint lastPoint = getLastTrackPoint();
this.mMapView.getController().animateTo( lastPoint );
}
}
@Override
protected void onSaveInstanceState( Bundle save )
{
super.onSaveInstanceState( save );
save.putLong( "track", this.mTrackId );
save.putInt( "zoom", this.mMapView.getZoomLevel() );
GeoPoint point = this.mMapView.getMapCenter();
save.putInt( "e6lat", point.getLatitudeE6() );
save.putInt( "e6long", point.getLongitudeE6() );
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRetainNonConfigurationInstance()
*/
@Override
public Object onRetainNonConfigurationInstance()
{
Object nonConfigurationInstance = this.mLoggerServiceManager;
return nonConfigurationInstance;
}
@Override
public boolean onKeyDown( int keyCode, KeyEvent event )
{
boolean propagate = true;
switch (keyCode)
{
case KeyEvent.KEYCODE_T:
propagate = this.mMapView.getController().zoomIn();
break;
case KeyEvent.KEYCODE_G:
propagate = this.mMapView.getController().zoomOut();
break;
case KeyEvent.KEYCODE_S:
setSatelliteOverlay( !this.mMapView.isSatellite() );
propagate = false;
break;
case KeyEvent.KEYCODE_A:
setTrafficOverlay( !this.mMapView.isTraffic() );
propagate = false;
break;
case KeyEvent.KEYCODE_F:
moveToTrack( this.mTrackId - 1, true );
propagate = false;
break;
case KeyEvent.KEYCODE_H:
moveToTrack( this.mTrackId + 1, true );
propagate = false;
break;
default:
propagate = super.onKeyDown( keyCode, event );
break;
}
return propagate;
}
private void setTrafficOverlay( boolean b )
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean( Constants.TRAFFIC, b );
editor.commit();
}
private void setSatelliteOverlay( boolean b )
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean( Constants.SATELLITE, b );
editor.commit();
}
private void setSpeedOverlay( boolean b )
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean( Constants.SPEED, b );
editor.commit();
}
private void setCompassOverlay( boolean b )
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean( Constants.COMPASS, b );
editor.commit();
}
private void setLocationOverlay( boolean b )
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean( Constants.LOCATION, b );
editor.commit();
}
@Override
public boolean onCreateOptionsMenu( Menu menu )
{
boolean result = super.onCreateOptionsMenu( menu );
menu.add( ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking ).setIcon( R.drawable.ic_menu_movie ).setAlphabeticShortcut( 'T' );
menu.add( ContextMenu.NONE, MENU_LAYERS, ContextMenu.NONE, R.string.menu_showLayers ).setIcon( R.drawable.ic_menu_mapmode ).setAlphabeticShortcut( 'L' );
SubMenu notemenu = menu.addSubMenu( ContextMenu.NONE, MENU_NOTE, ContextMenu.NONE, R.string.menu_insertnote ).setIcon( R.drawable.ic_menu_myplaces );
menu.add( ContextMenu.NONE, MENU_STATS, ContextMenu.NONE, R.string.menu_statistics ).setIcon( R.drawable.ic_menu_picture ).setAlphabeticShortcut( 'S' );
menu.add( ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack ).setIcon( R.drawable.ic_menu_share ).setAlphabeticShortcut('I');
// More
menu.add( ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist ).setIcon( R.drawable.ic_menu_show_list ).setAlphabeticShortcut( 'P' );
menu.add( ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings ).setIcon( R.drawable.ic_menu_preferences ).setAlphabeticShortcut( 'C' );
menu.add( ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about ).setIcon( R.drawable.ic_menu_info_details ).setAlphabeticShortcut( 'A' );
notemenu.add( ContextMenu.NONE, MENU_NAME, ContextMenu.NONE, R.string.menu_notename );
notemenu.add( ContextMenu.NONE, MENU_TEXT, ContextMenu.NONE, R.string.menu_notetext );
notemenu.add( ContextMenu.NONE, MENU_VOICE, ContextMenu.NONE, R.string.menu_notespeech );
notemenu.add( ContextMenu.NONE, MENU_PICTURE, ContextMenu.NONE, R.string.menu_notepicture );
notemenu.add( ContextMenu.NONE, MENU_VIDEO, ContextMenu.NONE, R.string.menu_notevideo );
return result;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu( Menu menu )
{
MenuItem notemenu = menu.findItem( MENU_NOTE );
notemenu.setEnabled( mLoggerServiceManager.isMediaPrepared() );
MenuItem sharemenu = menu.findItem( MENU_SHARE );
sharemenu.setEnabled( mTrackId >= 0 );
return super.onPrepareOptionsMenu( menu );
}
@Override
public boolean onOptionsItemSelected( MenuItem item )
{
boolean handled = false;
Uri trackUri;
switch (item.getItemId())
{
case MENU_TRACKING:
showDialog( DIALOG_LOGCONTROL );
updateBlankingBehavior();
handled = true;
break;
case MENU_LAYERS:
showDialog( DIALOG_LAYERS );
handled = true;
break;
case MENU_SETTINGS:
Intent i = new Intent( this, SettingsDialog.class );
startActivity( i );
handled = true;
break;
case MENU_TRACKLIST:
Intent tracklistIntent = new Intent( this, TrackList.class );
tracklistIntent.putExtra( Tracks._ID, this.mTrackId );
startActivityForResult( tracklistIntent, MENU_TRACKLIST );
break;
case MENU_STATS:
if( this.mTrackId >= 0 )
{
Intent actionIntent = new Intent( this, Statistics.class );
trackUri = ContentUris.withAppendedId( Tracks.CONTENT_URI, mTrackId );
actionIntent.setData( trackUri );
startActivity( actionIntent );
handled = true;
break;
}
else
{
showDialog( DIALOG_NOTRACK );
}
handled = true;
break;
case MENU_ABOUT:
Intent intent = new Intent( AboutIntents.ACTION_SHOW_ABOUT_DIALOG );
try
{
startActivityForResult( intent, MENU_ABOUT );
}
catch (ActivityNotFoundException e)
{
showDialog( DIALOG_INSTALL_ABOUT );
}
break;
case MENU_SHARE:
Intent actionIntent = new Intent( Intent.ACTION_RUN );
trackUri = ContentUris.withAppendedId( Tracks.CONTENT_URI, mTrackId );
actionIntent.setDataAndType( trackUri, Tracks.CONTENT_ITEM_TYPE );
actionIntent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
startActivity( Intent.createChooser( actionIntent, getString( R.string.share_track ) ) );
handled = true;
break;
case MENU_PICTURE:
addPicture();
handled = true;
break;
case MENU_VIDEO:
addVideo();
handled = true;
break;
case MENU_VOICE:
addVoice();
handled = true;
break;
case MENU_TEXT:
showDialog( DIALOG_TEXT );
handled = true;
break;
case MENU_NAME:
showDialog( DIALOG_NAME );
handled = true;
break;
default:
handled = super.onOptionsItemSelected( item );
break;
}
return handled;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_TRACKNAME:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.namedialog, null );
mTrackNameView = (EditText) view.findViewById( R.id.nameField );
builder
.setTitle( R.string.dialog_routename_title )
.setMessage( R.string.dialog_routename_message )
.setIcon( android.R.drawable.ic_dialog_alert )
.setPositiveButton( R.string.btn_okay, mTrackNameDialogListener )
.setView( view );
dialog = builder.create();
return dialog;
case DIALOG_LAYERS:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.layerdialog, null );
mSatellite = (CheckBox) view.findViewById( R.id.layer_satellite );
mSatellite.setOnCheckedChangeListener( mCheckedChangeListener );
mTraffic = (CheckBox) view.findViewById( R.id.layer_traffic );
mTraffic.setOnCheckedChangeListener( mCheckedChangeListener );
mSpeed = (CheckBox) view.findViewById( R.id.layer_speed );
mSpeed.setOnCheckedChangeListener( mCheckedChangeListener );
mCompass = (CheckBox) view.findViewById( R.id.layer_compass );
mCompass.setOnCheckedChangeListener( mCheckedChangeListener );
mLocation = (CheckBox) view.findViewById( R.id.layer_location );
mLocation.setOnCheckedChangeListener( mCheckedChangeListener );
builder
.setTitle( R.string.dialog_layer_title )
.setIcon( android.R.drawable.ic_dialog_map )
.setPositiveButton( R.string.btn_okay, null )
.setView( view );
dialog = builder.create();
return dialog;
case DIALOG_NOTRACK:
builder = new AlertDialog.Builder( this );
builder
.setTitle( R.string.dialog_notrack_title )
.setMessage( R.string.dialog_notrack_message )
.setIcon( android.R.drawable.ic_dialog_alert )
.setPositiveButton( R.string.btn_selecttrack, mNoTrackDialogListener )
.setNegativeButton( R.string.btn_cancel, null );
dialog = builder.create();
return dialog;
case DIALOG_LOGCONTROL:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.logcontrol, null );
builder
.setTitle( R.string.dialog_tracking_title )
.setIcon( android.R.drawable.ic_dialog_alert )
.setNegativeButton( R.string.btn_cancel, null )
.setView( view );
dialog = builder.create();
return dialog;
case DIALOG_INSTALL_ABOUT:
builder = new AlertDialog.Builder( this );
builder
.setTitle( R.string.dialog_nooiabout )
.setMessage( R.string.dialog_nooiabout_message )
.setIcon( android.R.drawable.ic_dialog_alert )
.setPositiveButton( R.string.btn_install, mOiAboutDialogListener )
.setNegativeButton( R.string.btn_cancel, null );
dialog = builder.create();
return dialog;
case DIALOG_TEXT:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.notetextdialog, null );
mNoteTextView = (EditText) view.findViewById( R.id.notetext );
builder
.setTitle( R.string.dialog_notetext_title )
.setMessage( R.string.dialog_notetext_message )
.setIcon( android.R.drawable.ic_dialog_map )
.setPositiveButton( R.string.btn_okay, mNoteTextDialogListener )
.setNegativeButton( R.string.btn_cancel, null )
.setView( view );
dialog = builder.create();
return dialog;
case DIALOG_NAME:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.notenamedialog, null );
mNoteNameView = (EditText) view.findViewById( R.id.notename );
builder
.setTitle( R.string.dialog_notename_title )
.setMessage( R.string.dialog_notename_message )
.setIcon( android.R.drawable.ic_dialog_map )
.setPositiveButton( R.string.btn_okay, mNoteNameDialogListener )
.setNegativeButton( R.string.btn_cancel, null )
.setView( view );
dialog = builder.create();
return dialog;
case DIALOG_URIS:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.mediachooser, null );
mGallery = (Gallery) view.findViewById( R.id.gallery );
builder
.setTitle( R.string.dialog_select_media_title )
.setMessage( R.string.dialog_select_media_message )
.setIcon( android.R.drawable.ic_dialog_alert )
.setNegativeButton( R.string.btn_cancel, null )
.setPositiveButton( R.string.btn_okay, mNoteSelectDialogListener )
.setView( view );
dialog = builder.create();
return dialog;
default:
return super.onCreateDialog( id );
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog( int id, Dialog dialog )
{
int state = mLoggerServiceManager.getLoggingState();
switch (id)
{
case DIALOG_LOGCONTROL:
Button start = (Button) dialog.findViewById( R.id.logcontrol_start );
Button pause = (Button) dialog.findViewById( R.id.logcontrol_pause );
Button resume = (Button) dialog.findViewById( R.id.logcontrol_resume );
Button stop = (Button) dialog.findViewById( R.id.logcontrol_stop );
start.setOnClickListener( mLoggingControlListener );
pause.setOnClickListener( mLoggingControlListener );
resume.setOnClickListener( mLoggingControlListener );
stop.setOnClickListener( mLoggingControlListener );
switch (state)
{
case Constants.STOPPED:
start.setEnabled( true );
pause.setEnabled( false );
resume.setEnabled( false );
stop.setEnabled( false );
break;
case Constants.LOGGING:
start.setEnabled( false );
pause.setEnabled( true );
resume.setEnabled( false );
stop.setEnabled( true );
break;
case Constants.PAUSED:
start.setEnabled( false );
pause.setEnabled( false );
resume.setEnabled( true );
stop.setEnabled( true );
break;
default:
Log.e( TAG, String.format( "State %d of logging, enabling and hope for the best....", state ) );
start.setEnabled( true );
pause.setEnabled( true );
resume.setEnabled( true );
stop.setEnabled( true );
break;
}
break;
case DIALOG_LAYERS:
mSatellite.setChecked( mSharedPreferences.getBoolean( Constants.SATELLITE, false ) );
mTraffic.setChecked( mSharedPreferences.getBoolean( Constants.TRAFFIC, false ) );
mSpeed.setChecked( mSharedPreferences.getBoolean( Constants.SPEED, false ) );
mCompass.setChecked( mSharedPreferences.getBoolean( Constants.COMPASS, false ) );
mLocation.setChecked( mSharedPreferences.getBoolean( Constants.LOCATION, false ) );
break;
case DIALOG_URIS:
mGallery.setAdapter( mMediaAdapter );
default:
break;
}
super.onPrepareDialog( id, dialog );
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent intent )
{
super.onActivityResult( requestCode, resultCode, intent );
if( resultCode != RESULT_CANCELED )
{
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
File file;
Uri uri;
File newFile;
String newName;
Uri fileUri;
android.net.Uri.Builder builder;
switch (requestCode)
{
case MENU_TRACKLIST:
Uri trackUri = intent.getData();
long trackId = Long.parseLong( trackUri.getLastPathSegment() );
moveToTrack( trackId, true );
break;
case MENU_ABOUT:
break;
case MENU_PICTURE:
file = new File( sdcard + Constants.TMPICTUREFILE_PATH );
Calendar c = Calendar.getInstance();
newName = String.format( "Picture_%tY-%tm-%td_%tH%tM%tS.jpg", c, c, c, c, c, c );
newFile = new File( sdcard + Constants.EXTERNAL_DIR + newName );
file.getParentFile().mkdirs();
file.renameTo( newFile );
Bitmap bm = BitmapFactory.decodeFile( newFile.getAbsolutePath() );
String height = Integer.toString( bm.getHeight() );
String width = Integer.toString( bm.getWidth() );
bm.recycle();
bm = null;
builder = new Uri.Builder();
fileUri = builder.scheme( "file").
appendEncodedPath( "/" ).
appendEncodedPath( newFile.getAbsolutePath() ).
appendQueryParameter( "width", width ).
appendQueryParameter( "height", height )
.build();
this.mLoggerServiceManager.storeMediaUri( fileUri );
mLastSegmentOverlay.calculateMedia();
mMapView.postInvalidate();
break;
case MENU_VIDEO:
file = new File( sdcard + Constants.TMPICTUREFILE_PATH );
c = Calendar.getInstance();
newName = String.format( "Video_%tY%tm%td_%tH%tM%tS.3gp", c, c, c, c, c, c );
newFile = new File( sdcard + Constants.EXTERNAL_DIR + newName );
file.getParentFile().mkdirs();
file.renameTo( newFile );
builder = new Uri.Builder();
fileUri = builder.scheme( "file").
appendPath( newFile.getAbsolutePath() ).build();
this.mLoggerServiceManager.storeMediaUri( fileUri );
mLastSegmentOverlay.calculateMedia();
mMapView.postInvalidate();
break;
case MENU_VOICE:
uri = Uri.parse( intent.getDataString() );
this.mLoggerServiceManager.storeMediaUri( uri );
mLastSegmentOverlay.calculateMedia();
mMapView.postInvalidate();
break;
default:
Log.e( TAG, "Returned form unknow activity: " + requestCode );
break;
}
}
}
/**
* (non-Javadoc)
*
* @see com.google.android.maps.MapActivity#isRouteDisplayed()
*/
@Override
protected boolean isRouteDisplayed()
{
return true;
}
private void updateTitleBar()
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Cursor trackCursor = null;
try
{
trackCursor = resolver.query( ContentUris.withAppendedId( Tracks.CONTENT_URI, this.mTrackId ), new String[] { Tracks.NAME }, null, null, null );
if( trackCursor != null && trackCursor.moveToLast() )
{
String trackName = trackCursor.getString( 0 );
this.setTitle( this.getString( R.string.app_name ) + ": " + trackName );
}
}
finally
{
if( trackCursor != null )
{
trackCursor.close();
}
}
}
private void updateBlankingBehavior()
{
boolean disableblanking = mSharedPreferences.getBoolean( Constants.DISABLEBLANKING, false );
if( disableblanking )
{
if( mWakeLock == null )
{
PowerManager pm = (PowerManager) this.getSystemService( Context.POWER_SERVICE );
mWakeLock = pm.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK, TAG );
}
if( mLoggerServiceManager.getLoggingState() == Constants.LOGGING && !mWakeLock.isHeld() )
{
mWakeLock.acquire();
Log.w( TAG, "Acquired lock to keep screen on!" );
}
}
}
private void updateSpeedbarVisibility()
{
int trackColoringMethod = new Integer( mSharedPreferences.getString( Constants.TRACKCOLORING, "3" ) ).intValue();
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Cursor waypointsCursor = null;
try
{
waypointsCursor = resolver.query( Uri.withAppendedPath( Tracks.CONTENT_URI, this.mTrackId + "/waypoints" ), new String[] { "avg(" + Waypoints.SPEED + ")" }, null, null, null );
if( waypointsCursor != null && waypointsCursor.moveToLast() )
{
mAverageSpeed = waypointsCursor.getDouble( 0 );
}
- if( mAverageSpeed < 5 )
+ if( mAverageSpeed < 2 )
{
- mAverageSpeed = 33.33d / 2d;
+ mAverageSpeed = 5.55d / 2;
}
}
finally
{
if( waypointsCursor != null )
{
waypointsCursor.close();
}
}
View speedbar = findViewById( R.id.speedbar );
if( trackColoringMethod == SegmentOverlay.DRAW_MEASURED || trackColoringMethod == SegmentOverlay.DRAW_CALCULATED )
{
drawSpeedTexts( mAverageSpeed );
speedbar.setVisibility( View.VISIBLE );
for (int i = 0; i < mSpeedtexts.length; i++)
{
mSpeedtexts[i].setVisibility( View.VISIBLE );
}
}
else
{
speedbar.setVisibility( View.INVISIBLE );
for (int i = 0; i < mSpeedtexts.length; i++)
{
mSpeedtexts[i].setVisibility( View.INVISIBLE );
}
}
}
private void updateSpeedDisplayVisibility()
{
boolean showspeed = mSharedPreferences.getBoolean( Constants.SPEED, false );
if( showspeed )
{
mLastGPSSpeedView.setVisibility( View.VISIBLE );
mLastGPSSpeedView.setText( "" );
}
else
{
mLastGPSSpeedView.setVisibility( View.INVISIBLE );
}
}
private void updateCompassDisplayVisibility()
{
boolean compass = mSharedPreferences.getBoolean( Constants.COMPASS, false );
if( compass )
{
mMylocation.enableCompass();
}
else
{
mMylocation.disableCompass();
}
}
private void updateLocationDisplayVisibility()
{
boolean location = mSharedPreferences.getBoolean( Constants.LOCATION, false );
if( location )
{
mMylocation.enableMyLocation();
}
else
{
mMylocation.disableMyLocation();
}
}
- protected void createSpeedDisplayNumbers()
+ private void updateDisplayedSpeedViews()
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Cursor waypointsCursor = null;
try
{
Uri lastSegmentUri = Uri.withAppendedPath( Tracks.CONTENT_URI, this.mTrackId + "/segments/" + mLastSegment + "/waypoints" );
waypointsCursor = resolver.query( lastSegmentUri, new String[] { Waypoints.SPEED }, null, null, null );
if( waypointsCursor != null && waypointsCursor.moveToLast() )
{
double speed = waypointsCursor.getDouble( 0 );
speed = mUnits.conversionFromMetersPerSecond( speed );
String speedText = String.format( "%.0f %s", speed, mUnits.getSpeedUnit() );
mLastGPSSpeedView.setText( speedText );
+ if( speed > 2*mAverageSpeed )
+ {
+ updateSpeedbarVisibility();
+ }
}
}
finally
{
if( waypointsCursor != null )
{
waypointsCursor.close();
}
}
}
/**
* For the current track identifier the route of that track is drawn by adding a OverLay for each segments in the track
*
* @param trackId
* @see SegmentOverlay
*/
private void createDataOverlays()
{
mLastSegmentOverlay = null;
List<Overlay> overlays = this.mMapView.getOverlays();
overlays.clear();
overlays.add( mMylocation );
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Cursor segments = null;
int trackColoringMethod = new Integer( mSharedPreferences.getString( Constants.TRACKCOLORING, "2" ) ).intValue();
try
{
Uri segmentsUri = Uri.withAppendedPath( Tracks.CONTENT_URI, this.mTrackId + "/segments" );
segments = resolver.query( segmentsUri, new String[] { Segments._ID }, null, null, null );
if( segments != null && segments.moveToFirst() )
{
do
{
long segmentsId = segments.getLong( 0 );
Uri segmentUri = ContentUris.withAppendedId( segmentsUri, segmentsId );
SegmentOverlay segmentOverlay = new SegmentOverlay( this, segmentUri, trackColoringMethod, mAverageSpeed, this.mMapView );
overlays.add( segmentOverlay );
mLastSegmentOverlay = segmentOverlay;
if( segments.isFirst() )
{
segmentOverlay.addPlacement( SegmentOverlay.FIRST_SEGMENT );
}
if( segments.isLast() )
{
segmentOverlay.addPlacement( SegmentOverlay.LAST_SEGMENT );
getLastTrackPoint();
}
mLastSegment = segmentsId;
}
while (segments.moveToNext());
}
}
finally
{
if( segments != null )
{
segments.close();
}
}
moveActiveViewWindow();
Uri lastSegmentUri = Uri.withAppendedPath( Tracks.CONTENT_URI, mTrackId+"/segments/"+mLastSegment+"/waypoints" );
resolver.unregisterContentObserver( this.mSegmentWaypointsObserver );
resolver.registerContentObserver( lastSegmentUri, false, this.mSegmentWaypointsObserver );
}
private void updateDataOverlays()
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Uri segmentsUri = Uri.withAppendedPath( Tracks.CONTENT_URI, this.mTrackId + "/segments" );
Cursor segmentsCursor = null;
List<Overlay> overlays = this.mMapView.getOverlays();
int segmentOverlaysCount = 0;
for( Overlay overlay : overlays )
{
if( overlay instanceof SegmentOverlay )
{
segmentOverlaysCount++;
}
}
try
{
segmentsCursor = resolver.query( segmentsUri, new String[] { Segments._ID }, null, null, null );
if( segmentsCursor != null && segmentsCursor.getCount() == segmentOverlaysCount )
{
// Log.d( TAG, "Alignment of segments" );
}
else
{
createDataOverlays();
}
}
finally
{
if( segmentsCursor != null ) { segmentsCursor.close(); }
}
moveActiveViewWindow();
}
private void moveActiveViewWindow()
{
GeoPoint lastPoint = getLastTrackPoint();
if( lastPoint != null && mLoggerServiceManager.getLoggingState() == Constants.LOGGING )
{
Point out = new Point();
this.mMapView.getProjection().toPixels( lastPoint, out );
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
if( out.x < 0 || out.y < 0 || out.y > height || out.x > width )
{
this.mMapView.clearAnimation();
this.mMapView.getController().setCenter( lastPoint );
// Log.d( TAG, "mMapView.setCenter()" );
}
else if( out.x < width / 4 || out.y < height / 4 || out.x > ( width / 4 ) * 3 || out.y > ( height / 4 ) * 3 )
{
this.mMapView.clearAnimation();
this.mMapView.getController().animateTo( lastPoint );
// Log.d( TAG, "mMapView.animateTo()" );
}
}
}
/**
* @param avgSpeed avgSpeed in m/s
*/
private void drawSpeedTexts( double avgSpeed )
{
avgSpeed = mUnits.conversionFromMetersPerSecond( avgSpeed );
for (int i = 0; i < mSpeedtexts.length; i++)
{
mSpeedtexts[i].setVisibility( View.VISIBLE );
double speed = ( ( avgSpeed * 2d ) / 5d ) * i;
String speedText = String.format( "%.0f %s", speed, mUnits.getSpeedUnit() );
mSpeedtexts[i].setText( speedText );
}
}
/**
* Alter this to set a new track as current.
*
* @param trackId
* @param center center on the end of the track
*/
private void moveToTrack( long trackId, boolean center )
{
Cursor track = null;
try
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
Uri trackUri = ContentUris.withAppendedId( Tracks.CONTENT_URI, trackId );
Uri mediaUri = ContentUris.withAppendedId( Media.CONTENT_URI, trackId );
track = resolver.query( trackUri, new String[] { Tracks.NAME }, null, null, null );
if( track != null && track.moveToFirst() )
{
this.mTrackId = trackId;
mLastSegment = -1;
mLastWaypoint = -1;
resolver.unregisterContentObserver( this.mTrackSegmentsObserver );
resolver.unregisterContentObserver( this.mTrackMediasObserver );
Uri tracksegmentsUri = Uri.withAppendedPath( Tracks.CONTENT_URI, trackId+"/segments" );
resolver.registerContentObserver( tracksegmentsUri, false, this.mTrackSegmentsObserver );
resolver.registerContentObserver( mediaUri, false, this.mTrackMediasObserver );
this.mMapView.getOverlays().clear();
updateTitleBar();
updateDataOverlays();
updateSpeedbarVisibility();
if( center )
{
GeoPoint lastPoint = getLastTrackPoint();
this.mMapView.getController().animateTo( lastPoint );
}
}
}
finally
{
if( track != null )
{
track.close();
}
}
}
/**
* Get the last know position from the GPS provider and return that information wrapped in a GeoPoint to which the Map can navigate.
*
* @see GeoPoint
* @return
*/
private GeoPoint getLastKnowGeopointLocation()
{
int microLatitude = 0;
int microLongitude = 0;
LocationManager locationManager = (LocationManager) this.getApplication().getSystemService( Context.LOCATION_SERVICE );
Location locationFine = locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER );
if( locationFine != null )
{
microLatitude = (int) ( locationFine.getLatitude() * 1E6d );
microLongitude = (int) ( locationFine.getLongitude() * 1E6d );
}
if( locationFine == null || microLatitude == 0 || microLongitude == 0 )
{
Location locationCoarse = locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
if( locationCoarse != null )
{
microLatitude = (int) ( locationCoarse.getLatitude() * 1E6d );
microLongitude = (int) ( locationCoarse.getLongitude() * 1E6d );
}
if( locationCoarse == null || microLatitude == 0 || microLongitude == 0 )
{
microLatitude = 51985105;
microLongitude = 5106132;
}
}
GeoPoint geoPoint = new GeoPoint( microLatitude, microLongitude );
return geoPoint;
}
/**
* Retrieve the last point of the current track
*
* @param context
*/
private GeoPoint getLastTrackPoint()
{
Cursor waypoint = null;
GeoPoint lastPoint = null;
try
{
ContentResolver resolver = this.getContentResolver();
waypoint = resolver.query( Uri.withAppendedPath( Tracks.CONTENT_URI, mTrackId + "/waypoints" ), new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE,
"max(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null );
if( waypoint != null && waypoint.moveToLast() )
{
int microLatitude = (int) ( waypoint.getDouble( 0 ) * 1E6d );
int microLongitude = (int) ( waypoint.getDouble( 1 ) * 1E6d );
lastPoint = new GeoPoint( microLatitude, microLongitude );
}
if( lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0 )
{
lastPoint = getLastKnowGeopointLocation();
}
else
{
mLastWaypoint = waypoint.getLong( 2 );
}
}
finally
{
if( waypoint != null )
{
waypoint.close();
}
}
return lastPoint;
}
private void moveToLastTrack()
{
int trackId = -1;
Cursor track = null;
try
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
track = resolver.query( Tracks.CONTENT_URI, new String[] { "max(" + Tracks._ID + ")", Tracks.NAME, }, null, null, null );
if( track != null && track.moveToLast() )
{
trackId = track.getInt( 0 );
moveToTrack( trackId, true );
}
}
finally
{
if( track != null )
{
track.close();
}
}
}
/***
* Collecting additional data
*/
private void addPicture()
{
Intent i = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.TMPICTUREFILE_PATH );
// Log.d( TAG, "Picture requested at: " + file );
i.putExtra( android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile( file ) );
i.putExtra( android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1 );
startActivityForResult( i, MENU_PICTURE );
}
/***
* Collecting additional data
*/
private void addVideo()
{
Intent i = new Intent( android.provider.MediaStore.ACTION_VIDEO_CAPTURE );
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.TMPICTUREFILE_PATH );
// Log.d( TAG, "Video requested at: " + file );
i.putExtra( android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile( file ) );
i.putExtra( android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1 );
startActivityForResult( i, MENU_VIDEO );
}
private void addVoice()
{
Intent intent = new Intent( android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION );
startActivityForResult( intent, MENU_VOICE );
}
public void showDialog( BaseAdapter mediaAdapter )
{
mMediaAdapter = mediaAdapter;
showDialog( LoggerMap.DIALOG_URIS );
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/example/taskshare/AudioTask.java b/src/com/example/taskshare/AudioTask.java
index 0332ea5..69feee1 100644
--- a/src/com/example/taskshare/AudioTask.java
+++ b/src/com/example/taskshare/AudioTask.java
@@ -1,9 +1,9 @@
package com.example.taskshare;
public class AudioTask extends Task<Audio>{
AudioTask(String name, String description, Integer authorID, Boolean sharedOnline) {
- super(name, description, sharedOnline);
+ super(name, description, authorID,sharedOnline);
// TODO Auto-generated constructor stub
}
}
diff --git a/src/com/example/taskshare/PhotoTask.java b/src/com/example/taskshare/PhotoTask.java
index 9e9d5c6..b512e15 100644
--- a/src/com/example/taskshare/PhotoTask.java
+++ b/src/com/example/taskshare/PhotoTask.java
@@ -1,12 +1,12 @@
package com.example.taskshare;
import android.text.format.Time;
public class PhotoTask extends Task<Photo>{
PhotoTask(String name, String description, Integer authorID, Boolean sharedOnline) {
- super(name, description, sharedOnline);
+ super(name, description, authorID,sharedOnline);
// TODO Auto-generated constructor stub
}
}
diff --git a/src/com/example/taskshare/TextTask.java b/src/com/example/taskshare/TextTask.java
index 7ada019..21af3c6 100644
--- a/src/com/example/taskshare/TextTask.java
+++ b/src/com/example/taskshare/TextTask.java
@@ -1,14 +1,14 @@
/**This is The text based Task class */
package com.example.taskshare;
import android.text.format.Time;
public class TextTask extends Task<Text>{
TextTask(String name, String description, Integer authorID, Boolean sharedOnline) {
- super(name, description, sharedOnline);
+ super(name, description,authorID,sharedOnline);
// TODO Auto-generated constructor stub
}
}
diff --git a/src/com/example/taskshare/VideoTask.java b/src/com/example/taskshare/VideoTask.java
index 5dffce7..66f2e3c 100644
--- a/src/com/example/taskshare/VideoTask.java
+++ b/src/com/example/taskshare/VideoTask.java
@@ -1,9 +1,9 @@
package com.example.taskshare;
public class VideoTask extends Task<Video>{
VideoTask(String name, String description, Integer authorID, Boolean sharedOnline) {
- super(name, description, sharedOnline);
+ super(name, description,authorID,sharedOnline);
// TODO Auto-generated constructor stub
}
}
| false | false | null | null |
diff --git a/src/main/java/net/minecraft/launchwrapper/LaunchClassLoader.java b/src/main/java/net/minecraft/launchwrapper/LaunchClassLoader.java
index b6ccfa9..ac20fa2 100644
--- a/src/main/java/net/minecraft/launchwrapper/LaunchClassLoader.java
+++ b/src/main/java/net/minecraft/launchwrapper/LaunchClassLoader.java
@@ -1,368 +1,368 @@
package net.minecraft.launchwrapper;
import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.security.CodeSigner;
import java.security.CodeSource;
import java.util.*;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
public class LaunchClassLoader extends URLClassLoader {
public static final int BUFFER_SIZE = 1 << 12;
private List<URL> sources;
private ClassLoader parent = getClass().getClassLoader();
private List<IClassTransformer> transformers = new ArrayList<IClassTransformer>(2);
private Map<String, Class> cachedClasses = new HashMap<String, Class>(1000);
private Set<String> invalidClasses = new HashSet<String>(1000);
private Set<String> classLoaderExceptions = new HashSet<String>();
private Set<String> transformerExceptions = new HashSet<String>();
private Map<Package, Manifest> packageManifests = new HashMap<Package, Manifest>();
private IClassNameTransformer renameTransformer;
private static final Manifest EMPTY = new Manifest();
private final ThreadLocal<byte[]> loadBuffer = new ThreadLocal<byte[]>();
private static final String[] RESERVED_NAMES = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"};
private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("legacy.debugClassLoading", "false"));
private static final boolean DEBUG_FINER = DEBUG && Boolean.parseBoolean(System.getProperty("legacy.debugClassLoadingFiner", "false"));
private static final boolean DEBUG_SAVE = DEBUG && Boolean.parseBoolean(System.getProperty("legacy.debugClassLoadingSave", "false"));
private static File tempFolder = null;
public LaunchClassLoader(URL[] sources) {
super(sources, null);
this.sources = new ArrayList<URL>(Arrays.asList(sources));
Thread.currentThread().setContextClassLoader(this);
// classloader exclusions
addClassLoaderExclusion("java.");
addClassLoaderExclusion("sun.");
addClassLoaderExclusion("org.lwjgl.");
addClassLoaderExclusion("net.minecraft.launchwrapper.");
// transformer exclusions
addTransformerExclusion("javax.");
addTransformerExclusion("argo.");
addTransformerExclusion("org.objectweb.asm.");
addTransformerExclusion("com.google.common.");
addTransformerExclusion("org.bouncycastle.");
addTransformerExclusion("net.minecraft.launchwrapper.injector.");
if (DEBUG_SAVE) {
int x = 1;
tempFolder = new File(Launch.minecraftHome, "CLASSLOADER_TEMP");
while (tempFolder.exists() && x <= 10) {
tempFolder = new File(Launch.minecraftHome, "CLASSLOADER_TEMP" + x++);
}
if (tempFolder.exists()) {
LogWrapper.info("DEBUG_SAVE enabled, but 10 temp directories already exist, clean them and try again.");
tempFolder = null;
} else {
LogWrapper.info("DEBUG_SAVE Enabled, saving all classes to \"%s\"", tempFolder.getAbsolutePath().replace('\\', '/'));
tempFolder.mkdirs();
}
}
}
public void registerTransformer(String transformerClassName) {
try {
IClassTransformer transformer = (IClassTransformer) loadClass(transformerClassName).newInstance();
transformers.add(transformer);
if (transformer instanceof IClassNameTransformer && renameTransformer == null) {
renameTransformer = (IClassNameTransformer) transformer;
}
} catch (Exception e) {
LogWrapper.log(Level.SEVERE, e, "A critical problem occurred registering the ASM transformer class %s", transformerClassName);
}
}
@Override
public Class<?> findClass(final String name) throws ClassNotFoundException {
if (invalidClasses.contains(name)) {
throw new ClassNotFoundException(name);
}
for (final String exception : classLoaderExceptions) {
if (name.startsWith(exception)) {
return parent.loadClass(name);
}
}
if (cachedClasses.containsKey(name)) {
return cachedClasses.get(name);
}
for (final String exception : transformerExceptions) {
if (name.startsWith(exception)) {
try {
final Class<?> clazz = super.findClass(name);
cachedClasses.put(name, clazz);
return clazz;
} catch (ClassNotFoundException e) {
invalidClasses.add(name);
throw e;
}
}
}
try {
final String transformedName = transformName(name);
final String untransformedName = untransformName(name);
final int lastDot = untransformedName.lastIndexOf('.');
final String packageName = lastDot == -1 ? "" : untransformedName.substring(0, lastDot);
final String fileName = untransformedName.replace('.', '/').concat(".class");
URLConnection urlConnection = findCodeSourceConnectionFor(fileName);
CodeSigner[] signers = null;
if (lastDot > -1 && !untransformedName.startsWith("net.minecraft.")) {
if (urlConnection instanceof JarURLConnection) {
final JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
final JarFile jarFile = jarURLConnection.getJarFile();
if (jarFile != null && jarFile.getManifest() != null) {
final Manifest manifest = jarFile.getManifest();
final JarEntry entry = jarFile.getJarEntry(fileName);
Package pkg = getPackage(packageName);
getClassBytes(untransformedName);
signers = entry.getCodeSigners();
if (pkg == null) {
pkg = definePackage(packageName, manifest, jarURLConnection.getJarFileURL());
packageManifests.put(pkg, manifest);
} else {
if (pkg.isSealed() && !pkg.isSealed(jarURLConnection.getJarFileURL())) {
LogWrapper.severe("The jar file %s is trying to seal already secured path %s", jarFile.getName(), packageName);
} else if (isSealed(packageName, manifest)) {
LogWrapper.severe("The jar file %s has a security seal for path %s, but that path is defined and not secure", jarFile.getName(), packageName);
}
}
}
} else {
Package pkg = getPackage(packageName);
if (pkg == null) {
pkg = definePackage(packageName, null, null, null, null, null, null, null);
packageManifests.put(pkg, EMPTY);
} else if (pkg.isSealed()) {
LogWrapper.severe("The URL %s is defining elements for sealed path %s", urlConnection.getURL(), packageName);
}
}
}
final byte[] transformedClass = runTransformers(untransformedName, transformedName, getClassBytes(untransformedName));
if (DEBUG_SAVE) {
saveTransformedClass(transformedClass, transformedName);
}
final CodeSource codeSource = urlConnection == null ? null : new CodeSource(urlConnection.getURL(), signers);
final Class<?> clazz = defineClass(transformedName, transformedClass, 0, transformedClass.length, codeSource);
cachedClasses.put(transformedName, clazz);
return clazz;
} catch (Throwable e) {
invalidClasses.add(name);
if (DEBUG) {
LogWrapper.log(Level.FINEST, e, "Exception encountered attempting classloading of %s", name);
}
throw new ClassNotFoundException(name, e);
}
}
private void saveTransformedClass(final byte[] data, final String transformedName) {
if (tempFolder == null) {
return;
}
final File outFile = new File(tempFolder, transformedName.replace('.', File.separatorChar) + ".class");
final File outDir = outFile.getParentFile();
if (!outDir.exists()) {
outDir.mkdirs();
}
if (outFile.exists()) {
outFile.delete();
}
try {
LogWrapper.fine("Saving transformed class \"%s\" to \"%s\"", transformedName, outFile.getAbsolutePath().replace('\\', '/'));
final OutputStream output = new FileOutputStream(outFile);
output.write(data);
output.close();
} catch (IOException ex) {
LogWrapper.log(Level.WARNING, ex, "Could not save transformed class \"%s\"", transformedName);
}
}
private String untransformName(final String name) {
if (renameTransformer != null) {
return renameTransformer.unmapClassName(name);
}
return name;
}
private String transformName(final String name) {
if (renameTransformer != null) {
return renameTransformer.remapClassName(name);
}
return name;
}
private boolean isSealed(final String path, final Manifest manifest) {
Attributes attributes = manifest.getAttributes(path);
String sealed = null;
if (attributes != null) {
sealed = attributes.getValue(Name.SEALED);
}
if (sealed == null) {
attributes = manifest.getMainAttributes();
if (attributes != null) {
sealed = attributes.getValue(Name.SEALED);
}
}
return "true".equalsIgnoreCase(sealed);
}
private URLConnection findCodeSourceConnectionFor(final String name) {
final URL resource = findResource(name);
if (resource != null) {
try {
return resource.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
private byte[] runTransformers(final String name, final String transformedName, byte[] basicClass) {
if (DEBUG_FINER) {
LogWrapper.finest("Beginning transform of %s (%s) Start Length: %d", name, transformedName, (basicClass == null ? 0 : basicClass.length));
for (final IClassTransformer transformer : transformers) {
final String transName = transformer.getClass().getName();
LogWrapper.finest("Before Transformer %s: %d", transName, (basicClass == null ? 0 : basicClass.length));
basicClass = transformer.transform(name, transformedName, basicClass);
LogWrapper.finest("After Transformer %s: %d", transName, (basicClass == null ? 0 : basicClass.length));
}
LogWrapper.finest("Ending transform of %s (%s) Start Length: %d", name, transformedName, (basicClass == null ? 0 : basicClass.length));
} else {
for (final IClassTransformer transformer : transformers) {
basicClass = transformer.transform(name, transformedName, basicClass);
}
}
return basicClass;
}
@Override
public void addURL(final URL url) {
super.addURL(url);
sources.add(url);
}
public List<URL> getSources() {
return sources;
}
- private byte[] readFully(final InputStream stream) {
+ private byte[] readFully(InputStream stream) {
try {
- int totalLength = 0;
-
byte[] buffer = getOrCreateBuffer();
+
int read;
- while ((read = stream.read(buffer, totalLength, totalLength - buffer.length)) != -1) {
+ int totalLength = 0;
+ while ((read = stream.read(buffer, totalLength, buffer.length - totalLength)) != -1) {
totalLength += read;
// Extend our buffer
if (totalLength >= buffer.length - 1) {
byte[] newBuffer = new byte[buffer.length + BUFFER_SIZE];
System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
buffer = newBuffer;
}
}
final byte[] result = new byte[totalLength];
System.arraycopy(buffer, 0, result, 0, totalLength);
return result;
} catch (Throwable t) {
LogWrapper.log(Level.WARNING, t, "Problem loading class");
return new byte[0];
}
}
private byte[] getOrCreateBuffer() {
byte[] buffer = loadBuffer.get();
if (buffer == null) {
loadBuffer.set(new byte[BUFFER_SIZE]);
buffer = loadBuffer.get();
}
return buffer;
}
public List<IClassTransformer> getTransformers() {
return Collections.unmodifiableList(transformers);
}
private void addClassLoaderExclusion(String toExclude) {
classLoaderExceptions.add(toExclude);
}
public void addTransformerExclusion(String toExclude) {
transformerExceptions.add(toExclude);
}
public byte[] getClassBytes(String name) throws IOException {
if (name.indexOf('.') == -1) {
for (final String reservedName : RESERVED_NAMES) {
if (name.toUpperCase(Locale.ENGLISH).startsWith(reservedName)) {
final byte[] data = getClassBytes("_" + name);
if (data != null) {
return data;
}
}
}
}
InputStream classStream = null;
try {
final String resourcePath = name.replace('.', '/').concat(".class");
final URL classResource = findResource(resourcePath);
if (classResource == null) {
if (DEBUG) LogWrapper.finest("Failed to find class resource %s", resourcePath);
return null;
}
classStream = classResource.openStream();
if (DEBUG) LogWrapper.finest("Loading class %s from resource %s", name, classResource.toString());
return readFully(classStream);
} finally {
closeSilently(classStream);
}
}
private static void closeSilently(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignored) {
}
}
}
}
| false | false | null | null |
diff --git a/src/Controleur.java b/src/Controleur.java
index 7588489..9add603 100644
--- a/src/Controleur.java
+++ b/src/Controleur.java
@@ -1,1717 +1,1718 @@
import java.util.ArrayList;
import java.util.Date;
import java.io.*;
import java.text.SimpleDateFormat;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFileChooser;
import javax.swing.filechooser.*;
import javax.imageio.ImageIO;
public class Controleur{
private static final int SUCCESS = 0;
private static final int COMMANDE_ERRONEE = 100;
private static final int NOMBRE_PARAM_LESS = 200;
private static final int NOMBRE_PARAM_SUP = 201;
private static final int PARAM_INCORRECTE = 202;
/*
* TODO
* mettre en constante les autres erreurs
*/
private Terminal term = null;
private ZoneDessin zd = null;
private BarreOutils zb = null;
private Curseur curseur = null;
private BarreMenu barreMenu;
/**
* Constructeur vide
*/
public Controleur(){}
/**
* Fonction qui permet d'initialiser les liens entre objets
* @param f Fenetre principale
* @param c Curseur
*/
public void ___hydrate___(Fenetre f, Curseur c)
{
term = f.getTerminal();
term.setControleur(this);
zd = f.getZoneDessin();
zd.setControleur(this);
zb = f.getZoneBouton();
zb.setControleur(this);
barreMenu = f.getBarreMenu();
barreMenu.setControleur(this);
curseur = c;
c.setControleur(this);
}
/**
* Fonction qui permet de contrôler le commande entrée par l'utilisateur
* @param s Commande entrée par l'utilisateur
* @return Si la fonction s'est correctement déroulée
*/
public boolean commande(String s, boolean write)
{
String[] commande_parser;
s = rework_command(s);
commande_parser = parse(s);
if ( write )
{
if ( (commande_parser[0].equalsIgnoreCase("setcolor") || commande_parser[0].equalsIgnoreCase("cursorwidth"))
&& StockageDonnee.lastCommande().equalsIgnoreCase(commande_parser[0]) )
{
term.remplace(s, term.getLastIndexOf(commande_parser[0]));
}
else
{
term.addMessage(" > " + s);
}
StockageDonnee.ajoutLCEG(s);
}
int numero_renvoie = init(commande_parser,write);
if ( numero_renvoie != 0 )
{
this.setMessageErreur(numero_renvoie);
}
term.replaceCompteur();
return true;
}
/**
* Fonction qui parse la chaîne de commande
* @param s Commande entrée par l'utilisateur
* @return Tableau comportant la commande et ses arguments ( si besoins )
*/
public String[] parse(String s)
{
return s.split(" ");
}
/**
* Fonction qui renvoie la commande tapée par l'utilisateur en enlevant tout espace superflu
* @param s Commande entrée par l'utilisateur
* @return Commande retravaillée
*/
public String rework_command(String s)
{
String regex = "\\s{2,}";
s = s.trim();
s = s.replaceAll(regex, " ");
return s;
}
/**
* Fonction qui envoie le message d'erreur au terminal
* @param numero_erreur numero de l'erreur
* @return boolean
*/
public boolean setMessageErreur(int numero_erreur)
{
String message = " /!\\ Erreur : ";
String param = StockageDonnee.getParamErreur();
if ( !param.equals("") )
message += param + " : ";
message += StockageDonnee.getMessageErreur(numero_erreur);
term.addMessage(message);
return false;
}
/**
* Fonction qui traite le string
* @param commande_parser Tableau contenant le nom de la commande ainsi que ses arguments
* @return 0 si la fonction s'est bien déroulée.
*/
public int init(String[] commande_parser, boolean write)
{
int retour = 0;
int valeur, r, g, b;
int valeur_x, valeur_y, width, height;
switch ( StockageDonnee.getNumeroFonction( commande_parser[0].toLowerCase() ) )
{
case 0:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = pendown();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 1:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = penup();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
case 2:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = pencil();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 3:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = eraser();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 4:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = up();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 5:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = down();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 6:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = left();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 7:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
retour = right();
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 8:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
else if ( commande_parser.length < 2 )
return NOMBRE_PARAM_LESS;
else;
if ( isDouble(commande_parser[1]) )
valeur = (int)Double.parseDouble(commande_parser[1]);
else
return PARAM_INCORRECTE;
retour = rotate(valeur);
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 9:
if ( commande_parser.length < 2 )
return NOMBRE_PARAM_LESS;
else if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
else;
if ( isInt(commande_parser[1]) )
valeur = Integer.parseInt(commande_parser[1]);
else
return PARAM_INCORRECTE;
retour = forward(valeur);
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, false);
return retour;
case 10:
if ( commande_parser.length < 2 )
return NOMBRE_PARAM_LESS;
else if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
else;
if ( isInt(commande_parser[1]) )
valeur = Integer.parseInt(commande_parser[1]);
else
return PARAM_INCORRECTE;
retour = backward(valeur);
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, false);
return retour;
case 11:
if ( commande_parser.length > 3 )
{
return NOMBRE_PARAM_SUP;
}
else if ( commande_parser.length < 3 )
{
return NOMBRE_PARAM_LESS;
}
else;
if ( isInt(commande_parser[1])
&& isInt(commande_parser[2]) )
{
valeur_x = Integer.parseInt(commande_parser[1]);
valeur_y = Integer.parseInt(commande_parser[2]);
}
else
return PARAM_INCORRECTE;
retour = goTo(valeur_x, valeur_y);
boolean verif = false;
if ( !curseur.isDown() )
verif = true;
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, verif);
return retour;
case 12:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
else if ( commande_parser.length < 2 )
return NOMBRE_PARAM_LESS;
else;
if ( isInt(commande_parser[1]) )
valeur = Integer.parseInt(commande_parser[1]);
else
return PARAM_INCORRECTE;
retour = cursorWidth(valeur);
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
case 13:
if ( commande_parser.length > 4 )
return NOMBRE_PARAM_SUP;
else if ( (commande_parser.length < 2) || (commande_parser.length == 3) )
return NOMBRE_PARAM_LESS;
else;
if ( commande_parser.length == 2 )
{
retour = setColor(commande_parser[1]);
}
else if ( commande_parser.length == 4 )
{
if ( isInt(commande_parser[1]) )
{
r = Integer.parseInt(commande_parser[1]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[1]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[2]) )
{
g = Integer.parseInt(commande_parser[2]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[2]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[3]) )
{
b = Integer.parseInt(commande_parser[3]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[3]);
return PARAM_INCORRECTE;
}
retour = setColor(r,g,b);
}
else;
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 14:
if ( commande_parser.length > 4 )
return NOMBRE_PARAM_SUP;
else if ( (commande_parser.length < 2) || (commande_parser.length == 3) )
return NOMBRE_PARAM_LESS;
else;
if ( commande_parser.length == 2 )
{
retour = setBackgroundColor(commande_parser[1]);
}
else if ( commande_parser.length == 4 )
{
if ( isInt(commande_parser[1]) )
{
r = Integer.parseInt(commande_parser[1]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[1]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[2]) )
{
g = Integer.parseInt(commande_parser[2]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[2]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[3]) )
{
b = Integer.parseInt(commande_parser[3]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[3]);
return PARAM_INCORRECTE;
}
retour = setBackgroundColor(r,g,b);
}
else;
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, true);
return retour;
case 15:
if ( commande_parser.length > 8 )
{
return NOMBRE_PARAM_SUP;
}
if ( commande_parser[1].equalsIgnoreCase("triangle") )
{
/* do triangle x1 y1 x2 y2 x3 y3 */
valeur_x = 0;
valeur_y = 0;
width = 0;
height = 0;
System.out.println("triangle");
}
else if ( commande_parser[1].equalsIgnoreCase("carre") )
{
if ( isInt(commande_parser[2]) )
{
valeur_x = Integer.parseInt(commande_parser[2]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[2]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[3]) )
{
valeur_y = Integer.parseInt(commande_parser[3]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[3]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[4]) )
{
width = Integer.parseInt(commande_parser[4]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[4]);
return PARAM_INCORRECTE;
}
height = width;
}
else if ( commande_parser[1].equalsIgnoreCase("rectangle") )
{
if ( isInt(commande_parser[2]) )
{
valeur_x = Integer.parseInt(commande_parser[2]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[2]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[3]) )
{
valeur_y = Integer.parseInt(commande_parser[3]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[3]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[4]) )
{
width = Integer.parseInt(commande_parser[4]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[4]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[5]) )
{
height = Integer.parseInt(commande_parser[5]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[5]);
return PARAM_INCORRECTE;
}
}
else if ( commande_parser[1].equalsIgnoreCase("cercle") )
{
if ( isInt(commande_parser[2]) )
{
valeur_x = Integer.parseInt(commande_parser[2]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[2]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[3]) )
{
valeur_y = Integer.parseInt(commande_parser[3]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[3]);
return PARAM_INCORRECTE;
}
if ( isInt(commande_parser[4]) )
{
width = Integer.parseInt(commande_parser[4]);
}
else
{
StockageDonnee.setParamErreur(commande_parser[4]);
return PARAM_INCORRECTE;
}
height = width;
}
else
{
return COMMANDE_ERRONEE;
}
/* VALEUR A MODIFIER */
return doFigure(2, valeur_x, valeur_y, width, height, true);
case 16:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
else if ( commande_parser.length < 2 )
return NOMBRE_PARAM_LESS;
else;
if ( isInt(commande_parser[1]) )
valeur = Integer.parseInt(commande_parser[1]);
else
return PARAM_INCORRECTE;
return width(valeur);
case 17:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
else if ( commande_parser.length < 2 )
return NOMBRE_PARAM_LESS;
else;
if ( isInt(commande_parser[1]) )
valeur = Integer.parseInt(commande_parser[1]);
else
return PARAM_INCORRECTE;
return height(valeur);
case 18:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
return newFile();
case 19:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
if ( commande_parser.length == 2 )
return open(commande_parser[1]);
return open("");
case 20:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
if ( commande_parser.length == 2 )
return saveas(commande_parser[1]);
return save();
case 21:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
if ( commande_parser.length == 2 )
return saveas(commande_parser[1]);
return saveas("");
case 22:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
if ( commande_parser.length == 2 )
return savehistory(commande_parser[1]);
else
return savehistory("");
case 23:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
if ( commande_parser.length == 2 )
return exec(commande_parser[1]);
return exec("");
case 24:
if ( commande_parser.length > 3 )
return NOMBRE_PARAM_SUP;
int debut = StockageDonnee.getSize_LCEC();
if ( commande_parser.length == 1 )
retour = repeat(1,1,debut);
else if ( commande_parser.length == 2 )
{
if ( isInt(commande_parser[1]) )
retour = repeat(Integer.parseInt(commande_parser[1]),1,debut);
else
return PARAM_INCORRECTE;
}
else
{
if ( isInt(commande_parser[1]) && isInt(commande_parser[1]) )
{
retour = repeat(Integer.parseInt(commande_parser[1]),
Integer.parseInt(commande_parser[2]),debut);
}
else
return PARAM_INCORRECTE;
}
if ( retour == 0 && write )
StockageDonnee.ajoutLCEC(commande_parser, false);
return retour;
case 25:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
return clear();
case 26:
if ( commande_parser.length > 1 )
return NOMBRE_PARAM_SUP;
return help();
case 27:
if ( commande_parser.length > 2 )
return NOMBRE_PARAM_SUP;
if ( commande_parser.length < 2 )
return man(false, "");
else
return man(true, commande_parser[1]);
case 28:
if ( commande_parser.length == 2 )
{
if ( commande_parser[1].equals("lcec") )
function_debug_test( true );
else if ( commande_parser[1].equals("lceg") )
function_debug_test( false );
else
return PARAM_INCORRECTE;
}
else
function_debug_test( false );
break;
default:
return COMMANDE_ERRONEE;
}
return SUCCESS;
}
/**
* Fonction qui permet l'écriture lorsque l'utilisateur se déplace
* @return si la fonction s'est bien déroulée.
*/
public int pendown()
{
this.curseur.setIsDown(true);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet d'arrêter l'écriture lorsque l'utilisateur se déplace
* @return si la fonction s'est bien déroulée.
*/
public int penup()
{
this.curseur.setIsDown(false);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de passer en mode crayon
* @return si la fonction s'est bien déroulée.
*/
public int pencil()
{
this.curseur.setType(0);
return SUCCESS;
}
/**
* Fonction qui permet de passer en mode gomme
* @return si la fonction s'est bien déroulée.
*/
public int eraser()
{
this.curseur.setType(1);
return SUCCESS;
}
/**
* Fonction qui permet de placer le pointeur vers le haut
* @return si la fonction s'est bien déroulée.
*/
public int up()
{
this.curseur.setOrientation(180);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de placer le pointeur vers le bas
* @return si la fonction s'est bien déroulée.
*/
public int down()
{
this.curseur.setOrientation(0);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de placer le pointeur vers la gauche
* @return si la fonction s'est bien déroulée.
*/
public int left()
{
this.curseur.setOrientation(270);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de placer le pointeur vers la droite
* @return si la fonction s'est bien déroulée.
*/
public int right()
{
this.curseur.setOrientation(90);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de faire une rotation sur le pointeur
* @return si la fonction s'est bien déroulée.
*/
public int rotate(int valeur)
{
this.curseur.setOrientation(valeur+90);
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de faire avancer le pointeur
* @param valeur Valeur d'avancée
* @return si la fonction s'est bien déroulée.
*/
public int forward(int valeur)
{
//Calcul de la nouvelle position du curseur
int posX1=curseur.getPosX();
int posY1=curseur.getPosY();
double posX = curseur.getPosX() + valeur * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY = curseur.getPosY() + valeur * Math.cos(curseur.getOrientation() * Math.PI / 180);
//conditions pour que le curseur ne dépasse pas la zone de dessin
if(posX <= zd.getLargeurDessin() && posX >= 0) curseur.setPosX((int)posX); //ok
if(posY <= zd.getHauteurDessin() && posY >= 0) curseur.setPosY((int)posY); //ok
if(posX <0) curseur.setPosX(0); //valeur négative : on replace à 0
if(posY <0) curseur.setPosY(0); //valeur négative : on replace à 0
if(posX > zd.getLargeurDessin()) curseur.setPosX(zd.getLargeurDessin()); //trop grand : on met à la position max
if(posY > zd.getHauteurDessin()) curseur.setPosY(zd.getHauteurDessin()); //trop grand : on met à la position max
if(curseur.isDown() && curseur.getType() == 0){
Traceur t = new Traceur(1, curseur.getEpaisseur(), curseur.getCouleur(), posX1, posY1, curseur.getPosX(), curseur.getPosY(), curseur.getForme());
StockageDonnee.liste_dessin.add(t);
}
if(curseur.isDown() && curseur.getType() == 1){
Traceur t = new Traceur(1, curseur.getEpaisseur(), zd.getBackground(), posX1, posY1, curseur.getPosX(), curseur.getPosY(), curseur.getForme());
StockageDonnee.liste_dessin.add(t);
}
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de faire reculer le pointeur
* @param valeur Valeur de recul
* @return si la fonction s'est bien déroulée.
*/
public int backward(int valeur)
{
//Calcul de la nouvelle position du curseur
int posX1=curseur.getPosX();
int posY1=curseur.getPosY();
double posX = curseur.getPosX() - valeur * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY = curseur.getPosY() - valeur * Math.cos(curseur.getOrientation() * Math.PI / 180);
//conditions pour que le curseur ne dépasse pas la zone de dessin
if(posX <= zd.getLargeurDessin() && posX >= 0) curseur.setPosX((int)posX); //ok
if(posY <= zd.getHauteurDessin() && posY >= 0) curseur.setPosY((int)posY); //ok
if(posX <0) curseur.setPosX(0); //valeur négative : on replace à 0
if(posY <0) curseur.setPosY(0); //valeur négative : on replace à 0
if(posX > zd.getLargeurDessin()) curseur.setPosX(zd.getLargeurDessin()); //trop grand : on met à la position max
if(posY > zd.getHauteurDessin()) curseur.setPosY(zd.getHauteurDessin()); //trop grand : on met à la position max
if(curseur.isDown() && curseur.getType() == 0){
Traceur t = new Traceur(1, curseur.getEpaisseur(), curseur.getCouleur(), posX1, posY1, curseur.getPosX(), curseur.getPosY(), curseur.getForme());
StockageDonnee.liste_dessin.add(t);
}
if(curseur.isDown() && curseur.getType() == 1){
Traceur t = new Traceur(1, curseur.getEpaisseur(), zd.getBackground(), posX1, posY1, curseur.getPosX(), curseur.getPosY(), curseur.getForme());
StockageDonnee.liste_dessin.add(t);
}
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de déplacer le pointeur
* @return si la fonction s'est bien déroulée.
*/
public int goTo(int value, int value_2)
{
int posX1=curseur.getPosX();
int posY1=curseur.getPosY();
//conditions pour que le curseur ne dépasse pas la zone de dessin
if( value >= 0 && value <= zd.getLargeurDessin()) curseur.setPosX(value); //ok
if(value_2 >= 0 && value_2 <= zd.getHauteurDessin()) curseur.setPosY(value_2); //ok
if(value > zd.getLargeurDessin()) curseur.setPosX(zd.getLargeurDessin()); //valeur X > largeur de la zone
if(value_2 > zd.getHauteurDessin()) curseur.setPosY(zd.getHauteurDessin()); //valeur Y > hauteur de la zone
if(value < 0) curseur.setPosX(0); //valeur négative => on replace à la valeur minimu : 0
if(value_2 < 0) curseur.setPosY(0); //valeur négative => on replace à la valeur minimu : 0
if(curseur.isDown() && curseur.getType() == 0){
Traceur t = new Traceur(1, curseur.getEpaisseur(), curseur.getCouleur(), posX1, posY1, curseur.getPosX(), curseur.getPosY(), curseur.getForme());
StockageDonnee.liste_dessin.add(t);
}
if(curseur.isDown() && curseur.getType() == 1){
Traceur t = new Traceur(1, curseur.getEpaisseur(), zd.getBackground(), posX1, posY1, curseur.getPosX(), curseur.getPosY(), curseur.getForme());
StockageDonnee.liste_dessin.add(t);
}
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de régler la largeur du curseur
* @return si la fonction s'est bien déroulée.
*/
public int cursorWidth(int valeur)
{
curseur.setTaille(valeur);
return SUCCESS;
}
/**
* Fonction qui permet de changer la couleur
* @return si la fonction s'est bien déroulée.
*/
public int setColor(String couleur)
{
if(StockageDonnee.liste_couleur.containsKey(couleur)){
Color c = StockageDonnee.liste_couleur.get(couleur);
curseur.setCouleur(c);
}
return SUCCESS;
}
/**
* Fonction qui permet de changer la couleur (int RGB)
* @return si la fonction s'est bien déroulée.
*/
public int setColor(int red, int green, int blue)
{
if(red >= 0 && red <= 255 && green >= 0 && green <= 255 && blue >= 0 && blue <= 255){
curseur.setCouleur(new Color(red,green,blue));
}
return SUCCESS;
}
/**
* Fonction qui permet de changer la couleur du fond d'écran
* @return si la fonction s'est bien déroulée.
*/
public int setBackgroundColor(String bgColor)
{
if(StockageDonnee.liste_couleur.containsKey(bgColor)){
Color c = StockageDonnee.liste_couleur.get(bgColor);
zd.setBackground(c);
}
return SUCCESS;
}
/**
* Fonction qui permet de changer la couleur du fond d'écran (int RGB)
* @return si la fonction s'est bien déroulée.
*/
public int setBackgroundColor(int red, int green, int blue)
{
zd.setBackground(new Color(red,green,blue));
return SUCCESS;
}
/**
* Fonction qui permet de tracer des figures particulières
* @return si la fonction s'est bien déroulée.
*/
public int doFigure(int type, int x, int y, int width, int height, boolean estRempli)
{
System.out.println("x : " + x + "\ny : " + y + "\nwidth : " + width
+ "\nheight : " + height);
if(type==2){
Traceur t = new Traceur(2, curseur.getCouleur(), height, width, x, y, estRempli);
StockageDonnee.liste_dessin.add(t);
}
return SUCCESS;
}
/**
* Fonction qui permet de changer la largeur de l'écran
* @return si la fonction s'est bien déroulée.
*/
public int width(int valeur)
{
zd.setLargeur(valeur);
zd.setSize(zd.getLargeurDessin(), zd.getHauteurDessin());
if(curseur.getPosX()>zd.getLargeurDessin()){
curseur.setPosX(zd.getLargeurDessin());
}
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de changer la hauteur de l'écran
* @return si la fonction s'est bien déroulée.
*/
public int height(int valeur)
{
zd.setHauteur(valeur);
zd.setSize(zd.getLargeurDessin(), zd.getHauteurDessin());
if(curseur.getPosY()>zd.getHauteurDessin()){
curseur.setPosY(zd.getHauteurDessin());
}
this.zd.repaint();
return SUCCESS;
}
/**
* Fonction qui permet de créer un nouveau document
* @return si la fonction s'est bien déroulée.
*/
public int newFile()
{
boolean save_return = StockageDonnee.getImageSave();
if ( !StockageDonnee.getImageSave() )
{
JOptionPane save_option = new JOptionPane();
int answer = save_option.showConfirmDialog(null,
"Sauvegarder avant de quitter ?",
"Nouveau fichier",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if ( answer == JOptionPane.YES_OPTION )
{
if ( save() == SUCCESS )
{
save_return = true;
}
}
else if ( answer == JOptionPane.CANCEL_OPTION
|| answer == JOptionPane.CLOSED_OPTION )
{
return SUCCESS;
}
else
{
save_return = true;
}
}
if ( save_return )
{
StockageDonnee.videTout();
zd.repaint();
}
else
{
return newFile();
}
return SUCCESS;
}
/**
* Fonction qui permet d'ouvrir une image
* @return si la fonction s'est bien déroulée.
*/
public int open(String path)
{
/*verifier que le fichiet existe*/
String[] path_tab=path.split(".");
if(path_tab[1]=="png"){
ImageIcon img=new ImageIcon(path);
int imageHeight=img.getIconHeight();
int imageWidth=img.getIconWidth();
if(imageHeight>zd.getHauteurDessin()){
zd.setHauteur(imageHeight);
}
if(imageWidth>zd.getLargeurDessin()){
zd.setLargeur(imageWidth);
}
Traceur t = new Traceur(5,path);
}
else{
//message erreur
}
return SUCCESS;
}
/**
* Fonction qui permet de sauvegarder un document en une image
* @return si la fonction s'est bien déroulée.
*/
public int save()
{
String path_to_drawing = StockageDonnee.getPathname();
if ( !path_to_drawing.equals("") )
{
File dessin = new File(path_to_drawing);
BufferedImage tmpSave = new BufferedImage( 1000,
1000,
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = (Graphics2D)tmpSave.getGraphics();
zd.paint(g);
BufferedImage final_image = tmpSave.getSubimage( zd.getEcartHorizontal(), zd.getEcartVertical(),
zd.getLargeurDessin(), zd.getHauteurDessin() );
try
{
ImageIO.write(final_image, "PNG", dessin);
StockageDonnee.changeImageSave();
}
catch (Exception e)
{
System.out.println("zhjrkjzehrjze");
}
}
else
{
return saveas("");
}
return SUCCESS;
}
/**
* Fonction qui sauvegarde dans un dossier donner par l'utilisateur
* @return si la fonction s'est bien déroulée
*/
public int saveas(String pathname)
{
String path_to_drawing = pathname;
if ( pathname.equals("") )
{
String debut_regex = "(.*)[\\.]";
JFileChooser chooser = getChooser("Fichier image (png, gif, jpg)", new String[] { debut_regex + "[pP][nN][gG]$",
debut_regex + "[jJ][pP][gG]", debut_regex + "[gG][iI][fF]" } );
int returnVal = chooser.showSaveDialog(zd);
if ( returnVal == JFileChooser.APPROVE_OPTION )
{
path_to_drawing = chooser.getSelectedFile().getAbsolutePath();
- if ( !path_to_drawing.endsWith(".png") )
+ String regex = "(.*)[\\.]([pP][nN][gG]||[jJ][pP][gG]||[gG][iI][fF])";
+ if ( !path_to_drawing.matches(regex) )
{
path_to_drawing += ".png";
}
}
else
{
return SUCCESS;
}
}
else
{
String regex = "(.*)[\\.]([pP][nN][gG]|[jJ][pP][gG]|[gG][iI][fF])";
if ( path_to_drawing.matches("^\\~"));
{
path_to_drawing = path_to_drawing.replaceAll("^\\~", "/home/" + System.getProperty("user.name"));
}
if ( !path_to_drawing.matches(regex) )
{
path_to_drawing += File.separator + "save" + getCurDate() + ".png";
}
File tmp = new File(path_to_drawing).getParentFile();
try
{
if ( !tmp.exists() )
{
try
{
tmp.mkdirs();
}
catch(Exception e)
{
System.out.println("peut pas creer");
}
}
}
catch(Exception e)
{
System.out.println("peut pas accéder");
}
}
File dessin = new File(path_to_drawing);
if ( !path_to_drawing.equals("") )
{
BufferedImage tmpSave = new BufferedImage( 2000,
2000,
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = (Graphics2D)tmpSave.getGraphics();
zd.paint(g);
BufferedImage final_image = tmpSave.getSubimage( zd.getEcartHorizontal(), zd.getEcartVertical(),
zd.getLargeurDessin(), zd.getHauteurDessin() );
try
{
ImageIO.write(final_image, path_to_drawing.substring(path_to_drawing.lastIndexOf(".")+1).toUpperCase(), dessin);
StockageDonnee.setPathname(path_to_drawing);
}
catch (Exception e)
{
System.out.println("zhjrkjzehrjze");
}
}
StockageDonnee.changeImageSave();
return SUCCESS;
}
/**
* Fonction qui sauvegarde l'historique dans un format .txt
* @return si la fonction s'est bien déroulée
*/
public int savehistory(String pathname)
{
File current = new File(System.getProperty("user.dir"));
File history;
if ( pathname.equals("") )
{
try
{
File folder = new File(current.getParent() + File.separator + "history");
if ( !folder.exists() )
{
if ( !folder.mkdir() )
term.addMessage(" /!\\ LE DOSSIER N'A PAS PU ETRE CREE");
}
history = new File(current.getParent()
+ File.separator + "history"
+ File.separator + "history" + getCurDate() + ".txt");
}
catch (Exception e)
{
return COMMANDE_ERRONEE;
}
}
else
{
String regex = "(.*)[\\.][tT][xX][tT]$";
if ( pathname.startsWith("~") )
{
pathname = pathname.replaceAll("^\\~", "/home/" + System.getProperty("user.name"));
}
if ( pathname.matches(regex) )
{
history = new File(pathname);
}
else
{
pathname += File.separator + "history" + getCurDate() + ".txt";
history = new File(pathname);
}
File tmp = new File(new File(pathname).getParent());
try
{
if ( !tmp.exists() )
{
try
{
tmp.mkdirs();
}
catch(Exception e)
{
System.out.println("peut pas creer");
}
}
}
catch(Exception e)
{
System.out.println("peut pas accéder");
}
}
try
{
history.createNewFile();
FileWriter fw = new FileWriter(history);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter fSortie = new PrintWriter(bw);
fSortie.println("##################################################");
fSortie.flush();
fSortie.println("##################################################");
fSortie.flush();
fSortie.println("##\t\tHISTORIQUE GENERE LE\t\t##");
fSortie.flush();
fSortie.println("##\t\t" + getCurDate() + "\t\t##");
fSortie.flush();
fSortie.println("##################################################");
fSortie.flush();
fSortie.println("##################################################\n");
fSortie.flush();
fSortie.println("new");
fSortie.println("width " + zd.getLargeurDessin());
fSortie.println("height " + zd.getHauteurDessin());
for (int i = 0; i < StockageDonnee.getSize_LCEC(); i++)
{
fSortie.println(StockageDonnee.getLCEC(i));
fSortie.flush();
}
fSortie.close();
}
catch (Exception e)
{
return COMMANDE_ERRONEE;
}
return SUCCESS;
}
/**
* Fonction qui lit un fichier et execute les lignes de commandes si celles-ci sont correctes
* @param pathname Chemin du fichier
* @return si la fonction s'est bien déroulée
*/
public int exec(String pathname)
{
if ( pathname.equals("") )
{
String regex = "(.*)[\\.][tT][xX][tT]$";
JFileChooser chooser = getChooser("Fichier texte", new String[] { regex });
int returnVal = chooser.showOpenDialog(null);
if ( returnVal == JFileChooser.APPROVE_OPTION )
{
pathname = chooser.getSelectedFile().getAbsolutePath();
if ( !pathname.matches(regex) )
{
return 1; /* ERREUR A ECRIRE */
}
}
else
{
return SUCCESS;
}
}
File file_to_exec = new File(pathname);
if ( file_to_exec.exists() )
{
try
{
InputStream ips = new FileInputStream(file_to_exec);
InputStreamReader isr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(isr);
String ligne;
int i = 1;
while ( (ligne=br.readLine()) != null )
{
ligne = ligne.trim();
if ( !ligne.startsWith("#") && !ligne.equals("") && !this.commande(ligne, true) )
{
StockageDonnee.videLCEC();
StockageDonnee.videListeDessin();
StockageDonnee.setParamErreur("ligne " + i);
zd.repaint();
return COMMANDE_ERRONEE;
}
i++;
}
}
catch (Exception e)
{
term.addMessage(" /!\\ LE FICHIER ENTRE EN ARGUMENT NE PEUT ETRE LU");
}
return SUCCESS;
}
else
{
return COMMANDE_ERRONEE;
}
}
/**
* Fonction qui répète les dernières commandes lancés par l'utilisateur
* @param nombre_de_commandes Nombres de commandes
* @param nombre_de_repetition Nombres de répétitions
* @param debut Permet de déterminer où se trouve le début des fonctions à répéter
* @return si la fonction s'est bien déroulée.
*/
public int repeat(int nombre_de_commandes, int nombre_de_repetition, int debut)
{
String[] commands = new String[nombre_de_commandes];
if ( debut <= 0 )
{
return COMMANDE_ERRONEE;
}
if ( nombre_de_commandes > StockageDonnee.getSize_LCEC() )
{
nombre_de_commandes = StockageDonnee.getSize_LCEC();
}
int i = 0;
int position_liste = debut-nombre_de_commandes;
int in = position_liste;
while ( i < nombre_de_commandes )
{
commands[i] = StockageDonnee.getLCEC(position_liste);
position_liste++;
i++;
}
int j = 1;
while ( j <= nombre_de_repetition )
{
i=0;
while ( i < commands.length )
{
if ( commands[i].startsWith("repeat") )
{
String[] s = commands[i].split(" ");
int parse1 = 1;
int parse2 = 1;
if ( s.length == 2 )
{
parse1 = Integer.parseInt(s[1]);
}
else if ( s.length == 3 )
{
parse1 = Integer.parseInt(s[1]);
parse2 = Integer.parseInt(s[2]);
}
else;
repeat(parse1, parse2, in-i, position_liste-i);
}
else
{
commande(commands[i], false);
}
i++;
}
j++;
}
return SUCCESS;
}
/**
* Fonction qui aide à la répétition
* @param nombre_de_commandes Nombres de commandes
* @param nombre_de_repetition Nombres de répétitions
* @param debut Permet de déterminer où se trouves les premières fonctions à répéter
* @param pos Position de la fonction repeat dans le tableau
* @return l'entier correspondant à l'erreur
*/
public int repeat(int nombre_de_commandes, int nombre_de_repetition, int debut, int pos)
{
String[] commands = new String[nombre_de_commandes];
if ( debut <= 0 )
{
debut = 0;
}
if ( nombre_de_commandes > StockageDonnee.getSize_LCEC() )
{
nombre_de_commandes = StockageDonnee.getSize_LCEC();
}
int i = 0;
int position_liste = pos-nombre_de_commandes;
int in = position_liste;
while ( i < nombre_de_commandes )
{
commands[i] = StockageDonnee.getLCEC(position_liste);
position_liste++;
i++;
}
int j = 1;
while ( j <= nombre_de_repetition )
{
i=1;
while ( i <= commands.length )
{
if ( commands[i-1].startsWith("repeat") )
{
String[] s = commands[i-1].split(" ");
int parse1 = 1;
int parse2 = 1;
if ( s.length == 2 )
{
parse1 = Integer.parseInt(s[1]);
}
else if ( s.length == 3 )
{
parse1 = Integer.parseInt(s[1]);
parse2 = Integer.parseInt(s[2]);
}
else;
repeat(parse1, parse2, in-i, position_liste-i);
}
else
{
commande(commands[i-1], false);
}
i++;
}
j++;
}
return SUCCESS;
}
/**
* Fonction qui efface l'écran de dessin
* @return si la fonction s'est bien déroulée.
*/
public int clear()
{
term.clear();
return SUCCESS;
}
/**
* Fonction qui affiche une fenêtre avec la liste des commandes
* @return si la fonction s'est bien déroulée.
*/
public int help()
{
return SUCCESS;
}
/**
* Fonction qui affiche le manuel de la commande
* @return si la fonction s'est bien déroulée.
*/
public int man(boolean isNotEmpty, String commande)
{
if ( isNotEmpty )
{
if ( StockageDonnee.manuel.containsKey(commande) )
System.out.println(StockageDonnee.getManuel(commande));
else
System.out.println("La commande n'existe pas");
}
else
System.out.println("Quel page voulez vous ? (Syntaxe : man <commande>)");
return SUCCESS;
}
private void function_debug_test(boolean b)
{
if ( !b )
{
for (int i = 0; i < StockageDonnee.getSize_LCEG(); i++)
{
System.out.println(StockageDonnee.getLCEG(i));
}
}
else
{
for (int i = 0; i < StockageDonnee.getSize_LCEC(); i++)
{
System.out.println(StockageDonnee.getLCEC(i));
}
}
}
/*cette fonction teste si une chaine de caractere est un int ou pas*/
public boolean isInt(String s){
try{
Integer.parseInt(s);
}
catch(NumberFormatException e){
StockageDonnee.setParamErreur(s);
return false;
}
return true;
}
public boolean isDouble(String s)
{
try
{
Double.parseDouble(s);
}
catch(NumberFormatException e)
{
StockageDonnee.setParamErreur(s);
return false;
}
return true;
}
public String getCurDate()
{
String format = "yy-MM-yy_H-mm-ss";
SimpleDateFormat formater = new SimpleDateFormat(format);
Date date = new java.util.Date();
return formater.format(date);
}
public JFileChooser getChooser(String description, String[] regex)
{
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory( new File( System.getProperty("user.dir") ).getParentFile() );
ExtensionFileFilter filter = new ExtensionFileFilter(description, regex);
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
return chooser;
}
}
| true | false | null | null |
diff --git a/main/src/main/java/com/bloatit/web/html/components/custom/HtmlPagedList.java b/main/src/main/java/com/bloatit/web/html/components/custom/HtmlPagedList.java
index 3811ee4a2..8ad37f18c 100644
--- a/main/src/main/java/com/bloatit/web/html/components/custom/HtmlPagedList.java
+++ b/main/src/main/java/com/bloatit/web/html/components/custom/HtmlPagedList.java
@@ -1,129 +1,129 @@
/*
* Copyright (C) 2010 BloatIt.
*
* This file is part of BloatIt.
*
* BloatIt is free software: you can redistribute it and/or modify it under the terms of
* the GNU Affero General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BloatIt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with
* BloatIt. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bloatit.web.html.components.custom;
import com.bloatit.common.PageIterable;
import com.bloatit.web.annotations.ParamContainer;
import com.bloatit.web.annotations.RequestParam;
import com.bloatit.web.html.HtmlElement;
import com.bloatit.web.html.HtmlNode;
import com.bloatit.web.html.HtmlText;
import com.bloatit.web.html.components.standard.HtmlGenericElement;
import com.bloatit.web.html.components.standard.HtmlList;
import com.bloatit.web.html.components.standard.HtmlRenderer;
import com.bloatit.web.server.Context;
import com.bloatit.web.server.Session;
import com.bloatit.web.utils.url.HtmlPagedListUrl;
import com.bloatit.web.utils.url.UrlComponent;
@ParamContainer(value = "pagedList", isComponent = true)
public class HtmlPagedList<T> extends HtmlList {
private final static String CURRENT_PAGE_FIELD_NAME = "current_page";
private final static String PAGE_SIZE_FIELD_NAME = "page_size";
private final Session session;
private final Integer pageCount;
private final UrlComponent currentUrl;
private final HtmlPagedListUrl url;
@RequestParam(defaultValue = "1", name = CURRENT_PAGE_FIELD_NAME)
private final Integer currentPage;
@RequestParam(defaultValue = "10", name = PAGE_SIZE_FIELD_NAME)
private final Integer pageSize;
// Explain contract for URL and PageListUrl
/**
* Do not forget to clone the Url !!!
*/
public HtmlPagedList(final HtmlRenderer<T> itemRenderer, final PageIterable<T> itemList, final UrlComponent url2, final HtmlPagedListUrl url) {
super();
this.session = Context.getSession();
this.currentPage = url.getCurrentPage();
this.pageSize = url.getPageSize();
this.currentUrl = url2;
this.url = url;
itemList.setPageSize(pageSize);
- itemList.setPage(currentPage);
+ itemList.setPage(currentPage - 1);
this.pageCount = itemList.pageNumber();
if (pageCount > 1) {
add(generateLinksBar());
}
for (final T item : itemList) {
add(itemRenderer.generate(item));
}
if (pageCount > 1) {
add(generateLinksBar());
}
}
private HtmlElement generateLinksBar() {
final HtmlGenericElement span = new HtmlGenericElement("span");
if (currentPage > 1) {
span.add(generateLink(currentPage - 1, session.tr("Previous")));
}
// first page
span.add(generateLink(1));
if (currentPage - 4 > 1) {
span.addText("...");
}
// center pages
for (int i = currentPage - 3; i < currentPage + 3; i++) {
if (i > 1 && i < pageCount) {
span.add(generateLink(i));
}
}
if (currentPage + 4 < pageCount) {
span.addText("...");
}
// Last page
span.add(generateLink(pageCount));
if (currentPage < pageCount) {
span.add(generateLink(currentPage + 1, session.tr("Next")));
}
return span;
}
private HtmlNode generateLink(final int i) {
final String iString = new Integer(i).toString();
return generateLink(i, iString);
}
private HtmlNode generateLink(final int i, final String text) {
final String iString = new Integer(i).toString();
if (i != currentPage) {
url.setCurrentPage(i);
url.setPageSize(pageSize);
return currentUrl.getHtmlLink(text);
}
return new HtmlText(iString);
}
}
| true | false | null | null |
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSClient.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
index cdaf07eb2..672c55f72 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
@@ -1,1732 +1,1738 @@
/**
* 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.hadoop.hdfs;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.SocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.fs.InvalidPathException;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.permission.FsPermission;
import static org.apache.hadoop.hdfs.DFSConfigKeys.*;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.UpgradeAction;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.HdfsProtoUtil;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.NSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
import org.apache.hadoop.hdfs.protocol.datatransfer.Op;
import org.apache.hadoop.hdfs.protocol.datatransfer.ReplaceDatanodeOnFailure;
import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.common.UpgradeStatusReport;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.Client;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenRenewer;
import org.apache.hadoop.util.DataChecksum;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException;
/********************************************************
* DFSClient can connect to a Hadoop Filesystem and
* perform basic file tasks. It uses the ClientProtocol
* to communicate with a NameNode daemon, and connects
* directly to DataNodes to read/write block data.
*
* Hadoop DFS users should obtain an instance of
* DistributedFileSystem, which uses DFSClient to handle
* filesystem tasks.
*
********************************************************/
@InterfaceAudience.Private
public class DFSClient implements java.io.Closeable {
public static final Log LOG = LogFactory.getLog(DFSClient.class);
public static final long SERVER_DEFAULTS_VALIDITY_PERIOD = 60 * 60 * 1000L; // 1 hour
static final int TCP_WINDOW_SIZE = 128 * 1024; // 128 KB
final ClientProtocol namenode;
private final InetSocketAddress nnAddress;
final UserGroupInformation ugi;
volatile boolean clientRunning = true;
private volatile FsServerDefaults serverDefaults;
private volatile long serverDefaultsLastUpdate;
final String clientName;
Configuration conf;
SocketFactory socketFactory;
final ReplaceDatanodeOnFailure dtpReplaceDatanodeOnFailure;
final FileSystem.Statistics stats;
final int hdfsTimeout; // timeout value for a DFS operation.
final LeaseRenewer leaserenewer;
final SocketCache socketCache;
final Conf dfsClientConf;
/**
* DFSClient configuration
*/
static class Conf {
final int maxBlockAcquireFailures;
final int confTime;
final int ioBufferSize;
final int checksumType;
final int bytesPerChecksum;
final int writePacketSize;
final int socketTimeout;
final int socketCacheCapacity;
/** Wait time window (in msec) if BlockMissingException is caught */
final int timeWindow;
final int nCachedConnRetry;
final int nBlockWriteRetry;
final int nBlockWriteLocateFollowingRetry;
final long defaultBlockSize;
final long prefetchSize;
final short defaultReplication;
final String taskId;
final FsPermission uMask;
final boolean useLegacyBlockReader;
Conf(Configuration conf) {
maxBlockAcquireFailures = conf.getInt(
DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY,
DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT);
confTime = conf.getInt(DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY,
HdfsServerConstants.WRITE_TIMEOUT);
ioBufferSize = conf.getInt(
CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_KEY,
CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT);
checksumType = getChecksumType(conf);
bytesPerChecksum = conf.getInt(DFS_BYTES_PER_CHECKSUM_KEY,
DFS_BYTES_PER_CHECKSUM_DEFAULT);
socketTimeout = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY,
HdfsServerConstants.READ_TIMEOUT);
/** dfs.write.packet.size is an internal config variable */
writePacketSize = conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT);
defaultBlockSize = conf.getLongBytes(DFS_BLOCK_SIZE_KEY,
DFS_BLOCK_SIZE_DEFAULT);
defaultReplication = (short) conf.getInt(
DFS_REPLICATION_KEY, DFS_REPLICATION_DEFAULT);
taskId = conf.get("mapreduce.task.attempt.id", "NONMAPREDUCE");
socketCacheCapacity = conf.getInt(DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY,
DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT);
prefetchSize = conf.getLong(DFS_CLIENT_READ_PREFETCH_SIZE_KEY,
10 * defaultBlockSize);
timeWindow = conf
.getInt(DFS_CLIENT_RETRY_WINDOW_BASE, 3000);
nCachedConnRetry = conf.getInt(DFS_CLIENT_CACHED_CONN_RETRY_KEY,
DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT);
nBlockWriteRetry = conf.getInt(DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY,
DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT);
nBlockWriteLocateFollowingRetry = conf
.getInt(DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY,
DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT);
uMask = FsPermission.getUMask(conf);
useLegacyBlockReader = conf.getBoolean(
DFS_CLIENT_USE_LEGACY_BLOCKREADER,
DFS_CLIENT_USE_LEGACY_BLOCKREADER_DEFAULT);
}
private int getChecksumType(Configuration conf) {
String checksum = conf.get(DFSConfigKeys.DFS_CHECKSUM_TYPE_KEY,
DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT);
if ("CRC32".equals(checksum)) {
return DataChecksum.CHECKSUM_CRC32;
} else if ("CRC32C".equals(checksum)) {
return DataChecksum.CHECKSUM_CRC32C;
} else if ("NULL".equals(checksum)) {
return DataChecksum.CHECKSUM_NULL;
} else {
LOG.warn("Bad checksum type: " + checksum + ". Using default.");
return DataChecksum.CHECKSUM_CRC32C;
}
}
private DataChecksum createChecksum() {
return DataChecksum.newDataChecksum(
checksumType, bytesPerChecksum);
}
}
Conf getConf() {
return dfsClientConf;
}
/**
* A map from file names to {@link DFSOutputStream} objects
* that are currently being written by this client.
* Note that a file can only be written by a single client.
*/
private final Map<String, DFSOutputStream> filesBeingWritten
= new HashMap<String, DFSOutputStream>();
private boolean shortCircuitLocalReads;
/**
* Same as this(NameNode.getAddress(conf), conf);
* @see #DFSClient(InetSocketAddress, Configuration)
* @deprecated Deprecated at 0.21
*/
@Deprecated
public DFSClient(Configuration conf) throws IOException {
this(NameNode.getAddress(conf), conf);
}
/**
* Same as this(nameNodeAddr, conf, null);
* @see #DFSClient(InetSocketAddress, Configuration, org.apache.hadoop.fs.FileSystem.Statistics)
*/
public DFSClient(InetSocketAddress nameNodeAddr, Configuration conf
) throws IOException {
this(nameNodeAddr, conf, null);
}
/**
* Same as this(nameNodeAddr, null, conf, stats);
* @see #DFSClient(InetSocketAddress, ClientProtocol, Configuration, org.apache.hadoop.fs.FileSystem.Statistics)
*/
public DFSClient(InetSocketAddress nameNodeAddr, Configuration conf,
FileSystem.Statistics stats)
throws IOException {
this(nameNodeAddr, null, conf, stats);
}
/**
* Create a new DFSClient connected to the given nameNodeAddr or rpcNamenode.
* Exactly one of nameNodeAddr or rpcNamenode must be null.
*/
DFSClient(InetSocketAddress nameNodeAddr, ClientProtocol rpcNamenode,
Configuration conf, FileSystem.Statistics stats)
throws IOException {
// Copy only the required DFSClient configuration
this.dfsClientConf = new Conf(conf);
this.conf = conf;
this.stats = stats;
this.nnAddress = nameNodeAddr;
this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class);
this.dtpReplaceDatanodeOnFailure = ReplaceDatanodeOnFailure.get(conf);
// The hdfsTimeout is currently the same as the ipc timeout
this.hdfsTimeout = Client.getTimeout(conf);
this.ugi = UserGroupInformation.getCurrentUser();
final String authority = nameNodeAddr == null? "null":
nameNodeAddr.getHostName() + ":" + nameNodeAddr.getPort();
this.leaserenewer = LeaseRenewer.getInstance(authority, ugi, this);
this.clientName = leaserenewer.getClientName(dfsClientConf.taskId);
this.socketCache = new SocketCache(dfsClientConf.socketCacheCapacity);
if (nameNodeAddr != null && rpcNamenode == null) {
this.namenode = DFSUtil.createNamenode(nameNodeAddr, conf, ugi);
} else if (nameNodeAddr == null && rpcNamenode != null) {
//This case is used for testing.
this.namenode = rpcNamenode;
} else {
throw new IllegalArgumentException(
"Expecting exactly one of nameNodeAddr and rpcNamenode being null: "
+ "nameNodeAddr=" + nameNodeAddr + ", rpcNamenode=" + rpcNamenode);
}
// read directly from the block file if configured.
this.shortCircuitLocalReads = conf.getBoolean(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY,
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT);
if (LOG.isDebugEnabled()) {
LOG.debug("Short circuit read is " + shortCircuitLocalReads);
}
}
/**
* Return the number of times the client should go back to the namenode
* to retrieve block locations when reading.
*/
int getMaxBlockAcquireFailures() {
return dfsClientConf.maxBlockAcquireFailures;
}
/**
* Return the timeout that clients should use when writing to datanodes.
* @param numNodes the number of nodes in the pipeline.
*/
int getDatanodeWriteTimeout(int numNodes) {
return (dfsClientConf.confTime > 0) ?
(dfsClientConf.confTime + HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * numNodes) : 0;
}
int getDatanodeReadTimeout(int numNodes) {
return dfsClientConf.socketTimeout > 0 ?
(HdfsServerConstants.READ_TIMEOUT_EXTENSION * numNodes +
dfsClientConf.socketTimeout) : 0;
}
int getHdfsTimeout() {
return hdfsTimeout;
}
String getClientName() {
return clientName;
}
void checkOpen() throws IOException {
if (!clientRunning) {
IOException result = new IOException("Filesystem closed");
throw result;
}
}
/** Put a file. */
void putFileBeingWritten(final String src, final DFSOutputStream out) {
synchronized(filesBeingWritten) {
filesBeingWritten.put(src, out);
}
}
/** Remove a file. */
void removeFileBeingWritten(final String src) {
synchronized(filesBeingWritten) {
filesBeingWritten.remove(src);
}
}
/** Is file-being-written map empty? */
boolean isFilesBeingWrittenEmpty() {
synchronized(filesBeingWritten) {
return filesBeingWritten.isEmpty();
}
}
/** @return true if the client is running */
boolean isClientRunning() {
return clientRunning;
}
/**
* Renew leases.
* @return true if lease was renewed. May return false if this
* client has been closed or has no files open.
**/
boolean renewLease() throws IOException {
if (clientRunning && !isFilesBeingWrittenEmpty()) {
namenode.renewLease(clientName);
return true;
}
return false;
}
/**
* Close connections the Namenode.
* The namenode variable is either a rpcProxy passed by a test or
* created using the protocolTranslator which is closeable.
* If closeable then call close, else close using RPC.stopProxy().
*/
void closeConnectionToNamenode() {
if (namenode instanceof Closeable) {
try {
((Closeable) namenode).close();
return;
} catch (IOException e) {
// fall through - lets try the stopProxy
LOG.warn("Exception closing namenode, stopping the proxy");
}
}
RPC.stopProxy(namenode);
}
/** Abort and release resources held. Ignore all errors. */
void abort() {
clientRunning = false;
closeAllFilesBeingWritten(true);
closeConnectionToNamenode();
}
/** Close/abort all files being written. */
private void closeAllFilesBeingWritten(final boolean abort) {
for(;;) {
final String src;
final DFSOutputStream out;
synchronized(filesBeingWritten) {
if (filesBeingWritten.isEmpty()) {
return;
}
src = filesBeingWritten.keySet().iterator().next();
out = filesBeingWritten.remove(src);
}
if (out != null) {
try {
if (abort) {
out.abort();
} else {
out.close();
}
} catch(IOException ie) {
LOG.error("Failed to " + (abort? "abort": "close") + " file " + src,
ie);
}
}
}
}
/**
* Close the file system, abandoning all of the leases and files being
* created and close connections to the namenode.
*/
public synchronized void close() throws IOException {
if(clientRunning) {
closeAllFilesBeingWritten(false);
clientRunning = false;
leaserenewer.closeClient(this);
// close connections to the namenode
closeConnectionToNamenode();
}
}
/**
* Get the default block size for this cluster
* @return the default block size in bytes
*/
public long getDefaultBlockSize() {
return dfsClientConf.defaultBlockSize;
}
/**
* @see ClientProtocol#getPreferredBlockSize(String)
*/
public long getBlockSize(String f) throws IOException {
try {
return namenode.getPreferredBlockSize(f);
} catch (IOException ie) {
LOG.warn("Problem getting block size", ie);
throw ie;
}
}
/**
* Get server default values for a number of configuration params.
* @see ClientProtocol#getServerDefaults()
*/
public FsServerDefaults getServerDefaults() throws IOException {
long now = System.currentTimeMillis();
if (now - serverDefaultsLastUpdate > SERVER_DEFAULTS_VALIDITY_PERIOD) {
serverDefaults = namenode.getServerDefaults();
serverDefaultsLastUpdate = now;
}
return serverDefaults;
}
/**
* @see ClientProtocol#getDelegationToken(Text)
*/
public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
throws IOException {
Token<DelegationTokenIdentifier> result =
namenode.getDelegationToken(renewer);
SecurityUtil.setTokenService(result, nnAddress);
LOG.info("Created " + DelegationTokenIdentifier.stringifyToken(result));
return result;
}
/**
* Renew a delegation token
* @param token the token to renew
* @return the new expiration time
* @throws InvalidToken
* @throws IOException
* @deprecated Use Token.renew instead.
*/
public long renewDelegationToken(Token<DelegationTokenIdentifier> token)
throws InvalidToken, IOException {
LOG.info("Renewing " + DelegationTokenIdentifier.stringifyToken(token));
try {
return token.renew(conf);
} catch (InterruptedException ie) {
throw new RuntimeException("caught interrupted", ie);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
/**
* Get {@link BlockReader} for short circuited local reads.
*/
static BlockReader getLocalBlockReader(Configuration conf,
String src, ExtendedBlock blk, Token<BlockTokenIdentifier> accessToken,
DatanodeInfo chosenNode, int socketTimeout, long offsetIntoBlock)
throws InvalidToken, IOException {
try {
return BlockReaderLocal.newBlockReader(conf, src, blk, accessToken,
chosenNode, socketTimeout, offsetIntoBlock, blk.getNumBytes()
- offsetIntoBlock);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
private static Map<String, Boolean> localAddrMap = Collections
.synchronizedMap(new HashMap<String, Boolean>());
private static boolean isLocalAddress(InetSocketAddress targetAddr) {
InetAddress addr = targetAddr.getAddress();
Boolean cached = localAddrMap.get(addr.getHostAddress());
if (cached != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Address " + targetAddr +
(cached ? " is local" : " is not local"));
}
return cached;
}
// Check if the address is any local or loop back
boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();
// Check if the address is defined on any interface
if (!local) {
try {
local = NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
local = false;
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("Address " + targetAddr +
(local ? " is local" : " is not local"));
}
localAddrMap.put(addr.getHostAddress(), local);
return local;
}
/**
* Should the block access token be refetched on an exception
*
* @param ex Exception received
* @param targetAddr Target datanode address from where exception was received
* @return true if block access token has expired or invalid and it should be
* refetched
*/
private static boolean tokenRefetchNeeded(IOException ex,
InetSocketAddress targetAddr) {
/*
* Get a new access token and retry. Retry is needed in 2 cases. 1) When
* both NN and DN re-started while DFSClient holding a cached access token.
* 2) In the case that NN fails to update its access key at pre-set interval
* (by a wide margin) and subsequently restarts. In this case, DN
* re-registers itself with NN and receives a new access key, but DN will
* delete the old access key from its memory since it's considered expired
* based on the estimated expiration date.
*/
if (ex instanceof InvalidBlockTokenException || ex instanceof InvalidToken) {
LOG.info("Access token was invalid when connecting to " + targetAddr
+ " : " + ex);
return true;
}
return false;
}
/**
* Cancel a delegation token
* @param token the token to cancel
* @throws InvalidToken
* @throws IOException
* @deprecated Use Token.cancel instead.
*/
public void cancelDelegationToken(Token<DelegationTokenIdentifier> token)
throws InvalidToken, IOException {
LOG.info("Cancelling " + DelegationTokenIdentifier.stringifyToken(token));
try {
token.cancel(conf);
} catch (InterruptedException ie) {
throw new RuntimeException("caught interrupted", ie);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
@InterfaceAudience.Private
public static class Renewer extends TokenRenewer {
+ static {
+ //Ensure that HDFS Configuration files are loaded before trying to use
+ // the renewer.
+ HdfsConfiguration.init();
+ }
+
@Override
public boolean handleKind(Text kind) {
return DelegationTokenIdentifier.HDFS_DELEGATION_KIND.equals(kind);
}
@SuppressWarnings("unchecked")
@Override
public long renew(Token<?> token, Configuration conf) throws IOException {
Token<DelegationTokenIdentifier> delToken =
(Token<DelegationTokenIdentifier>) token;
LOG.info("Renewing " +
DelegationTokenIdentifier.stringifyToken(delToken));
ClientProtocol nn =
DFSUtil.createNamenode
(SecurityUtil.getTokenServiceAddr(delToken),
conf, UserGroupInformation.getCurrentUser());
try {
return nn.renewDelegationToken(delToken);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
@SuppressWarnings("unchecked")
@Override
public void cancel(Token<?> token, Configuration conf) throws IOException {
Token<DelegationTokenIdentifier> delToken =
(Token<DelegationTokenIdentifier>) token;
LOG.info("Cancelling " +
DelegationTokenIdentifier.stringifyToken(delToken));
ClientProtocol nn = DFSUtil.createNamenode(
SecurityUtil.getTokenServiceAddr(delToken), conf,
UserGroupInformation.getCurrentUser());
try {
nn.cancelDelegationToken(delToken);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
@Override
public boolean isManaged(Token<?> token) throws IOException {
return true;
}
}
/**
* Report corrupt blocks that were discovered by the client.
* @see ClientProtocol#reportBadBlocks(LocatedBlock[])
*/
public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
namenode.reportBadBlocks(blocks);
}
public short getDefaultReplication() {
return dfsClientConf.defaultReplication;
}
/**
* @see ClientProtocol#getBlockLocations(String, long, long)
*/
static LocatedBlocks callGetBlockLocations(ClientProtocol namenode,
String src, long start, long length)
throws IOException {
try {
return namenode.getBlockLocations(src, start, length);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Recover a file's lease
* @param src a file's path
* @return true if the file is already closed
* @throws IOException
*/
boolean recoverLease(String src) throws IOException {
checkOpen();
try {
return namenode.recoverLease(src, clientName);
} catch (RemoteException re) {
throw re.unwrapRemoteException(FileNotFoundException.class,
AccessControlException.class);
}
}
/**
* Get block location info about file
*
* getBlockLocations() returns a list of hostnames that store
* data for a specific file region. It returns a set of hostnames
* for every block within the indicated region.
*
* This function is very useful when writing code that considers
* data-placement when performing operations. For example, the
* MapReduce system tries to schedule tasks on the same machines
* as the data-block the task processes.
*/
public BlockLocation[] getBlockLocations(String src, long start,
long length) throws IOException, UnresolvedLinkException {
LocatedBlocks blocks = callGetBlockLocations(namenode, src, start, length);
return DFSUtil.locatedBlocks2Locations(blocks);
}
public DFSInputStream open(String src)
throws IOException, UnresolvedLinkException {
return open(src, dfsClientConf.ioBufferSize, true, null);
}
/**
* Create an input stream that obtains a nodelist from the
* namenode, and then reads from all the right places. Creates
* inner subclass of InputStream that does the right out-of-band
* work.
* @deprecated Use {@link #open(String, int, boolean)} instead.
*/
@Deprecated
public DFSInputStream open(String src, int buffersize, boolean verifyChecksum,
FileSystem.Statistics stats)
throws IOException, UnresolvedLinkException {
return open(src, buffersize, verifyChecksum);
}
/**
* Create an input stream that obtains a nodelist from the
* namenode, and then reads from all the right places. Creates
* inner subclass of InputStream that does the right out-of-band
* work.
*/
public DFSInputStream open(String src, int buffersize, boolean verifyChecksum)
throws IOException, UnresolvedLinkException {
checkOpen();
// Get block info from namenode
return new DFSInputStream(this, src, buffersize, verifyChecksum);
}
/**
* Get the namenode associated with this DFSClient object
* @return the namenode associated with this DFSClient object
*/
public ClientProtocol getNamenode() {
return namenode;
}
/**
* Call {@link #create(String, boolean, short, long, Progressable)} with
* default <code>replication</code> and <code>blockSize<code> and null <code>
* progress</code>.
*/
public OutputStream create(String src, boolean overwrite)
throws IOException {
return create(src, overwrite, dfsClientConf.defaultReplication,
dfsClientConf.defaultBlockSize, null);
}
/**
* Call {@link #create(String, boolean, short, long, Progressable)} with
* default <code>replication</code> and <code>blockSize<code>.
*/
public OutputStream create(String src,
boolean overwrite,
Progressable progress) throws IOException {
return create(src, overwrite, dfsClientConf.defaultReplication,
dfsClientConf.defaultBlockSize, progress);
}
/**
* Call {@link #create(String, boolean, short, long, Progressable)} with
* null <code>progress</code>.
*/
public OutputStream create(String src,
boolean overwrite,
short replication,
long blockSize) throws IOException {
return create(src, overwrite, replication, blockSize, null);
}
/**
* Call {@link #create(String, boolean, short, long, Progressable, int)}
* with default bufferSize.
*/
public OutputStream create(String src, boolean overwrite, short replication,
long blockSize, Progressable progress) throws IOException {
return create(src, overwrite, replication, blockSize, progress,
dfsClientConf.ioBufferSize);
}
/**
* Call {@link #create(String, FsPermission, EnumSet, short, long,
* Progressable, int)} with default <code>permission</code>
* {@link FsPermission#getDefault()}.
*
* @param src File name
* @param overwrite overwrite an existing file if true
* @param replication replication factor for the file
* @param blockSize maximum block size
* @param progress interface for reporting client progress
* @param buffersize underlying buffersize
*
* @return output stream
*/
public OutputStream create(String src,
boolean overwrite,
short replication,
long blockSize,
Progressable progress,
int buffersize)
throws IOException {
return create(src, FsPermission.getDefault(),
overwrite ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)
: EnumSet.of(CreateFlag.CREATE), replication, blockSize, progress,
buffersize);
}
/**
* Call {@link #create(String, FsPermission, EnumSet, boolean, short,
* long, Progressable, int)} with <code>createParent</code> set to true.
*/
public OutputStream create(String src,
FsPermission permission,
EnumSet<CreateFlag> flag,
short replication,
long blockSize,
Progressable progress,
int buffersize)
throws IOException {
return create(src, permission, flag, true,
replication, blockSize, progress, buffersize);
}
/**
* Create a new dfs file with the specified block replication
* with write-progress reporting and return an output stream for writing
* into the file.
*
* @param src File name
* @param permission The permission of the directory being created.
* If null, use default permission {@link FsPermission#getDefault()}
* @param flag indicates create a new file or create/overwrite an
* existing file or append to an existing file
* @param createParent create missing parent directory if true
* @param replication block replication
* @param blockSize maximum block size
* @param progress interface for reporting client progress
* @param buffersize underlying buffer size
*
* @return output stream
*
* @see ClientProtocol#create(String, FsPermission, String, EnumSetWritable,
* boolean, short, long) for detailed description of exceptions thrown
*/
public OutputStream create(String src,
FsPermission permission,
EnumSet<CreateFlag> flag,
boolean createParent,
short replication,
long blockSize,
Progressable progress,
int buffersize)
throws IOException {
checkOpen();
if (permission == null) {
permission = FsPermission.getDefault();
}
FsPermission masked = permission.applyUMask(dfsClientConf.uMask);
if(LOG.isDebugEnabled()) {
LOG.debug(src + ": masked=" + masked);
}
final DFSOutputStream result = new DFSOutputStream(this, src, masked, flag,
createParent, replication, blockSize, progress, buffersize,
dfsClientConf.createChecksum());
leaserenewer.put(src, result, this);
return result;
}
/**
* Append to an existing file if {@link CreateFlag#APPEND} is present
*/
private DFSOutputStream primitiveAppend(String src, EnumSet<CreateFlag> flag,
int buffersize, Progressable progress) throws IOException {
if (flag.contains(CreateFlag.APPEND)) {
HdfsFileStatus stat = getFileInfo(src);
if (stat == null) { // No file to append to
// New file needs to be created if create option is present
if (!flag.contains(CreateFlag.CREATE)) {
throw new FileNotFoundException("failed to append to non-existent file "
+ src + " on client " + clientName);
}
return null;
}
return callAppend(stat, src, buffersize, progress);
}
return null;
}
/**
* Same as {{@link #create(String, FsPermission, EnumSet, short, long,
* Progressable, int)} except that the permission
* is absolute (ie has already been masked with umask.
*/
public OutputStream primitiveCreate(String src,
FsPermission absPermission,
EnumSet<CreateFlag> flag,
boolean createParent,
short replication,
long blockSize,
Progressable progress,
int buffersize,
int bytesPerChecksum)
throws IOException, UnresolvedLinkException {
checkOpen();
CreateFlag.validate(flag);
DFSOutputStream result = primitiveAppend(src, flag, buffersize, progress);
if (result == null) {
DataChecksum checksum = DataChecksum.newDataChecksum(
dfsClientConf.checksumType,
bytesPerChecksum);
result = new DFSOutputStream(this, src, absPermission,
flag, createParent, replication, blockSize, progress, buffersize,
checksum);
}
leaserenewer.put(src, result, this);
return result;
}
/**
* Creates a symbolic link.
*
* @see ClientProtocol#createSymlink(String, String,FsPermission, boolean)
*/
public void createSymlink(String target, String link, boolean createParent)
throws IOException {
try {
FsPermission dirPerm =
FsPermission.getDefault().applyUMask(dfsClientConf.uMask);
namenode.createSymlink(target, link, dirPerm, createParent);
} catch (RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileAlreadyExistsException.class,
FileNotFoundException.class,
ParentNotDirectoryException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* Resolve the *first* symlink, if any, in the path.
*
* @see ClientProtocol#getLinkTarget(String)
*/
public String getLinkTarget(String path) throws IOException {
checkOpen();
try {
return namenode.getLinkTarget(path);
} catch (RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class);
}
}
/** Method to get stream returned by append call */
private DFSOutputStream callAppend(HdfsFileStatus stat, String src,
int buffersize, Progressable progress) throws IOException {
LocatedBlock lastBlock = null;
try {
lastBlock = namenode.append(src, clientName);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
DSQuotaExceededException.class,
UnsupportedOperationException.class,
UnresolvedPathException.class);
}
return new DFSOutputStream(this, src, buffersize, progress,
lastBlock, stat, dfsClientConf.createChecksum());
}
/**
* Append to an existing HDFS file.
*
* @param src file name
* @param buffersize buffer size
* @param progress for reporting write-progress; null is acceptable.
* @param statistics file system statistics; null is acceptable.
* @return an output stream for writing into the file
*
* @see ClientProtocol#append(String, String)
*/
public FSDataOutputStream append(final String src, final int buffersize,
final Progressable progress, final FileSystem.Statistics statistics
) throws IOException {
final DFSOutputStream out = append(src, buffersize, progress);
return new FSDataOutputStream(out, statistics, out.getInitialLen());
}
private DFSOutputStream append(String src, int buffersize, Progressable progress)
throws IOException {
checkOpen();
HdfsFileStatus stat = getFileInfo(src);
if (stat == null) { // No file found
throw new FileNotFoundException("failed to append to non-existent file "
+ src + " on client " + clientName);
}
final DFSOutputStream result = callAppend(stat, src, buffersize, progress);
leaserenewer.put(src, result, this);
return result;
}
/**
* Set replication for an existing file.
* @param src file name
* @param replication
*
* @see ClientProtocol#setReplication(String, short)
*/
public boolean setReplication(String src, short replication)
throws IOException {
try {
return namenode.setReplication(src, replication);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* Rename file or directory.
* @see ClientProtocol#rename(String, String)
* @deprecated Use {@link #rename(String, String, Options.Rename...)} instead.
*/
@Deprecated
public boolean rename(String src, String dst) throws IOException {
checkOpen();
try {
return namenode.rename(src, dst);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* Move blocks from src to trg and delete src
* See {@link ClientProtocol#concat(String, String [])}.
*/
public void concat(String trg, String [] srcs) throws IOException {
checkOpen();
try {
namenode.concat(trg, srcs);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
UnresolvedPathException.class);
}
}
/**
* Rename file or directory.
* @see ClientProtocol#rename2(String, String, Options.Rename...)
*/
public void rename(String src, String dst, Options.Rename... options)
throws IOException {
checkOpen();
try {
namenode.rename2(src, dst, options);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
DSQuotaExceededException.class,
FileAlreadyExistsException.class,
FileNotFoundException.class,
ParentNotDirectoryException.class,
SafeModeException.class,
NSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* Delete file or directory.
* See {@link ClientProtocol#delete(String)}.
*/
@Deprecated
public boolean delete(String src) throws IOException {
checkOpen();
return namenode.delete(src, true);
}
/**
* delete file or directory.
* delete contents of the directory if non empty and recursive
* set to true
*
* @see ClientProtocol#delete(String, boolean)
*/
public boolean delete(String src, boolean recursive) throws IOException {
checkOpen();
try {
return namenode.delete(src, recursive);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
UnresolvedPathException.class);
}
}
/** Implemented using getFileInfo(src)
*/
public boolean exists(String src) throws IOException {
checkOpen();
return getFileInfo(src) != null;
}
/**
* Get a partial listing of the indicated directory
* No block locations need to be fetched
*/
public DirectoryListing listPaths(String src, byte[] startAfter)
throws IOException {
return listPaths(src, startAfter, false);
}
/**
* Get a partial listing of the indicated directory
*
* Recommend to use HdfsFileStatus.EMPTY_NAME as startAfter
* if the application wants to fetch a listing starting from
* the first entry in the directory
*
* @see ClientProtocol#getListing(String, byte[], boolean)
*/
public DirectoryListing listPaths(String src, byte[] startAfter,
boolean needLocation)
throws IOException {
checkOpen();
try {
return namenode.getListing(src, startAfter, needLocation);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Get the file info for a specific file or directory.
* @param src The string representation of the path to the file
* @return object containing information regarding the file
* or null if file not found
*
* @see ClientProtocol#getFileInfo(String) for description of exceptions
*/
public HdfsFileStatus getFileInfo(String src) throws IOException {
checkOpen();
try {
return namenode.getFileInfo(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Get the file info for a specific file or directory. If src
* refers to a symlink then the FileStatus of the link is returned.
* @param src path to a file or directory.
*
* For description of exceptions thrown
* @see ClientProtocol#getFileLinkInfo(String)
*/
public HdfsFileStatus getFileLinkInfo(String src) throws IOException {
checkOpen();
try {
return namenode.getFileLinkInfo(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
UnresolvedPathException.class);
}
}
/**
* Get the checksum of a file.
* @param src The file path
* @return The checksum
* @see DistributedFileSystem#getFileChecksum(Path)
*/
public MD5MD5CRC32FileChecksum getFileChecksum(String src) throws IOException {
checkOpen();
return getFileChecksum(src, namenode, socketFactory, dfsClientConf.socketTimeout);
}
/**
* Get the checksum of a file.
* @param src The file path
* @return The checksum
*/
public static MD5MD5CRC32FileChecksum getFileChecksum(String src,
ClientProtocol namenode, SocketFactory socketFactory, int socketTimeout
) throws IOException {
//get all block locations
LocatedBlocks blockLocations = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE);
if (null == blockLocations) {
throw new FileNotFoundException("File does not exist: " + src);
}
List<LocatedBlock> locatedblocks = blockLocations.getLocatedBlocks();
final DataOutputBuffer md5out = new DataOutputBuffer();
int bytesPerCRC = 0;
long crcPerBlock = 0;
boolean refetchBlocks = false;
int lastRetriedIndex = -1;
//get block checksum for each block
for(int i = 0; i < locatedblocks.size(); i++) {
if (refetchBlocks) { // refetch to get fresh tokens
blockLocations = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE);
if (null == blockLocations) {
throw new FileNotFoundException("File does not exist: " + src);
}
locatedblocks = blockLocations.getLocatedBlocks();
refetchBlocks = false;
}
LocatedBlock lb = locatedblocks.get(i);
final ExtendedBlock block = lb.getBlock();
final DatanodeInfo[] datanodes = lb.getLocations();
//try each datanode location of the block
final int timeout = 3000 * datanodes.length + socketTimeout;
boolean done = false;
for(int j = 0; !done && j < datanodes.length; j++) {
Socket sock = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
//connect to a datanode
sock = socketFactory.createSocket();
NetUtils.connect(sock,
NetUtils.createSocketAddr(datanodes[j].getName()), timeout);
sock.setSoTimeout(timeout);
out = new DataOutputStream(
new BufferedOutputStream(NetUtils.getOutputStream(sock),
HdfsConstants.SMALL_BUFFER_SIZE));
in = new DataInputStream(NetUtils.getInputStream(sock));
if (LOG.isDebugEnabled()) {
LOG.debug("write to " + datanodes[j].getName() + ": "
+ Op.BLOCK_CHECKSUM + ", block=" + block);
}
// get block MD5
new Sender(out).blockChecksum(block, lb.getBlockToken());
final BlockOpResponseProto reply =
BlockOpResponseProto.parseFrom(HdfsProtoUtil.vintPrefixed(in));
if (reply.getStatus() != Status.SUCCESS) {
if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN
&& i > lastRetriedIndex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM "
+ "for file " + src + " for block " + block
+ " from datanode " + datanodes[j].getName()
+ ". Will retry the block once.");
}
lastRetriedIndex = i;
done = true; // actually it's not done; but we'll retry
i--; // repeat at i-th block
refetchBlocks = true;
break;
} else {
throw new IOException("Bad response " + reply + " for block "
+ block + " from datanode " + datanodes[j].getName());
}
}
OpBlockChecksumResponseProto checksumData =
reply.getChecksumResponse();
//read byte-per-checksum
final int bpc = checksumData.getBytesPerCrc();
if (i == 0) { //first block
bytesPerCRC = bpc;
}
else if (bpc != bytesPerCRC) {
throw new IOException("Byte-per-checksum not matched: bpc=" + bpc
+ " but bytesPerCRC=" + bytesPerCRC);
}
//read crc-per-block
final long cpb = checksumData.getCrcPerBlock();
if (locatedblocks.size() > 1 && i == 0) {
crcPerBlock = cpb;
}
//read md5
final MD5Hash md5 = new MD5Hash(
checksumData.getMd5().toByteArray());
md5.write(md5out);
done = true;
if (LOG.isDebugEnabled()) {
if (i == 0) {
LOG.debug("set bytesPerCRC=" + bytesPerCRC
+ ", crcPerBlock=" + crcPerBlock);
}
LOG.debug("got reply from " + datanodes[j].getName()
+ ": md5=" + md5);
}
} catch (IOException ie) {
LOG.warn("src=" + src + ", datanodes[" + j + "].getName()="
+ datanodes[j].getName(), ie);
} finally {
IOUtils.closeStream(in);
IOUtils.closeStream(out);
IOUtils.closeSocket(sock);
}
}
if (!done) {
throw new IOException("Fail to get block MD5 for " + block);
}
}
//compute file MD5
final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData());
return new MD5MD5CRC32FileChecksum(bytesPerCRC, crcPerBlock, fileMD5);
}
/**
* Set permissions to a file or directory.
* @param src path name.
* @param permission
*
* @see ClientProtocol#setPermission(String, FsPermission)
*/
public void setPermission(String src, FsPermission permission)
throws IOException {
checkOpen();
try {
namenode.setPermission(src, permission);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
UnresolvedPathException.class);
}
}
/**
* Set file or directory owner.
* @param src path name.
* @param username user id.
* @param groupname user group.
*
* @see ClientProtocol#setOwner(String, String, String)
*/
public void setOwner(String src, String username, String groupname)
throws IOException {
checkOpen();
try {
namenode.setOwner(src, username, groupname);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
UnresolvedPathException.class);
}
}
/**
* @see ClientProtocol#getStats()
*/
public FsStatus getDiskStatus() throws IOException {
long rawNums[] = namenode.getStats();
return new FsStatus(rawNums[0], rawNums[1], rawNums[2]);
}
/**
* Returns count of blocks with no good replicas left. Normally should be
* zero.
* @throws IOException
*/
public long getMissingBlocksCount() throws IOException {
return namenode.getStats()[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX];
}
/**
* Returns count of blocks with one of more replica missing.
* @throws IOException
*/
public long getUnderReplicatedBlocksCount() throws IOException {
return namenode.getStats()[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX];
}
/**
* Returns count of blocks with at least one replica marked corrupt.
* @throws IOException
*/
public long getCorruptBlocksCount() throws IOException {
return namenode.getStats()[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX];
}
/**
* @return a list in which each entry describes a corrupt file/block
* @throws IOException
*/
public CorruptFileBlocks listCorruptFileBlocks(String path,
String cookie)
throws IOException {
return namenode.listCorruptFileBlocks(path, cookie);
}
public DatanodeInfo[] datanodeReport(DatanodeReportType type)
throws IOException {
return namenode.getDatanodeReport(type);
}
/**
* Enter, leave or get safe mode.
*
* @see ClientProtocol#setSafeMode(HdfsConstants.SafeModeAction)
*/
public boolean setSafeMode(SafeModeAction action) throws IOException {
return namenode.setSafeMode(action);
}
/**
* Save namespace image.
*
* @see ClientProtocol#saveNamespace()
*/
void saveNamespace() throws AccessControlException, IOException {
try {
namenode.saveNamespace();
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class);
}
}
/**
* enable/disable restore failed storage.
*
* @see ClientProtocol#restoreFailedStorage(String arg)
*/
boolean restoreFailedStorage(String arg)
throws AccessControlException, IOException{
return namenode.restoreFailedStorage(arg);
}
/**
* Refresh the hosts and exclude files. (Rereads them.)
* See {@link ClientProtocol#refreshNodes()}
* for more details.
*
* @see ClientProtocol#refreshNodes()
*/
public void refreshNodes() throws IOException {
namenode.refreshNodes();
}
/**
* Dumps DFS data structures into specified file.
*
* @see ClientProtocol#metaSave(String)
*/
public void metaSave(String pathname) throws IOException {
namenode.metaSave(pathname);
}
/**
* Requests the namenode to tell all datanodes to use a new, non-persistent
* bandwidth value for dfs.balance.bandwidthPerSec.
* See {@link ClientProtocol#setBalancerBandwidth(long)}
* for more details.
*
* @see ClientProtocol#setBalancerBandwidth(long)
*/
public void setBalancerBandwidth(long bandwidth) throws IOException {
namenode.setBalancerBandwidth(bandwidth);
}
/**
* @see ClientProtocol#finalizeUpgrade()
*/
public void finalizeUpgrade() throws IOException {
namenode.finalizeUpgrade();
}
/**
* @see ClientProtocol#distributedUpgradeProgress(HdfsConstants.UpgradeAction)
*/
public UpgradeStatusReport distributedUpgradeProgress(UpgradeAction action)
throws IOException {
return namenode.distributedUpgradeProgress(action);
}
/**
*/
@Deprecated
public boolean mkdirs(String src) throws IOException {
return mkdirs(src, null, true);
}
/**
* Create a directory (or hierarchy of directories) with the given
* name and permission.
*
* @param src The path of the directory being created
* @param permission The permission of the directory being created.
* If permission == null, use {@link FsPermission#getDefault()}.
* @param createParent create missing parent directory if true
*
* @return True if the operation success.
*
* @see ClientProtocol#mkdirs(String, FsPermission, boolean)
*/
public boolean mkdirs(String src, FsPermission permission,
boolean createParent) throws IOException {
checkOpen();
if (permission == null) {
permission = FsPermission.getDefault();
}
FsPermission masked = permission.applyUMask(dfsClientConf.uMask);
if(LOG.isDebugEnabled()) {
LOG.debug(src + ": masked=" + masked);
}
try {
return namenode.mkdirs(src, masked, createParent);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
InvalidPathException.class,
FileAlreadyExistsException.class,
FileNotFoundException.class,
ParentNotDirectoryException.class,
SafeModeException.class,
NSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* Same {{@link #mkdirs(String, FsPermission, boolean)} except
* that the permissions has already been masked against umask.
*/
public boolean primitiveMkdir(String src, FsPermission absPermission)
throws IOException {
checkOpen();
if (absPermission == null) {
absPermission =
FsPermission.getDefault().applyUMask(dfsClientConf.uMask);
}
if(LOG.isDebugEnabled()) {
LOG.debug(src + ": masked=" + absPermission);
}
try {
return namenode.mkdirs(src, absPermission, true);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* Get {@link ContentSummary} rooted at the specified directory.
* @param path The string representation of the path
*
* @see ClientProtocol#getContentSummary(String)
*/
ContentSummary getContentSummary(String src) throws IOException {
try {
return namenode.getContentSummary(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Sets or resets quotas for a directory.
* @see ClientProtocol#setQuota(String, long, long)
*/
void setQuota(String src, long namespaceQuota, long diskspaceQuota)
throws IOException {
// sanity check
if ((namespaceQuota <= 0 && namespaceQuota != HdfsConstants.QUOTA_DONT_SET &&
namespaceQuota != HdfsConstants.QUOTA_RESET) ||
(diskspaceQuota <= 0 && diskspaceQuota != HdfsConstants.QUOTA_DONT_SET &&
diskspaceQuota != HdfsConstants.QUOTA_RESET)) {
throw new IllegalArgumentException("Invalid values for quota : " +
namespaceQuota + " and " +
diskspaceQuota);
}
try {
namenode.setQuota(src, namespaceQuota, diskspaceQuota);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class);
}
}
/**
* set the modification and access time of a file
*
* @see ClientProtocol#setTimes(String, long, long)
*/
public void setTimes(String src, long mtime, long atime) throws IOException {
checkOpen();
try {
namenode.setTimes(src, mtime, atime);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* The Hdfs implementation of {@link FSDataInputStream}
*/
@InterfaceAudience.Private
public static class DFSDataInputStream extends FSDataInputStream {
public DFSDataInputStream(DFSInputStream in)
throws IOException {
super(in);
}
/**
* Returns the datanode from which the stream is currently reading.
*/
public DatanodeInfo getCurrentDatanode() {
return ((DFSInputStream)in).getCurrentDatanode();
}
/**
* Returns the block containing the target position.
*/
public ExtendedBlock getCurrentBlock() {
return ((DFSInputStream)in).getCurrentBlock();
}
/**
* Return collection of blocks that has already been located.
*/
synchronized List<LocatedBlock> getAllBlocks() throws IOException {
return ((DFSInputStream)in).getAllBlocks();
}
/**
* @return The visible length of the file.
*/
public long getVisibleLength() throws IOException {
return ((DFSInputStream)in).getFileLength();
}
}
boolean shouldTryShortCircuitRead(InetSocketAddress targetAddr) {
if (shortCircuitLocalReads && isLocalAddress(targetAddr)) {
return true;
}
return false;
}
void reportChecksumFailure(String file, ExtendedBlock blk, DatanodeInfo dn) {
DatanodeInfo [] dnArr = { dn };
LocatedBlock [] lblocks = { new LocatedBlock(blk, dnArr) };
reportChecksumFailure(file, lblocks);
}
// just reports checksum failure and ignores any exception during the report.
void reportChecksumFailure(String file, LocatedBlock lblocks[]) {
try {
reportBadBlocks(lblocks);
} catch (IOException ie) {
LOG.info("Found corruption while reading " + file
+ ". Error repairing corrupt blocks. Bad blocks remain.", ie);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "[clientName=" + clientName
+ ", ugi=" + ugi + "]";
}
void disableShortCircuit() {
shortCircuitLocalReads = false;
}
}
| true | false | null | null |
diff --git a/src/org/fife/rsta/ac/groovy/GroovySourceCompletionProvider.java b/src/org/fife/rsta/ac/groovy/GroovySourceCompletionProvider.java
index 4656568..84dc730 100644
--- a/src/org/fife/rsta/ac/groovy/GroovySourceCompletionProvider.java
+++ b/src/org/fife/rsta/ac/groovy/GroovySourceCompletionProvider.java
@@ -1,176 +1,178 @@
/*
* 01/11/2010
*
* Copyright (C) 2011 Robert Futrell
* robert_futrell at users.sourceforge.net
* http://fifesoft.com/rsyntaxtextarea
*
* This code is licensed under the LGPL. See the "license.txt" file included
* with this project.
*/
package org.fife.rsta.ac.groovy;
import java.util.Collections;
import java.util.List;
import javax.swing.text.JTextComponent;
import org.fife.rsta.ac.common.CodeBlock;
import org.fife.rsta.ac.common.TokenScanner;
import org.fife.rsta.ac.common.VariableDeclaration;
import org.fife.rsta.ac.java.JarManager;
import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Token;
/**
* The completion provider used for Groovy source code.
*
* @author Robert Futrell
* @version 1.0
*/
public class GroovySourceCompletionProvider extends DefaultCompletionProvider {
private JarManager jarManager;
+ private static final char[] KEYWORD_DEF = { 'd', 'e', 'f' };
+
/**
* Constructor.
*/
public GroovySourceCompletionProvider() {
this(null);
}
/**
* Constructor.
*
* @param jarManager The jar manager for this provider.
*/
public GroovySourceCompletionProvider(JarManager jarManager) {
if (jarManager==null) {
jarManager = new JarManager();
}
this.jarManager = jarManager;
setParameterizedCompletionParams('(', ", ", ')');
setAutoActivationRules(false, "."); // Default - only activate after '.'
}
private CodeBlock createAst(JTextComponent comp) {
CodeBlock ast = new CodeBlock(0);
RSyntaxTextArea textArea = (RSyntaxTextArea)comp;
TokenScanner scanner = new TokenScanner(textArea);
parseCodeBlock(scanner, ast);
return ast;
}
/**
* {@inheritDoc}
*/
protected List getCompletionsImpl(JTextComponent comp) {
completions.clear();
CodeBlock ast = createAst(comp);
int dot = comp.getCaretPosition();
recursivelyAddLocalVars(completions, ast, dot);
Collections.sort(completions);
// Cut down the list to just those matching what we've typed.
String text = getAlreadyEnteredText(comp);
int start = Collections.binarySearch(completions, text, comparator);
if (start<0) {
start = -(start+1);
}
else {
// There might be multiple entries with the same input text.
while (start>0 &&
comparator.compare(completions.get(start-1), text)==0) {
start--;
}
}
int end = Collections.binarySearch(completions, text+'{', comparator);
end = -(end+1);
return completions.subList(start, end);
}
/**
* {@inheritDoc}
*/
protected boolean isValidChar(char ch) {
return Character.isJavaIdentifierPart(ch) || ch=='.';
}
private void parseCodeBlock(TokenScanner scanner, CodeBlock block) {
Token t = scanner.next();
while (t != null) {
if (t.isRightCurly()) {
block.setEndOffset(t.textOffset);
return;
} else if (t.isLeftCurly()) {
CodeBlock child = block.addChildCodeBlock(t.textOffset);
parseCodeBlock(scanner, child);
- } else if (t.is(Token.RESERVED_WORD, "def")) {
+ } else if (t.is(Token.RESERVED_WORD, KEYWORD_DEF)) {
t = scanner.next();
if (t != null) {
VariableDeclaration varDec = new VariableDeclaration(t
.getLexeme(), t.textOffset);
block.addVariable(varDec);
}
}
t = scanner.next();
}
}
private void recursivelyAddLocalVars(List completions, CodeBlock block,
int dot) {
if (!block.contains(dot)) {
return;
}
// Add local variables declared in this code block
for (int i=0; i<block.getVariableDeclarationCount(); i++) {
VariableDeclaration dec = block.getVariableDeclaration(i);
int decOffs = dec.getOffset();
if (decOffs<dot) {
BasicCompletion c = new BasicCompletion(this, dec.getName());
completions.add(c);
}
else {
break;
}
}
// Add any local variables declared in a child code block
for (int i=0; i<block.getChildCodeBlockCount(); i++) {
CodeBlock child = block.getChildCodeBlock(i);
if (child.contains(dot)) {
recursivelyAddLocalVars(completions, child, dot);
return; // No other child blocks can contain the dot
}
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/ApplicationMojo.java b/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/ApplicationMojo.java
index 275557c2..c5f06263 100644
--- a/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/ApplicationMojo.java
+++ b/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/ApplicationMojo.java
@@ -1,242 +1,242 @@
package info.rvin.mojo.flexmojo.compiler;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static info.rvin.flexmojos.utilities.MavenUtils.resolveSourceFile;
import static java.util.Arrays.asList;
import flex2.tools.oem.Application;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Goal which compiles the Flex sources into an application for either Flex or
* AIR depending on the package type.
*
* @goal compile-swf
* @requiresDependencyResolution
* @phase compile
*/
public class ApplicationMojo extends AbstractFlexCompilerMojo<Application> {
/**
* The file to be compiled. The path must be relative with source folder
*
* @parameter
*/
protected String sourceFile;
/**
* The list of modules files to be compiled. The path must be relative with
* source folder.<BR>
* Usage:
*
* <pre>
* <moduleFiles>
* <module>com/acme/AModule.mxml</module>
* </moduleFiles>
* </pre>
*
* @parameter
*/
private String[] moduleFiles;
private List<File> modules;
/**
* When true, tells flex-mojos to use link reports/load externs on modules
* compilation
*
* @parameter default-value="true"
*/
private boolean loadExternsOnModules;
/**
* The file to be compiled
*/
protected File source;
@Override
public void setUp() throws MojoExecutionException, MojoFailureException {
File sourceDirectory = new File(build.getSourceDirectory());
if (!sourceDirectory.exists()) {
throw new MojoExecutionException(
"Unable to found sourceDirectory: " + sourceDirectory);
}
if (source == null) {
source = resolveSourceFile(project, sourceFile);
}
if (source == null) {
throw new MojoExecutionException(
"Source file not expecified and no default found!");
}
if (!source.exists()) {
throw new MojoFailureException("Unable to find " + sourceFile);
}
// need to initialize builder before go super
try {
builder = new Application(source);
} catch (FileNotFoundException e) {
throw new MojoFailureException("Unable to find " + source);
}
if (moduleFiles != null) {
modules = new ArrayList<File>();
for (String modulePath : moduleFiles) {
File module = new File(sourceDirectory, modulePath);
if (!module.exists()) {
throw new MojoExecutionException("Module " + module
+ " not found.");
}
modules.add(module);
}
if (loadExternsOnModules) {
super.linkReport = true;
}
}
super.setUp();
if (outputFile == null) {
if (output == null) {
outputFile = new File(build.getDirectory(), build
.getFinalName()
+ ".swf");
} else {
outputFile = new File(build.getDirectory(), output);
}
}
builder.setOutput(outputFile);
}
@Override
protected void tearDown() throws MojoExecutionException,
MojoFailureException {
super.tearDown();
if (modules != null) {
configuration.addExterns(new File[] { linkReportFile });
for (File module : modules) {
getLog().info("Compiling module " + module);
String moduleName = module.getName();
moduleName = moduleName.substring(0, moduleName
.lastIndexOf('.'));
Application moduleBuilder;
try {
moduleBuilder = new Application(module);
} catch (FileNotFoundException e) {
throw new MojoFailureException("Unable to find " + module);
}
moduleBuilder.setConfiguration(configuration);
moduleBuilder.setLogger(new CompileLogger(getLog()));
File outputModule = new File(build.getDirectory(), build
.getFinalName()
+ "-" + moduleName + "." + project.getPackaging());
moduleBuilder.setOutput(outputModule);
build(moduleBuilder);
projectHelper.attachArtifact(project, "swf", moduleName,
outputModule);
}
}
}
@Override
protected void writeResourceBundle(String[] bundles, String locale,
File localePath) throws MojoExecutionException {
// Dont break this method in parts, is a work around
- File output = new File(build.getDirectory(), project.getArtifactId()
- + "-" + project.getVersion() + "-" + locale + ".swf");
+ File output = new File(build.getDirectory(), build.getFinalName()
+ + "-" + locale + ".swf");
/*
* mxmlc -locale=en_US -source-path=locale/{locale}
* -include-resource-bundles
* =FlightReservation2,SharedResources,collections
* ,containers,controls,core,effects,formatters,skins,styles
* -output=src/Resources_en_US.swf
*/
String bundlesString = Arrays.toString(bundles) //
.replace("[", "") // remove start [
.replace("]", "") // remove end ]
.replace(", ", ","); // remove spaces
ArrayList<File> external = new ArrayList<File>();
ArrayList<File> internal = new ArrayList<File>();
ArrayList<File> merged = new ArrayList<File>();
external.addAll(asList(getDependenciesPath("external")));
external.addAll(asList(getDependenciesPath("rsl")));
internal.addAll(asList(getDependenciesPath("internal")));
merged.addAll(asList(getDependenciesPath("compile")));
merged.addAll(asList(getDependenciesPath("merged")));
merged.addAll(asList(getResourcesBundles()));
Set<String> args = new HashSet<String>();
// args.addAll(Arrays.asList(configs));
args.add("-locale=" + locale);
args.add("-source-path=" + localePath.getAbsolutePath());
args.add("-include-resource-bundles=" + bundlesString);
args.add("-output=" + output.getAbsolutePath());
args.add("-compiler.fonts.local-fonts-snapshot="
+ getFontsSnapshot().getAbsolutePath());
args.add("-load-config=" + configFile.getAbsolutePath());
args.add("-external-library-path=" + toString(external));
args.add("-include-libraries=" + toString(internal));
args.add("-library-path=" + toString(merged));
// Just a work around
// TODO https://bugs.adobe.com/jira/browse/SDK-15139
flex2.tools.Compiler.mxmlc(args.toArray(new String[args.size()]));
projectHelper.attachArtifact(project, "swf", locale, output);
}
private String toString(List<File> libs) {
StringBuilder sb = new StringBuilder();
for (File lib : libs) {
if (sb.length() != 0) {
sb.append(',');
}
sb.append(lib.getAbsolutePath());
}
return sb.toString();
}
}
diff --git a/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/LibraryMojo.java b/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/LibraryMojo.java
index c631ef56..2ad7115d 100644
--- a/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/LibraryMojo.java
+++ b/rvin-mojo/compiler-mojo/src/main/java/info/rvin/mojo/flexmojo/compiler/LibraryMojo.java
@@ -1,329 +1,329 @@
package info.rvin.mojo.flexmojo.compiler;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static info.rvin.flexmojos.utilities.MavenUtils.resolveArtifact;
import flex2.tools.oem.Library;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Goal which compiles the Flex sources into a library for either Flex or AIR
* depending.
*
* @goal compile-swc
* @requiresDependencyResolution
* @phase compile
*/
public class LibraryMojo extends AbstractFlexCompilerMojo<Library> {
/**
* Enable or disable the computation of a digest for the created swf
* library. This is equivalent to using the
* <code>compiler.computDigest</code> in the compc compiler.
*
* @parameter default-value="true"
*/
private boolean computeDigest;
/**
* This is the equilvalent of the <code>include-classes</code> option of the
* compc compiler.<BR>
* Usage:
*
* <pre>
* <includeClasses>
* <class>AClass</class>
* <class>BClass</class>
* </includeClasses>
* </pre>
*
* @parameter
*/
private String[] includeClasses;
/**
* This is equilvalent to the <code>include-file</code> option of the compc
* compiler.<BR>
* Usage:
*
* <pre>
* <includeFiles>
* <file>${baseDir}/anyFile.txt</file>
* </includeFiles>
* </pre>
*
* @parameter
*/
private File[] includeFiles;
/**
* This is equilvalent to the <code>include-namespaces</code> option of the
* compc compiler.<BR>
* Usage:
*
* <pre>
* <includeNamespaces>
* <namespace>http://www.adobe.com/2006/mxml</namespace>
* </includeNamespaces>
* </pre>
*
* @parameter
*/
private String[] includeNamespaces;
/**
* This is equilvalent to the <code>include-resource-bundles</code> option
* of the compc compiler.<BR>
* Usage:
*
* <pre>
* <includeResourceBundles>
* <bundle>SharedResources</bundle>
* <bundle>collections</bundle>
* <bundle>containers</bundle>
* </includeResourceBundles>
* </pre>
*
* @parameter
*/
private String[] includeResourceBundles;
/**
* @parameter TODO check if is used/useful
*/
private MavenArtifact[] includeResourceBundlesArtifact;
/**
* This is the equilvalent of the <code>include-sources</code> option of the
* compc compiler.<BR>
* Usage:
*
* <pre>
* <includeSources>
* <sources>${baseDir}/src/main/flex</sources>
* </includeSources>
* </pre>
*
* @parameter
*/
protected File[] includeSources;
/**
* Sets the RSL output directory.
*
* @parameter
*/
private File directory;
/*
* TODO how to set this on flex-compiler-oem
*
* -include-lookup-only private boolean includeLookupOnly;
*/
/**
* Adds a CSS stylesheet to this <code>Library</code> object. This is
* equilvalent to the <code>include-stylesheet</code> option of the compc
* compiler.<BR>
* Usage:
*
* <pre>
* <includeStylesheet>
* <stylesheet>
* <name>style1</name>
* <path>${baseDir}/src/main/flex/style1.css</path>
* </stylesheet>
* </includeStylesheet>
* </pre>
*
* @parameter
*/
private Stylesheet[] includeStylesheet;
@Override
public void setUp() throws MojoExecutionException, MojoFailureException {
// need to initialize builder before go super
builder = new Library();
if (directory != null) {
builder.setDirectory(directory);
}
super.setUp();
if (outputFile == null) {
if (output == null) {
outputFile = new File(build.getDirectory(), build
.getFinalName()
+ ".swc");
} else {
outputFile = new File(build.getDirectory(), output);
}
}
builder.setOutput(outputFile);
if (checkNullOrEmpty(includeClasses) && checkNullOrEmpty(includeFiles)
&& checkNullOrEmpty(includeNamespaces)
&& checkNullOrEmpty(includeResourceBundles)
&& checkNullOrEmpty(includeResourceBundlesArtifact)
&& checkNullOrEmpty(includeSources)
&& checkNullOrEmpty(includeStylesheet)) {
getLog().warn(
"Nothing expecified to include. Assuming source folders.");
includeSources = sourcePaths.clone();
}
if (!checkNullOrEmpty(includeClasses)) {
for (String asClass : includeClasses) {
builder.addComponent(asClass);
}
}
if (!checkNullOrEmpty(includeFiles)) {
for (File file : includeFiles) {
if (file == null) {
throw new MojoFailureException("Cannot include a null file");
}
if (!file.exists()) {
throw new MojoFailureException("File " + file.getName()
+ " not found");
}
builder.addArchiveFile(file.getName(), file);
}
}
if (!checkNullOrEmpty(includeNamespaces)) {
for (String uri : includeNamespaces) {
try {
builder.addComponent(new URI(uri));
} catch (URISyntaxException e) {
throw new MojoExecutionException("Invalid URI " + uri, e);
}
}
}
if (!checkNullOrEmpty(includeResourceBundles)) {
for (String rb : includeResourceBundles) {
builder.addResourceBundle(rb);
}
}
if (!checkNullOrEmpty(includeResourceBundlesArtifact)) {
for (MavenArtifact mvnArtifact : includeResourceBundlesArtifact) {
Artifact artifact = artifactFactory
.createArtifactWithClassifier(mvnArtifact.getGroupId(),
mvnArtifact.getArtifactId(), mvnArtifact
.getVersion(), "properties",
"resource-bundle");
resolveArtifact(artifact, resolver, localRepository,
remoteRepositories);
String bundleFile;
try {
bundleFile = FileUtils.readFileToString(artifact.getFile());
} catch (IOException e) {
throw new MojoExecutionException(
"Ocorreu um erro ao ler o artefato " + artifact, e);
}
String[] bundles = bundleFile.split(" ");
for (String bundle : bundles) {
builder.addResourceBundle(bundle);
}
}
}
if (!checkNullOrEmpty(includeSources)) {
for (File file : includeSources) {
if (file == null) {
throw new MojoFailureException("Cannot include a null file");
}
if (!file.exists()) {
throw new MojoFailureException("File " + file.getName()
+ " not found");
}
builder.addComponent(file);
}
}
if (!checkNullOrEmpty(includeStylesheet)) {
for (Stylesheet sheet : includeStylesheet) {
if (!sheet.getPath().exists()) {
throw new MojoExecutionException("Stylesheet not found: "
+ sheet.getPath());
}
builder.addStyleSheet(sheet.getName(), sheet.getPath());
}
}
configuration.enableDigestComputation(computeDigest);
builder.addArchiveFile("maven/" + project.getGroupId() + "/"
+ project.getArtifactId() + "/pom.xml", new File(project
.getBasedir(), "pom.xml"));
}
private boolean checkNullOrEmpty(Object[] array) {
if (array == null) {
return true;
}
if (array.length == 0) {
return false;
}
return false;
}
@Override
protected void writeResourceBundle(String[] bundles, String locale,
File localePath) throws MojoExecutionException {
getLog().info("Generating resource-bundle for " + locale);
Library localized = new Library();
localized.setConfiguration(configuration);
localized.setLogger(new CompileLogger(getLog()));
configuration.addLibraryPath(new File[] { outputFile });
configuration.setLocale(new String[] { locale });
configuration.setSourcePath(new File[] { localePath });
for (String bundle : bundles) {
localized.addResourceBundle(bundle);
}
configuration.addLibraryPath(getResourcesBundles());
- File output = new File(build.getDirectory(), project.getArtifactId()
- + "-" + project.getVersion() + "-" + locale + ".swc");
+ File output = new File(build.getDirectory(), build.getFinalName()
+ + "-" + locale + ".swc");
localized.setOutput(output);
build(localized);
projectHelper
.attachArtifact(project, "resource-bundle", locale, output);
}
}
| false | false | null | null |
diff --git a/ui_swing/src/com/dmdirc/addons/ui_swing/components/frames/InputTextFramePasteAction.java b/ui_swing/src/com/dmdirc/addons/ui_swing/components/frames/InputTextFramePasteAction.java
index 59b97a0b..5aabc088 100644
--- a/ui_swing/src/com/dmdirc/addons/ui_swing/components/frames/InputTextFramePasteAction.java
+++ b/ui_swing/src/com/dmdirc/addons/ui_swing/components/frames/InputTextFramePasteAction.java
@@ -1,172 +1,171 @@
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.components.frames;
import com.dmdirc.DMDircMBassador;
import com.dmdirc.FrameContainer;
import com.dmdirc.addons.ui_swing.components.inputfields.SwingInputField;
import com.dmdirc.addons.ui_swing.dialogs.paste.PasteDialogFactory;
-import com.dmdirc.addons.ui_swing.injection.MainWindow;
import com.dmdirc.events.UserErrorEvent;
import com.dmdirc.logger.ErrorLevel;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.AbstractAction;
/**
* Paste action for input frames.
*/
public final class InputTextFramePasteAction extends AbstractAction {
/** A version number for this class. */
private static final long serialVersionUID = 1;
/** Clipboard to paste from. */
private final Clipboard clipboard;
/** Text component to be acted upon. */
private final InputTextFrame inputFrame;
/** Event bus to post events to. */
private final DMDircMBassador eventBus;
/** Swing input field. */
private final SwingInputField inputField;
/** Frame container. */
private final FrameContainer container;
/** Paste dialog factory. */
private final PasteDialogFactory pasteDialogFactory;
/** Window to parent the dialog on. */
private final Window window;
/**
* Instantiates a new paste action.
*
* @param clipboard Clipboard to paste from
* @param inputFrame Component to be acted upon
*/
public InputTextFramePasteAction(final InputTextFrame inputFrame,
final SwingInputField inputField,
final FrameContainer container,
final Clipboard clipboard,
final DMDircMBassador eventBus,
final PasteDialogFactory pasteDialogFactory,
- @MainWindow final Window window) {
+ final Window window) {
super("Paste");
this.clipboard = clipboard;
this.inputFrame = inputFrame;
this.eventBus = eventBus;
this.inputField = inputField;
this.container = container;
this.pasteDialogFactory = pasteDialogFactory;
this.window = window;
}
@Override
public void actionPerformed(final ActionEvent e) {
try {
if (!clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
return;
}
} catch (final IllegalStateException ex) {
eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, ex,
"Unable to past from clipboard.", ""));
return;
}
try {
//get the contents of the input field and combine it with the
//clipboard
doPaste((String) Toolkit.getDefaultToolkit()
.getSystemClipboard().getData(DataFlavor.stringFlavor));
} catch (final IOException ex) {
eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, ex,
"Unable to get clipboard contents: " + ex.getMessage(), ""));
} catch (final UnsupportedFlavorException ex) {
eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, ex,
"Unsupported clipboard type", ""));
}
}
/**
* Pastes the specified content into the input area.
*
* @param clipboard The contents of the clipboard to be pasted
*
* @since 0.6.3m1
*/
public void doPaste(final String clipboard) {
final String inputFieldText = inputField.getText();
//Get the text that would result from the paste (inputfield
//- selection + clipboard)
final String text = inputFieldText.substring(0, inputField.getSelectionStart())
+ clipboard + inputFieldText.substring(inputField.getSelectionEnd());
final String[] clipboardLines = getSplitLine(text);
//check theres something to paste
if (clipboardLines.length > 1) {
//Clear the input field
inputField.setText("");
final Integer pasteTrigger = container.getConfigManager().
getOptionInt("ui", "pasteProtectionLimit", false);
//check whether the number of lines is over the limit
if (pasteTrigger != null && container.getNumLines(text) > pasteTrigger) {
//show the multi line paste dialog
pasteDialogFactory.getPasteDialog(inputFrame, text, window).displayOrRequestFocus();
} else {
//send the lines
for (final String clipboardLine : clipboardLines) {
inputFrame.getContainer().sendLine(clipboardLine);
}
}
} else {
//put clipboard text in input field
inputField.replaceSelection(clipboard);
}
}
/**
* Splits the line on all line endings.
*
* @param line Line that will be split
*
* @return Split line array
*/
private String[] getSplitLine(final String line) {
return line.replace("\r\n", "\n").replace('\r', '\n').split("\n");
}
@Override
@SuppressWarnings("PMD.AvoidCatchingNPE")
public boolean isEnabled() {
try {
return clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor);
} catch (NullPointerException | IllegalStateException ex) { //https://bugs.openjdk.java.net/browse/JDK-7000965
return false;
}
}
}
| false | false | null | null |
diff --git a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java
index e063fd7093..c26b9cc6e9 100644
--- a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java
+++ b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/window/desktop/RwtScoutDesktop.java
@@ -1,147 +1,159 @@
/*******************************************************************************
* Copyright (c) 2011 BSI Business Systems Integration AG.
* 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:
* BSI Business Systems Integration AG - initial API and implementation
*******************************************************************************/
package org.eclipse.scout.rt.ui.rap.window.desktop;
import org.eclipse.rwt.lifecycle.WidgetUtil;
import org.eclipse.scout.commons.logger.IScoutLogger;
import org.eclipse.scout.commons.logger.ScoutLogManager;
import org.eclipse.scout.rt.client.ui.desktop.IDesktop;
import org.eclipse.scout.rt.client.ui.form.IForm;
import org.eclipse.scout.rt.ui.rap.IRwtStandaloneEnvironment;
import org.eclipse.scout.rt.ui.rap.basic.RwtScoutComposite;
import org.eclipse.scout.rt.ui.rap.core.window.IRwtScoutPart;
import org.eclipse.scout.rt.ui.rap.core.window.desktop.IRwtDesktop;
import org.eclipse.scout.rt.ui.rap.core.window.desktop.IRwtScoutToolbar;
import org.eclipse.scout.rt.ui.rap.core.window.desktop.IViewArea;
import org.eclipse.scout.rt.ui.rap.core.window.desktop.viewarea.ILayoutListener;
import org.eclipse.scout.rt.ui.rap.util.RwtUtility;
import org.eclipse.scout.rt.ui.rap.window.desktop.toolbar.RwtScoutToolbar;
import org.eclipse.scout.rt.ui.rap.window.desktop.viewarea.ViewArea;
import org.eclipse.scout.rt.ui.rap.window.desktop.viewarea.ViewArea.SashKey;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Sash;
/**
* <h3>RwtScoutDesktop</h3> ...
*
* @author Andreas Hoegger
* @since 3.7.0 June 2011
*/
public class RwtScoutDesktop extends RwtScoutComposite<IDesktop> implements IRwtDesktop {
private static final IScoutLogger LOG = ScoutLogManager.getLogger(RwtScoutDesktop.class);
private static final String VARIANT_VIEWS_AREA = "viewsArea";
private ViewArea m_viewArea;
private RwtScoutToolbar m_uiToolbar;
+ private Integer m_toolbarHeight;
public RwtScoutDesktop() {
}
@Override
protected void attachScout() {
super.attachScout();
}
@Override
protected void detachScout() {
super.detachScout();
}
@Override
protected void initializeUi(Composite parent) {
try {
Composite desktopComposite = parent;
Control toolbar = createToolBar(desktopComposite);
Control viewsArea = createViewsArea(desktopComposite);
viewsArea.setData(WidgetUtil.CUSTOM_VARIANT, VARIANT_VIEWS_AREA);
initLayout(desktopComposite, toolbar, viewsArea);
setUiContainer(desktopComposite);
}
catch (Throwable t) {
LOG.error("Exception occured while creating ui desktop.", t);
}
}
protected void initLayout(Composite container, Control toolbar, Control viewsArea) {
GridLayout layout = RwtUtility.createGridLayoutNoSpacing(1, true);
container.setLayout(layout);
if (toolbar != null) {
GridData toolbarData = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
+ if (getToolbarHeight() != null) {
+ toolbarData.heightHint = getToolbarHeight();
+ }
toolbar.setLayoutData(toolbarData);
}
if (viewsArea != null) {
GridData viewsAreaData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH);
viewsArea.setLayoutData(viewsAreaData);
}
}
protected Control createToolBar(Composite parent) {
m_uiToolbar = new RwtScoutToolbar();
m_uiToolbar.createUiField(parent, getScoutObject(), getUiEnvironment());
return m_uiToolbar.getUiContainer();
}
protected Control createViewsArea(Composite parent) {
m_viewArea = new ViewArea(parent);
m_viewArea.getLayout().addLayoutListener(new ILayoutListener() {
@Override
public void handleCompositeLayouted() {
int xOffset = -1;
Sash sash = m_viewArea.getSash(SashKey.VERTICAL_RIGHT);
if (sash.getVisible()) {
Rectangle sashBounds = sash.getBounds();
xOffset = sashBounds.x + sashBounds.width;
}
getUiToolbar().handleRightViewPositionChanged(xOffset);
}
});
return m_viewArea;
}
@Override
public IRwtStandaloneEnvironment getUiEnvironment() {
return (IRwtStandaloneEnvironment) super.getUiEnvironment();
}
@Override
public IRwtScoutPart addForm(IForm form) {
RwtScoutViewStack stack = m_viewArea.getStackForForm(form);
IRwtScoutPart rwtForm = stack.addForm(form);
updateLayout();
return rwtForm;
}
@Override
public void updateLayout() {
m_viewArea.layout();
}
@Override
public IRwtScoutToolbar getUiToolbar() {
return m_uiToolbar;
}
@Override
public IViewArea getViewArea() {
return m_viewArea;
}
+ public Integer getToolbarHeight() {
+ return m_toolbarHeight;
+ }
+
+ public void setToolbarHeight(Integer toolbarHeight) {
+ m_toolbarHeight = toolbarHeight;
+ }
+
}
| false | false | null | null |
diff --git a/src/ma/eugene/nextbusapi/BusStop.java b/src/ma/eugene/nextbusapi/BusStop.java
index 20c86eb..9406fd5 100644
--- a/src/ma/eugene/nextbusapi/BusStop.java
+++ b/src/ma/eugene/nextbusapi/BusStop.java
@@ -1,31 +1,32 @@
/**
* Bus stop state.
* Knows prediction information for each incoming route in either direction.
*/
package ma.eugene.nextbusapi;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import org.xml.sax.SAXException;
public class BusStop {
private class Route {
private String title;
private String direction;
public Route(String title, String direction) {
this.title = title;
this.direction = direction;
}
}
- private HashMap<Route, List<Integer>> predictions;
+ private HashMap<Route, List<Integer>> predictions = new HashMap<Route,
+ List<Integer>>();
public BusStop(String agency, int stopId, int lat, int lon)
throws IOException, org.xml.sax.SAXException {
API api = new API(agency);
for (PredictionsInfo p : api.getPredictions(stopId))
predictions.put(new Route(p.title, p.direction), p.times);
}
}
| true | false | null | null |
diff --git a/src/gui/ImportSessionsForm.java b/src/gui/ImportSessionsForm.java
index 936d6ea..b7aae60 100644
--- a/src/gui/ImportSessionsForm.java
+++ b/src/gui/ImportSessionsForm.java
@@ -1,244 +1,244 @@
/* This file is part of "MidpSSH".
* Copyright (c) 2005 Karl von Randow.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package gui;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import app.LineInputStream;
import app.Main;
import app.SessionManager;
import app.SessionSpec;
import app.Settings;
/**
* Import sessions using an HTTP connection. Parses the returned page looking for lines of the form:
* ssh username@hostname[:port] alias
* telnet hostname[:port] alias
* @author Karl
*
*/
public class ImportSessionsForm extends Form implements Activatable, Runnable, CommandListener {
private TextField tfUrl;
private Activatable back;
//#ifdef blackberryconntypes
private ChoiceGroup cgBlackberryConnType;
//#endif
/**
* @param title
* @param text
* @param maxSize
* @param constraints
*/
public ImportSessionsForm() {
super("Import Sessions");
tfUrl = new TextField( "URL:", null, 255, TextField.ANY );
//#ifdef midp2
tfUrl.setConstraints(TextField.ANY | TextField.URL);
//#endif
append(tfUrl);
//#ifdef blackberryconntypes
cgBlackberryConnType = new ChoiceGroup( "Connection Type", ChoiceGroup.EXCLUSIVE);
cgBlackberryConnType.append( "Default", null );
cgBlackberryConnType.append( "TCP/IP", null );
cgBlackberryConnType.append( "BES", null );
append(cgBlackberryConnType);
//#endif
addCommand(MessageForm.okCommand);
addCommand(MessageForm.backCommand);
setCommandListener(this);
}
public void commandAction(Command command, Displayable arg1) {
if (command == MessageForm.okCommand) {
new Thread(this).start();
}
else if (command == MessageForm.backCommand) {
if (back != null) {
back.activate();
}
}
}
public void activate() {
Main.setDisplay(this);
}
public void activate(Activatable back) {
this.back = back;
activate();
}
public void run() {
HttpConnection c = null;
LineInputStream in = null;
try {
int imported = 0;
String url = tfUrl.getString();
//#ifdef blackberryconntypes
if (cgBlackberryConnType.getSelectedIndex() == 1) {
url += ";deviceside=true";
}
else if (cgBlackberryConnType.getSelectedIndex() == 2) {
url += ";deviceside=false";
}
//#endif
//#ifdef blackberryenterprise
url += ";deviceside=false";
//#endif
c = (HttpConnection) Connector.open(url);
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
- throw new IOException("HTTP response code: " + rc);
+ throw new IOException("HTTP " + rc);
}
in = new LineInputStream(c.openInputStream());
String line = in.readLine();
while (line != null) {
String username = "", host = null, alias = "";
SessionSpec spec = null;
if (line.startsWith("ssh ")) {
int soh = 4;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
int at = line.indexOf('@', soh);
if (at != -1 && at < eoh) {
/* Contains username */
username = line.substring(soh, at);
soh = at + 1;
}
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_SSH;
}
}
else if (line.startsWith("telnet ")) {
int soh = 7;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
/* Insert or replace in Sessions list */
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_TELNET;
}
}
if (spec != null) {
/* Insert or replace in Sessions list */
spec.alias = alias;
spec.host = host;
spec.username = username;
spec.password = "";
appendOrReplaceSession(spec);
imported++;
}
line = in.readLine();
}
back.activate();
Settings.sessionsImportUrl = url;
Settings.saveSettings();
Alert alert = new Alert( "Import Complete" );
alert.setType( AlertType.INFO );
alert.setString( "Imported " + imported + " sessions" );
Main.alert(alert, (Displayable)back);
}
catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert( "Import Failed" );
alert.setType( AlertType.ERROR );
alert.setString( e.getMessage() );
alert.setTimeout( Alert.FOREVER );
Main.alert(alert, this);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (c != null) {
try {
c.close();
} catch (IOException e1) {
}
}
}
}
private void appendOrReplaceSession(SessionSpec newSpec) {
SessionSpec spec = null;
int replaceAt = -1;
Vector sessions = SessionManager.getSessions();
for (int i = 0; i < sessions.size(); i++) {
spec = (SessionSpec) sessions.elementAt(i);
if (spec.type.equals(newSpec.type)) {
if (newSpec.alias.equals(spec.alias)) {
/* Replace this one */
replaceAt = i;
break;
}
}
}
if (replaceAt == -1) {
SessionManager.addSession(newSpec);
}
else {
spec.alias = newSpec.alias;
spec.username = newSpec.username;
spec.host = newSpec.host;
SessionManager.replaceSession(replaceAt, spec);
}
}
}
| true | true | public void run() {
HttpConnection c = null;
LineInputStream in = null;
try {
int imported = 0;
String url = tfUrl.getString();
//#ifdef blackberryconntypes
if (cgBlackberryConnType.getSelectedIndex() == 1) {
url += ";deviceside=true";
}
else if (cgBlackberryConnType.getSelectedIndex() == 2) {
url += ";deviceside=false";
}
//#endif
//#ifdef blackberryenterprise
url += ";deviceside=false";
//#endif
c = (HttpConnection) Connector.open(url);
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
in = new LineInputStream(c.openInputStream());
String line = in.readLine();
while (line != null) {
String username = "", host = null, alias = "";
SessionSpec spec = null;
if (line.startsWith("ssh ")) {
int soh = 4;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
int at = line.indexOf('@', soh);
if (at != -1 && at < eoh) {
/* Contains username */
username = line.substring(soh, at);
soh = at + 1;
}
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_SSH;
}
}
else if (line.startsWith("telnet ")) {
int soh = 7;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
/* Insert or replace in Sessions list */
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_TELNET;
}
}
if (spec != null) {
/* Insert or replace in Sessions list */
spec.alias = alias;
spec.host = host;
spec.username = username;
spec.password = "";
appendOrReplaceSession(spec);
imported++;
}
line = in.readLine();
}
back.activate();
Settings.sessionsImportUrl = url;
Settings.saveSettings();
Alert alert = new Alert( "Import Complete" );
alert.setType( AlertType.INFO );
alert.setString( "Imported " + imported + " sessions" );
Main.alert(alert, (Displayable)back);
}
catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert( "Import Failed" );
alert.setType( AlertType.ERROR );
alert.setString( e.getMessage() );
alert.setTimeout( Alert.FOREVER );
Main.alert(alert, this);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (c != null) {
try {
c.close();
} catch (IOException e1) {
}
}
}
}
| public void run() {
HttpConnection c = null;
LineInputStream in = null;
try {
int imported = 0;
String url = tfUrl.getString();
//#ifdef blackberryconntypes
if (cgBlackberryConnType.getSelectedIndex() == 1) {
url += ";deviceside=true";
}
else if (cgBlackberryConnType.getSelectedIndex() == 2) {
url += ";deviceside=false";
}
//#endif
//#ifdef blackberryenterprise
url += ";deviceside=false";
//#endif
c = (HttpConnection) Connector.open(url);
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP " + rc);
}
in = new LineInputStream(c.openInputStream());
String line = in.readLine();
while (line != null) {
String username = "", host = null, alias = "";
SessionSpec spec = null;
if (line.startsWith("ssh ")) {
int soh = 4;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
int at = line.indexOf('@', soh);
if (at != -1 && at < eoh) {
/* Contains username */
username = line.substring(soh, at);
soh = at + 1;
}
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_SSH;
}
}
else if (line.startsWith("telnet ")) {
int soh = 7;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
/* Insert or replace in Sessions list */
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_TELNET;
}
}
if (spec != null) {
/* Insert or replace in Sessions list */
spec.alias = alias;
spec.host = host;
spec.username = username;
spec.password = "";
appendOrReplaceSession(spec);
imported++;
}
line = in.readLine();
}
back.activate();
Settings.sessionsImportUrl = url;
Settings.saveSettings();
Alert alert = new Alert( "Import Complete" );
alert.setType( AlertType.INFO );
alert.setString( "Imported " + imported + " sessions" );
Main.alert(alert, (Displayable)back);
}
catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert( "Import Failed" );
alert.setType( AlertType.ERROR );
alert.setString( e.getMessage() );
alert.setTimeout( Alert.FOREVER );
Main.alert(alert, this);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (c != null) {
try {
c.close();
} catch (IOException e1) {
}
}
}
}
|
diff --git a/src/org/ohmage/feedback/FeedbackService.java b/src/org/ohmage/feedback/FeedbackService.java
index 91bf2e6..9ae019c 100644
--- a/src/org/ohmage/feedback/FeedbackService.java
+++ b/src/org/ohmage/feedback/FeedbackService.java
@@ -1,335 +1,338 @@
package org.ohmage.feedback;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.OhmageApi;
import org.ohmage.SharedPreferencesHelper;
import org.ohmage.OhmageApi.ImageReadResponse;
import org.ohmage.OhmageApi.Result;
import org.ohmage.OhmageApi.SurveyReadResponse;
import org.ohmage.db.Campaign;
import org.ohmage.db.DbHelper;
import org.ohmage.prompt.photo.PhotoPrompt;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import edu.ucla.cens.systemlog.Log;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class FeedbackService extends WakefulIntentService {
private static final String TAG = "FeedbackService";
public FeedbackService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
}
@SuppressWarnings("unchecked")
@Override
protected void doWakefulWork(Intent intent) {
// for the time being, we just pull all the surveys and update our feedback cache with them
// FIXME: in the future, we should only download what we need...two strategies for that:
// 1) maintain a timestamp of the most recent refresh and request only things after it
// 2) somehow figure out which surveys the server has and we don't via the hashcode and sync accordingly
Log.v(TAG, "Feedback service starting");
OhmageApi api = new OhmageApi(this);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(this);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
// helper instance for parsing utc timestamps
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
// get the time since the last refresh so we can retrieve entries only since then.
// also save the time of this refresh, but only put it into the prefs at the end
long lastRefresh = prefs.getLastFeedbackRefreshTimestamp();
long thisRefresh = System.currentTimeMillis();
// opening two databases here:
// the standard db which lists the users' campaigns...
DbHelper dbHelper = new DbHelper(this);
List<Campaign> campaigns = dbHelper.getCampaigns();
// ...and the feedback database into which we'll be inserting their responses (if necessary)
FeedbackDatabase fbDB = new FeedbackDatabase(this);
if (intent.hasExtra("campaign_urn")) {
// if we received a campaign_urn in the intent, only download the data for that one
- campaigns = new ArrayList<Campaign>(1);
- campaigns.add(dbHelper.getCampaign(intent.getStringExtra("campaign_urn")));
+ // the campaign object we create only inclues the mUrn field since we don't have anything else
+ campaigns = new ArrayList<Campaign>();
+ Campaign candidate = new Campaign();
+ candidate.mUrn = intent.getStringExtra("campaign_urn");
+ campaigns.add(candidate);
}
else {
// otherwise, do all the campaigns
campaigns = dbHelper.getCampaigns();
}
// we'll have to iterate through all the campaigns in which this user
// is participating in order to gather all of their data
for (Campaign c : campaigns) {
Log.v(TAG, "Requesting responsese for campaign " + c.mUrn + "...");
// attempt to construct a date range on which to query, if one exists
// this will be from the last refresh to next year, in order to get everything
String startDate = null;
String endDate = null;
// disabled for now b/c it's going to be hard to test
/*
if (lastRefresh > 0) {
Date future = new Date();
future.setYear(future.getYear()+1);
startDate = ISO8601Utilities.formatDateTime(new Date(lastRefresh));
endDate = ISO8601Utilities.formatDateTime(future);
}
*/
SurveyReadResponse apiResponse = api.surveyResponseRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, null, null, "json-rows", startDate, endDate);
// check if it was successful or not
String error = null;
switch (apiResponse.getResult()) {
case FAILURE: error = "survey response query failed"; break;
case HTTP_ERROR: error = "http error during request"; break;
case INTERNAL_ERROR: error = "internal error during request"; break;
}
if (error != null) {
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
Log.v(TAG, "Request for campaign " + c.mUrn + " complete!");
// gather our survey response array from the response
JSONArray data = apiResponse.getData();
// also maintain a list of photo UUIDs that may or may not be on the device
// this is campaign-specific, which is why it's happening in this loop over the campaigns
ArrayList<String> photoUUIDs = new ArrayList<String>();
// if they have nothing on the server, data may be null
// if that's the case, don't do anything
if (data == null) {
Log.v(TAG, "No data to process, continuing feedback service");
return;
}
// for each survey, insert a record into our feedback db
// if we're unable to insert, just continue (likely a duplicate)
// also, note the schema follows the definition in the documentation
for (int i = 0; i < data.length(); ++i) {
Log.v(TAG, "Processing record " + (i+1) + "/" + data.length());
try {
JSONObject survey = data.getJSONObject(i);
// first we need to gather all of the appropriate data
// from the survey response. some of this data needs to
// be transformed to match the format that SurveyActivity
// uploads/broadcasts, since our survey responses can come
// from either source and need to be stored the same way.
String date = survey.getString("timestamp");
String timezone = survey.getString("timezone");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
long time = sdf.parse(date).getTime();
// much of the location data is optional, hence the "opt*()" calls
String locationStatus = survey.getString("location_status");
double locationLatitude = survey.optDouble("latitude");
double locationLongitude = survey.optDouble("longitude");
String locationProvider = survey.optString("location_provider");
float locationAccuracy = (float)survey.optDouble("location_accuracy");
long locationTime = survey.optLong("location_timestamp");
String surveyId = survey.getString("survey_id");
String surveyLaunchContext = survey.getString("launch_context_long").toString();
// we need to parse out the responses and put them in
// the same format as what we collect from the local activity
JSONObject inputResponses = survey.getJSONObject("responses");
// iterate through inputResponses and create a new JSON object of prompt_ids and values
JSONArray responseJson = new JSONArray();
Iterator<String> keys = inputResponses.keys();
while (keys.hasNext()) {
// for each prompt response, create an object with a prompt_id/value pair
// FIXME: ignoring the "custom_fields" field for now, since it's unused
String key = keys.next();
JSONObject curItem = inputResponses.getJSONObject(key);
// FIXME: deal with repeatable sets here someday, although i'm not sure how
// how do we visualize them on a line graph along with regular points? scatter chart?
if (curItem.has("prompt_response")) {
JSONObject newItem = new JSONObject();
try {
String value = curItem.getString("prompt_response");
newItem.put("prompt_id", key);
newItem.put("value", value);
// if it's a photo, put its value (the photo's UUID) into the photoUUIDs list
if (curItem.getString("prompt_type").equalsIgnoreCase("photo") && !value.equalsIgnoreCase("NOT_DISPLAYED")) {
photoUUIDs.add(value);
}
} catch (JSONException e) {
Log.e(TAG, "JSONException when trying to generate response json", e);
throw new RuntimeException(e);
}
responseJson.put(newItem);
}
}
// render it to a string for storage into our db
String response = responseJson.toString();
// ok, gathered everything; time to insert into the feedback DB
// note that we mark this entry as "remote", meaning it came from the server
fbDB.addResponseRow(
c.mUrn,
username,
date,
time,
timezone,
locationStatus,
locationLatitude,
locationLongitude,
locationProvider,
locationAccuracy,
locationTime,
surveyId,
surveyLaunchContext,
response,
"remote");
// it's possible that the above will fail, in which case it silently returns -1
// we don't do anything differently in that case, so there's no need to check
}
catch(ParseException e) {
// this is a date parse exception, likely thrown from where we parse the utc timestamp
Log.e(TAG, "Problem parsing survey response timestamp", e);
return;
}
catch (JSONException e) {
Log.e(TAG, "Problem parsing response json", e);
return;
}
}
// now that we're done inserting all that data from the server
// let's see if we already have all the photos that were mentioned in the responses
/*
if (photoUUIDs.size() > 0) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + c.mUrn.replace(':', '_'));
photoDir.mkdirs();
for (String photoUUID : photoUUIDs) {
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
Log.v(TAG, "Checking photo w/UUID " + photoUUID + "...");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
Log.v(TAG, "Downloaded photo w/UUID " + photoUUID);
}
else
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID + ": " + ir.getResult().toString());
}
catch (IOException e) {
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID, e);
return;
}
}
else
Log.v(TAG, "Photo w/UUID " + photoUUID + " already exists");
}
}
*/
// done with this campaign! on to the next one...
}
// once we're completely done, it's safe to store the time at which this refresh happened.
// this is to ensure that we don't incorrectly flag the range between the last and current
// as completed in the case that there's an error mid-way through.
prefs.putLastFeedbackRefreshTimestamp(thisRefresh);
Log.v(TAG, "Feedback service complete");
}
public static boolean ensurePhotoExists(Context context, String campaignUrn, String photoUUID) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + campaignUrn.replace(':', '_'));
photoDir.mkdirs();
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
// assemble all the resources to connect to the server
// and then do so!
OhmageApi api = new OhmageApi(context);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(context);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", campaignUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
return true; // we downloaded it successfuly
}
else
return false; // we were unable to download it for some reason
}
catch (IOException e) {
return false; // something went wrong while downloading it
}
}
return true; // it was already there!
}
}
| true | true | protected void doWakefulWork(Intent intent) {
// for the time being, we just pull all the surveys and update our feedback cache with them
// FIXME: in the future, we should only download what we need...two strategies for that:
// 1) maintain a timestamp of the most recent refresh and request only things after it
// 2) somehow figure out which surveys the server has and we don't via the hashcode and sync accordingly
Log.v(TAG, "Feedback service starting");
OhmageApi api = new OhmageApi(this);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(this);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
// helper instance for parsing utc timestamps
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
// get the time since the last refresh so we can retrieve entries only since then.
// also save the time of this refresh, but only put it into the prefs at the end
long lastRefresh = prefs.getLastFeedbackRefreshTimestamp();
long thisRefresh = System.currentTimeMillis();
// opening two databases here:
// the standard db which lists the users' campaigns...
DbHelper dbHelper = new DbHelper(this);
List<Campaign> campaigns = dbHelper.getCampaigns();
// ...and the feedback database into which we'll be inserting their responses (if necessary)
FeedbackDatabase fbDB = new FeedbackDatabase(this);
if (intent.hasExtra("campaign_urn")) {
// if we received a campaign_urn in the intent, only download the data for that one
campaigns = new ArrayList<Campaign>(1);
campaigns.add(dbHelper.getCampaign(intent.getStringExtra("campaign_urn")));
}
else {
// otherwise, do all the campaigns
campaigns = dbHelper.getCampaigns();
}
// we'll have to iterate through all the campaigns in which this user
// is participating in order to gather all of their data
for (Campaign c : campaigns) {
Log.v(TAG, "Requesting responsese for campaign " + c.mUrn + "...");
// attempt to construct a date range on which to query, if one exists
// this will be from the last refresh to next year, in order to get everything
String startDate = null;
String endDate = null;
// disabled for now b/c it's going to be hard to test
/*
if (lastRefresh > 0) {
Date future = new Date();
future.setYear(future.getYear()+1);
startDate = ISO8601Utilities.formatDateTime(new Date(lastRefresh));
endDate = ISO8601Utilities.formatDateTime(future);
}
*/
SurveyReadResponse apiResponse = api.surveyResponseRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, null, null, "json-rows", startDate, endDate);
// check if it was successful or not
String error = null;
switch (apiResponse.getResult()) {
case FAILURE: error = "survey response query failed"; break;
case HTTP_ERROR: error = "http error during request"; break;
case INTERNAL_ERROR: error = "internal error during request"; break;
}
if (error != null) {
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
Log.v(TAG, "Request for campaign " + c.mUrn + " complete!");
// gather our survey response array from the response
JSONArray data = apiResponse.getData();
// also maintain a list of photo UUIDs that may or may not be on the device
// this is campaign-specific, which is why it's happening in this loop over the campaigns
ArrayList<String> photoUUIDs = new ArrayList<String>();
// if they have nothing on the server, data may be null
// if that's the case, don't do anything
if (data == null) {
Log.v(TAG, "No data to process, continuing feedback service");
return;
}
// for each survey, insert a record into our feedback db
// if we're unable to insert, just continue (likely a duplicate)
// also, note the schema follows the definition in the documentation
for (int i = 0; i < data.length(); ++i) {
Log.v(TAG, "Processing record " + (i+1) + "/" + data.length());
try {
JSONObject survey = data.getJSONObject(i);
// first we need to gather all of the appropriate data
// from the survey response. some of this data needs to
// be transformed to match the format that SurveyActivity
// uploads/broadcasts, since our survey responses can come
// from either source and need to be stored the same way.
String date = survey.getString("timestamp");
String timezone = survey.getString("timezone");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
long time = sdf.parse(date).getTime();
// much of the location data is optional, hence the "opt*()" calls
String locationStatus = survey.getString("location_status");
double locationLatitude = survey.optDouble("latitude");
double locationLongitude = survey.optDouble("longitude");
String locationProvider = survey.optString("location_provider");
float locationAccuracy = (float)survey.optDouble("location_accuracy");
long locationTime = survey.optLong("location_timestamp");
String surveyId = survey.getString("survey_id");
String surveyLaunchContext = survey.getString("launch_context_long").toString();
// we need to parse out the responses and put them in
// the same format as what we collect from the local activity
JSONObject inputResponses = survey.getJSONObject("responses");
// iterate through inputResponses and create a new JSON object of prompt_ids and values
JSONArray responseJson = new JSONArray();
Iterator<String> keys = inputResponses.keys();
while (keys.hasNext()) {
// for each prompt response, create an object with a prompt_id/value pair
// FIXME: ignoring the "custom_fields" field for now, since it's unused
String key = keys.next();
JSONObject curItem = inputResponses.getJSONObject(key);
// FIXME: deal with repeatable sets here someday, although i'm not sure how
// how do we visualize them on a line graph along with regular points? scatter chart?
if (curItem.has("prompt_response")) {
JSONObject newItem = new JSONObject();
try {
String value = curItem.getString("prompt_response");
newItem.put("prompt_id", key);
newItem.put("value", value);
// if it's a photo, put its value (the photo's UUID) into the photoUUIDs list
if (curItem.getString("prompt_type").equalsIgnoreCase("photo") && !value.equalsIgnoreCase("NOT_DISPLAYED")) {
photoUUIDs.add(value);
}
} catch (JSONException e) {
Log.e(TAG, "JSONException when trying to generate response json", e);
throw new RuntimeException(e);
}
responseJson.put(newItem);
}
}
// render it to a string for storage into our db
String response = responseJson.toString();
// ok, gathered everything; time to insert into the feedback DB
// note that we mark this entry as "remote", meaning it came from the server
fbDB.addResponseRow(
c.mUrn,
username,
date,
time,
timezone,
locationStatus,
locationLatitude,
locationLongitude,
locationProvider,
locationAccuracy,
locationTime,
surveyId,
surveyLaunchContext,
response,
"remote");
// it's possible that the above will fail, in which case it silently returns -1
// we don't do anything differently in that case, so there's no need to check
}
catch(ParseException e) {
// this is a date parse exception, likely thrown from where we parse the utc timestamp
Log.e(TAG, "Problem parsing survey response timestamp", e);
return;
}
catch (JSONException e) {
Log.e(TAG, "Problem parsing response json", e);
return;
}
}
// now that we're done inserting all that data from the server
// let's see if we already have all the photos that were mentioned in the responses
/*
if (photoUUIDs.size() > 0) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + c.mUrn.replace(':', '_'));
photoDir.mkdirs();
for (String photoUUID : photoUUIDs) {
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
Log.v(TAG, "Checking photo w/UUID " + photoUUID + "...");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
Log.v(TAG, "Downloaded photo w/UUID " + photoUUID);
}
else
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID + ": " + ir.getResult().toString());
}
catch (IOException e) {
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID, e);
return;
}
}
else
Log.v(TAG, "Photo w/UUID " + photoUUID + " already exists");
}
}
*/
// done with this campaign! on to the next one...
}
// once we're completely done, it's safe to store the time at which this refresh happened.
// this is to ensure that we don't incorrectly flag the range between the last and current
// as completed in the case that there's an error mid-way through.
prefs.putLastFeedbackRefreshTimestamp(thisRefresh);
Log.v(TAG, "Feedback service complete");
}
| protected void doWakefulWork(Intent intent) {
// for the time being, we just pull all the surveys and update our feedback cache with them
// FIXME: in the future, we should only download what we need...two strategies for that:
// 1) maintain a timestamp of the most recent refresh and request only things after it
// 2) somehow figure out which surveys the server has and we don't via the hashcode and sync accordingly
Log.v(TAG, "Feedback service starting");
OhmageApi api = new OhmageApi(this);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(this);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
// helper instance for parsing utc timestamps
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
// get the time since the last refresh so we can retrieve entries only since then.
// also save the time of this refresh, but only put it into the prefs at the end
long lastRefresh = prefs.getLastFeedbackRefreshTimestamp();
long thisRefresh = System.currentTimeMillis();
// opening two databases here:
// the standard db which lists the users' campaigns...
DbHelper dbHelper = new DbHelper(this);
List<Campaign> campaigns = dbHelper.getCampaigns();
// ...and the feedback database into which we'll be inserting their responses (if necessary)
FeedbackDatabase fbDB = new FeedbackDatabase(this);
if (intent.hasExtra("campaign_urn")) {
// if we received a campaign_urn in the intent, only download the data for that one
// the campaign object we create only inclues the mUrn field since we don't have anything else
campaigns = new ArrayList<Campaign>();
Campaign candidate = new Campaign();
candidate.mUrn = intent.getStringExtra("campaign_urn");
campaigns.add(candidate);
}
else {
// otherwise, do all the campaigns
campaigns = dbHelper.getCampaigns();
}
// we'll have to iterate through all the campaigns in which this user
// is participating in order to gather all of their data
for (Campaign c : campaigns) {
Log.v(TAG, "Requesting responsese for campaign " + c.mUrn + "...");
// attempt to construct a date range on which to query, if one exists
// this will be from the last refresh to next year, in order to get everything
String startDate = null;
String endDate = null;
// disabled for now b/c it's going to be hard to test
/*
if (lastRefresh > 0) {
Date future = new Date();
future.setYear(future.getYear()+1);
startDate = ISO8601Utilities.formatDateTime(new Date(lastRefresh));
endDate = ISO8601Utilities.formatDateTime(future);
}
*/
SurveyReadResponse apiResponse = api.surveyResponseRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, null, null, "json-rows", startDate, endDate);
// check if it was successful or not
String error = null;
switch (apiResponse.getResult()) {
case FAILURE: error = "survey response query failed"; break;
case HTTP_ERROR: error = "http error during request"; break;
case INTERNAL_ERROR: error = "internal error during request"; break;
}
if (error != null) {
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
Log.v(TAG, "Request for campaign " + c.mUrn + " complete!");
// gather our survey response array from the response
JSONArray data = apiResponse.getData();
// also maintain a list of photo UUIDs that may or may not be on the device
// this is campaign-specific, which is why it's happening in this loop over the campaigns
ArrayList<String> photoUUIDs = new ArrayList<String>();
// if they have nothing on the server, data may be null
// if that's the case, don't do anything
if (data == null) {
Log.v(TAG, "No data to process, continuing feedback service");
return;
}
// for each survey, insert a record into our feedback db
// if we're unable to insert, just continue (likely a duplicate)
// also, note the schema follows the definition in the documentation
for (int i = 0; i < data.length(); ++i) {
Log.v(TAG, "Processing record " + (i+1) + "/" + data.length());
try {
JSONObject survey = data.getJSONObject(i);
// first we need to gather all of the appropriate data
// from the survey response. some of this data needs to
// be transformed to match the format that SurveyActivity
// uploads/broadcasts, since our survey responses can come
// from either source and need to be stored the same way.
String date = survey.getString("timestamp");
String timezone = survey.getString("timezone");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
long time = sdf.parse(date).getTime();
// much of the location data is optional, hence the "opt*()" calls
String locationStatus = survey.getString("location_status");
double locationLatitude = survey.optDouble("latitude");
double locationLongitude = survey.optDouble("longitude");
String locationProvider = survey.optString("location_provider");
float locationAccuracy = (float)survey.optDouble("location_accuracy");
long locationTime = survey.optLong("location_timestamp");
String surveyId = survey.getString("survey_id");
String surveyLaunchContext = survey.getString("launch_context_long").toString();
// we need to parse out the responses and put them in
// the same format as what we collect from the local activity
JSONObject inputResponses = survey.getJSONObject("responses");
// iterate through inputResponses and create a new JSON object of prompt_ids and values
JSONArray responseJson = new JSONArray();
Iterator<String> keys = inputResponses.keys();
while (keys.hasNext()) {
// for each prompt response, create an object with a prompt_id/value pair
// FIXME: ignoring the "custom_fields" field for now, since it's unused
String key = keys.next();
JSONObject curItem = inputResponses.getJSONObject(key);
// FIXME: deal with repeatable sets here someday, although i'm not sure how
// how do we visualize them on a line graph along with regular points? scatter chart?
if (curItem.has("prompt_response")) {
JSONObject newItem = new JSONObject();
try {
String value = curItem.getString("prompt_response");
newItem.put("prompt_id", key);
newItem.put("value", value);
// if it's a photo, put its value (the photo's UUID) into the photoUUIDs list
if (curItem.getString("prompt_type").equalsIgnoreCase("photo") && !value.equalsIgnoreCase("NOT_DISPLAYED")) {
photoUUIDs.add(value);
}
} catch (JSONException e) {
Log.e(TAG, "JSONException when trying to generate response json", e);
throw new RuntimeException(e);
}
responseJson.put(newItem);
}
}
// render it to a string for storage into our db
String response = responseJson.toString();
// ok, gathered everything; time to insert into the feedback DB
// note that we mark this entry as "remote", meaning it came from the server
fbDB.addResponseRow(
c.mUrn,
username,
date,
time,
timezone,
locationStatus,
locationLatitude,
locationLongitude,
locationProvider,
locationAccuracy,
locationTime,
surveyId,
surveyLaunchContext,
response,
"remote");
// it's possible that the above will fail, in which case it silently returns -1
// we don't do anything differently in that case, so there's no need to check
}
catch(ParseException e) {
// this is a date parse exception, likely thrown from where we parse the utc timestamp
Log.e(TAG, "Problem parsing survey response timestamp", e);
return;
}
catch (JSONException e) {
Log.e(TAG, "Problem parsing response json", e);
return;
}
}
// now that we're done inserting all that data from the server
// let's see if we already have all the photos that were mentioned in the responses
/*
if (photoUUIDs.size() > 0) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + c.mUrn.replace(':', '_'));
photoDir.mkdirs();
for (String photoUUID : photoUUIDs) {
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
Log.v(TAG, "Checking photo w/UUID " + photoUUID + "...");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
Log.v(TAG, "Downloaded photo w/UUID " + photoUUID);
}
else
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID + ": " + ir.getResult().toString());
}
catch (IOException e) {
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID, e);
return;
}
}
else
Log.v(TAG, "Photo w/UUID " + photoUUID + " already exists");
}
}
*/
// done with this campaign! on to the next one...
}
// once we're completely done, it's safe to store the time at which this refresh happened.
// this is to ensure that we don't incorrectly flag the range between the last and current
// as completed in the case that there's an error mid-way through.
prefs.putLastFeedbackRefreshTimestamp(thisRefresh);
Log.v(TAG, "Feedback service complete");
}
|
diff --git a/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java b/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java
index 667d86bc2..7da35ce27 100644
--- a/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java
+++ b/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java
@@ -1,347 +1,347 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.patches;
import static com.google.gerrit.client.patches.PatchLine.Type.CONTEXT;
import static com.google.gerrit.client.patches.PatchLine.Type.DELETE;
import static com.google.gerrit.client.patches.PatchLine.Type.INSERT;
import com.google.gerrit.client.data.EditList;
import com.google.gerrit.client.data.PatchScript;
import com.google.gerrit.client.data.SparseFileContent;
import com.google.gerrit.client.data.EditList.Hunk;
import com.google.gerrit.client.data.PatchScript.DisplayMethod;
import com.google.gerrit.client.reviewdb.Patch;
import com.google.gerrit.client.reviewdb.PatchLineComment;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.safehtml.client.PrettyFormatter;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
import com.google.gwtorm.client.KeyUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class UnifiedDiffTable extends AbstractPatchContentTable {
private static final int PC = 3;
private static final Comparator<PatchLineComment> BY_DATE =
new Comparator<PatchLineComment>() {
public int compare(final PatchLineComment o1, final PatchLineComment o2) {
return o1.getWrittenOn().compareTo(o2.getWrittenOn());
}
};
@Override
protected void onCellDoubleClick(final int row, final int column) {
if (getRowItem(row) instanceof PatchLine) {
final PatchLine pl = (PatchLine) getRowItem(row);
switch (pl.getType()) {
case DELETE:
case CONTEXT:
createCommentEditor(row + 1, PC, pl.getLineA(), (short) 0);
break;
case INSERT:
createCommentEditor(row + 1, PC, pl.getLineB(), (short) 1);
break;
}
}
}
@Override
protected void onInsertComment(final PatchLine pl) {
final int row = getCurrentRow();
switch (pl.getType()) {
case DELETE:
case CONTEXT:
createCommentEditor(row + 1, PC, pl.getLineA(), (short) 0);
break;
case INSERT:
createCommentEditor(row + 1, PC, pl.getLineB(), (short) 1);
break;
}
}
private void appendImgTag(SafeHtmlBuilder nc, String url) {
nc.openElement("img");
nc.setAttribute("src", url);
nc.closeElement("img");
}
@Override
protected void render(final PatchScript script) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
final SafeHtmlBuilder nc = new SafeHtmlBuilder();
final PrettyFormatter fmtA = PrettyFormatter.newFormatter(formatLanguage);
final PrettyFormatter fmtB = PrettyFormatter.newFormatter(formatLanguage);
fmtB.setShowWhiteSpaceErrors(true);
// Display the patch header
for (final String line : script.getPatchHeader()) {
appendFileHeader(nc, line);
}
if (script.getDisplayMethodA() == DisplayMethod.IMG
|| script.getDisplayMethodB() == DisplayMethod.IMG) {
final String rawBase = GWT.getHostPageBaseURL() + "cat/";
nc.openTr();
nc.setAttribute("valign", "center");
nc.setAttribute("align", "center");
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
if (script.getDisplayMethodA() == DisplayMethod.IMG) {
if (idSideA == null) {
+ appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
+ } else {
Patch.Key k = new Patch.Key(idSideA, patchKey.get());
appendImgTag(nc, rawBase + KeyUtil.encode(k.toString()) + "^0");
- } else {
- appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
}
}
if (script.getDisplayMethodB() == DisplayMethod.IMG) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^0");
}
nc.closeTd();
nc.closeTr();
}
final ArrayList<PatchLine> lines = new ArrayList<PatchLine>();
for (final EditList.Hunk hunk : script.getHunks()) {
appendHunkHeader(nc, hunk);
while (hunk.next()) {
if (hunk.isContextLine()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, CONTEXT, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incBoth();
lines.add(new PatchLine(CONTEXT, hunk.getCurA(), hunk.getCurB()));
} else if (hunk.isDeletedA()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
padLineNumber(nc);
appendLineText(nc, DELETE, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incA();
lines.add(new PatchLine(DELETE, hunk.getCurA(), 0));
if (a.size() == hunk.getCurA() && a.isMissingNewlineAtEnd())
appendNoLF(nc);
} else if (hunk.isInsertedB()) {
openLine(nc);
padLineNumber(nc);
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, INSERT, b, hunk.getCurB(), fmtA, fmtB);
closeLine(nc);
hunk.incB();
lines.add(new PatchLine(INSERT, 0, hunk.getCurB()));
if (b.size() == hunk.getCurB() && b.isMissingNewlineAtEnd())
appendNoLF(nc);
}
}
}
resetHtml(nc);
initScript(script);
int row = script.getPatchHeader().size();
final CellFormatter fmt = table.getCellFormatter();
final Iterator<PatchLine> iLine = lines.iterator();
while (iLine.hasNext()) {
final PatchLine l = iLine.next();
final String n = "DiffText-" + l.getType().name();
while (!fmt.getStyleName(row, PC).contains(n)) {
row++;
}
setRowItem(row++, l);
}
}
@Override
public void display(final CommentDetail cd) {
if (cd.isEmpty()) {
return;
}
setAccountInfoCache(cd.getAccounts());
final ArrayList<PatchLineComment> all = new ArrayList<PatchLineComment>();
for (int row = 0; row < table.getRowCount();) {
if (getRowItem(row) instanceof PatchLine) {
final PatchLine pLine = (PatchLine) getRowItem(row);
final List<PatchLineComment> fora = cd.getForA(pLine.getLineA());
final List<PatchLineComment> forb = cd.getForB(pLine.getLineB());
row++;
if (!fora.isEmpty() && !forb.isEmpty()) {
all.clear();
all.addAll(fora);
all.addAll(forb);
Collections.sort(all, BY_DATE);
row = insert(all, row);
} else if (!fora.isEmpty()) {
row = insert(fora, row);
} else if (!forb.isEmpty()) {
row = insert(forb, row);
}
} else {
row++;
}
}
}
private int insert(final List<PatchLineComment> in, int row) {
for (Iterator<PatchLineComment> ci = in.iterator(); ci.hasNext();) {
final PatchLineComment c = ci.next();
table.insertRow(row);
table.getCellFormatter().setStyleName(row, 0, S_ICON_CELL);
bindComment(row, PC, c, !ci.hasNext());
row++;
}
return row;
}
private void appendFileHeader(final SafeHtmlBuilder m, final String line) {
openLine(m);
padLineNumber(m);
padLineNumber(m);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-FILE_HEADER");
m.append(line);
m.closeTd();
closeLine(m);
}
private void appendHunkHeader(final SafeHtmlBuilder m, final Hunk hunk) {
openLine(m);
padLineNumber(m);
padLineNumber(m);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-HUNK_HEADER");
m.append("@@ -");
appendRange(m, hunk.getCurA() + 1, hunk.getEndA() - hunk.getCurA());
m.append(" +");
appendRange(m, hunk.getCurB() + 1, hunk.getEndB() - hunk.getCurB());
m.append(" @@");
m.closeTd();
closeLine(m);
}
private void appendRange(final SafeHtmlBuilder m, final int begin,
final int cnt) {
switch (cnt) {
case 0:
m.append(begin - 1);
m.append(",0");
break;
case 1:
m.append(begin);
break;
default:
m.append(begin);
m.append(',');
m.append(cnt);
break;
}
}
private void appendLineText(final SafeHtmlBuilder m,
final PatchLine.Type type, final SparseFileContent src, final int i,
final PrettyFormatter fmtA, final PrettyFormatter fmtB) {
final String text = src.get(i);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-" + type.name());
switch (type) {
case CONTEXT:
m.nbsp();
m.append(fmtA.format(text));
fmtB.update(text);
break;
case DELETE:
m.append("-");
m.append(fmtA.format(text));
break;
case INSERT:
m.append("+");
m.append(fmtB.format(text));
break;
}
m.closeTd();
}
private void appendNoLF(final SafeHtmlBuilder m) {
openLine(m);
padLineNumber(m);
padLineNumber(m);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-NO_LF");
m.append("\\ No newline at end of file");
m.closeTd();
closeLine(m);
}
private void openLine(final SafeHtmlBuilder m) {
m.openTr();
m.setAttribute("valign", "top");
m.openTd();
m.setStyleName(S_ICON_CELL);
m.closeTd();
}
private void closeLine(final SafeHtmlBuilder m) {
m.closeTr();
}
private void padLineNumber(final SafeHtmlBuilder m) {
m.openTd();
m.setStyleName("LineNumber");
m.closeTd();
}
private void appendLineNumber(final SafeHtmlBuilder m, final int idx) {
m.openTd();
m.setStyleName("LineNumber");
m.append(idx + 1);
m.closeTd();
}
}
| false | true | protected void render(final PatchScript script) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
final SafeHtmlBuilder nc = new SafeHtmlBuilder();
final PrettyFormatter fmtA = PrettyFormatter.newFormatter(formatLanguage);
final PrettyFormatter fmtB = PrettyFormatter.newFormatter(formatLanguage);
fmtB.setShowWhiteSpaceErrors(true);
// Display the patch header
for (final String line : script.getPatchHeader()) {
appendFileHeader(nc, line);
}
if (script.getDisplayMethodA() == DisplayMethod.IMG
|| script.getDisplayMethodB() == DisplayMethod.IMG) {
final String rawBase = GWT.getHostPageBaseURL() + "cat/";
nc.openTr();
nc.setAttribute("valign", "center");
nc.setAttribute("align", "center");
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
if (script.getDisplayMethodA() == DisplayMethod.IMG) {
if (idSideA == null) {
Patch.Key k = new Patch.Key(idSideA, patchKey.get());
appendImgTag(nc, rawBase + KeyUtil.encode(k.toString()) + "^0");
} else {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
}
}
if (script.getDisplayMethodB() == DisplayMethod.IMG) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^0");
}
nc.closeTd();
nc.closeTr();
}
final ArrayList<PatchLine> lines = new ArrayList<PatchLine>();
for (final EditList.Hunk hunk : script.getHunks()) {
appendHunkHeader(nc, hunk);
while (hunk.next()) {
if (hunk.isContextLine()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, CONTEXT, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incBoth();
lines.add(new PatchLine(CONTEXT, hunk.getCurA(), hunk.getCurB()));
} else if (hunk.isDeletedA()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
padLineNumber(nc);
appendLineText(nc, DELETE, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incA();
lines.add(new PatchLine(DELETE, hunk.getCurA(), 0));
if (a.size() == hunk.getCurA() && a.isMissingNewlineAtEnd())
appendNoLF(nc);
} else if (hunk.isInsertedB()) {
openLine(nc);
padLineNumber(nc);
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, INSERT, b, hunk.getCurB(), fmtA, fmtB);
closeLine(nc);
hunk.incB();
lines.add(new PatchLine(INSERT, 0, hunk.getCurB()));
if (b.size() == hunk.getCurB() && b.isMissingNewlineAtEnd())
appendNoLF(nc);
}
}
}
resetHtml(nc);
initScript(script);
int row = script.getPatchHeader().size();
final CellFormatter fmt = table.getCellFormatter();
final Iterator<PatchLine> iLine = lines.iterator();
while (iLine.hasNext()) {
final PatchLine l = iLine.next();
final String n = "DiffText-" + l.getType().name();
while (!fmt.getStyleName(row, PC).contains(n)) {
row++;
}
setRowItem(row++, l);
}
}
| protected void render(final PatchScript script) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
final SafeHtmlBuilder nc = new SafeHtmlBuilder();
final PrettyFormatter fmtA = PrettyFormatter.newFormatter(formatLanguage);
final PrettyFormatter fmtB = PrettyFormatter.newFormatter(formatLanguage);
fmtB.setShowWhiteSpaceErrors(true);
// Display the patch header
for (final String line : script.getPatchHeader()) {
appendFileHeader(nc, line);
}
if (script.getDisplayMethodA() == DisplayMethod.IMG
|| script.getDisplayMethodB() == DisplayMethod.IMG) {
final String rawBase = GWT.getHostPageBaseURL() + "cat/";
nc.openTr();
nc.setAttribute("valign", "center");
nc.setAttribute("align", "center");
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
if (script.getDisplayMethodA() == DisplayMethod.IMG) {
if (idSideA == null) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
} else {
Patch.Key k = new Patch.Key(idSideA, patchKey.get());
appendImgTag(nc, rawBase + KeyUtil.encode(k.toString()) + "^0");
}
}
if (script.getDisplayMethodB() == DisplayMethod.IMG) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^0");
}
nc.closeTd();
nc.closeTr();
}
final ArrayList<PatchLine> lines = new ArrayList<PatchLine>();
for (final EditList.Hunk hunk : script.getHunks()) {
appendHunkHeader(nc, hunk);
while (hunk.next()) {
if (hunk.isContextLine()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, CONTEXT, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incBoth();
lines.add(new PatchLine(CONTEXT, hunk.getCurA(), hunk.getCurB()));
} else if (hunk.isDeletedA()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
padLineNumber(nc);
appendLineText(nc, DELETE, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incA();
lines.add(new PatchLine(DELETE, hunk.getCurA(), 0));
if (a.size() == hunk.getCurA() && a.isMissingNewlineAtEnd())
appendNoLF(nc);
} else if (hunk.isInsertedB()) {
openLine(nc);
padLineNumber(nc);
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, INSERT, b, hunk.getCurB(), fmtA, fmtB);
closeLine(nc);
hunk.incB();
lines.add(new PatchLine(INSERT, 0, hunk.getCurB()));
if (b.size() == hunk.getCurB() && b.isMissingNewlineAtEnd())
appendNoLF(nc);
}
}
}
resetHtml(nc);
initScript(script);
int row = script.getPatchHeader().size();
final CellFormatter fmt = table.getCellFormatter();
final Iterator<PatchLine> iLine = lines.iterator();
while (iLine.hasNext()) {
final PatchLine l = iLine.next();
final String n = "DiffText-" + l.getType().name();
while (!fmt.getStyleName(row, PC).contains(n)) {
row++;
}
setRowItem(row++, l);
}
}
|
diff --git a/src/minecraft/biomesoplenty/fluids/BlockFluidSpringWater.java b/src/minecraft/biomesoplenty/fluids/BlockFluidSpringWater.java
index 100297338..3ea4dde27 100644
--- a/src/minecraft/biomesoplenty/fluids/BlockFluidSpringWater.java
+++ b/src/minecraft/biomesoplenty/fluids/BlockFluidSpringWater.java
@@ -1,101 +1,102 @@
package biomesoplenty.fluids;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import biomesoplenty.BiomesOPlenty;
import biomesoplenty.api.Fluids;
import biomesoplenty.configuration.BOPConfiguration;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockFluidSpringWater extends BlockFluidClassic
{
public static Icon springWaterStillIcon;
public static Icon springWaterFlowingIcon;
public BlockFluidSpringWater(int id, Fluid fluid, Material material)
{
super(id, fluid, material);
stack = new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME);
for (int i = 8; i < 11; i++)
{
displacementIds.put(i, false);
}
displacementIds.put(Fluids.liquidPoison.get().blockID, false);
}
@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
super.randomDisplayTick(par1World, par2, par3, par4, par5Random);
if (par5Random.nextInt(1) == 0)
{
BiomesOPlenty.proxy.spawnParticle("steam", par2 + par5Random.nextFloat(), par3 + 1.0F, par4 + par5Random.nextFloat());
}
}
@Override
public boolean canDisplace(IBlockAccess world, int x, int y, int z) {
int bId = world.getBlockId(x, y, z);
if (bId == 0)
return true;
if (bId == blockID)
return false;
if (displacementIds.containsKey(bId))
return displacementIds.get(bId);
Material material = Block.blocksList[bId].blockMaterial;
if (material.blocksMovement() || material == Material.water || material == Material.lava || material == Material.portal)
return false;
return true;
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity)
{
int meta = world.getBlockMetadata(x, y, z);
if (!world.isRemote && BOPConfiguration.Misc.hotSpringsRegeneration)
{
if (entity instanceof EntityLivingBase)
{
- ((EntityLivingBase)entity).addPotionEffect(new PotionEffect(Potion.regeneration.id, 20));
+ if (!((EntityLivingBase)entity).isPotionActive(Potion.regeneration.id))
+ ((EntityLivingBase)entity).addPotionEffect(new PotionEffect(Potion.regeneration.id, 50));
}
}
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister)
{
springWaterStillIcon = iconRegister.registerIcon("biomesoplenty:spring_water_still");
springWaterFlowingIcon = iconRegister.registerIcon("biomesoplenty:spring_water_flowing");
}
@Override
@SideOnly(Side.CLIENT)
public Icon getIcon(int par1, int par2)
{
return par1 != 0 && par1 != 1 ? springWaterFlowingIcon : springWaterStillIcon;
}
}
| true | false | null | null |
diff --git a/src/main/org/openscience/jchempaint/JCPMenuTextMaker.java b/src/main/org/openscience/jchempaint/JCPMenuTextMaker.java
index 1bfc371..84a8968 100644
--- a/src/main/org/openscience/jchempaint/JCPMenuTextMaker.java
+++ b/src/main/org/openscience/jchempaint/JCPMenuTextMaker.java
@@ -1,350 +1,350 @@
/*
* $RCSfile$
* $Author: egonw $
* $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $
* $Revision: 7634 $
*
* Copyright (C) 1997-2008 Stefan Kuhn
*
* Contact: [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openscience.jchempaint;
import java.util.HashMap;
import java.util.Map;
import org.openscience.jchempaint.applet.JChemPaintEditorApplet;
/**
* This class held text entries for menu items, tool tips etc., which are
* configured in the JCPGUI_*.properties files. They all need an entry
* in the entries map to be recognized by the localization system. The same
* is true about the DrawModeString for the status bar, which come from
* controller modules in cdk and are only in English there.
*
*/
public class JCPMenuTextMaker {
private static JCPMenuTextMaker instance=null;
private Map<String,String> entries=new HashMap<String,String>();
/**
* The constructor. Private since class is a singleton.
*/
private JCPMenuTextMaker(String guistring){
init(guistring);
}
public void init(String guistring){
entries.clear();
entries.put("file", GT._("File"));
entries.put("new", GT._("New"));
entries.put("atomMenuTitle", GT._("Atom Popup Menu"));
entries.put("pseudoMenuTitle", GT._("Pseudo Atom Popup Menu"));
entries.put("open", GT._("Open"));
entries.put("saveAs", GT._("Save As..."));
entries.put("view", GT._("View"));
entries.put("print", GT._("Print..."));
entries.put("export", GT._("Save As Image..."));
entries.put("save", GT._("Save"));
entries.put("edit", GT._("Edit"));
entries.put("report", GT._("Report"));
entries.put("close", GT._("Close"));
entries.put("exit", GT._("Exit"));
entries.put("undo", GT._("Undo"));
entries.put("redo", GT._("Redo"));
entries.put("selectAll", GT._("Select All"));
entries.put("copy", GT._("Copy"));
entries.put("copyAsSmiles", GT._("Copy As SMILES"));
entries.put("eraser", GT._("Delete"));
entries.put("paste", GT._("Paste"));
entries.put("pasteTemplate", GT._("All Templates"));
entries.put("cut", GT._("Cut"));
entries.put("atomMenu", GT._("Atom"));
entries.put("bondMenu", GT._("Bond"));
entries.put("tools", GT._("Tools"));
entries.put("templates", GT._("Templates"));
entries.put("radical", GT._("Radical"));
entries.put("bond", GT._("Single"));
entries.put("down_bond", GT._("Stereo Down"));
entries.put("up_bond", GT._("Stereo Up"));
entries.put("undefined_bond", GT._("Undefined Stereo"));
entries.put("undefined_stereo_bond", GT._("Undefined E/Z"));
entries.put("formalCharge", GT._("Charge"));
entries.put("plus", GT._("Plus"));
entries.put("minus", GT._("Minus"));
entries.put("hydrogen", GT._("Implicit Hydrogens"));
entries.put("flip", GT._("Flip"));
entries.put("cleanup", GT._("Clean Structure"));
entries.put("toolbar", GT._("Toolbar"));
entries.put("statusbar", GT._("Statusbar"));
entries.put("menubar", GT._("Menubar"));
entries.put("insertstructure", GT._("Direct Entry as SMILES/InChI/CAS"));
entries.put("zoomin", GT._("Zoom In"));
entries.put("zoomout", GT._("Zoom Out"));
entries.put("zoomoriginal", GT._("Zoom 100%"));
entries.put("options", GT._("Preferences..."));
entries.put("createSMILES", GT._("Create SMILES"));
entries.put("createInChI", GT._("Create InChI"));
entries.put("help", GT._("Help"));
entries.put("tutorial", GT._("Tutorial"));
entries.put("feedback", GT._("Report Feedback"));
entries.put("license", GT._("License"));
entries.put("about", GT._("About"));
entries.put("hydroon", GT._("On All"));
entries.put("hydrooff", GT._("Off"));
entries.put("flipHorizontal", GT._("Horizontal"));
entries.put("flipVertical", GT._("Vertical"));
entries.put("selectFromChemObject", GT._("Select"));
entries.put("symbolChange", GT._("Change Element"));
entries.put("periodictable", GT._("Periodic Table"));
entries.put("enterelement", GT._("Custom"));
entries.put("isotopeChange", GT._("Isotopes"));
entries.put("convertToRadical", GT._("Add Electron Pair"));
entries.put("convertFromRadical", GT._("Remove Electron Pair"));
entries.put("showChemObjectProperties", GT._("Properties"));
entries.put("showACProperties", GT._("Molecule Properties"));
entries.put("makeNormal", GT._("Convert to Regular Atom"));
entries.put("commonSymbols", GT._("Common Elements"));
entries.put("halogenSymbols", GT._("Halogens"));
entries.put("nobelSymbols", GT._("Nobel Gases"));
entries.put("alkaliMetals", GT._("Alkali Metals"));
entries.put("alkaliEarthMetals", GT._("Alkali Earth Metals"));
entries.put("transitionMetals", GT._("Transition Metals"));
entries.put("metals", GT._("Metals"));
entries.put("metalloids", GT._("Metalloids"));
entries.put("Transition m", GT._("Non-Metals"));
entries.put("pseudoSymbols", GT._("Pseudo Atoms"));
entries.put("majorPlusThree", GT._("Major Plus {0}","3"));
entries.put("majorPlusTwo", GT._("Major Plus {0}","2"));
entries.put("majorPlusOne", GT._("Major Plus {0}","1"));
entries.put("major", GT._("Major Isotope"));
entries.put("majorMinusOne", GT._("Major Minus {0}","1"));
entries.put("majorMinusTwo", GT._("Major Minus {0}","2"));
entries.put("majorMinusThree", GT._("Major Minus {0}","3"));
entries.put("valence", GT._("Valence"));
entries.put("valenceOff", GT._("Valence Off"));
entries.put("valence1", GT._("Valence {0}","1"));
entries.put("valence2", GT._("Valence {0}","2"));
entries.put("valence3", GT._("Valence {0}","3"));
entries.put("valence4", GT._("Valence {0}","4"));
entries.put("valence5", GT._("Valence {0}","5"));
entries.put("valence6", GT._("Valence {0}","6"));
entries.put("valence7", GT._("Valence {0}","7"));
entries.put("valence8", GT._("Valence {0}","8"));
entries.put("symbolC", GT._("C"));
entries.put("symbolO", GT._("O"));
entries.put("symbolN", GT._("N"));
entries.put("symbolH", GT._("H"));
entries.put("symbolP", GT._("P"));
entries.put("symbolS", GT._("S"));
entries.put("symbolF", GT._("F"));
entries.put("symbolCl", GT._("Cl"));
entries.put("symbolBr", GT._("Br"));
entries.put("symbolI", GT._("I"));
entries.put("symbolHe", GT._("He"));
entries.put("symbolNe", GT._("Ne"));
entries.put("symbolAr", GT._("Ar"));
entries.put("symbolB", GT._("B"));
entries.put("symbolP", GT._("P"));
entries.put("symbolLi", GT._("Li"));
entries.put("symbolBe", GT._("Be"));
entries.put("symbolNa", GT._("Na"));
entries.put("symbolMg", GT._("Mg"));
entries.put("symbolAl", GT._("Al"));
entries.put("symbolSi", GT._("Si"));
entries.put("symbolFe", GT._("Fe"));
entries.put("symbolCo", GT._("Co"));
entries.put("symbolAg", GT._("Ag"));
entries.put("symbolPt", GT._("Pt"));
entries.put("symbolAu", GT._("Au"));
entries.put("symbolHg", GT._("Hg"));
entries.put("symbolCu", GT._("Cu"));
entries.put("symbolNi", GT._("Ni"));
entries.put("symbolZn", GT._("Zn"));
entries.put("symbolSn", GT._("Sn"));
entries.put("symbolK", GT._("K"));
entries.put("symbolRb", GT._("Rb"));
entries.put("symbolCs", GT._("Cs"));
entries.put("symbolFr", GT._("Fr"));
entries.put("symbolCa", GT._("Ca"));
entries.put("symbolSr", GT._("Sr"));
entries.put("symbolBa", GT._("Ba"));
entries.put("symbolRa", GT._("Ra"));
entries.put("symbolSc", GT._("Sc"));
entries.put("symbolTi", GT._("Ti"));
entries.put("symbolV", GT._("V"));
entries.put("symbolCr", GT._("Cr"));
entries.put("symbolMn", GT._("Mn"));
entries.put("symbolY", GT._("Y"));
entries.put("symbolZr", GT._("Zr"));
entries.put("symbolNb", GT._("Nb"));
entries.put("symbolMo", GT._("Mo"));
entries.put("symbolTc", GT._("Tc"));
entries.put("symbolRu", GT._("Ru"));
entries.put("symbolRh", GT._("Rh"));
entries.put("symbolPd", GT._("Pd"));
entries.put("symbolCd", GT._("Cd"));
entries.put("symbolHf", GT._("Hf"));
entries.put("symbolTa", GT._("Ta"));
entries.put("symbolW", GT._("W"));
entries.put("symbolRe", GT._("Re"));
entries.put("symbolOs", GT._("Os"));
entries.put("symbolIr", GT._("Ir"));
entries.put("symbolRf", GT._("Rf"));
entries.put("symbolDb", GT._("Db"));
entries.put("symbolSg", GT._("Sg"));
entries.put("symbolBh", GT._("Bh"));
entries.put("symbolHs", GT._("Hs"));
entries.put("symbolMt", GT._("Mt"));
entries.put("symbolDs", GT._("Ds"));
entries.put("symbolRg", GT._("Rg"));
entries.put("symbolGa", GT._("Ga"));
entries.put("symbolIn", GT._("In"));
entries.put("symbolTl", GT._("Tl"));
entries.put("symbolPb", GT._("Pb"));
entries.put("symbolBi", GT._("Bi"));
entries.put("symbolGe", GT._("Ge"));
entries.put("symbolAs", GT._("As"));
entries.put("symbolSb", GT._("Sb"));
entries.put("symbolTe", GT._("Te"));
entries.put("symbolPo", GT._("Po"));
entries.put("pseudoStar", GT._("Variable Attachment Point *"));
entries.put("pseudoR", GT._("R"));
entries.put("pseudoRX", GT._("R.."));
entries.put("pseudoR1", GT._("R1"));
entries.put("pseudoR2", GT._("R2"));
entries.put("pseudoR3", GT._("R3"));
entries.put("pseudoR4", GT._("R4"));
entries.put("bondTooltip", GT._("Draw Bonds and Atoms"));
entries.put("cyclesymbolTooltip", GT._("Change the Atom's Symbol"));
entries.put("periodictableTooltip", GT._("Select new drawing symbol from periodic table"));
entries.put("enterelementTooltip", GT._("Enter an element symbol via keyboard"));
entries.put("up_bondTooltip", GT._("Make the Bonds Stereo Up"));
entries.put("down_bondTooltip", GT._("Make the Bonds Stereo Down"));
entries.put("plusTooltip", GT._("Increase the charge on an Atom"));
entries.put("minusTooltip", GT._("Decrease the charge on an Atom"));
entries.put("eraserTooltip", GT._("Delete atoms and bonds"));
entries.put("lassoTooltip", GT._("Select atoms and bonds in a free-form region"));
entries.put("selectTooltip", GT._("Select atoms and bonds in a rectangular region"));
entries.put("triangleTooltip", GT._("Add a propane ring"));
entries.put("squareTooltip", GT._("Add a butane ring"));
entries.put("pentagonTooltip", GT._("Add a pentane ring"));
entries.put("hexagonTooltip", GT._("Add a hexane ring"));
entries.put("heptagonTooltip", GT._("Add a heptane ring"));
entries.put("octagonTooltip", GT._("Add a octane ring"));
entries.put("benzeneTooltip", GT._("Add a benzene ring"));
entries.put("cleanupTooltip", GT._("Relayout the structures"));
if(guistring.equals(JChemPaintEditorApplet.GUI_APPLET))
entries.put("newTooltip", GT._("Clear"));
else
entries.put("newTooltip", GT._("Create new file"));
entries.put("openTooltip", GT._("Open existing file"));
entries.put("saveTooltip", GT._("Save current file"));
entries.put("printTooltip", GT._("Print current file")); entries.put("newTooltip", GT._("Create new file"));
entries.put("redoTooltip", GT._("Redo Action"));
entries.put("saveAsTooltip", GT._("Save to a file"));
entries.put("undoTooltip", GT._("Undo Action"));
entries.put("zoominTooltip", GT._("Zoom in"));
entries.put("zoomoutTooltip", GT._("Zoom out"));
entries.put("undefined_bondTooltip", GT._("Stereo up or stereo down bond"));
entries.put("undefined_stereo_bondTooltip", GT._("Any stereo bond"));
entries.put("rotateTooltip", GT._("Rotate selection"));
entries.put("cutTooltip", GT._("Cut selection"));
entries.put("copyTooltip", GT._("Copy selection to clipboard"));
entries.put("pasteTooltip", GT._("Paste from clipboard"));
entries.put("flipVerticalTooltip", GT._("Flip vertical"));
entries.put("flipHorizontalTooltip", GT._("Flip horizontal"));
entries.put("pasteTemplateTooltip", GT._("Choose from complex templates"));
entries.put("bondMenuTitle", GT._("Bond Popup Menu"));
entries.put("chemmodelMenuTitle", GT._("ChemModel Popup Menu"));
entries.put("Enter Element or Group", GT._("Enter Element or Group"));
entries.put("Add Atom Or Change Element", GT._("Add Atom Or Change Element"));
entries.put("Draw Bond", GT._("Draw Bond"));
entries.put("Ring 3", GT._("Ring {0}","3"));
entries.put("Ring 4", GT._("Ring {0}","4"));
entries.put("Ring 5", GT._("Ring {0}","5"));
entries.put("Ring 6", GT._("Ring {0}","6"));
entries.put("Ring 7", GT._("Ring {0}","7"));
entries.put("Ring 8", GT._("Ring {0}","8"));
entries.put("Add or convert to bond up", GT._("Add or convert to bond up"));
entries.put("Add or convert to bond down", GT._("Add or convert to bond down"));
entries.put("Decrease Charge", GT._("Decrease Charge"));
entries.put("Increase Charge", GT._("Increase Charge"));
entries.put("Cycle Symbol", GT._("Cyclic change of symbol"));
entries.put("Delete", GT._("Delete"));
entries.put("Benzene", GT._("Benzene"));
entries.put("Select in Free Form", GT._("Select in Free Form"));
entries.put("Select Square", GT._("Select Rectangle"));
- entries.put("CTooltip", GT._("Change drawing symbol to C"));
- entries.put("HTooltip", GT._("Change drawing symbol to H"));
- entries.put("OTooltip", GT._("Change drawing symbol to O"));
- entries.put("NTooltip", GT._("Change drawing symbol to N"));
- entries.put("PTooltip", GT._("Change drawing symbol to P"));
- entries.put("STooltip", GT._("Change drawing symbol to S"));
- entries.put("FTooltip", GT._("Change drawing symbol to F"));
- entries.put("ClTooltip", GT._("Change drawing symbol to Cl"));
- entries.put("BrTooltip", GT._("Change drawing symbol to Br"));
- entries.put("ITooltip", GT._("Change drawing symbol to I"));
+ entries.put("CTooltip", GT._("Change drawing symbol to {0}", GT._("C")));
+ entries.put("HTooltip", GT._("Change drawing symbol to {0}", GT._("H")));
+ entries.put("OTooltip", GT._("Change drawing symbol to {0}", GT._("O")));
+ entries.put("NTooltip", GT._("Change drawing symbol to {0}", GT._("N")));
+ entries.put("PTooltip", GT._("Change drawing symbol to {0}", GT._("P")));
+ entries.put("STooltip", GT._("Change drawing symbol to {0}", GT._("S")));
+ entries.put("FTooltip", GT._("Change drawing symbol to {0}", GT._("F")));
+ entries.put("ClTooltip", GT._("Change drawing symbol to {0}", GT._("Cl")));
+ entries.put("BrTooltip", GT._("Change drawing symbol to {0}", GT._("Br")));
+ entries.put("ITooltip", GT._("Change drawing symbol to {0}", GT._("I")));
entries.put("reaction", GT._("Reaction"));
entries.put("addReactantToNewReaction", GT._("Make Reactant in New Reaction"));
entries.put("addReactantToExistingReaction", GT._("Make Reactant in Existing Reaction"));
entries.put("addProductToNewReaction", GT._("Make Product in New Reaction"));
entries.put("addProductToExistingReaction", GT._("Make Product in Existing Reaction"));
entries.put("selectReactants", GT._("Select Reactants"));
entries.put("selectProducts", GT._("Select Products"));
entries.put("reactionMenuTitle", GT._("Reaction Popup Menu"));
entries.put("alkaloids", GT._("Alkaloids"));
entries.put("beta_lactams", GT._("Beta Lactams"));
entries.put("carbohydrates", GT._("Carbohydrates"));
entries.put("inositols", GT._("Inositols"));
entries.put("lipids", GT._("Lipids"));
entries.put("miscellaneous", GT._("Miscellaneous"));
entries.put("nucleosides", GT._("Nucleosides"));
entries.put("porphyrins", GT._("Porphyrins"));
entries.put("steroids", GT._("Steroids"));
entries.put("language", GT._("Language"));
}
/**
* Gives the text for an item.
*
* @param key The key for the text
* @return The text in current language
*/
public String getText(String key){
if(entries.get(key)==null)
return key;
else
return entries.get(key);
}
/**
* Gives an instance of JCPMenuTextMaker.
*
* @return The instance
*/
public static JCPMenuTextMaker getInstance(String guistring){
if(instance==null){
instance=new JCPMenuTextMaker(guistring);
}
return instance;
}
}
diff --git a/src/main/org/openscience/jchempaint/dialog/PeriodicTablePanel.java b/src/main/org/openscience/jchempaint/dialog/PeriodicTablePanel.java
index c2306cc..5f4198a 100755
--- a/src/main/org/openscience/jchempaint/dialog/PeriodicTablePanel.java
+++ b/src/main/org/openscience/jchempaint/dialog/PeriodicTablePanel.java
@@ -1,1080 +1,1080 @@
/*
* $RCSfile$
* $Author: egonw $
* $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $
* $Revision: 7634 $
*
* Copyright (C) 1997-2008 Egone Willighagen, Miguel Rojas, Geert Josten
*
* Contact: [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openscience.jchempaint.dialog;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import org.openscience.cdk.Element;
import org.openscience.cdk.PeriodicTableElement;
import org.openscience.cdk.config.ElementPTFactory;
import org.openscience.cdk.event.ICDKChangeListener;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.tools.ILoggingTool;
import org.openscience.cdk.tools.LoggingToolFactory;
import org.openscience.jchempaint.GT;
/**
* JPanel version of the periodic system.
*
* @author Egon Willighagen
* @author Geert Josten
* @author Miguel Rojas
* @author Konstantin Tokarev
*/
public class PeriodicTablePanel extends JPanel
{
private static final long serialVersionUID = -2539418347261469740L;
Vector listeners = null;
PeriodicTableElement selectedElement = null;
private JPanel panel;
//private JLabel label;
private JLayeredPane layeredPane;
private ElementPTFactory factory;
private static ILoggingTool logger =
LoggingToolFactory.createLoggingTool(PeriodicTableDialog.class);
private Map<JButton,Color> buttoncolors = new HashMap<JButton,Color>();
public static int APPLICATION = 0;
/*default*/
public static int JCP = 1;
/*
* set if the button should be written with html - which takes
* too long time for loading
* APPLICATION = with html
* JCP = default
*/
/**
* Constructor of the PeriodicTablePanel object
*/
public PeriodicTablePanel()
{
super();
setLayout( new BorderLayout());
try {
factory = ElementPTFactory.getInstance();
} catch (Exception ex1)
{
logger.error(ex1.getMessage());
logger.debug(ex1);
}
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(581, 435));
JPanel tp = PTPanel();
tp.setBounds(8,85,570, 340);
panel = CreateLabelProperties(null);
layeredPane.add(tp, new Integer(0));
layeredPane.add(panel, new Integer(1));
add(layeredPane);
}
private JPanel PTPanel()
{
JPanel panel = new JPanel();
listeners = new Vector();
panel.setLayout(new GridLayout(0, 19));
//--------------------------------
Box.createHorizontalGlue();
panel.add(Box.createHorizontalGlue());
JButton butt = new JButton("1");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
//--------------------------------
for (int i = 0; i < 16; i++)
{
Box.createHorizontalGlue();
panel.add(Box.createHorizontalGlue());
}
butt = new JButton("18");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("1");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("H")));
butt = new JButton("2");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
for (int i = 0; i < 10; i++)
{
panel.add(Box.createHorizontalGlue());
}
butt = new JButton("13");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("14");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("15");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("16");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("17");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
//
panel.add(createButton(GT._("He")));
butt = new JButton("2");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("Li")));
panel.add(createButton(GT._("Be")));
for (int i = 0; i < 10; i++)
{
panel.add(Box.createHorizontalGlue());
}
//no metall
panel.add(createButton(GT._("B")));
panel.add(createButton(GT._("C")));
panel.add(createButton(GT._("N")));
panel.add(createButton(GT._("O")));
panel.add(createButton(GT._("F")));
//
panel.add(createButton(GT._("Ne")));
butt = new JButton("3");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("Na")));
panel.add(createButton(GT._("Mg")));
butt = new JButton("3");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("4");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("5");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("6");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("7");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("8");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("9");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("10");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("11");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
butt = new JButton("12");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
//no metall
panel.add(createButton(GT._("Al")));
panel.add(createButton(GT._("Si")));
panel.add(createButton(GT._("P")));
panel.add(createButton(GT._("S")));
panel.add(createButton(GT._("Cl")));
//
panel.add(createButton(GT._("Ar")));
butt = new JButton("4");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("K")));
panel.add(createButton(GT._("Ca")));
//transition
panel.add(createButton(GT._("Sc")));
panel.add(createButton(GT._("Ti")));
panel.add(createButton(GT._("V")));
panel.add(createButton(GT._("Cr")));
panel.add(createButton(GT._("Mn")));
panel.add(createButton(GT._("Fe")));
panel.add(createButton(GT._("Co")));
panel.add(createButton(GT._("Ni")));
panel.add(createButton(GT._("Cu")));
panel.add(createButton(GT._("Zn")));
//no metall
panel.add(createButton(GT._("Ga")));
panel.add(createButton(GT._("Ge")));
panel.add(createButton(GT._("As")));
panel.add(createButton(GT._("Se")));
panel.add(createButton(GT._("Br")));
//
panel.add(createButton(GT._("Kr")));
butt = new JButton("5");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("Rb")));
panel.add(createButton(GT._("Sr")));
//transition
panel.add(createButton(GT._("Y")));
panel.add(createButton(GT._("Zr")));
panel.add(createButton(GT._("Nb")));
panel.add(createButton(GT._("Mo")));
panel.add(createButton(GT._("Tc")));
panel.add(createButton(GT._("Ru")));
panel.add( createButton(GT._("Rh")));
panel.add(createButton(GT._("Pd")));
panel.add(createButton(GT._("Ag")));
panel.add(createButton(GT._("Cd")));
//no metall
panel.add(createButton(GT._("In")));
panel.add(createButton(GT._("Sn")));
panel.add(createButton(GT._("Sb")));
panel.add(createButton(GT._("Te")));
panel.add(createButton(GT._("I")));
//
panel.add(createButton(GT._("Xe")));
butt = new JButton("6");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("Cs")));
panel.add(createButton(GT._("Ba")));
//transition
panel.add(createButton(GT._("La")));
panel.add(createButton(GT._("Hf")));
panel.add(createButton(GT._("Ta")));
panel.add(createButton(GT._("W")));
panel.add(createButton(GT._("Re")));
panel.add(createButton(GT._("Os")));
panel.add(createButton(GT._("Ir")));
panel.add(createButton(GT._("Pt")));
panel.add(createButton(GT._("Au")));
panel.add(createButton(GT._("Hg")));
//no metall
panel.add(createButton(GT._("Tl")));
panel.add(createButton(GT._("Pb")));
panel.add(createButton(GT._("Bi")));
panel.add(createButton(GT._("Po")));
panel.add(createButton(GT._("At")));
//
panel.add(createButton(GT._("Rn")));
butt = new JButton("7");
butt.setBorder(new EmptyBorder(2,2,2,2));
panel.add(butt);
panel.add(createButton(GT._("Fr")));
panel.add(createButton(GT._("Ra")));
//transition
panel.add(createButton(GT._("Ac")));
panel.add(createButton(GT._("Rf")));
panel.add(createButton(GT._("Db")));
panel.add(createButton(GT._("Sg")));
panel.add(createButton(GT._("Bh")));
panel.add(createButton(GT._("Hs")));
panel.add(createButton(GT._("Mt")));
panel.add(createButton(GT._("Ds")));
panel.add(createButton(GT._("Rg")));
for (int i = 0; i < 10; i++)
{
panel.add(Box.createHorizontalGlue());
}
//Acti
panel.add(createButton(GT._("Ce")));
panel.add(createButton(GT._("Pr")));
panel.add(createButton(GT._("Nd")));
panel.add(createButton(GT._("Pm")));
panel.add(createButton(GT._("Sm")));
panel.add(createButton(GT._("Eu")));
panel.add(createButton(GT._("Gd")));
panel.add(createButton(GT._("Tb")));
panel.add(createButton(GT._("Dy")));
panel.add(createButton(GT._("Ho")));
panel.add(createButton(GT._("Er")));
panel.add(createButton(GT._("Tm")));
panel.add(createButton(GT._("Yb")));
panel.add(createButton(GT._("Lu")));
for (int i = 0; i < 5; i++)
{
panel.add(Box.createHorizontalGlue());
}
//Lacti
panel.add( createButton(GT._("Th")));
panel.add(createButton(GT._("Pa")));
panel.add(createButton(GT._("U")));
panel.add(createButton(GT._("Np")));
panel.add(createButton(GT._("Pu")));
panel.add(createButton(GT._("Am")));
panel.add(createButton(GT._("Cm")));
panel.add(createButton(GT._("Bk")));
panel.add(createButton(GT._("Cf")));
panel.add(createButton(GT._("Es")));
panel.add(createButton(GT._("Fm")));
panel.add(createButton(GT._("Md")));
panel.add(createButton(GT._("No")));
panel.add(createButton(GT._("Lr")));
//End
panel.setVisible(true);
return panel;
}
/**
* create button. Difine the color of the font and background
*
*@param elementS String of the element
*@return button JButton
*/
private JButton createButton(String elementS)
{
PeriodicTableElement element;
try {
element = factory.configure(new PeriodicTableElement(elementS));
} catch (CDKException e) {
throw new RuntimeException (e);
}
String colorFS = "000000";
Color colorF = new Color(0,0,0);
Color colorB = null;
String serie = element.getChemicalSerie();
if(serie.equals("Noble Gasses"))
colorB = new Color(255,153,255);
else if(serie.equals("Halogens"))
colorB = new Color(255,153,153);
else if(serie.equals("Nonmetals"))
colorB = new Color(255,152,90);
else if(serie.equals("Metalloids"))
colorB = new Color(255,80,80);
else if(serie.equals("Metals"))
colorB = new Color(255,50,0);
else if(serie.equals("Alkali Earth Metals"))
colorB = new Color(102,150,255);
else if(serie.equals("Alkali Metals"))
colorB = new Color(130,130,255);
else if(serie.equals("Transition metals"))
colorB = new Color(255,255,110);
else if(serie.equals("Lanthanides"))
colorB = new Color(255,255,150);
else if(serie.equals("Actinides"))
colorB = new Color(255,255,200);
JButton button = new ElementButton(element, new ElementMouseAction(), getTextButton(element,colorFS), colorF);
button.setBackground(colorB);
button.setName(elementS);
buttoncolors.put(button,colorB);
return button;
}
/**
* Sets the selectedElement attribute of the PeriodicTablePanel object
*
*@param selectedElement The new selectedElement value
*/
public void setSelectedElement(PeriodicTableElement selectedElement)
{
this.selectedElement = selectedElement;
}
/**
* Gets the selectedElement attribute of the PeriodicTablePanel object
*
*@return The selectedElement value
*/
public Element getSelectedElement() throws IOException, CDKException {
ElementPTFactory eptf = ElementPTFactory.getInstance();
return eptf.configure(selectedElement);
//or ? -> factory.configure(new PeriodicTableElement(selectedElement.getSymbol()));
//return PeriodicTableElement.configure(selectedElement);
}
/**
* Adds a change listener to the list of listeners
*
*@param listener The listener added to the list
*/
public void addCDKChangeListener(ICDKChangeListener listener)
{
listeners.add(listener);
}
/**
* Removes a change listener from the list of listeners
*
*@param listener The listener removed from the list
*/
public void removeCDKChangeListener(ICDKChangeListener listener)
{
listeners.remove(listener);
}
/**
* Notifies registered listeners of certain changes that have occurred in this
* model.
*/
public void fireChange()
{
EventObject event = new EventObject(this);
for (int i = 0; i < listeners.size(); i++)
{
((ICDKChangeListener) listeners.get(i)).stateChanged(event);
}
}
/**
* get the format which the text will be introduce into the button
*
* @param element The PeriodicTableElement
* @return the String to show
*/
public String getTextButton(PeriodicTableElement element, String color){
return element.getSymbol();
}
/**
* get translated name of element
*
* @author Geoffrey R. Hutchison
* @param atomic number of element
* @return the name element to show
*/
private String elementTranslator(int element) {
String result;
switch(element) {
case 1:
result = GT._("Hydrogen");
break;
case 2:
result = GT._("Helium");
break;
case 3:
result = GT._("Lithium");
break;
case 4:
result = GT._("Beryllium");
break;
case 5:
result = GT._("Boron");
break;
case 6:
result = GT._("Carbon");
break;
case 7:
result = GT._("Nitrogen");
break;
case 8:
result = GT._("Oxygen");
break;
case 9:
result = GT._("Fluorine");
break;
case 10:
result = GT._("Neon");
break;
case 11:
result = GT._("Sodium");
break;
case 12:
result = GT._("Magnesium");
break;
case 13:
result = GT._("Aluminum");
break;
case 14:
result = GT._("Silicon");
break;
case 15:
result = GT._("Phosphorus");
break;
case 16:
result = GT._("Sulfur");
break;
case 17:
result = GT._("Chlorine");
break;
case 18:
result = GT._("Argon");
break;
case 19:
result = GT._("Potassium");
break;
case 20:
result = GT._("Calcium");
break;
case 21:
result = GT._("Scandium");
break;
case 22:
result = GT._("Titanium");
break;
case 23:
result = GT._("Vanadium");
break;
case 24:
result = GT._("Chromium");
break;
case 25:
result = GT._("Manganese");
break;
case 26:
result = GT._("Iron");
break;
case 27:
result = GT._("Cobalt");
break;
case 28:
result = GT._("Nickel");
break;
case 29:
result = GT._("Copper");
break;
case 30:
result = GT._("Zinc");
break;
case 31:
result = GT._("Gallium");
break;
case 32:
result = GT._("Germanium");
break;
case 33:
result = GT._("Arsenic");
break;
case 34:
result = GT._("Selenium");
break;
case 35:
result = GT._("Bromine");
break;
case 36:
result = GT._("Krypton");
break;
case 37:
result = GT._("Rubidium");
break;
case 38:
result = GT._("Strontium");
break;
case 39:
result = GT._("Yttrium");
break;
case 40:
result = GT._("Zirconium");
break;
case 41:
result = GT._("Niobium");
break;
case 42:
result = GT._("Molybdenum");
break;
case 43:
result = GT._("Technetium");
break;
case 44:
result = GT._("Ruthenium");
break;
case 45:
result = GT._("Rhodium");
break;
case 46:
result = GT._("Palladium");
break;
case 47:
result = GT._("Silver");
break;
case 48:
result = GT._("Cadmium");
break;
case 49:
result = GT._("Indium");
break;
case 50:
result = GT._("Tin");
break;
case 51:
result = GT._("Antimony");
break;
case 52:
result = GT._("Tellurium");
break;
case 53:
result = GT._("Iodine");
break;
case 54:
result = GT._("Xenon");
break;
case 55:
result = GT._("Cesium");
break;
case 56:
result = GT._("Barium");
break;
case 57:
result = GT._("Lanthanum");
break;
case 58:
result = GT._("Cerium");
break;
case 59:
result = GT._("Praseodymium");
break;
case 60:
result = GT._("Neodymium");
break;
case 61:
result = GT._("Promethium");
break;
case 62:
result = GT._("Samarium");
break;
case 63:
result = GT._("Europium");
break;
case 64:
result = GT._("Gadolinium");
break;
case 65:
result = GT._("Terbium");
break;
case 66:
result = GT._("Dysprosium");
break;
case 67:
result = GT._("Holmium");
break;
case 68:
result = GT._("Erbium");
break;
case 69:
result = GT._("Thulium");
break;
case 70:
result = GT._("Ytterbium");
break;
case 71:
result = GT._("Lutetium");
break;
case 72:
result = GT._("Hafnium");
break;
case 73:
result = GT._("Tantalum");
break;
case 74:
result = GT._("Tungsten");
break;
case 75:
result = GT._("Rhenium");
break;
case 76:
result = GT._("Osmium");
break;
case 77:
result = GT._("Iridium");
break;
case 78:
result = GT._("Platinum");
break;
case 79:
result = GT._("Gold");
break;
case 80:
result = GT._("Mercury");
break;
case 81:
result = GT._("Thallium");
break;
case 82:
result = GT._("Lead");
break;
case 83:
result = GT._("Bismuth");
break;
case 84:
result = GT._("Polonium");
break;
case 85:
result = GT._("Astatine");
break;
case 86:
result = GT._("Radon");
break;
case 87:
result = GT._("Francium");
break;
case 88:
result = GT._("Radium");
break;
case 89:
result = GT._("Actinium");
break;
case 90:
result = GT._("Thorium");
break;
case 91:
result = GT._("Protactinium");
break;
case 92:
result = GT._("Uranium");
break;
case 93:
result = GT._("Neptunium");
break;
case 94:
result = GT._("Plutonium");
break;
case 95:
result = GT._("Americium");
break;
case 96:
result = GT._("Curium");
break;
case 97:
result = GT._("Berkelium");
break;
case 98:
result = GT._("Californium");
break;
case 99:
result = GT._("Einsteinium");
break;
case 100:
result = GT._("Fermium");
break;
case 101:
result = GT._("Mendelevium");
break;
case 102:
result = GT._("Nobelium");
break;
case 103:
result = GT._("Lawrencium");
break;
case 104:
result = GT._("Rutherfordium");
break;
case 105:
result = GT._("Dubnium");
break;
case 106:
result = GT._("Seaborgium");
break;
case 107:
result = GT._("Bohrium");
break;
case 108:
result = GT._("Hassium");
break;
case 109:
result = GT._("Meitnerium");
break;
case 110:
result = GT._("Darmstadtium");
break;
case 111:
result = GT._("Roentgenium");
break;
case 112:
result = GT._("Ununbium");
break;
case 113:
result = GT._("Ununtrium");
break;
case 114:
result = GT._("Ununquadium");
break;
case 115:
result = GT._("Ununpentium");
break;
case 116:
result = GT._("Ununhexium");
break;
case 117:
result = GT._("Ununseptium");
break;
case 118:
result = GT._("Ununoctium");
break;
default:
result = GT._("Unknown");
}
return result;
}
/**
* get translated name of element
*
* @author Konstantin Tokarev
* @param chemical serie to translate
* @return the String to show
*/
public String serieTranslator(String serie) {
if(serie.equals("Noble Gasses"))
return GT._("Noble Gases");
else if(serie.equals("Halogens"))
return GT._("Halogens");
else if(serie.equals("Nonmetals"))
return GT._("Nonmetals");
else if(serie.equals("Metalloids"))
return GT._("Metalloids");
else if(serie.equals("Metals"))
return GT._("Metals");
else if(serie.equals("Alkali Earth Metals"))
return GT._("Alkali Earth Metals");
else if(serie.equals("Alkali Metals"))
return GT._("Alkali Metals");
else if(serie.equals("Transition metals"))
return GT._("Transition metals");
else if(serie.equals("Lanthanides"))
return GT._("Lanthanides");
else if(serie.equals("Actinides"))
return GT._("Actinides");
else
return GT._("Unknown");
}
/**
* get translated name of phase
*
* @author Konstantin Tokarev
* @param phase name to translate
* @return the String to show
*/
public String phaseTranslator(String serie) {
if(serie.equals("Gas"))
return GT._("Gas");
else if(serie.equals("Liquid"))
return GT._("Liquid");
else if(serie.equals("Solid"))
return GT._("Solid");
else
return GT._("Unknown");
}
/**
* Description of the Class
*
*@author steinbeck
*@cdk.created February 10, 2004
*/
public class ElementMouseAction implements MouseListener
{
private static final long serialVersionUID = 6176240749900870566L;
public void mouseClicked(MouseEvent e) {
fireChange();
}
public void mouseEntered(MouseEvent e) {
ElementButton button = (ElementButton) e.getSource();
setSelectedElement(button.getElement());
layeredPane.remove(panel);
panel = CreateLabelProperties(button.getElement());
layeredPane.add(panel, new Integer(1));
layeredPane.repaint();
button.setBackground(Color.LIGHT_GRAY);
}
public void mouseExited(MouseEvent e) {
((ElementButton)e.getSource()).setBackground(buttoncolors.get(e.getSource()));
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
/**
* This action fragment a molecule which is on the frame JChemPaint
*
*/
class BackAction extends AbstractAction
{
private static final long serialVersionUID = -8708581865777449553L;
public void actionPerformed(ActionEvent e)
{
layeredPane.remove(panel);
panel = CreateLabelProperties(null);
layeredPane.add(panel, new Integer(1));
layeredPane.repaint();
}
}
class ElementButton extends JButton
{
private static final long serialVersionUID = 1504183423628680664L;
private PeriodicTableElement element;
/**
* Constructor for the ElementButton object
*
*@param element Description of the Parameter
*/
public ElementButton(PeriodicTableElement element)
{
super("H");
try {
this.element = factory.configure(element);
} catch (CDKException e) {
throw new RuntimeException(e);
}
}
/**
* Constructor for the ElementButton object
*
* @param element Description of the Parameter
* @param e Description of the Parameter
* @param color Description of the Parameter
* @param controlViewer Description of the Parameter
*/
public ElementButton(
PeriodicTableElement element, MouseListener e,String buttonString, Color color)
{
super(buttonString);
setForeground(color);
this.element = element;
setFont(new Font("Times-Roman",Font.BOLD, 15));
setBorder( new BevelBorder(BevelBorder.RAISED) );
setToolTipText(elementTranslator(element.getAtomicNumber()));
addMouseListener(e);
}
/**
* Gets the element attribute of the ElementButton object
*
*@return The element value
*/
public PeriodicTableElement getElement()
{
return this.element;
}
}
/**
* create the Label
*
*@param element PeriodicTableElement
*@return pan JPanel
*/
private JPanel CreateLabelProperties(PeriodicTableElement element)
{
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout());
Color color = new Color(255,255,255);
Point origin = new Point(120, 20);
JLabel label;
if(element != null){
label = new JLabel("<html><FONT SIZE=+2>"
+elementTranslator(element.getAtomicNumber())+" ("+element.getSymbol()+")</FONT><br> "
+GT._("Atomic number")+" "+element.getAtomicNumber()
+ (element.getGroup()!=null ?
", "+GT._("Group")+" "+element.getGroup() : "")
+", "+GT._("Period")+" "+element.getPeriod()+"</html>");
label.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
pan.add(label,BorderLayout.NORTH);
label = new JLabel("<html><FONT> "
+GT._("CAS RN:")+" "+element.getCASid()+"<br> "
+GT._("Element Category:")+" "+serieTranslator(element.getChemicalSerie())+"<br> "
+GT._("State:")+" "+phaseTranslator(element.getPhase())+"<br> "
- +GT._("Electronativity:")+" "+(element.getPaulingEneg()==null ? GT._("undefined") : element.getPaulingEneg())+"<br>"
+ +GT._("Electronegativity:")+" "+(element.getPaulingEneg()==null ? GT._("undefined") : element.getPaulingEneg())+"<br>"
+"</FONT></html>");
label.setMinimumSize(new Dimension(165,150));
label.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
pan.add(label,BorderLayout.CENTER);
}
else
{
label = new JLabel(" "+GT._("Periodic Table of elements"));
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color);
pan.add(label,BorderLayout.CENTER);
}
pan.setBackground(color);
pan.setForeground(Color.black);
pan.setBorder(BorderFactory.createLineBorder(Color.black));
pan.setBounds(origin.x, origin.y, 255, 160);
return pan;
}
}
| false | false | null | null |
diff --git a/app/src/org/orange/familylink/fragment/LogFragment.java b/app/src/org/orange/familylink/fragment/LogFragment.java
index fd41df0..0ea8a19 100644
--- a/app/src/org/orange/familylink/fragment/LogFragment.java
+++ b/app/src/org/orange/familylink/fragment/LogFragment.java
@@ -1,1240 +1,1223 @@
/**
*
*/
package org.orange.familylink.fragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
-import org.holoeverywhere.FontLoader;
import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.ListFragment;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.preference.SharedPreferences.Editor;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.AdapterView.OnItemSelectedListener;
import org.holoeverywhere.widget.ArrayAdapter;
import org.holoeverywhere.widget.CheckedTextView;
import org.holoeverywhere.widget.LinearLayout;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.ListView.MultiChoiceModeListener;
import org.holoeverywhere.widget.Spinner;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;
import org.orange.familylink.R;
import org.orange.familylink.data.Message;
import org.orange.familylink.data.Message.Code;
import org.orange.familylink.data.MessageLogRecord.Direction;
import org.orange.familylink.data.MessageLogRecord.Status;
import org.orange.familylink.data.Settings;
import org.orange.familylink.database.Contract;
import org.orange.familylink.fragment.LogFragment.MessagesSender.MessageWrapper;
import org.orange.familylink.sms.SmsMessage;
import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.format.DateFormat;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SpinnerAdapter;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
/**
* 日志{@link ListFragment}
* @author Team Orange
*/
public class LogFragment extends ListFragment {
/** 参数Key:需要选中的消息IDs */
public static final String ARGUMENT_KEY_IDS =
LogFragment.class.getName() + ".argument.IDS";
/** 参数Key:需要设置的 <em>消息状态</em> 筛选条件,用R.string.*设置 */
public static final String ARGUMENT_KEY_STATUS =
LogFragment.class.getName() + ".argument.STATUS";
/** 参数Key:需要设置的 <em>消息代码</em> 筛选条件 ,用R.string.*设置*/
public static final String ARGUMENT_KEY_CODE =
LogFragment.class.getName() + ".argument.CODE";
/** 参数Key:需要设置的 <em>对方联系人ID</em> 筛选条件 ,用R.string.*设置*/
public static final String ARGUMENT_KEY_CONTACT_ID =
LogFragment.class.getName() + ".argument.CONTACT_ID";
private static final String PREF_NAME = "log_fragment";
private static final String PREF_KEY_STATUS = "status";
private static final String PREF_KEY_CODE = "code";
private static final String PREF_KEY_CONTACT_ID = "contact_id";
private static final String STATE_CHECKED_ITEM_IDS =
LogFragment.class.getName() + ".state.CHECKED_ITEM_IDS";
private static final int LOADER_ID_CONTACTS = 1;
private static final int LOADER_ID_LOG = 2;
/** 当前启动的{@link ActionMode};如果没有启动,则为null */
private ActionMode mActionMode;
/** 最近选中的消息的IDs,用于恢复之前的选中状态。仅在{@link #mActionMode} != null时有效 */
private long[] mCheckedItemids;
/** 用于把联系人ID映射为联系人名称的{@link Map} */
private Map<Long, String> mContactIdToNameMap;
/** 用于显示联系人筛选条件的{@link Spinner}的{@link SpinnerAdapter} */
private MySimpleCursorAdapterWithHeader mAdapterForContactsSpinner;
/** 用于显示消息日志的{@link ListView}的{@link ListAdapter} */
private CursorAdapter mAdapterForLogList;
private Spinner mSpinnerForStatus;
private Spinner mSpinnerForCode;
private Spinner mSpinnerForContact;
private String[] mSelectionForStatus;
private String[] mSelectionForCode;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 因为super.onCreateView没有使用android.R.layout.list_content布局文件,
// 我们也无法按此方法的文档说明来include list_content,
// 只能在这用代码继承布局,以保留其内建indeterminant progress state
// 创建自定义布局,把原来的root作为新布局的子元素
View originalRoot = super.onCreateView(inflater, container, savedInstanceState);
LinearLayout root = new LinearLayout(getActivity());
root.setOrientation(LinearLayout.VERTICAL);
// ------------------------------------------------------------------
// 添加 原来的root
root.addView(originalRoot, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
1));
// ------------------------------------------------------------------
// 添加 筛选条件输入部件
root.addView(createFilterWidget(), new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
0));
// ------------------------------------------------------------------
return root;
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@SuppressLint("NewApi")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 尝试恢复选中状态
if(savedInstanceState != null) {
long[] ids = savedInstanceState.getLongArray(STATE_CHECKED_ITEM_IDS);
if(ids != null)
mCheckedItemids = ids;
}
int codePosition, statusPosition;
// 恢复上次的筛选选项
SharedPreferences pref = getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE);
statusPosition = pref.getInt(PREF_KEY_STATUS, 0);
codePosition = pref.getInt(PREF_KEY_CODE, 0);
// 处理Fragment的参数
Bundle arguments = getArguments();
if(arguments != null) {
long[] argumentIds = arguments.getLongArray(ARGUMENT_KEY_IDS);
if(argumentIds != null) {
mCheckedItemids = argumentIds;
codePosition = statusPosition = 0; //禁止筛选,设为“全部”
}
if(arguments.containsKey(ARGUMENT_KEY_STATUS)) {
int status = arguments.getInt(ARGUMENT_KEY_STATUS);
Integer position = getStatusSpinnerPosition(status);
if(position != null)
statusPosition = position;
}
if(arguments.containsKey(ARGUMENT_KEY_CODE)) {
int code = arguments.getInt(ARGUMENT_KEY_CODE);
Integer position = getCodeSpinnerPosition(code);
if(position != null)
codePosition = position;
}
}
mSpinnerForStatus.setSelection(statusPosition);
mSpinnerForCode.setSelection(codePosition);
// Give some text to display if there is no data.
setEmptyText(getResources().getText(R.string.no_message_record));
// 设置ListView
ListView listView = getListView();
// 设置ListView为多选模式
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(mMultiChoiceModeListener);
// 设置ListView的FastScrollBar
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(false);
listView.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT);
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapterForLogList = new LogAdapter(getActivity(), null, 0);
setListAdapter(mAdapterForLogList);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(LOADER_ID_CONTACTS, null, mLoaderCallbacksForContacts);
loaderManager.initLoader(LOADER_ID_LOG, null, mLoaderCallbacksForLogList);
}
@SuppressLint("NewApi")
@Override
public void onStop() {
super.onStop();
// 保存筛选条件的当前选择
Editor editor = getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE).edit();
editor.putInt(PREF_KEY_STATUS, mSpinnerForStatus.getSelectedItemPosition());
editor.putInt(PREF_KEY_CODE, mSpinnerForCode.getSelectedItemPosition());
editor.putLong(PREF_KEY_CONTACT_ID, mSpinnerForContact.getSelectedItemId());
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
editor.apply();
else
editor.commit();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mActionMode != null)
outState.putLongArray(STATE_CHECKED_ITEM_IDS, getListView().getCheckedItemIds());
else
outState.putLongArray(STATE_CHECKED_ITEM_IDS, null);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(mActionMode == null)
l.setItemChecked(position, true); //触发ActionModes
}
/**
* 创建筛选条件输入部件
* @return 新创建的筛选条件输入部件
*/
protected View createFilterWidget() {
LinearLayout spinnersContainer = new LinearLayout(getActivity());
spinnersContainer.setOrientation(LinearLayout.HORIZONTAL);
mSpinnerForStatus = new Spinner(getActivity());
// Create an ArrayAdapter using the string array and a default spinner layout
String[] status = getResources().getStringArray(R.array.message_status);
if(status.length != 9)
throw new IllegalStateException("Unexpected number of status. " +
"Maybe because you only update on one place");
String columnStatus = Contract.Messages.COLUMN_NAME_STATUS;
mSelectionForStatus = new String[status.length];
mSelectionForStatus[0] = "1";
mSelectionForStatus[2] = columnStatus + " = '" + Status.UNREAD.name() + "'";
mSelectionForStatus[3] = columnStatus + " = '" + Status.HAVE_READ.name() + "'";
mSelectionForStatus[1] = mSelectionForStatus[2] + " OR " + mSelectionForStatus[3];
mSelectionForStatus[5] = columnStatus + " = '" + Status.SENDING.name() + "'";
mSelectionForStatus[6] = columnStatus + " = '" + Status.SENT.name() + "'";
mSelectionForStatus[7] = columnStatus + " = '" + Status.DELIVERED.name() + "'";
mSelectionForStatus[8] = columnStatus + " = '" + Status.FAILED_TO_SEND.name() + "'";
mSelectionForStatus[4] = mSelectionForStatus[5] + " OR " + mSelectionForStatus[6]
+ " OR " + mSelectionForStatus[7] + " OR " + mSelectionForStatus[8];
ArrayAdapter<String> adapter = new MyHierarchicalArrayAdapter<String>(
getActivity(), R.layout.simple_spinner_item, status) {
@Override
protected int getLevel(int position) {
if(position != 0 && position != 1 && position != 4)
return 2;
else
return 1;
}
};
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
mSpinnerForStatus.setAdapter(adapter);
mSpinnerForStatus.setOnItemSelectedListener(mOnSpinnerItemSelectedListener);
spinnersContainer.addView(mSpinnerForStatus, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT,
1));
mSpinnerForCode = new Spinner(getActivity());
String[] code = getResources().getStringArray(R.array.message_code);
if(code.length != 5)
throw new IllegalStateException("Unexpected number of code. " +
"Maybe because you only update on one place");
String columnCode = Contract.Messages.COLUMN_NAME_CODE;
mSelectionForCode = new String[code.length];
mSelectionForCode[0] = "1";
// 通告
mSelectionForCode[1] = columnCode + " BETWEEN " + Code.INFORM + " AND " +
(Code.INFORM | Code.EXTRA_BITS);
// 通告 && 定时消息
mSelectionForCode[2] = mSelectionForCode[1] + " AND " +
columnCode + " & " + Code.Extra.Inform.PULSE + " = " + Code.Extra.Inform.PULSE;
// 通告 && 紧急消息
mSelectionForCode[3] = mSelectionForCode[1] + " AND " +
columnCode + " & " + Code.Extra.Inform.URGENT + " = " + Code.Extra.Inform.URGENT;
// 命令 || ( 通告 && 命令响应 )
mSelectionForCode[4] = columnCode + " BETWEEN " + Code.COMMAND + " AND " +
(Code.COMMAND | Code.EXTRA_BITS) + " OR ( " +
mSelectionForCode[1] + " AND " +
columnCode + " & " + Code.Extra.Inform.RESPOND + " = " + Code.Extra.Inform.RESPOND + " )";
adapter = new MyHierarchicalArrayAdapter<String>(
getActivity(), R.layout.simple_spinner_item, code) {
@Override
protected int getLevel(int position) {
if(position == 2 || position == 3)
return 2;
else
return 1;
}
};
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
mSpinnerForCode.setAdapter(adapter);
mSpinnerForCode.setOnItemSelectedListener(mOnSpinnerItemSelectedListener);
spinnersContainer.addView(mSpinnerForCode, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT,
1));
mSpinnerForContact = new Spinner(getActivity());
mAdapterForContactsSpinner = new MySimpleCursorAdapterWithHeader(
getActivity(),
null,
new String[]{Contract.Contacts.COLUMN_NAME_NAME},
0,
new String[]{getString(R.string.all)});
mSpinnerForContact.setAdapter(mAdapterForContactsSpinner);
mSpinnerForContact.setOnItemSelectedListener(mOnSpinnerItemSelectedListener);
spinnersContainer.addView(mSpinnerForContact, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT,
1));
return spinnersContainer;
}
/**
* 取得指定消息状态在其{@link Spinner}中的位置
* @param status 需要查询的消息状态,用R.string.*表示
* @return 指定状态在其{@link Spinner}中的位置;如果没有其位置,返回null
*/
protected Integer getStatusSpinnerPosition(int status) {
String[] statuses = getResources().getStringArray(R.array.message_status);
String target = getString(status);
int position = -1;
for(int i = 0 ; i < statuses.length ; i++) {
if(statuses[i].equals(target)) {
position = i;
break;
}
}
if(position == -1)
return null;
else
return position;
}
/**
* 取得指定消息代码在其{@link Spinner}中的位置
* @param code 需要查询的消息代码,用R.string.*表示
* @return 指定代码在其{@link Spinner}中的位置;如果没有其位置,返回null
*/
protected Integer getCodeSpinnerPosition(int code) {
String[] codes = getResources().getStringArray(R.array.message_code);
String target = getString(code);
int position = -1;
for(int i = 0 ; i < codes.length ; i++) {
if(codes[i].equals(target)) {
position = i;
break;
}
}
if(position == -1)
return null;
else
return position;
}
/**
* 选中指定ID的日志消息记录
* <p>
* <strong>Note</strong>:此方法 <em>不会</em> 自动清除以前选中的内容,只会选中指定的消息(如果有的话)
* @param ids 应当选中的消息(如果有的话)的ID
* @return 实际选中的消息的个数
* @see #setItemsCheckedByIds(long[])
*/
public int checkItemsByIds(long[] ids) {
ListView listView = getListView();
if(listView == null || mAdapterForLogList == null || mAdapterForLogList.isEmpty()
|| ids == null || ids.length == 0)
return 0;
int counter = 0;
// 对ids、LogItems排序
SortedMap<Long, Integer> items = new TreeMap<Long, Integer>();
for(int i = 0 ; i < mAdapterForLogList.getCount() ; i++) {
items.put(mAdapterForLogList.getItemId(i), i);
}
Arrays.sort(ids);
// 依次序比较ids和items中的元素
int idIndex = 0;
Iterator<Entry<Long, Integer>> iterator = items.entrySet().iterator();
long id = ids[idIndex++]; // idIndex和iterator类似指针,id和item类似上个元素的值
Entry<Long, Integer> item = iterator.next();
while(idIndex < ids.length && iterator.hasNext()) {
if(id == item.getKey()) {
listView.setItemChecked(item.getValue(), true);
counter++;
id = ids[idIndex++];
item = iterator.next();
} else if(id > item.getKey()) {
item = iterator.next();
} else { // id < item.getKey()
id = ids[idIndex++];
}
}
// id或者item是最后一个元素,比较一下这个边界元素(如果另一个还有,可能还需比较后续元素)
if(id == item.getKey()) {
listView.setItemChecked(item.getValue(), true);
counter++;
} else if(id > item.getKey()) {
// 尝试后移item
while(id > item.getKey() && iterator.hasNext()) {
item = iterator.next();
if(id == item.getKey()) {
listView.setItemChecked(item.getValue(), true);
counter++;
}
}
} else { // id < item.getKey()
while(id < item.getKey() && idIndex < ids.length) {
id = ids[idIndex++];
if(id == item.getKey()) {
listView.setItemChecked(item.getValue(), true);
counter++;
}
}
}
return counter;
}
/**
* 选中指定ID的日志消息记录,并移动到第一个选中的消息处
* <p>
* <strong>Note</strong>:此方法 <em>会</em> 自动清除以前选中的内容,再选中指定的消息(如果有的话)
* @param ids 应当选中的消息(如果有的话)的ID
* @return 实际选中的消息的个数
* @see #checkItemsByIds(long[])
*/
@SuppressLint("NewApi")
public int setItemsCheckedByIds(long[] ids) {
ListView listView = getListView();
if(listView == null)
return 0;
listView.clearChoices();
int checkedCount = checkItemsByIds(ids);
if(mActionMode != null)
mMultiChoiceModeListener.updateTitle(mActionMode);
if(checkedCount >= 1) {
List<Integer> positions = getCheckedItemPositions();
int min = positions.get(0);
for(Integer position : positions) {
if(min > position)
min = position;
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
listView.smoothScrollToPositionFromTop(min, 0);
else
listView.smoothScrollToPosition(min);
}
return checkedCount;
}
/** 取得选中的Items的位置 */
public List<Integer> getCheckedItemPositions() {
List<Integer> checkeditems = new ArrayList<Integer>();
ListView listView = getListView();
if(listView == null)
return checkeditems;
SparseBooleanArray checkedPositionsBool = listView.getCheckedItemPositions();
if(checkedPositionsBool == null)
return checkeditems;
for (int i = 0; i < checkedPositionsBool.size(); i++) {
if (checkedPositionsBool.valueAt(i)) {
checkeditems.add(checkedPositionsBool.keyAt(i));
}
}
return checkeditems;
}
private int getImportantCode(Integer code) {
if(code == null) {
return R.string.undefined;
} else if(Code.isInform(code)){
if(Code.Extra.Inform.hasSetUrgent(code))
return R.string.urgent;
else if(Code.Extra.Inform.hasSetRespond(code))
return R.string.respond;
else if(Code.Extra.Inform.hasSetPulse(code))
return R.string.pulse;
else
return R.string.inform;
} else if(Code.isCommand(code)){
if(Code.Extra.Command.hasSetLocateNow(code))
return R.string.locate_now;
else
return R.string.command;
} else if(!Code.isLegalCode(code)) {
return R.string.illegal_code;
} else {
throw new IllegalArgumentException("May be method Code.isLegalCode() not correct");
}
}
private String valueOfCode(Integer code) {
if(code == null)
return getString(R.string.undefined);
else if(Code.isInform(code))
return getString(R.string.inform);
else if(Code.isCommand(code))
return getString(R.string.command);
else if(!Code.isLegalCode(code))
return getString(R.string.illegal_code, code.intValue());
else
throw new IllegalArgumentException("May be method Code.isLegalCode() not correct");
}
private String valueOfCodeExtra(Integer code, String delimiter) {
if(delimiter.length() == 0)
throw new IllegalArgumentException("you should set a delimiter");
if(code == null || !Code.isLegalCode(code))
return "";
StringBuilder sb = new StringBuilder();
if(Code.isInform(code)){
if(Code.Extra.Inform.hasSetUrgent(code))
sb.append(getString(R.string.urgent) + delimiter);
if(Code.Extra.Inform.hasSetRespond(code))
sb.append(getString(R.string.respond) + delimiter);
if(Code.Extra.Inform.hasSetPulse(code))
sb.append(getString(R.string.pulse) + delimiter);
} else if(Code.isCommand(code)) {
if(Code.Extra.Command.hasSetLocateNow(code))
sb.append(getString(R.string.locate_now) + delimiter);
} else {
throw new IllegalArgumentException("May be method Code.isLegalCode() not correct");
}
int last = sb.lastIndexOf(delimiter);
if(last > 0)
return sb.substring(0, last);
else
return "";
}
private String valueOfDirection(Status status) {
if(status == null)
return "";
Direction direction = status.getDirection();
if(direction == Direction.SEND)
return getString(R.string.send);
else if(direction == Direction.RECEIVE)
return getString(R.string.receive);
else
throw new UnsupportedOperationException("unsupport "+direction+" now.");
}
private String valueOfHasRead(Status status) {
if(status == Status.HAVE_READ)
return getString(R.string.has_read);
else if(status == Status.UNREAD)
return getString(R.string.unread);
else
return "";
}
private String valueOfSendStatus(Status status) {
if(status == null || status.getDirection() != Direction.SEND)
return "";
switch(status) {
case SENDING:
return getString(R.string.sending);
case SENT:
return getString(R.string.sent);
case DELIVERED:
return getString(R.string.delivered);
case FAILED_TO_SEND:
return getString(R.string.failed_to_send);
default:
throw new UnsupportedOperationException("unsupport "+status+" now.");
}
}
protected final LoaderCallbacks<Cursor> mLoaderCallbacksForContacts =
new LoaderCallbacks<Cursor>(){
private final Uri baseUri = Contract.Contacts.CONTACTS_URI;;
private final String[] projection = {Contract.Contacts._ID, Contract.Contacts.COLUMN_NAME_NAME};
private static final String sortOrder = Contract.Contacts.COLUMN_NAME_NAME;
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// One callback only to one loader, so we don't care about the ID.
return new CursorLoader(getActivity(), baseUri, projection, null, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Cursor old = mAdapterForContactsSpinner.swapCursor(data);
// setup Map
Map<Long, String> id2nameNew = new HashMap<Long, String>(data.getCount());
int indexId = data.getColumnIndex(Contract.Contacts._ID);
int indexName = data.getColumnIndex(Contract.Contacts.COLUMN_NAME_NAME);
data.moveToPosition(-1);
while(data.moveToNext()) {
id2nameNew.put(data.getLong(indexId), data.getString(indexName));
}
mContactIdToNameMap = id2nameNew;
mAdapterForLogList.notifyDataSetChanged();
if(old == null)
onFirstLoadFinished();
}
private void onFirstLoadFinished() {
// 如果是第一次更新,使用Arguments指定的联系人或恢复上次的选择
Long contactId = null;
Bundle args = getArguments();
if(args != null) {
if(args.containsKey(ARGUMENT_KEY_IDS))
contactId = -1L; // 暂设置为Header:ALL,其ID应该为0-1
if(args.containsKey(ARGUMENT_KEY_CONTACT_ID))
contactId = args.getLong(ARGUMENT_KEY_CONTACT_ID);
}
if(contactId == null) {
SharedPreferences pref = getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE);
if(pref.contains(PREF_KEY_CONTACT_ID))
contactId = pref.getLong(PREF_KEY_CONTACT_ID, 0);
}
if(contactId != null) {
for(int i = 0 ; i < mSpinnerForContact.getCount() ; i++) {
if(mSpinnerForContact.getItemIdAtPosition(i) == contactId) {
mSpinnerForContact.setSelection(i);
break;
}
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapterForContactsSpinner.swapCursor(null);
mContactIdToNameMap = null;
}
};
protected final LoaderCallbacks<Cursor> mLoaderCallbacksForLogList =
new LoaderCallbacks<Cursor>() {
private final Uri baseUri = Contract.Messages.MESSAGES_URI;
private final String[] projection = {
Contract.Messages._ID,
Contract.Messages.COLUMN_NAME_ADDRESS,
Contract.Messages.COLUMN_NAME_BODY,
Contract.Messages.COLUMN_NAME_CODE,
Contract.Messages.COLUMN_NAME_CONTACT_ID,
Contract.Messages.COLUMN_NAME_STATUS,
Contract.Messages.COLUMN_NAME_TIME };
private final String sortOrder = Contract.Messages.COLUMN_NAME_TIME + " DESC";
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This class only has one Loader, so we don't care about the ID.
// 根据当前筛选条件,构造where子句
String selection =
"( " + mSelectionForStatus[mSpinnerForStatus.getSelectedItemPosition()] +
" ) AND ( " + mSelectionForCode[mSpinnerForCode.getSelectedItemPosition()]
+ " )";
if(mAdapterForContactsSpinner.getPositionWithoutHeader(
mSpinnerForContact.getSelectedItemPosition()) >= 0) {
selection += " AND ( " + Contract.Messages.COLUMN_NAME_CONTACT_ID + " = " +
mSpinnerForContact.getSelectedItemId() + " )";
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), baseUri, projection, selection, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Cursor oldCursor = mAdapterForLogList.swapCursor(data);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
// 如果处于多选状态或第一次获得日志信息,尝试恢复以前的状态
if((mActionMode != null || oldCursor == null) && mCheckedItemids != null) {
setItemsCheckedByIds(mCheckedItemids);
mCheckedItemids = null;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapterForLogList.swapCursor(null);
}
};
/** 用于接收 已修改筛选条件 的事件监听器*/
protected final OnItemSelectedListener mOnSpinnerItemSelectedListener =
new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// 如果正处于多选状态,保存现在的选择状态
if(mActionMode != null)
mCheckedItemids = getListView().getCheckedItemIds();
// 重新加载日志
getLoaderManager().restartLoader(LOADER_ID_LOG, null, mLoaderCallbacksForLogList);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
};
protected final LogMultiChoiceModeListener mMultiChoiceModeListener =
new LogMultiChoiceModeListener();
protected class LogMultiChoiceModeListener implements MultiChoiceModeListener {
private int mUnretransmittableCount = 0;
private MessagesSender mMessagesSender = null;
private List<AsyncQueryHandler> mDeletehandlers = new LinkedList<AsyncQueryHandler>();
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mActionMode = mode;
// Inflate the menu for the contextual action bar
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.fragment_log_action_mode, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here you can perform updates to the CAB due to
// an invalidate() request
MenuItem retransmit = menu.findItem(R.id.retransmit);
if(canRetransmit()) {
retransmit.setVisible(true);
retransmit.setEnabled(true);
} else {
retransmit.setVisible(false);
retransmit.setEnabled(false);
}
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.retransmit:
if(mMessagesSender == null)
retransmitSelectedItems();
else {
Toast.makeText(
getActivity(),
R.string.prompt_one_retransmission_at_a_time,
Toast.LENGTH_LONG)
.show();
return true;
}
break;
case R.id.delete:
deletetSelectedItems();
break;
default:
return false;
}
mode.finish();
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
mActionMode = null;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
updateTitle(mode);
Cursor cursor = (Cursor) getListView().getItemAtPosition(position);
String statusString = cursor.getString(
cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_STATUS));
Status status = statusString != null ? Status.valueOf(statusString) : null;
if(!isRetransmittable(status)) {
boolean oldCanRetransmit = canRetransmit();
if(checked)
mUnretransmittableCount++;
else
mUnretransmittableCount--;
boolean newCanRetransmit = canRetransmit();
if(oldCanRetransmit != newCanRetransmit)
mode.invalidate();
}
}
@SuppressLint("NewApi")
public void updateTitle(ActionMode mode) {
int count = getListView().getCheckedItemCount();
String title = getString(
count != 1 ? R.string.checked_n_messages : R.string.checked_one_message,
count);
mode.setTitle(title);
}
protected boolean isRetransmittable(Status status) {
return status == Status.FAILED_TO_SEND;
}
protected boolean canRetransmit() {
return mUnretransmittableCount == 0;
}
protected void retransmitSelectedItems() {
List<Integer> items = getCheckedItemPositions();
MessageWrapper[] messages = new MessageWrapper[items.size()];
int index = 0;
for(int position : items) {
MessageWrapper message = new MessageWrapper();
message.message = new SmsMessage();
Cursor cursor = (Cursor) mAdapterForLogList.getItem(position);
int indexId = cursor.getColumnIndex(Contract.Messages._ID);
int indexCode = cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_CODE);
int indexBody = cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_BODY);
int indexDest = cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_ADDRESS);
if(!cursor.isNull(indexCode))
message.message.setCode(cursor.getInt(indexCode));
message.message.setBody(cursor.getString(indexBody));
message.dest = cursor.getString(indexDest);
// 设置Uri
long _id = cursor.getLong(indexId);
Uri uri = Contract.Messages.MESSAGES_ID_URI;
uri = ContentUris.withAppendedId(uri, _id);
message.uri = uri;
messages[index++] = message;
}
mMessagesSender = new MessagesSender(getActivity()) {
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mMessagesSender = null;
}
};
mMessagesSender.execute(messages);
}
protected void deletetSelectedItems() {
// 构造删除条件(where子句)
long[] ids = getListView().getCheckedItemIds();
if(ids == null)
throw new NullPointerException("ids is null");
if(ids.length == 0)
return;
StringBuilder sb = new StringBuilder();
for(long id : ids)
sb.append(id + ",");
sb.deleteCharAt(sb.length() - 1);
String selection = Contract.Messages._ID + " IN ( " + sb.toString() + " )";
AsyncQueryHandler handler = new AsyncQueryHandler(
getActivity().getContentResolver()) {
@Override
protected void onDeleteComplete(int token,
Object cookie, int result) {
mDeletehandlers.remove(this);
if(mDeletehandlers.isEmpty())
getSupportActivity().setSupportProgressBarIndeterminateVisibility(false);
Toast.makeText(
getActivity(),
getString(R.string.prompt_delete_messages_successfully, result),
Toast.LENGTH_LONG)
.show();
}
};
mDeletehandlers.add(handler);
getSupportActivity().setSupportProgressBarIndeterminateVisibility(true);
handler.startDelete(-1, null, Contract.Messages.MESSAGES_URI, selection, null);
}
}
protected class LogAdapter extends CursorAdapter {
private final Context mContext;
private final LayoutInflater mInflater;
public LogAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mContext = context;
mInflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View rootView = mInflater.inflate(R.layout.fragment_log_list_item, parent, false);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
ViewHolder holder = new ViewHolder();
holder.code = (TextView) rootView.findViewById(R.id.code);
holder.code_extra = (TextView) rootView.findViewById(R.id.code_extra);
holder.body = (TextView) rootView.findViewById(R.id.body);
holder.contact_name = (TextView) rootView.findViewById(R.id.contact_name);
holder.address = (TextView) rootView.findViewById(R.id.address);
holder.send_status = (TextView) rootView.findViewById(R.id.send_status);
holder.date = (TextView) rootView.findViewById(R.id.date);
holder.type_icon = (ImageView) rootView.findViewById(R.id.type_icon);
holder.directon_icon = (ImageView) rootView.findViewById(R.id.direction_icon);
holder.unread_icon = (ImageView) rootView.findViewById(R.id.unread_icon);
rootView.setTag(holder);
return rootView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
long contactId = cursor.getLong(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_CONTACT_ID));
String address = cursor.getString(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_ADDRESS));
Date date = null;
if(!cursor.isNull(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_TIME))) {
long time = cursor.getLong(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_TIME));
date = new Date(time);
}
String statusString = cursor.getString(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_STATUS));
Status status = statusString != null ? Status.valueOf(statusString) : null;
String body = cursor.getString(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_BODY));
Integer code = null;
if(!cursor.isNull(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_CODE))) {
code = cursor.getInt(cursor.getColumnIndex(Contract.Messages.COLUMN_NAME_CODE));
}
ViewHolder holder = (ViewHolder) view.getTag();
// message code
holder.code.setText(valueOfCode(code));
holder.code_extra.setText(valueOfCodeExtra(code, " | "));
setViewColor(code, holder.type_icon);
// message body
if(body != null)
holder.body.setText(body);
else
holder.body.setText("");
// 联系人
if(mContactIdToNameMap != null) {
String contactName = mContactIdToNameMap.get(contactId);
if(contactName == null)
contactName = "null";
holder.contact_name.setText(contactName);
}
// address
if(address != null)
holder.address.setText(getString(R.string.address_formatter, address));
else
holder.address.setText(R.string.unknown);
// date
if(date != null) {
holder.date.setVisibility(View.VISIBLE);
holder.date.setText(DateFormat.getDateFormat(mContext).format(date)
+ " " + DateFormat.getTimeFormat(mContext).format(date));
} else {
holder.date.setVisibility(View.INVISIBLE);
}
// direction (in status)
if(status != null) {
//direction
holder.directon_icon.setVisibility(View.VISIBLE);
Direction dirct = status.getDirection();
if(dirct == Direction.SEND)
holder.directon_icon.setImageResource(R.drawable.left);
else if(dirct == Direction.RECEIVE)
holder.directon_icon.setImageResource(R.drawable.right);
else
throw new IllegalStateException("unknown Direction: " + dirct.name());
} else {
holder.directon_icon.setVisibility(View.INVISIBLE);
}
holder.directon_icon.setContentDescription(valueOfDirection(status));
// is it unread
if((status == Status.UNREAD)) {
holder.unread_icon.setVisibility(View.VISIBLE);
setTextAppearance(holder, R.style.TextAppearance_AppTheme_ListItem_Strong);
} else { // 包括 就收 或 status==null 的情况
holder.unread_icon.setVisibility(View.INVISIBLE);
setTextAppearance(holder, R.style.TextAppearance_AppTheme_ListItem_Weak);
}
holder.unread_icon.setContentDescription(valueOfHasRead(status));
// is it sent
if(status == null || status.getDirection() != Direction.SEND)
holder.send_status.setVisibility(View.GONE);
else {
holder.send_status.setText(
getString(R.string.send_status_formatter, valueOfSendStatus(status)));
holder.send_status.setVisibility(View.VISIBLE);
}
}
/**
* 设置每项记录视图的颜色
*/
private void setViewColor(Integer code, View rootView) {
Integer colorResId = null;
switch(getImportantCode(code)) {
case R.string.urgent:
colorResId = R.color.urgent;
break;
case R.string.respond:
colorResId = R.color.respond;
break;
case R.string.locate_now: case R.string.command:
colorResId = R.color.command;
break;
default:
colorResId = android.R.color.transparent;
}
rootView.setBackgroundColor(getResources().getColor(colorResId));
}
/**
* 设置文字显示效果(颜色、大小等)
* @param holder 要设置的数据项视图的{@link ViewHolder}
* @param resid TextAppearance资源ID
* @see TextView#setTextAppearance(Context, int)
*/
private void setTextAppearance(ViewHolder holder, int resid) {
- resetFontStyle(holder);
holder.code.setTextAppearance(mContext, resid);
holder.code_extra.setTextAppearance(mContext, resid);
holder.body.setTextAppearance(mContext, resid);
holder.contact_name.setTextAppearance(mContext, resid);
holder.address.setTextAppearance(mContext, resid);
holder.send_status.setTextAppearance(mContext, resid);
holder.date.setTextAppearance(mContext, resid);
}
- /**
- * a hack for {@link TextView#setTextAppearance(Context, int)}
- * can't cancel bold, when using
- * <a href="https://github.com/Prototik/HoloEverywhere">HoloEverywhere</a>
- * @see #setTextAppearance(ViewHolder, int)
- */
- private void resetFontStyle(ViewHolder holder) {
- holder.code.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- holder.code_extra.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- holder.body.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- holder.contact_name.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- holder.address.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- holder.send_status.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- holder.date.setFontStyle(null, FontLoader.TEXT_STYLE_NORMAL);
- }
/**
* 保存对 每项记录的视图中各元素 的引用,避免每次重复执行<code>findViewById()</code>,也方便使用
* @author Team Orange
*/
private class ViewHolder {
TextView code;
TextView code_extra;
TextView body;
TextView contact_name;
TextView address;
TextView send_status;
TextView date;
ImageView type_icon;
ImageView directon_icon;
ImageView unread_icon;
}
}
/**
* 带有层次结构的{@link ArrayAdapter}。低层次的item会被缩进。
* @author Team Orange
* @see MyHierarchicalArrayAdapter#getLevel(int)
*/
protected abstract class MyHierarchicalArrayAdapter<T> extends ArrayAdapter<T> {
private Integer DefaultPaddingLeft, DefaultPaddingRight, DefaultPaddingTop, DefaultPaddingBottom;
public MyHierarchicalArrayAdapter(Context context, int resource, T[] objects) {
super(context, resource, objects);
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
if(DefaultPaddingLeft == null) {
DefaultPaddingLeft = view.getPaddingLeft();
DefaultPaddingRight = view.getPaddingRight();
DefaultPaddingTop = view.getPaddingTop();
DefaultPaddingBottom = view.getPaddingBottom();
}
view.setPadding(DefaultPaddingLeft * getLevel(position),
DefaultPaddingTop, DefaultPaddingRight, DefaultPaddingBottom);
return view;
}
/**
* 取得位置为position的item的层级
* @param position 待判定层次的item的position
* @return 如果此item是最高层(类似<h1>)返回1;第二层返回2。以此类推
*/
protected abstract int getLevel(int position);
}
/**
* 带有标题的{@link SimpleCursorAdapter}
* <p>
* <strong>Note</strong>:这是一个特化的{@link SimpleCursorAdapter},此类是用于{@link Spinner}的{@link SpinnerAdapter},
* 其layout已经设置为了{@link R.layout#simple_spinner_item},
* 其DropDownViewResource已设置为{@link R.layout#simple_spinner_dropdown_item}。
* @author Team Orange
* @see SimpleCursorAdapter#SimpleCursorAdapter(Context, int, Cursor, String[], int[], int)
* @see SimpleCursorAdapter#setDropDownViewResource(int)
*/
protected class MySimpleCursorAdapterWithHeader extends SimpleCursorAdapter {
private final String[] mHeader;
private final LayoutInflater mInflater;
public MySimpleCursorAdapterWithHeader(Context context,
Cursor c, String[] from, int flags, String[] header) {
super(context, R.layout.simple_spinner_item, c, from,
new int[]{android.R.id.text1}, flags);
setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
mHeader = header;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return super.getCount() + mHeader.length;
}
@Override
public Object getItem(int position) {
if(!isHeader(position))
return super.getItem(getPositionWithoutHeader(position));
else
return mHeader[position];
}
@Override
public long getItemId(int position) {
if(!isHeader(position))
return super.getItemId(getPositionWithoutHeader(position));
else
return position - mHeader.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(!isHeader(position))
return super.getView(getPositionWithoutHeader(position), convertView, parent);
else {
if(convertView == null)
convertView = mInflater.inflate(R.layout.simple_spinner_item, parent, false);
((TextView)convertView.findViewById(android.R.id.text1)).setText(mHeader[position]);
return convertView;
}
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
if(!isHeader(position))
return super.getDropDownView(getPositionWithoutHeader(position), convertView, parent);
else {
if(convertView == null)
convertView = mInflater.inflate(R.layout.simple_spinner_dropdown_item, parent, false);
((CheckedTextView)convertView.findViewById(android.R.id.text1)).setText(mHeader[position]);
return convertView;
}
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public int getItemViewType(int position) {
return 0;
}
public boolean isHeader(int position) {
return position < mHeader.length;
}
public int getPositionWithoutHeader(int rawPosition) {
return rawPosition - mHeader.length;
}
}
/**
* 用于发送消息的{@link AsyncTask}。支持批量发送。
* @author Team Orange
*/
protected static class MessagesSender extends
AsyncTask<MessageWrapper, Integer, Void> {
private final Context mContext;
public MessagesSender(Context context) {
super();
mContext = context;
}
@Override
protected Void doInBackground(MessageWrapper... messages) {
if(messages == null)
return null;
final int total = messages.length;
int finished = 0;
String password = Settings.getPassword(mContext);
for(MessageWrapper message : messages) {
if(message.uri != null)
message.message.send(mContext, message.uri, message.dest, password);
else
message.message.sendAndSave(mContext, message.contactId, message.dest, password);
publishProgress(total, ++finished);
if(isCancelled())
break;
}
return null;
}
/**
* {@link Message}的包装器,作为{@link MessagesSender}的泛型参数,用于传递发送参数。
* @author Team Orange
*/
public static class MessageWrapper {
/** 要发送的消息主体,也将使用此对象的方法发送消息 */
public Message message;
/** 如果用于重发,可以不设置此字段;如果发送新消息,请设置为对方联系人ID */
public Long contactId;
/** 目标地址。如对方手机号 */
public String dest;
/** 如果用于重发,此属性为原消息的{@link Uri};如果发送新消息,此属性应设置为null */
public Uri uri;
}
}
}
| false | false | null | null |
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/JavaInformations.java b/javamelody-core/src/main/java/net/bull/javamelody/JavaInformations.java
index 950c1341..a60741d7 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/JavaInformations.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/JavaInformations.java
@@ -1,666 +1,660 @@
/*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody 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.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
/**
* Informations systèmes sur le serveur, sans code html de présentation.
* L'état d'une instance est initialisé à son instanciation et non mutable;
* il est donc de fait thread-safe.
* Cet état est celui d'une instance de JVM java, de ses threads et du système à un instant t.
* Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte.
* @author Emeric Vernat
*/
class JavaInformations implements Serializable { // NOPMD
// les stack traces des threads ne sont récupérées qu'à partir de java 1.6.0 update 1
// pour éviter la fuite mémoire du bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648
static final boolean STACK_TRACES_ENABLED = "1.6.0_01".compareTo(Parameters.JAVA_VERSION) <= 0;
private static final boolean SYNCHRONIZER_ENABLED = "1.6".compareTo(Parameters.JAVA_VERSION) < 0;
private static final boolean SYSTEM_LOAD_AVERAGE_ENABLED = "1.6"
.compareTo(Parameters.JAVA_VERSION) < 0;
private static final boolean FREE_DISK_SPACE_ENABLED = "1.6".compareTo(Parameters.JAVA_VERSION) < 0;
private static final long serialVersionUID = 3281861236369720876L;
private static final Date START_DATE = new Date();
private static boolean localWebXmlExists = true; // true par défaut
private static boolean localPomXmlExists = true; // true par défaut
private final MemoryInformations memoryInformations;
private final int sessionCount;
private final int activeThreadCount;
private final int usedConnectionCount;
private final int maxConnectionCount;
private final int activeConnectionCount;
private final long processCpuTimeMillis;
private final double systemLoadAverage;
private final long unixOpenFileDescriptorCount;
private final long unixMaxFileDescriptorCount;
private final String host;
private final String os;
private final int availableProcessors;
private final String javaVersion;
private final String jvmVersion;
private final String pid;
private final String serverInfo;
private final String contextPath;
private final String contextDisplayName;
private final Date startDate;
private final String jvmArguments;
private final long freeDiskSpaceInTemp;
private final int threadCount;
private final int peakThreadCount;
private final long totalStartedThreadCount;
private final String dataBaseVersion;
private final String dataSourceDetails;
@SuppressWarnings("all")
private final List<ThreadInformations> threadInformationsList;
@SuppressWarnings("all")
private final List<CacheInformations> cacheInformationsList;
@SuppressWarnings("all")
private final List<JobInformations> jobInformationsList;
@SuppressWarnings("all")
private final List<String> dependenciesList;
private final boolean webXmlExists = localWebXmlExists;
private final boolean pomXmlExists = localPomXmlExists;
static final class ThreadInformationsComparator implements Comparator<ThreadInformations>,
Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
public int compare(ThreadInformations thread1, ThreadInformations thread2) {
return thread1.getName().compareToIgnoreCase(thread2.getName());
}
}
static final class CacheInformationsComparator implements Comparator<CacheInformations>,
Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
public int compare(CacheInformations cache1, CacheInformations cache2) {
return cache1.getName().compareToIgnoreCase(cache2.getName());
}
}
static final class JobInformationsComparator implements Comparator<JobInformations>,
Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
public int compare(JobInformations job1, JobInformations job2) {
return job1.getName().compareToIgnoreCase(job2.getName());
}
}
// CHECKSTYLE:OFF
JavaInformations(ServletContext servletContext, boolean includeDetails) {
// CHECKSTYLE:ON
super();
memoryInformations = new MemoryInformations();
if (SessionListener.isEnabled()) {
sessionCount = SessionListener.getSessionCount();
} else {
sessionCount = -1;
}
activeThreadCount = JdbcWrapper.getActiveThreadCount();
usedConnectionCount = JdbcWrapper.getUsedConnectionCount();
activeConnectionCount = JdbcWrapper.getActiveConnectionCount();
maxConnectionCount = JdbcWrapper.getMaxConnectionCount();
systemLoadAverage = buildSystemLoadAverage();
processCpuTimeMillis = buildProcessCpuTimeMillis();
unixOpenFileDescriptorCount = buildOpenFileDescriptorCount();
unixMaxFileDescriptorCount = buildMaxFileDescriptorCount();
host = Parameters.getHostName() + '@' + Parameters.getHostAddress();
os = System.getProperty("os.name") + ' ' + System.getProperty("sun.os.patch.level") + ", "
+ System.getProperty("os.arch") + '/' + System.getProperty("sun.arch.data.model");
availableProcessors = Runtime.getRuntime().availableProcessors();
javaVersion = System.getProperty("java.runtime.name") + ", "
+ System.getProperty("java.runtime.version");
jvmVersion = System.getProperty("java.vm.name") + ", "
+ System.getProperty("java.vm.version") + ", " + System.getProperty("java.vm.info");
if (servletContext == null) {
serverInfo = null;
contextPath = null;
contextDisplayName = null;
dependenciesList = null;
} else {
serverInfo = servletContext.getServerInfo();
contextPath = Parameters.getContextPath(servletContext);
contextDisplayName = servletContext.getServletContextName();
dependenciesList = buildDependenciesList();
}
startDate = START_DATE;
jvmArguments = buildJvmArguments();
final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
threadCount = threadBean.getThreadCount();
peakThreadCount = threadBean.getPeakThreadCount();
totalStartedThreadCount = threadBean.getTotalStartedThreadCount();
if (FREE_DISK_SPACE_ENABLED) {
freeDiskSpaceInTemp = Parameters.TEMPORARY_DIRECTORY.getFreeSpace();
} else {
freeDiskSpaceInTemp = -1;
}
if (includeDetails) {
dataBaseVersion = buildDataBaseVersion();
dataSourceDetails = buildDataSourceDetails();
threadInformationsList = buildThreadInformationsList();
cacheInformationsList = CacheInformations.buildCacheInformationsList();
jobInformationsList = JobInformations.buildJobInformationsList();
pid = PID.getPID();
} else {
dataBaseVersion = null;
dataSourceDetails = null;
threadInformationsList = null;
cacheInformationsList = null;
jobInformationsList = null;
pid = null;
}
}
static void setWebXmlExistsAndPomXmlExists(boolean webXmlExists, boolean pomXmlExists) {
localWebXmlExists = webXmlExists;
localPomXmlExists = pomXmlExists;
}
boolean doesWebXmlExists() {
return webXmlExists;
}
boolean doesPomXmlExists() {
return pomXmlExists;
}
private static long buildProcessCpuTimeMillis() {
final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
if (isSunOsMBean(operatingSystem)) {
final com.sun.management.OperatingSystemMXBean osBean = (com.sun.management.OperatingSystemMXBean) operatingSystem;
// nano-secondes converties en milli-secondes
return osBean.getProcessCpuTime() / 1000000;
}
return -1;
}
private static long buildOpenFileDescriptorCount() {
final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
if (isSunOsMBean(operatingSystem)
&& "com.sun.management.UnixOperatingSystem".equals(operatingSystem.getClass()
.getName())) {
final com.sun.management.UnixOperatingSystemMXBean unixOsBean = (com.sun.management.UnixOperatingSystemMXBean) operatingSystem;
try {
return unixOsBean.getOpenFileDescriptorCount();
} catch (final Error e) {
// pour issue 16 (using jsvc on ubuntu or debian)
return -1;
}
}
return -1;
}
private static long buildMaxFileDescriptorCount() {
final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
if (isSunOsMBean(operatingSystem)
&& "com.sun.management.UnixOperatingSystem".equals(operatingSystem.getClass()
.getName())) {
final com.sun.management.UnixOperatingSystemMXBean unixOsBean = (com.sun.management.UnixOperatingSystemMXBean) operatingSystem;
try {
return unixOsBean.getMaxFileDescriptorCount();
} catch (final Error e) {
// pour issue 16 (using jsvc on ubuntu or debian)
return -1;
}
}
return -1;
}
private static double buildSystemLoadAverage() {
// System load average for the last minute.
// The system load average is the sum of
// the number of runnable entities queued to the available processors
// and the number of runnable entities running on the available processors
// averaged over a period of time.
final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
if (SYSTEM_LOAD_AVERAGE_ENABLED && operatingSystem.getSystemLoadAverage() >= 0) {
// systemLoadAverage n'existe qu'à partir du jdk 1.6
return operatingSystem.getSystemLoadAverage();
}
return -1;
}
private static String buildJvmArguments() {
final StringBuilder jvmArgs = new StringBuilder();
for (final String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
jvmArgs.append(jvmArg).append('\n');
}
if (jvmArgs.length() > 0) {
jvmArgs.deleteCharAt(jvmArgs.length() - 1);
}
return jvmArgs.toString();
}
static List<ThreadInformations> buildThreadInformationsList() {
final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
final List<Thread> threads;
final Map<Thread, StackTraceElement[]> stackTraces;
if (STACK_TRACES_ENABLED) {
stackTraces = Thread.getAllStackTraces();
threads = new ArrayList<Thread>(stackTraces.keySet());
} else {
// on récupère les threads sans stack trace en contournant bug 6434648 avant 1.6.0_01
// hormis pour le thread courant qui obtient sa stack trace différemment sans le bug
threads = getThreadsFromThreadGroups();
final Thread currentThread = Thread.currentThread();
stackTraces = Collections.singletonMap(currentThread, currentThread.getStackTrace());
}
final boolean cpuTimeEnabled = threadBean.isThreadCpuTimeSupported()
&& threadBean.isThreadCpuTimeEnabled();
final long[] deadlockedThreads = getDeadlockedThreads(threadBean);
final List<ThreadInformations> threadInfosList = new ArrayList<ThreadInformations>(
threads.size());
for (final Thread thread : threads) {
final StackTraceElement[] stackTraceElements = stackTraces.get(thread);
final List<StackTraceElement> stackTraceElementList = stackTraceElements == null ? null
: new ArrayList<StackTraceElement>(Arrays.asList(stackTraceElements));
final long cpuTimeMillis;
final long userTimeMillis;
if (cpuTimeEnabled) {
cpuTimeMillis = threadBean.getThreadCpuTime(thread.getId()) / 1000000;
userTimeMillis = threadBean.getThreadUserTime(thread.getId()) / 1000000;
} else {
cpuTimeMillis = -1;
userTimeMillis = -1;
}
final boolean deadlocked = deadlockedThreads != null
&& Arrays.binarySearch(deadlockedThreads, thread.getId()) >= 0;
// stackTraceElementList est une ArrayList et non unmodifiableList pour lisibilité xml
threadInfosList.add(new ThreadInformations(thread, stackTraceElementList,
cpuTimeMillis, userTimeMillis, deadlocked));
}
// on retourne ArrayList et non unmodifiableList pour lisibilité du xml par xstream
return threadInfosList;
}
static List<Thread> getThreadsFromThreadGroups() {
ThreadGroup group = Thread.currentThread().getThreadGroup(); // NOPMD
while (group.getParent() != null) {
group = group.getParent();
}
final Thread[] threadsArray = new Thread[group.activeCount()];
group.enumerate(threadsArray, true);
return Arrays.asList(threadsArray);
}
private static long[] getDeadlockedThreads(ThreadMXBean threadBean) {
final long[] deadlockedThreads;
if (SYNCHRONIZER_ENABLED && threadBean.isSynchronizerUsageSupported()) {
deadlockedThreads = threadBean.findDeadlockedThreads();
} else {
deadlockedThreads = threadBean.findMonitorDeadlockedThreads();
}
if (deadlockedThreads != null) {
Arrays.sort(deadlockedThreads);
}
return deadlockedThreads;
}
private static String buildDataBaseVersion() {
final StringBuilder result = new StringBuilder();
try {
// on commence par voir si le driver jdbc a été utilisé
// car s'il n'y a pas de datasource une exception est déclenchée
final JdbcDriver jdbcDriver = JdbcDriver.SINGLETON;
if (jdbcDriver.getLastConnectUrl() != null) {
final Connection connection = DriverManager.getConnection(
jdbcDriver.getLastConnectUrl(), jdbcDriver.getLastConnectInfo());
connection.setAutoCommit(false);
try {
appendDataBaseVersion(result, connection);
} finally {
- try {
- connection.rollback();
- } finally {
- connection.close();
- }
+ // rollback inutile ici car on ne fait que lire les meta-data (+ cf issue 38)
+ connection.close();
}
return result.toString();
}
// on cherche une datasource avec InitialContext pour afficher nom et version bdd + nom et version driver jdbc
// (le nom de la dataSource recherchée dans JNDI est du genre jdbc/Xxx qui est le nom standard d'une DataSource)
final Map<String, DataSource> dataSources = JdbcWrapperHelper
.getJndiAndSpringDataSources();
for (final Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
final String name = entry.getKey();
final DataSource dataSource = entry.getValue();
final Connection connection = dataSource.getConnection();
connection.setAutoCommit(false);
try {
if (result.length() > 0) {
result.append("\n\n");
}
result.append(name).append(":\n");
appendDataBaseVersion(result, connection);
} finally {
- try {
- connection.rollback();
- } finally {
- connection.close();
- }
+ // rollback inutile ici car on ne fait que lire les meta-data (+ cf issue 38)
+ connection.close();
}
}
} catch (final NamingException e) {
result.append(e.toString());
} catch (final SQLException e) {
result.append(e.toString());
}
if (result.length() > 0) {
return result.toString();
}
return null;
}
private static void appendDataBaseVersion(StringBuilder result, Connection connection)
throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
// Sécurité: pour l'instant on n'indique pas metaData.getUserName()
result.append(metaData.getURL()).append('\n');
result.append(metaData.getDatabaseProductName()).append(", ")
.append(metaData.getDatabaseProductVersion()).append('\n');
result.append("Driver JDBC:\n").append(metaData.getDriverName()).append(", ")
.append(metaData.getDriverVersion());
}
private static String buildDataSourceDetails() {
final Map<String, Map<String, Object>> dataSourcesProperties = JdbcWrapper
.getBasicDataSourceProperties();
final StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, Map<String, Object>> entry : dataSourcesProperties.entrySet()) {
final Map<String, Object> dataSourceProperties = entry.getValue();
if (dataSourceProperties.isEmpty()) {
continue;
}
if (sb.length() > 0) {
sb.append('\n');
}
final String name = entry.getKey();
if (name != null) {
sb.append(name).append(":\n");
}
for (final Map.Entry<String, Object> propertyEntry : dataSourceProperties.entrySet()) {
sb.append(propertyEntry.getKey()).append(" = ").append(propertyEntry.getValue())
.append('\n');
}
}
if (sb.length() == 0) {
return null;
}
return sb.toString();
}
private static List<String> buildDependenciesList() {
final String directory = "/WEB-INF/lib/";
@SuppressWarnings("unchecked")
final Set<String> dependencies = Parameters.getServletContext().getResourcePaths(directory);
if (dependencies == null || dependencies.isEmpty()) {
return Collections.emptyList();
}
final List<String> result = new ArrayList<String>(dependencies.size());
for (final String dependency : dependencies) {
result.add(dependency.substring(directory.length()));
}
Collections.sort(result);
return result;
}
private static boolean isSunOsMBean(OperatingSystemMXBean operatingSystem) {
// on ne teste pas operatingSystem instanceof com.sun.management.OperatingSystemMXBean
// car le package com.sun n'existe à priori pas sur une jvm tierce
final String className = operatingSystem.getClass().getName();
return "com.sun.management.OperatingSystem".equals(className)
|| "com.sun.management.UnixOperatingSystem".equals(className);
}
MemoryInformations getMemoryInformations() {
return memoryInformations;
}
int getSessionCount() {
return sessionCount;
}
int getActiveThreadCount() {
return activeThreadCount;
}
int getUsedConnectionCount() {
return usedConnectionCount;
}
int getActiveConnectionCount() {
return activeConnectionCount;
}
int getMaxConnectionCount() {
return maxConnectionCount;
}
double getUsedConnectionPercentage() {
if (maxConnectionCount > 0) {
return 100d * usedConnectionCount / maxConnectionCount;
}
return -1d;
}
long getProcessCpuTimeMillis() {
return processCpuTimeMillis;
}
double getSystemLoadAverage() {
return systemLoadAverage;
}
long getUnixOpenFileDescriptorCount() {
return unixOpenFileDescriptorCount;
}
long getUnixMaxFileDescriptorCount() {
return unixMaxFileDescriptorCount;
}
double getUnixOpenFileDescriptorPercentage() {
if (unixOpenFileDescriptorCount >= 0) {
return 100d * unixOpenFileDescriptorCount / unixMaxFileDescriptorCount;
}
return -1d;
}
String getHost() {
return host;
}
String getOS() {
return os;
}
int getAvailableProcessors() {
return availableProcessors;
}
String getJavaVersion() {
return javaVersion;
}
String getJvmVersion() {
return jvmVersion;
}
String getPID() {
return pid;
}
String getServerInfo() {
return serverInfo;
}
String getContextPath() {
return contextPath;
}
String getContextDisplayName() {
return contextDisplayName;
}
Date getStartDate() {
return startDate;
}
String getJvmArguments() {
return jvmArguments;
}
long getFreeDiskSpaceInTemp() {
return freeDiskSpaceInTemp;
}
int getThreadCount() {
return threadCount;
}
int getPeakThreadCount() {
return peakThreadCount;
}
long getTotalStartedThreadCount() {
return totalStartedThreadCount;
}
String getDataBaseVersion() {
return dataBaseVersion;
}
String getDataSourceDetails() {
return dataSourceDetails;
}
List<ThreadInformations> getThreadInformationsList() {
// on trie sur demande (si affichage)
final List<ThreadInformations> result = new ArrayList<ThreadInformations>(
threadInformationsList);
Collections.sort(result, new ThreadInformationsComparator());
return Collections.unmodifiableList(result);
}
List<CacheInformations> getCacheInformationsList() {
// on trie sur demande (si affichage)
final List<CacheInformations> result = new ArrayList<CacheInformations>(
cacheInformationsList);
Collections.sort(result, new CacheInformationsComparator());
return Collections.unmodifiableList(result);
}
List<JobInformations> getJobInformationsList() {
// on trie sur demande (si affichage)
final List<JobInformations> result = new ArrayList<JobInformations>(jobInformationsList);
Collections.sort(result, new JobInformationsComparator());
return Collections.unmodifiableList(result);
}
int getCurrentlyExecutingJobCount() {
int result = 0;
for (final JobInformations jobInformations : jobInformationsList) {
if (jobInformations.isCurrentlyExecuting()) {
result++;
}
}
return result;
}
boolean isDependenciesEnabled() {
return dependenciesList != null && !dependenciesList.isEmpty();
}
List<String> getDependenciesList() {
if (dependenciesList != null) {
return Collections.unmodifiableList(dependenciesList);
}
return Collections.emptyList();
}
String getDependencies() {
if (!isDependenciesEnabled()) {
return null;
}
final StringBuilder sb = new StringBuilder();
for (final String dependency : getDependenciesList()) {
if (dependency.endsWith(".jar") || dependency.endsWith(".JAR")) {
sb.append(dependency);
sb.append(",\n");
}
}
if (sb.length() >= 2) {
sb.delete(sb.length() - 2, sb.length());
}
return sb.toString();
}
boolean isStackTraceEnabled() {
for (final ThreadInformations threadInformations : threadInformationsList) {
final List<StackTraceElement> stackTrace = threadInformations.getStackTrace();
if (stackTrace != null && !stackTrace.isEmpty()) {
return true;
}
}
return false;
}
boolean isCacheEnabled() {
return cacheInformationsList != null && !cacheInformationsList.isEmpty();
}
boolean isJobEnabled() {
return jobInformationsList != null && !jobInformationsList.isEmpty();
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + "[pid=" + getPID() + ", host=" + getHost()
+ ", javaVersion=" + getJavaVersion() + ", serverInfo=" + getServerInfo() + ']';
}
}
| false | false | null | null |
diff --git a/src/com/csipsimple/pjsip/UAStateReceiver.java b/src/com/csipsimple/pjsip/UAStateReceiver.java
index 4fb916c2..d3efa3b8 100644
--- a/src/com/csipsimple/pjsip/UAStateReceiver.java
+++ b/src/com/csipsimple/pjsip/UAStateReceiver.java
@@ -1,890 +1,905 @@
/**
* Copyright (C) 2010 Regis Montoya (aka r3gis - www.r3gis.fr)
* Copyright (C) 2010 Chris McCormick (aka mccormix - [email protected])
* This file is part of CSipSimple.
*
* CSipSimple 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.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.pjsip;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.pjsip.pjsua.Callback;
import org.pjsip.pjsua.SWIGTYPE_p_p_pjmedia_port;
import org.pjsip.pjsua.SWIGTYPE_p_pjmedia_session;
import org.pjsip.pjsua.SWIGTYPE_p_pjsip_rx_data;
import org.pjsip.pjsua.pj_str_t;
import org.pjsip.pjsua.pj_stun_nat_detect_result;
import org.pjsip.pjsua.pjsip_event;
import org.pjsip.pjsua.pjsip_redirect_op;
import org.pjsip.pjsua.pjsip_status_code;
import org.pjsip.pjsua.pjsua;
import org.pjsip.pjsua.pjsuaConstants;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
+import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import com.csipsimple.R;
import com.csipsimple.api.SipCallSession;
import com.csipsimple.api.SipConfigManager;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.api.SipUri;
import com.csipsimple.api.SipUri.ParsedSipContactInfos;
import com.csipsimple.db.DBAdapter;
import com.csipsimple.models.SipMessage;
import com.csipsimple.service.SipNotifications;
import com.csipsimple.service.SipService;
import com.csipsimple.utils.CallLogHelper;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesWrapper;
import com.csipsimple.utils.Threading;
public class UAStateReceiver extends Callback {
static String THIS_FILE = "SIP UA Receiver";
final static String ACTION_PHONE_STATE_CHANGED = "android.intent.action.PHONE_STATE";
private SipNotifications notificationManager;
private PjSipService pjService;
// private ComponentName remoteControlResponder;
+ // Time in ms during which we should not relaunch call activity again
+ final static long LAUNCH_TRIGGER_DELAY = 2000;
+ private long lastLaunchCallHandler = 0;
+
int eventLockCount = 0;
private void lockCpu(){
if(eventLock != null) {
Log.d(THIS_FILE, "< LOCK CPU");
eventLock.acquire();
eventLockCount ++;
}
}
private void unlockCpu() {
if(eventLock != null && eventLock.isHeld()) {
eventLock.release();
eventLockCount --;
Log.d(THIS_FILE, "> UNLOCK CPU " + eventLockCount);
}
}
@Override
public void on_incoming_call(final int acc_id, final int callId, SWIGTYPE_p_pjsip_rx_data rdata) {
Thread t = new Thread() {
public void run() {
lockCpu();
//Check if we have not already an ongoing call
/*
SipCallSession existingOngoingCall = getActiveCallInProgress();
if(existingOngoingCall != null) {
if(existingOngoingCall.getCallState() == SipCallSession.InvState.CONFIRMED) {
Log.e(THIS_FILE, "For now we do not support two call at the same time !!!");
//If there is an ongoing call... For now decline TODO : should here manage multiple calls
//Send busy here
pjsua.call_hangup(callId, 486, null, null);
unlockCpu();
return;
}
}
*/
SipCallSession callInfo = getCallInfo(callId, true);
Log.d(THIS_FILE, "Incoming call <<");
treatIncomingCall(acc_id, callInfo);
msgHandler.sendMessage(msgHandler.obtainMessage(ON_INCOMING_CALL, callInfo));
Log.d(THIS_FILE, "Incoming call >>");
unlockCpu();
};
};
t.start();
}
@Override
public void on_call_state(final int callId, pjsip_event e) {
Thread t = new Thread() {
public void run() {
lockCpu();
Log.d(THIS_FILE, "Call state <<");
//Get current infos
SipCallSession callInfo = getCallInfo(callId, true);
int callState = callInfo.getCallState();
if (callState == SipCallSession.InvState.DISCONNECTED) {
if(pjService.mediaManager != null) {
pjService.mediaManager.stopAnnoucing();
pjService.mediaManager.resetSettings();
}
if(incomingCallLock != null && incomingCallLock.isHeld()) {
incomingCallLock.release();
}
// Call is now ended
pjService.stopDialtoneGenerator();
//TODO : should be stopped only if it's the current call.
stopRecording();
}
msgHandler.sendMessage(msgHandler.obtainMessage(ON_CALL_STATE, callInfo));
Log.d(THIS_FILE, "Call state >>");
unlockCpu();
}
};
t.start();
}
@Override
public void on_buddy_state(int buddy_id) {
lockCpu();
Log.d(THIS_FILE, "On buddy state");
// buddy_info = pjsua.buddy_get_info(buddy_id, new pjsua_buddy_info());
unlockCpu();
}
@Override
public void on_pager(int call_id, pj_str_t from, pj_str_t to, pj_str_t contact, pj_str_t mime_type, pj_str_t body) {
lockCpu();
long date = System.currentTimeMillis();
String sFrom = SipUri.getCanonicalSipContact(from.getPtr());
String contactString = "";
if(contact != null && contact.getSlen() > 0) {
Log.d(THIS_FILE, "Contact is present");
contactString = contact.getPtr();
}else {
Log.d(THIS_FILE, "EMPTY CONTACT !!!");
}
SipMessage msg = new SipMessage(sFrom, to.getPtr(), contactString, body.getPtr(), mime_type.getPtr(),
date, SipMessage.MESSAGE_TYPE_INBOX, from.getPtr());
//Insert the message to the DB
DBAdapter database = new DBAdapter(pjService.service);
database.open();
database.insertMessage(msg);
database.close();
//Broadcast the message
Intent intent = new Intent(SipManager.ACTION_SIP_MESSAGE_RECEIVED);
//TODO : could be parcelable !
intent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());
intent.putExtra(SipMessage.FIELD_BODY, msg.getBody());
pjService.service.sendBroadcast(intent);
//Notify android os of the new message
notificationManager.showNotificationForMessage(msg);
unlockCpu();
}
@Override
public void on_pager_status(int call_id, pj_str_t to, pj_str_t body, pjsip_status_code status, pj_str_t reason) {
lockCpu();
//TODO : treat error / acknowledge of messages
int messageType = (status.equals(pjsip_status_code.PJSIP_SC_OK)
|| status.equals(pjsip_status_code.PJSIP_SC_ACCEPTED))? SipMessage.MESSAGE_TYPE_SENT : SipMessage.MESSAGE_TYPE_FAILED;
String sTo = SipUri.getCanonicalSipContact(to.getPtr());
Log.d(THIS_FILE, "SipMessage in on pager status "+status.toString()+" / "+reason.getPtr());
//Update the db
DBAdapter database = new DBAdapter(pjService.service);
database.open();
database.updateMessageStatus(sTo, body.getPtr(), messageType, status.swigValue(), reason.getPtr());
database.close();
//Broadcast the information
Intent intent = new Intent(SipManager.ACTION_SIP_MESSAGE_RECEIVED);
intent.putExtra(SipMessage.FIELD_FROM, sTo);
pjService.service.sendBroadcast(intent);
unlockCpu();
}
@Override
public void on_reg_state(final int accountId) {
Thread t = new Thread() {
public void run() {
lockCpu();
Log.d(THIS_FILE, "New reg state for : " + accountId);
if(msgHandler != null) {
msgHandler.sendMessage(msgHandler.obtainMessage(ON_REGISTRATION_STATE, accountId));
}
unlockCpu();
}
};
t.start();
}
@Override
public void on_stream_created(int call_id, SWIGTYPE_p_pjmedia_session sess, long stream_idx, SWIGTYPE_p_p_pjmedia_port p_port) {
lockCpu();
Log.d(THIS_FILE, "Stream created");
unlockCpu();
}
@Override
public void on_stream_destroyed(int callId, SWIGTYPE_p_pjmedia_session sess, long streamIdx) {
lockCpu();
Log.d(THIS_FILE, "Stream destroyed");
unlockCpu();
}
@Override
public void on_call_media_state(final int callId) {
Thread t = new Thread() {
public void run() {
lockCpu();
if(pjService.mediaManager != null) {
pjService.mediaManager.stopRing();
}
if(incomingCallLock != null && incomingCallLock.isHeld()) {
incomingCallLock.release();
}
SipCallSession callInfo = getCallInfo(callId, true);
if (callInfo.getMediaStatus() == SipCallSession.MediaState.ACTIVE) {
pjsua.conf_connect(callInfo.getConfPort(), 0);
pjsua.conf_connect(0, callInfo.getConfPort());
// Adjust software volume
if(pjService.mediaManager != null) {
pjService.mediaManager.setSoftwareVolume();
}
pjsua.set_ec( pjService.prefsWrapper.getEchoCancellationTail(), pjService.prefsWrapper.getEchoMode());
// Auto record
if (recordedCall == INVALID_RECORD &&
pjService.prefsWrapper.getPreferenceBooleanValue(SipConfigManager.AUTO_RECORD_CALLS)) {
startRecording(callId);
}
}
msgHandler.sendMessage(msgHandler.obtainMessage(ON_MEDIA_STATE, callInfo));
unlockCpu();
}
};
t.start();
}
@Override
public void on_mwi_info(int acc_id, pj_str_t mime_type, pj_str_t body) {
lockCpu();
//Treat incoming voice mail notification.
String msg = body.getPtr();
//Log.d(THIS_FILE, "We have a message :: " + acc_id + " | " + mime_type.getPtr() + " | " + body.getPtr());
boolean hasMessage = false;
int numberOfMessages = 0;
String voiceMailNumber = "";
String lines[] = msg.split("\\r?\\n");
// Decapsulate the application/simple-message-summary
// TODO : should we check mime-type?
// rfc3842
Pattern messWaitingPattern = Pattern.compile(".*Messages-Waiting[ \t]?:[ \t]?(yes|no).*", Pattern.CASE_INSENSITIVE);
Pattern messAccountPattern = Pattern.compile(".*Message-Account[ \t]?:[ \t]?(.*)", Pattern.CASE_INSENSITIVE);
Pattern messVoiceNbrPattern = Pattern.compile(".*Voice-Message[ \t]?:[ \t]?([0-9]*)/[0-9]*.*", Pattern.CASE_INSENSITIVE);
for(String line : lines) {
Matcher m;
m = messWaitingPattern.matcher(line);
if(m.matches()) {
Log.w(THIS_FILE, "Matches : "+m.group(1));
if("yes".equalsIgnoreCase(m.group(1))) {
Log.d(THIS_FILE, "Hey there is messages !!! ");
hasMessage = true;
}
continue;
}
m = messAccountPattern.matcher(line);
if(m.matches()) {
voiceMailNumber = m.group(1);
Log.d(THIS_FILE, "VM acc : " + voiceMailNumber);
continue;
}
m = messVoiceNbrPattern.matcher(line);
if(m.matches()) {
try {
numberOfMessages = Integer.parseInt(m.group(1));
}catch(NumberFormatException e) {
Log.w(THIS_FILE, "Not well formated number "+m.group(1));
}
Log.d(THIS_FILE, "Nbr : "+numberOfMessages);
continue;
}
}
if(hasMessage && numberOfMessages > 0) {
SipProfile acc = pjService.getAccountForPjsipId(acc_id);
if(acc != null) {
Log.d(THIS_FILE, acc_id+" -> Has found account "+acc.getDefaultDomain()+" "+ acc.id + " >> "+acc.getProfileName());
notificationManager.showNotificationForVoiceMail(acc, numberOfMessages, voiceMailNumber);
}
}
unlockCpu();
}
@Override
public void on_zrtp_show_sas(pj_str_t sas, int verified) {
String sasString = sas.getPtr();
Log.d(THIS_FILE, "Hey hoy hay, we get the show SAS " + sasString);
Intent zrtpIntent = new Intent("com.cipsimple.tmp.zrtp.showSAS");
zrtpIntent.putExtra(Intent.EXTRA_SUBJECT, sasString);
pjService.service.sendBroadcast(zrtpIntent);
}
@Override
public int on_setup_audio(int clockRate) {
if(pjService != null) {
return pjService.setAudioInCall(clockRate);
}
return -1;
}
@Override
public void on_teardown_audio() {
if(pjService != null) {
pjService.unsetAudioInCall();
}
}
@Override
public pjsip_redirect_op on_call_redirected(int call_id, pj_str_t target) {
Log.w(THIS_FILE, "Ask for redirection, not yet implemented, for now allow all "+target.getPtr());
return pjsip_redirect_op.PJSIP_REDIRECT_ACCEPT;
}
@Override
public void on_nat_detect(pj_stun_nat_detect_result res) {
//TODO : IMPLEMENT THIS FEATURE
Log.d(THIS_FILE, "NAT TYPE DETECTED !!!" + res.getNat_type_name()+ " et "+res.getStatus());
}
// -------
// Current call management -- assume for now one unique call is managed
// -------
private HashMap<Integer, SipCallSession> callsList = new HashMap<Integer, SipCallSession>();
//private long currentCallStart = 0;
public SipCallSession getCallInfo(Integer callId, boolean update) {
Log.d(THIS_FILE, "Get call info");
SipCallSession callInfo;
synchronized (callsList) {
callInfo = callsList.get(callId);
if(callInfo == null) {
callInfo = PjSipCalls.getCallInfo(callId, pjService);
callsList.put(callId, callInfo);
} else {
if(update) {
Log.d(THIS_FILE, "UPDATE CALL INFOS !!!");
PjSipCalls.updateSessionFromPj(callInfo, pjService);
}
}
}
return callInfo;
}
public SipCallSession[] getCalls() {
if(callsList != null ) {
SipCallSession[] callsInfos = new SipCallSession[callsList.size()];
int i = 0;
for( Entry<Integer, SipCallSession> entry : callsList.entrySet()) {
callsInfos[i] = entry.getValue();
i++;
}
return callsInfos;
}
return null;
}
private WorkerHandler msgHandler;
private HandlerThread handlerThread;
private WakeLock incomingCallLock;
private WakeLock eventLock;
+
private static final int ON_INCOMING_CALL = 1;
private static final int ON_CALL_STATE = 2;
private static final int ON_MEDIA_STATE = 3;
private static final int ON_REGISTRATION_STATE = 4;
private static final int ON_PAGER = 5;
private class WorkerHandler extends Handler {
public WorkerHandler(Looper looper) {
super(looper);
Log.d(THIS_FILE, "Create async worker !!!");
}
public void handleMessage(Message msg) {
switch (msg.what) {
case ON_INCOMING_CALL:{
//CallInfo callInfo = (CallInfo) msg.obj;
break;
}
case ON_CALL_STATE:{
SipCallSession callInfo = (SipCallSession) msg.obj;
int callState = callInfo.getCallState();
switch (callState) {
case SipCallSession.InvState.INCOMING:
case SipCallSession.InvState.CALLING:
notificationManager.showNotificationForCall(callInfo);
launchCallHandler(callInfo);
broadCastAndroidCallState("RINGING", callInfo.getRemoteContact());
break;
case SipCallSession.InvState.EARLY:
case SipCallSession.InvState.CONNECTING :
case SipCallSession.InvState.CONFIRMED:
// As per issue #857 we should re-ensure notification + callHandler at each state
// cause we can miss some states due to the fact treatment of call state is threaded
// Anyway if we miss the call early + confirmed we do not need to show the UI.
notificationManager.showNotificationForCall(callInfo);
launchCallHandler(callInfo);
broadCastAndroidCallState("OFFHOOK", callInfo.getRemoteContact());
if(pjService.mediaManager != null) {
if(callState == SipCallSession.InvState.CONFIRMED) {
pjService.mediaManager.stopRing();
}
}
if(incomingCallLock != null && incomingCallLock.isHeld()) {
incomingCallLock.release();
}
// If state is confirmed and not already intialized
if(callState == SipCallSession.InvState.CONFIRMED && callInfo.callStart == 0) {
callInfo.callStart = System.currentTimeMillis();
}
break;
case SipCallSession.InvState.DISCONNECTED:
if(pjService.mediaManager != null) {
pjService.mediaManager.stopRing();
}
if(incomingCallLock != null && incomingCallLock.isHeld()) {
incomingCallLock.release();
}
Log.d(THIS_FILE, "Finish call2");
//CallLog
ContentValues cv = CallLogHelper.logValuesForCall(pjService.service, callInfo, callInfo.callStart);
//Fill our own database
//TODO : raise in DB
DBAdapter database = new DBAdapter(pjService.service);
database.open();
database.insertCallLog(cv);
database.close();
Integer isNew = cv.getAsInteger(CallLog.Calls.NEW);
if(isNew != null && isNew == 1) {
notificationManager.showNotificationForMissedCall(cv);
}
//If needed fill native database
if(pjService.prefsWrapper.useIntegrateCallLogs()) {
//Don't add with new flag
cv.put(CallLog.Calls.NEW, false);
//Reformat number for callogs
ParsedSipContactInfos callerInfos = SipUri.parseSipContact(cv.getAsString(Calls.NUMBER));
if (callerInfos != null) {
String phoneNumber = null;
if(SipUri.isPhoneNumber(callerInfos.displayName)) {
phoneNumber = callerInfos.displayName;
}else if(SipUri.isPhoneNumber(callerInfos.userName)) {
phoneNumber = callerInfos.userName;
}
//Only log numbers that can be called by GSM too.
if(phoneNumber != null) {
cv.put(Calls.NUMBER, phoneNumber);
// For log in call logs => don't add as new calls... we manage it ourselves.
cv.put(Calls.NEW, false);
CallLogHelper.addCallLog(pjService.service, cv);
}
}
}
callInfo.setIncoming(false);
callInfo.callStart = 0;
broadCastAndroidCallState("IDLE", callInfo.getRemoteContact());
//If no remaining calls, cancel the notification
if(getActiveCallInProgress() == null) {
notificationManager.cancelCalls();
// We should now ask parent to stop if needed
if(pjService != null && pjService.service != null) {
if( ! pjService.prefsWrapper.isValidConnectionForIncoming()) {
pjService.service.stopSelf();
}
}
}
break;
default:
break;
}
onBroadcastCallState(callInfo);
break;
}
case ON_MEDIA_STATE:{
SipCallSession mediaCallInfo = (SipCallSession) msg.obj;
SipCallSession callInfo = callsList.get(mediaCallInfo.getCallId());
callInfo.setMediaStatus(mediaCallInfo.getMediaStatus());
onBroadcastCallState(callInfo);
break;
}
case ON_REGISTRATION_STATE:{
Log.d(THIS_FILE, "In reg state");
// Update sip pjService (for notifications
((SipService) pjService.service).updateRegistrationsState();
// Send a broadcast message that for an account
// registration state has changed
Intent regStateChangedIntent = new Intent(SipManager.ACTION_SIP_REGISTRATION_CHANGED);
pjService.service.sendBroadcast(regStateChangedIntent);
break;
}
case ON_PAGER: {
//startSMSRing();
//String message = (String) msg.obj;
//pjService.showMessage(message);
Log.e(THIS_FILE, "yana you in CASE ON_PAGER");
//stopRing();
break;
}
}
}
};
private void treatIncomingCall(int accountId, SipCallSession callInfo) {
int callId = callInfo.getCallId();
//Get lock while ringing to be sure notification is well done !
if (incomingCallLock == null) {
PowerManager pman = (PowerManager) pjService.service.getSystemService(Context.POWER_SERVICE);
incomingCallLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.incomingCallLock");
incomingCallLock.setReferenceCounted(false);
}
//Extra check if set reference counted is false ???
if(!incomingCallLock.isHeld()) {
incomingCallLock.acquire();
}
pjService.service.getSystemService(Context.POWER_SERVICE);
String remContact = callInfo.getRemoteContact();
callInfo.setIncoming(true);
notificationManager.showNotificationForCall(callInfo);
//Auto answer feature
SipProfile acc = pjService.getAccountForPjsipId(accountId);
boolean shouldAutoAnswer = pjService.service.shouldAutoAnswer(remContact, acc);
Log.d(THIS_FILE, "Should I anto answer????"+shouldAutoAnswer);
//Or by api
if (shouldAutoAnswer) {
// Automatically answer incoming calls with 200/OK
pjService.callAnswer(callId, 200);
} else {
// Automatically answer incoming calls with 180/RINGING
pjService.callAnswer(callId, 180);
if(pjService.service.getGSMCallState() == TelephonyManager.CALL_STATE_IDLE) {
if(pjService.mediaManager != null) {
pjService.mediaManager.startRing(remContact);
}
broadCastAndroidCallState("RINGING", remContact);
}
}
launchCallHandler(callInfo);
}
// -------
// Public configuration for receiver
// -------
public void initService(PjSipService srv) {
pjService = srv;
notificationManager = pjService.service.notificationManager;
if(handlerThread == null) {
handlerThread = new HandlerThread("UAStateAsyncWorker");
handlerThread.start();
}
if(msgHandler == null) {
msgHandler = new WorkerHandler(handlerThread.getLooper());
}
if (eventLock == null) {
PowerManager pman = (PowerManager) pjService.service.getSystemService(Context.POWER_SERVICE);
eventLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.inEventLock");
eventLock.setReferenceCounted(true);
}
}
public void stopService() {
Threading.stopHandlerThread(handlerThread);
handlerThread = null;
msgHandler = null;
//Ensure lock is released since this lock is a ref counted one.
if( eventLock != null ) {
while (eventLock.isHeld()) {
eventLock.release();
}
}
}
// --------
// Private methods
// --------
private void onBroadcastCallState(final SipCallSession callInfo) {
//Internal event
Intent callStateChangedIntent = new Intent(SipManager.ACTION_SIP_CALL_CHANGED);
callStateChangedIntent.putExtra(SipManager.EXTRA_CALL_INFO, callInfo);
pjService.service.sendBroadcast(callStateChangedIntent);
}
private void broadCastAndroidCallState(String state, String number) {
//Android normalized event
Intent intent = new Intent(ACTION_PHONE_STATE_CHANGED);
intent.putExtra(TelephonyManager.EXTRA_STATE, state);
if (number != null) {
intent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, number);
}
intent.putExtra(pjService.service.getString(R.string.app_name), true);
pjService.service.sendBroadcast(intent, android.Manifest.permission.READ_PHONE_STATE);
}
/**
*
* @param currentCallInfo2
* @param callInfo
*/
private synchronized void launchCallHandler(SipCallSession currentCallInfo2) {
+ long currentElapsedTime = SystemClock.elapsedRealtime();
- // Launch activity to choose what to do with this call
- Intent callHandlerIntent = new Intent(SipManager.ACTION_SIP_CALL_UI); //new Intent(pjService, getInCallClass());
- callHandlerIntent.putExtra(SipManager.EXTRA_CALL_INFO, currentCallInfo2);
- callHandlerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP );
-
- Log.d(THIS_FILE, "Anounce call activity");
- pjService.service.startActivity(callHandlerIntent);
-
+ // Synchronized ensure we do not get this launched several time
+ // We also ensure that a minimum delay has been consumed so that we do not fire this too much times
+ // Specially for EARLY - CONNECTING states
+ if(lastLaunchCallHandler + LAUNCH_TRIGGER_DELAY < currentElapsedTime) {
+
+ // Launch activity to choose what to do with this call
+ Intent callHandlerIntent = new Intent(SipManager.ACTION_SIP_CALL_UI);
+ callHandlerIntent.putExtra(SipManager.EXTRA_CALL_INFO, currentCallInfo2);
+ callHandlerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP );
+
+ Log.d(THIS_FILE, "Anounce call activity");
+ pjService.service.startActivity(callHandlerIntent);
+ lastLaunchCallHandler = currentElapsedTime;
+ }else {
+ Log.d(THIS_FILE, "Ignore extra launch handler");
+ }
}
/**
* Check if any of call infos indicate there is an active
* call in progress.
*/
public SipCallSession getActiveCallInProgress() {
//Log.d(THIS_FILE, "isActiveCallInProgress(), number of calls: " + callsList.keySet().size());
//
// Go through the whole list of calls and check if
// any call is in an active state.
//
for (Integer i : callsList.keySet()) {
SipCallSession callInfo = getCallInfo(i, false);
if (callInfo.isActive()) {
return callInfo;
}
}
return null;
}
/**
* Broadcast the Headset button press event internally if
* there is any call in progress.
*/
public boolean handleHeadsetButton() {
SipCallSession callInfo = getActiveCallInProgress();
if (callInfo != null) {
// Headset button has been pressed by user. If there is an
// incoming call ringing the button will be used to answer the
// call. If there is an ongoing call in progress the button will
// be used to hangup the call or mute the microphone.
int state = callInfo.getCallState();
if (callInfo.isIncoming() &&
(state == SipCallSession.InvState.INCOMING ||
state == SipCallSession.InvState.EARLY)) {
pjService.callAnswer(callInfo.getCallId(), pjsip_status_code.PJSIP_SC_OK.swigValue());
return true;
}else if(state == SipCallSession.InvState.INCOMING ||
state == SipCallSession.InvState.EARLY ||
state == SipCallSession.InvState.CALLING ||
state == SipCallSession.InvState.CONFIRMED ||
state == SipCallSession.InvState.CONNECTING){
//
// In the Android phone app using the media button during
// a call mutes the microphone instead of terminating the call.
// We check here if this should be the behavior here or if
// the call should be cleared.
//
switch(pjService.prefsWrapper.getHeadsetAction()) {
//TODO : add hold -
case PreferencesWrapper.HEADSET_ACTION_CLEAR_CALL:
pjService.callHangup(callInfo.getCallId(), 0);
break;
case PreferencesWrapper.HEADSET_ACTION_MUTE:
pjService.mediaManager.toggleMute();
break;
}
return true;
}
}
return false;
}
// Recorder
private static int INVALID_RECORD = -1;
private int recordedCall = INVALID_RECORD;
private int recPort = -1;
private int recorderId = -1;
private int recordedConfPort = -1;
public void startRecording(int callId) {
// Ensure nothing is recording actually
if (recordedCall == INVALID_RECORD) {
SipCallSession callInfo = getCallInfo(callId, false);
if(callInfo == null || callInfo.getMediaStatus() != SipCallSession.MediaState.ACTIVE) {
return;
}
File mp3File = getRecordFile(callInfo.getRemoteContact());
if (mp3File != null){
int[] recId = new int[1];
pj_str_t filename = pjsua.pj_str_copy(mp3File.getAbsolutePath());
int status = pjsua.recorder_create(filename, 0, (byte[]) null, 0, 0, recId);
if(status == pjsuaConstants.PJ_SUCCESS) {
recorderId = recId[0];
Log.d(THIS_FILE, "Record started : " + recorderId);
recordedConfPort = callInfo.getConfPort();
recPort = pjsua.recorder_get_conf_port(recorderId);
pjsua.conf_connect(recordedConfPort, recPort);
pjsua.conf_connect(0, recPort);
recordedCall = callId;
}
}else {
//TODO: toaster
Log.w(THIS_FILE, "Impossible to write file");
}
}
}
public void stopRecording() {
Log.d(THIS_FILE, "Stop recording " + recordedCall+" et "+ recorderId);
if (recorderId != -1) {
pjsua.recorder_destroy(recorderId);
recorderId = -1;
}
recordedCall = INVALID_RECORD;
}
public boolean canRecord(int callId) {
if (recordedCall == INVALID_RECORD) {
SipCallSession callInfo = getCallInfo(callId, false);
if(callInfo == null || callInfo.getMediaStatus() != SipCallSession.MediaState.ACTIVE) {
return false;
}
return true;
}
return false;
}
public int getRecordedCall() {
return recordedCall;
}
private File getRecordFile(String remoteContact) {
File dir = PreferencesWrapper.getRecordsFolder();
if (dir != null){
Date d = new Date();
File file = new File(dir.getAbsoluteFile() + File.separator + sanitizeForFile(remoteContact)+ "_"+DateFormat.format("MM-dd-yy_kkmmss", d)+".wav");
Log.d(THIS_FILE, "Out dir " + file.getAbsolutePath());
return file;
}
return null;
}
private String sanitizeForFile(String remoteContact) {
String fileName = remoteContact;
fileName = fileName.replaceAll("[\\.\\\\<>:; \"\'\\*]", "_");
return fileName;
}
}
| false | false | null | null |
diff --git a/src/com.gluster.storage.management.core/src/com/gluster/storage/management/core/utils/FileUtil.java b/src/com.gluster.storage.management.core/src/com/gluster/storage/management/core/utils/FileUtil.java
index d93ab2fb..d10dfee5 100644
--- a/src/com.gluster.storage.management.core/src/com/gluster/storage/management/core/utils/FileUtil.java
+++ b/src/com.gluster.storage.management.core/src/com/gluster/storage/management/core/utils/FileUtil.java
@@ -1,126 +1,134 @@
/*******************************************************************************
* Copyright (c) 2011 Gluster, Inc. <http://www.gluster.com>
* This file is part of Gluster Management Console.
*
* Gluster Management Console is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Gluster Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.gluster.storage.management.core.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import com.gluster.storage.management.core.constants.CoreConstants;
import com.gluster.storage.management.core.exceptions.GlusterRuntimeException;
public class FileUtil {
public static String readFileAsString(File file) {
try {
return new String(readFileAsByteArray(file), CoreConstants.ENCODING_UTF8);
} catch (Exception e) {
e.printStackTrace();
throw new GlusterRuntimeException("Could not read file [" + file + "]", e);
}
}
public static byte[] readFileAsByteArray(File file) throws FileNotFoundException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[fileInputStream.available()];
fileInputStream.read(data);
fileInputStream.close();
return data;
}
public static void createTextFile(String fileName, String contents) {
try {
FileWriter writer = new FileWriter(fileName);
writer.write(contents);
writer.close();
} catch (Exception e) {
throw new GlusterRuntimeException("Exception while trying to create text file [" + fileName + "]", e);
}
}
public static String getTempDirName() {
return System.getProperty("java.io.tmpdir");
}
/**
* Create a new temporary directory. Use something like
* {@link #recursiveDelete(File)} to clean this directory up since it isn't
* deleted automatically
* @return the new directory
* @throws IOException if there is an error creating the temporary directory
*/
public static File createTempDir()
{
final File sysTempDir = new File(getTempDirName());
File newTempDir;
final int maxAttempts = 9;
int attemptCount = 0;
do
{
attemptCount++;
if(attemptCount > maxAttempts)
{
throw new GlusterRuntimeException(
"The highly improbable has occurred! Failed to " +
"create a unique temporary directory after " +
maxAttempts + " attempts.");
}
String dirName = UUID.randomUUID().toString();
newTempDir = new File(sysTempDir, dirName);
} while(newTempDir.exists());
if(newTempDir.mkdirs())
{
return newTempDir;
}
else
{
throw new GlusterRuntimeException(
"Failed to create temp dir named " +
newTempDir.getAbsolutePath());
}
}
/**
* Recursively delete file or directory
*
* @param fileOrDir
* the file or dir to delete
* @return true if all files are successfully deleted
*/
- public static boolean recursiveDelete(File fileOrDir)
+ public static void recursiveDelete(File fileOrDir)
{
if(fileOrDir.isDirectory())
{
// recursively delete contents
for(File innerFile: fileOrDir.listFiles())
{
- if(!recursiveDelete(innerFile))
- {
- return false;
- }
+ recursiveDelete(innerFile);
}
}
- return fileOrDir.delete();
+ if(!fileOrDir.delete()) {
+ throw new GlusterRuntimeException("Couldn't delete file/directory [" + fileOrDir + "]");
+ }
+ }
+
+ public static void renameFile(String fromPath, String toPath) {
+ File fromFile = new File(fromPath);
+ File toFile = new File(toPath);
+
+ if(!fromFile.renameTo(toFile)) {
+ throw new GlusterRuntimeException("Couldn't rename [" + fromFile + "] to [" + toFile + "]");
+ }
}
-}
\ No newline at end of file
+}
diff --git a/src/com.gluster.storage.management.server/src/com/gluster/storage/management/server/resources/VolumesResource.java b/src/com.gluster.storage.management.server/src/com/gluster/storage/management/server/resources/VolumesResource.java
index c8796d27..1cbab5b0 100644
--- a/src/com.gluster.storage.management.server/src/com/gluster/storage/management/server/resources/VolumesResource.java
+++ b/src/com.gluster.storage.management.server/src/com/gluster/storage/management/server/resources/VolumesResource.java
@@ -1,660 +1,668 @@
/**
* VolumesResource.java
*
* Copyright (c) 2011 Gluster, Inc. <http://www.gluster.com>
* This file is part of Gluster Management Console.
*
* Gluster Management Console is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Gluster Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.gluster.storage.management.server.resources;
import static com.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_BRICKS;
import static com.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_OPERATION;
import static com.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_SOURCE;
import static com.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_TARGET;
import static com.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_VALUE_START;
import static com.gluster.storage.management.core.constants.RESTConstants.FORM_PARAM_VALUE_STOP;
import static com.gluster.storage.management.core.constants.RESTConstants.PATH_PARAM_CLUSTER_NAME;
import static com.gluster.storage.management.core.constants.RESTConstants.PATH_PARAM_VOLUME_NAME;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_BRICKS;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_BRICK_NAME;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_DELETE_OPTION;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_DOWNLOAD;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_FROM_TIMESTAMP;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_LINE_COUNT;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_LOG_SEVERITY;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_TO_TIMESTAMP;
import static com.gluster.storage.management.core.constants.RESTConstants.QUERY_PARAM_VOLUME_NAME;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_DEFAULT_OPTIONS;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_DISKS;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_DOWNLOAD;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_LOGS;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_OPTIONS;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_PATH_CLUSTERS;
import static com.gluster.storage.management.core.constants.RESTConstants.RESOURCE_VOLUMES;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.StreamingOutput;
import com.gluster.storage.management.core.constants.CoreConstants;
import com.gluster.storage.management.core.constants.RESTConstants;
import com.gluster.storage.management.core.exceptions.ConnectionException;
import com.gluster.storage.management.core.exceptions.GlusterRuntimeException;
import com.gluster.storage.management.core.model.Brick;
import com.gluster.storage.management.core.model.GlusterServer;
import com.gluster.storage.management.core.model.Status;
import com.gluster.storage.management.core.model.Volume;
import com.gluster.storage.management.core.model.VolumeLogMessage;
import com.gluster.storage.management.core.response.GenericResponse;
import com.gluster.storage.management.core.response.LogMessageListResponse;
import com.gluster.storage.management.core.response.VolumeListResponse;
import com.gluster.storage.management.core.response.VolumeOptionInfoListResponse;
import com.gluster.storage.management.core.utils.DateUtil;
import com.gluster.storage.management.core.utils.FileUtil;
import com.gluster.storage.management.core.utils.GlusterCoreUtil;
import com.gluster.storage.management.core.utils.ProcessUtil;
import com.gluster.storage.management.server.constants.VolumeOptionsDefaults;
import com.gluster.storage.management.server.data.ClusterInfo;
import com.gluster.storage.management.server.services.ClusterService;
import com.gluster.storage.management.server.utils.GlusterUtil;
import com.gluster.storage.management.server.utils.ServerUtil;
import com.sun.jersey.api.core.InjectParam;
import com.sun.jersey.spi.resource.Singleton;
@Singleton
@Path(RESOURCE_PATH_CLUSTERS + "/{" + PATH_PARAM_CLUSTER_NAME + "}/" + RESOURCE_VOLUMES)
public class VolumesResource {
private static final String PREPARE_BRICK_SCRIPT = "create_volume_directory.py";
private static final String VOLUME_DIRECTORY_CLEANUP_SCRIPT = "clear_volume_directory.py";
private static final String VOLUME_BRICK_LOG_SCRIPT = "get_volume_brick_log.py";
@InjectParam
private GlusterServersResource glusterServersResource;
@InjectParam
private ServerUtil serverUtil;
@InjectParam
private GlusterUtil glusterUtil;
@InjectParam
private ClusterService clusterService;
@InjectParam
private VolumeOptionsDefaults volumeOptionsDefaults;
@GET
@Produces(MediaType.TEXT_XML)
public VolumeListResponse getAllVolumes(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new VolumeListResponse(Status.STATUS_SUCCESS, new ArrayList<Volume>());
}
try {
return new VolumeListResponse(Status.STATUS_SUCCESS, glusterUtil.getAllVolumes(onlineServer.getName()));
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new VolumeListResponse(Status.STATUS_SUCCESS, new ArrayList<Volume>());
}
return new VolumeListResponse(Status.STATUS_SUCCESS, glusterUtil.getAllVolumes(onlineServer.getName()));
}
}
@POST
@Consumes(MediaType.TEXT_XML)
@Produces(MediaType.TEXT_XML)
public Status createVolume(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName, Volume volume) {
List<String> brickDirectories = GlusterCoreUtil.getQualifiedBrickList(volume.getBricks());
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
Status status = null;
try {
status = glusterUtil.createVolume(volume, brickDirectories, onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
status = glusterUtil.createVolume(volume, brickDirectories, onlineServer.getName());
}
return status;
}
@SuppressWarnings("rawtypes")
@GET
@Path("{" + PATH_PARAM_VOLUME_NAME + "}")
@Produces(MediaType.TEXT_XML)
public GenericResponse getVolume(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(PATH_PARAM_VOLUME_NAME) String volumeName) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new GenericResponse<Volume>(new Status(Status.STATUS_CODE_FAILURE,
"No online servers found in cluster [" + clusterName + "]"), null);
}
try {
return new GenericResponse<Volume>(Status.STATUS_SUCCESS, glusterUtil.getVolume(volumeName,
onlineServer.getName()));
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new GenericResponse<Volume>(new Status(Status.STATUS_CODE_FAILURE,
"No online servers found in cluster [" + clusterName + "]"), null);
}
return new GenericResponse<Volume>(Status.STATUS_SUCCESS, glusterUtil.getVolume(volumeName,
onlineServer.getName()));
}
}
@PUT
@Path("{" + PATH_PARAM_VOLUME_NAME + "}")
@Produces(MediaType.TEXT_XML)
public Status performOperation(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(PATH_PARAM_VOLUME_NAME) String volumeName, @FormParam(FORM_PARAM_OPERATION) String operation) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
try {
return performOperation(volumeName, operation, onlineServer);
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
return performOperation(volumeName, operation, onlineServer);
}
}
private Status performOperation(String volumeName, String operation, GlusterServer onlineServer) {
if (operation.equals(FORM_PARAM_VALUE_START)) {
return glusterUtil.startVolume(volumeName, onlineServer.getName());
} else if (operation.equals(FORM_PARAM_VALUE_STOP)) {
return glusterUtil.stopVolume(volumeName, onlineServer.getName());
} else {
return new Status(Status.STATUS_CODE_FAILURE, "Invalid operation code [" + operation + "]");
}
}
@DELETE
@Path("{" + PATH_PARAM_VOLUME_NAME + "}")
@Produces(MediaType.TEXT_XML)
public Status deleteVolume(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@QueryParam(QUERY_PARAM_VOLUME_NAME) String volumeName,
@QueryParam(QUERY_PARAM_DELETE_OPTION) boolean deleteFlag) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
Volume volume = null;
try {
volume = glusterUtil.getVolume(volumeName, onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
volume = glusterUtil.getVolume(volumeName, onlineServer.getName());
}
List<Brick> bricks = volume.getBricks();
Status status = glusterUtil.deleteVolume(volumeName, onlineServer.getName());
if (status.isSuccess()) {
Status postDeleteStatus = postDelete(volumeName, bricks, deleteFlag);
if (!postDeleteStatus.isSuccess()) {
status.setCode(Status.STATUS_CODE_PART_SUCCESS);
status.setMessage("Error in post-delete operation: " + postDeleteStatus);
}
}
return status;
}
@DELETE
@Path("{" + QUERY_PARAM_VOLUME_NAME + "}/" + RESOURCE_DISKS)
@Produces(MediaType.TEXT_XML)
public Status removeBricks(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(QUERY_PARAM_VOLUME_NAME) String volumeName, @QueryParam(QUERY_PARAM_BRICKS) String bricks,
@QueryParam(QUERY_PARAM_DELETE_OPTION) boolean deleteFlag) {
List<String> brickList = Arrays.asList(bricks.split(",")); // Convert from comma separated string (query
// parameter)
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
Status status = null;
try {
status = glusterUtil.removeBricks(volumeName, brickList, onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
status = glusterUtil.removeBricks(volumeName, brickList, onlineServer.getName());
}
if (status.isSuccess()) {
Status cleanupStatus = cleanupDirectories(brickList, volumeName, brickList.size(), deleteFlag);
if (!cleanupStatus.isSuccess()) {
// append cleanup error to prepare brick error
status.setMessage(status.getMessage() + CoreConstants.NEWLINE + cleanupStatus.getMessage());
}
}
return status;
}
private Status postDelete(String volumeName, List<Brick> bricks, boolean deleteFlag) {
Status result;
for (Brick brick : bricks) {
String brickDirectory = brick.getBrickDirectory();
String mountPoint = brickDirectory.substring(0, brickDirectory.lastIndexOf("/"));
result = (Status) serverUtil.executeOnServer(true, brick.getServerName(), VOLUME_DIRECTORY_CLEANUP_SCRIPT
+ " " + mountPoint + " " + volumeName + (deleteFlag ? " -d" : ""), Status.class);
if (!result.isSuccess()) {
return result;
}
}
return new Status(Status.STATUS_CODE_SUCCESS, "Post volume delete operation successfully initiated");
}
@POST
@Path("{" + PATH_PARAM_VOLUME_NAME + " }/" + RESOURCE_OPTIONS)
@Produces(MediaType.TEXT_XML)
public Status setOption(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(PATH_PARAM_VOLUME_NAME) String volumeName,
@FormParam(RESTConstants.FORM_PARAM_OPTION_KEY) String key,
@FormParam(RESTConstants.FORM_PARAM_OPTION_VALUE) String value) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
try {
return glusterUtil.setOption(volumeName, key, value, onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
return glusterUtil.setOption(volumeName, key, value, onlineServer.getName());
}
}
@PUT
@Path("{" + PATH_PARAM_VOLUME_NAME + " }/" + RESOURCE_OPTIONS)
@Produces(MediaType.TEXT_XML)
public Status resetOptions(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(PATH_PARAM_VOLUME_NAME) String volumeName) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
try {
return glusterUtil.resetOptions(volumeName, onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
return glusterUtil.resetOptions(volumeName, onlineServer.getName());
}
}
@GET
@Path(RESOURCE_DEFAULT_OPTIONS)
@Produces(MediaType.TEXT_XML)
public VolumeOptionInfoListResponse getDefaultOptions(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName) {
// TODO: Fetch all volume options with their default values from GlusterFS
// whenever such a CLI command is made available in GlusterFS
return new VolumeOptionInfoListResponse(Status.STATUS_SUCCESS, volumeOptionsDefaults.getDefaults());
}
@SuppressWarnings("rawtypes")
private Status cleanupDirectories(List<String> bricks, String volumeName, int maxIndex, boolean deleteFlag) {
Status result;
for (int i = 0; i < maxIndex; i++) {
String[] brickInfo = bricks.get(i).split(":");
String serverName = brickInfo[0];
String brickDirectory = brickInfo[1];
String mountPoint = brickDirectory.substring(0, brickDirectory.lastIndexOf("/"));
Object response = serverUtil.executeOnServer(true, serverName, VOLUME_DIRECTORY_CLEANUP_SCRIPT + " "
+ mountPoint + " " + volumeName + " " + (deleteFlag ? "-d" : ""), GenericResponse.class);
if (response instanceof GenericResponse) {
result = ((GenericResponse) response).getStatus();
if (!result.isSuccess()) {
// TODO: append error and continue with cleaning up of other directories
return result;
}
} else {
// TODO: append error and continue with cleaning up of other directories
// In case of script execution failure, a Status object will be returned.
return (Status) response;
}
}
return new Status(Status.STATUS_CODE_SUCCESS, "Directories cleaned up successfully!");
}
private List<VolumeLogMessage> getBrickLogs(Volume volume, Brick brick, Integer lineCount)
throws GlusterRuntimeException {
String logDir = glusterUtil.getLogLocation(volume.getName(), brick.getQualifiedName(), brick.getServerName());
String logFileName = glusterUtil.getLogFileNameForBrickDir(brick.getBrickDirectory());
String logFilePath = logDir + CoreConstants.FILE_SEPARATOR + logFileName;
// Usage: get_volume_disk_log.py <volumeName> <diskName> <lineCount>
Object responseObj = serverUtil.executeOnServer(true, brick.getServerName(), VOLUME_BRICK_LOG_SCRIPT + " "
+ logFilePath + " " + lineCount, LogMessageListResponse.class);
Status status = null;
LogMessageListResponse response = null;
if (responseObj instanceof LogMessageListResponse) {
response = (LogMessageListResponse) responseObj;
status = response.getStatus();
} else {
status = (Status) responseObj;
}
if (!status.isSuccess()) {
throw new GlusterRuntimeException(status.toString());
}
// populate disk and trim other fields
List<VolumeLogMessage> logMessages = response.getLogMessages();
for (VolumeLogMessage logMessage : logMessages) {
logMessage.setBrickDirectory(brick.getBrickDirectory());
logMessage.setMessage(logMessage.getMessage().trim());
logMessage.setSeverity(logMessage.getSeverity().trim());
}
return logMessages;
}
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("{" + PATH_PARAM_VOLUME_NAME + "}/" + RESOURCE_LOGS + "/" + RESOURCE_DOWNLOAD)
public StreamingOutput downloadLogs(@PathParam(PATH_PARAM_CLUSTER_NAME) final String clusterName,
@PathParam(PATH_PARAM_VOLUME_NAME) final String volumeName) {
final ClusterInfo cluster = clusterService.getCluster(clusterName);
if (cluster == null) {
throw new GlusterRuntimeException("Cluster [" + clusterName + "] doesn't exist!");
}
final Volume volume = (Volume) getVolume(clusterName, volumeName).getData();
if (volume == null) {
throw new GlusterRuntimeException("Volume [" + volumeName + "] doesn't exist in cluster [" + clusterName
+ "]!");
}
return new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
File archiveFile = new File(downloadLogs(volume));
output.write(FileUtil.readFileAsByteArray(archiveFile));
archiveFile.delete();
} catch (Exception e) {
+ // TODO: Log the exception
e.printStackTrace();
throw new GlusterRuntimeException("Exception while downloading/archiving volume log files!", e);
}
}
};
}
private String downloadLogs(Volume volume) {
// create temporary directory
File tempDir = FileUtil.createTempDir();
String tempDirPath = tempDir.getPath();
for (Brick brick : volume.getBricks()) {
String logDir = glusterUtil.getLogLocation(volume.getName(), brick.getQualifiedName(),
brick.getServerName());
String logFileName = glusterUtil.getLogFileNameForBrickDir(brick.getBrickDirectory());
String logFilePath = logDir + CoreConstants.FILE_SEPARATOR + logFileName;
serverUtil.getFileFromServer(brick.getServerName(), logFilePath, tempDirPath);
+
+ String fetchedLogFile = tempDirPath + File.separator + logFileName;
+ // append log file name with server name so that log files don't overwrite each other
+ // in cases where the brick log file names are same on multiple servers
+ String localLogFile = tempDirPath + File.separator + brick.getServerName() + "-" + logFileName;
+
+ FileUtil.renameFile(fetchedLogFile, localLogFile);
}
String gzipPath = FileUtil.getTempDirName() + CoreConstants.FILE_SEPARATOR + volume.getName() + "-logs.tar.gz";
new ProcessUtil().executeCommand("tar", "czvf", gzipPath, "-C", tempDir.getParent(), tempDir.getName());
// delete the temp directory
FileUtil.recursiveDelete(tempDir);
return gzipPath;
}
@GET
@Path("{" + PATH_PARAM_VOLUME_NAME + "}/" + RESOURCE_LOGS)
public LogMessageListResponse getLogs(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(PATH_PARAM_VOLUME_NAME) String volumeName, @QueryParam(QUERY_PARAM_BRICK_NAME) String brickName,
@QueryParam(QUERY_PARAM_LOG_SEVERITY) String severity,
@QueryParam(QUERY_PARAM_FROM_TIMESTAMP) String fromTimestamp,
@QueryParam(QUERY_PARAM_TO_TIMESTAMP) String toTimestamp,
@QueryParam(QUERY_PARAM_LINE_COUNT) Integer lineCount, @QueryParam(QUERY_PARAM_DOWNLOAD) Boolean download) {
List<VolumeLogMessage> logMessages = null;
ClusterInfo cluster = clusterService.getCluster(clusterName);
if (cluster == null) {
return new LogMessageListResponse(new Status(Status.STATUS_CODE_FAILURE, "Cluster [" + clusterName
+ "] doesn't exist!"), null);
}
try {
Volume volume = (Volume) getVolume(clusterName, volumeName).getData();
if (volume == null) {
return new LogMessageListResponse(new Status(Status.STATUS_CODE_FAILURE, "Volume [" + volumeName
+ "] doesn't exist in cluster [" + clusterName + "]!"), null);
}
if (brickName == null || brickName.isEmpty() || brickName.equals(CoreConstants.ALL)) {
logMessages = getLogsForAllBricks(volume, lineCount);
} else {
// fetch logs for given brick of the volume
for (Brick brick : volume.getBricks()) {
if (brick.getQualifiedName().equals(brickName)) {
logMessages = getBrickLogs(volume, brick, lineCount);
break;
}
}
}
} catch (Exception e) {
return new LogMessageListResponse(new Status(e), null);
}
filterLogsBySeverity(logMessages, severity);
filterLogsByTime(logMessages, fromTimestamp, toTimestamp);
return new LogMessageListResponse(Status.STATUS_SUCCESS, logMessages);
}
private void filterLogsByTime(List<VolumeLogMessage> logMessages, String fromTimestamp, String toTimestamp) {
Date fromTime = null, toTime = null;
if (fromTimestamp != null && !fromTimestamp.isEmpty()) {
fromTime = DateUtil.stringToDate(fromTimestamp);
}
if (toTimestamp != null && !toTimestamp.isEmpty()) {
toTime = DateUtil.stringToDate(toTimestamp);
}
List<VolumeLogMessage> messagesToRemove = new ArrayList<VolumeLogMessage>();
for (VolumeLogMessage logMessage : logMessages) {
Date logTimestamp = logMessage.getTimestamp();
if (fromTime != null && logTimestamp.before(fromTime)) {
messagesToRemove.add(logMessage);
continue;
}
if (toTime != null && logTimestamp.after(toTime)) {
messagesToRemove.add(logMessage);
}
}
logMessages.removeAll(messagesToRemove);
}
private void filterLogsBySeverity(List<VolumeLogMessage> logMessages, String severity) {
if (severity == null || severity.isEmpty()) {
return;
}
List<VolumeLogMessage> messagesToRemove = new ArrayList<VolumeLogMessage>();
for (VolumeLogMessage logMessage : logMessages) {
if (!logMessage.getSeverity().equals(severity)) {
messagesToRemove.add(logMessage);
}
}
logMessages.removeAll(messagesToRemove);
}
private List<VolumeLogMessage> getLogsForAllBricks(Volume volume, Integer lineCount) {
List<VolumeLogMessage> logMessages;
logMessages = new ArrayList<VolumeLogMessage>();
// fetch logs for every brick of the volume
for (Brick brick : volume.getBricks()) {
logMessages.addAll(getBrickLogs(volume, brick, lineCount));
}
// Sort the log messages based on log timestamp
Collections.sort(logMessages, new Comparator<VolumeLogMessage>() {
@Override
public int compare(VolumeLogMessage message1, VolumeLogMessage message2) {
return message1.getTimestamp().compareTo(message2.getTimestamp());
}
});
return logMessages;
}
@POST
@Path("{" + QUERY_PARAM_VOLUME_NAME + "}/" + RESOURCE_DISKS)
public Status addBricks(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(QUERY_PARAM_VOLUME_NAME) String volumeName, @FormParam(FORM_PARAM_BRICKS) String bricks) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
try {
return glusterUtil.addBricks(volumeName, Arrays.asList(bricks.split(",")), onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
return glusterUtil.addBricks(volumeName, Arrays.asList(bricks.split(",")), onlineServer.getName());
}
}
@PUT
@Path("{" + QUERY_PARAM_VOLUME_NAME + "}/" + RESOURCE_DISKS)
public Status replaceDisk(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName,
@PathParam(QUERY_PARAM_VOLUME_NAME) String volumeName, @FormParam(FORM_PARAM_SOURCE) String diskFrom,
@FormParam(FORM_PARAM_TARGET) String diskTo, @FormParam(FORM_PARAM_OPERATION) String operation) {
GlusterServer onlineServer = glusterServersResource.getOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName + "]");
}
try {
return glusterUtil.migrateDisk(volumeName, diskFrom, diskTo, operation, onlineServer.getName());
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = glusterServersResource.getNewOnlineServer(clusterName);
if (onlineServer == null) {
return new Status(Status.STATUS_CODE_FAILURE, "No online servers found in cluster [" + clusterName
+ "]");
}
return glusterUtil.migrateDisk(volumeName, diskFrom, diskTo, operation, onlineServer.getName());
}
}
public static void main(String[] args) throws ClassNotFoundException {
VolumesResource vr = new VolumesResource();
// VolumeListResponse response = vr.getAllVolumes();
// for (Volume volume : response.getVolumes()) {
// System.out.println("\nName:" + volume.getName() + "\nType: " + volume.getVolumeTypeStr() + "\nStatus: "
// + volume.getStatusStr());
// }
// Volume volume = new Volume();
// volume.setName("vol3");
// volume.setTransportType(TRANSPORT_TYPE.ETHERNET);
// List<String> disks = new ArrayList<String>();
// disks.add("192.168.1.210:sdb");
// volume.addDisks(disks);
// volume.setAccessControlList("192.168.*");
// // Status status = vr.createVolume(volume);
// // System.out.println(status.getMessage());
// Form form = new Form();
// form.add("volumeName", volume.getName());
// form.add(RESTConstants.FORM_PARAM_DELETE_OPTION, 1);
// Status status = vr.deleteVolume("Vol2", true);
// System.out.println("Code : " + status.getCode());
// System.out.println("Message " + status.getMessage());
Status status1 = vr.removeBricks("testCluster", "test", "192.168.1.210:sdb", true);
System.out.println("Code : " + status1.getCode());
System.out.println("Message " + status1.getMessage());
}
}
| false | false | null | null |
diff --git a/src/com/paypal/core/AuthenticationService.java b/src/com/paypal/core/AuthenticationService.java
index 9644818..15e4f08 100644
--- a/src/com/paypal/core/AuthenticationService.java
+++ b/src/com/paypal/core/AuthenticationService.java
@@ -1,146 +1,146 @@
/**
*
*/
package com.paypal.core;
import java.util.HashMap;
import java.util.Map;
import com.paypal.exception.InvalidCredentialException;
import com.paypal.exception.MissingCredentialException;
import com.paypal.exception.SSLConfigurationException;
import com.paypal.sdk.exceptions.OAuthException;
import com.paypal.sdk.util.OAuthSignature;
/**
* @author lvairamani
*
*/
public class AuthenticationService {
private Map<String, String> headers = new HashMap<String, String>();
ICredential apiCred = null;
CredentialManager cred = null;
private String authString = Constants.EMPTY_STRING;
ConfigManager config = null;
/**
* @param apiUsername
* @param connection
* @param accessToken
* @param tokenSecret
* @param httpConfiguration
* @return map of HTTP headers to be added to request
* @throws SSLConfigurationException
* @throws InvalidCredentialException
* @throws MissingCredentialException
* @throws OAuthException
*/
public Map<String, String> getPayPalHeaders(String apiUsername,
HttpConnection connection, String accessToken, String tokenSecret,
HttpConfiguration httpConfiguration)
throws SSLConfigurationException, InvalidCredentialException,
MissingCredentialException, OAuthException {
cred = CredentialManager.getInstance();
apiCred = cred.getCredentialObject(apiUsername);
config = ConfigManager.getInstance();
/* Add headers required for service authentication */
- if ((accessToken != null && accessToken.length() == 0)
- && (tokenSecret != null && tokenSecret.length() == 0)) {
+ if ((accessToken != null && accessToken.length() != 0)
+ && (tokenSecret != null && tokenSecret.length() != 0)) {
authString = generateAuthString(apiCred, accessToken, tokenSecret,
httpConfiguration.getEndPointUrl());
headers.put("X-PAYPAL-AUTHORIZATION", authString);
connection.setDefaultSSL(true);
connection.setupClientSSL(null, null);
} else if (apiCred instanceof SignatureCredential) {
headers.put("X-PAYPAL-SECURITY-USERID",
((SignatureCredential) apiCred).getUserName());
headers.put("X-PAYPAL-SECURITY-PASSWORD",
((SignatureCredential) apiCred).getPassword());
headers.put("X-PAYPAL-SECURITY-SIGNATURE",
((SignatureCredential) apiCred).getSignature());
connection.setDefaultSSL(true);
connection.setupClientSSL(null, null);
} else if (apiCred instanceof CertificateCredential) {
connection.setDefaultSSL(false);
headers.put("X-PAYPAL-SECURITY-USERID",
((CertificateCredential) apiCred).getUserName());
headers.put("X-PAYPAL-SECURITY-PASSWORD",
((CertificateCredential) apiCred).getPassword());
connection.setupClientSSL(
((CertificateCredential) apiCred).getCertificatePath(),
((CertificateCredential) apiCred).getCertificateKey());
}
/* Add other headers */
headers.put("X-PAYPAL-APPLICATION-ID", apiCred.getApplicationId());
headers.put("X-PAYPAL-REQUEST-DATA-FORMAT",
config.getValue("service.Binding"));
headers.put("X-PAYPAL-RESPONSE-DATA-FORMAT",
config.getValue("service.Binding"));
headers.put("X-PAYPAL-DEVICE-IPADDRESS",
httpConfiguration.getIpAddress());
headers.put("X-PAYPAL-REQUEST-SOURCE", Constants.SDK_NAME + "-"
+ Constants.SDK_VERSION);
return headers;
}
public String appendSoapHeader(String payload, String accessToken,
String tokenSecret) throws InvalidCredentialException,
MissingCredentialException {
StringBuffer soapMsg = new StringBuffer(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:ebay:api:PayPalAPI\" xmlns:ebl=\"urn:ebay:apis:eBLBaseComponents\" xmlns:cc=\"urn:ebay:apis:CoreComponentTypes\" xmlns:ed=\"urn:ebay:apis:EnhancedDataTypes\">");
- if ((accessToken != null && accessToken.length() == 0)
- && (tokenSecret != null && tokenSecret.length() == 0)) {
+ if ((accessToken != null && accessToken.length() != 0)
+ && (tokenSecret != null && tokenSecret.length() != 0)) {
soapMsg.append("<soapenv:Header>");
soapMsg.append("<urn:RequesterCredentials/>");
soapMsg.append("</soapenv:Header>");
} else if (apiCred instanceof SignatureCredential) {
soapMsg.append("<soapenv:Header>");
soapMsg.append("<urn:RequesterCredentials>");
soapMsg.append("<ebl:Credentials>");
soapMsg.append("<ebl:Username>"
+ ((SignatureCredential) apiCred).getUserName()
+ "</ebl:Username>");
soapMsg.append("<ebl:Password>"
+ ((SignatureCredential) apiCred).getPassword()
+ "</ebl:Password>");
soapMsg.append("<ebl:Signature>"
+ ((SignatureCredential) apiCred).getSignature()
+ "</ebl:Signature>");
soapMsg.append("</ebl:Credentials>");
soapMsg.append("</urn:RequesterCredentials>");
soapMsg.append("</soapenv:Header>");
} else if (apiCred instanceof CertificateCredential) {
soapMsg.append("<soapenv:Header>");
soapMsg.append("<urn:RequesterCredentials>");
soapMsg.append("<ebl:Credentials>");
soapMsg.append("<ebl:Username>"
+ ((CertificateCredential) apiCred).getUserName()
+ "</ebl:Username>");
soapMsg.append("<ebl:Password>"
+ ((CertificateCredential) apiCred).getPassword()
+ "</ebl:Password>");
soapMsg.append("</ebl:Credentials>");
soapMsg.append("</urn:RequesterCredentials>");
soapMsg.append("</soapenv:Header>");
}
soapMsg.append("<soapenv:Body>");
soapMsg.append(payload);
soapMsg.append("</soapenv:Body>");
soapMsg.append("</soapenv:Envelope>");
LoggingManager.info(AuthenticationService.class, soapMsg.toString());
return soapMsg.toString();
}
private String generateAuthString(ICredential apiCred, String accessToken,
String tokenSecret, String endPoint) throws OAuthException {
authString = OAuthSignature.getFullAuthString(apiCred.getUserName(),
apiCred.getPassword(), accessToken, tokenSecret,
OAuthSignature.HTTPMethod.POST, endPoint, null);
return authString;
}
}
| false | false | null | null |
diff --git a/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java b/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java
index 136a4bb..a17e9d5 100644
--- a/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java
+++ b/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java
@@ -1,42 +1,42 @@
package com.theminequest.api.quest.event;
import java.util.Collection;
import java.util.Map;
import com.theminequest.api.CompleteStatus;
import com.theminequest.api.platform.entity.MQPlayer;
import com.theminequest.api.quest.QuestDetails;
import com.theminequest.api.targeted.QuestTarget;
public abstract class TargetedQuestEvent extends DelayedQuestEvent {
private int targetID;
private long delayMS;
public final void setupTarget(int targetID, long delayMS) {
this.targetID = targetID;
this.delayMS = delayMS;
}
@Override
public final long getDelay() {
return delayMS;
}
@Override
public final boolean delayedConditions() {
return true;
}
@Override
public final CompleteStatus action() {
Map<Integer, QuestTarget> targetMap = getQuest().getDetails().getProperty(QuestDetails.QUEST_TARGET);
if (!targetMap.containsKey(targetID))
- throw new RuntimeException("No such target ID!");
+ throw new RuntimeException("No such target ID " + targetID + "...");
QuestTarget t = targetMap.get(targetID);
return targetAction(t.getPlayers(getQuest()));
}
public abstract CompleteStatus targetAction(Collection<MQPlayer> entities);
}
| true | true | public final CompleteStatus action() {
Map<Integer, QuestTarget> targetMap = getQuest().getDetails().getProperty(QuestDetails.QUEST_TARGET);
if (!targetMap.containsKey(targetID))
throw new RuntimeException("No such target ID!");
QuestTarget t = targetMap.get(targetID);
return targetAction(t.getPlayers(getQuest()));
}
| public final CompleteStatus action() {
Map<Integer, QuestTarget> targetMap = getQuest().getDetails().getProperty(QuestDetails.QUEST_TARGET);
if (!targetMap.containsKey(targetID))
throw new RuntimeException("No such target ID " + targetID + "...");
QuestTarget t = targetMap.get(targetID);
return targetAction(t.getPlayers(getQuest()));
}
|
diff --git a/src/com/douglasinfoweb/bandecodroid/ConfiguracoesActivity.java b/src/com/douglasinfoweb/bandecodroid/ConfiguracoesActivity.java
index 87f5f5f..e2703dd 100644
--- a/src/com/douglasinfoweb/bandecodroid/ConfiguracoesActivity.java
+++ b/src/com/douglasinfoweb/bandecodroid/ConfiguracoesActivity.java
@@ -1,96 +1,96 @@
package com.douglasinfoweb.bandecodroid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TabHost;
public class ConfiguracoesActivity extends Activity {
private Configuracoes config;
private HashSet<Restaurante> restaurantesSelecionados;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configuracoes);
//Pega configuracoes
Intent intent=getIntent();
config = (Configuracoes)intent.getExtras().get("config");
restaurantesSelecionados = new HashSet<Restaurante>(config.getRestaurantesEscolhidos());
//Cria o tabHost
TabHost tabHost = (TabHost)findViewById(R.id.tabConfiguracoes);
tabHost.setup();
Resources res = getResources();
TabHost.TabSpec spec; // Resusable TabSpec for each tab
spec = tabHost.newTabSpec("restaurantes");
spec.setIndicator("", res.getDrawable(R.drawable.ic_restaurantes));
spec.setContent(R.id.RestaurantesGrid);
tabHost.addTab(spec);
spec = tabHost.newTabSpec("sobre");
spec.setIndicator("", res.getDrawable(android.R.drawable.ic_menu_help));
spec.setContent(R.id.about);
tabHost.addTab(spec);
//E a grid...
GridView grid = (GridView)findViewById(R.id.RestaurantesGrid);
- grid.setAdapter(new RestauranteAdapter(this,config));
+ grid.setAdapter(new RestauranteAdapter(this));
//Botao de salvar
Button btn = (Button)findViewById(R.id.salvarButton);
final ConfiguracoesActivity act = this;
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (getRestaurantesSelecionados().size() == 0)
return;
try {
ArrayList<Restaurante> velhosRestaurantes = getConfiguracoes().getRestaurantesEscolhidos();
ArrayList<Restaurante> novosRestaurantes = new ArrayList<Restaurante>();
for (Restaurante r : Restaurante.possiveisRestaurantes) {
if (getRestaurantesSelecionados().contains(r)) {
if (velhosRestaurantes.contains(r)) {
novosRestaurantes.add(velhosRestaurantes.get(velhosRestaurantes.indexOf(r)));
} else {
novosRestaurantes.add(r);
}
}
}
getConfiguracoes().setRestaurantesEscolhidos(novosRestaurantes);
Configuracoes.save(act, act.getConfiguracoes());
Intent resultado = new Intent();
resultado.putExtra("config", act.getConfiguracoes());
act.setResult(RESULT_OK, resultado);
act.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void update() {
Button btn = (Button)findViewById(R.id.salvarButton);
btn.setEnabled((getRestaurantesSelecionados().size()>0));
}
public Configuracoes getConfiguracoes() {
return config;
}
public HashSet<Restaurante> getRestaurantesSelecionados() {
return restaurantesSelecionados;
}
public void setRestaurantesSelecionados(HashSet<Restaurante> restaurantesSelecionados) {
this.restaurantesSelecionados = restaurantesSelecionados;
}
}
diff --git a/src/com/douglasinfoweb/bandecodroid/RestauranteAdapter.java b/src/com/douglasinfoweb/bandecodroid/RestauranteAdapter.java
index 09f35fc..de487b8 100644
--- a/src/com/douglasinfoweb/bandecodroid/RestauranteAdapter.java
+++ b/src/com/douglasinfoweb/bandecodroid/RestauranteAdapter.java
@@ -1,65 +1,63 @@
package com.douglasinfoweb.bandecodroid;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
public class RestauranteAdapter extends BaseAdapter {
private ConfiguracoesActivity activity;
- private Configuracoes config;
- public RestauranteAdapter(ConfiguracoesActivity c, Configuracoes conf) {
+ public RestauranteAdapter(ConfiguracoesActivity c) {
activity = c;
- config=conf;
}
@Override
public int getCount() {
return Restaurante.possiveisRestaurantes.length;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater li = LayoutInflater.from(activity);
View restauranteView = li.inflate(R.layout.restaurante_adapter, null);
final Restaurante restaurante = Restaurante.possiveisRestaurantes[position];
ImageView image = (ImageView)restauranteView.findViewById(R.id.RestauranteImage);
image.setImageResource(restaurante.getImagem());
CheckBox checkBox = (CheckBox)restauranteView.findViewById(R.id.RestauranteCheckbox);
- checkBox.setChecked(config.getRestaurantesEscolhidos().contains(restaurante));
+ checkBox.setChecked(activity.getRestaurantesSelecionados().contains(restaurante));
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (activity.getRestaurantesSelecionados().contains(restaurante)) {
activity.getRestaurantesSelecionados().remove(restaurante);
} else {
activity.getRestaurantesSelecionados().add(restaurante);
}
activity.update();
}
});
activity.update();
return restauranteView;
}
}
| false | false | null | null |
diff --git a/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/criteria/fetch/FetchTest.java b/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/criteria/fetch/FetchTest.java
index 65f4b9f7..7cd589da 100644
--- a/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/criteria/fetch/FetchTest.java
+++ b/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/criteria/fetch/FetchTest.java
@@ -1,273 +1,273 @@
/*
* Copyright (c) 2012 - Batoo Software ve Consultancy Ltd.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.batoo.jpa.core.test.q.criteria.fetch;
import java.util.List;
import javax.persistence.TypedQuery;
import org.batoo.jpa.core.impl.criteria.CriteriaBuilderImpl;
import org.batoo.jpa.core.impl.criteria.CriteriaQueryImpl;
import org.batoo.jpa.core.impl.criteria.RootImpl;
import org.batoo.jpa.core.test.BaseCoreTest;
import org.batoo.jpa.core.test.q.Department;
import org.batoo.jpa.core.test.q.Employee;
import org.batoo.jpa.core.test.q.Manager;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author hceylan
* @since 2.0.0
*/
public class FetchTest extends BaseCoreTest {
/**
* @since 2.0.0
*/
@Test
public void testEmpty() {
final Department qa = new Department("QA");
this.persist(qa);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager qaManager2 = new Manager("Manager2", qa, 100000);
this.persist(qaManager);
this.persist(qaManager2);
final Employee employee1 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee2 = new Employee("Employee2", qaManager, qa, 100000);
this.persist(employee1);
this.persist(employee2);
this.commit();
this.close();
TypedQuery<Integer> q;
q = this.cq("select m.id from Manager m where m.employees is empty", Integer.class);
- Assert.assertEquals(qaManager.getId(), q.getSingleResult());
+ Assert.assertEquals(qaManager2.getId(), q.getSingleResult());
q = this.cq("select m.id from Manager m where m.employees is not empty", Integer.class);
- Assert.assertEquals(qaManager2.getId(), q.getSingleResult());
+ Assert.assertEquals(qaManager.getId(), q.getSingleResult());
}
/**
* @since 2.0.0
*/
@Test
public void testExists() {
final Employee employee1 = new Employee();
employee1.setName("Employee1");
final Employee employee2 = new Employee();
employee2.setName("Employee2");
final Employee employee3 = new Employee();
employee3.setName("Employee3");
final Employee employee4 = new Employee();
employee4.setName("Employee4");
final Manager manager1 = new Manager();
manager1.setName("Manager1");
final Manager manager2 = new Manager();
manager2.setName("Manager2");
employee1.setManager(manager1);
employee2.setManager(manager1);
employee4.setManager(manager2);
this.persist(employee1);
this.persist(employee2);
this.persist(employee3);
this.persist(employee4);
this.persist(manager1);
this.persist(manager2);
this.commit();
TypedQuery<Integer> q;
q = this.cq("select e.id from Employee e where exists (select m from Manager m where e.manager = m) order by e.id", Integer.class);
Assert.assertEquals("[1, 2, 4]", q.getResultList().toString());
q = this.cq("select e.id from Employee e where not exists (select m.id from Manager m where e.manager = m)", Integer.class);
Assert.assertEquals("[3]", q.getResultList().toString());
}
/**
* @since 2.0.0
*/
@Test
public void testfetche() {
final Department qa = new Department("QA");
final Department rnd = new Department("RND");
this.persist(qa);
this.persist(rnd);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager rndManager = new Manager("Manager2", rnd, 100000);
final Manager qaManager2 = new Manager("Manager3", qa, 80000);
this.persist(rndManager);
this.persist(qaManager);
this.persist(qaManager2);
final Employee employee1 = new Employee("Employee1", rndManager, rnd, 90000);
final Employee employee2 = new Employee("Employee2", rndManager, rnd, 100000);
this.persist(employee1);
this.persist(employee2);
final Employee employee3 = new Employee("Employee3", qaManager, qa, 90000);
final Employee employee4 = new Employee("Employee4", qaManager, qa, 110000);
final Employee employee5 = new Employee("Employee5", qaManager, qa, 90000);
final Employee employee6 = new Employee("Employee6", qaManager, qa, 90000);
this.persist(employee3);
this.persist(employee4);
this.persist(employee5);
this.persist(employee6);
this.commit();
final CriteriaBuilderImpl cb = this.em().getCriteriaBuilder();
final CriteriaQueryImpl<Employee> q = cb.createQuery(Employee.class);
final RootImpl<Employee> r = q.from(Employee.class);
q.select(r);
// r.join("manager");
// r.fetch("manager").fetch("employees");
// r.fetch("department");
// final Join<Employee, Manager> a = r.join("manager");
// a.fetch("person");
// a.fetch("manager");
final List<Employee> resultList = this.em().createQuery(q).getResultList();
for (final Employee emp : resultList) {
System.out.println(emp.getManager().getDepartment().getName());
}
Assert.assertEquals(6, resultList.size());
}
/**
* @since 2.0.0
*/
@Test
public void testMemberOf() {
final Department qa = new Department("QA");
final Department rnd = new Department("RND");
this.persist(qa);
this.persist(rnd);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager rndManager = new Manager("Manager2", rnd, 100000);
this.persist(rndManager);
this.persist(qaManager);
final Employee employee1 = new Employee("Employee1", rndManager, rnd, 90000);
final Employee employee2 = new Employee("Employee2", rndManager, rnd, 100000);
this.persist(employee1);
this.persist(employee2);
final Employee employee3 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee4 = new Employee("Employee2", qaManager, qa, 110000);
final Employee employee5 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee6 = new Employee("Employee2", null, qa, 90000);
this.persist(employee3);
this.persist(employee4);
this.persist(employee5);
this.persist(employee6);
this.commit();
TypedQuery<Integer> q;
q = this.cq("select m.id from Manager m where :p member of m.employees", Integer.class).setParameter("p", employee1);
Assert.assertEquals((Integer) 3, q.getSingleResult());
}
/**
* @since 2.0.0
*/
@Test
public void testSize() {
final Employee employee1 = new Employee();
employee1.setName("Employee1");
final Employee employee2 = new Employee();
employee2.setName("Employee2");
final Employee employee3 = new Employee();
employee3.setName("Employee3");
final Employee employee4 = new Employee();
employee4.setName("Employee4");
final Manager manager1 = new Manager();
manager1.setName("Manager1");
final Manager manager2 = new Manager();
manager2.setName("Manager2");
employee1.setManager(manager1);
employee2.setManager(manager1);
employee4.setManager(manager2);
this.persist(employee1);
this.persist(employee2);
this.persist(employee3);
this.persist(employee4);
this.persist(manager1);
this.persist(manager2);
this.commit();
Assert.assertEquals(2, this.cq("select size(m.employees) from Manager m where size(m.employees) = 2", Number.class).getSingleResult());
}
/**
* @since 2.0.0
*/
@Test
public void testSubQuery() {
final Department qa = new Department("QA");
final Department rnd = new Department("RND");
this.persist(qa);
this.persist(rnd);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager rndManager = new Manager("Manager2", rnd, 100000);
this.persist(rndManager);
this.persist(qaManager);
final Employee employee1 = new Employee("Employee1", rndManager, rnd, 90000);
final Employee employee2 = new Employee("Employee2", rndManager, rnd, 100000);
this.persist(employee1);
this.persist(employee2);
final Employee employee3 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee4 = new Employee("Employee2", qaManager, qa, 110000);
final Employee employee5 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee6 = new Employee("Employee2", qaManager, qa, 90000);
this.persist(employee3);
this.persist(employee4);
this.persist(employee5);
this.persist(employee6);
this.commit();
TypedQuery<Number> q;
q = this.cq("select e.id from Employee e where e.salary > (select m.salary from Manager m where m.department = e.department)", Number.class);
Assert.assertEquals(employee4.getId(), q.getSingleResult());
}
}
diff --git a/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/jpql/subquery/SubQueryJpqlTest.java b/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/jpql/subquery/SubQueryJpqlTest.java
index 0274fff6..62a2f25e 100644
--- a/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/jpql/subquery/SubQueryJpqlTest.java
+++ b/batoo-jpa/src/test/java/org/batoo/jpa/core/test/q/jpql/subquery/SubQueryJpqlTest.java
@@ -1,260 +1,260 @@
/*
* Copyright (c) 2012 - Batoo Software ve Consultancy Ltd.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.batoo.jpa.core.test.q.jpql.subquery;
import javax.persistence.TypedQuery;
import org.batoo.jpa.core.test.BaseCoreTest;
import org.batoo.jpa.core.test.q.Department;
import org.batoo.jpa.core.test.q.Employee;
import org.batoo.jpa.core.test.q.Manager;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author hceylan
* @since 2.0.0
*/
public class SubQueryJpqlTest extends BaseCoreTest {
/**
* @since 2.0.0
*/
@Test
public void testAllAnySome() {
final Department qa = new Department("QA");
final Department rnd = new Department("RND");
this.persist(qa);
this.persist(rnd);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager rndManager = new Manager("Manager2", rnd, 100000);
final Manager qaManager2 = new Manager("Manager3", qa, 80000);
this.persist(rndManager);
this.persist(qaManager);
this.persist(qaManager2);
final Employee employee1 = new Employee("Employee1", rndManager, rnd, 90000);
final Employee employee2 = new Employee("Employee2", rndManager, rnd, 100000);
this.persist(employee1);
this.persist(employee2);
final Employee employee3 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee4 = new Employee("Employee2", qaManager, qa, 110000);
final Employee employee5 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee6 = new Employee("Employee2", qaManager, qa, 90000);
this.persist(employee3);
this.persist(employee4);
this.persist(employee5);
this.persist(employee6);
this.commit();
final TypedQuery<Integer> q;
final TypedQuery<String> q2;
q = this.cq("select e.id from Employee e where e.salary > all (select m.salary from Manager m where m.department = e.department)", Integer.class);
Assert.assertEquals(employee4.getId(), q.getSingleResult());
q2 = this.cq("select e.name from Employee e where e.salary > any (select m.salary from Manager m where m.department = e.department)", String.class);
Assert.assertEquals(4, q2.getResultList().size());
}
/**
* @since 2.0.0
*/
@Test
public void testEmpty() {
final Department qa = new Department("QA");
this.persist(qa);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager qaManager2 = new Manager("Manager2", qa, 100000);
this.persist(qaManager);
this.persist(qaManager2);
final Employee employee1 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee2 = new Employee("Employee2", qaManager, qa, 100000);
this.persist(employee1);
this.persist(employee2);
this.commit();
this.close();
TypedQuery<Integer> q;
q = this.cq("select m.id from Manager m where m.employees is empty", Integer.class);
- Assert.assertEquals(qaManager.getId(), q.getSingleResult());
+ Assert.assertEquals(qaManager2.getId(), q.getSingleResult());
q = this.cq("select m.id from Manager m where m.employees is not empty", Integer.class);
- Assert.assertEquals(qaManager2.getId(), q.getSingleResult());
+ Assert.assertEquals(qaManager.getId(), q.getSingleResult());
}
/**
* @since 2.0.0
*/
@Test
public void testExists() {
final Employee employee1 = new Employee();
employee1.setName("Employee1");
final Employee employee2 = new Employee();
employee2.setName("Employee2");
final Employee employee3 = new Employee();
employee3.setName("Employee3");
final Employee employee4 = new Employee();
employee4.setName("Employee4");
final Manager manager1 = new Manager();
manager1.setName("Manager1");
final Manager manager2 = new Manager();
manager2.setName("Manager2");
employee1.setManager(manager1);
employee2.setManager(manager1);
employee4.setManager(manager2);
this.persist(employee1);
this.persist(employee2);
this.persist(employee3);
this.persist(employee4);
this.persist(manager1);
this.persist(manager2);
this.commit();
TypedQuery<Integer> q;
q = this.cq("select e.id from Employee e where exists (select m.id from Manager m where e.manager = m) order by e.id", Integer.class);
Assert.assertEquals("[1, 2, 4]", q.getResultList().toString());
q = this.cq("select e.id from Employee e where not exists (select m.id from Manager m where e.manager = m)", Integer.class);
Assert.assertEquals("[3]", q.getResultList().toString());
}
/**
* @since 2.0.0
*/
@Test
public void testMemberOf() {
final Department qa = new Department("QA");
final Department rnd = new Department("RND");
this.persist(qa);
this.persist(rnd);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager rndManager = new Manager("Manager2", rnd, 100000);
this.persist(rndManager);
this.persist(qaManager);
final Employee employee1 = new Employee("Employee1", rndManager, rnd, 90000);
final Employee employee2 = new Employee("Employee2", rndManager, rnd, 100000);
this.persist(employee1);
this.persist(employee2);
final Employee employee3 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee4 = new Employee("Employee2", qaManager, qa, 110000);
final Employee employee5 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee6 = new Employee("Employee2", null, qa, 90000);
this.persist(employee3);
this.persist(employee4);
this.persist(employee5);
this.persist(employee6);
this.commit();
TypedQuery<Integer> q;
q = this.cq("select m.id from Manager m where :p member of m.employees", Integer.class).setParameter("p", employee1);
Assert.assertEquals((Integer) 3, q.getSingleResult());
}
/**
* @since 2.0.0
*/
@Test
public void testSize() {
final Employee employee1 = new Employee();
employee1.setName("Employee1");
final Employee employee2 = new Employee();
employee2.setName("Employee2");
final Employee employee3 = new Employee();
employee3.setName("Employee3");
final Employee employee4 = new Employee();
employee4.setName("Employee4");
final Manager manager1 = new Manager();
manager1.setName("Manager1");
final Manager manager2 = new Manager();
manager2.setName("Manager2");
employee1.setManager(manager1);
employee2.setManager(manager1);
employee4.setManager(manager2);
this.persist(employee1);
this.persist(employee2);
this.persist(employee3);
this.persist(employee4);
this.persist(manager1);
this.persist(manager2);
this.commit();
Assert.assertEquals((Integer) 2, this.cq("select size(m.employees) from Manager m where size(m.employees) = 2", Integer.class).getSingleResult());
}
/**
* @since 2.0.0
*/
@Test
public void testSubQuery() {
final Department qa = new Department("QA");
final Department rnd = new Department("RND");
this.persist(qa);
this.persist(rnd);
final Manager qaManager = new Manager("Manager1", qa, 100000);
final Manager rndManager = new Manager("Manager2", rnd, 100000);
this.persist(rndManager);
this.persist(qaManager);
final Employee employee1 = new Employee("Employee1", rndManager, rnd, 90000);
final Employee employee2 = new Employee("Employee2", rndManager, rnd, 100000);
this.persist(employee1);
this.persist(employee2);
final Employee employee3 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee4 = new Employee("Employee2", qaManager, qa, 110000);
final Employee employee5 = new Employee("Employee1", qaManager, qa, 90000);
final Employee employee6 = new Employee("Employee2", qaManager, qa, 90000);
this.persist(employee3);
this.persist(employee4);
this.persist(employee5);
this.persist(employee6);
this.commit();
TypedQuery<Number> q;
q = this.cq("select e.id from Employee e where e.salary > (select m.salary from Manager m where m.department = e.department)", Number.class);
Assert.assertEquals(employee4.getId(), q.getSingleResult());
this.cq("select count(e) from Employee e where e.name in (select e.name from Employee e2)", Number.class).getResultList();
}
}
| false | false | null | null |
diff --git a/src/ibis/ipl/impl/registry/central/PeerConnectionHandler.java b/src/ibis/ipl/impl/registry/central/PeerConnectionHandler.java
index cfa5c745..efda9829 100644
--- a/src/ibis/ipl/impl/registry/central/PeerConnectionHandler.java
+++ b/src/ibis/ipl/impl/registry/central/PeerConnectionHandler.java
@@ -1,169 +1,170 @@
package ibis.ipl.impl.registry.central;
import ibis.util.ThreadPool;
import java.io.IOException;
import org.apache.log4j.Logger;
final class PeerConnectionHandler implements Runnable {
private static final Logger logger = Logger
.getLogger(PeerConnectionHandler.class);
private final ConnectionFactory connectionFactory;
private final Registry registry;
PeerConnectionHandler(ConnectionFactory connectionFactory, Registry registry) {
this.connectionFactory = connectionFactory;
this.registry = registry;
ThreadPool.createNew(this, "peer connection handler");
}
private void handleGossip(Connection connection) throws IOException {
logger.debug("got a gossip request");
String poolName = connection.in().readUTF();
int peerTime = connection.in().readInt();
if (!poolName.equals(registry.getPoolName())) {
logger.error("wrong pool: " + poolName + " instead of "
+ registry.getPoolName());
connection.closeWithError("wrong pool: " + poolName
+ " instead of " + registry.getPoolName());
return;
}
int localTime = registry.currentEventTime();
connection.sendOKReply();
connection.out().writeInt(localTime);
connection.out().flush();
if (localTime > peerTime) {
int sendEntries = localTime - peerTime;
connection.out().writeInt(sendEntries);
for (int i = 0; i < sendEntries; i++) {
Event event = registry.getEvent(peerTime + i);
event.writeTo(connection.out());
}
connection.out().flush();
} else if (localTime < peerTime) {
Event[] newEvents = new Event[connection.in().readInt()];
for (int i = 0; i < newEvents.length; i++) {
newEvents[i] = new Event(connection.in());
}
connection.close();
registry.handleNewEvents(newEvents);
}
connection.close();
}
private void handlePush(Connection connection) throws IOException {
logger.debug("got a push from the server");
String poolName = connection.in().readUTF();
if (!poolName.equals(registry.getPoolName())) {
logger.error("wrong pool: " + poolName + " instead of "
+ registry.getPoolName());
connection.closeWithError("wrong pool: " + poolName
+ " instead of " + registry.getPoolName());
}
if (!registry.statefulServer()) {
connection.out().writeInt(registry.currentEventTime());
connection.out().flush();
}
int events = connection.in().readInt();
if (events < 0) {
connection.closeWithError("negative event size");
return;
}
Event[] newEvents = new Event[events];
for (int i = 0; i < newEvents.length; i++) {
newEvents[i] = new Event(connection.in());
}
connection.sendOKReply();
connection.close();
registry.handleNewEvents(newEvents);
}
private void handlePing(Connection connection) throws IOException {
logger.debug("got a ping request");
connection.sendOKReply();
registry.getIbisIdentifier().writeTo(connection.out());
connection.out().flush();
connection.close();
}
public void run() {
Connection connection = null;
try {
logger.debug("accepting connection");
connection = connectionFactory.accept();
logger.debug("connection accepted");
} catch (IOException e) {
if (!registry.isStopped()) {
logger.error("error on accepting connection", e);
}
// wait a bit
try {
+ logger.error("Accept failed, waiting a second, will retry", e);
Thread.sleep(1000);
} catch (InterruptedException e1) {
// IGNORE
}
}
// create new thread for next connection
ThreadPool.createNew(this, "peer connection handler");
if (connection == null) {
return;
}
try {
byte magic = connection.in().readByte();
if (magic != Protocol.CLIENT_MAGIC_BYTE) {
throw new IOException(
"Invalid header byte in accepting connection");
}
byte opcode = connection.in().readByte();
logger.debug("received request: " + Protocol.opcodeString(opcode));
switch (opcode) {
case Protocol.OPCODE_GOSSIP:
handleGossip(connection);
break;
case Protocol.OPCODE_PING:
handlePing(connection);
break;
case Protocol.OPCODE_PUSH:
handlePush(connection);
break;
default:
logger.error("unknown opcode in request: " + opcode + "("
+ Protocol.opcodeString(opcode) + ")");
}
logger.debug("done handling request");
} catch (IOException e) {
logger.error("error on handling request", e);
}
}
}
diff --git a/src/ibis/ipl/impl/registry/central/ServerConnectionHandler.java b/src/ibis/ipl/impl/registry/central/ServerConnectionHandler.java
index 4412c3c4..ed3363ac 100644
--- a/src/ibis/ipl/impl/registry/central/ServerConnectionHandler.java
+++ b/src/ibis/ipl/impl/registry/central/ServerConnectionHandler.java
@@ -1,273 +1,274 @@
package ibis.ipl.impl.registry.central;
import ibis.ipl.impl.IbisIdentifier;
import ibis.ipl.impl.Location;
import ibis.util.ThreadPool;
import java.io.IOException;
import org.apache.log4j.Logger;
final class ServerConnectionHandler implements Runnable {
static final int THREADS = 10;
private static final Logger logger = Logger
.getLogger(ServerConnectionHandler.class);
private final Server server;
private final ConnectionFactory connectionFactory;
private final Stats stats;
ServerConnectionHandler(Server server, ConnectionFactory connectionFactory) {
this.server = server;
this.connectionFactory = connectionFactory;
stats = new Stats(Protocol.NR_OF_OPCODES);
ThreadPool.createNew(this, "registry server connection handler");
}
private void handleJoin(Connection connection) throws IOException {
IbisIdentifier result;
Pool pool;
byte[] clientAddress = new byte[connection.in().readInt()];
connection.in().read(clientAddress);
String poolName = connection.in().readUTF();
byte[] implementationData = new byte[connection.in().readInt()];
connection.in().read(implementationData);
Location location = new Location(connection.in());
boolean gossip = connection.in().readBoolean();
boolean keepNodeState = connection.in().readBoolean();
long pingInterval = connection.in().readLong();
pool = server.getAndCreatePool(poolName, gossip, keepNodeState, pingInterval);
try {
result = pool.join(implementationData, clientAddress, location);
} catch (Exception e) {
connection.closeWithError(e.toString());
return;
}
connection.sendOKReply();
result.writeTo(connection.out());
pool.writeBootstrap(connection.out());
connection.out().flush();
}
private void handleLeave(Connection connection) throws IOException {
IbisIdentifier identifier = new IbisIdentifier(connection.in());
Pool pool = server.getPool(identifier.poolName());
if (pool == null) {
connection.closeWithError("pool not found");
return;
}
try {
pool.leave(identifier);
} catch (Exception e) {
logger.error("error on leave", e);
connection.closeWithError(e.toString());
return;
}
connection.sendOKReply();
if (pool.ended()) {
// wake up the server so it can check the pools (and remove this
// one)
server.nudge();
}
}
private void handleElect(Connection connection) throws IOException {
IbisIdentifier candidate = new IbisIdentifier(connection.in());
String election = connection.in().readUTF();
Pool pool = server.getPool(candidate.poolName());
if (pool == null) {
connection.closeWithError("pool not found");
return;
}
IbisIdentifier winner = pool.elect(election, candidate);
connection.sendOKReply();
winner.writeTo(connection.out());
}
private void handleGetSequenceNumber(Connection connection)
throws IOException {
String poolName = connection.in().readUTF();
Pool pool = server.getPool(poolName);
if (pool == null) {
connection.closeWithError("pool not found");
return;
}
long number = pool.getSequenceNumber();
connection.sendOKReply();
connection.out().writeLong(number);
}
private void handleDead(Connection connection) throws IOException {
IbisIdentifier identifier = new IbisIdentifier(connection.in());
Pool pool = server.getPool(identifier.poolName());
if (pool == null) {
connection.closeWithError("pool not found");
return;
}
try {
pool.dead(identifier);
} catch (Exception e) {
connection.closeWithError(e.toString());
return;
}
connection.sendOKReply();
}
private void handleMaybeDead(Connection connection) throws IOException {
IbisIdentifier identifier = new IbisIdentifier(connection.in());
Pool pool = server.getPool(identifier.poolName());
if (pool == null) {
connection.closeWithError("pool not found");
return;
}
pool.maybeDead(identifier);
connection.sendOKReply();
}
private void handleSignal(Connection connection) throws IOException {
String poolName = connection.in().readUTF();
String signal = connection.in().readUTF();
IbisIdentifier[] identifiers = new IbisIdentifier[connection.in()
.readInt()];
for (int i = 0; i < identifiers.length; i++) {
identifiers[i] = new IbisIdentifier(connection.in());
}
Pool pool = server.getPool(poolName);
if (pool == null) {
connection.closeWithError("pool not found");
return;
}
pool.signal(signal, identifiers);
connection.sendOKReply();
}
String getStats(boolean clear) {
return stats.getStats(clear);
}
public void run() {
Connection connection = null;
try {
logger.debug("server: accepting new connection");
connection = connectionFactory.accept();
logger.debug("server: connection accepted");
} catch (IOException e) {
if (!server.isStopped()) {
logger.error("could not accept socket", e);
}
//wait a bit
try {
+ logger.error("Accept failed, waiting a second, will retry", e);
Thread.sleep(1000);
} catch (InterruptedException e1) {
//IGNORE
}
}
// new thread for next connection
ThreadPool.createNew(this, "registry server connection handler");
if (connection == null) {
return;
}
long start = System.currentTimeMillis();
byte opcode = 0;
try {
byte magic = connection.in().readByte();
if (magic != Protocol.SERVER_MAGIC_BYTE) {
throw new IOException("Invalid header byte in accepting connection");
}
opcode = connection.in().readByte();
if (logger.isDebugEnabled()) {
logger.debug("got request, opcode = "
+ Protocol.opcodeString(opcode));
}
switch (opcode) {
case Protocol.OPCODE_JOIN:
handleJoin(connection);
break;
case Protocol.OPCODE_LEAVE:
handleLeave(connection);
break;
case Protocol.OPCODE_ELECT:
handleElect(connection);
break;
case Protocol.OPCODE_SEQUENCE_NR:
handleGetSequenceNumber(connection);
break;
case Protocol.OPCODE_DEAD:
handleDead(connection);
break;
case Protocol.OPCODE_MAYBE_DEAD:
handleMaybeDead(connection);
break;
case Protocol.OPCODE_SIGNAL:
handleSignal(connection);
break;
default:
logger.error("unknown opcode: " + opcode);
}
} catch (IOException e) {
logger.error("error on handling connection", e);
connection.close();
return;
}
connection.close();
stats.add(opcode, System.currentTimeMillis() - start);
logger.debug("done handling request");
}
}
| false | false | null | null |
diff --git a/src/org/encog/neural/data/basic/BasicNeuralDataSet.java b/src/org/encog/neural/data/basic/BasicNeuralDataSet.java
index 264970c77..fee2df6d7 100644
--- a/src/org/encog/neural/data/basic/BasicNeuralDataSet.java
+++ b/src/org/encog/neural/data/basic/BasicNeuralDataSet.java
@@ -1,348 +1,346 @@
/*
* Encog Artificial Intelligence Framework v2.x
* Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
*
* Copyright 2008-2009, Heaton Research Inc., and individual contributors.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.encog.neural.data.basic;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import org.encog.neural.data.Indexable;
import org.encog.neural.data.NeuralData;
import org.encog.neural.data.NeuralDataPair;
import org.encog.neural.data.NeuralDataSet;
import org.encog.persist.EncogPersistedObject;
import org.encog.persist.Persistor;
import org.encog.persist.persistors.BasicNeuralDataSetPersistor;
import org.encog.util.ObjectCloner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* neural data in an ArrayList. This class is memory based, so large enough
* datasets could cause memory issues. Many other dataset types extend this
* class.
*
* @author jheaton
*/
public class BasicNeuralDataSet implements EncogPersistedObject,
Serializable, Indexable {
/**
* An iterator to be used with the BasicNeuralDataSet. This iterator does
* not support removes.
*
* @author jheaton
*/
public class BasicNeuralIterator implements Iterator<NeuralDataPair> {
/**
* The index that the iterator is currently at.
*/
private int currentIndex = 0;
/**
* Is there more data for the iterator to read?
*
* @return Returns true if there is more data to read.
*/
public boolean hasNext() {
return this.currentIndex < BasicNeuralDataSet.this.data.size();
}
/**
* Read the next item.
*
* @return The next item.
*/
public NeuralDataPair next() {
if (!hasNext()) {
return null;
}
return BasicNeuralDataSet.this.data.get(this.currentIndex++);
}
/**
* Removes are not supported.
*/
public void remove() {
if (BasicNeuralDataSet.this.logger.isErrorEnabled()) {
BasicNeuralDataSet.this.logger
.error("Called remove, unsupported operation.");
}
throw new UnsupportedOperationException();
}
}
/**
* The serial id.
*/
private static final long serialVersionUID = -2279722928570071183L;
/**
* The logging object.
*/
private final transient Logger logger = LoggerFactory.getLogger(this
.getClass());
/**
* The data held by this object.
*/
private List<NeuralDataPair> data = new ArrayList<NeuralDataPair>();
/**
* The iterators that are currently open to this object.
*/
private final List<BasicNeuralIterator> iterators = new ArrayList<BasicNeuralIterator>();
/**
* The description for this object.
*/
private String description;
/**
* The name for this object.
*/
private String name;
/**
* Default constructor.
*/
public BasicNeuralDataSet() {
}
/**
* Construct a data set from an input and idea array.
*
* @param input
* The input into the neural network for training.
* @param ideal
* The ideal output for training.
*/
public BasicNeuralDataSet(final double[][] input, final double[][] ideal) {
if (ideal != null) {
for (int i = 0; i < input.length; i++) {
final BasicNeuralData inputData = new BasicNeuralData(input[i]);
final BasicNeuralData idealData = new BasicNeuralData(ideal[i]);
this.add(inputData, idealData);
}
} else {
for (final double[] element : input) {
final BasicNeuralData inputData = new BasicNeuralData(element);
this.add(inputData);
}
}
}
/**
* Add input to the training set with no expected output. This is used for
* unsupervised training.
*
* @param data
* The input to be added to the training set.
*/
public void add(final NeuralData data) {
this.data.add(new BasicNeuralDataPair(data));
}
/**
* Add input and expected output. This is used for supervised training.
*
* @param inputData
* The input data to train on.
* @param idealData
* The ideal data to use for training.
*/
public void add(final NeuralData inputData, final NeuralData idealData) {
if (!this.iterators.isEmpty()) {
if (this.logger.isErrorEnabled()) {
this.logger.error("Concurrent modification exception");
}
throw new ConcurrentModificationException();
}
final NeuralDataPair pair = new BasicNeuralDataPair(inputData,
idealData);
this.data.add(pair);
}
/**
* Add a neural data pair to the list.
*
* @param inputData
* A NeuralDataPair object that contains both input and ideal
* data.
*/
public void add(final NeuralDataPair inputData) {
this.data.add(inputData);
}
/**
* @return A cloned copy of this object.
*/
@Override
public Object clone() {
return ObjectCloner.deepCopy(this);
}
/**
* Close this data set.
*/
public void close() {
// nothing to close
}
/**
* Create a persistor for this object.
*
* @return A persistor for this object.
*/
public Persistor createPersistor() {
return new BasicNeuralDataSetPersistor();
}
/**
* Get the data held by this container.
*
* @return the data
*/
public List<NeuralDataPair> getData() {
return this.data;
}
/**
* @return the description
*/
public String getDescription() {
return this.description;
}
/**
* Get the size of the ideal dataset. This is obtained from the first item
* in the list.
*
* @return The size of the ideal data.
*/
public int getIdealSize() {
if (this.data.isEmpty()) {
return 0;
}
final NeuralDataPair first = this.data.get(0);
if (first.getIdeal() == null) {
return 0;
}
return first.getIdeal().size();
}
/**
* Get the size of the input dataset. This is obtained from the first item
* in the list.
*
* @return The size of the input data.
*/
public int getInputSize() {
if (this.data.isEmpty()) {
return 0;
}
final NeuralDataPair first = this.data.get(0);
return first.getInput().size();
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Determine if this neural data set is supervied. All of the pairs should
* be either supervised or not, so simply check the first pair. If the list
* is empty then assume unsupervised.
*
* @return True if supervised.
*/
public boolean isSupervised() {
if (this.data.size() == 0) {
return false;
}
return this.data.get(0).isSupervised();
}
/**
* Create an iterator for this collection.
*
* @return An iterator to access this collection.
*/
public Iterator<NeuralDataPair> iterator() {
final BasicNeuralIterator result = new BasicNeuralIterator();
this.iterators.add(result);
return result;
}
/**
* @param data
* the data to set
*/
public void setData(final List<NeuralDataPair> data) {
this.data = data;
}
/**
* @param description
* the description to set
*/
public void setDescription(final String description) {
this.description = description;
}
/**
* @param name
* the name to set
*/
public void setName(final String name) {
this.name = name;
}
- @Override
public void getRecord(long index, NeuralDataPair pair) {
NeuralDataPair source = this.data.get((int)index);
pair.getInput().setData(source.getInput().getData());
if( pair.getIdeal()!=null ) {
pair.getIdeal().setData(source.getIdeal().getData());
}
}
- @Override
public long getRecordCount() {
return this.data.size();
}
}
| false | false | null | null |
diff --git a/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java b/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java
index 38b91415d..7bc576fe5 100644
--- a/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java
+++ b/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java
@@ -1,124 +1,124 @@
/*
* Copyright 2011 Wyona
*/
package org.wyona.yanel.impl.resources.search;
import org.wyona.yarep.util.YarepUtil;
import org.wyona.yarep.core.Repository;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.log4j.Logger;
/**
* Re-indexing resource. This resource can be used to start the re-indexing
* process of an arbitrary repository from within a browser session. If you
* configure this resource in your realm, make sure to protect it because you
* most likely don't want your users to start re-indexing processes.
*/
public class ReindexResource extends BasicXMLResource {
private static Logger log = Logger.getLogger(ReindexResource.class);
private static String REPO_NAME = "repository";
private static String REINDEX_XMLNS = "http://www.wyona.org/yanel/reindex/1.0";
/**
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
protected InputStream getContentXML(String viewId) throws Exception {
// Build output document
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<r:reindex xmlns:r=\"");
sb.append(REINDEX_XMLNS);
sb.append("\">");
// Which repo needs to be re-indexed?
String reindexRepo = getEnvironment().getRequest().getParameter(REPO_NAME);
// Are we allowed to re-index this repository?
// Only default repositories and the ones listed in the resource configuration are allowed to be re-indexed
boolean allowed = false;
// List default repositories
// Only show them if we're allowed to re-index them
String defaultRepos = getResourceConfigProperty("allow-default-repos");
if("true".equals(defaultRepos)) {
sb.append("<r:repository id=\"yanel_data\">Realm's data repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-identities\">Realm's ac-identities repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-policies\">Realm's ac-policies repository</r:repository>");
sb.append("<r:repository id=\"yanel_res-configs\">Realm's res-configs repository</r:repository>");
}
// List extra repositories from repo configuration
String[] repoIds = getResourceConfigProperties("repository-id");
for(String repoId : repoIds) {
if(repoId != null && !"".equals(repoId)) {
sb.append("<r:repository id=\"");
sb.append(repoId);
sb.append("\">Configured repository with id '");
sb.append(repoId);
sb.append("'</r:repository>");
// Check if repo that should be re-indexed is listed in resource configuration (see property 'repository-id')
if(!allowed && repoId.equals(reindexRepo)) allowed = true;
}
}
// Check if repo that should be re-indexed is default repo
if(!allowed && "true".equals(defaultRepos) &&
("yanel_data".equals(reindexRepo) ||
"yanel_ac-policies".equals(reindexRepo) ||
"yanel_ac-identities".equals(reindexRepo) ||
"yanel_res-configs".equals(reindexRepo))) {
allowed = true;
}
// If it's an extra repo, allowed needs to be set to true
Repository repo = null;
if(allowed) {
try {
repo = getRealm().getRepository(reindexRepo);
} catch(Exception e) {
sb.append("<r:exception>Opening repo failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
}
// Perform re-indexing now
if(repo != null) {
YarepUtil yu = new YarepUtil();
String path = "/";
if (getEnvironment().getRequest().getParameter("path") != null) {
path = getEnvironment().getRequest().getParameter("path"); // INFO: Allows to re-index sub-tree, for example http://127.0.0.1:8080/yanel/yanel-website/re-index.html?repository=yanel_data&path=/en/documentation
}
try {
yu.indexRepository(repo, path);
sb.append("<r:message>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' was successful :-)</r:message>");
- sb.append("<r:selected-repository id=\"" + repo.getID() + "\">" + repo.getName() + "</r:selected-repository>");
+ sb.append("<r:selected-repository id=\"" + reindexRepo + "\">" + repo.getName() + "</r:selected-repository>");
sb.append("<r:selected-path>" + path + "</r:selected-path>");
} catch(Exception e) {
sb.append("<r:exception>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
} else if(reindexRepo != null) {
sb.append("<r:exception>Repository '" + reindexRepo + "' does either not exist or is not configured in order to be re-indexed.</r:exception>");
}
sb.append("</r:reindex>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return true;
}
}
| true | true | protected InputStream getContentXML(String viewId) throws Exception {
// Build output document
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<r:reindex xmlns:r=\"");
sb.append(REINDEX_XMLNS);
sb.append("\">");
// Which repo needs to be re-indexed?
String reindexRepo = getEnvironment().getRequest().getParameter(REPO_NAME);
// Are we allowed to re-index this repository?
// Only default repositories and the ones listed in the resource configuration are allowed to be re-indexed
boolean allowed = false;
// List default repositories
// Only show them if we're allowed to re-index them
String defaultRepos = getResourceConfigProperty("allow-default-repos");
if("true".equals(defaultRepos)) {
sb.append("<r:repository id=\"yanel_data\">Realm's data repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-identities\">Realm's ac-identities repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-policies\">Realm's ac-policies repository</r:repository>");
sb.append("<r:repository id=\"yanel_res-configs\">Realm's res-configs repository</r:repository>");
}
// List extra repositories from repo configuration
String[] repoIds = getResourceConfigProperties("repository-id");
for(String repoId : repoIds) {
if(repoId != null && !"".equals(repoId)) {
sb.append("<r:repository id=\"");
sb.append(repoId);
sb.append("\">Configured repository with id '");
sb.append(repoId);
sb.append("'</r:repository>");
// Check if repo that should be re-indexed is listed in resource configuration (see property 'repository-id')
if(!allowed && repoId.equals(reindexRepo)) allowed = true;
}
}
// Check if repo that should be re-indexed is default repo
if(!allowed && "true".equals(defaultRepos) &&
("yanel_data".equals(reindexRepo) ||
"yanel_ac-policies".equals(reindexRepo) ||
"yanel_ac-identities".equals(reindexRepo) ||
"yanel_res-configs".equals(reindexRepo))) {
allowed = true;
}
// If it's an extra repo, allowed needs to be set to true
Repository repo = null;
if(allowed) {
try {
repo = getRealm().getRepository(reindexRepo);
} catch(Exception e) {
sb.append("<r:exception>Opening repo failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
}
// Perform re-indexing now
if(repo != null) {
YarepUtil yu = new YarepUtil();
String path = "/";
if (getEnvironment().getRequest().getParameter("path") != null) {
path = getEnvironment().getRequest().getParameter("path"); // INFO: Allows to re-index sub-tree, for example http://127.0.0.1:8080/yanel/yanel-website/re-index.html?repository=yanel_data&path=/en/documentation
}
try {
yu.indexRepository(repo, path);
sb.append("<r:message>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' was successful :-)</r:message>");
sb.append("<r:selected-repository id=\"" + repo.getID() + "\">" + repo.getName() + "</r:selected-repository>");
sb.append("<r:selected-path>" + path + "</r:selected-path>");
} catch(Exception e) {
sb.append("<r:exception>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
} else if(reindexRepo != null) {
sb.append("<r:exception>Repository '" + reindexRepo + "' does either not exist or is not configured in order to be re-indexed.</r:exception>");
}
sb.append("</r:reindex>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
| protected InputStream getContentXML(String viewId) throws Exception {
// Build output document
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<r:reindex xmlns:r=\"");
sb.append(REINDEX_XMLNS);
sb.append("\">");
// Which repo needs to be re-indexed?
String reindexRepo = getEnvironment().getRequest().getParameter(REPO_NAME);
// Are we allowed to re-index this repository?
// Only default repositories and the ones listed in the resource configuration are allowed to be re-indexed
boolean allowed = false;
// List default repositories
// Only show them if we're allowed to re-index them
String defaultRepos = getResourceConfigProperty("allow-default-repos");
if("true".equals(defaultRepos)) {
sb.append("<r:repository id=\"yanel_data\">Realm's data repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-identities\">Realm's ac-identities repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-policies\">Realm's ac-policies repository</r:repository>");
sb.append("<r:repository id=\"yanel_res-configs\">Realm's res-configs repository</r:repository>");
}
// List extra repositories from repo configuration
String[] repoIds = getResourceConfigProperties("repository-id");
for(String repoId : repoIds) {
if(repoId != null && !"".equals(repoId)) {
sb.append("<r:repository id=\"");
sb.append(repoId);
sb.append("\">Configured repository with id '");
sb.append(repoId);
sb.append("'</r:repository>");
// Check if repo that should be re-indexed is listed in resource configuration (see property 'repository-id')
if(!allowed && repoId.equals(reindexRepo)) allowed = true;
}
}
// Check if repo that should be re-indexed is default repo
if(!allowed && "true".equals(defaultRepos) &&
("yanel_data".equals(reindexRepo) ||
"yanel_ac-policies".equals(reindexRepo) ||
"yanel_ac-identities".equals(reindexRepo) ||
"yanel_res-configs".equals(reindexRepo))) {
allowed = true;
}
// If it's an extra repo, allowed needs to be set to true
Repository repo = null;
if(allowed) {
try {
repo = getRealm().getRepository(reindexRepo);
} catch(Exception e) {
sb.append("<r:exception>Opening repo failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
}
// Perform re-indexing now
if(repo != null) {
YarepUtil yu = new YarepUtil();
String path = "/";
if (getEnvironment().getRequest().getParameter("path") != null) {
path = getEnvironment().getRequest().getParameter("path"); // INFO: Allows to re-index sub-tree, for example http://127.0.0.1:8080/yanel/yanel-website/re-index.html?repository=yanel_data&path=/en/documentation
}
try {
yu.indexRepository(repo, path);
sb.append("<r:message>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' was successful :-)</r:message>");
sb.append("<r:selected-repository id=\"" + reindexRepo + "\">" + repo.getName() + "</r:selected-repository>");
sb.append("<r:selected-path>" + path + "</r:selected-path>");
} catch(Exception e) {
sb.append("<r:exception>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
} else if(reindexRepo != null) {
sb.append("<r:exception>Repository '" + reindexRepo + "' does either not exist or is not configured in order to be re-indexed.</r:exception>");
}
sb.append("</r:reindex>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
|
diff --git a/common/logisticspipes/proxy/specialinventoryhandler/QuantumChestHandler.java b/common/logisticspipes/proxy/specialinventoryhandler/QuantumChestHandler.java
index b394f6c4..acc8d8de 100644
--- a/common/logisticspipes/proxy/specialinventoryhandler/QuantumChestHandler.java
+++ b/common/logisticspipes/proxy/specialinventoryhandler/QuantumChestHandler.java
@@ -1,142 +1,145 @@
package logisticspipes.proxy.specialinventoryhandler;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import logisticspipes.interfaces.ISpecialInventoryHandler;
import logisticspipes.utils.ItemIdentifier;
import net.minecraft.src.IInventory;
import net.minecraft.src.ItemStack;
import net.minecraft.src.TileEntity;
public class QuantumChestHandler implements ISpecialInventoryHandler {
Class<?> GT_TileEntity_Quantumchest;
Field mItemCount;
Method getStoredItemData;
@Override
public boolean init() {
try {
GT_TileEntity_Quantumchest = Class.forName("gregtechmod.common.tileentities.GT_TileEntity_Quantumchest");
mItemCount = GT_TileEntity_Quantumchest.getDeclaredField("mItemCount");
mItemCount.setAccessible(true);
getStoredItemData = GT_TileEntity_Quantumchest.getDeclaredMethod("getStoredItemData", new Class[]{});
return true;
} catch(Exception e) {
return false;
}
}
@Override
public boolean isType(TileEntity tile) {
return GT_TileEntity_Quantumchest.isAssignableFrom(tile.getClass());
}
@Override
public HashMap<ItemIdentifier, Integer> getItemsAndCount(TileEntity tile) {
HashMap<ItemIdentifier, Integer> map = new HashMap<ItemIdentifier, Integer>();
ItemStack[] data = new ItemStack[]{};
try {
data = (ItemStack[]) getStoredItemData.invoke(tile, new Object[]{});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
ItemStack stack = ((IInventory)tile).getStackInSlot(1);
if(data.length < 1 || data[0] == null || data[0].itemID < 1) return map;
+ if(stack == null || stack.itemID < 1) return map;
ItemIdentifier dataIdent = ItemIdentifier.get(data[0]);
ItemIdentifier stackIdent = ItemIdentifier.get(stack);
if(dataIdent != stackIdent) {
if(data[0].stackSize != 0) map.put(dataIdent, data[0].stackSize);
if(stack.stackSize != 0) map.put(stackIdent, stack.stackSize);
} else {
map.put(dataIdent, data[0].stackSize + stack.stackSize - 1);
}
return map;
}
@Override
public int roomForItem(TileEntity tile, ItemIdentifier item) {
int result = Integer.MAX_VALUE - 128;
ItemStack[] data = new ItemStack[]{};
try {
data = (ItemStack[]) getStoredItemData.invoke(tile, new Object[]{});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if(data.length < 1 || data[0] == null || data[0].itemID < 1) return result;
ItemStack stack = ((IInventory)tile).getStackInSlot(1);
+ if(stack == null || stack.itemID < 1) return result;
ItemIdentifier dataIdent = ItemIdentifier.get(data[0]);
ItemIdentifier stackIdent = ItemIdentifier.get(stack);
if(item == dataIdent || item == stackIdent) {
return result - (data[0].stackSize + stack.stackSize);
} else {
return 0;
}
}
@Override
public ItemStack getSingleItem(TileEntity tile, ItemIdentifier item) {
ItemStack[] data = new ItemStack[]{};
try {
data = (ItemStack[]) getStoredItemData.invoke(tile, new Object[]{});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if(data.length < 1 || data[0] == null || data[0].itemID < 1) return null;
ItemStack stack = ((IInventory)tile).getStackInSlot(1);
+ if(stack == null || stack.itemID < 1) return null;
ItemIdentifier dataIdent = ItemIdentifier.get(data[0]);
ItemIdentifier stackIdent = ItemIdentifier.get(stack);
if(stackIdent == item && stack.stackSize > 1) {
stack.stackSize--;
return stackIdent.makeNormalStack(1);
}
if(dataIdent == item && data[0].stackSize > 0) {
try {
mItemCount.set(tile, data[0].stackSize - 1);
return dataIdent.makeNormalStack(1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if(stackIdent == item && stack.stackSize > 0) {
stack.stackSize--;
return stackIdent.makeNormalStack(1);
}
return null;
}
@Override
public boolean containsItem(TileEntity tile, ItemIdentifier item) {
ItemStack[] data = new ItemStack[]{};
try {
data = (ItemStack[]) getStoredItemData.invoke(tile, new Object[]{});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if(data.length < 1 || data[0] == null || data[0].itemID < 1) return false;
ItemIdentifier dataIdent = ItemIdentifier.get(data[0]);
return item == dataIdent;
}
}
| false | false | null | null |
diff --git a/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java b/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java
index d78c0f403..61a85eb04 100644
--- a/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java
+++ b/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java
@@ -1,188 +1,192 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* 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.acegisecurity.providers.ldap;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.ldap.LdapUserInfo;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.naming.directory.Attributes;
/**
* An {@link org.acegisecurity.providers.AuthenticationProvider} implementation that
* provides integration with an LDAP server.
*
* <p>
* There are many ways in which an LDAP directory can be configured so this class
* delegates most of its responsibilites to two separate strategy interfaces,
* {@link LdapAuthenticator} and {@link LdapAuthoritiesPopulator}.
* </p>
*
* <h3>LdapAuthenticator</h3>
*
* This interface is responsible for performing the user authentication and retrieving
* the user's information from the directory. Example implementations are
* {@link org.acegisecurity.providers.ldap.authenticator.BindAuthenticator BindAuthenticator}
* which authenticates the user by "binding" as that user, and
* {@link org.acegisecurity.providers.ldap.authenticator.PasswordComparisonAuthenticator PasswordComparisonAuthenticator}
* which performs a comparison of the supplied password with the value stored in the directory,
* either by retrieving the password or performing an LDAP "compare" operation.
* <p>
* The task of retrieving the user attributes is delegated to the authenticator
* because the permissions on the attributes may depend on the type of authentication
* being used; for example, if binding as the user, it may be necessary to read them
* with the user's own permissions (using the same context used for the bind operation).
* </p>
*
* <h3>LdapAuthoritiesPopulator</h3>
*
* Once the user has been authenticated, this interface is called to obtain the set of
* granted authorities for the user. The
* {@link org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator DefaultLdapAuthoritiesPopulator}
* can be configured to obtain user role information from the user's attributes and/or to perform
* a search for "groups" that the user is a member of and map these to roles.
* <p>
* A custom implementation could obtain the roles from a completely different source,
* for example from a database.
* </p>
*
* <h3>Configuration</h3>
* A simple configuration might be as follows:
* <pre>
* <bean id="initialDirContextFactory" class="org.acegisecurity.providers.ldap.DefaultInitialDirContextFactory">
* <constructor-arg value="ldap://monkeymachine:389/dc=acegisecurity,dc=org"/>
* <property name="managerDn"><value>cn=manager,dc=acegisecurity,dc=org</value></property>
* <property name="managerPassword"><value>password</value></property>
* </bean>
*
* <bean id="ldapAuthProvider" class="org.acegisecurity.providers.ldap.LdapAuthenticationProvider">
* <constructor-arg>
* <bean class="org.acegisecurity.providers.ldap.authenticator.BindAuthenticator">
* <constructor-arg><ref local="initialDirContextFactory"/></constructor-arg>
* <property name="userDnPatterns"><list><value>uid={0},ou=people</value></list></property>
* </bean>
* </constructor-arg>
* <constructor-arg>
* <bean class="org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator">
* <constructor-arg><ref local="initialDirContextFactory"/></constructor-arg>
* <constructor-arg><value>ou=groups</value></constructor-arg>
* <property name="groupRoleAttribute"><value>ou</value></property>
* </bean>
* </constructor-arg>
* </bean>
* </pre>
* <p>
* This would set up the provider to access an LDAP server with URL
* <tt>ldap://monkeymachine:389/dc=acegisecurity,dc=org</tt>. Authentication will be performed by
* attempting to bind with the DN <tt>uid=<user-login-name>,ou=people,dc=acegisecurity,dc=org</tt>.
* After successful authentication, roles will be assigned to the user by searching under the DN
* <tt>ou=groups,dc=acegisecurity,dc=org</tt> with the default filter <tt>(member=<user's-DN>)</tt>.
* The role name will be taken from the "ou" attribute of each match.
* </p>
*
* @see org.acegisecurity.providers.ldap.authenticator.BindAuthenticator
* @see org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator
*
* @author Luke Taylor
* @version $Id$
*/
public class LdapAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
//~ Static fields/initializers =============================================
private static final Log logger = LogFactory.getLog(LdapAuthenticationProvider.class);
//~ Instance fields ========================================================
private LdapAuthenticator authenticator;
private LdapAuthoritiesPopulator authoritiesPopulator;
//~ Constructors ===========================================================
public LdapAuthenticationProvider(LdapAuthenticator authenticator,
LdapAuthoritiesPopulator authoritiesPopulator) {
Assert.notNull(authenticator, "An LdapAuthenticator must be supplied");
Assert.notNull(authoritiesPopulator, "An LdapAuthoritiesPopulator must be supplied");
this.authenticator = authenticator;
this.authoritiesPopulator = authoritiesPopulator;
// TODO: Check that the role attributes specified for the populator will be retrieved
// by the authenticator. If not, add them to the authenticator's list and log a
// warning.
}
//~ Methods ================================================================
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
}
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
if(!StringUtils.hasLength(username)) {
throw new BadCredentialsException(messages.getMessage(
"LdapAuthenticationProvider.emptyUsername",
"Empty Username"));
}
if (logger.isDebugEnabled()) {
logger.debug("Retrieving user " + username);
}
String password = (String)authentication.getCredentials();
Assert.notNull(password, "Null password was supplied in authentication token");
LdapUserInfo ldapUser = authenticator.authenticate(username, password);
return createUserDetails(username, password, ldapUser.getDn(), ldapUser.getAttributes());
}
/**
* Creates the user final <tt>UserDetails</tt> object that will be returned by the provider
* once the user has been authenticated.
* <p>
* The <tt>LdapAuthoritiesPopulator</tt> will be used to create the granted authorites for the
* user.
* </p>
* <p>
* Can be overridden to customize the mapping of user attributes to additional user information.
* </p>
*
* @param username The user login, as passed to the provider
* @param password The submitted password
* @param userDn The DN of the user in the Ldap system.
* @param attributes The user attributes retrieved from the Ldap system.
* @return The UserDetails for the successfully authenticated user.
*/
protected UserDetails createUserDetails(String username, String password, String userDn, Attributes attributes) {
return new User(username, password, true, true, true, true,
authoritiesPopulator.getGrantedAuthorities(username, userDn, attributes));
}
+
+ protected LdapAuthoritiesPopulator getAuthoritiesPoulator() {
+ return authoritiesPopulator;
+ }
}
| true | false | null | null |
diff --git a/jackrabbit-tests/src/test/java/org/modeshape/JRPerformanceTest.java b/jackrabbit-tests/src/test/java/org/modeshape/JRPerformanceTest.java
index e2ff23b..bc8e9f7 100644
--- a/jackrabbit-tests/src/test/java/org/modeshape/JRPerformanceTest.java
+++ b/jackrabbit-tests/src/test/java/org/modeshape/JRPerformanceTest.java
@@ -1,55 +1,57 @@
/*
* JBoss, Home of Professional Open Source
* Copyright [2011], Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modeshape;
import javax.jcr.SimpleCredentials;
import org.apache.jackrabbit.commons.JcrUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.modeshape.jcr.perftests.PerformanceTestSuiteRunner;
+import org.modeshape.jcr.perftests.report.BarChartReport;
import org.modeshape.jcr.perftests.report.TextFileReport;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Test which runs the performance suite against a Jackrabbit in memory repo.
*
* @author Horia Chiorean
*/
public class JRPerformanceTest {
private PerformanceTestSuiteRunner performanceTestSuiteRunner;
@Before
public void before() {
performanceTestSuiteRunner = new PerformanceTestSuiteRunner();
}
@Test
public void testJackrabbitInMemoryRepo() throws Exception {
Map<String, URL> parameters = new HashMap<String, URL>();
parameters.put(JcrUtils.REPOSITORY_URI, getClass().getClassLoader().getResource("./"));
performanceTestSuiteRunner.runPerformanceTests(parameters, new SimpleCredentials("test", "test".toCharArray()));
}
@After
public void after() throws Exception {
performanceTestSuiteRunner.generateTestReport(new TextFileReport());
+ performanceTestSuiteRunner.generateTestReport(new BarChartReport());
}
}
diff --git a/modeshape-3.x-tests/src/test/java/org/modeshape/ModeShape3xPerformanceTest.java b/modeshape-3.x-tests/src/test/java/org/modeshape/ModeShape3xPerformanceTest.java
index c023050..4779157 100644
--- a/modeshape-3.x-tests/src/test/java/org/modeshape/ModeShape3xPerformanceTest.java
+++ b/modeshape-3.x-tests/src/test/java/org/modeshape/ModeShape3xPerformanceTest.java
@@ -1,54 +1,56 @@
/*
* JBoss, Home of Professional Open Source
* Copyright [2011], Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modeshape;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.modeshape.jcr.JcrRepositoryFactory;
import org.modeshape.jcr.perftests.PerformanceTestSuiteRunner;
+import org.modeshape.jcr.perftests.report.BarChartReport;
import org.modeshape.jcr.perftests.report.TextFileReport;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Runs the performance tests against a Modeshape 3.x repo.
*
* @author Horia Chiorean
*/
public class ModeShape3xPerformanceTest {
private PerformanceTestSuiteRunner performanceTestSuiteRunner;
@Before
public void before() {
performanceTestSuiteRunner = new PerformanceTestSuiteRunner();
}
@Test
public void testModeShapeInMemory() throws Exception {
Map<String, URL> parameters = new HashMap<String, URL>();
parameters.put(JcrRepositoryFactory.URL, getClass().getClassLoader().getResource("configRepository.json"));
performanceTestSuiteRunner.runPerformanceTests(parameters, null);
}
@After
public void after() throws Exception {
performanceTestSuiteRunner.generateTestReport(new TextFileReport());
+ performanceTestSuiteRunner.generateTestReport(new BarChartReport());
}
}
| false | false | null | null |
diff --git a/src/main/java/org/mythtv/services/utils/ArticleCleaner.java b/src/main/java/org/mythtv/services/utils/ArticleCleaner.java
index 581420f..9ea0f43 100644
--- a/src/main/java/org/mythtv/services/utils/ArticleCleaner.java
+++ b/src/main/java/org/mythtv/services/utils/ArticleCleaner.java
@@ -1,50 +1,50 @@
/**
* This file is part of MythTV for Android
*
* MythTV for Android is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MythTV for Android is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MythTV for Android. If not, see <http://www.gnu.org/licenses/>.
*
* This software can be found at <https://github.com/MythTV-Android/mythtv-for-android/>
*
*/
package org.mythtv.services.utils;
/**
* @author Daniel Frey
*
*/
public class ArticleCleaner {
- private static final String[] ARTICLES = new String[] { "THE", "AN", "A " };
+ private static final String[] ARTICLES = new String[] { "THE", "AN ", "A " };
public static String clean( String text ) {
if( null != text && !"".equals( text ) ) {
String temp = text.toUpperCase();
// iterate over all articles
for( String article : ARTICLES ) {
if( temp.startsWith( article ) ) {
int len = article.length();
// remove the length of the article from the beginning and trim any remaining whitespace from the original text
text = text.substring( len ).trim();
}
}
}
return text;
}
}
| true | false | null | null |
diff --git a/src/web/org/openmrs/web/controller/user/UserListController.java b/src/web/org/openmrs/web/controller/user/UserListController.java
index 0c1529da..4c77ee60 100644
--- a/src/web/org/openmrs/web/controller/user/UserListController.java
+++ b/src/web/org/openmrs/web/controller/user/UserListController.java
@@ -1,85 +1,85 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.user;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.User;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
public class UserListController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
* Allows for Integers to be used as values in input tags. Normally, only strings and lists are
* expected
*
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
* org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
}
/**
* The onSubmit function receives the form/command object that was modified by the input form
* and saves it to the db
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
return new ModelAndView(new RedirectView(getSuccessView()));
}
/**
* This is called prior to displaying a form for the first time. It tells Spring the
* form/command object to load into the request
*
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
*/
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
//default empty Object
List<User> userList = new Vector<User>();
//only fill the Object is the user has authenticated properly
if (Context.isAuthenticated()) {
- UserService us = Context.getUserService();
- userList = us.getAllUsers();
+ //UserService us = Context.getUserService();
+ //userList = us.getAllUsers();
}
return userList;
}
}
| true | true | protected Object formBackingObject(HttpServletRequest request) throws ServletException {
//default empty Object
List<User> userList = new Vector<User>();
//only fill the Object is the user has authenticated properly
if (Context.isAuthenticated()) {
UserService us = Context.getUserService();
userList = us.getAllUsers();
}
return userList;
}
| protected Object formBackingObject(HttpServletRequest request) throws ServletException {
//default empty Object
List<User> userList = new Vector<User>();
//only fill the Object is the user has authenticated properly
if (Context.isAuthenticated()) {
//UserService us = Context.getUserService();
//userList = us.getAllUsers();
}
return userList;
}
|
diff --git a/src/com/ACM/binarycalculator/CalculatorHexFragment.java b/src/com/ACM/binarycalculator/CalculatorHexFragment.java
index 373a5c6..cc056c9 100644
--- a/src/com/ACM/binarycalculator/CalculatorHexFragment.java
+++ b/src/com/ACM/binarycalculator/CalculatorHexFragment.java
@@ -1,782 +1,794 @@
package com.ACM.binarycalculator;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Locale;
import java.util.StringTokenizer;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
/**
*
* @author James Van Gaasbeck, ACM at UCF <[email protected]>
*
*
*/
public class CalculatorHexFragment extends SherlockFragment {
// this is a tag used for debugging purposes
// private static final String TAG = "CalculatorHexFragment";
// string constant for saving our workingTextViewText
private static final String KEY_WORKINGTEXTVIEW_STRING = "workingTextString";
private static final int VIEW_NUMBER = 1;
// the radix number (base-number) to be used when parsing the string.
private static final int VIEWS_RADIX = 16;
// these are our variables
// TextView mComputeTextView;
TextView mWorkingTextView;
private String mCurrentWorkingText;
private String mSavedStateString;
String mDataFromActivity;
FragmentDataPasser mCallback;
public static int numberOfOpenParenthesis;
public static int numberOfClosedParenthesis;
private ArrayList<String> mExpressions;
@Override
// we need to inflate our View so let's grab all the View IDs and inflate
// them.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// we need to make a view instance from our layout.
View v = inflater.inflate(R.layout.fragment_calculator_hex, container,
false);
// get the textViews by id, notice we have to reference them via the
// view instance we just created.
mWorkingTextView = (TextView) v
.findViewById(R.id.fragment_calculator_hex_workingTextView);
// initialize variables that need to be
mCurrentWorkingText = new String("");
mSavedStateString = new String("");
mExpressions = new ArrayList<String>();
// if the we saved something away, grab it!
if (savedInstanceState != null) {
mSavedStateString = savedInstanceState
.getString(KEY_WORKINGTEXTVIEW_STRING);
// We need to check that we aren't accessing null data or else it
// will crash upon turning the screen.
if (mSavedStateString == null) {
mSavedStateString = new String("");
}
// set the text to be what we saved away and just now retrieved.
mWorkingTextView.setText(mSavedStateString);
}
View.OnClickListener genericNumberButtonListener = new View.OnClickListener() {
// when someone clicks a button that isn't "special" we are going to
// add it to the workingTextView
@Override
public void onClick(View v) {
TextView textView = (TextView) v;
// mCurrentWorkingText = mWorkingTextView.getText().toString();
String textFromButton = textView.getText().toString();
if (mCurrentWorkingText.length() == 0) {
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = textFromButton;
} else {
if (mCurrentWorkingText.length() <= 47) {
StringTokenizer toke = new StringTokenizer(
mCurrentWorkingText.concat(textFromButton),
"-+/x)( ");
String numberLengthTest = null;
while (toke.hasMoreTokens()) {
numberLengthTest = (String) toke.nextToken();
}
if (numberLengthTest.length() > 11) {
return;
}
// if the working TextView isn't zero we need to append
// the
// textFromButton to what is already there.
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = mCurrentWorkingText
.concat(textFromButton);
}
}
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
};
View.OnClickListener genericOperatorButtonListener = new View.OnClickListener() {
// when someone clicks an operator "/x+" NOT "-", "-" is special so
// it gets it's own listener. We can't have expressions with
// adjacent operators "/+x" nor can we start with them.
// We also cannot have a "." followed by an operator "+/x"
// Nor can we have a "-" followed by an operator.
@Override
public void onClick(View v) {
TextView textView = (TextView) v;
// mCurrentWorkingText = mWorkingTextView.getText().toString();
String textFromButton = textView.getText().toString();
// see if the workingTextView is empty, if so DON'T add the
// operator
if (mCurrentWorkingText.length() == 0) {
// do NOTHING because we can't start an expression with
// "+/x" but we can with "-" which is why we are going to
// give the minus/negative sign it's own listener.
} else {
if (mCurrentWorkingText.length() <= 47) {
// we can't have adjacent "+/x" nor can we have a "."
// followed by "+/x"
if (mCurrentWorkingText.endsWith("+ ")
|| mCurrentWorkingText.endsWith("x ")
|| mCurrentWorkingText.endsWith("/ ")
|| mCurrentWorkingText.endsWith(".")
|| mCurrentWorkingText.endsWith("- ")
|| mCurrentWorkingText.endsWith("-")
|| mCurrentWorkingText.endsWith("(")) {
// do nothing because we can't have multiple
// adjacent
// operators
} else {
// add it on up!
mWorkingTextView.setText(mWorkingTextView.getText()
.toString()
.concat(" " + textFromButton + " "));
mCurrentWorkingText = mCurrentWorkingText
.concat(" " + textFromButton + " ");
}
}
}
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
};
View.OnClickListener openParenthesisButtonListener = new View.OnClickListener() {
// We can't have a "." followed by a "("
// We also can't have something like this "6)"
@Override
public void onClick(View v) {
TextView textView = (TextView) v;
// mCurrentWorkingText = mWorkingTextView.getText().toString();
String textFromButton = textView.getText().toString();
if (mCurrentWorkingText.length() == 0) {
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = mCurrentWorkingText
.concat(textFromButton);
CalculatorDecimalFragment.numberOfOpenParenthesis++;
CalculatorBinaryFragment.numberOfOpenParenthesis++;
CalculatorHexFragment.numberOfOpenParenthesis++;
CalculatorOctalFragment.numberOfOpenParenthesis++;
} else {
if (mCurrentWorkingText.endsWith(".")) {
// do nothing
} else {
if (mCurrentWorkingText.length() <= 47) {
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = mCurrentWorkingText
.concat(textFromButton);
CalculatorDecimalFragment.numberOfOpenParenthesis++;
CalculatorBinaryFragment.numberOfOpenParenthesis++;
CalculatorHexFragment.numberOfOpenParenthesis++;
CalculatorOctalFragment.numberOfOpenParenthesis++;
}
}
}
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
};
View.OnClickListener closeParenthesisButtonListener = new View.OnClickListener() {
// We can't have any of these "./+-x" followed by a ")" nor can we
// have something like this "()"
// We also can't have something like this "6)" nor something like
// "(4x4)9)"
@Override
public void onClick(View v) {
TextView textView = (TextView) v;
// mCurrentWorkingText = mWorkingTextView.getText().toString();
String textFromButton = textView.getText().toString();
if (mCurrentWorkingText.length() == 0) {
// do nothing we can't start with ")"
} else {
if (mCurrentWorkingText.length() <= 47) {
if (((mCurrentWorkingText.endsWith(".")
|| mCurrentWorkingText.endsWith("/ ")
|| mCurrentWorkingText.endsWith("x ")
|| mCurrentWorkingText.endsWith("+ ")
|| mCurrentWorkingText.endsWith("- ")
|| mCurrentWorkingText.endsWith("-") || mCurrentWorkingText
.endsWith("(")))
|| numberOfClosedParenthesis >= numberOfOpenParenthesis) {
// do nothing
} else {
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = mCurrentWorkingText
.concat(textFromButton);
CalculatorBinaryFragment.numberOfClosedParenthesis++;
CalculatorDecimalFragment.numberOfClosedParenthesis++;
CalculatorOctalFragment.numberOfClosedParenthesis++;
CalculatorHexFragment.numberOfClosedParenthesis++;
}
}
}
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
};
View.OnClickListener genericMinusButtonListener = new View.OnClickListener() {
// we can't have more than 2 adjacent "-"
// we also can't have something like this ".-3"
// No cases like this "--3" BUT we can have "5--3"
// No cases like this "(--3)
@Override
public void onClick(View v) {
TextView textView = (TextView) v;
// mCurrentWorkingText = mWorkingTextView.getText().toString();
String textFromButton = textView.getText().toString();
// see if the workingTextView is empty
if (mCurrentWorkingText.length() == 0) {
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = textFromButton;
} else if (mCurrentWorkingText.length() == 1
&& mCurrentWorkingText.endsWith("-")) {
// do nothing so we don't start out with something like this
// "--2"
} else {
if (mCurrentWorkingText.length() <= 47) {
// we can't have more than 2 adjacent '-'. So get the
// last
// two char's and check if it's "--"
if (mCurrentWorkingText.endsWith(".")
|| mCurrentWorkingText.endsWith("--")
|| mCurrentWorkingText.endsWith("(-")) {
// do nothing because we can't have more than 2
// adjacent minus's
} else {
// otherwise, add it to the view
if (mCurrentWorkingText.endsWith("0")
|| mCurrentWorkingText.endsWith("1")
|| mCurrentWorkingText.endsWith("2")
|| mCurrentWorkingText.endsWith("3")
|| mCurrentWorkingText.endsWith("4")
|| mCurrentWorkingText.endsWith("5")
|| mCurrentWorkingText.endsWith("6")
|| mCurrentWorkingText.endsWith("7")
|| mCurrentWorkingText.endsWith("8")
|| mCurrentWorkingText.endsWith("9")
|| mCurrentWorkingText.endsWith("A")
|| mCurrentWorkingText.endsWith("B")
|| mCurrentWorkingText.endsWith("C")
|| mCurrentWorkingText.endsWith("D")
|| mCurrentWorkingText.endsWith("E")
|| mCurrentWorkingText.endsWith("F")) {
mWorkingTextView.setText(mWorkingTextView
.getText().toString()
.concat(" " + textFromButton + " "));
mCurrentWorkingText = mCurrentWorkingText
.concat(" " + textFromButton + " ");
} else {
mWorkingTextView.setText(mWorkingTextView
.getText().toString()
.concat(textFromButton));
mCurrentWorkingText = mCurrentWorkingText
.concat(textFromButton);
}
}
}
}
// need to pass data to our call back so all fragments can
// be
// updated with the new workingTextView
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
};
View.OnClickListener backspaceButtonListener = new View.OnClickListener() {
// remove the last thing to be inputed into the workingTextView,
// also update the post fix stacks accordingly?
@Override
public void onClick(View v) {
// need to check if the view has anything in it, because if it
// doesn't the app will crash when trying to change a null
// string.
if (mCurrentWorkingText != null) {
if (mCurrentWorkingText.length() != 0) {
if (mCurrentWorkingText.endsWith(")")) {
CalculatorDecimalFragment.numberOfClosedParenthesis--;
CalculatorBinaryFragment.numberOfClosedParenthesis--;
CalculatorHexFragment.numberOfClosedParenthesis--;
CalculatorOctalFragment.numberOfClosedParenthesis--;
} else if (mCurrentWorkingText.endsWith("(")) {
CalculatorDecimalFragment.numberOfOpenParenthesis--;
CalculatorBinaryFragment.numberOfOpenParenthesis--;
CalculatorHexFragment.numberOfOpenParenthesis--;
CalculatorOctalFragment.numberOfOpenParenthesis--;
}
// we need to delete the spaces around the operators
// also, not just the last char added to the
// workingTextView
if (mCurrentWorkingText.endsWith(" + ")
|| mCurrentWorkingText.endsWith(" - ")
|| mCurrentWorkingText.endsWith(" x ")
|| mCurrentWorkingText.endsWith(" / ")) {
// this deletes the last three char's
mCurrentWorkingText = mCurrentWorkingText
.substring(0,
mCurrentWorkingText.length() - 3);
mWorkingTextView.setText(mCurrentWorkingText);
} else {
// if it's not an operator with spaces around it,
// just delete the last char
mCurrentWorkingText = mCurrentWorkingText
.substring(0,
mCurrentWorkingText.length() - 1);
mWorkingTextView
.setText(mWorkingTextView
.getText()
.toString()
.substring(
0,
mWorkingTextView.length() - 1));
}
}
}
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
};
// get a reference to our TableLayout XML
TableLayout tableLayout = (TableLayout) v
.findViewById(R.id.fragment_calculator_hex_tableLayout);
// get a reference to the first (topmost) row so we can set the clear
// all button manually, because it was annoying trying to work it in to
// the for loop
TableRow firstRow = (TableRow) tableLayout.getChildAt(0);
// the clear all button was decided to be the third button in the
Button open = (Button) firstRow.getChildAt(0);
open.setText("(");
open.setOnClickListener(openParenthesisButtonListener);
Button close = (Button) firstRow.getChildAt(1);
close.setText(")");
close.setOnClickListener(closeParenthesisButtonListener);
// topmost row
Button clearAllButton = (Button) firstRow.getChildAt(2);
clearAllButton.setText("Clear All");
clearAllButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// clear all the text in the working textView, AND maybe the
// computed textView as well?
// Also, might want to clear out the post fix expression stack
mWorkingTextView.setText("");
mCurrentWorkingText = new String("");
mExpressions = new ArrayList<String>();
// update the Static variable in our activity so we can use it
// as a fragment argument
// mComputeTextView.setText("");
CalculatorDecimalFragment.numberOfOpenParenthesis = 0;
CalculatorBinaryFragment.numberOfOpenParenthesis = 0;
CalculatorHexFragment.numberOfOpenParenthesis = 0;
CalculatorOctalFragment.numberOfOpenParenthesis = 0;
CalculatorDecimalFragment.numberOfClosedParenthesis = 0;
CalculatorBinaryFragment.numberOfClosedParenthesis = 0;
CalculatorHexFragment.numberOfClosedParenthesis = 0;
CalculatorOctalFragment.numberOfClosedParenthesis = 0;
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
});
ImageButton backspaceButton = (ImageButton) firstRow.getChildAt(3);
backspaceButton.setOnClickListener(backspaceButtonListener);
// get a reference to the second row of the table (AND, OR, NAND)
TableRow secondRow = (TableRow) tableLayout.getChildAt(1);
Button dButton = (Button) secondRow.getChildAt(0);
dButton.setText("D");
dButton.setOnClickListener(genericNumberButtonListener);
Button eButton = (Button) secondRow.getChildAt(1);
eButton.setText("E");
eButton.setOnClickListener(genericNumberButtonListener);
Button fButton = (Button) secondRow.getChildAt(2);
fButton.setText("F");
fButton.setOnClickListener(genericNumberButtonListener);
TableRow thirdRow = (TableRow) tableLayout.getChildAt(2);
// the NOR button
Button aButton = (Button) thirdRow.getChildAt(0);
aButton.setText("A");
aButton.setOnClickListener(genericNumberButtonListener);
// XOR button
Button bButton = (Button) thirdRow.getChildAt(1);
bButton.setText("B");
bButton.setOnClickListener(genericNumberButtonListener);
// XNOR button
Button cButton = (Button) thirdRow.getChildAt(2);
cButton.setText("C");
cButton.setOnClickListener(genericNumberButtonListener);
TableRow fourthRow = (TableRow) tableLayout.getChildAt(3);
// button '1'
Button sevenButton = (Button) fourthRow.getChildAt(0);
sevenButton.setText("7");
sevenButton.setOnClickListener(genericNumberButtonListener);
// bitwise shift Left button
Button eightButton = (Button) fourthRow.getChildAt(1);
eightButton.setText("8");
eightButton.setOnClickListener(genericNumberButtonListener);
// bitwise shift Right button
Button nineButton = (Button) fourthRow.getChildAt(2);
nineButton.setText("9");
nineButton.setOnClickListener(genericNumberButtonListener);
Button divideButt = (Button) fourthRow.getChildAt(3);
divideButt.setText("/");
divideButt.setOnClickListener(genericOperatorButtonListener);
// now we need to get the last row of buttons and get them to the
// screen.
TableRow fifthRow = (TableRow) tableLayout.getChildAt(4);
// set the decimal button
Button fourButton = (Button) fifthRow.getChildAt(0);
fourButton.setText("4");
fourButton.setOnClickListener(genericNumberButtonListener);
// set the zero button
Button fiveButton = (Button) fifthRow.getChildAt(1);
fiveButton.setText("5");
fiveButton.setOnClickListener(genericNumberButtonListener);
// set the plus button
Button sixButton = (Button) fifthRow.getChildAt(2);
sixButton.setText("6");
sixButton.setOnClickListener(genericNumberButtonListener);
// set the equals button, it will have it's own separate listener to
// compute the inputed value
Button multButt = (Button) fifthRow.getChildAt(3);
multButt.setText("x");
multButt.setOnClickListener(genericOperatorButtonListener);
TableRow sixthRow = (TableRow) tableLayout.getChildAt(5);
Button oneButton = (Button) sixthRow.getChildAt(0);
oneButton.setText("1");
oneButton.setOnClickListener(genericNumberButtonListener);
Button twoButton = (Button) sixthRow.getChildAt(1);
twoButton.setText("2");
twoButton.setOnClickListener(genericNumberButtonListener);
Button threeButton = (Button) sixthRow.getChildAt(2);
threeButton.setText("3");
threeButton.setOnClickListener(genericNumberButtonListener);
Button minusButt = (Button) sixthRow.getChildAt(3);
minusButt.setText("-");
minusButt.setOnClickListener(genericMinusButtonListener);
TableRow lastRow = (TableRow) tableLayout.getChildAt(6);
Button equalsButton = (Button) lastRow.getChildAt(0);
equalsButton.setText("=");
equalsButton.setOnClickListener(new OnClickListener() {
// EQUALS button on click listener
@Override
public void onClick(View v) {
// Do arithmetic
// Now we need to display the answer on a completely new line
// store the answer in a variable then add that variable to the
// textView and add a new line because the next expression will
// start on a newline, also add the answer to the 'mExpressions"
// list with the newLine characters
mExpressions.add(mCurrentWorkingText);
String fourtyTwo = Integer.toHexString(42);
// 42 is obviously not the real answer, just a place holder to
// display
// how the fully functioning app should work. The real computed
// answer should be inserted in it's place
String answer = "\n" + fourtyTwo + "\n";
-
+
mExpressions.add(answer);
mWorkingTextView.setText(mWorkingTextView.getText().toString()
.concat(answer));
mSavedStateString = mWorkingTextView.getText().toString();
-
+
onPassData(mSavedStateString);
-
+
mCurrentWorkingText = new String("");
}
});
Button zeroButton = (Button) lastRow.getChildAt(1);
zeroButton.setText("0");
zeroButton.setOnClickListener(genericNumberButtonListener);
Button decimalPointButton = (Button) lastRow.getChildAt(2);
decimalPointButton.setText(".");
decimalPointButton.setOnClickListener(new OnClickListener() {
// we can't put a "." up there if there has already been one in
// the current token (number)
@Override
public void onClick(View v) {
TextView textView = (TextView) v;
// mCurrentWorkingText = mWorkingTextView.getText().toString();
String textFromButton = textView.getText().toString();
// see if the workingTextView is empty, if so just add the '.'
if (mCurrentWorkingText.length() == 0) {
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = textFromButton;
} else {
if (mCurrentWorkingText.length() <= 47) {
StringTokenizer toke = new StringTokenizer(
mCurrentWorkingText, "+-/x)(", true);
String currentElement = null;
// get the current(last) token(number) so we can test if
// it
// has a '.' in it.
while (toke.hasMoreTokens()) {
currentElement = toke.nextElement().toString();
}
// if the working TextView isn't zero we need to append
// the
// textFromButton to what is already there. AND we need
// to
// check if the current token already has a '.' in it
// because we can't have something like '2..2' or
// 2.2.33'
if (mCurrentWorkingText.endsWith(".")
|| currentElement.contains(".")) {
// do nothing here so we don't end up with
// expressions
// like "2..2" or "2.3.22"
} else {
// otherwise we're all good and just add the ".' up
// there.
mWorkingTextView.setText(mWorkingTextView.getText()
.toString().concat(textFromButton));
mCurrentWorkingText = mCurrentWorkingText
.concat(textFromButton);
}
}
}
mSavedStateString = mWorkingTextView.getText().toString();
onPassData(mSavedStateString);
}
});
Button plusButt = (Button) lastRow.getChildAt(3);
plusButt.setText("+");
plusButt.setOnClickListener(genericOperatorButtonListener);
return v;
}
public static SherlockFragment newInstance() {
CalculatorHexFragment binFrag = new CalculatorHexFragment();
return binFrag;
}
// method to save the state of the application during the activity life
// cycle. This is so we can preserve the values in the textViews upon screen
// rotation.
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Log.i(TAG, "onSaveInstanceState");
outState.putString(KEY_WORKINGTEXTVIEW_STRING, mSavedStateString);
}
// need to make sure the fragment life cycle complies with the
// actionBarSherlock support library
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(getClass().getSimpleName()
+ " must be attached to a SherlockFragmentActivity.");
}
super.onAttach(activity);
// set our dataPasser interface up when the fragment is on the activity
try {
// hook the call back up to the activity it is attached to, should
// do this in a try/catch because the parent activity must implement
// the interface.
mCallback = (FragmentDataPasser) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
activity.toString()
+ " must implement the FragmentDataPasser interface so we can pass data between the fragments.");
}
}
// callback method to send data to the activity so we can then update all
// the fragments
public void onPassData(String dataToBePassed) {
mCallback.onDataPassed(dataToBePassed, VIEW_NUMBER, VIEWS_RADIX);
}
// method to receive the data from the activity/other-fragments and update
// the textViews accordingly
public void updateWorkingTextView(String dataToBePassed, int base) {
if (dataToBePassed.length() != 0) {
StringTokenizer toke = new StringTokenizer(dataToBePassed,
"x+-/)( \n", true);
StringBuilder builder = new StringBuilder();
while (toke.hasMoreElements()) {
String aToken = (String) toke.nextElement().toString();
if (aToken.equals("+") || aToken.equals("x")
|| aToken.equals("-") || aToken.equals("/")
|| aToken.equals("(") || aToken.equals(")")
|| aToken.equals(" ") || aToken.equals("\n")) {
builder.append(aToken);
}
// if our token contains a "." in it then that means that we
// need to do some conversion trickery
else if (aToken.contains(".")) {
if (aToken.endsWith(".")) {
// don't do any conversions when the number is still
// being
// inputed and in the current state of something like
// this
// "5."
return;
}
// split the string around the "." delimiter.
String[] parts = aToken.split("\\.");
StringBuilder tempBuilder = new StringBuilder();
if (aToken.charAt(0) == '.') {
} else {
// add the portion of the number to the left of the
// "."
// to our string this doesn't need any conversion
// nonsense.
tempBuilder.append(Integer.toHexString(Integer
.parseInt(parts[0], base)));
}
// convert the fraction portion
String getRidOfZeroBeforePoint = null;
if (base == 10) {
String fractionWithRadixPoint = "." + parts[1];
String converted = Fractions
.convertFractionPortionFromDecimal(
fractionWithRadixPoint, VIEWS_RADIX);
parts = converted.split("\\.");
tempBuilder.append(".").append(parts[0]);
} else {
getRidOfZeroBeforePoint = Fractions
.convertFractionPortionToDecimal(parts[1], base);
// the conversion returns just the fraction
// portion
// with
// a "0" to the left of the ".", so let's get
// rid of
// that extra zero.
getRidOfZeroBeforePoint = getRidOfZeroBeforePoint
.substring(1, getRidOfZeroBeforePoint.length());
String partsAgain[] = getRidOfZeroBeforePoint
.split("\\.");
String converted = Fractions
.convertFractionPortionFromDecimal(
getRidOfZeroBeforePoint, VIEWS_RADIX);
partsAgain = converted.split("\\.");
tempBuilder.append(".").append(partsAgain[0]);
}
// add that to the string that gets put on the textView
// (this may be excessive) (I wrote this late at night
// so stuff probably got a little weird)
builder.append(tempBuilder.toString());
} else {
BigInteger sizeTestBigInt = new BigInteger(aToken, base);
if (sizeTestBigInt.bitLength() < 64) {
mCurrentWorkingText = Long.toHexString(Long.parseLong(
aToken, base));
builder.append(mCurrentWorkingText);
}
}
- mCurrentWorkingText = builder.toString().toUpperCase(
- Locale.getDefault());
+
+ String[] dontUpperCaseX = builder.toString().split("x");
+ StringBuilder safeUpperCase = new StringBuilder();
+ for (int i = 0; i < dontUpperCaseX.length; i++) {
+ if (i != dontUpperCaseX.length - 1) {
+ safeUpperCase.append(
+ dontUpperCaseX[i].toUpperCase(Locale
+ .getDefault())).append("x");
+ } else {
+ safeUpperCase.append(dontUpperCaseX[i]
+ .toUpperCase(Locale.getDefault()));
+ }
+ }
+ mCurrentWorkingText = safeUpperCase.toString();
mWorkingTextView.setText(mCurrentWorkingText);
mSavedStateString = mWorkingTextView.getText().toString();
}
} else {
mCurrentWorkingText = "";
mWorkingTextView.setText(mCurrentWorkingText);
mSavedStateString = mWorkingTextView.getText().toString();
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/github/athieriot/jtaches/taches/LessCompilerTache.java b/src/main/java/com/github/athieriot/jtaches/taches/LessCompilerTache.java
index 5c51d45..3f30e0b 100644
--- a/src/main/java/com/github/athieriot/jtaches/taches/LessCompilerTache.java
+++ b/src/main/java/com/github/athieriot/jtaches/taches/LessCompilerTache.java
@@ -1,102 +1,102 @@
package com.github.athieriot.jtaches.taches;
import com.github.athieriot.jtaches.taches.internal.ConfiguredTache;
import org.lesscss.LessCompiler;
import org.lesscss.LessException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.security.InvalidParameterException;
import java.util.Collection;
import java.util.Map;
import static com.esotericsoftware.minlog.Log.info;
import static com.github.athieriot.jtaches.command.Configuration.CONFIGURATION_PATH;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.Boolean.parseBoolean;
import static java.nio.file.Files.createDirectories;
import static java.nio.file.Files.delete;
import static java.nio.file.Paths.get;
public class LessCompilerTache extends ConfiguredTache {
public static final String CONFIGURATION_COMPILE_TO = "compileTo";
public static final String CONFIGURATION_MAKE_PATH = "makePath";
public LessCompilerTache(Map<String, String> configuration) {
super(configuration, CONFIGURATION_COMPILE_TO);
}
@Override
protected void additionalValidation(Map<String, String> configuration) throws InvalidParameterException {
super.additionalValidation(configuration);
if(configuration.get(CONFIGURATION_PATH).startsWith(configuration.get(CONFIGURATION_COMPILE_TO))
|| configuration.get(CONFIGURATION_COMPILE_TO).startsWith(configuration.get(CONFIGURATION_PATH))) {
throw new InvalidParameterException("An error occured while creating the task. Incompatibility between Path parameter and CompileTo parameter.");
}
}
@Override
public void onCreate(WatchEvent<?> event) {
if (isLessFile(event)) {
doCompile(event);
}
}
@Override
public void onDelete(WatchEvent<?> event) {
if (isLessFile(event)) {
- Path to = get(getConfiguration().get(CONFIGURATION_COMPILE_TO), resolveFileName(event));
+ Path to = get(getConfiguration().get(CONFIGURATION_COMPILE_TO), resolveFileName(event).replaceAll(".less", ".css"));
try {
info("Deleting file: " + to.toString());
delete(to);
} catch (IOException e) {
info("Unable to delete file: " + e.getMessage(), e);
}
}
}
@Override
public void onModify(WatchEvent<?> event) {
if (isLessFile(event)) {
doCompile(event);
}
}
private String resolveFileName(WatchEvent<?> event) {
return event.context().toString();
}
private void doCompile(WatchEvent<?> event) {
LessCompiler lessCompiler = new LessCompiler();
Path from = get(getConfiguration().get(CONFIGURATION_PATH), resolveFileName(event));
Path to = get(getConfiguration().get(CONFIGURATION_COMPILE_TO), resolveFileName(event).replaceAll(".less", ".css"));
try {
makePathIfWanted(to);
info("Compiling file: " + to.toString());
lessCompiler.compile(from.toFile(), to.toFile());
} catch (IOException e) {
info("Unable to copy file: " + e.getMessage(), e);
} catch (LessException e) {
info("Unable to compile file: " + e.getMessage(), e);
}
}
//CLEANUP: Could be good to handle Boolean as the object and not only via String
private void makePathIfWanted(Path file) throws IOException {
if(!getConfiguration().containsKey(CONFIGURATION_MAKE_PATH)
|| parseBoolean(getConfiguration().get(CONFIGURATION_MAKE_PATH))) {
createDirectories(file.getParent());
}
}
private boolean isLessFile(WatchEvent<?> event) {
return resolveFileName(event).matches(".*less$");
}
}
diff --git a/src/test/java/com/github/athieriot/jtaches/taches/CopyTacheTest.java b/src/test/java/com/github/athieriot/jtaches/taches/CopyTacheTest.java
index efa5037..fb9047d 100644
--- a/src/test/java/com/github/athieriot/jtaches/taches/CopyTacheTest.java
+++ b/src/test/java/com/github/athieriot/jtaches/taches/CopyTacheTest.java
@@ -1,163 +1,163 @@
package com.github.athieriot.jtaches.taches;
import com.github.athieriot.jtaches.Tache;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.StandardWatchEventKinds;
import java.security.InvalidParameterException;
import java.util.Map;
import static com.github.athieriot.jtaches.command.Configuration.CONFIGURATION_PATH;
import static com.github.athieriot.jtaches.taches.CopyTache.CONFIGURATION_COPY_TO;
import static com.github.athieriot.jtaches.taches.CopyTache.CONFIGURATION_MAKE_PATH;
import static com.github.athieriot.jtaches.utils.TestUtils.newWatchEvent;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.io.Files.*;
import static java.nio.file.Paths.get;
import static org.mockito.Mockito.spy;
import static org.testng.Assert.*;
//CLEANUP: This test is not really a beauty
public class CopyTacheTest {
private final Map<String,String> map = newHashMap();
private final File fromTemp = createTempDir();
private final File toTemp = createTempDir();
@BeforeTest
public void setup() {
map.put(CONFIGURATION_PATH, fromTemp.getAbsolutePath());
map.put(CONFIGURATION_COPY_TO, toTemp.getAbsolutePath());
}
@Test
public void copy_tache_must_copy_if_a_file_is_created() throws IOException {
Tache tache = spy(new CopyTache(map));
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.gad");
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, //
get(from.getName()))); //
assertTrue(new File(toTemp + "/" + from.getName()).exists());
}
@Test
public void copy_tache_must_copy_if_a_directory_is_created() throws IOException {
Tache tache = spy(new CopyTache(map));
File from = new File(fromTemp.getAbsolutePath() + "/" + "omagad");
from.mkdir();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, //
get(from.getName()))); //
assertTrue(new File(toTemp + "/" + from.getName()).exists());
assertTrue(new File(toTemp + "/" + from.getName()).isDirectory());
}
@Test
public void copy_tache_must_delete_if_a_file_is_deleted() throws IOException {
Tache tache = spy(new CopyTache(map));
File to = new File(toTemp.getAbsolutePath() + "/" + "oma.gad");
to.createNewFile();
tache.onDelete(newWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, //
get(to.getName()))); //
assertFalse(to.exists());
}
@Test
public void copy_tache_must_copy_if_a_file_is_modified() throws IOException {
Tache tache = spy(new CopyTache(map));
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.gad");
from.createNewFile();
copy(from, new File(toTemp + "/" + from.getName()));
tache.onModify(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
assertTrue(new File(toTemp + "/" + from.getName()).exists());
assertEquals(from.length(), new File(toTemp + "/" + from.getName()).length());
}
@Test
public void copy_tache_if_to_directory_not_exists_must_not_block() throws IOException {
Map<String, String> cloneMap = newHashMap();
cloneMap.putAll(map);
Tache tache = spy(new CopyTache(cloneMap));
- cloneMap.put(CONFIGURATION_COPY_TO, "bullshit");
+ cloneMap.put(CONFIGURATION_COPY_TO, "./target/bullshit");
cloneMap.put(CONFIGURATION_MAKE_PATH, "false");
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.gad");
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
tache.onDelete(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
tache.onModify(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
}
@Test
public void copy_tache_to_a_none_existing_directory_must_create_path_if_option() throws IOException {
Map<String, String> cloneMap = newHashMap();
cloneMap.putAll(map);
Tache tache = spy(new CopyTache(cloneMap));
cloneMap.put(CONFIGURATION_COPY_TO, toTemp + "/truth");
cloneMap.put(CONFIGURATION_MAKE_PATH, "true");
File from = new File(fromTemp.getAbsolutePath() + "/ghost/" + "oma.gad");
createParentDirs(from);
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get("ghost/", from.getName()))); //
assertTrue(new File(toTemp + "/truth/ghost/" + from.getName()).exists());
}
@Test
public void copy_tache_to_a_none_existing_directory_must_NOT_create_path_by_default() throws IOException {
Map<String, String> cloneMap = newHashMap();
cloneMap.putAll(map);
Tache tache = spy(new CopyTache(cloneMap));
cloneMap.put(CONFIGURATION_COPY_TO, toTemp + "/bollocs");
cloneMap.put(CONFIGURATION_MAKE_PATH, "false");
File from = new File(fromTemp.getAbsolutePath() + "/ghost/" + "oma.gad");
createParentDirs(from);
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get("ghost/", from.getName()))); //
assertFalse(new File(toTemp + "/bollocs/ghost/" + from.getName()).exists());
}
@Test(expectedExceptions = InvalidParameterException.class)
public void copy_tache_must_not_create_if_copyTo_include_in_path() {
Map<String, String> bad_map = newHashMap();
bad_map.put(CONFIGURATION_PATH, toTemp + "/un/deux");
bad_map.put(CONFIGURATION_COPY_TO, toTemp + "/un/");
new CopyTache(bad_map);
}
@Test(expectedExceptions = InvalidParameterException.class)
public void copy_tache_must_not_create_if_path_include_in_copyTo() {
Map<String, String> bad_map = newHashMap();
bad_map.put(CONFIGURATION_PATH, toTemp + "/un");
bad_map.put(CONFIGURATION_COPY_TO, toTemp + "/un/deux");
new CopyTache(bad_map);
}
}
diff --git a/src/test/java/com/github/athieriot/jtaches/taches/LessCompilerTacheTest.java b/src/test/java/com/github/athieriot/jtaches/taches/LessCompilerTacheTest.java
index 6a93f1a..774be2c 100644
--- a/src/test/java/com/github/athieriot/jtaches/taches/LessCompilerTacheTest.java
+++ b/src/test/java/com/github/athieriot/jtaches/taches/LessCompilerTacheTest.java
@@ -1,162 +1,163 @@
package com.github.athieriot.jtaches.taches;
import com.github.athieriot.jtaches.Tache;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.StandardWatchEventKinds;
import java.security.InvalidParameterException;
import java.util.Map;
import static com.github.athieriot.jtaches.command.Configuration.CONFIGURATION_PATH;
import static com.github.athieriot.jtaches.taches.LessCompilerTache.CONFIGURATION_COMPILE_TO;
import static com.github.athieriot.jtaches.taches.LessCompilerTache.CONFIGURATION_MAKE_PATH;
import static com.github.athieriot.jtaches.utils.TestUtils.newWatchEvent;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.io.Files.*;
import static java.nio.file.Paths.get;
import static org.mockito.Mockito.spy;
import static org.testng.Assert.*;
//CLEANUP: This test is not really a beauty
public class LessCompilerTacheTest {
private final Map<String,String> map = newHashMap();
private final File fromTemp = createTempDir();
private final File toTemp = createTempDir();
@BeforeTest
public void setup() {
map.put(CONFIGURATION_PATH, fromTemp.getAbsolutePath());
map.put(CONFIGURATION_COMPILE_TO, toTemp.getAbsolutePath());
}
@Test
public void compile_tache_must_compile_if_a_less_file_is_created() throws IOException {
Tache tache = spy(new LessCompilerTache(map));
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.less");
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, //
get(from.getName()))); //
assertTrue(new File(toTemp + "/" + "oma.css").exists());
}
@Test
public void compile_tache_must_not_compile_if_another_file_is_created() throws IOException {
Tache tache = spy(new LessCompilerTache(map));
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.gad");
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, //
get(from.getName()))); //
assertFalse(new File(toTemp + "/" + from.getName()).exists());
}
@Test
public void compile_tache_must_delete_if_a_file_is_deleted() throws IOException {
Tache tache = spy(new LessCompilerTache(map));
- File to = new File(toTemp.getAbsolutePath() + "/" + "oma.less");
+ File from = new File(toTemp.getAbsolutePath() + "/" + "oma.less");
+ File to = new File(toTemp.getAbsolutePath() + "/" + "oma.css");
to.createNewFile();
tache.onDelete(newWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, //
- get(to.getName()))); //
+ get(from.getName()))); //
assertFalse(to.exists());
}
@Test
public void compile_tache_must_copy_if_a_file_is_modified() throws IOException {
Tache tache = spy(new LessCompilerTache(map));
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.less");
from.createNewFile();
copy(from, new File(toTemp + "/" + from.getName()));
tache.onModify(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
assertTrue(new File(toTemp + "/" + "oma.css").exists());
assertEquals(from.length(), new File(toTemp + "/oma.css").length());
}
@Test
public void compile_tache_if_to_directory_not_exists_must_not_block() throws IOException {
Map<String, String> cloneMap = newHashMap();
cloneMap.putAll(map);
Tache tache = spy(new LessCompilerTache(cloneMap));
- cloneMap.put(CONFIGURATION_COMPILE_TO, "bullshit");
+ cloneMap.put(CONFIGURATION_COMPILE_TO, "./target/bullshit");
cloneMap.put(CONFIGURATION_MAKE_PATH, "false");
File from = new File(fromTemp.getAbsolutePath() + "/" + "oma.less");
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
tache.onDelete(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
tache.onModify(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get(from.getName()))); //
}
@Test
public void compile_tache_to_a_none_existing_directory_must_create_path_if_option() throws IOException {
Map<String, String> cloneMap = newHashMap();
cloneMap.putAll(map);
Tache tache = spy(new LessCompilerTache(cloneMap));
cloneMap.put(CONFIGURATION_COMPILE_TO, toTemp + "/truth");
cloneMap.put(CONFIGURATION_MAKE_PATH, "true");
File from = new File(fromTemp.getAbsolutePath() + "/ghost/" + "oma.less");
createParentDirs(from);
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get("ghost/", from.getName()))); //
assertTrue(new File(toTemp + "/truth/ghost/oma.css").exists());
}
@Test
public void compile_tache_to_a_none_existing_directory_must_NOT_create_path_by_default() throws IOException {
Map<String, String> cloneMap = newHashMap();
cloneMap.putAll(map);
Tache tache = spy(new LessCompilerTache(cloneMap));
cloneMap.put(CONFIGURATION_COMPILE_TO, toTemp + "/bollocs");
cloneMap.put(CONFIGURATION_MAKE_PATH, "false");
File from = new File(fromTemp.getAbsolutePath() + "/ghost/" + "oma.less");
createParentDirs(from);
from.createNewFile();
tache.onCreate(newWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, //
get("ghost/", from.getName()))); //
assertFalse(new File(toTemp + "/bollocs/ghost/" + from.getName()).exists());
}
@Test(expectedExceptions = InvalidParameterException.class)
public void copy_tache_must_not_create_if_copyTo_include_in_path() {
Map<String, String> bad_map = newHashMap();
bad_map.put(CONFIGURATION_PATH, toTemp + "/un/deux");
bad_map.put(CONFIGURATION_COMPILE_TO, toTemp + "/un/");
new LessCompilerTache(bad_map);
}
@Test(expectedExceptions = InvalidParameterException.class)
public void copy_tache_must_not_create_if_path_include_in_copyTo() {
Map<String, String> bad_map = newHashMap();
bad_map.put(CONFIGURATION_PATH, toTemp + "/un");
bad_map.put(CONFIGURATION_COMPILE_TO, toTemp + "/un/deux");
new LessCompilerTache(bad_map);
}
}
| false | false | null | null |
diff --git a/src/main/java/net/minecraft/src/NetClientHandler.java b/src/main/java/net/minecraft/src/NetClientHandler.java
index 4f4e185a..deeb1a92 100644
--- a/src/main/java/net/minecraft/src/NetClientHandler.java
+++ b/src/main/java/net/minecraft/src/NetClientHandler.java
@@ -1,1238 +1,1241 @@
package net.minecraft.src;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.crypto.SecretKey;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
// Spout Start
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import org.spoutcraft.client.SpoutClient;
import org.spoutcraft.client.config.Configuration;
import org.spoutcraft.client.io.FileDownloadThread;
import org.spoutcraft.client.packet.PacketCustomBlockChunkOverride;
import org.spoutcraft.client.player.ClientPlayer;
import org.spoutcraft.client.util.NetworkUtils;
import org.spoutcraft.client.gui.precache.GuiPrecache;
import org.spoutcraft.api.entity.LivingEntity;
// Spout End
public class NetClientHandler extends NetHandler {
/** True if kicked or disconnected from the server. */
private boolean disconnected = false;
/** Reference to the NetworkManager object. */
private INetworkManager netManager;
public String field_72560_a;
/** Reference to the Minecraft object. */
private Minecraft mc;
private WorldClient worldClient;
/**
* True if the client has finished downloading terrain and may spawn. Set upon receipt of a player position packet,
* reset upon respawning.
*/
private boolean doneLoadingTerrain = false;
public MapStorage mapStorage = new MapStorage((ISaveHandler)null);
/** A HashMap of all player names and their player information objects */
private Map playerInfoMap = new HashMap();
/**
* An ArrayList of GuiPlayerInfo (includes all the players' GuiPlayerInfo on the current server)
*/
public List playerInfoList = new ArrayList();
public int currentServerMaxPlayers = 20;
/** RNG. */
Random rand = new Random();
// Spout Start
long timeout = System.currentTimeMillis() + 5000;
public LinkedList<Packet> queue = new LinkedList<Packet>();
public long packetQueueTime = 0L;
public boolean queued = false;
// Spout End
public NetClientHandler(Minecraft par1Minecraft, String par2Str, int par3) throws IOException {
this.mc = par1Minecraft;
// Spout Start
InetSocketAddress address = NetworkUtils.resolve(par2Str, par3);
if (address.isUnresolved()) {
throw new UnknownHostException(address.getHostName());
}
this.netManager = new TcpConnection(new Socket(address.getAddress(), address.getPort()), "Client", this);
org.spoutcraft.client.gui.error.GuiConnectionLost.lastServerIp = par2Str;
org.spoutcraft.client.gui.error.GuiConnectionLost.lastServerPort = par3;
ClientPlayer.getInstance().resetMainScreen();
SpoutClient.getInstance().setSpoutActive(false);
// Spout End
}
public NetClientHandler(Minecraft par1Minecraft, IntegratedServer par2IntegratedServer) throws IOException {
this.mc = par1Minecraft;
this.netManager = new MemoryConnection(this);
par2IntegratedServer.getServerListeningThread().func_71754_a((MemoryConnection)this.netManager, par1Minecraft.session.username);
}
/**
* sets netManager and worldClient to null
*/
public void cleanup() {
if (this.netManager != null) {
this.netManager.wakeThreads();
}
this.netManager = null;
this.worldClient = null;
// Spout Start
ClientPlayer.getInstance().resetMainScreen();
SpoutClient.getInstance().setSpoutActive(false);
// Spout End
}
/**
* Processes the packets that have been read since the last call to this function.
*/
public void processReadPackets() {
if (!this.disconnected && this.netManager != null) {
this.netManager.processReadPackets();
}
if (this.netManager != null) {
this.netManager.wakeThreads();
}
if (mc.currentScreen instanceof GuiDownloadTerrain) { // If PreCache Manager was never called, this will close Downloading Terrain Screen.
if (System.currentTimeMillis() > timeout) {
mc.displayGuiScreen(null, false);
}
}
}
public void handleServerAuthData(Packet253ServerAuthData par1Packet253ServerAuthData) {
String var2 = par1Packet253ServerAuthData.getServerId().trim();
PublicKey var3 = par1Packet253ServerAuthData.getPublicKey();
SecretKey var4 = CryptManager.createNewSharedKey();
if (!"-".equals(var2)) {
String var5 = (new BigInteger(CryptManager.getServerIdHash(var2, var3, var4))).toString(16);
String var6 = this.sendSessionRequest(this.mc.session.username, this.mc.session.sessionId, var5);
if (!"ok".equalsIgnoreCase(var6)) {
this.netManager.networkShutdown("disconnect.loginFailedInfo", new Object[] {var6});
return;
}
}
this.addToSendQueue(new Packet252SharedKey(var4, var3, par1Packet253ServerAuthData.getVerifyToken()));
}
/**
* Send request to http://session.minecraft.net with user's sessionId and serverId hash
*/
private String sendSessionRequest(String par1Str, String par2Str, String par3Str) {
try {
URL var4 = new URL("http://session.minecraft.net/game/joinserver.jsp?user=" + urlEncode(par1Str) + "&sessionId=" + urlEncode(par2Str) + "&serverId=" + urlEncode(par3Str));
BufferedReader var5 = new BufferedReader(new InputStreamReader(var4.openStream()));
String var6 = var5.readLine();
var5.close();
return var6;
} catch (IOException var7) {
return var7.toString();
}
}
/**
* Encode the given string for insertion into a URL
*/
private static String urlEncode(String par0Str) throws IOException {
return URLEncoder.encode(par0Str, "UTF-8");
}
public void handleSharedKey(Packet252SharedKey par1Packet252SharedKey) {
this.addToSendQueue(new Packet205ClientCommand(0));
}
public void handleLogin(Packet1Login par1Packet1Login) {
this.mc.playerController = new PlayerControllerMP(this.mc, this);
this.mc.statFileWriter.readStat(StatList.joinMultiplayerStat, 1);
this.worldClient = new WorldClient(this, new WorldSettings(0L, par1Packet1Login.gameType, false, par1Packet1Login.hardcoreMode, par1Packet1Login.terrainType), par1Packet1Login.dimension, par1Packet1Login.difficultySetting, this.mc.mcProfiler);
this.worldClient.isRemote = true;
this.mc.loadWorld(this.worldClient);
this.mc.thePlayer.dimension = par1Packet1Login.dimension;
this.mc.displayGuiScreen(new GuiDownloadTerrain(this));
// Spout Start - Don't do this because of the dumb close screen call above it.
//this.mc.displayGuiScreen(new org.spoutcraft.client.gui.precache.GuiPrecache());
// Spout End
this.mc.thePlayer.entityId = par1Packet1Login.clientEntityId;
this.currentServerMaxPlayers = par1Packet1Login.maxPlayers;
this.mc.playerController.setGameType(par1Packet1Login.gameType);
this.mc.gameSettings.sendSettingsToServer();
}
public void handleVehicleSpawn(Packet23VehicleSpawn par1Packet23VehicleSpawn) {
double var2 = (double)par1Packet23VehicleSpawn.xPosition / 32.0D;
double var4 = (double)par1Packet23VehicleSpawn.yPosition / 32.0D;
double var6 = (double)par1Packet23VehicleSpawn.zPosition / 32.0D;
Object var8 = null;
if (par1Packet23VehicleSpawn.type == 10) {
var8 = new EntityMinecart(this.worldClient, var2, var4, var6, 0);
} else if (par1Packet23VehicleSpawn.type == 11) {
var8 = new EntityMinecart(this.worldClient, var2, var4, var6, 1);
} else if (par1Packet23VehicleSpawn.type == 12) {
var8 = new EntityMinecart(this.worldClient, var2, var4, var6, 2);
} else if (par1Packet23VehicleSpawn.type == 90) {
Entity var9 = this.getEntityByID(par1Packet23VehicleSpawn.throwerEntityId);
if (var9 instanceof EntityPlayer) {
var8 = new EntityFishHook(this.worldClient, var2, var4, var6, (EntityPlayer)var9);
}
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 60) {
var8 = new EntityArrow(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 61) {
var8 = new EntitySnowball(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 71) {
var8 = new EntityItemFrame(this.worldClient, (int)var2, (int)var4, (int)var6, par1Packet23VehicleSpawn.throwerEntityId);
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 65) {
var8 = new EntityEnderPearl(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 72) {
var8 = new EntityEnderEye(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 76) {
var8 = new EntityFireworkRocket(this.worldClient, var2, var4, var6, (ItemStack)null);
} else if (par1Packet23VehicleSpawn.type == 63) {
var8 = new EntityLargeFireball(this.worldClient, var2, var4, var6, (double)par1Packet23VehicleSpawn.speedX / 8000.0D, (double)par1Packet23VehicleSpawn.speedY / 8000.0D, (double)par1Packet23VehicleSpawn.speedZ / 8000.0D);
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 64) {
var8 = new EntitySmallFireball(this.worldClient, var2, var4, var6, (double)par1Packet23VehicleSpawn.speedX / 8000.0D, (double)par1Packet23VehicleSpawn.speedY / 8000.0D, (double)par1Packet23VehicleSpawn.speedZ / 8000.0D);
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 66) {
var8 = new EntityWitherSkull(this.worldClient, var2, var4, var6, (double)par1Packet23VehicleSpawn.speedX / 8000.0D, (double)par1Packet23VehicleSpawn.speedY / 8000.0D, (double)par1Packet23VehicleSpawn.speedZ / 8000.0D);
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 62) {
var8 = new EntityEgg(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 73) {
var8 = new EntityPotion(this.worldClient, var2, var4, var6, par1Packet23VehicleSpawn.throwerEntityId);
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 75) {
var8 = new EntityExpBottle(this.worldClient, var2, var4, var6);
par1Packet23VehicleSpawn.throwerEntityId = 0;
} else if (par1Packet23VehicleSpawn.type == 1) {
var8 = new EntityBoat(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 50) {
var8 = new EntityTNTPrimed(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 51) {
var8 = new EntityEnderCrystal(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 2) {
var8 = new EntityItem(this.worldClient, var2, var4, var6);
} else if (par1Packet23VehicleSpawn.type == 70) {
var8 = new EntityFallingSand(this.worldClient, var2, var4, var6, par1Packet23VehicleSpawn.throwerEntityId & 65535, par1Packet23VehicleSpawn.throwerEntityId >> 16);
par1Packet23VehicleSpawn.throwerEntityId = 0;
}
if (var8 != null) {
((Entity)var8).serverPosX = par1Packet23VehicleSpawn.xPosition;
((Entity)var8).serverPosY = par1Packet23VehicleSpawn.yPosition;
((Entity)var8).serverPosZ = par1Packet23VehicleSpawn.zPosition;
((Entity)var8).rotationPitch = (float)(par1Packet23VehicleSpawn.field_92077_h * 360) / 256.0F;
((Entity)var8).rotationYaw = (float)(par1Packet23VehicleSpawn.field_92078_i * 360) / 256.0F;
Entity[] var12 = ((Entity)var8).getParts();
if (var12 != null) {
int var10 = par1Packet23VehicleSpawn.entityId - ((Entity)var8).entityId;
for (int var11 = 0; var11 < var12.length; ++var11) {
var12[var11].entityId += var10;
}
}
((Entity)var8).entityId = par1Packet23VehicleSpawn.entityId;
this.worldClient.addEntityToWorld(par1Packet23VehicleSpawn.entityId, (Entity)var8);
if (par1Packet23VehicleSpawn.throwerEntityId > 0) {
if (par1Packet23VehicleSpawn.type == 60) {
Entity var13 = this.getEntityByID(par1Packet23VehicleSpawn.throwerEntityId);
if (var13 instanceof EntityLiving) {
EntityArrow var14 = (EntityArrow)var8;
var14.shootingEntity = var13;
}
}
((Entity)var8).setVelocity((double)par1Packet23VehicleSpawn.speedX / 8000.0D, (double)par1Packet23VehicleSpawn.speedY / 8000.0D, (double)par1Packet23VehicleSpawn.speedZ / 8000.0D);
}
}
}
/**
* Handle a entity experience orb packet.
*/
public void handleEntityExpOrb(Packet26EntityExpOrb par1Packet26EntityExpOrb) {
EntityXPOrb var2 = new EntityXPOrb(this.worldClient, (double)par1Packet26EntityExpOrb.posX, (double)par1Packet26EntityExpOrb.posY, (double)par1Packet26EntityExpOrb.posZ, par1Packet26EntityExpOrb.xpValue);
var2.serverPosX = par1Packet26EntityExpOrb.posX;
var2.serverPosY = par1Packet26EntityExpOrb.posY;
var2.serverPosZ = par1Packet26EntityExpOrb.posZ;
var2.rotationYaw = 0.0F;
var2.rotationPitch = 0.0F;
var2.entityId = par1Packet26EntityExpOrb.entityId;
this.worldClient.addEntityToWorld(par1Packet26EntityExpOrb.entityId, var2);
}
/**
* Handles weather packet
*/
public void handleWeather(Packet71Weather par1Packet71Weather) {
double var2 = (double)par1Packet71Weather.posX / 32.0D;
double var4 = (double)par1Packet71Weather.posY / 32.0D;
double var6 = (double)par1Packet71Weather.posZ / 32.0D;
EntityLightningBolt var8 = null;
if (par1Packet71Weather.isLightningBolt == 1) {
var8 = new EntityLightningBolt(this.worldClient, var2, var4, var6);
}
if (var8 != null) {
var8.serverPosX = par1Packet71Weather.posX;
var8.serverPosY = par1Packet71Weather.posY;
var8.serverPosZ = par1Packet71Weather.posZ;
var8.rotationYaw = 0.0F;
var8.rotationPitch = 0.0F;
var8.entityId = par1Packet71Weather.entityID;
this.worldClient.addWeatherEffect(var8);
}
}
/**
* Packet handler
*/
public void handleEntityPainting(Packet25EntityPainting par1Packet25EntityPainting) {
EntityPainting var2 = new EntityPainting(this.worldClient, par1Packet25EntityPainting.xPosition, par1Packet25EntityPainting.yPosition, par1Packet25EntityPainting.zPosition, par1Packet25EntityPainting.direction, par1Packet25EntityPainting.title);
this.worldClient.addEntityToWorld(par1Packet25EntityPainting.entityId, var2);
}
/**
* Packet handler
*/
public void handleEntityVelocity(Packet28EntityVelocity par1Packet28EntityVelocity) {
Entity var2 = this.getEntityByID(par1Packet28EntityVelocity.entityId);
if (var2 != null) {
var2.setVelocity((double)par1Packet28EntityVelocity.motionX / 8000.0D, (double)par1Packet28EntityVelocity.motionY / 8000.0D, (double)par1Packet28EntityVelocity.motionZ / 8000.0D);
}
}
/**
* Packet handler
*/
public void handleEntityMetadata(Packet40EntityMetadata par1Packet40EntityMetadata) {
Entity var2 = this.getEntityByID(par1Packet40EntityMetadata.entityId);
if (var2 != null && par1Packet40EntityMetadata.getMetadata() != null) {
var2.getDataWatcher().updateWatchedObjectsFromList(par1Packet40EntityMetadata.getMetadata());
}
}
public void handleNamedEntitySpawn(Packet20NamedEntitySpawn par1Packet20NamedEntitySpawn) {
double var2 = (double)par1Packet20NamedEntitySpawn.xPosition / 32.0D;
double var4 = (double)par1Packet20NamedEntitySpawn.yPosition / 32.0D;
double var6 = (double)par1Packet20NamedEntitySpawn.zPosition / 32.0D;
float var8 = (float)(par1Packet20NamedEntitySpawn.rotation * 360) / 256.0F;
float var9 = (float)(par1Packet20NamedEntitySpawn.pitch * 360) / 256.0F;
EntityOtherPlayerMP var10 = new EntityOtherPlayerMP(this.mc.theWorld, par1Packet20NamedEntitySpawn.name);
var10.prevPosX = var10.lastTickPosX = (double)(var10.serverPosX = par1Packet20NamedEntitySpawn.xPosition);
var10.prevPosY = var10.lastTickPosY = (double)(var10.serverPosY = par1Packet20NamedEntitySpawn.yPosition);
var10.prevPosZ = var10.lastTickPosZ = (double)(var10.serverPosZ = par1Packet20NamedEntitySpawn.zPosition);
int var11 = par1Packet20NamedEntitySpawn.currentItem;
if (var11 == 0) {
var10.inventory.mainInventory[var10.inventory.currentItem] = null;
} else {
var10.inventory.mainInventory[var10.inventory.currentItem] = new ItemStack(var11, 1, 0);
}
var10.setPositionAndRotation(var2, var4, var6, var8, var9);
this.worldClient.addEntityToWorld(par1Packet20NamedEntitySpawn.entityId, var10);
List var12 = par1Packet20NamedEntitySpawn.func_73509_c();
if (var12 != null) {
var10.getDataWatcher().updateWatchedObjectsFromList(var12);
}
// Spout Start - Set the entity's title
if (var10.worldObj.customTitles.containsKey(var10.entityId)) {
((LivingEntity)SpoutClient.getInstance().getEntityFromId(var10.entityId).spoutEnty).setTitle(var10.worldObj.customTitles.get(var10.entityId));
}
// Spout End
}
public void handleEntityTeleport(Packet34EntityTeleport par1Packet34EntityTeleport) {
Entity var2 = this.getEntityByID(par1Packet34EntityTeleport.entityId);
if (var2 != null) {
var2.serverPosX = par1Packet34EntityTeleport.xPosition;
var2.serverPosY = par1Packet34EntityTeleport.yPosition;
var2.serverPosZ = par1Packet34EntityTeleport.zPosition;
double var3 = (double)var2.serverPosX / 32.0D;
double var5 = (double)var2.serverPosY / 32.0D + 0.015625D;
double var7 = (double)var2.serverPosZ / 32.0D;
float var9 = (float)(par1Packet34EntityTeleport.yaw * 360) / 256.0F;
float var10 = (float)(par1Packet34EntityTeleport.pitch * 360) / 256.0F;
var2.setPositionAndRotation2(var3, var5, var7, var9, var10, 3);
}
}
public void handleBlockItemSwitch(Packet16BlockItemSwitch par1Packet16BlockItemSwitch) {
if (par1Packet16BlockItemSwitch.id >= 0 && par1Packet16BlockItemSwitch.id < InventoryPlayer.getHotbarSize()) {
this.mc.thePlayer.inventory.currentItem = par1Packet16BlockItemSwitch.id;
}
}
public void handleEntity(Packet30Entity par1Packet30Entity) {
Entity var2 = this.getEntityByID(par1Packet30Entity.entityId);
if (var2 != null) {
var2.serverPosX += par1Packet30Entity.xPosition;
var2.serverPosY += par1Packet30Entity.yPosition;
var2.serverPosZ += par1Packet30Entity.zPosition;
double var3 = (double)var2.serverPosX / 32.0D;
double var5 = (double)var2.serverPosY / 32.0D;
double var7 = (double)var2.serverPosZ / 32.0D;
float var9 = par1Packet30Entity.rotating ? (float)(par1Packet30Entity.yaw * 360) / 256.0F : var2.rotationYaw;
float var10 = par1Packet30Entity.rotating ? (float)(par1Packet30Entity.pitch * 360) / 256.0F : var2.rotationPitch;
var2.setPositionAndRotation2(var3, var5, var7, var9, var10, 3);
}
}
public void handleEntityHeadRotation(Packet35EntityHeadRotation par1Packet35EntityHeadRotation) {
Entity var2 = this.getEntityByID(par1Packet35EntityHeadRotation.entityId);
if (var2 != null) {
float var3 = (float)(par1Packet35EntityHeadRotation.headRotationYaw * 360) / 256.0F;
var2.setHeadRotationYaw(var3);
}
}
public void handleDestroyEntity(Packet29DestroyEntity par1Packet29DestroyEntity) {
for (int var2 = 0; var2 < par1Packet29DestroyEntity.entityId.length; ++var2) {
this.worldClient.removeEntityFromWorld(par1Packet29DestroyEntity.entityId[var2]);
}
}
// Spout Start
private boolean cachePacketSent = false;
// Spout End
public void handleFlying(Packet10Flying par1Packet10Flying) {
// Spout Start
sendCacheSetupPacket();
// Spout End
EntityClientPlayerMP var2 = this.mc.thePlayer;
double var3 = var2.posX;
double var5 = var2.posY;
double var7 = var2.posZ;
float var9 = var2.rotationYaw;
float var10 = var2.rotationPitch;
if (par1Packet10Flying.moving) {
var3 = par1Packet10Flying.xPosition;
var5 = par1Packet10Flying.yPosition;
var7 = par1Packet10Flying.zPosition;
}
if (par1Packet10Flying.rotating) {
var9 = par1Packet10Flying.yaw;
var10 = par1Packet10Flying.pitch;
}
var2.ySize = 0.0F;
var2.motionX = var2.motionY = var2.motionZ = 0.0D;
var2.setPositionAndRotation(var3, var5, var7, var9, var10);
par1Packet10Flying.xPosition = var2.posX;
par1Packet10Flying.yPosition = var2.boundingBox.minY;
par1Packet10Flying.zPosition = var2.posZ;
par1Packet10Flying.stance = var2.posY;
this.netManager.addToSendQueue(par1Packet10Flying);
if (!this.doneLoadingTerrain) {
this.mc.thePlayer.prevPosX = this.mc.thePlayer.posX;
this.mc.thePlayer.prevPosY = this.mc.thePlayer.posY;
this.mc.thePlayer.prevPosZ = this.mc.thePlayer.posZ;
this.doneLoadingTerrain = true;
// Spout Start
if (SpoutClient.getInstance().isSpoutEnabled()) {
if (FileDownloadThread.preCacheCompleted.get() == 0L) {
return;
}
}
// Spout End
this.mc.displayGuiScreen((GuiScreen)null);
}
}
public void handleMultiBlockChange(Packet52MultiBlockChange par1Packet52MultiBlockChange) {
int var2 = par1Packet52MultiBlockChange.xPosition * 16;
int var3 = par1Packet52MultiBlockChange.zPosition * 16;
if (par1Packet52MultiBlockChange.metadataArray != null) {
DataInputStream var4 = new DataInputStream(new ByteArrayInputStream(par1Packet52MultiBlockChange.metadataArray));
try {
for (int var5 = 0; var5 < par1Packet52MultiBlockChange.size; ++var5) {
short var6 = var4.readShort();
short var7 = var4.readShort();
int var8 = var7 >> 4 & 4095;
int var9 = var7 & 15;
int var10 = var6 >> 12 & 15;
int var11 = var6 >> 8 & 15;
int var12 = var6 & 255;
this.worldClient.setBlockAndMetadataAndInvalidate(var10 + var2, var12, var11 + var3, var8, var9);
}
} catch (IOException var13) {
;
}
}
}
/**
* Handle Packet51MapChunk (full chunk update of blocks, metadata, light levels, and optionally biome data)
*/
public void handleMapChunk(Packet51MapChunk par1Packet51MapChunk) {
// Spout Start
if (par1Packet51MapChunk.yChMax == -1 && par1Packet51MapChunk.yChMin == -1) {
getNetManager().networkShutdown("Spout Cache Error - Corrupt File Deleted", new Object[0]);
kick("Cache Error - Corrupt File Deleted");
return;
}
if (worldClient == null) {
return;
}
// Spout End
if (par1Packet51MapChunk.includeInitialize) {
if (par1Packet51MapChunk.yChMin == 0) {
this.worldClient.doPreChunk(par1Packet51MapChunk.xCh, par1Packet51MapChunk.zCh, false);
return;
}
this.worldClient.doPreChunk(par1Packet51MapChunk.xCh, par1Packet51MapChunk.zCh, true);
}
this.worldClient.invalidateBlockReceiveRegion(par1Packet51MapChunk.xCh << 4, 0, par1Packet51MapChunk.zCh << 4, (par1Packet51MapChunk.xCh << 4) + 15, 256, (par1Packet51MapChunk.zCh << 4) + 15);
Chunk var2 = this.worldClient.getChunkFromChunkCoords(par1Packet51MapChunk.xCh, par1Packet51MapChunk.zCh);
if (par1Packet51MapChunk.includeInitialize && var2 == null) {
this.worldClient.doPreChunk(par1Packet51MapChunk.xCh, par1Packet51MapChunk.zCh, true);
var2 = this.worldClient.getChunkFromChunkCoords(par1Packet51MapChunk.xCh, par1Packet51MapChunk.zCh);
}
if (var2 != null) {
var2.fillChunk(par1Packet51MapChunk.func_73593_d(), par1Packet51MapChunk.yChMin, par1Packet51MapChunk.yChMax, par1Packet51MapChunk.includeInitialize);
this.worldClient.markBlockRangeForRenderUpdate(par1Packet51MapChunk.xCh << 4, 0, par1Packet51MapChunk.zCh << 4, (par1Packet51MapChunk.xCh << 4) + 15, 256, (par1Packet51MapChunk.zCh << 4) + 15);
if (!par1Packet51MapChunk.includeInitialize || !(this.worldClient.provider instanceof WorldProviderSurface)) {
// Spout Start
if (Configuration.isClientLight()) {
var2.resetRelightChecks();
}
// Spout End
}
}
}
public void handleBlockChange(Packet53BlockChange par1Packet53BlockChange) {
this.worldClient.setBlockAndMetadataAndInvalidate(par1Packet53BlockChange.xPosition, par1Packet53BlockChange.yPosition, par1Packet53BlockChange.zPosition, par1Packet53BlockChange.type, par1Packet53BlockChange.metadata);
}
// Spout Start
public void kick(String reason) {
if (this.mc.thePlayer != null) {
this.mc.thePlayer.closeScreen(); // Close the active screen first!
}
this.netManager.networkShutdown("disconnect.kicked", new Object[0]);
this.disconnected = true;
this.mc.loadWorld((WorldClient)null);
this.mc.displayGuiScreen(new GuiDisconnected("disconnect.disconnected", "disconnect.genericReason", new Object[] {reason}));
}
public void handleKickDisconnect(Packet255KickDisconnect par1Packet255KickDisconnect) {
kick(par1Packet255KickDisconnect.reason);
}
// Spout End
public void handleErrorMessage(String par1Str, Object[] par2ArrayOfObj) {
if (!this.disconnected) {
this.disconnected = true;
this.mc.loadWorld((WorldClient)null);
// Spout Start
System.out.println(par1Str);
if (par1Str != null && par1Str.toLowerCase().contains("endofstream")) {
this.mc.displayGuiScreen(new org.spoutcraft.client.gui.error.GuiConnectionLost());
} else if (par2ArrayOfObj == null || par2ArrayOfObj.length == 0 || !(par2ArrayOfObj[0] instanceof String)) {
this.mc.displayGuiScreen(new GuiDisconnected("disconnect.lost", par1Str, par2ArrayOfObj));
} else if (((String)par2ArrayOfObj[0]).toLowerCase().contains("connection reset")) {
this.mc.displayGuiScreen(new org.spoutcraft.client.gui.error.GuiConnectionLost());
} else if (((String)par2ArrayOfObj[0]).toLowerCase().contains("connection refused")) {
this.mc.displayGuiScreen(new org.spoutcraft.client.gui.error.GuiConnectionLost("The server is not currently online!"));
} else if (((String)par2ArrayOfObj[0]).toLowerCase().contains("overflow")) {
this.mc.displayGuiScreen(new org.spoutcraft.client.gui.error.GuiConnectionLost("The server is currently experiencing heavy traffic. Try again later."));
} else {
this.mc.displayGuiScreen(new GuiDisconnected("disconnect.lost", par1Str, par2ArrayOfObj));
}
// Spout End
}
}
public void quitWithPacket(Packet par1Packet) {
if (!this.disconnected) {
this.netManager.addToSendQueue(par1Packet);
this.netManager.serverShutdown();
}
}
/**
* Adds the packet to the send queue
*/
public void addToSendQueue(Packet par1Packet) {
if (!this.disconnected) {
this.netManager.addToSendQueue(par1Packet);
}
}
public void handleCollect(Packet22Collect par1Packet22Collect) {
Entity var2 = this.getEntityByID(par1Packet22Collect.collectedEntityId);
Object var3 = (EntityLiving)this.getEntityByID(par1Packet22Collect.collectorEntityId);
if (var3 == null) {
var3 = this.mc.thePlayer;
}
if (var2 != null) {
if (var2 instanceof EntityXPOrb) {
this.worldClient.playSoundAtEntity(var2, "random.orb", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
} else {
this.worldClient.playSoundAtEntity(var2, "random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
}
this.mc.effectRenderer.addEffect(new EntityPickupFX(this.mc.theWorld, var2, (Entity)var3, -0.5F));
this.worldClient.removeEntityFromWorld(par1Packet22Collect.collectedEntityId);
}
}
public void handleChat(Packet3Chat par1Packet3Chat) {
this.mc.ingameGUI.getChatGUI().printChatMessage(par1Packet3Chat.message);
}
public void handleAnimation(Packet18Animation par1Packet18Animation) {
Entity var2 = this.getEntityByID(par1Packet18Animation.entityId);
if (var2 != null) {
if (par1Packet18Animation.animate == 1) {
EntityLiving var3 = (EntityLiving)var2;
var3.swingItem();
} else if (par1Packet18Animation.animate == 2) {
var2.performHurtAnimation();
} else if (par1Packet18Animation.animate == 3) {
EntityPlayer var4 = (EntityPlayer)var2;
var4.wakeUpPlayer(false, false, false);
} else if (par1Packet18Animation.animate != 4) {
if (par1Packet18Animation.animate == 6) {
this.mc.effectRenderer.addEffect(new EntityCrit2FX(this.mc.theWorld, var2));
} else if (par1Packet18Animation.animate == 7) {
EntityCrit2FX var5 = new EntityCrit2FX(this.mc.theWorld, var2, "magicCrit");
this.mc.effectRenderer.addEffect(var5);
} else if (par1Packet18Animation.animate == 5 && var2 instanceof EntityOtherPlayerMP) {
;
}
}
}
}
public void handleSleep(Packet17Sleep par1Packet17Sleep) {
Entity var2 = this.getEntityByID(par1Packet17Sleep.entityID);
if (var2 != null) {
if (par1Packet17Sleep.field_73622_e == 0) {
EntityPlayer var3 = (EntityPlayer)var2;
var3.sleepInBedAt(par1Packet17Sleep.bedX, par1Packet17Sleep.bedY, par1Packet17Sleep.bedZ);
}
}
}
/**
* Disconnects the network connection.
*/
public void disconnect() {
this.disconnected = true;
this.netManager.wakeThreads();
this.netManager.networkShutdown("disconnect.closed", new Object[0]);
}
public void handleMobSpawn(Packet24MobSpawn par1Packet24MobSpawn) {
double var2 = (double)par1Packet24MobSpawn.xPosition / 32.0D;
double var4 = (double)par1Packet24MobSpawn.yPosition / 32.0D;
double var6 = (double)par1Packet24MobSpawn.zPosition / 32.0D;
float var8 = (float)(par1Packet24MobSpawn.yaw * 360) / 256.0F;
float var9 = (float)(par1Packet24MobSpawn.pitch * 360) / 256.0F;
EntityLiving var10 = (EntityLiving)EntityList.createEntityByID(par1Packet24MobSpawn.type, this.mc.theWorld);
var10.serverPosX = par1Packet24MobSpawn.xPosition;
var10.serverPosY = par1Packet24MobSpawn.yPosition;
var10.serverPosZ = par1Packet24MobSpawn.zPosition;
var10.rotationYawHead = (float)(par1Packet24MobSpawn.headYaw * 360) / 256.0F;
Entity[] var11 = var10.getParts();
if (var11 != null) {
int var12 = par1Packet24MobSpawn.entityId - var10.entityId;
for (int var13 = 0; var13 < var11.length; ++var13) {
var11[var13].entityId += var12;
}
}
var10.entityId = par1Packet24MobSpawn.entityId;
var10.setPositionAndRotation(var2, var4, var6, var8, var9);
var10.motionX = (double)((float)par1Packet24MobSpawn.velocityX / 8000.0F);
var10.motionY = (double)((float)par1Packet24MobSpawn.velocityY / 8000.0F);
var10.motionZ = (double)((float)par1Packet24MobSpawn.velocityZ / 8000.0F);
this.worldClient.addEntityToWorld(par1Packet24MobSpawn.entityId, var10);
List var14 = par1Packet24MobSpawn.getMetadata();
if (var14 != null) {
var10.getDataWatcher().updateWatchedObjectsFromList(var14);
}
// Spout Start - Set the entity's title
if (var10.worldObj.customTitles.containsKey(var10.entityId)) {
((LivingEntity)SpoutClient.getInstance().getEntityFromId(var10.entityId).spoutEnty).setTitle(var10.worldObj.customTitles.get(var10.entityId));
}
// Spout End
}
public void handleUpdateTime(Packet4UpdateTime par1Packet4UpdateTime) {
this.mc.theWorld.func_82738_a(par1Packet4UpdateTime.field_82562_a);
this.mc.theWorld.setWorldTime(par1Packet4UpdateTime.time);
}
public void handleSpawnPosition(Packet6SpawnPosition par1Packet6SpawnPosition) {
// Spout Start
sendCacheSetupPacket();
// Spout End
this.mc.thePlayer.setSpawnChunk(new ChunkCoordinates(par1Packet6SpawnPosition.xPosition, par1Packet6SpawnPosition.yPosition, par1Packet6SpawnPosition.zPosition), true);
this.mc.theWorld.getWorldInfo().setSpawnPosition(par1Packet6SpawnPosition.xPosition, par1Packet6SpawnPosition.yPosition, par1Packet6SpawnPosition.zPosition);
}
// Spout Start
private void sendCacheSetupPacket() {
if (!cachePacketSent) {
cachePacketSent = true;
//this.netManager.addToSendQueue(new Packet250CustomPayload("ChkCache:setHash", new byte[1]));
}
}
// Spout End
/**
* Packet handler
*/
public void handleAttachEntity(Packet39AttachEntity par1Packet39AttachEntity) {
Object var2 = this.getEntityByID(par1Packet39AttachEntity.entityId);
Entity var3 = this.getEntityByID(par1Packet39AttachEntity.vehicleEntityId);
if (par1Packet39AttachEntity.entityId == this.mc.thePlayer.entityId) {
var2 = this.mc.thePlayer;
if (var3 instanceof EntityBoat) {
((EntityBoat)var3).func_70270_d(false);
}
} else if (var3 instanceof EntityBoat) {
((EntityBoat)var3).func_70270_d(true);
}
if (var2 != null) {
((Entity)var2).mountEntity(var3);
}
}
/**
* Packet handler
*/
public void handleEntityStatus(Packet38EntityStatus par1Packet38EntityStatus) {
Entity var2 = this.getEntityByID(par1Packet38EntityStatus.entityId);
if (var2 != null) {
var2.handleHealthUpdate(par1Packet38EntityStatus.entityStatus);
}
}
private Entity getEntityByID(int par1) {
return (Entity)(par1 == this.mc.thePlayer.entityId ? this.mc.thePlayer : this.worldClient.getEntityByID(par1));
}
/**
* Recieves player health from the server and then proceeds to set it locally on the client.
*/
public void handleUpdateHealth(Packet8UpdateHealth par1Packet8UpdateHealth) {
this.mc.thePlayer.setHealth(par1Packet8UpdateHealth.healthMP);
this.mc.thePlayer.getFoodStats().setFoodLevel(par1Packet8UpdateHealth.food);
this.mc.thePlayer.getFoodStats().setFoodSaturationLevel(par1Packet8UpdateHealth.foodSaturation);
}
/**
* Handle an experience packet.
*/
public void handleExperience(Packet43Experience par1Packet43Experience) {
this.mc.thePlayer.setXPStats(par1Packet43Experience.experience, par1Packet43Experience.experienceTotal, par1Packet43Experience.experienceLevel);
}
/**
* respawns the player
*/
public void handleRespawn(Packet9Respawn par1Packet9Respawn) {
if (par1Packet9Respawn.respawnDimension != this.mc.thePlayer.dimension) {
this.doneLoadingTerrain = false;
this.worldClient = new WorldClient(this, new WorldSettings(0L, par1Packet9Respawn.gameType, false, this.mc.theWorld.getWorldInfo().isHardcoreModeEnabled(), par1Packet9Respawn.terrainType), par1Packet9Respawn.respawnDimension, par1Packet9Respawn.difficulty, this.mc.mcProfiler);
this.worldClient.isRemote = true;
this.mc.loadWorld(this.worldClient);
this.mc.thePlayer.dimension = par1Packet9Respawn.respawnDimension;
this.mc.displayGuiScreen(new GuiDownloadTerrain(this));
}
this.mc.setDimensionAndSpawnPlayer(par1Packet9Respawn.respawnDimension);
this.mc.playerController.setGameType(par1Packet9Respawn.gameType);
}
public void handleExplosion(Packet60Explosion par1Packet60Explosion) {
Explosion var2 = new Explosion(this.mc.theWorld, (Entity)null, par1Packet60Explosion.explosionX, par1Packet60Explosion.explosionY, par1Packet60Explosion.explosionZ, par1Packet60Explosion.explosionSize);
var2.affectedBlockPositions = par1Packet60Explosion.chunkPositionRecords;
var2.doExplosionB(true);
this.mc.thePlayer.motionX += (double)par1Packet60Explosion.func_73607_d();
this.mc.thePlayer.motionY += (double)par1Packet60Explosion.func_73609_f();
this.mc.thePlayer.motionZ += (double)par1Packet60Explosion.func_73608_g();
}
public void handleOpenWindow(Packet100OpenWindow par1Packet100OpenWindow) {
EntityClientPlayerMP var2 = this.mc.thePlayer;
switch (par1Packet100OpenWindow.inventoryType) {
case 0:
var2.displayGUIChest(new InventoryBasic(par1Packet100OpenWindow.windowTitle, par1Packet100OpenWindow.slotsCount));
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 1:
var2.displayGUIWorkbench(MathHelper.floor_double(var2.posX), MathHelper.floor_double(var2.posY), MathHelper.floor_double(var2.posZ));
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 2:
var2.displayGUIFurnace(new TileEntityFurnace());
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 3:
var2.displayGUIDispenser(new TileEntityDispenser());
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 4:
var2.displayGUIEnchantment(MathHelper.floor_double(var2.posX), MathHelper.floor_double(var2.posY), MathHelper.floor_double(var2.posZ));
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 5:
var2.displayGUIBrewingStand(new TileEntityBrewingStand());
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 6:
var2.displayGUIMerchant(new NpcMerchant(var2));
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 7:
var2.displayGUIBeacon(new TileEntityBeacon());
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
break;
case 8:
var2.displayGUIAnvil(MathHelper.floor_double(var2.posX), MathHelper.floor_double(var2.posY), MathHelper.floor_double(var2.posZ));
var2.openContainer.windowId = par1Packet100OpenWindow.windowId;
}
}
public void handleSetSlot(Packet103SetSlot par1Packet103SetSlot) {
EntityClientPlayerMP var2 = this.mc.thePlayer;
if (par1Packet103SetSlot.windowId == -1) {
var2.inventory.setItemStack(par1Packet103SetSlot.myItemStack);
} else {
boolean var3 = false;
if (this.mc.currentScreen instanceof GuiContainerCreative) {
GuiContainerCreative var4 = (GuiContainerCreative)this.mc.currentScreen;
var3 = var4.func_74230_h() != CreativeTabs.tabInventory.getTabIndex();
}
if (par1Packet103SetSlot.windowId == 0 && par1Packet103SetSlot.itemSlot >= 36 && par1Packet103SetSlot.itemSlot < 45) {
ItemStack var5 = var2.inventoryContainer.getSlot(par1Packet103SetSlot.itemSlot).getStack();
if (par1Packet103SetSlot.myItemStack != null && (var5 == null || var5.stackSize < par1Packet103SetSlot.myItemStack.stackSize)) {
par1Packet103SetSlot.myItemStack.animationsToGo = 5;
}
var2.inventoryContainer.putStackInSlot(par1Packet103SetSlot.itemSlot, par1Packet103SetSlot.myItemStack);
} else if (par1Packet103SetSlot.windowId == var2.openContainer.windowId && (par1Packet103SetSlot.windowId != 0 || !var3)) {
var2.openContainer.putStackInSlot(par1Packet103SetSlot.itemSlot, par1Packet103SetSlot.myItemStack);
}
}
}
public void handleTransaction(Packet106Transaction par1Packet106Transaction) {
Container var2 = null;
EntityClientPlayerMP var3 = this.mc.thePlayer;
if (par1Packet106Transaction.windowId == 0) {
var2 = var3.inventoryContainer;
} else if (par1Packet106Transaction.windowId == var3.openContainer.windowId) {
var2 = var3.openContainer;
}
if (var2 != null && !par1Packet106Transaction.accepted) {
this.addToSendQueue(new Packet106Transaction(par1Packet106Transaction.windowId, par1Packet106Transaction.shortWindowId, true));
}
}
public void handleWindowItems(Packet104WindowItems par1Packet104WindowItems) {
EntityClientPlayerMP var2 = this.mc.thePlayer;
if (par1Packet104WindowItems.windowId == 0) {
var2.inventoryContainer.putStacksInSlots(par1Packet104WindowItems.itemStack);
} else if (par1Packet104WindowItems.windowId == var2.openContainer.windowId) {
var2.openContainer.putStacksInSlots(par1Packet104WindowItems.itemStack);
}
}
/**
* Updates Client side signs
*/
public void handleUpdateSign(Packet130UpdateSign par1Packet130UpdateSign) {
boolean var2 = false;
if (this.mc.theWorld.blockExists(par1Packet130UpdateSign.xPosition, par1Packet130UpdateSign.yPosition, par1Packet130UpdateSign.zPosition)) {
TileEntity var3 = this.mc.theWorld.getBlockTileEntity(par1Packet130UpdateSign.xPosition, par1Packet130UpdateSign.yPosition, par1Packet130UpdateSign.zPosition);
if (var3 instanceof TileEntitySign) {
TileEntitySign var4 = (TileEntitySign)var3;
if (var4.isEditable()) {
for (int var5 = 0; var5 < 4; ++var5) {
var4.signText[var5] = par1Packet130UpdateSign.signLines[var5];
}
var4.onInventoryChanged();
// Spout Start
var4.recalculateText();
// Spout End
}
var2 = true;
}
}
if (!var2 && this.mc.thePlayer != null) {
this.mc.thePlayer.sendChatToPlayer("Unable to locate sign at " + par1Packet130UpdateSign.xPosition + ", " + par1Packet130UpdateSign.yPosition + ", " + par1Packet130UpdateSign.zPosition);
}
}
public void handleTileEntityData(Packet132TileEntityData par1Packet132TileEntityData) {
if (this.mc.theWorld.blockExists(par1Packet132TileEntityData.xPosition, par1Packet132TileEntityData.yPosition, par1Packet132TileEntityData.zPosition)) {
TileEntity var2 = this.mc.theWorld.getBlockTileEntity(par1Packet132TileEntityData.xPosition, par1Packet132TileEntityData.yPosition, par1Packet132TileEntityData.zPosition);
if (var2 != null) {
if (par1Packet132TileEntityData.actionType == 1 && var2 instanceof TileEntityMobSpawner) {
var2.readFromNBT(par1Packet132TileEntityData.customParam1);
} else if (par1Packet132TileEntityData.actionType == 2 && var2 instanceof TileEntityCommandBlock) {
var2.readFromNBT(par1Packet132TileEntityData.customParam1);
} else if (par1Packet132TileEntityData.actionType == 3 && var2 instanceof TileEntityBeacon) {
var2.readFromNBT(par1Packet132TileEntityData.customParam1);
} else if (par1Packet132TileEntityData.actionType == 4 && var2 instanceof TileEntitySkull) {
var2.readFromNBT(par1Packet132TileEntityData.customParam1);
}
}
}
}
public void handleUpdateProgressbar(Packet105UpdateProgressbar par1Packet105UpdateProgressbar) {
EntityClientPlayerMP var2 = this.mc.thePlayer;
this.unexpectedPacket(par1Packet105UpdateProgressbar);
if (var2.openContainer != null && var2.openContainer.windowId == par1Packet105UpdateProgressbar.windowId) {
var2.openContainer.updateProgressBar(par1Packet105UpdateProgressbar.progressBar, par1Packet105UpdateProgressbar.progressBarValue);
}
}
public void handlePlayerInventory(Packet5PlayerInventory par1Packet5PlayerInventory) {
Entity var2 = this.getEntityByID(par1Packet5PlayerInventory.entityID);
if (var2 != null) {
var2.setCurrentItemOrArmor(par1Packet5PlayerInventory.slot, par1Packet5PlayerInventory.getItemSlot());
}
}
public void handleCloseWindow(Packet101CloseWindow par1Packet101CloseWindow) {
// Spout Start
this.mc.thePlayer.closeScreen();
// Spout End
}
public void handleBlockEvent(Packet54PlayNoteBlock par1Packet54PlayNoteBlock) {
this.mc.theWorld.addBlockEvent(par1Packet54PlayNoteBlock.xLocation, par1Packet54PlayNoteBlock.yLocation, par1Packet54PlayNoteBlock.zLocation, par1Packet54PlayNoteBlock.blockId, par1Packet54PlayNoteBlock.instrumentType, par1Packet54PlayNoteBlock.pitch);
}
public void handleBlockDestroy(Packet55BlockDestroy par1Packet55BlockDestroy) {
this.mc.theWorld.cancelDestroyingBlock(par1Packet55BlockDestroy.getEntityId(), par1Packet55BlockDestroy.getPosX(), par1Packet55BlockDestroy.getPosY(), par1Packet55BlockDestroy.getPosZ(), par1Packet55BlockDestroy.getDestroyedStage());
}
public void handleMapChunks(Packet56MapChunks par1Packet56MapChunks) {
for (int var2 = 0; var2 < par1Packet56MapChunks.getNumberOfChunkInPacket(); ++var2) {
int var3 = par1Packet56MapChunks.getChunkPosX(var2);
int var4 = par1Packet56MapChunks.getChunkPosZ(var2);
this.worldClient.doPreChunk(var3, var4, true);
this.worldClient.invalidateBlockReceiveRegion(var3 << 4, 0, var4 << 4, (var3 << 4) + 15, 256, (var4 << 4) + 15);
Chunk var5 = this.worldClient.getChunkFromChunkCoords(var3, var4);
if (var5 == null) {
this.worldClient.doPreChunk(var3, var4, true);
var5 = this.worldClient.getChunkFromChunkCoords(var3, var4);
}
if (var5 != null) {
var5.fillChunk(par1Packet56MapChunks.getChunkCompressedData(var2), par1Packet56MapChunks.field_73590_a[var2], par1Packet56MapChunks.field_73588_b[var2], true);
this.worldClient.markBlockRangeForRenderUpdate(var3 << 4, 0, var4 << 4, (var3 << 4) + 15, 256, (var4 << 4) + 15);
if (!(this.worldClient.provider instanceof WorldProviderSurface)) {
var5.resetRelightChecks();
}
}
}
}
/**
* packet.processPacket is only called if this returns true
*/
public boolean canProcessPacketsAsync() {
return this.mc != null && this.mc.theWorld != null && this.mc.thePlayer != null && this.worldClient != null;
}
public void handleGameEvent(Packet70GameEvent par1Packet70GameEvent) {
EntityClientPlayerMP var2 = this.mc.thePlayer;
int var3 = par1Packet70GameEvent.eventType;
int var4 = par1Packet70GameEvent.gameMode;
if (var3 >= 0 && var3 < Packet70GameEvent.clientMessage.length && Packet70GameEvent.clientMessage[var3] != null) {
var2.addChatMessage(Packet70GameEvent.clientMessage[var3]);
}
if (var3 == 1) {
this.worldClient.getWorldInfo().setRaining(true);
this.worldClient.setRainStrength(0.0F);
} else if (var3 == 2) {
this.worldClient.getWorldInfo().setRaining(false);
this.worldClient.setRainStrength(1.0F);
} else if (var3 == 3) {
this.mc.playerController.setGameType(EnumGameType.getByID(var4));
} else if (var3 == 4) {
this.mc.displayGuiScreen(new GuiWinGame());
} else if (var3 == 5) {
GameSettings var5 = this.mc.gameSettings;
if (var4 == 0) {
this.mc.displayGuiScreen(new GuiScreenDemo());
} else if (var4 == 101) {
this.mc.ingameGUI.getChatGUI().addTranslatedMessage("demo.help.movement", new Object[] {Keyboard.getKeyName(var5.keyBindForward.keyCode), Keyboard.getKeyName(var5.keyBindLeft.keyCode), Keyboard.getKeyName(var5.keyBindBack.keyCode), Keyboard.getKeyName(var5.keyBindRight.keyCode)});
} else if (var4 == 102) {
this.mc.ingameGUI.getChatGUI().addTranslatedMessage("demo.help.jump", new Object[] {Keyboard.getKeyName(var5.keyBindJump.keyCode)});
} else if (var4 == 103) {
this.mc.ingameGUI.getChatGUI().addTranslatedMessage("demo.help.inventory", new Object[] {Keyboard.getKeyName(var5.keyBindInventory.keyCode)});
}
} else if (var3 == 6) {
this.worldClient.playSound(var2.posX, var2.posY + (double)var2.getEyeHeight(), var2.posZ, "random.successful_hit", 0.15F, 0.45F, false);
}
+ // Spout Start
+ GuiIngame.dirtySurvival(); // Trigger SurvivalHUD update
+ // Spout End
}
/**
* Contains logic for handling packets containing arbitrary unique item data. Currently this is only for maps.
*/
public void handleMapData(Packet131MapData par1Packet131MapData) {
if (par1Packet131MapData.itemID == Item.map.itemID) {
ItemMap.getMPMapData(par1Packet131MapData.uniqueID, this.mc.theWorld).updateMPMapData(par1Packet131MapData.itemData);
} else {
System.out.println("Unknown itemid: " + par1Packet131MapData.uniqueID);
}
}
public void handleDoorChange(Packet61DoorChange par1Packet61DoorChange) {
if (par1Packet61DoorChange.func_82560_d()) {
this.mc.theWorld.func_82739_e(par1Packet61DoorChange.sfxID, par1Packet61DoorChange.posX, par1Packet61DoorChange.posY, par1Packet61DoorChange.posZ, par1Packet61DoorChange.auxData);
} else {
this.mc.theWorld.playAuxSFX(par1Packet61DoorChange.sfxID, par1Packet61DoorChange.posX, par1Packet61DoorChange.posY, par1Packet61DoorChange.posZ, par1Packet61DoorChange.auxData);
}
}
/**
* Increment player statistics
*/
public void handleStatistic(Packet200Statistic par1Packet200Statistic) {
this.mc.thePlayer.incrementStat(StatList.getOneShotStat(par1Packet200Statistic.statisticId), par1Packet200Statistic.amount);
}
/**
* Handle an entity effect packet.
*/
public void handleEntityEffect(Packet41EntityEffect par1Packet41EntityEffect) {
Entity var2 = this.getEntityByID(par1Packet41EntityEffect.entityId);
if (var2 instanceof EntityLiving) {
((EntityLiving)var2).addPotionEffect(new PotionEffect(par1Packet41EntityEffect.effectId, par1Packet41EntityEffect.duration, par1Packet41EntityEffect.effectAmplifier));
}
}
/**
* Handle a remove entity effect packet.
*/
public void handleRemoveEntityEffect(Packet42RemoveEntityEffect par1Packet42RemoveEntityEffect) {
Entity var2 = this.getEntityByID(par1Packet42RemoveEntityEffect.entityId);
if (var2 instanceof EntityLiving) {
((EntityLiving)var2).removePotionEffectClient(par1Packet42RemoveEntityEffect.effectId);
}
}
/**
* determine if it is a server handler
*/
public boolean isServerHandler() {
return false;
}
/**
* Handle a player information packet.
*/
public void handlePlayerInfo(Packet201PlayerInfo par1Packet201PlayerInfo) {
GuiPlayerInfo var2 = (GuiPlayerInfo)this.playerInfoMap.get(par1Packet201PlayerInfo.playerName);
if (var2 == null && par1Packet201PlayerInfo.isConnected) {
var2 = new GuiPlayerInfo(par1Packet201PlayerInfo.playerName);
this.playerInfoMap.put(par1Packet201PlayerInfo.playerName, var2);
this.playerInfoList.add(var2);
}
if (var2 != null && !par1Packet201PlayerInfo.isConnected) {
this.playerInfoMap.remove(par1Packet201PlayerInfo.playerName);
this.playerInfoList.remove(var2);
}
if (par1Packet201PlayerInfo.isConnected && var2 != null) {
var2.responseTime = par1Packet201PlayerInfo.ping;
}
}
/**
* Handle a keep alive packet.
*/
public void handleKeepAlive(Packet0KeepAlive par1Packet0KeepAlive) {
this.addToSendQueue(new Packet0KeepAlive(par1Packet0KeepAlive.randomId));
}
/**
* Handle a player abilities packet.
*/
public void handlePlayerAbilities(Packet202PlayerAbilities par1Packet202PlayerAbilities) {
EntityClientPlayerMP var2 = this.mc.thePlayer;
var2.capabilities.isFlying = par1Packet202PlayerAbilities.getFlying();
var2.capabilities.isCreativeMode = par1Packet202PlayerAbilities.isCreativeMode();
var2.capabilities.disableDamage = par1Packet202PlayerAbilities.getDisableDamage();
var2.capabilities.allowFlying = par1Packet202PlayerAbilities.getAllowFlying();
var2.capabilities.setFlySpeed(par1Packet202PlayerAbilities.getFlySpeed());
var2.capabilities.func_82877_b(par1Packet202PlayerAbilities.func_82558_j());
}
public void handleAutoComplete(Packet203AutoComplete par1Packet203AutoComplete) {
String[] var2 = par1Packet203AutoComplete.getText().split("\u0000");
if (this.mc.currentScreen instanceof GuiChat) {
// Spout Start
GuiChat var3 = (GuiChat)this.mc.currentScreen;
// Spout End
var3.func_73894_a(var2);
}
}
public void handleLevelSound(Packet62LevelSound par1Packet62LevelSound) {
this.mc.theWorld.playSound(par1Packet62LevelSound.getEffectX(), par1Packet62LevelSound.getEffectY(), par1Packet62LevelSound.getEffectZ(), par1Packet62LevelSound.getSoundName(), par1Packet62LevelSound.getVolume(), par1Packet62LevelSound.getPitch(), false);
}
public void handleCustomPayload(Packet250CustomPayload par1Packet250CustomPayload) {
if ("MC|TPack".equals(par1Packet250CustomPayload.channel)) {
String[] var2 = (new String(par1Packet250CustomPayload.data)).split("\u0000");
String var3 = var2[0];
if (var2[1].equals("16")) {
if (this.mc.texturePackList.getAcceptsTextures()) {
this.mc.texturePackList.requestDownloadOfTexture(var3);
} else if (this.mc.texturePackList.func_77300_f()) {
// Spout Start
if (Configuration.isServerTexturePromptsEnabled()) {
this.mc.displayGuiScreen(new GuiYesNo(new NetClientWebTextures(this, var3), StringTranslate.getInstance().translateKey("multiplayer.texturePrompt.line1"), StringTranslate.getInstance().translateKey("multiplayer.texturePrompt.line2"), 0));
}
// Spout End
}
}
} else if ("MC|TrList".equals(par1Packet250CustomPayload.channel)) {
DataInputStream var8 = new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
try {
int var9 = var8.readInt();
GuiScreen var4 = this.mc.currentScreen;
if (var4 != null && var4 instanceof GuiMerchant && var9 == this.mc.thePlayer.openContainer.windowId) {
IMerchant var5 = ((GuiMerchant)var4).getIMerchant();
MerchantRecipeList var6 = MerchantRecipeList.readRecipiesFromStream(var8);
var5.setRecipes(var6);
}
} catch (IOException var7) {
var7.printStackTrace();
}
}
}
/**
* Return the NetworkManager instance used by this NetClientHandler
*/
public INetworkManager getNetManager() {
return this.netManager;
}
}
| true | false | null | null |
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/model/PermissionCurator.java b/proxy/src/main/java/org/fedoraproject/candlepin/model/PermissionCurator.java
index b4ffbd716..d5819cc6d 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/model/PermissionCurator.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/model/PermissionCurator.java
@@ -1,34 +1,49 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.model;
import org.fedoraproject.candlepin.auth.Verb;
import org.hibernate.criterion.Restrictions;
/**
* PermissionCurator
*/
public class PermissionCurator extends AbstractHibernateCurator<Permission> {
protected PermissionCurator() {
super(Permission.class);
}
+ /**
+ * Return the permission for this owner and verb if it exists, create it otherwise.
+ * @param owner Owner
+ * @param verb Verb
+ * @return Permission object.
+ */
+ public Permission findOrCreate(Owner owner, Verb verb) {
+ Permission p = findByOwnerAndVerb(owner, verb);
+ if (p == null) {
+ p = new Permission(owner, verb);
+ create(p);
+ }
+ return p;
+ }
+
public Permission findByOwnerAndVerb(Owner owner, Verb verb) {
return (Permission) currentSession().createCriteria(Permission.class)
.add(Restrictions.eq("owner", owner))
.add(Restrictions.eq("verb", verb)).uniqueResult();
}
}
diff --git a/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/OwnerResourceTest.java b/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/OwnerResourceTest.java
index 029892822..8ec23b6a1 100644
--- a/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/OwnerResourceTest.java
+++ b/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/OwnerResourceTest.java
@@ -1,501 +1,500 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.resource.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.fedoraproject.candlepin.audit.Event;
import org.fedoraproject.candlepin.audit.EventFactory;
import org.fedoraproject.candlepin.auth.ConsumerPrincipal;
import org.fedoraproject.candlepin.auth.Principal;
import org.fedoraproject.candlepin.auth.Verb;
import org.fedoraproject.candlepin.config.CandlepinCommonTestConfig;
import org.fedoraproject.candlepin.config.Config;
import org.fedoraproject.candlepin.config.ConfigProperties;
import org.fedoraproject.candlepin.exceptions.BadRequestException;
import org.fedoraproject.candlepin.exceptions.ForbiddenException;
import org.fedoraproject.candlepin.model.Consumer;
import org.fedoraproject.candlepin.model.Entitlement;
import org.fedoraproject.candlepin.model.Owner;
import org.fedoraproject.candlepin.model.Pool;
import org.fedoraproject.candlepin.model.Product;
import org.fedoraproject.candlepin.model.Subscription;
import org.fedoraproject.candlepin.model.User;
import org.fedoraproject.candlepin.resource.OwnerResource;
import org.fedoraproject.candlepin.test.DatabaseTestFixture;
import org.fedoraproject.candlepin.test.TestUtil;
import org.jboss.resteasy.plugins.providers.atom.Entry;
import org.jboss.resteasy.plugins.providers.atom.Feed;
import org.junit.Before;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.fedoraproject.candlepin.model.Permission;
import org.fedoraproject.candlepin.model.Role;
-import org.fedoraproject.candlepin.model.UserCurator;
/**
* OwnerResourceTest
*/
public class OwnerResourceTest extends DatabaseTestFixture {
private static final String OWNER_NAME = "Jar Jar Binks";
private OwnerResource ownerResource;
private Owner owner;
private List<Owner> owners;
private Product product;
private EventFactory eventFactory;
private CandlepinCommonTestConfig config;
@Before
public void setUp() {
this.ownerResource = injector.getInstance(OwnerResource.class);
owner = ownerCurator.create(new Owner(OWNER_NAME));
owners = new ArrayList<Owner>();
owners.add(owner);
product = TestUtil.createProduct();
productCurator.create(product);
eventFactory = injector.getInstance(EventFactory.class);
this.config = (CandlepinCommonTestConfig) injector
.getInstance(Config.class);
}
@Test
public void testCreateOwner() {
assertNotNull(owner);
assertNotNull(ownerCurator.find(owner.getId()));
assertTrue(owner.getPools().isEmpty());
}
@Test
public void testSimpleDeleteOwner() {
String id = owner.getId();
ownerResource.deleteOwner(owner.getKey(), true, TestUtil.createPrincipal(
"someuser", owner, Verb.OWNER_ADMIN));
owner = ownerCurator.find(id);
assertNull(owner);
}
@Test
public void testGetUsers() {
String ownerName = owner.getKey();
User user = new User();
user.setUsername("someusername");
user.setPassword("somepassword");
userCurator.create(user);
Role role = new Role();
role.addUser(user);
role.addPermission(new Permission(owner, Verb.OWNER_ADMIN));
user.addRole(role);
roleCurator.create(role);
User user2 = new User();
user2.setUsername("someotherusername");
user2.setPassword("someotherpassword");
user2.addRole(role);
userCurator.create(user2);
roleCurator.merge(role);
List<User> users = ownerResource.getUsers(ownerName);
assertEquals(users.size(), 2);
assertEquals(users.get(1), user2);
}
@Test
public void testRefreshPoolsWithNewSubscriptions() {
Product prod = TestUtil.createProduct();
productCurator.create(prod);
Subscription sub = new Subscription(owner, prod,
new HashSet<Product>(), 2000L, TestUtil.createDate(2010, 2, 9),
TestUtil.createDate(3000, 2, 9), TestUtil.createDate(2010, 2, 12));
subCurator.create(sub);
// Trigger the refresh:
poolManager.refreshPools(owner);
List<Pool> pools = poolCurator.listByOwnerAndProduct(owner,
prod.getId());
assertEquals(1, pools.size());
Pool newPool = pools.get(0);
assertEquals(sub.getId(), newPool.getSubscriptionId());
assertEquals(sub.getQuantity(), newPool.getQuantity());
assertEquals(sub.getStartDate(), newPool.getStartDate());
assertEquals(sub.getEndDate(), newPool.getEndDate());
}
@Test
public void testRefreshPoolsWithChangedSubscriptions() {
Product prod = TestUtil.createProduct();
productCurator.create(prod);
Pool pool = createPoolAndSub(createOwner(), prod, 1000L,
TestUtil.createDate(2009, 11, 30),
TestUtil.createDate(2015, 11, 30));
Owner owner = pool.getOwner();
Subscription sub = new Subscription(owner, prod,
new HashSet<Product>(), 2000L, TestUtil.createDate(2010, 2, 9),
TestUtil.createDate(3000, 2, 9), TestUtil.createDate(2010, 2, 12));
subCurator.create(sub);
assertTrue(pool.getQuantity() < sub.getQuantity());
assertTrue(pool.getStartDate() != sub.getStartDate());
assertTrue(pool.getEndDate() != sub.getEndDate());
pool.setSubscriptionId(sub.getId());
poolCurator.merge(pool);
poolManager.refreshPools(owner);
pool = poolCurator.find(pool.getId());
assertEquals(sub.getId(), pool.getSubscriptionId());
assertEquals(sub.getQuantity(), pool.getQuantity());
assertEquals(sub.getStartDate(), pool.getStartDate());
assertEquals(sub.getEndDate(), pool.getEndDate());
}
@Test
public void testRefreshPoolsWithRemovedSubscriptions() {
Product prod = TestUtil.createProduct();
productCurator.create(prod);
Subscription sub = new Subscription(owner, prod,
new HashSet<Product>(), 2000L, TestUtil.createDate(2010, 2, 9),
TestUtil.createDate(3000, 2, 9), TestUtil.createDate(2010, 2, 12));
subCurator.create(sub);
// Trigger the refresh:
poolManager.refreshPools(owner);
List<Pool> pools = poolCurator.listByOwnerAndProduct(owner,
prod.getId());
assertEquals(1, pools.size());
Pool newPool = pools.get(0);
String poolId = newPool.getId();
// Now delete the subscription:
subCurator.delete(sub);
// Trigger the refresh:
poolManager.refreshPools(owner);
assertNull("Pool not having subscription should have been deleted",
poolCurator.find(poolId));
}
@Test
public void testRefreshMultiplePools() {
Product prod = TestUtil.createProduct();
productCurator.create(prod);
Product prod2 = TestUtil.createProduct();
productCurator.create(prod2);
Subscription sub = new Subscription(owner, prod,
new HashSet<Product>(), 2000L, TestUtil.createDate(2010, 2, 9),
TestUtil.createDate(3000, 2, 9), TestUtil.createDate(2010, 2, 12));
subCurator.create(sub);
Subscription sub2 = new Subscription(owner, prod2,
new HashSet<Product>(), 800L, TestUtil.createDate(2010, 2, 9),
TestUtil.createDate(3000, 2, 9), TestUtil.createDate(2010, 2, 12));
subCurator.create(sub2);
// Trigger the refresh:
poolManager.refreshPools(owner);
List<Pool> pools = poolCurator.listByOwner(owner);
assertEquals(2, pools.size());
}
@Test
public void testComplexDeleteOwner() throws Exception {
// Create some consumers:
Consumer c1 = TestUtil.createConsumer(owner);
consumerTypeCurator.create(c1.getType());
consumerCurator.create(c1);
Consumer c2 = TestUtil.createConsumer(owner);
consumerTypeCurator.create(c2.getType());
consumerCurator.create(c2);
// Create a pool for this owner:
Pool pool = TestUtil.createPool(owner, product);
poolCurator.create(pool);
// Give those consumers entitlements:
poolManager.entitleByPool(c1, pool, 1);
assertEquals(2, consumerCurator.listByOwner(owner).size());
assertEquals(1, poolCurator.listByOwner(owner).size());
assertEquals(1, entitlementCurator.listByOwner(owner).size());
ownerResource.deleteOwner(owner.getKey(), true, null);
assertEquals(0, consumerCurator.listByOwner(owner).size());
assertNull(consumerCurator.findByUuid(c1.getUuid()));
assertNull(consumerCurator.findByUuid(c2.getUuid()));
assertEquals(0, poolCurator.listByOwner(owner).size());
assertEquals(0, entitlementCurator.listByOwner(owner).size());
}
@Test(expected = ForbiddenException.class)
public void testConsumerRoleCannotGetOwner() {
Consumer c = TestUtil.createConsumer(owner);
consumerTypeCurator.create(c.getType());
consumerCurator.create(c);
setupPrincipal(new ConsumerPrincipal(c));
securityInterceptor.enable();
crudInterceptor.enable();
ownerResource.getOwner(owner.getKey());
}
@Test
public void testOwnerAdminCanGetPools() {
setupPrincipal(owner, Verb.OWNER_ADMIN);
Product p = TestUtil.createProduct();
productCurator.create(p);
Pool pool1 = TestUtil.createPool(owner, p);
Pool pool2 = TestUtil.createPool(owner, p);
poolCurator.create(pool1);
poolCurator.create(pool2);
List<Pool> pools = ownerResource.ownerEntitlementPools(owner.getKey(),
null, null, true, null);
assertEquals(2, pools.size());
}
@Test
public void testOwnerAdminCannotAccessAnotherOwnersPools() {
Owner evilOwner = new Owner("evilowner");
ownerCurator.create(evilOwner);
setupPrincipal(evilOwner, Verb.OWNER_ADMIN);
Product p = TestUtil.createProduct();
productCurator.create(p);
Pool pool1 = TestUtil.createPool(owner, p);
Pool pool2 = TestUtil.createPool(owner, p);
poolCurator.create(pool1);
poolCurator.create(pool2);
securityInterceptor.enable();
crudInterceptor.enable();
// Filtering should just cause this to return no results:
List<Pool> pools = ownerResource.ownerEntitlementPools(owner.getKey(),
null, null, true, null);
assertEquals(0, pools.size());
}
@Test(expected = ForbiddenException.class)
public void testOwnerAdminCannotListAllOwners() {
setupPrincipal(owner, Verb.OWNER_ADMIN);
securityInterceptor.enable();
crudInterceptor.enable();
ownerResource.list(null);
}
@Test(expected = ForbiddenException.class)
public void testOwnerAdminCannotDelete() {
Principal principal = setupPrincipal(owner, Verb.OWNER_ADMIN);
securityInterceptor.enable();
crudInterceptor.enable();
ownerResource.deleteOwner(owner.getKey(), true, principal);
}
private Event createConsumerCreatedEvent(Owner o) {
// Rather than run through an entire call to ConsumerResource, we'll
// fake the
// events in the db:
setupPrincipal(o, Verb.OWNER_ADMIN);
Consumer consumer = TestUtil.createConsumer(o);
consumerTypeCurator.create(consumer.getType());
consumerCurator.create(consumer);
Event e1 = eventFactory.consumerCreated(consumer);
eventCurator.create(e1);
return e1;
}
@Test
public void testOwnersAtomFeed() {
Owner owner2 = new Owner("anotherOwner");
ownerCurator.create(owner2);
securityInterceptor.enable();
crudInterceptor.enable();
Event e1 = createConsumerCreatedEvent(owner);
// Make an event from another owner:
createConsumerCreatedEvent(owner2);
// Make sure we're acting as the correct owner admin:
setupPrincipal(owner, Verb.OWNER_ADMIN);
Feed feed = ownerResource.getOwnerAtomFeed(owner.getKey());
assertEquals(1, feed.getEntries().size());
Entry entry = feed.getEntries().get(0);
assertEquals(e1.getTimestamp(), entry.getPublished());
}
@Test
public void testOwnerCannotAccessAnotherOwnersAtomFeed() {
Owner owner2 = new Owner("anotherOwner");
ownerCurator.create(owner2);
securityInterceptor.enable();
crudInterceptor.enable();
// Or more specifically, gets no results, the call will not error out
// because he has the correct role.
createConsumerCreatedEvent(owner);
setupPrincipal(owner2, Verb.OWNER_ADMIN);
Feed feed = ownerResource.getOwnerAtomFeed(owner.getKey());
System.out.println(feed);
assertEquals(0, feed.getEntries().size());
}
@Test(expected = ForbiddenException.class)
public void testConsumerRoleCannotAccessOwnerAtomFeed() {
Consumer c = TestUtil.createConsumer(owner);
consumerTypeCurator.create(c.getType());
consumerCurator.create(c);
setupPrincipal(new ConsumerPrincipal(c));
securityInterceptor.enable();
crudInterceptor.enable();
ownerResource.getOwnerAtomFeed(owner.getKey());
}
@Test
public void testEntitlementsRevocationWithFifoOrder() {
Pool pool = doTestEntitlementsRevocationCommon(7, 4, 4, true);
assertTrue(this.poolCurator.find(pool.getId()).getConsumed() == 4);
}
@Test
public void testEntitlementsRevocationWithLifoOrder() {
Pool pool = doTestEntitlementsRevocationCommon(7, 4, 5, false);
assertEquals(5L, this.poolCurator.find(pool.getId()).getConsumed()
.longValue());
}
@Test
public void testEntitlementsRevocationWithNoOverflow() {
Pool pool = doTestEntitlementsRevocationCommon(10, 4, 5, false);
assertTrue(this.poolCurator.find(pool.getId()).getConsumed() == 9);
}
private Pool doTestEntitlementsRevocationCommon(long subQ, int e1, int e2,
boolean fifo) {
Product prod = TestUtil.createProduct();
productCurator.create(prod);
Pool pool = createPoolAndSub(createOwner(), prod, 1000L,
TestUtil.createDate(2009, 11, 30),
TestUtil.createDate(2015, 11, 30));
Owner owner = pool.getOwner();
Consumer consumer = createConsumer(owner);
Consumer consumer1 = createConsumer(owner);
Subscription sub = this.subCurator.find(pool.getSubscriptionId());
sub.setQuantity(subQ);
this.subCurator.merge(sub);
// this.ownerResource.refreshEntitlementPools(owner.getKey(), false);
pool = this.poolCurator.find(pool.getId());
createEntitlementWithQ(pool, owner, consumer, e1, "01/02/2010");
createEntitlementWithQ(pool, owner, consumer1, e2, "01/01/2010");
assertEquals(pool.getConsumed(), Long.valueOf(e1 + e2));
this.config.setProperty(
ConfigProperties.REVOKE_ENTITLEMENT_IN_FIFO_ORDER, fifo ? "true"
: "false");
poolManager.refreshPools(owner);
pool = poolCurator.find(pool.getId());
return pool;
}
/**
* @param pool
* @param owner
* @param consumer
* @return
*/
private Entitlement createEntitlementWithQ(Pool pool, Owner owner,
Consumer consumer, int quantity, String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Entitlement e1 = createEntitlement(owner, consumer, pool, null);
e1.setQuantity(quantity);
pool.getEntitlements().add(e1);
this.entitlementCurator.create(e1);
this.poolCurator.merge(e1.getPool());
this.poolCurator.refresh(pool);
try {
e1.setCreated(dateFormat.parse(date));
this.entitlementCurator.merge(e1);
}
catch (ParseException e) {
e.printStackTrace();
}
return e1;
}
@Test
public void ownerWithParentOwnerCanBeCreated() {
Owner child = new Owner("name", "name1");
child.setParentOwner(this.owner);
this.ownerResource.createOwner(child);
assertNotNull(ownerCurator.find(child.getId()));
assertNotNull(child.getParentOwner());
assertEquals(this.owner.getId(), child.getParentOwner().getId());
}
@Test(expected = BadRequestException.class)
public void ownerWithInvalidParentCannotBeCreated() {
Owner child = new Owner("name", "name1");
Owner owner1 = new Owner("name2", "name3");
owner1.setId("xyz");
child.setParentOwner(owner1);
this.ownerResource.createOwner(child);
throw new RuntimeException(
"OwnerResource should have thrown BadRequestException");
}
@Test(expected = BadRequestException.class)
public void ownerWithInvalidParentWhoseIdIsNullCannotBeCreated() {
Owner child = new Owner("name", "name1");
Owner owner1 = new Owner("name2", "name3");
child.setParentOwner(owner1);
this.ownerResource.createOwner(child);
throw new RuntimeException(
"OwnerResource should have thrown BadRequestException");
}
}
diff --git a/proxy/src/test/java/org/fedoraproject/candlepin/test/DatabaseTestFixture.java b/proxy/src/test/java/org/fedoraproject/candlepin/test/DatabaseTestFixture.java
index d4cf3855f..dfdc4da50 100644
--- a/proxy/src/test/java/org/fedoraproject/candlepin/test/DatabaseTestFixture.java
+++ b/proxy/src/test/java/org/fedoraproject/candlepin/test/DatabaseTestFixture.java
@@ -1,303 +1,304 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.test;
+import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import org.fedoraproject.candlepin.CandlepinCommonTestingModule;
import org.fedoraproject.candlepin.CandlepinNonServletEnvironmentTestingModule;
import org.fedoraproject.candlepin.TestingInterceptor;
import org.fedoraproject.candlepin.auth.Principal;
+import org.fedoraproject.candlepin.auth.UserPrincipal;
import org.fedoraproject.candlepin.auth.Verb;
import org.fedoraproject.candlepin.controller.CandlepinPoolManager;
import org.fedoraproject.candlepin.guice.TestPrincipalProviderSetter;
import org.fedoraproject.candlepin.model.CertificateSerial;
import org.fedoraproject.candlepin.model.CertificateSerialCurator;
import org.fedoraproject.candlepin.model.Consumer;
import org.fedoraproject.candlepin.model.ConsumerCurator;
import org.fedoraproject.candlepin.model.ConsumerType;
import org.fedoraproject.candlepin.model.ConsumerTypeCurator;
import org.fedoraproject.candlepin.model.ContentCurator;
import org.fedoraproject.candlepin.model.Entitlement;
import org.fedoraproject.candlepin.model.EntitlementCertificate;
import org.fedoraproject.candlepin.model.EntitlementCertificateCurator;
import org.fedoraproject.candlepin.model.EntitlementCurator;
import org.fedoraproject.candlepin.model.EventCurator;
import org.fedoraproject.candlepin.model.Role;
import org.fedoraproject.candlepin.model.Owner;
import org.fedoraproject.candlepin.model.OwnerCurator;
import org.fedoraproject.candlepin.model.Permission;
import org.fedoraproject.candlepin.model.PermissionCurator;
import org.fedoraproject.candlepin.model.Pool;
import org.fedoraproject.candlepin.model.PoolCurator;
import org.fedoraproject.candlepin.model.Product;
import org.fedoraproject.candlepin.model.ProductAttributeCurator;
import org.fedoraproject.candlepin.model.ProductCertificateCurator;
import org.fedoraproject.candlepin.model.ProductCurator;
import org.fedoraproject.candlepin.model.ProvidedProduct;
import org.fedoraproject.candlepin.model.RoleCurator;
import org.fedoraproject.candlepin.model.RulesCurator;
import org.fedoraproject.candlepin.model.Subscription;
import org.fedoraproject.candlepin.model.SubscriptionCurator;
import org.fedoraproject.candlepin.model.SubscriptionToken;
import org.fedoraproject.candlepin.model.SubscriptionTokenCurator;
import org.fedoraproject.candlepin.model.SubscriptionsCertificateCurator;
import org.fedoraproject.candlepin.model.UserCurator;
import org.fedoraproject.candlepin.service.EntitlementCertServiceAdapter;
import org.fedoraproject.candlepin.service.ProductServiceAdapter;
import org.fedoraproject.candlepin.service.SubscriptionServiceAdapter;
import org.fedoraproject.candlepin.util.DateSource;
import org.junit.Before;
import org.xnap.commons.i18n.I18n;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.util.Modules;
import com.wideplay.warp.persist.PersistenceService;
import com.wideplay.warp.persist.UnitOfWork;
import com.wideplay.warp.persist.WorkManager;
/**
* Test fixture for test classes requiring access to the database.
*/
public class DatabaseTestFixture {
private static final String DEFAULT_CONTRACT = "SUB349923";
private static final String DEFAULT_ACCOUNT = "ACC123";
protected EntityManagerFactory emf;
protected Injector injector;
protected OwnerCurator ownerCurator;
protected UserCurator userCurator;
protected ProductCurator productCurator;
protected ProductCertificateCurator productCertificateCurator;
protected ProductServiceAdapter productAdapter;
protected SubscriptionServiceAdapter subAdapter;
protected ConsumerCurator consumerCurator;
protected ConsumerTypeCurator consumerTypeCurator;
protected SubscriptionsCertificateCurator certificateCurator;
protected PoolCurator poolCurator;
protected DateSourceForTesting dateSource;
protected EntitlementCurator entitlementCurator;
protected ProductAttributeCurator attributeCurator;
protected RulesCurator rulesCurator;
protected EventCurator eventCurator;
protected SubscriptionCurator subCurator;
protected SubscriptionTokenCurator subTokenCurator;
protected ContentCurator contentCurator;
protected WorkManager unitOfWork;
protected HttpServletRequest httpServletRequest;
protected EntitlementCertificateCurator entCertCurator;
protected CertificateSerialCurator certSerialCurator;
protected PermissionCurator permissionCurator;
protected RoleCurator roleCurator;
protected I18n i18n;
protected TestingInterceptor crudInterceptor;
protected TestingInterceptor securityInterceptor;
protected EntitlementCertServiceAdapter entitlementCertService;
protected CandlepinPoolManager poolManager;
@Before
public void init() {
Module guiceOverrideModule = getGuiceOverrideModule();
CandlepinCommonTestingModule testingModule = new CandlepinCommonTestingModule();
if (guiceOverrideModule == null) {
injector = Guice.createInjector(
testingModule,
new CandlepinNonServletEnvironmentTestingModule(),
PersistenceService.usingJpa()
.across(UnitOfWork.REQUEST)
.buildModule()
);
}
else {
injector = Guice.createInjector(
Modules.override(testingModule).with(
guiceOverrideModule),
new CandlepinNonServletEnvironmentTestingModule(),
PersistenceService.usingJpa()
.across(UnitOfWork.REQUEST)
.buildModule()
);
}
injector.getInstance(EntityManagerFactory.class);
emf = injector.getProvider(EntityManagerFactory.class).get();
ownerCurator = injector.getInstance(OwnerCurator.class);
userCurator = injector.getInstance(UserCurator.class);
productCurator = injector.getInstance(ProductCurator.class);
productCertificateCurator = injector.getInstance(ProductCertificateCurator.class);
consumerCurator = injector.getInstance(ConsumerCurator.class);
eventCurator = injector.getInstance(EventCurator.class);
permissionCurator = injector.getInstance(PermissionCurator.class);
roleCurator = injector.getInstance(RoleCurator.class);
consumerTypeCurator = injector.getInstance(ConsumerTypeCurator.class);
certificateCurator = injector.getInstance(SubscriptionsCertificateCurator.class);
poolCurator = injector.getInstance(PoolCurator.class);
entitlementCurator = injector.getInstance(EntitlementCurator.class);
attributeCurator = injector.getInstance(ProductAttributeCurator.class);
rulesCurator = injector.getInstance(RulesCurator.class);
subCurator = injector.getInstance(SubscriptionCurator.class);
subTokenCurator = injector.getInstance(SubscriptionTokenCurator.class);
contentCurator = injector.getInstance(ContentCurator.class);
unitOfWork = injector.getInstance(WorkManager.class);
productAdapter = injector.getInstance(ProductServiceAdapter.class);
subAdapter = injector.getInstance(SubscriptionServiceAdapter.class);
entCertCurator = injector.getInstance(EntitlementCertificateCurator.class);
certSerialCurator = injector.getInstance(CertificateSerialCurator.class);
entitlementCertService = injector.getInstance(EntitlementCertServiceAdapter.class);
poolManager = injector.getInstance(CandlepinPoolManager.class);
i18n = injector.getInstance(I18n.class);
crudInterceptor = testingModule.crudInterceptor();
securityInterceptor = testingModule.securityInterceptor();
dateSource = (DateSourceForTesting) injector.getInstance(DateSource.class);
dateSource.currentDate(TestDateUtil.date(2010, 1, 1));
}
protected Module getGuiceOverrideModule() {
return null;
}
protected EntityManager entityManager() {
return injector.getProvider(EntityManager.class).get();
}
/**
* Helper to open a new db transaction. Pretty simple for now, but may
* require additional logic and error handling down the road.
*/
protected void beginTransaction() {
entityManager().getTransaction().begin();
}
/**
* Helper to commit the current db transaction. Pretty simple for now, but may
* require additional logic and error handling down the road.
*/
protected void commitTransaction() {
entityManager().getTransaction().commit();
}
/**
* Create an entitlement pool and matching subscription.
* @return an entitlement pool and matching subscription.
*/
protected Pool createPoolAndSub(Owner owner, Product product, Long quantity,
Date startDate, Date endDate) {
Pool p = new Pool(owner, product.getId(), product.getName(),
new HashSet<ProvidedProduct>(), quantity,
startDate, endDate, DEFAULT_CONTRACT, DEFAULT_ACCOUNT);
Subscription sub = new Subscription(owner, product, new HashSet<Product>(),
quantity, startDate, endDate, TestUtil.createDate(2010, 2, 12));
subCurator.create(sub);
p.setSubscriptionId(sub.getId());
poolCurator.create(p);
return p;
}
protected Owner createOwner() {
Owner o = new Owner("Test Owner " + TestUtil.randomInt());
ownerCurator.create(o);
return o;
}
protected Consumer createConsumer(Owner owner) {
ConsumerType type = new ConsumerType("test-consumer-type-" + TestUtil.randomInt());
consumerTypeCurator.create(type);
Consumer c = new Consumer("test-consumer", "test-user", owner, type);
consumerCurator.create(c);
return c;
}
protected Subscription createSubscription() {
Product p = TestUtil.createProduct();
productCurator.create(p);
Subscription sub = new Subscription(createOwner(),
p, new HashSet<Product>(),
1000L,
TestUtil.createDate(2000, 1, 1),
TestUtil.createDate(2010, 1, 1),
TestUtil.createDate(2000, 1, 1));
subCurator.create(sub);
return sub;
}
protected SubscriptionToken createSubscriptionToken() {
Subscription sub = createSubscription();
SubscriptionToken token = new SubscriptionToken();
token.setToken("this_is_a_test_token");
token.setSubscription(sub);
sub.getTokens().add(token);
subCurator.create(sub);
subTokenCurator.create(token);
return token;
}
protected Entitlement createEntitlement(Owner owner, Consumer consumer,
Pool pool, EntitlementCertificate cert) {
return TestUtil.createEntitlement(owner, consumer, pool, cert);
}
protected EntitlementCertificate createEntitlementCertificate(String key, String cert) {
EntitlementCertificate toReturn = new EntitlementCertificate();
CertificateSerial certSerial = new CertificateSerial(new Date());
certSerialCurator.create(certSerial);
toReturn.setKeyAsBytes(key.getBytes());
toReturn.setCertAsBytes(cert.getBytes());
toReturn.setSerial(certSerial);
return toReturn;
}
protected Principal setupPrincipal(Owner owner, Verb role) {
return setupPrincipal("someuser", owner, role);
}
protected Principal setupPrincipal(String username, Owner owner, Verb verb) {
- Principal ownerAdmin = TestUtil.createPrincipal(username, owner, verb);
- for (Permission p : ownerAdmin.getPermissions()) {
- permissionCurator.create(p);
- }
+ Permission p = permissionCurator.findOrCreate(owner, verb);
+ Principal ownerAdmin = new UserPrincipal(username, Arrays.asList(new Permission[] {
+ p}));
setupPrincipal(ownerAdmin);
return ownerAdmin;
}
protected void setupPrincipal(Principal p) {
// TODO: might be good to get rid of this singleton
TestPrincipalProviderSetter.get().setPrincipal(p);
}
public Role createAdminRole(Owner owner) {
Permission p = new Permission(owner, Verb.OWNER_ADMIN);
Role role = new Role();
role.addPermission(p);
return role;
}
}
| false | false | null | null |
diff --git a/src/java/com/bigml/histogram/Histogram.java b/src/java/com/bigml/histogram/Histogram.java
index 7d3ed26..f25e841 100644
--- a/src/java/com/bigml/histogram/Histogram.java
+++ b/src/java/com/bigml/histogram/Histogram.java
@@ -1,606 +1,606 @@
package com.bigml.histogram;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.TreeSet;
import org.json.simple.JSONArray;
/**
* Implements a Histogram as defined by the <a
* href="http://jmlr.csail.mit.edu/papers/v11/ben-haim10a.html">
* Streaming Parallel Decision Tree (SPDT)</a> algorithm. <p>The
* Histogram consumes numeric points and maintains a running
* approximation of the dataset using the given number of bins. The
* methods <code>insert</code>, <code>sum</code>, and
* <code>uniform</code> are described in detail in the SPDT paper.
*
* <p>The histogram has an <code>insert</code> method which uses two
* parameters and an <code>extendedSum</code> method which add the
* capabilities described in <a
* href="http://research.engineering.wustl.edu/~tyrees/Publications_files/fr819-tyreeA.pdf">
* Tyree's paper</a>. Along with Tyree's extension this histogram
* supports inserts with categorical targets.
*
* @author Adam Ashenfelter ([email protected])
*/
public class Histogram<T extends Target> {
public static final String DEFAULT_FORMAT_STRING = "#.#####";
/**
* Creates an empty Histogram with the defined number of bins
*
* @param maxBins the maximum number of bins for this histogram
* @param countWeightedGaps true if count weighted gaps are desired
* @param categories if the histogram uses categorical targets
* then a collection of the possible category targets may be
* provided to increase performance
*/
public Histogram(int maxBins, boolean countWeightedGaps, Collection<Object> categories) {
_maxBins = maxBins;
_bins = new TreeMap<Double, Bin<T>>();
_gaps = new TreeSet<Gap<T>>();
_binsToGaps = new HashMap<Double, Gap<T>>();
_decimalFormat = new DecimalFormat(DEFAULT_FORMAT_STRING);
_countWeightedGaps = countWeightedGaps;
if (categories != null && !categories.isEmpty()) {
_targetType = TargetType.categorical;
_indexMap = new HashMap<Object, Integer>();
for (Object category : categories) {
if (_indexMap.get(category) == null) {
_indexMap.put(category, _indexMap.size());
}
}
} else {
_indexMap = null;
}
}
/**
* Creates an empty Histogram with the defined number of bins
*
* @param maxBins the maximum number of bins for this histogram
* @param countWeightedGaps true if count weighted gaps are desired
*/
public Histogram(int maxBins, boolean countWeightedGaps) {
this(maxBins, countWeightedGaps, null);
}
/**
* Creates an empty Histogram with the defined number of bins
*
* @param maxBins the maximum number of bins for this histogram
*/
public Histogram(int maxBins) {
this(maxBins, false);
}
/**
* Inserts a new point into the histogram
*
* @param point the new point
*/
public Histogram<T> insert(double point) throws MixedInsertException {
checkType(TargetType.none);
insert(new Bin(point, 1, SimpleTarget.TARGET));
return this;
}
/**
* Inserts a new point with a numeric target into the histogram
*
* @param point the new point
* @param target the numeric target
*/
public Histogram<T> insert(double point, double target) throws MixedInsertException {
checkType(TargetType.numeric);
insert(new Bin(point, 1, new NumericTarget(target)));
return this;
}
/**
* Inserts a new point with a categorical target into the histogram
*
* @param point the new point
* @param target the categorical target
*/
public Histogram<T> insert(double point, String target) throws MixedInsertException {
return insertCategorical(point, target);
}
/**
* Inserts a new point with a group of targets into the histogram
*
* @param point the new point
* @param target the group targets
*/
public Histogram<T> insert(double point, Collection<Object> group) throws MixedInsertException {
checkType(TargetType.group);
insert(new Bin(point, 1, new GroupTarget(group)));
return this;
}
/**
* Inserts a new point with a categorical target into the histogram
*
* @param point the new point
* @param target the categorical target
*/
public Histogram<T> insertCategorical(double point, Object target)
throws MixedInsertException {
checkType(TargetType.categorical);
Target catTarget;
if (_indexMap == null) {
catTarget = new MapCategoricalTarget(target);
} else {
catTarget = new ArrayCategoricalTarget(_indexMap, target);
}
insert(new Bin(point, 1, catTarget));
return this;
}
/**
* Inserts a new bin into the histogram
*
* @param bin the new bin
*/
public Histogram<T> insert(Bin<T> bin) {
insertBin(bin);
mergeBins();
return this;
}
/**
* Returns the target type for the histogram
*/
public TargetType getTargetType() {
return _targetType;
}
/**
* Returns the approximate number of points less than
* <code>p</code>
*
* @param p the sum point
*/
public double sum(double p) throws SumOutOfRangeException {
return extendedSum(p).getCount();
}
/**
* Returns a <code>SumResult</code> object which contains the
* approximate number of points less than <code>p</code> along
* with the sum of their targets.
*
* @param p the sum point
*/
public SumResult<T> extendedSum(double p) throws SumOutOfRangeException {
SumResult<T> result = null;
double min = _bins.firstKey();
double max = _bins.lastKey();
if (p < min || p > max) {
throw new SumOutOfRangeException("Sum point " + p + " should be between "
+ min + " and " + max);
} else if (p == max) {
Bin<T> lastBin = _bins.lastEntry().getValue();
double totalCount = this.getTotalCount();
double count = totalCount - (lastBin.getCount() / 2d);
T targetSum = (T) lastBin.getTarget().clone().mult(0.5d);
Entry<Double, Bin<T>> prevEntry = _bins.lowerEntry(lastBin.getMean());
if (prevEntry != null) {
targetSum.sum(prevEntry.getValue().getTarget().clone());
}
result = new SumResult<T>(count, targetSum);
} else {
Bin<T> bin_i = _bins.floorEntry(p).getValue();
Bin<T> bin_i1 = _bins.higherEntry(p).getValue();
double prevCount = 0;
T prevTargetSum = (T) _bins.firstEntry().getValue().getTarget().init();
for (Bin<T> bin : _bins.values()) {
if (bin.equals(bin_i)) {
break;
}
prevCount += bin.getCount();
prevTargetSum.sum(bin.getTarget().clone());
}
double bDiff = p - bin_i.getMean();
double pDiff = bin_i1.getMean() - bin_i.getMean();
double bpRatio = bDiff / pDiff;
NumericTarget countTarget = (NumericTarget) computeSum(bpRatio, new NumericTarget(prevCount),
new NumericTarget(bin_i.getCount()), new NumericTarget(bin_i1.getCount()));
double countSum = countTarget.getTarget();
T targetSum = (T) computeSum(bpRatio, prevTargetSum, bin_i.getTarget(), bin_i1.getTarget());
result = new SumResult<T>(countSum, targetSum);
}
return result;
}
/**
* Returns the density estimate at point p
* <code>p</code>
*
* @param p the density estimate point
*/
public double density(double p) {
return extendedDensity(p).getCount();
}
/**
* Returns a <code>SumResult</code> object which contains the
* density estimate at the point <code>p</code> along
* with the density for the targets.
*
* @param p the density estimate point
*/
public SumResult<T> extendedDensity(double p) {
double countDensity;
T targetDensity;
Bin<T> exact = _bins.get(p);
if (exact != null) {
double higher = Double.longBitsToDouble(Double.doubleToLongBits(p) + 1);
double lower = Double.longBitsToDouble(Double.doubleToLongBits(p) - 1);
countDensity = (density(higher) + density(lower)) / 2;
targetDensity = (T) exact.getTarget().clone().mult(countDensity);
} else {
Entry<Double, Bin<T>> lower = _bins.lowerEntry(p);
Entry<Double, Bin<T>> higher = _bins.higherEntry(p);
if (lower == null && higher == null) {
countDensity = 0;
targetDensity = null;
} else if (lower == null || higher == null) {
Bin<T> bin;
if (lower != null) {
bin = lower.getValue();
} else {
bin = higher.getValue();
}
if (Math.abs(p - bin.getMean()) < binGapRange(p, bin)) {
countDensity = binGapDensity(p, bin);
targetDensity = (T) bin.getTarget().clone().mult(countDensity);
} else {
countDensity = 0;
targetDensity = null;
}
} else {
Bin<T> hBin = higher.getValue();
double hDensity = binGapDensity(p, hBin);
Bin<T> lBin = lower.getValue();
double lDensity = binGapDensity(p, lBin);
countDensity = hDensity + lDensity;
T lTargetDensity = (T) lBin.getTarget().clone().mult(lDensity);
T hTargetDensity = (T) hBin.getTarget().clone().mult(hDensity);
targetDensity = (T) lTargetDensity.sum(hTargetDensity);
}
}
return new SumResult<T>(countDensity, targetDensity);
}
/**
* Returns a list containing split points that form bins with
* uniform membership
*
* @param numberOfBins the desired number of uniform bins
*/
public ArrayList<Double> uniform(int numberOfBins) {
ArrayList<Double> uniformBinSplits = new ArrayList<Double>();
double totalCount = getTotalCount();
if (totalCount > 0) {
TreeMap<Double, Bin<T>> binSumMap = createBinSumMap();
double gapSize = totalCount / (double) numberOfBins;
double minGapSize = Math.max(_bins.firstEntry().getValue().getCount(),
_bins.lastEntry().getValue().getCount()) / 2;
int splits = numberOfBins;
if (gapSize < minGapSize) {
splits = (int) (totalCount / minGapSize);
gapSize = totalCount / (double) splits;
}
for (int i = 1; i < splits; i++) {
double targetSum = (double) i * gapSize;
double binSplit = findPointForSum(targetSum, binSumMap);
uniformBinSplits.add(binSplit);
}
}
return uniformBinSplits;
}
/**
* Merges a histogram into the current histogram
*
* @param histogram the histogram to be merged
*/
public Histogram merge(Histogram<T> histogram) throws MixedInsertException {
if (_indexMap == null && histogram._indexMap != null) {
if (getBins().isEmpty()) {
_indexMap = histogram._indexMap;
} else {
throw new MixedInsertException();
}
}
if (_indexMap != null && !_indexMap.equals(histogram._indexMap)) {
throw new MixedInsertException();
} else if (!histogram.getBins().isEmpty()) {
checkType(histogram.getTargetType());
for (Bin<T> bin : histogram.getBins()) {
Bin<T> newBin = new Bin<T>(bin);
if (_indexMap != null) {
((ArrayCategoricalTarget) newBin.getTarget()).setIndexMap(_indexMap);
}
insertBin(new Bin<T>(bin));
}
mergeBins();
}
return this;
}
/**
* Returns the total number of points in the histogram
*/
public double getTotalCount() {
double count = 0;
for (Bin<T> bin : _bins.values()) {
count += bin.getCount();
}
return count;
}
/**
* Returns the collection of bins that form the histogram
*/
public Collection<Bin<T>> getBins() {
return _bins.values();
}
public JSONArray toJSON(DecimalFormat format) {
JSONArray bins = new JSONArray();
for (Bin<T> bin : getBins()) {
bins.add(bin.toJSON(format));
}
return bins;
}
public String toJSONString(DecimalFormat format) {
return toJSON(format).toJSONString();
}
@Override
public String toString() {
return toJSONString(_decimalFormat);
}
public T getTotalTargetSum() {
T target = null;
for (Bin<T> bin : _bins.values()) {
if (target == null) {
target = (T) bin.getTarget().init();
}
target.sum(bin.getTarget().clone());
}
return target;
}
private void checkType(TargetType newType) throws MixedInsertException {
if (_targetType == null) {
_targetType = newType;
} else if (_targetType != newType || newType == null) {
throw new MixedInsertException();
}
}
private void insertBin(Bin<T> bin) {
Bin<T> existingBin = _bins.get(bin.getMean());
if (existingBin != null) {
try {
existingBin.sumUpdate(bin);
if (_countWeightedGaps) {
- updateGaps(bin);
+ updateGaps(existingBin);
}
} catch (BinUpdateException ex) {
}
} else {
updateGaps(bin);
_bins.put(bin.getMean(), bin);
}
}
private TreeMap<Double, Bin<T>> createBinSumMap() {
TreeMap<Double, Bin<T>> binSumMap = new TreeMap<Double, Bin<T>>();
for (Bin<T> bin : _bins.values()) {
try {
double sum = sum(bin.getMean());
binSumMap.put(sum, bin);
} catch (SumOutOfRangeException e) {
}
}
return binSumMap;
}
private double binGapRange(double p, Bin<T> bin) {
Entry<Double, Bin<T>> lower = _bins.lowerEntry(bin.getMean());
Entry<Double, Bin<T>> higher = _bins.higherEntry(bin.getMean());
double range;
if (lower == null && higher == null) {
range = 0;
} else if (lower == null) {
range = higher.getValue().getMean() - bin.getMean();
} else if (higher == null) {
range = bin.getMean() - lower.getValue().getMean();
} else {
if (p < bin.getMean()) {
range = bin.getMean() - lower.getValue().getMean();
} else {
range = higher.getValue().getMean() - bin.getMean();
}
}
return range;
}
private double binGapDensity(double p, Bin<T> bin) {
double range = binGapRange(p, bin);
if (range == 0) {
return 0;
} else {
return (bin.getCount() / 2) / range;
}
}
// m = i + (i1 - i) * r
// s = p + i/2 + (m + i) * r/2
// s = p + i/2 + (i + (i1 - i) * r + i) * r/2
// s = p + i/2 + (i + r*i1 - r*i + i) * r/2
// s = p + i/2 + r/2*i + r^2/2*i1 - r^2/2*i + r/2*i
// s = p + i/2 + r/2*i + r/2*i - r^2/2*i + r^2/2*i1
// s = p + i/2 + r*i - r^2/2*i + r^2/2*i1
// s = p + (1/2 + r - r^2/2)*i + r^2/2*i1
private <U extends Target> Target computeSum(double r, U p, U i, U i1) {
double i1Term = 0.5 * r * r;
double iTerm = 0.5 + r - i1Term;
return (U) p.sum(i.clone().mult(iTerm)).sum(i1.clone().mult(i1Term));
}
private double findPointForSum(double s, TreeMap<Double, Bin<T>> binSumMap) {
Entry<Double, Bin<T>> sumEntry = binSumMap.floorEntry(s);
double sumP_i = sumEntry.getKey();
Bin<T> bin_i = sumEntry.getValue();
double p_i = bin_i.getMean();
double m_i = bin_i.getCount();
Double sumP_i1 = binSumMap.navigableKeySet().higher(sumP_i);
if (sumP_i1 == null) {
sumP_i1 = binSumMap.navigableKeySet().floor(sumP_i);
}
Bin<T> bin_i1 = binSumMap.get(sumP_i1);
double p_i1 = bin_i1.getMean();
double m_i1 = bin_i1.getCount();
double d = s - sumP_i;
double a = m_i1 - m_i;
double u;
if (a == 0) {
double offset = d / ((m_i + m_i1) / 2);
u = p_i + (offset * (p_i1 - p_i));
} else {
double b = 2 * m_i;
double c = -2 * d;
double z = findZ(a, b, c);
u = (p_i + (p_i1 - p_i) * z);
}
return u;
}
private void updateGaps(Bin<T> newBin) {
Entry<Double, Bin<T>> prevEntry = _bins.lowerEntry(newBin.getMean());
if (prevEntry != null) {
updateGaps(prevEntry.getValue(), newBin);
}
Entry<Double, Bin<T>> nextEntry = _bins.higherEntry(newBin.getMean());
if (nextEntry != null) {
updateGaps(newBin, nextEntry.getValue());
}
}
private void updateGaps(Bin<T> prevBin, Bin<T> nextBin) {
double gapWeight = nextBin.getMean() - prevBin.getMean();
if (_countWeightedGaps) {
gapWeight *= Math.log(Math.E + Math.min(prevBin.getCount(), nextBin.getCount()));
}
Gap<T> newGap = new Gap<T>(prevBin, nextBin, gapWeight);
Gap<T> prevGap = _binsToGaps.get(prevBin.getMean());
if (prevGap != null) {
_gaps.remove(prevGap);
}
_binsToGaps.put(prevBin.getMean(), newGap);
_gaps.add(newGap);
}
private void mergeBins() {
while (_bins.size() > _maxBins) {
Gap<T> smallestGap = _gaps.pollFirst();
Bin<T> newBin = smallestGap.getStartBin().combine(smallestGap.getEndBin());
Gap<T> followingGap = _binsToGaps.get(smallestGap.getEndBin().getMean());
if (followingGap != null) {
_gaps.remove(followingGap);
}
_bins.remove(smallestGap.getStartBin().getMean());
_bins.remove(smallestGap.getEndBin().getMean());
_binsToGaps.remove(smallestGap.getStartBin().getMean());
_binsToGaps.remove(smallestGap.getEndBin().getMean());
updateGaps(newBin);
_bins.put(newBin.getMean(), newBin);
}
}
private static Double findZ(double a, double b, double c) {
Double resultRoot = null;
ArrayList<Double> candidateRoots = solveQuadratic(a, b, c);
for (Double candidateRoot : candidateRoots) {
if (candidateRoot >= 0 && candidateRoot <= 1) {
resultRoot = candidateRoot;
break;
}
}
return resultRoot;
}
/*
* Simple quadratic solver - doesn't handle edge cases
*/
private static ArrayList<Double> solveQuadratic(double a, double b, double c) {
double discriminantSquareRoot = Math.sqrt(Math.pow(b, 2) - (4 * a * c));
ArrayList<Double> roots = new ArrayList<Double>();
roots.add((-b + discriminantSquareRoot) / (2 * a));
roots.add((-b - discriminantSquareRoot) / (2 * a));
return roots;
}
public enum TargetType {none, numeric, categorical, group};
private TargetType _targetType;
private final int _maxBins;
private final TreeMap<Double, Bin<T>> _bins;
private final TreeSet<Gap<T>> _gaps;
private final HashMap<Double, Gap<T>> _binsToGaps;
private final DecimalFormat _decimalFormat;
private final boolean _countWeightedGaps;
private HashMap<Object, Integer> _indexMap;
}
| true | false | null | null |
diff --git a/hot-deploy/financials/src/com/opensourcestrategies/financials/reports/FinancialReports.java b/hot-deploy/financials/src/com/opensourcestrategies/financials/reports/FinancialReports.java
index bdfbee3f3..a2dbbeefb 100644
--- a/hot-deploy/financials/src/com/opensourcestrategies/financials/reports/FinancialReports.java
+++ b/hot-deploy/financials/src/com/opensourcestrategies/financials/reports/FinancialReports.java
@@ -1,2221 +1,2224 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package com.opensourcestrategies.financials.reports;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javolution.util.FastList;
import javolution.util.FastMap;
import javolution.util.FastSet;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import org.hibernate.ScrollableResults;
import org.hibernate.Transaction;
import org.ofbiz.accounting.invoice.InvoiceWorker;
import org.ofbiz.accounting.util.UtilAccounting;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.ResourceBundleMapWrapper;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelKeyMap;
import org.ofbiz.entity.model.ModelViewEntity.ComplexAlias;
import org.ofbiz.entity.model.ModelViewEntity.ComplexAliasField;
import org.ofbiz.entity.util.EntityFindOptions;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.party.party.PartyHelper;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
import org.opentaps.base.entities.SalesInvoiceItemFact;
import org.opentaps.base.entities.TaxInvoiceItemFact;
import org.opentaps.common.jndi.DataSourceImpl;
import org.opentaps.common.reporting.etl.UtilEtl;
import org.opentaps.common.util.UtilAccountingTags;
import org.opentaps.common.util.UtilCommon;
import org.opentaps.common.util.UtilDate;
import org.opentaps.common.util.UtilMessage;
import org.opentaps.domain.billing.invoice.Invoice;
import org.opentaps.foundation.entity.hibernate.Query;
import org.opentaps.foundation.entity.hibernate.Session;
import org.opentaps.foundation.infrastructure.Infrastructure;
import org.opentaps.foundation.infrastructure.InfrastructureException;
import org.opentaps.foundation.repository.RepositoryException;
import com.opensourcestrategies.financials.accounts.AccountsHelper;
import com.opensourcestrategies.financials.financials.FinancialServices;
import com.opensourcestrategies.financials.util.UtilFinancial;
/**
* Events preparing data passed to Jasper reports.
*/
public final class FinancialReports {
private static final String MODULE = FinancialReports.class.getName();
private FinancialReports() { }
/**
* Prepare query parameters for standard financial report.
* @param request a <code>HttpServletRequest</code> value
* @return query parameter map
* @throws GenericEntityException if error occur
*/
public static Map<String, Object> prepareFinancialReportParameters(HttpServletRequest request) throws GenericEntityException {
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
TimeZone timeZone = UtilCommon.getTimeZone(request);
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
String organizationPartyId = (String) request.getSession().getAttribute("organizationPartyId");
String glFiscalTypeId = UtilCommon.getParameter(request, "glFiscalTypeId");
String dateOption = UtilCommon.getParameter(request, "reportDateOption");
String fromDateText = UtilCommon.getParameter(request, "fromDate");
String thruDateText = UtilCommon.getParameter(request, "thruDate");
String reportFormType = UtilCommon.getParameter(request, "reportFormType");
Timestamp fromDate = null;
Timestamp thruDate = null;
Timestamp defaultAsOfDate = UtilDateTime.getDayEnd(UtilDateTime.nowTimestamp(), timeZone, locale);
Timestamp asOfDate = null;
Map<String, Object> ctxt = FastMap.newInstance();
ctxt.put("userLogin", userLogin);
ctxt.put("organizationPartyId", organizationPartyId);
ctxt.put("glFiscalTypeId", glFiscalTypeId);
// determine the period
if (dateOption == null) {
// use the default asOfDate and run the report
ctxt.put("asOfDate", defaultAsOfDate);
} else if ("byDate".equals(dateOption)) {
if ("state".equals(reportFormType)) {
String asOfDateText = UtilCommon.getParameter(request, "asOfDate");
asOfDate = UtilDateTime.getDayEnd(UtilDate.toTimestamp(asOfDateText, timeZone, locale), timeZone, locale);
// use current date
if (asOfDate == null) {
asOfDate = defaultAsOfDate;
}
ctxt.put("asOfDate", asOfDate);
} else if ("flow".equals(reportFormType)) {
fromDateText = UtilCommon.getParameter(request, "fromDate");
thruDateText = UtilCommon.getParameter(request, "thruDate");
if (UtilValidate.isNotEmpty(fromDateText)) {
fromDate = UtilDateTime.getDayStart(UtilDate.toTimestamp(fromDateText, timeZone, locale), timeZone, locale);
}
if (UtilValidate.isNotEmpty(thruDateText)) {
thruDate = UtilDateTime.getDayEnd(UtilDate.toTimestamp(thruDateText, timeZone, locale), timeZone, locale);
}
ctxt.put("fromDate", fromDate);
ctxt.put("thruDate", thruDate);
}
} else if ("byTimePeriod".equals(dateOption)) {
if ("state".equals(reportFormType) || "flow".equals(reportFormType)) {
String customTimePeriodId = UtilCommon.getParameter(request, "customTimePeriodId");
ctxt.put("customTimePeriodId", customTimePeriodId);
GenericValue timePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", customTimePeriodId));
fromDate = UtilDateTime.getDayStart(UtilDateTime.getTimestamp(((Date) timePeriod.get("fromDate")).getTime()), timeZone, locale);
thruDate = UtilDateTime.adjustTimestamp(UtilDateTime.getTimestamp(((Date) timePeriod.get("thruDate")).getTime()), Calendar.MILLISECOND, -1, timeZone, locale);
ctxt.put("fromDate", fromDate);
ctxt.put("thruDate", thruDate);
asOfDate = thruDate;
ctxt.put("asOfDate", asOfDate);
}
}
return ctxt;
}
/**
* Prepare query parameters for comparative flow report.
* @param request a <code>HttpServletRequest</code> value
* @return query parameter map
* @throws GenericEntityException if error occur
*/
public static Map<String, Object> prepareComparativeFlowReportParameters(HttpServletRequest request) throws GenericEntityException {
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
TimeZone timeZone = UtilHttp.getTimeZone(request);
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
String organizationPartyId = (String) request.getSession().getAttribute("organizationPartyId");
String glFiscalTypeId1 = UtilCommon.getParameter(request, "glFiscalTypeId1");
String glFiscalTypeId2 = UtilCommon.getParameter(request, "glFiscalTypeId2");
String fromDateText1 = null;
String thruDateText1 = null;
String fromDateText2 = null;
String thruDateText2 = null;
Timestamp fromDate1 = null;
Timestamp thruDate1 = null;
Timestamp fromDate2 = null;
Timestamp thruDate2 = null;
String dateOption = UtilCommon.getParameter(request, "reportDateOption");
Map<String, Object> ctxt = FastMap.newInstance();
ctxt.put("userLogin", userLogin);
ctxt.put("organizationPartyId", organizationPartyId);
ctxt.put("glFiscalTypeId1", glFiscalTypeId1);
ctxt.put("glFiscalTypeId2", glFiscalTypeId2);
// determine the period
if (dateOption != null) {
if (dateOption.equals("byDate")) {
fromDateText1 = UtilCommon.getParameter(request, "fromDate1");
thruDateText1 = UtilCommon.getParameter(request, "thruDate1");
fromDateText2 = UtilCommon.getParameter(request, "fromDate2");
thruDateText2 = UtilCommon.getParameter(request, "thruDate2");
fromDate1 = UtilDateTime.getDayStart(UtilDate.toTimestamp(fromDateText1, timeZone, locale), timeZone, locale);
thruDate1 = UtilDateTime.getDayEnd(UtilDate.toTimestamp(thruDateText1, timeZone, locale), timeZone, locale);
fromDate2 = UtilDateTime.getDayStart(UtilDate.toTimestamp(fromDateText2, timeZone, locale), timeZone, locale);
thruDate2 = UtilDateTime.getDayEnd(UtilDate.toTimestamp(thruDateText2, timeZone, locale), timeZone, locale);
ctxt.put("fromDate1", fromDate1);
ctxt.put("thruDate1", thruDate1);
ctxt.put("fromDate2", fromDate2);
ctxt.put("thruDate2", thruDate2);
} else if (dateOption.equals("byTimePeriod")) {
String fromCustomTimePeriodId = UtilCommon.getParameter(request, "fromCustomTimePeriodId");
String thruCustomTimePeriodId = UtilCommon.getParameter(request, "thruCustomTimePeriodId");
ctxt.put("fromCustomTimePeriodId", fromCustomTimePeriodId);
ctxt.put("thruCustomTimePeriodId", thruCustomTimePeriodId);
GenericValue fromTimePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", fromCustomTimePeriodId));
GenericValue thruTimePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", thruCustomTimePeriodId));
fromDate1 = UtilDateTime.getDayStart(UtilDateTime.getTimestamp(((Date) fromTimePeriod.get("fromDate")).getTime()), timeZone, locale);
thruDate1 = UtilDateTime.adjustTimestamp(UtilDateTime.getTimestamp(((Date) fromTimePeriod.get("thruDate")).getTime()), Calendar.MILLISECOND, -1, timeZone, locale);
fromDate2 = UtilDateTime.getDayStart(UtilDateTime.getTimestamp(((Date) thruTimePeriod.get("fromDate")).getTime()), timeZone, locale);
thruDate2 = UtilDateTime.adjustTimestamp(UtilDateTime.getTimestamp(((Date) thruTimePeriod.get("thruDate")).getTime()), Calendar.MILLISECOND, -1, timeZone, locale);
ctxt.put("fromDate1", fromDate1);
ctxt.put("thruDate1", thruDate1);
ctxt.put("fromDate2", fromDate2);
ctxt.put("thruDate2", thruDate2);
}
}
return ctxt;
}
/**
* Prepare query parameters for comparative state report.
* @param request a <code>HttpServletRequest</code> value
* @return query parameter map
* @throws GenericEntityException if error occur
*/
public static Map<String, Object> prepareComparativeStateReportParameters(HttpServletRequest request) throws GenericEntityException {
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
TimeZone timeZone = UtilHttp.getTimeZone(request);
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
String organizationPartyId = (String) request.getSession().getAttribute("organizationPartyId");
String glFiscalTypeId1 = UtilCommon.getParameter(request, "glFiscalTypeId1");
String glFiscalTypeId2 = UtilCommon.getParameter(request, "glFiscalTypeId2");
String fromDateText = null;
String thruDateText = null;
Timestamp fromDate = null;
Timestamp thruDate = null;
String dateOption = UtilCommon.getParameter(request, "reportDateOption");
Map<String, Object> ctxt = FastMap.newInstance();
ctxt.put("userLogin", userLogin);
ctxt.put("organizationPartyId", organizationPartyId);
ctxt.put("glFiscalTypeId1", glFiscalTypeId1);
ctxt.put("glFiscalTypeId2", glFiscalTypeId2);
// determine the period
if (dateOption != null) {
// do nothing
if (dateOption.equals("byDate")) {
fromDateText = UtilCommon.getParameter(request, "fromDate");
thruDateText = UtilCommon.getParameter(request, "thruDate");
fromDate = UtilDateTime.getDayEnd(UtilDate.toTimestamp(fromDateText, timeZone, locale), timeZone, locale);
thruDate = UtilDateTime.getDayEnd(UtilDate.toTimestamp(thruDateText, timeZone, locale), timeZone, locale);
ctxt.put("fromDate", fromDate);
ctxt.put("thruDate", thruDate);
} else if (dateOption.equals("byTimePeriod")) {
String fromCustomTimePeriodId = UtilCommon.getParameter(request, "fromCustomTimePeriodId");
String thruCustomTimePeriodId = UtilCommon.getParameter(request, "thruCustomTimePeriodId");
ctxt.put("fromCustomTimePeriodId", fromCustomTimePeriodId);
ctxt.put("thruCustomTimePeriodId", thruCustomTimePeriodId);
GenericValue fromTimePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", fromCustomTimePeriodId));
GenericValue thruTimePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", thruCustomTimePeriodId));
// the time periods end at the beginning of the thruDate, end we want to adjust it so that the report ends at the end of day before the thruDate
fromDate = UtilDateTime.adjustTimestamp(UtilDateTime.getTimestamp(((Date) fromTimePeriod.get("thruDate")).getTime()), Calendar.MILLISECOND, -1, timeZone, locale);
thruDate = UtilDateTime.adjustTimestamp(UtilDateTime.getTimestamp(((Date) thruTimePeriod.get("thruDate")).getTime()), Calendar.MILLISECOND, -1, timeZone, locale);
ctxt.put("fromDate", fromDate);
ctxt.put("thruDate", thruDate);
}
}
return ctxt;
}
/**
* Prepare data source and parameters for income statement report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareIncomeStatementReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
Map<String, String> groupMarkers = UtilMisc.<String, String>toMap(
"REVENUE", uiLabelMap.get("FinancialsGrossProfit"), "COGS", uiLabelMap.get("FinancialsGrossProfit"),
"OPERATING_EXPENSE", uiLabelMap.get("FinancialsOperatingIncome"),
"OTHER_EXPENSE", uiLabelMap.get("FinancialsPretaxIncome"), "OTHER_INCOME", uiLabelMap.get("FinancialsPretaxIncome"),
"TAX_EXPENSE", uiLabelMap.get("AccountingNetIncome")
);
String reportType = UtilCommon.getParameter(request, "type");
try {
Map ctxt = prepareFinancialReportParameters(request);
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, ?> results = dispatcher.runSync("getIncomeStatementByDates", dispatcher.getDispatchContext().makeValidContext("getIncomeStatementByDates", ModelService.IN_PARAM, ctxt));
Map<String, Object> glAccountSums = (Map<String, Object>) results.get("glAccountSums");
BigDecimal grossProfit = (BigDecimal) results.get("grossProfit");
BigDecimal operatingIncome = (BigDecimal) results.get("operatingIncome");
BigDecimal pretaxIncome = (BigDecimal) results.get("pretaxIncome");
BigDecimal netIncome = (BigDecimal) results.get("netIncome");
Map<String, BigDecimal> glAccountGroupSums = (Map) results.get("glAccountGroupSums");
List<Map<String, Object>> rows = FastList.newInstance();
Integer i = 1;
for (String glAccountTypeId : FinancialServices.INCOME_STATEMENT_TYPES) {
List<Map<String, Object>> accounts = (List<Map<String, Object>>) glAccountSums.get(glAccountTypeId);
// find account type
GenericValue glAccountType = delegator.findByPrimaryKey("GlAccountType", UtilMisc.toMap("glAccountTypeId", glAccountTypeId));
// create records for report
if (UtilValidate.isNotEmpty(accounts)) {
for (Map<String, Object> account : accounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("typeSeqNum", i);
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("glAccountTypeDescription", glAccountType.getString("description"));
row.put("glAccountTypeAmount", glAccountGroupSums.get(glAccountTypeId));
row.put("accountSum", account.get("accountSum"));
row.put("cumulativeIncomeName", groupMarkers.get(glAccountTypeId));
if ("REVENUE".equals(glAccountTypeId) || "COGS".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", grossProfit);
} else if ("OPERATING_EXPENSE".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", operatingIncome);
} else if ("OTHER_EXPENSE".equals(glAccountTypeId) || "OTHER_INCOME".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", pretaxIncome);
} else if ("TAX_EXPENSE".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", netIncome);
} else {
row.put("cumulativeIncomeAmount", null);
}
rows.add(row);
}
} else {
// put line w/ empty detail fields to display grouping and totals in any case
Map<String, Object> row = FastMap.newInstance();
row.put("typeSeqNum", i);
row.put("glAccountTypeDescription", glAccountType.getString("description"));
row.put("glAccountTypeAmount", glAccountGroupSums.get(glAccountTypeId));
row.put("cumulativeIncomeName", groupMarkers.get(glAccountTypeId));
if ("REVENUE".equals(glAccountTypeId) || "COGS".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", grossProfit);
} else if ("OPERATING_EXPENSE".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", operatingIncome);
} else if ("OTHER_EXPENSE".equals(glAccountTypeId) || "OTHER_INCOME".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", pretaxIncome);
} else if ("TAX_EXPENSE".equals(glAccountTypeId)) {
row.put("cumulativeIncomeAmount", netIncome);
} else {
row.put("cumulativeIncomeAmount", null);
}
rows.add(row);
}
i++;
}
// sort records by account code
Collections.sort(rows, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
Integer seqNum1 = (Integer) o1.get("typeSeqNum");
Integer seqNum2 = (Integer) o2.get("typeSeqNum");
int isSeqNumEq = seqNum1.compareTo(seqNum2);
if (isSeqNumEq != 0) {
return isSeqNumEq;
}
String accountCode1 = (String) o1.get("accountCode");
String accountCode2 = (String) o2.get("accountCode");
if (accountCode1 == null && accountCode2 == null) {
return 0;
}
if (accountCode1 == null && accountCode2 != null) {
return -1;
}
if (accountCode1 != null && accountCode2 == null) {
return 1;
}
return accountCode1.compareTo(accountCode2);
}
});
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("glFiscalTypeId", ctxt.get("glFiscalTypeId"));
jrParameters.put("fromDate", ctxt.get("fromDate"));
jrParameters.put("thruDate", ctxt.get("thruDate"));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for comparative income statement report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareComparativeIncomeStatementReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
try {
Map ctxt = prepareComparativeFlowReportParameters(request);
// validate parameters
if (ctxt.get("fromDate1") == null || ctxt.get("thruDate1") == null || ctxt.get("fromDate2") == null || ctxt.get("thruDate2") == null) {
return UtilMessage.createAndLogEventError(request, "FinancialsError_DateRangeMissing", locale, MODULE);
}
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> results = dispatcher.runSync("getComparativeIncomeStatement", dispatcher.getDispatchContext().makeValidContext("getComparativeIncomeStatement", ModelService.IN_PARAM, ctxt));
Map<String, Object> set1IncomeStatement = (Map<String, Object>) results.get("set1IncomeStatement");
Map<String, Object> set2IncomeStatement = (Map<String, Object>) results.get("set2IncomeStatement");
BigDecimal netIncome1 = (BigDecimal) set1IncomeStatement.get("netIncome");
BigDecimal netIncome2 = (BigDecimal) set2IncomeStatement.get("netIncome");
Map<GenericValue, BigDecimal> accountBalances = (Map<GenericValue, BigDecimal>) results.get("accountBalances");
Map<GenericValue, BigDecimal> set1Accounts = (Map<GenericValue, BigDecimal>) set1IncomeStatement.get("glAccountSumsFlat");
Map<GenericValue, BigDecimal> set2Accounts = (Map<GenericValue, BigDecimal>) set2IncomeStatement.get("glAccountSumsFlat");
GenericValue glFiscalType1 = delegator.findByPrimaryKey("GlFiscalType", UtilMisc.toMap("glFiscalTypeId", ctxt.get("glFiscalTypeId1")));
GenericValue glFiscalType2 = delegator.findByPrimaryKey("GlFiscalType", UtilMisc.toMap("glFiscalTypeId", ctxt.get("glFiscalTypeId2")));
List<Map<String, Object>> rows = FastList.newInstance();
// create records for report
Set<GenericValue> accounts = accountBalances.keySet();
for (GenericValue account : accounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSumLeft", set1Accounts.get(account));
row.put("cumulativeIncomeName", uiLabelMap.get("AccountingNetIncome"));
row.put("accountSumRight", set2Accounts.get(account));
row.put("accountSumDiff", accountBalances.get(account));
rows.add(row);
}
// sort records by account code
Collections.sort(rows, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
String accountCode1 = (String) o1.get("accountCode");
String accountCode2 = (String) o2.get("accountCode");
if (accountCode1 == null && accountCode2 == null) {
return 0;
}
if (accountCode1 == null && accountCode2 != null) {
return -1;
}
if (accountCode1 != null && accountCode2 == null) {
return 1;
}
return accountCode1.compareTo(accountCode2);
}
});
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("fromDateLeft", ctxt.get("fromDate1"));
jrParameters.put("thruDateLeft", ctxt.get("thruDate1"));
jrParameters.put("fromDateRight", ctxt.get("fromDate2"));
jrParameters.put("thruDateRight", ctxt.get("thruDate2"));
jrParameters.put("netIncomeLeft", netIncome1);
jrParameters.put("netIncomeRight", netIncome2);
jrParameters.put("fiscalTypeLeft", glFiscalType1.get("description", locale));
jrParameters.put("fiscalTypeRight", glFiscalType2.get("description", locale));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for trial balance report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareTrialBalanceReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
try {
// retrieve financial data
Map ctxt = prepareFinancialReportParameters(request);
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> results = dispatcher.runSync("getTrialBalanceForDate", dispatcher.getDispatchContext().makeValidContext("getTrialBalanceForDate", ModelService.IN_PARAM, ctxt));
List<Map<String, Object>> rows = FastList.newInstance();
// the account groups that will be included in the report, in the same order
Map<String, String> accountLabels = new LinkedHashMap<String, String>();
accountLabels.put("asset", "AccountingAssets");
accountLabels.put("liability", "AccountingLiabilities");
accountLabels.put("equity", "AccountingEquities");
accountLabels.put("revenue", "FinancialsRevenue");
accountLabels.put("expense", "FinancialsExpense");
accountLabels.put("income", "FinancialsIncome");
accountLabels.put("other", "CommonOther");
for (String pre : accountLabels.keySet()) {
Object label = uiLabelMap.get(accountLabels.get(pre));
// for the given group, list the entries ordered by account code
List<GenericValue> accounts = EntityUtil.orderBy(((Map) results.get(pre + "AccountBalances")).keySet(), UtilMisc.toList("accountCode"));
if (UtilValidate.isNotEmpty(accounts)) {
Map<GenericValue, Double> accountBalances = (Map) results.get(pre + "AccountBalances");
Map<GenericValue, Double> accountCredits = (Map) results.get(pre + "AccountCredits");
Map<GenericValue, Double> accountDebits = (Map) results.get(pre + "AccountDebits");
for (GenericValue account : accounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", accountBalances.get(account));
row.put("accountCredit", accountCredits.get(account));
row.put("accountDebit", accountDebits.get(account));
row.put("accountType", label);
row.put("accountCreditDebitFlag", UtilAccounting.isDebitAccount(account) ? "D" : "C");
rows.add(row);
}
} else {
// for empty groups
rows.add(UtilMisc.toMap("accountType", label));
}
}
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("asOfDate", ctxt.get("asOfDate"));
jrParameters.put("glFiscalTypeId", ctxt.get("glFiscalTypeId"));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("totalDebits", results.get("totalDebits"));
jrParameters.put("totalCredits", results.get("totalCredits"));
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for balance sheet report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareBalanceSheetReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
try {
// retrieve financial data
Map ctxt = prepareFinancialReportParameters(request);
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> results = dispatcher.runSync("getBalanceSheetForDate", dispatcher.getDispatchContext().makeValidContext("getBalanceSheetForDate", ModelService.IN_PARAM, ctxt));
List<GenericValue> assetAccounts = EntityUtil.orderBy(((Map) results.get("assetAccountBalances")).keySet(), UtilMisc.toList("glAccountId"));
Map<GenericValue, BigDecimal> assetAccountBalances = (Map) results.get("assetAccountBalances");
List<GenericValue> liabilityAccounts = EntityUtil.orderBy(((Map) results.get("liabilityAccountBalances")).keySet(), UtilMisc.toList("glAccountId"));
Map<GenericValue, BigDecimal> liabilityAccountBalances = (Map) results.get("liabilityAccountBalances");
List<GenericValue> equityAccounts = EntityUtil.orderBy(((Map) results.get("equityAccountBalances")).keySet(), UtilMisc.toList("glAccountId"));
Map<GenericValue, BigDecimal> equityAccountBalances = (Map) results.get("equityAccountBalances");
List<Map<String, Object>> rows = FastList.newInstance();
// create record set for report
if (UtilValidate.isNotEmpty(assetAccounts)) {
for (GenericValue account : assetAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", assetAccountBalances.get(account));
row.put("accountType", uiLabelMap.get("AccountingAssets"));
row.put("accountTypeSeqNum", Integer.valueOf(1));
rows.add(row);
}
} else {
rows.add(UtilMisc.toMap("accountType", uiLabelMap.get("AccountingAssets"), "accountTypeSeqNum", Integer.valueOf(1)));
}
if (UtilValidate.isNotEmpty(liabilityAccounts)) {
for (GenericValue account : liabilityAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", liabilityAccountBalances.get(account));
row.put("accountType", uiLabelMap.get("AccountingLiabilities"));
row.put("accountTypeSeqNum", Integer.valueOf(2));
rows.add(row);
}
} else {
rows.add(UtilMisc.toMap("accountType", uiLabelMap.get("AccountingLiabilities"), "accountTypeSeqNum", Integer.valueOf(2)));
}
if (UtilValidate.isNotEmpty(equityAccounts)) {
for (GenericValue account : equityAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", equityAccountBalances.get(account));
row.put("accountType", uiLabelMap.get("AccountingEquities"));
row.put("accountTypeSeqNum", Integer.valueOf(3));
rows.add(row);
}
} else {
rows.add(UtilMisc.toMap("accountType", uiLabelMap.get("AccountingEquities"), "accountTypeSeqNum", Integer.valueOf(3)));
}
// sort records by account code
Collections.sort(rows, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
Integer accountTypeSeqNum1 = (Integer) o1.get("accountTypeSeqNum");
Integer accountTypeSeqNum2 = (Integer) o2.get("accountTypeSeqNum");
int c = accountTypeSeqNum1.compareTo(accountTypeSeqNum2);
if (c == 0) {
String accountCode1 = (String) o1.get("accountCode");
String accountCode2 = (String) o2.get("accountCode");
if (accountCode1 == null && accountCode2 == null) {
return 0;
}
if (accountCode1 == null && accountCode2 != null) {
return -1;
}
if (accountCode1 != null && accountCode2 == null) {
return 1;
}
return accountCode1.compareTo(accountCode2);
}
return c;
}
});
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("glFiscalTypeId", ctxt.get("glFiscalTypeId"));
jrParameters.put("asOfDate", ctxt.get("asOfDate"));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for comparative balance sheet report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareComparativeBalanceReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
try {
// retrieve financial data
Map ctxt = prepareComparativeStateReportParameters(request);
if (ctxt.get("fromDate") == null || ctxt.get("thruDate") == null) {
return UtilMessage.createAndLogEventError(request, "FinancialsError_FromOrThruDateMissing", locale, MODULE);
}
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> results = dispatcher.runSync("getComparativeBalanceSheet", dispatcher.getDispatchContext().makeValidContext("getComparativeBalanceSheet", ModelService.IN_PARAM, ctxt));
List<GenericValue> assetAccounts = EntityUtil.orderBy(((Map<GenericValue, BigDecimal>) results.get("assetAccountBalances")).keySet(), UtilMisc.toList("glAccountId"));
Map<GenericValue, BigDecimal> assetAccountBalances = (Map<GenericValue, BigDecimal>) results.get("assetAccountBalances");
List<GenericValue> liabilityAccounts = EntityUtil.orderBy(((Map<GenericValue, BigDecimal>) results.get("liabilityAccountBalances")).keySet(), UtilMisc.toList("glAccountId"));
Map<GenericValue, BigDecimal> liabilityAccountBalances = (Map<GenericValue, BigDecimal>) results.get("liabilityAccountBalances");
List<GenericValue> equityAccounts = EntityUtil.orderBy(((Map<GenericValue, BigDecimal>) results.get("equityAccountBalances")).keySet(), UtilMisc.toList("glAccountId"));
Map<GenericValue, BigDecimal> equityAccountBalances = (Map<GenericValue, BigDecimal>) results.get("equityAccountBalances");
Map<String, Object> fromDateAccountBalances = (Map<String, Object>) results.get("fromDateAccountBalances");
Map<GenericValue, BigDecimal> fromAssetAccountBalances = (Map<GenericValue, BigDecimal>) fromDateAccountBalances.get("assetAccountBalances");
Map<GenericValue, BigDecimal> fromLiabilityAccountBalances = (Map<GenericValue, BigDecimal>) fromDateAccountBalances.get("liabilityAccountBalances");
Map<GenericValue, BigDecimal> fromEquityAccountBalances = (Map<GenericValue, BigDecimal>) fromDateAccountBalances.get("equityAccountBalances");
Map<String, Object> thruDateAccountBalances = (Map<String, Object>) results.get("thruDateAccountBalances");
Map<GenericValue, BigDecimal> toAssetAccountBalances = (Map<GenericValue, BigDecimal>) thruDateAccountBalances.get("assetAccountBalances");
Map<GenericValue, BigDecimal> toLiabilityAccountBalances = (Map<GenericValue, BigDecimal>) thruDateAccountBalances.get("liabilityAccountBalances");
Map<GenericValue, BigDecimal> toEquityAccountBalances = (Map<GenericValue, BigDecimal>) thruDateAccountBalances.get("equityAccountBalances");
GenericValue fromGlFiscalType = delegator.findByPrimaryKey("GlFiscalType", UtilMisc.toMap("glFiscalTypeId", ctxt.get("glFiscalTypeId1")));
GenericValue toGlFiscalType = delegator.findByPrimaryKey("GlFiscalType", UtilMisc.toMap("glFiscalTypeId", ctxt.get("glFiscalTypeId2")));
List<Map<String, Object>> rows = FastList.newInstance();
// create record set for report
if (UtilValidate.isNotEmpty(assetAccounts)) {
for (GenericValue account : assetAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", assetAccountBalances.get(account));
row.put("accountBalanceLeft", fromAssetAccountBalances.get(account));
row.put("accountBalanceRight", toAssetAccountBalances.get(account));
row.put("accountType", uiLabelMap.get("AccountingAssets"));
row.put("accountTypeSeqNum", Integer.valueOf(1));
rows.add(row);
}
} else {
rows.add(UtilMisc.toMap("accountType", uiLabelMap.get("AccountingAssets"), "accountTypeSeqNum", Integer.valueOf(1)));
}
if (UtilValidate.isNotEmpty(liabilityAccounts)) {
for (GenericValue account : liabilityAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", liabilityAccountBalances.get(account));
row.put("accountBalanceLeft", fromLiabilityAccountBalances.get(account));
row.put("accountBalanceRight", toLiabilityAccountBalances.get(account));
row.put("accountType", uiLabelMap.get("AccountingLiabilities"));
row.put("accountTypeSeqNum", Integer.valueOf(2));
rows.add(row);
}
} else {
rows.add(UtilMisc.toMap("accountType", uiLabelMap.get("AccountingLiabilities"), "accountTypeSeqNum", Integer.valueOf(2)));
}
if (UtilValidate.isNotEmpty(equityAccounts)) {
for (GenericValue account : equityAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountBalance", equityAccountBalances.get(account));
row.put("accountBalanceLeft", fromEquityAccountBalances.get(account));
row.put("accountBalanceRight", toEquityAccountBalances.get(account));
row.put("accountType", uiLabelMap.get("AccountingEquities"));
row.put("accountTypeSeqNum", Integer.valueOf(3));
rows.add(row);
}
} else {
rows.add(UtilMisc.toMap("accountType", uiLabelMap.get("AccountingEquities"), "accountTypeSeqNum", Integer.valueOf(3)));
}
// sort records by account code
Collections.sort(rows, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
Integer accountTypeSeqNum1 = (Integer) o1.get("accountTypeSeqNum");
Integer accountTypeSeqNum2 = (Integer) o2.get("accountTypeSeqNum");
int c = accountTypeSeqNum1.compareTo(accountTypeSeqNum2);
if (c == 0) {
String accountCode1 = (String) o1.get("accountCode");
String accountCode2 = (String) o2.get("accountCode");
if (accountCode1 == null && accountCode2 == null) {
return 0;
}
if (accountCode1 == null && accountCode2 != null) {
return -1;
}
if (accountCode1 != null && accountCode2 == null) {
return 1;
}
return accountCode1.compareTo(accountCode2);
}
return c;
}
});
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("fromDate", ctxt.get("fromDate"));
jrParameters.put("thruDate", ctxt.get("thruDate"));
jrParameters.put("fiscalTypeLeft", fromGlFiscalType.get("description", locale));
jrParameters.put("fiscalTypeRight", toGlFiscalType.get("description", locale));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for cash flow report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareCashFlowStatementReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
try {
// retrieve financial data
Map ctxt = prepareFinancialReportParameters(request);
if (ctxt.get("fromDate") == null || ctxt.get("thruDate") == null) {
return UtilMessage.createAndLogEventError(request, "FinancialsError_FromOrThruDateMissing", locale, MODULE);
}
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> results = dispatcher.runSync("getCashFlowStatementForDates", dispatcher.getDispatchContext().makeValidContext("getCashFlowStatementForDates", ModelService.IN_PARAM, ctxt));
BigDecimal beginningCashAmount = (BigDecimal) results.get("beginningCashAmount");
BigDecimal endingCashAmount = (BigDecimal) results.get("endingCashAmount");
BigDecimal operatingCashFlow = (BigDecimal) results.get("operatingCashFlow");
BigDecimal investingCashFlow = (BigDecimal) results.get("investingCashFlow");
BigDecimal financingCashFlow = (BigDecimal) results.get("financingCashFlow");
BigDecimal netCashFlow = (BigDecimal) results.get("netCashFlow");
BigDecimal netIncome = (BigDecimal) results.get("netIncome");
Map<GenericValue, BigDecimal> operatingCashFlowAccountBalances = (Map<GenericValue, BigDecimal>) results.get("operatingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> investingCashFlowAccountBalances = (Map<GenericValue, BigDecimal>) results.get("investingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> financingCashFlowAccountBalances = (Map<GenericValue, BigDecimal>) results.get("financingCashFlowAccountBalances");
List<GenericValue> operatingAccounts = EntityUtil.orderBy(operatingCashFlowAccountBalances.keySet(), UtilMisc.toList("glAccountId"));
List<GenericValue> investingAccounts = EntityUtil.orderBy(investingCashFlowAccountBalances.keySet(), UtilMisc.toList("glAccountId"));
List<GenericValue> financingAccounts = EntityUtil.orderBy(financingCashFlowAccountBalances.keySet(), UtilMisc.toList("glAccountId"));
List<Map<String, Object>> rows = FastList.newInstance();
// create record set for report
for (GenericValue account : operatingAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSum", operatingCashFlowAccountBalances.get(account));
row.put("cashFlowType", uiLabelMap.get("FinancialsOperatingCashFlowAccounts"));
row.put("cashFlowTypeTotal", uiLabelMap.get("FinancialsTotalOperatingCashFlow"));
row.put("cashFlowTypeTotalAmount", operatingCashFlow);
row.put("netCashFlow", uiLabelMap.get("FinancialsTotalNetCashFlow"));
row.put("endingCashFlow", uiLabelMap.get("FinancialsEndingCashBalance"));
rows.add(row);
}
for (GenericValue account : investingAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSum", investingCashFlowAccountBalances.get(account));
row.put("cashFlowType", uiLabelMap.get("FinancialsInvestingCashFlowAccounts"));
row.put("cashFlowTypeTotal", uiLabelMap.get("FinancialsTotalInvestingCashFlow"));
row.put("cashFlowTypeTotalAmount", investingCashFlow);
row.put("netCashFlow", uiLabelMap.get("FinancialsTotalNetCashFlow"));
row.put("endingCashFlow", uiLabelMap.get("FinancialsEndingCashBalance"));
rows.add(row);
}
for (GenericValue account : financingAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSum", financingCashFlowAccountBalances.get(account));
row.put("cashFlowType", uiLabelMap.get("FinancialsFinancingCashFlowAccounts"));
row.put("cashFlowTypeTotal", uiLabelMap.get("FinancialsTotalFinancingCashFlow"));
row.put("cashFlowTypeTotalAmount", financingCashFlow);
row.put("netCashFlow", uiLabelMap.get("FinancialsTotalNetCashFlow"));
row.put("endingCashFlow", uiLabelMap.get("FinancialsEndingCashBalance"));
rows.add(row);
}
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("glFiscalTypeId", ctxt.get("glFiscalTypeId"));
jrParameters.put("fromDate", ctxt.get("fromDate"));
jrParameters.put("thruDate", ctxt.get("thruDate"));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("beginningCashAmount", beginningCashAmount);
jrParameters.put("endingCashAmount", endingCashAmount);
jrParameters.put("netCashFlow", netCashFlow);
jrParameters.put("netIncome", netIncome);
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for comparative cash flow report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
@SuppressWarnings("unchecked")
public static String prepareComparativeCashFlowStatementReport(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
try {
// retrieve financial data
Map ctxt = prepareComparativeFlowReportParameters(request);
if (ctxt.get("fromDate1") == null || ctxt.get("thruDate1") == null || ctxt.get("fromDate2") == null || ctxt.get("thruDate2") == null) {
return UtilMessage.createAndLogEventError(request, "FinancialsError_DateRangeMissing", locale, MODULE);
}
UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> results = dispatcher.runSync("getComparativeCashFlowStatement", dispatcher.getDispatchContext().makeValidContext("getComparativeCashFlowStatement", ModelService.IN_PARAM, ctxt));
Map<String, Object> set1CashFlowStatement = (Map<String, Object>) results.get("set1CashFlowStatement");
Map<String, Object> set2CashFlowStatement = (Map<String, Object>) results.get("set2CashFlowStatement");
BigDecimal beginningCashAmount1 = (BigDecimal) set1CashFlowStatement.get("beginningCashAmount");
BigDecimal beginningCashAmount2 = (BigDecimal) set2CashFlowStatement.get("beginningCashAmount");
BigDecimal endingCashAmount1 = (BigDecimal) set1CashFlowStatement.get("endingCashAmount");
BigDecimal endingCashAmount2 = (BigDecimal) set2CashFlowStatement.get("endingCashAmount");
BigDecimal operatingCashFlow1 = (BigDecimal) set1CashFlowStatement.get("operatingCashFlow");
BigDecimal operatingCashFlow2 = (BigDecimal) set2CashFlowStatement.get("operatingCashFlow");
BigDecimal investingCashFlow1 = (BigDecimal) set1CashFlowStatement.get("investingCashFlow");
BigDecimal investingCashFlow2 = (BigDecimal) set2CashFlowStatement.get("investingCashFlow");
BigDecimal financingCashFlow1 = (BigDecimal) set1CashFlowStatement.get("financingCashFlow");
BigDecimal financingCashFlow2 = (BigDecimal) set2CashFlowStatement.get("financingCashFlow");
BigDecimal netCashFlow1 = (BigDecimal) set1CashFlowStatement.get("netCashFlow");
BigDecimal netCashFlow2 = (BigDecimal) set2CashFlowStatement.get("netCashFlow");
BigDecimal netIncome1 = (BigDecimal) set1CashFlowStatement.get("netIncome");
BigDecimal netIncome2 = (BigDecimal) set2CashFlowStatement.get("netIncome");
Map<GenericValue, BigDecimal> operatingCashFlowAccounts1 = (Map<GenericValue, BigDecimal>) set1CashFlowStatement.get("operatingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> investingCashFlowAccounts1 = (Map<GenericValue, BigDecimal>) set1CashFlowStatement.get("investingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> financingCashFlowAccounts1 = (Map<GenericValue, BigDecimal>) set1CashFlowStatement.get("financingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> operatingCashFlowAccounts2 = (Map<GenericValue, BigDecimal>) set2CashFlowStatement.get("operatingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> investingCashFlowAccounts2 = (Map<GenericValue, BigDecimal>) set2CashFlowStatement.get("investingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> financingCashFlowAccounts2 = (Map<GenericValue, BigDecimal>) set2CashFlowStatement.get("financingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> operatingCashFlowAccountBalances = (Map<GenericValue, BigDecimal>) results.get("operatingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> investingCashFlowAccountBalances = (Map<GenericValue, BigDecimal>) results.get("investingCashFlowAccountBalances");
Map<GenericValue, BigDecimal> financingCashFlowAccountBalances = (Map<GenericValue, BigDecimal>) results.get("financingCashFlowAccountBalances");
List<GenericValue> operatingAccounts = EntityUtil.orderBy(operatingCashFlowAccountBalances.keySet(), UtilMisc.toList("glAccountId"));
List<GenericValue> investingAccounts = EntityUtil.orderBy(investingCashFlowAccountBalances.keySet(), UtilMisc.toList("glAccountId"));
List<GenericValue> financingAccounts = EntityUtil.orderBy(financingCashFlowAccountBalances.keySet(), UtilMisc.toList("glAccountId"));
List<Map<String, Object>> rows = FastList.newInstance();
// create record set for report
for (GenericValue account : operatingAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSumLeft", operatingCashFlowAccounts1.get(account));
row.put("accountSumRight", operatingCashFlowAccounts2.get(account));
row.put("accountSumDiff", operatingCashFlowAccountBalances.get(account));
row.put("cashFlowType", uiLabelMap.get("FinancialsOperatingCashFlowAccounts"));
row.put("cashFlowTypeTotal", uiLabelMap.get("FinancialsTotalOperatingCashFlow"));
row.put("cashFlowTypeTotalAmountLeft", operatingCashFlow1);
row.put("cashFlowTypeTotalAmountRight", operatingCashFlow2);
row.put("netCashFlow", uiLabelMap.get("FinancialsTotalNetCashFlow"));
row.put("endingCashFlow", uiLabelMap.get("FinancialsEndingCashBalance"));
rows.add(row);
}
for (GenericValue account : investingAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSumLeft", investingCashFlowAccounts1.get(account));
row.put("accountSumRight", investingCashFlowAccounts2.get(account));
row.put("accountSumDiff", investingCashFlowAccountBalances.get(account));
row.put("cashFlowType", uiLabelMap.get("FinancialsInvestingCashFlowAccounts"));
row.put("cashFlowTypeTotal", uiLabelMap.get("FinancialsTotalInvestingCashFlow"));
row.put("cashFlowTypeTotalAmountLeft", investingCashFlow1);
row.put("cashFlowTypeTotalAmountRight", investingCashFlow2);
row.put("netCashFlow", uiLabelMap.get("FinancialsTotalNetCashFlow"));
row.put("endingCashFlow", uiLabelMap.get("FinancialsEndingCashBalance"));
rows.add(row);
}
for (GenericValue account : financingAccounts) {
Map<String, Object> row = FastMap.newInstance();
row.put("accountCode", account.get("accountCode"));
row.put("accountName", account.get("accountName"));
row.put("accountSumLeft", financingCashFlowAccounts1.get(account));
row.put("accountSumRight", financingCashFlowAccounts2.get(account));
row.put("accountSumDiff", financingCashFlowAccountBalances.get(account));
row.put("cashFlowType", uiLabelMap.get("FinancialsFinancingCashFlowAccounts"));
row.put("cashFlowTypeTotal", uiLabelMap.get("FinancialsTotalFinancingCashFlow"));
row.put("cashFlowTypeTotalAmountLeft", financingCashFlow1);
row.put("cashFlowTypeTotalAmountRight", financingCashFlow2);
row.put("netCashFlow", uiLabelMap.get("FinancialsTotalNetCashFlow"));
row.put("endingCashFlow", uiLabelMap.get("FinancialsEndingCashBalance"));
rows.add(row);
}
// sort records by account code
Collections.sort(rows, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
String accountCode1 = (String) o1.get("accountCode");
String accountCode2 = (String) o2.get("accountCode");
if (accountCode1 == null && accountCode2 == null) {
return 0;
}
if (accountCode1 == null && accountCode2 != null) {
return -1;
}
if (accountCode1 != null && accountCode2 == null) {
return 1;
}
return accountCode1.compareTo(accountCode2);
}
});
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(rows));
GenericValue glFiscalType1 = delegator.findByPrimaryKey("GlFiscalType", UtilMisc.toMap("glFiscalTypeId", ctxt.get("glFiscalTypeId1")));
GenericValue glFiscalType2 = delegator.findByPrimaryKey("GlFiscalType", UtilMisc.toMap("glFiscalTypeId", ctxt.get("glFiscalTypeId2")));
// prepare report parameters
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.put("fromDateLeft", ctxt.get("fromDate1"));
jrParameters.put("thruDateLeft", ctxt.get("thruDate1"));
jrParameters.put("fromDateRight", ctxt.get("fromDate2"));
jrParameters.put("thruDateRight", ctxt.get("thruDate2"));
jrParameters.put("organizationPartyId", ctxt.get("organizationPartyId"));
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("fiscalTypeLeft", glFiscalType1.get("description", locale));
jrParameters.put("fiscalTypeRight", glFiscalType2.get("description", locale));
jrParameters.put("beginningCashAmountLeft", beginningCashAmount1);
jrParameters.put("beginningCashAmountRight", beginningCashAmount2);
jrParameters.put("endingCashAmountLeft", endingCashAmount1);
jrParameters.put("endingCashAmountRight", endingCashAmount2);
jrParameters.put("netCashFlowLeft", netCashFlow1);
jrParameters.put("netCashFlowRight", netCashFlow2);
jrParameters.put("netIncomeLeft", netIncome1);
jrParameters.put("netIncomeRight", netIncome2);
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
request.setAttribute("jrParameters", jrParameters);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for accounts receivables aging report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response, either "pdf" or "xls" string to select report type, or "error".
*/
public static String prepareReceivablesAgingReport(HttpServletRequest request, HttpServletResponse response) {
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
TimeZone timeZone = UtilHttp.getTimeZone(request);
- ResourceBundleMapWrapper uiLabelMap = UtilMessage.getUiLabels(locale);
String reportType = UtilCommon.getParameter(request, "type");
String partyId = UtilCommon.getParameter(request, "partyId");
String organizationPartyId = null;
Timestamp asOfDate = null;
try {
// retrieve financial data
Map<String, Object> ctxt = prepareFinancialReportParameters(request);
UtilAccountingTags.addTagParameters(request, ctxt);
asOfDate = (Timestamp) ctxt.get("asOfDate");
organizationPartyId = (String) ctxt.get("organizationPartyId");
List<Integer> daysOutstandingBreakPoints = UtilMisc.<Integer>toList(30, 60, 90);
// this is a hack to get the the invoices over the last break point (ie, 90+ invoices)
Integer maximumDSOBreakPoint = 9999;
List<Integer> breakPointParams = FastList.<Integer>newInstance();
breakPointParams.addAll(daysOutstandingBreakPoints);
breakPointParams.add(maximumDSOBreakPoint);
Map<Integer, List<Invoice>> invoicesByDSO = null;
if (UtilValidate.isEmpty(partyId)) {
invoicesByDSO = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, breakPointParams, asOfDate, UtilMisc.toList("INVOICE_READY"), delegator, timeZone, locale);
} else {
invoicesByDSO = AccountsHelper.getUnpaidInvoicesForCustomer(organizationPartyId, partyId, breakPointParams, asOfDate, UtilMisc.toList("INVOICE_READY"), delegator, timeZone, locale);
}
List<Map<String, Object>> plainList = FastList.<Map<String, Object>>newInstance();
Integer prevDCOBreakPoint = 0;
for (Integer breakPoint : invoicesByDSO.keySet()) {
List<Invoice> invoicesForBreakPoint = invoicesByDSO.get(breakPoint);
if (UtilValidate.isEmpty(invoicesForBreakPoint)) {
plainList.add(UtilMisc.<String, Object>toMap("DCOBreakPoint", breakPoint, "prevDCOBreakPoint", prevDCOBreakPoint, "isEmpty", Boolean.TRUE));
}
for (Invoice invoice : invoicesForBreakPoint) {
FastMap<String, Object> reportLine = FastMap.<String, Object>newInstance();
reportLine.put("prevDCOBreakPoint", prevDCOBreakPoint);
reportLine.put("DCOBreakPoint", breakPoint);
reportLine.put("isEmpty", Boolean.FALSE);
reportLine.put("invoiceDate", invoice.getInvoiceDate());
reportLine.put("invoiceId", invoice.getInvoiceId());
reportLine.put("invoiceTotal", invoice.getInvoiceTotal());
reportLine.put("partyId", invoice.getPartyId());
reportLine.put("partyName", PartyHelper.getPartyName(delegator, invoice.getPartyId(), false));
plainList.add(reportLine);
}
prevDCOBreakPoint = breakPoint;
}
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(plainList));
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.putAll(ctxt);
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("isReceivables", Boolean.TRUE);
request.setAttribute("jrParameters", jrParameters);
} catch (GenericEntityException e) {
UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for accounts payables aging report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response, either "pdf" or "xls" string to select report type, or "error".
*/
public static String preparePayablesAgingReport(HttpServletRequest request, HttpServletResponse response) {
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
Locale locale = UtilHttp.getLocale(request);
TimeZone timeZone = UtilHttp.getTimeZone(request);
String reportType = UtilCommon.getParameter(request, "type");
String partyId = UtilCommon.getParameter(request, "partyId");
String organizationPartyId = null;
Timestamp asOfDate = null;
try {
// retrieve financial data
Map<String, Object> ctxt = prepareFinancialReportParameters(request);
UtilAccountingTags.addTagParameters(request, ctxt);
asOfDate = (Timestamp) ctxt.get("asOfDate");
organizationPartyId = (String) ctxt.get("organizationPartyId");
List<Integer> daysOutstandingBreakPoints = UtilMisc.<Integer>toList(30, 60, 90);
// this is a hack to get the the invoices over the last break point (ie, 90+ invoices)
Integer maximumDSOBreakPoint = 9999;
List<Integer> breakPointParams = FastList.<Integer>newInstance();
breakPointParams.addAll(daysOutstandingBreakPoints);
breakPointParams.add(maximumDSOBreakPoint);
Map<Integer, List<Invoice>> invoicesByDSO = null;
if (UtilValidate.isEmpty(partyId)) {
invoicesByDSO = AccountsHelper.getUnpaidInvoicesForVendors(organizationPartyId, breakPointParams, asOfDate, UtilMisc.toList("INVOICE_READY"), delegator, timeZone, locale);
} else {
invoicesByDSO = AccountsHelper.getUnpaidInvoicesForVendor(organizationPartyId, partyId, breakPointParams, asOfDate, UtilMisc.toList("INVOICE_READY"), delegator, timeZone, locale);
}
List<Map<String, Object>> plainList = FastList.<Map<String, Object>>newInstance();
Integer prevDCOBreakPoint = 0;
for (Integer breakPoint : invoicesByDSO.keySet()) {
List<Invoice> invoicesForBreakPoint = invoicesByDSO.get(breakPoint);
if (UtilValidate.isEmpty(invoicesForBreakPoint)) {
plainList.add(UtilMisc.<String, Object>toMap("DCOBreakPoint", breakPoint, "prevDCOBreakPoint", prevDCOBreakPoint, "isEmpty", Boolean.TRUE));
}
for (Invoice invoice : invoicesForBreakPoint) {
FastMap<String, Object> reportLine = FastMap.<String, Object>newInstance();
reportLine.put("prevDCOBreakPoint", prevDCOBreakPoint);
reportLine.put("DCOBreakPoint", breakPoint);
reportLine.put("isEmpty", Boolean.FALSE);
reportLine.put("invoiceDate", invoice.getInvoiceDate());
reportLine.put("invoiceId", invoice.getInvoiceId());
reportLine.put("invoiceTotal", invoice.getInvoiceTotal());
reportLine.put("partyId", invoice.getPartyIdFrom());
reportLine.put("partyName", PartyHelper.getPartyName(delegator, invoice.getPartyIdFrom(), false));
plainList.add(reportLine);
}
prevDCOBreakPoint = breakPoint;
}
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(plainList));
Map<String, Object> jrParameters = FastMap.newInstance();
jrParameters.putAll(ctxt);
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
jrParameters.put("accountingTags", UtilAccountingTags.formatTagsAsString(request, UtilAccountingTags.FINANCIALS_REPORTS_TAG, delegator));
jrParameters.put("isReceivables", Boolean.FALSE);
request.setAttribute("jrParameters", jrParameters);
} catch (GenericEntityException e) {
UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (RepositoryException e) {
UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Prepare data source and parameters for average DSO receivables report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response, either "pdf" or "xls" string to select report type, or "error".
*/
public static String prepareAverageDSOReportReceivables(HttpServletRequest request, HttpServletResponse response) {
return prepareAverageDSOReport("SALES_INVOICE", request);
}
/**
* Prepare data source and parameters for average DSO payables report.
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response, either "pdf" or "xls" string to select report type, or "error".
*/
public static String prepareAverageDSOReportPayables(HttpServletRequest request, HttpServletResponse response) {
return prepareAverageDSOReport("PURCHASE_INVOICE", request);
}
/**
* Implements common logic for average DSO reports.
* @param invoiceTypeId report analyzes invoices of this type
* @param request a <code>HttpServletRequest</code> value
* @return the event response, either "pdf" or "xls" string to select report type, or "error".
*/
+ @SuppressWarnings("unchecked")
private static String prepareAverageDSOReport(String invoiceTypeId, HttpServletRequest request) {
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
TimeZone timeZone = UtilCommon.getTimeZone(request);
Locale locale = UtilCommon.getLocale(request);
String reportType = UtilCommon.getParameter(request, "type");
try {
+ // parse user's input
Map<String, Object> ctxt = prepareFinancialReportParameters(request);
- UtilAccountingTags.addTagParameters(request, ctxt);
Map<String, Object> jrParameters = FastMap.<String, Object>newInstance();
- // get the from and thru date from parseReportOptions
+ // get the from and thru date
Timestamp fromDate = (Timestamp) ctxt.get("fromDate");
Timestamp thruDate = (Timestamp) ctxt.get("thruDate");
// get the invoice type of the report
Boolean isReceivables =
"SALES_INVOICE".equals(invoiceTypeId) ? Boolean.TRUE : "PURCHASE_INVOICE".equals(invoiceTypeId) ? Boolean.FALSE : null;
// don't do anything if invoiceTypeId is invalid
if (isReceivables == null) {
return "error";
}
+ jrParameters.put("isReceivables", isReceivables);
+
// the date of the report is either now or the thruDate of user's input, whichever is earlier
Timestamp now = UtilDateTime.nowTimestamp();
Timestamp reportDate = (thruDate != null && thruDate.before(now) ? thruDate : now);
jrParameters.put("reportDate", reportDate);
- // the partyId field we want to use for grouping the report fields is partyIdFrom for receivables, partyId for payables
+ // report should display period, pass dates to parameters
+ jrParameters.put("fromDate", fromDate);
+ jrParameters.put("thruDate", reportDate);
+
+ // the partyId field we want to use for grouping the report fields is partyIdFrom for receivables or
+ // partyId for payables
String partyIdField = (isReceivables ? "partyId" : "partyIdFrom");
// constants
EntityFindOptions options = new EntityFindOptions(true, EntityFindOptions.TYPE_SCROLL_INSENSITIVE, EntityFindOptions.CONCUR_READ_ONLY, true);
String organizationPartyId = UtilCommon.getOrganizationPartyId(request);
jrParameters.put("organizationPartyId", organizationPartyId);
jrParameters.put("organizationName", PartyHelper.getPartyName(delegator, (String) ctxt.get("organizationPartyId"), false));
- // Get the base currency for the organization
- String currencyUomId = UtilCommon.getOrgBaseCurrency(organizationPartyId, delegator);
-
- // get the invoices as a list iterator. Pending and cancelled invoices should not be considered.
+ // get the invoices as a list iterator. Pending and canceled invoices should not be considered.
List<EntityCondition> conditionList = FastList.<EntityCondition>newInstance();
conditionList.add(EntityCondition.makeCondition("invoiceTypeId", invoiceTypeId));
conditionList.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_IN_PROCESS"));
conditionList.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_WRITEOFF"));
conditionList.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_CANCELLED"));
conditionList.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_VOIDED"));
conditionList.add(EntityCondition.makeCondition("invoiceDate", EntityOperator.LESS_THAN_EQUAL_TO, reportDate));
// use the other partyId field to restrict invoices to those just for the current organization
if (isReceivables) {
conditionList.add(EntityCondition.makeCondition("partyIdFrom", organizationPartyId));
} else {
conditionList.add(EntityCondition.makeCondition("partyId", organizationPartyId));
}
if (fromDate != null) {
conditionList.add(EntityCondition.makeCondition("invoiceDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate) );
}
EntityConditionList<EntityCondition> conditions = EntityCondition.makeCondition(conditionList);
EntityListIterator iterator =
delegator.findListIteratorByCondition("Invoice", conditions, null, null, UtilMisc.toList(partyIdField), options);
// compose the report by keeping each row of data in a report map keyed to partyId
Map<String, Object> reportData = FastMap.<String, Object>newInstance();
GenericValue invoice = null;
while ((invoice = iterator.next()) != null) {
String partyId = invoice.getString(partyIdField);
Map<String, Object> reportLine = (Map<String, Object>) reportData.get(partyId);
// if no row yet, create a new row and add party data for display
if (reportLine == null) {
reportLine = FastMap.<String, Object>newInstance();
reportLine.put("partyId", partyId);
reportLine.put("partyName", PartyHelper.getPartyName(delegator, partyId, false));
}
// keep running total of invoice
BigDecimal invoiceTotal = InvoiceWorker.getInvoiceTotal(invoice);
// convert to the currency exchange rate at the time of the invoiceDate
BigDecimal invoiceSum = UtilFinancial.determineUomConversionFactor(delegator, dispatcher, organizationPartyId, invoice.getString("currencyUomId"), invoice.getTimestamp("invoiceDate")).multiply(invoiceTotal);
if (reportLine.get("invoiceSum") != null) {
invoiceSum = invoiceSum.add((BigDecimal) reportLine.get("invoiceSum")).setScale(2, BigDecimal.ROUND_HALF_UP);
}
reportLine.put("invoiceSum", invoiceSum);
// compute DSO, number of days outstanding for invoice
Timestamp invoiceDate = invoice.getTimestamp("invoiceDate");
if (invoiceDate == null) {
Debug.logWarning("No invoice date for invoice [" + invoice.get("invoiceId") + "], skipping it", MODULE);
}
// if the invoice is PAID, then the paid date from the invoice is used as paid date
// if there is no paidDate, then it is set to invoiceDate -- ie, DSO of 0, because in older versions of ofbiz
// most orders are captured & paid when they are shipped and no paidDate was set
Timestamp dsoDate = reportDate;
if ("INVOICE_PAID".equals(invoice.getString("statusId"))) {
dsoDate = (invoice.get("paidDate") != null ? invoice.getTimestamp("paidDate") : invoiceDate);
}
Calendar fromCal = UtilDate.toCalendar(invoiceDate, timeZone, locale);
Calendar thruCal = UtilDate.toCalendar(dsoDate, timeZone, locale);
BigDecimal dso = BigDecimal.valueOf((thruCal.getTimeInMillis() - fromCal.getTimeInMillis()) / (UtilDate.MS_IN_A_DAY));
// keep running sum of DSO
BigDecimal dsoSum = dso;
if (reportLine.get("dsoSum") != null) {
dsoSum = dsoSum.add((BigDecimal) reportLine.get("dsoSum"));
}
reportLine.put("dsoSum", dsoSum);
// keep running DSO*invoiceTotal sum
BigDecimal dsoValueSum = dso.multiply(invoiceTotal);
if (reportLine.get("dsoValueSum") != null) {
dsoValueSum = dsoValueSum.add((BigDecimal) reportLine.get("dsoValueSum"));
}
reportLine.put("dsoValueSum", dsoValueSum);
// update number of invoices
int numberOfInvoices = 1;
if (reportLine.get("numberOfInvoices") != null) {
numberOfInvoices += ((Integer) reportLine.get("numberOfInvoices")).intValue();
}
reportLine.put("numberOfInvoices", numberOfInvoices);
// update avg DSO
- reportLine.put("dsoAvg", dsoSum.divide(BigDecimal.valueOf(numberOfInvoices)));
+ reportLine.put("dsoAvg", dsoSum.divide(BigDecimal.valueOf(numberOfInvoices), 0, BigDecimal.ROUND_HALF_UP));
// update weighted DSO
reportLine.put("dsoWeighted", invoiceSum.signum() != 0 ? dsoValueSum.divide(invoiceSum, 0, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO);
reportData.put(partyId, reportLine);
}
iterator.close();
Collection<Object> report = reportData.values();
request.setAttribute("jrDataSource", new JRMapCollectionDataSource(report));
// go through report once more and compute totals row
BigDecimal invoiceSum = BigDecimal.ZERO;
BigDecimal dsoSum = BigDecimal.ZERO;
BigDecimal dsoValueSum = BigDecimal.ZERO;
int numberOfInvoices = 0;
for (Object row : reportData.values()) {
Map<String, Object> reportLine = (Map<String, Object>) row;
invoiceSum = invoiceSum.add((BigDecimal) reportLine.get("invoiceSum"));
dsoSum = dsoSum.add((BigDecimal) reportLine.get("dsoSum"));
dsoValueSum = dsoValueSum.add((BigDecimal) reportLine.get("dsoValueSum"));
numberOfInvoices += ((Integer) reportLine.get("numberOfInvoices")).intValue();
}
jrParameters.put("invoiceSum", invoiceSum);
jrParameters.put("dsoSum", dsoSum);
jrParameters.put("dsoValueSum", dsoValueSum);
jrParameters.put("numberOfInvoices", new Integer(numberOfInvoices));
if (numberOfInvoices > 0) {
- jrParameters.put("dsoAvg", dsoSum.divide(BigDecimal.valueOf(numberOfInvoices)));
+ jrParameters.put("dsoAvg", dsoSum.divide(BigDecimal.valueOf(numberOfInvoices), 0, BigDecimal.ROUND_HALF_UP));
};
if (invoiceSum.compareTo(BigDecimal.ZERO) > 0) {
jrParameters.put("dsoWeighted", dsoValueSum.divide(invoiceSum, 0, BigDecimal.ROUND_HALF_UP));
}
request.setAttribute("jrParameters", jrParameters);
} catch (GenericEntityException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, locale, MODULE);
}
return reportType;
}
/**
* Call a service to update GlAccountTransEntryFact entity. This intermediate data are used by budgeting reports.
*
* @param request a <code>HttpServletRequest</code> value
* @param response a <code>HttpServletResponse</code> value
* @return the event response <code>String</code> value
*/
public static String createGlAccountTransEntryFacts(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
String organizationPartyId = (String) request.getSession().getAttribute("organizationPartyId");
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
Map<String, Object> context = FastMap.<String, Object>newInstance();
context.put("organizationPartyId", organizationPartyId);
context.put("userLogin", userLogin);
try {
dispatcher.runSync("financials.collectEncumbranceAndTransEntryFacts", context);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogEventError(request, e, UtilHttp.getLocale(request), MODULE);
}
return "success";
}
/**
* <p>Load data to TaxInvoiceItemFact entity.</p>
*
* <p>TODO: It would be great to rework this service and use Hibernate API. This might make
* code more understandable and independent of underlying database.<br>
* Make sense also rid of sales invoice item fact Kettle transformation and fill out both fact tables
* in one procedure as they very similar.</p>
*
* @param dctx a <code>DispatchContext</code> instance
* @param context the service context <code>Map</code>
* @return the service response <code>Map</code>
*/
public static Map<String, Object> loadTaxInvoiceItemFact(DispatchContext dctx, Map<String, Object> context) {
GenericDelegator delegator = dctx.getDelegator();
Map<String, Object> results = ServiceUtil.returnSuccess();
Locale locale = (Locale) context.get("locale");
if (locale == null) {
locale = Locale.getDefault();
}
TimeZone timeZone = (TimeZone) context.get("timeZone");
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
// collection of unique invoice id
Set<String> uniqueInvoices = FastSet.<String>newInstance();
Long sequenceId = 0L;
try {
// find all invoice items (as join Invoice and InvoiceItem) from involved invoices
// and which aren't sales tax, promotion or shipping charges
DynamicViewEntity salesInvoiceItems = new DynamicViewEntity();
salesInvoiceItems.addMemberEntity("I", "Invoice");
salesInvoiceItems.addMemberEntity("II", "InvoiceItem");
salesInvoiceItems.addViewLink("I", "II", false, ModelKeyMap.makeKeyMapList("invoiceId"));
salesInvoiceItems.addAlias("I", "invoiceDate");
salesInvoiceItems.addAlias("I", "currencyUomId");
salesInvoiceItems.addAlias("I", "invoiceTypeId");
salesInvoiceItems.addAlias("I", "statusId");
salesInvoiceItems.addAlias("I", "partyIdFrom");
salesInvoiceItems.addAlias("II", "invoiceId");
salesInvoiceItems.addAlias("II", "invoiceItemSeqId");
salesInvoiceItems.addAlias("II", "invoiceItemTypeId");
salesInvoiceItems.addAlias("II", "quantity");
salesInvoiceItems.addAlias("II", "amount");
List<String> selectList = UtilMisc.toList("invoiceId", "invoiceItemSeqId", "invoiceDate", "currencyUomId", "quantity", "amount");
selectList.add("partyIdFrom");
DateFormat dayOfMonthFmt = new SimpleDateFormat("dd");
DateFormat monthOfYearFmt = new SimpleDateFormat("MM");
DateFormat yearNumberFmt = new SimpleDateFormat("yyyy");
EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("invoiceTypeId", "SALES_INVOICE"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, Arrays.asList("INVOICE_IN_PROCESS", "INVOICE_CANCELLED", "INVOICE_VOIDED", "INVOICE_WRITEOFF")),
EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.NOT_IN, Arrays.asList("ITM_SALES_TAX", "INV_SALES_TAX", "ITM_PROMOTION_ADJ", "ITM_SHIPPING_CHARGES"))
);
EntityListIterator itemsIterator = delegator.findListIteratorByCondition(salesInvoiceItems, conditions, null, selectList, UtilMisc.toList("invoiceId", "invoiceItemSeqId"), null);
GenericValue invoiceItem = null;
// iterate over found items and build fact item for each
while ((invoiceItem = itemsIterator.next()) != null) {
GenericValue taxInvItemFact = delegator.makeValue("TaxInvoiceItemFact");
// set item ids
String invoiceId = invoiceItem.getString("invoiceId");
uniqueInvoices.add(invoiceId);
String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId");
taxInvItemFact.put("invoiceId", invoiceId);
taxInvItemFact.put("invoiceItemSeqId", invoiceItemSeqId);
// store quantity and amount in variables
BigDecimal quantity = invoiceItem.getBigDecimal("quantity");
if (quantity == null) {
quantity = BigDecimal.ONE;
}
BigDecimal amount = invoiceItem.getBigDecimal("amount");
if (amount == null) {
amount = BigDecimal.ZERO;
}
// set gross amount
BigDecimal grossAmount = quantity.multiply(amount);
taxInvItemFact.set("grossAmount", grossAmount != null ? grossAmount : null);
// set total promotions amount
BigDecimal totalPromotions = getTotalPromoAmount(invoiceId, invoiceItemSeqId, delegator);
taxInvItemFact.set("discounts", totalPromotions != null ? totalPromotions : null);
// set total refunds
BigDecimal totalRefunds = getTotalRefundAmount(invoiceId, invoiceItemSeqId, delegator);
taxInvItemFact.set("refunds", totalRefunds != null ? totalRefunds : null);
// set net amount
// net amount is total sales minus returns and plus adjustments
taxInvItemFact.set("netAmount", grossAmount.subtract(totalRefunds).add(totalPromotions));
// set tax due amount
List<Map<String, Object>> taxes = getTaxDueAmount(invoiceId, invoiceItemSeqId, delegator);
// lookup and set date dimension id
// TODO: date dimension lookup deserves a separate method accepting only argument of Timestamp
Timestamp invoiceDate = invoiceItem.getTimestamp("invoiceDate");
String dayOfMonth = dayOfMonthFmt.format(invoiceDate);
String monthOfYear = monthOfYearFmt.format(invoiceDate);
String yearNumber = yearNumberFmt.format(invoiceDate);
EntityCondition dateDimConditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("dayOfMonth", dayOfMonth),
EntityCondition.makeCondition("monthOfYear", monthOfYear),
EntityCondition.makeCondition("yearNumber", yearNumber));
taxInvItemFact.set("dateDimId", UtilEtl.lookupDimension("DateDim", "dateDimId", dateDimConditions, delegator));
// lookup and set store dimension id
taxInvItemFact.set("storeDimId", lookupStoreDim(invoiceId, invoiceItemSeqId, delegator));
// lookup and set currency dimension id
taxInvItemFact.set("currencyDimId", UtilEtl.lookupDimension("CurrencyDim", "currencyDimId", EntityCondition.makeCondition("uomId", EntityOperator.EQUALS, invoiceItem.getString("currencyUomId")), delegator)
);
// lookup and set organization dimension id
taxInvItemFact.set("organizationDimId", UtilEtl.lookupDimension("OrganizationDim", "organizationDimId", EntityCondition.makeCondition("organizationPartyId", EntityOperator.EQUALS, invoiceItem.getString("partyIdFrom")), delegator)
);
// store collected records
if (UtilValidate.isNotEmpty(taxes)) {
for (Map<String, Object> taxInfo : taxes) {
// add a record for each tax authority party & geo
EntityCondition taxAuthCondList = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("taxAuthPartyId", EntityOperator.EQUALS, taxInfo.get("taxAuthPartyId")),
EntityCondition.makeCondition("taxAuthGeoId", EntityOperator.EQUALS, taxInfo.get("taxAuthGeoId")));
taxInvItemFact.set("taxAuthorityDimId", UtilEtl.lookupDimension("TaxAuthorityDim", "taxAuthorityDimId", taxAuthCondList, delegator));
BigDecimal taxable = (BigDecimal) taxInfo.get("taxable");
if (taxable != null) {
taxable = taxable.subtract(totalRefunds);
}
taxInvItemFact.set("taxable", taxable);
BigDecimal taxDue = (BigDecimal) taxInfo.get("taxDue");
taxInvItemFact.set("taxDue", (taxDue != null && taxable.compareTo(BigDecimal.ZERO) > 0) ? taxDue : BigDecimal.ZERO);
sequenceId++;
taxInvItemFact.set("taxInvItemFactId", sequenceId);
taxInvItemFact.create();
}
} else {
taxInvItemFact.set("taxAuthorityDimId", Long.valueOf(0));
taxInvItemFact.set("taxDue", BigDecimal.ZERO);
taxInvItemFact.set("taxable", BigDecimal.ZERO);
sequenceId++;
taxInvItemFact.set("taxInvItemFactId", sequenceId);
taxInvItemFact.create();
}
}
itemsIterator.close();
// following code retrieve all sales tax invoice items that have no parent invoice item
// hence can't be linked to any product invoice item and described as separate fact row.
DynamicViewEntity dv = new DynamicViewEntity();
dv.addMemberEntity("I", "Invoice");
dv.addMemberEntity("II", "InvoiceItem");
dv.addViewLink("I", "II", false, ModelKeyMap.makeKeyMapList("invoiceId"));
dv.addAlias("I", "invoiceDate");
dv.addAlias("I", "currencyUomId");
dv.addAlias("I", "invoiceId");
dv.addAlias("I", "partyIdFrom");
dv.addAlias("II", "invoiceItemSeqId");
dv.addAlias("II", "invoiceItemTypeId");
dv.addAlias("II", "parentInvoiceId");
dv.addAlias("II", "parentInvoiceItemSeqId");
dv.addAlias("II", "quantity");
dv.addAlias("II", "amount");
dv.addAlias("II", "taxAuthPartyId");
dv.addAlias("II", "taxAuthGeoId");
ComplexAlias totalAlias = new ComplexAlias("*");
totalAlias.addComplexAliasMember(new ComplexAliasField("II", "quantity", "1.0", null));
totalAlias.addComplexAliasMember(new ComplexAliasField("II", "amount", "0.0", null));
dv.addAlias("II", "totalAmount", null, null, null, null, null, totalAlias);
selectList = UtilMisc.toList("invoiceId", "invoiceItemSeqId", "totalAmount", "taxAuthPartyId", "taxAuthGeoId", "currencyUomId");
selectList.add("partyIdFrom");
selectList.add("invoiceDate");
EntityCondition invoiceLevelTaxConditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("invoiceItemTypeId", "ITM_SALES_TAX"),
EntityCondition.makeCondition("invoiceId", EntityOperator.IN, uniqueInvoices),
EntityCondition.makeCondition("parentInvoiceId", EntityOperator.EQUALS, null),
EntityCondition.makeCondition("parentInvoiceItemSeqId", EntityOperator.EQUALS, null));
EntityListIterator iter2 = delegator.findListIteratorByCondition(dv, invoiceLevelTaxConditions, null, selectList, null, null);
GenericValue tax = null;
// iterate over found records and create fact row for each
// every such fact looks like ordinary one but has only valued amount taxDue, all other equals to zero
while ((tax = iter2.next()) != null) {
BigDecimal amount = tax.getBigDecimal("totalAmount");
if (amount != null) {
// date lookup conditions
Timestamp invoiceDate = tax.getTimestamp("invoiceDate");
String dayOfMonth = dayOfMonthFmt.format(invoiceDate);
String monthOfYear = monthOfYearFmt.format(invoiceDate);
String yearNumber = yearNumberFmt.format(invoiceDate);
EntityCondition dateDimConditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("dayOfMonth", dayOfMonth),
EntityCondition.makeCondition("monthOfYear", monthOfYear),
EntityCondition.makeCondition("yearNumber", yearNumber));
// tax authority lookup conditions
EntityCondition taxAuthCondList = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("taxAuthPartyId", tax.get("taxAuthPartyId")),
EntityCondition.makeCondition("taxAuthGeoId", tax.get("taxAuthGeoId")));
GenericValue taxInvItemFact = delegator.makeValue("TaxInvoiceItemFact");
taxInvItemFact.set("dateDimId", UtilEtl.lookupDimension("DateDim", "dateDimId", dateDimConditions, delegator));
taxInvItemFact.set("storeDimId", lookupStoreDim(tax.getString("invoiceId"), tax.getString("invoiceItemSeqId"), delegator));
taxInvItemFact.set("taxAuthorityDimId", UtilEtl.lookupDimension("TaxAuthorityDim", "taxAuthorityDimId", taxAuthCondList, delegator));
taxInvItemFact.set("currencyDimId", UtilEtl.lookupDimension("CurrencyDim", "currencyDimId", EntityCondition.makeCondition("uomId", EntityOperator.EQUALS, tax.getString("currencyUomId")), delegator));
taxInvItemFact.set("organizationDimId", UtilEtl.lookupDimension("OrganizationDim", "organizationDimId", EntityCondition.makeCondition("organizationPartyId", EntityOperator.EQUALS, tax.getString("partyIdFrom")), delegator));
taxInvItemFact.set("invoiceId", tax.getString("invoiceId"));
taxInvItemFact.set("invoiceItemSeqId", tax.getString("invoiceItemSeqId"));
taxInvItemFact.set("grossAmount", BigDecimal.ZERO);
taxInvItemFact.set("discounts", BigDecimal.ZERO);
taxInvItemFact.set("refunds", BigDecimal.ZERO);
taxInvItemFact.set("netAmount", BigDecimal.ZERO);
taxInvItemFact.set("taxable", BigDecimal.ZERO);
BigDecimal totalAmount = tax.getBigDecimal("totalAmount");
taxInvItemFact.set("taxDue", totalAmount != null ? totalAmount : null);
sequenceId++;
taxInvItemFact.set("taxInvItemFactId", sequenceId);
taxInvItemFact.create();
}
}
iter2.close();
} catch (GenericEntityException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
return results;
}
/**
* <p>Collect sales taxes on given sales invoice item.<br>
* Since a few tax items to different authorities are possible this method returns records grouped
* by tax authority party and geographical unit.</p>
*
* @param invoiceId sales invoice id
* @param invoiceItemSeqId sales invoice item id
* @param delegator <code>GenericDelegator</code> instance
* @return
* Each record is <code>Map</code> with following members:<br>
* <b>taxAuthPartyId</b> : tax authority party<br>
* <b>taxAuthGeoId</b> : tax authority geographical unit<br>
* <b>taxDue</b> : sales tax amount under the taxing authority<br>
* <b>taxable</b> : taxable amount of specified invoice item
* @throws GenericEntityException
*/
private static List<Map<String, Object>> getTaxDueAmount(String invoiceId, String invoiceItemSeqId, GenericDelegator delegator) throws GenericEntityException {
List<Map<String, Object>> taxes = FastList.newInstance();
// find sales tax invoice items which have given invoice item as parent
// and calculate product of quantity and amount for each record
DynamicViewEntity dv = new DynamicViewEntity();
ComplexAlias a = new ComplexAlias("*");
a.addComplexAliasMember(new ComplexAliasField("II", "quantity", "1.0", null));
a.addComplexAliasMember(new ComplexAliasField("II", "amount", "0.0", null));
dv.addMemberEntity("II", "InvoiceItem");
dv.addAlias("II", "taxAuthPartyId", null, null, null, Boolean.TRUE, null);
dv.addAlias("II", "taxAuthGeoId", null, null, null, Boolean.TRUE, null);
dv.addAlias("II", "parentInvoiceId");
dv.addAlias("II", "parentInvoiceItemSeqId");
dv.addAlias("II", "quantity");
dv.addAlias("II", "amount");
dv.addAlias("II", "totalTaxDue", null, null, null, null, "sum", a);
dv.addAlias("II", "invoiceId", null, null, null, Boolean.TRUE, null);
dv.addAlias("II", "invoiceItemSeqId", null, null, null, Boolean.TRUE, null);
dv.addAlias("II", "invoiceItemTypeId");
EntityCondition conditionList = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.EQUALS, "ITM_SALES_TAX"),
EntityCondition.makeCondition("parentInvoiceId", EntityOperator.EQUALS, invoiceId),
EntityCondition.makeCondition("parentInvoiceItemSeqId", EntityOperator.EQUALS, invoiceItemSeqId));
List<String> selectList = UtilMisc.toList("totalTaxDue", "taxAuthPartyId", "taxAuthGeoId");
// retrieve complete list because only small number of sales tax items might be related to an invoice item
EntityListIterator iter = delegator.findListIteratorByCondition(dv, conditionList, null, selectList, null, null);
List<GenericValue> taxItems = iter.getCompleteList();
iter.close();
for (GenericValue taxItem : taxItems) {
BigDecimal taxDue = taxItem.getBigDecimal("totalTaxDue");
BigDecimal taxAdjAmount = BigDecimal.ZERO;
String taxAuthPartyId = taxItem.getString("taxAuthPartyId");
String taxAuthGeoId = taxItem.getString("taxAuthGeoId");
// calculate taxable amount for current invoiceId, invoiceItemSeqId and authority data
BigDecimal taxable = BigDecimal.ZERO;
GenericValue originalInvoiceItem = delegator.findByPrimaryKey("InvoiceItem", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId));
if (originalInvoiceItem != null) {
BigDecimal taxableQuantity = originalInvoiceItem.getBigDecimal("quantity");
BigDecimal taxableAmount = originalInvoiceItem.getBigDecimal("amount");
taxable = (taxableQuantity == null ? BigDecimal.ONE : taxableQuantity).multiply((taxableAmount == null ? BigDecimal.ZERO : taxableAmount));
}
// track relation to order and further to return invoice
// OrderItemBilling -> ReturnItem -> ReturnItemBilling -> InvoiceItem
List<GenericValue> orderItemBillings = delegator.findByAnd("OrderItemBilling", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId));
for (GenericValue orderItemBilling : orderItemBillings) {
List<GenericValue> returnItems = delegator.findByAnd("ReturnItem", UtilMisc.toMap("orderId", orderItemBilling.getString("orderId"), "orderItemSeqId", orderItemBilling.getString("orderItemSeqId")));
for (GenericValue returnItem : returnItems) {
List<GenericValue> returnBillings = returnItem.getRelated("ReturnItemBilling");
for (GenericValue returnItemBilling : returnBillings) {
String ribInvoiceId = returnItemBilling.getString("invoiceId");
String ribInvoiceItemSeqId = returnItemBilling.getString("invoiceItemSeqId");
// retrieve return invoice items as join of Invoice and InvoiceItem
// and calculate product of quantity and amount for each record
DynamicViewEntity rdv = new DynamicViewEntity();
rdv.addMemberEntity("RI", "Invoice");
rdv.addMemberEntity("RII", "InvoiceItem");
rdv.addAlias("RI", "invoiceId");
rdv.addAlias("RI", "invoiceTypeId");
rdv.addAlias("RII", "parentInvoiceId");
rdv.addAlias("RII", "parentInvoiceItemSeqId");
rdv.addAlias("RII", "invoiceItemTypeId");
rdv.addAlias("RII", "taxAuthPartyId");
rdv.addAlias("RII", "taxAuthGeoId");
rdv.addAlias("RII", "quantity");
rdv.addAlias("RII", "amount");
ComplexAlias r = new ComplexAlias("*");
r.addComplexAliasMember(new ComplexAliasField("RII", "quantity", "1.0", null));
r.addComplexAliasMember(new ComplexAliasField("RII", "amount", "0.0", null));
rdv.addAlias("RII", "totalTaxRefundAdj", null, null, null, null, "sum", r);
EntityCondition conditionList1 = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, ribInvoiceId),
EntityCondition.makeCondition("invoiceTypeId", EntityOperator.EQUALS, "CUST_RTN_INVOICE"),
EntityCondition.makeCondition("parentInvoiceId", EntityOperator.EQUALS, ribInvoiceId),
EntityCondition.makeCondition("parentInvoiceItemSeqId", EntityOperator.EQUALS, ribInvoiceItemSeqId),
EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.EQUALS, "CRT_SALES_TAX_ADJ"),
EntityCondition.makeCondition("taxAuthPartyId", EntityOperator.EQUALS, taxAuthPartyId),
EntityCondition.makeCondition("taxAuthGeoId", EntityOperator.EQUALS, taxAuthGeoId));
EntityListIterator iter1 = delegator.findListIteratorByCondition(rdv, conditionList1, null, Arrays.asList("totalTaxRefundAdj"), null, null);
List<GenericValue> taxAdjs = iter1.getCompleteList();
iter1.close();
// add up sales tax adjustments
for (GenericValue taxAdj : taxAdjs) {
BigDecimal totalTaxRefundAdj = taxAdj.getBigDecimal("totalTaxRefundAdj");
if (totalTaxRefundAdj != null) {
taxAdjAmount = taxAdjAmount.add(totalTaxRefundAdj);
}
}
}
}
}
// tad due w/o tax adjustments
taxDue = taxDue.subtract(taxAdjAmount);
// add all significant things into return value
taxes.add(UtilMisc.<String, Object>toMap(
"taxDue", taxDue,
"taxAuthPartyId", taxAuthPartyId,
"taxAuthGeoId", taxAuthGeoId,
"taxable", taxable
));
}
return taxes;
}
/**
* Returns amount that corresponds to sales subject returned by customer.
*
* @param invoiceId sales invoice id
* @param invoiceItemSeqId sales invoice item id
* @param delegator <code>GenericDelegator</code> instance.
* @return refund amount for given sales invoice item.
* @throws GenericEntityException
*/
private static BigDecimal getTotalRefundAmount(String invoiceId, String invoiceItemSeqId, GenericDelegator delegator) throws GenericEntityException {
BigDecimal totalRefunds = BigDecimal.ZERO;
long totalRefundsIiNum = 0;
// find order item corresponding to given sales invoice item, available in OrderItemBilling
List<GenericValue> orderItemBillings = delegator.findByAnd("OrderItemBilling", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId));
if (UtilValidate.isEmpty(orderItemBillings)) {
// not found
return BigDecimal.ZERO;
}
// find all return invoice items related to given invoice item looking through
// OrderItemBilling -> ReturnItem -> ReturnItemBilling
// add up product of quantity and amount of each item to calculate returns amount
for (GenericValue orderBillingItem : orderItemBillings) {
List<GenericValue> returnItems = delegator.findByAnd("ReturnItem", UtilMisc.toMap("orderId", orderBillingItem.getString("orderId"), "orderItemSeqId", orderBillingItem.getString("orderItemSeqId")));
for (GenericValue returnItem : returnItems) {
List<GenericValue> returnItemBillings = returnItem.getRelated("ReturnItemBilling");
for (GenericValue returnItemBilling : returnItemBillings) {
GenericValue returnInvoice = returnItemBilling.getRelatedOne("Invoice");
if ("CUST_RTN_INVOICE".equals(returnInvoice.getString("invoiceTypeId"))) {
GenericValue returnInvoiceItem = returnItemBilling.getRelatedOne("InvoiceItem");
if ("CRT_PROD_ITEM".equals(returnInvoiceItem.getString("invoiceItemTypeId"))
|| "CRT_DPROD_ITEM".equals(returnInvoiceItem.getString("invoiceItemTypeId"))
|| "CRT_FDPROD_ITEM".equals(returnInvoiceItem.getString("invoiceItemTypeId"))
|| "CRT_PROD_FEATR_ITEM".equals(returnInvoiceItem.getString("invoiceItemTypeId"))
|| "CRT_SPROD_ITEM".equals(returnInvoiceItem.getString("invoiceItemTypeId"))
) {
BigDecimal quantity = returnInvoiceItem.getBigDecimal("quantity");
BigDecimal amount = returnInvoiceItem.getBigDecimal("amount");
totalRefunds = totalRefunds.add((quantity == null ? BigDecimal.ONE : quantity).multiply((amount == null ? BigDecimal.ZERO : amount)));
totalRefundsIiNum++;
}
}
}
}
}
return totalRefunds;
}
/**
* Returns total amount of discounts and promotions on given sales invoice item.
*
* @param invoiceId sales invoice id
* @param invoiceItemSeqId sales invoice item id
* @param delegator <code>GenericDelegator</code> instance
* @return sales invoice item adjustments.
* @throws GenericEntityException
*/
private static BigDecimal getTotalPromoAmount(String invoiceId, String invoiceItemSeqId, GenericDelegator delegator) throws GenericEntityException {
BigDecimal totalPromotions = BigDecimal.ZERO;
// find promotion/discount invoice items which have given invoice item as a parent
EntityCondition promoConditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("parentInvoiceId", EntityOperator.EQUALS, invoiceId),
EntityCondition.makeCondition("parentInvoiceItemSeqId", EntityOperator.EQUALS, invoiceItemSeqId),
EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, Arrays.asList("ITM_PROMOTION_ADJ", "ITM_DISCOUNT_ADJ")));
List<GenericValue> promoItems = delegator.findByCondition("InvoiceItem", promoConditions, UtilMisc.toSet("quantity", "amount"), null);
// add up each product of quantity and amount to get total promotion amount related to specified invoice item
// default value for quantity is 1 and for amount is 0
if (UtilValidate.isNotEmpty(promoItems)) {
for (GenericValue promoItem : promoItems) {
BigDecimal quantity = promoItem.getBigDecimal("quantity");
BigDecimal amount = promoItem.getBigDecimal("amount");
totalPromotions = totalPromotions.add((quantity == null ? BigDecimal.ONE : quantity).multiply((amount == null ? BigDecimal.ZERO : amount)));
}
}
return totalPromotions;
}
/**
* Lookup store dimension key.
*
* @param invoiceId invoice identifier
* @param invoiceItemSeqId invoice item sequence number
* @param delegator <code>GenericDelegator</code> instance
* @return
* Store dimension key.
* @throws GenericEntityException
*/
private static Long lookupStoreDim(String invoiceId, String invoiceItemSeqId, GenericDelegator delegator) throws GenericEntityException {
// store dim has a special record with key 0 with meaning "no product store"
Long notfound = 0L;
if (invoiceId == null && invoiceItemSeqId == null) {
return notfound;
}
// in order to get product store id for an invoice item we have to find OrderItemBilling
// entity for the invoice item and further corresponding OrderHeader.productStoreId
DynamicViewEntity dv = new DynamicViewEntity();
dv.addMemberEntity("OIB", "OrderItemBilling");
dv.addMemberEntity("OH", "OrderHeader");
dv.addAlias("OIB", "invoiceId");
dv.addAlias("OIB", "invoiceItemSeqId");
dv.addAlias("OIB", "orderId");
dv.addAlias("OH", "orderId");
dv.addAlias("OH", "productStoreId", null, null, null, null, "max");
dv.addViewLink("OIB", "OH", false, ModelKeyMap.makeKeyMapList("orderId"));
EntityCondition conditionList = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId),
EntityCondition.makeCondition("invoiceItemSeqId", EntityOperator.EQUALS, invoiceItemSeqId));
// retrieve first record
EntityListIterator iter = delegator.findListIteratorByCondition(dv, conditionList, null, UtilMisc.toList("productStoreId"), null, null);
GenericValue orderStore = EntityUtil.getFirst(iter.getCompleteList());
iter.close();
// it isn't necessary order have to be found
if (orderStore == null) {
return notfound;
}
String productStoreId = orderStore.getString("productStoreId");
if (UtilValidate.isEmpty(productStoreId)) {
return notfound;
}
// find store dimension key for given productStoreId
GenericValue storeDim = EntityUtil.getFirst(
delegator.findByCondition("StoreDim", EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, productStoreId), Arrays.asList("storeDimId"), null)
);
if (storeDim == null) {
return notfound;
}
// return store dimension key
Long storeDimId = storeDim.getLong("storeDimId");
return storeDimId == null ? notfound : storeDimId;
}
/**
* <p>Look over invoice adjustments and transform them into into sales and tax invoice item facts.
* Thus an adjustment amount is added into discount column of the fact table and this is only
* currency column affected.</p>
*
* @param session Hibernate session
* @throws GenericEntityException
*/
public static void loadInvoiceAdjustments(Session session, GenericDelegator delegator) throws GenericEntityException {
Transaction tx = session.beginTransaction();
// retrieve data as scrollable result set.
// this is join of InvoiceAdjustment and Invoice entities and each record has all required data
// to create new fact row
Query invAdjQry = session.createQuery("select IA.invoiceAdjustmentId, IA.invoiceId, IA.amount, I.partyIdFrom, I.invoiceDate, I.currencyUomId from InvoiceAdjustment IA, Invoice I where IA.invoiceId = I.invoiceId and I.invoiceTypeId = 'SALES_INVOICE' and I.statusId not in ('INVOICE_IN_PROCESS', 'INVOICE_CANCELLED', 'INVOICE_VOIDED', 'INVOICE_WRITEOFF')");
ScrollableResults adjustments = invAdjQry.scroll();
// iterate over record set
while (adjustments.next()) {
// keep result fields in variables as a matter of convenience
String invoiceId = adjustments.getString(1);
String invoiceAdjustmentId = adjustments.getString(0);
BigDecimal amount = adjustments.getBigDecimal(2);
String organizationPartyId = adjustments.getString(3);
Timestamp invoiceDate = (Timestamp) adjustments.get(4);
String currencyUomId = adjustments.getString(5);
// lookup date dimension
DateFormat dayOfMonthFmt = new SimpleDateFormat("dd");
DateFormat monthOfYearFmt = new SimpleDateFormat("MM");
DateFormat yearNumberFmt = new SimpleDateFormat("yyyy");
String dayOfMonth = dayOfMonthFmt.format(invoiceDate);
String monthOfYear = monthOfYearFmt.format(invoiceDate);
String yearNumber = yearNumberFmt.format(invoiceDate);
EntityCondition dateDimConditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition("dayOfMonth", dayOfMonth),
EntityCondition.makeCondition("monthOfYear", monthOfYear),
EntityCondition.makeCondition("yearNumber", yearNumber));
Long dateDimId = UtilEtl.lookupDimension("DateDim", "dateDimId", dateDimConditions, delegator);
// lookup currency dimension
Long currencyDimId = UtilEtl.lookupDimension("CurrencyDim", "currencyDimId", EntityCondition.makeCondition("uomId", currencyUomId), delegator);
// lookup organization dimension
Long organizationDimId = UtilEtl.lookupDimension("OrganizationDim", "organizationDimId", EntityCondition.makeCondition("organizationPartyId", organizationPartyId), delegator);
// creates rows for both fact tables
TaxInvoiceItemFact taxFact = new TaxInvoiceItemFact();
taxFact.setDateDimId(dateDimId);
taxFact.setStoreDimId(0L);
taxFact.setTaxAuthorityDimId(0L);
taxFact.setCurrencyDimId(currencyDimId);
taxFact.setOrganizationDimId(organizationDimId);
taxFact.setInvoiceId(invoiceId);
taxFact.setInvoiceAdjustmentId(invoiceAdjustmentId);
taxFact.setGrossAmount(BigDecimal.ZERO);
taxFact.setDiscounts(amount);
taxFact.setRefunds(BigDecimal.ZERO);
taxFact.setNetAmount(BigDecimal.ZERO);
taxFact.setTaxable(BigDecimal.ZERO);
taxFact.setTaxDue(BigDecimal.ZERO);
session.save(taxFact);
SalesInvoiceItemFact salesFact = new SalesInvoiceItemFact();
salesFact.setDateDimId(dateDimId);
salesFact.setStoreDimId(0L);
salesFact.setCurrencyDimId(currencyDimId);
salesFact.setOrganizationDimId(organizationDimId);
salesFact.setInvoiceId(invoiceId);
salesFact.setInvoiceAdjustmentId(invoiceAdjustmentId);
salesFact.setGrossAmount(BigDecimal.ZERO);
salesFact.setDiscounts(amount);
salesFact.setRefunds(BigDecimal.ZERO);
salesFact.setNetAmount(BigDecimal.ZERO);
session.save(salesFact);
}
adjustments.close();
tx.commit(); // persist result, don't move this statement upper
}
/**
* Wrapper service that prepare fact tables on behalf of sales tax report
* running Kettle sales tax transformations and loadTaxInvoiceItemFact service.
*
* @param dctx a <code>DispatchContext</code> instance
* @param context the service context <code>Map</code>
* @return the service response <code>Map</code>
*/
public static Map<String, Object> loadSalesTaxData(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericDelegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
if (locale == null) {
locale = Locale.getDefault();
}
TimeZone timeZone = (TimeZone) context.get("timeZone");
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
String organizationPartyId = (String) context.get("organizationPartyId");
// since organization party id attribute is optional we use special value
// in case no id is provided, in order to keep this fact in runtime data
if (UtilValidate.isEmpty(organizationPartyId)) {
organizationPartyId = "ALL";
}
Map<String, Object> results = ServiceUtil.returnSuccess();
Timestamp startedAt = UtilDateTime.nowTimestamp();
try {
long rowCount = delegator.findCountByCondition("DateDim", null, null);
if (rowCount < 2) {
Debug.logInfo("Creating date dimension ...", MODULE);
UtilEtl.setupDateDimension(delegator, timeZone, locale);
}
// clean up datamart data
Debug.logInfo("Clean up dimension and fact tables", MODULE);
delegator.removeByCondition("StoreDim", EntityCondition.makeCondition("storeDimId", EntityOperator.NOT_EQUAL, null));
delegator.removeByCondition("TaxAuthorityDim", EntityCondition.makeCondition("taxAuthorityDimId", EntityOperator.NOT_EQUAL, null));
delegator.removeByCondition("CurrencyDim", EntityCondition.makeCondition("currencyDimId", EntityOperator.NOT_EQUAL, null));
delegator.removeByCondition("OrganizationDim", EntityCondition.makeCondition("organizationDimId", EntityOperator.NOT_EQUAL, null));
delegator.removeByCondition("SalesInvoiceItemFact", EntityCondition.makeCondition("dateDimId", EntityOperator.NOT_EQUAL, null));
delegator.removeByCondition("TaxInvoiceItemFact", EntityCondition.makeCondition("dateDimId", EntityOperator.NOT_EQUAL, null));
// ETL transformations use JNDI to obtain database connection parameters.
// We have to put proper data source into naming context before run transformations.
String dataSourceName = delegator.getGroupHelperName("org.ofbiz");
DataSourceImpl datasource = new DataSourceImpl(dataSourceName);
new InitialContext().rebind("java:comp/env/jdbc/default_delegator", datasource);
// run the ETL transformations to load the datamarts
UtilEtl.runTrans("component://financials/script/etl/load_product_store_dimension.ktr", null);
UtilEtl.runTrans("component://financials/script/etl/load_tax_authority_dimension.ktr", null);
UtilEtl.runTrans("component://financials/script/etl/load_organization_dimension.ktr", null);
UtilEtl.runTrans("component://financials/script/etl/load_sales_invoice_item_fact.ktr", null);
UtilEtl.runTrans("component://financials/script/etl/load_invoice_level_promotions.ktr", null);
// ... and invoke other required services and methods
dispatcher.runSync("financials.loadTaxInvoiceItemFact", UtilMisc.toMap("userLogin", userLogin, "locale", locale));
loadInvoiceAdjustments(new Infrastructure(dispatcher).getSession(), delegator);
// unregister data source
new InitialContext().unbind("java:comp/env/jdbc/default_delegator");
// keep runtime info
GenericValue transform = delegator.makeValue("DataWarehouseTransform");
transform.set("transformId", delegator.getNextSeqId("DataWarehouseTransform"));
transform.set("organizationPartyId", organizationPartyId);
transform.set("transformEnumId", "SALES_TAX_FACT");
transform.set("transformTimestamp", startedAt);
transform.set("userLoginId", userLogin.get("userLoginId"));
transform.create();
} catch (GenericEntityException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
} catch (GenericServiceException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
} catch (NamingException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
} catch (InfrastructureException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
return results;
}
}
| false | false | null | null |
diff --git a/src/de/meisterfuu/animexx/ENS/ENSObject.java b/src/de/meisterfuu/animexx/ENS/ENSObject.java
index 5539263..8ff31e3 100644
--- a/src/de/meisterfuu/animexx/ENS/ENSObject.java
+++ b/src/de/meisterfuu/animexx/ENS/ENSObject.java
@@ -1,291 +1,295 @@
package de.meisterfuu.animexx.ENS;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import de.meisterfuu.animexx.Helper;
import de.meisterfuu.animexx.other.UserObject;
public class ENSObject implements Comparable<Object> {
private String Betreff, Signatur, Time, AnVon;
private String Text = "";
private int Flags, Konversation, id, Typ;
private long ENS_id, Referenz, Ordner, TimeStamp;
private UserObject von;
private ArrayList<UserObject> an = new ArrayList<UserObject>();
public boolean IsEmpty = false;
public ENSObject() {
}
public boolean isFolder() {
if (Typ == 99) return true;
return false;
}
public String getTitle() {
return Betreff;
}
public boolean isSystem() {
// TODO Auto-generated method stub
return (getTyp() == 2);
}
public boolean isUnread() {
String flag = Integer.toBinaryString(getFlags());
if (flag.length() >= 2 && flag.charAt(flag.length() - 2) == '1')
return false;
else
return true;
}
@Override
public boolean equals(Object obj) {
return (this.getTimeStamp() == ((ENSObject) obj).getTimeStamp());
}
public int compareTo(Object arg0) {
if (this.getTimeStamp() < ((ENSObject) arg0).getTimeStamp()) {
return 1;
} else if (this.getTimeStamp() > ((ENSObject) arg0).getTimeStamp()) {
return -1;
} else {
return 0;
}
}
public ENSObject parseJSON(JSONObject JSON) {
try {
this.setBetreff(JSON.getString("betreff"));
this.setTime(JSON.getString("datum_server"));
if (JSON.has("text_html")) this.setText(JSON.getString("text_html"));
UserObject von = new UserObject();
- if (JSON.has("von")) von.ParseJSON(JSON.getJSONObject("von"));
+ if (!JSON.isNull("von")) von.ParseJSON(JSON.getJSONObject("von"));
this.setVon(von);
- if (JSON.has("an"))
- for (int z = 0; z < JSON.getJSONArray("an").length(); z++) {
+ if (!JSON.isNull("an")) {
+ for (int z = 0; z < JSON.getJSONArray("an").length(); z++) {
+ UserObject an = new UserObject();
+ an.ParseJSON(JSON.getJSONArray("an").getJSONObject(z));
+ this.addAnUser(an);
+ }
+ } else {
UserObject an = new UserObject();
- an.ParseJSON(JSON.getJSONArray("an").getJSONObject(z));
this.addAnUser(an);
}
-
+
if (JSON.has("an_flags")) {
this.setFlags(JSON.getInt("an_flags"));
} else {
this.setFlags(JSON.getInt("von_flags"));
}
this.setENS_id(JSON.getLong("id"));
this.setTyp(JSON.getInt("typ"));
if (JSON.has("von_ordner")) {
this.setOrdner(JSON.getInt("von_ordner"));
this.setAnVon("von");
} else {
this.setOrdner(JSON.getInt("an_ordner"));
this.setAnVon("an");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
public void addAnUser(UserObject user) {
this.an.add(user);
}
public UserObject getAnUser(int i) {
return this.an.get(i);
}
public UserObject[] getAnArray() {
UserObject[] temp = new UserObject[this.an.size()];
for (int i = 0; i < this.an.size(); i++) {
temp[i] = this.an.get(i);
}
return temp;
}
public String getAnString() {
String s = "";
for (UserObject i : this.an) {
s = i.getUsername() + ", ";
}
s = s.substring(0, s.length() - 3);
return s;
}
public String getAnIDString() {
String s = "";
for (UserObject i : this.an) {
s = i.getId() + ", ";
}
s = s.substring(0, s.length() - 3);
return s;
}
public String getText() {
return Text;
}
public void setText(String text) {
Text = text;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getSignatur() {
return Signatur;
}
public void setSignatur(String signatur) {
Signatur = signatur;
}
public long getENS_id() {
return ENS_id;
}
public void setENS_id(long eNS_id) {
ENS_id = eNS_id;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
TimeStamp = Helper.toTimestamp(time);
Time = time;
}
public int getFlags() {
return Flags;
}
public void setFlags(int flags) {
Flags = flags;
}
public long getReferenz() {
return Referenz;
}
public void setReferenz(long referenz) {
Referenz = referenz;
}
public int getKonversation() {
return Konversation;
}
public void setKonversation(int konversation) {
Konversation = konversation;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getOrdner() {
return Ordner;
}
public void setOrdner(long folder) {
Ordner = folder;
}
public int getTyp() {
return Typ;
}
public void setTyp(int typ) {
Typ = typ;
}
public UserObject getVon() {
return von;
}
public void setVon(UserObject von) {
this.von = von;
}
public String getAnVon() {
return AnVon;
}
public void setAnVon(String anVon) {
AnVon = anVon;
}
public long getTimeStamp() {
return TimeStamp;
}
public void setTimeStamp(long timeStamp) {
TimeStamp = timeStamp;
}
}
| false | false | null | null |
diff --git a/structure/src/main/java/org/biojava/bio/structure/align/AFPTwister.java b/structure/src/main/java/org/biojava/bio/structure/align/AFPTwister.java
index a3c4d1543..7b7afbfa6 100644
--- a/structure/src/main/java/org/biojava/bio/structure/align/AFPTwister.java
+++ b/structure/src/main/java/org/biojava/bio/structure/align/AFPTwister.java
@@ -1,472 +1,480 @@
/* This class is based on the original FATCAT implementation by
* <pre>
* Yuzhen Ye & Adam Godzik (2003)
* Flexible structure alignment by chaining aligned fragment pairs allowing twists.
* Bioinformatics vol.19 suppl. 2. ii246-ii255.
* http://www.ncbi.nlm.nih.gov/pubmed/14534198
* </pre>
*
* Thanks to Yuzhen Ye and A. Godzik for granting permission to freely use and redistribute this 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.
*
*
* Created on Jun 17, 2009
* Created by Andreas Prlic - RCSB PDB
*
*/
package org.biojava.bio.structure.align;
import java.util.ArrayList;
import java.util.List;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.Calc;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.ChainImpl;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.SVDSuperimposer;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.StructureTools;
//import org.biojava.bio.structure.align.gui.jmol.StructureAlignmentJmol;
import org.biojava.bio.structure.align.model.AFP;
import org.biojava.bio.structure.align.model.AFPChain;
import org.biojava.bio.structure.jama.Matrix;
public class AFPTwister
{
// private static final boolean showAlignmentSteps = false;
private static final boolean debug = false;
/**
* calculate the total rmsd of the blocks
* output a merged pdb file for both proteins
protein 1, in chain A
protein 2 is twisted according to the twists detected, in chain B
- * returns the Atoms of the optTwistPDB.
+ * @return twisted Groups
*/
public static Group[] twistPDB(AFPChain afpChain,Atom[] ca1, Atom[] ca2) throws StructureException {
//--------------------------------------------------------
if ( afpChain.isShortAlign())
return new Group[0];
List<AFP> afpSet = afpChain.getAfpSet();
int blockNum = afpChain.getBlockNum();
int i, b2, e2;
//superimposing according to the initial AFP-chaining
Atom[] origCA = StructureTools.cloneCAArray(ca2);
Atom[] iniTwistPdb = StructureTools.cloneCAArray(ca2);
int[] blockResSize = afpChain.getBlockResSize();
int[][][] blockResList = afpChain.getBlockResList();
int[] afpChainList = afpChain.getAfpChainList();
int[] block2Afp = afpChain.getBlock2Afp();
int[] blockSize = afpChain.getBlockSize();
int[] focusAfpList = afpChain.getFocusAfpList();
if ( focusAfpList == null){
focusAfpList = new int[afpChain.getMinLen()];
afpChain.setFocusAfpList(focusAfpList);
}
int focusAfpn = 0;
e2 = 0;
b2 = 0;
if ( debug)
System.out.println("blockNUm at twister:" + blockNum);
for(int bk = 0; bk < blockNum; bk ++) {
// THIS IS TRANSFORMING THE ORIGINAL ca2 COORDINATES, NO CLONING...
// copies the atoms over to iniTwistPdb later on in modifyCod
transformOrigPDB(blockResSize[bk], blockResList[bk][0], blockResList[bk][1], ca1, ca2, null,-1);
//transform pro2 according to comparison of pro1 and pro2 at give residues
if(bk > 0) {
b2 = e2;
}
if ( debug ){
System.out.println("b2 is " + b2 + " before modifyCon");
}
if(bk < (blockNum - 1)) {
//bend at the middle of two consecutive AFPs
int afpPos = afpChainList[block2Afp[bk] + blockSize[bk] - 1];
AFP a1 = afpSet.get(afpPos);
e2 = a1.getP2() ;
int afpPos2 = afpChainList[block2Afp[bk + 1]];
AFP a2 = afpSet.get(afpPos2);
e2 = (a2.getP2() - e2)/ 2 + e2;
if (debug)
System.err.println("e2 : " + e2);
} else{
// last one is until the end...
e2 = ca2.length;
}
// this copies the coordinates over into iniTwistPdb
cloneAtomRange(iniTwistPdb, ca2, b2, e2);
//bound[bk] = e2;
for(i = 0; i < blockSize[bk]; i ++) {
focusAfpList[focusAfpn] = afpChainList[block2Afp[bk] + i];
focusAfpn++;
}
}
int focusResn = afp2Res(afpChain, focusAfpn, focusAfpList, 0);
int totalLenIni = focusResn;
afpChain.setTotalLenIni(totalLenIni);
if(debug)
System.out.println(String.format("calrmsdini for %d residues", focusResn));
double totalRmsdIni = calCaRmsd(ca1,iniTwistPdb, focusResn, afpChain.getFocusRes1() , afpChain.getFocusRes2() );
afpChain.setTotalRmsdIni(totalRmsdIni);
if ( debug ) {
System.out.println("got iniRMSD: " + totalRmsdIni);
if ( totalRmsdIni == 5.76611141613097) {
System.out.println(afpChain.getAlnseq1());
System.out.println(afpChain.getAlnsymb());
System.out.println(afpChain.getAlnseq2());
// System.exit(0);
}
}
afpChain.setFocusAfpList(focusAfpList);
afpChain.setBlock2Afp(block2Afp);
afpChain.setAfpChainList(afpChainList);
return twistOptimized(afpChain,ca1,origCA);
}
+ /** superimposing according to the optimized alignment
+ *
+ * @param afpChain
+ * @param ca1
+ * @param ca2
+ * @return Group array twisted.
+ * @throws StructureException
+ */
public static Group[] twistOptimized(AFPChain afpChain,Atom[] ca1, Atom[] ca2) throws StructureException {
- // superimposing according to the optimized alignment
+
Atom[] optTwistPdb = new Atom[ca2.length];
int gPos = -1;
for (Atom a : ca2){
gPos++;
optTwistPdb[gPos] = a;
}
int blockNum = afpChain.getBlockNum();
int b2 = 0;
int e2 = 0;
int focusResn = 0;
int[] focusRes1 = afpChain.getFocusRes1();
int[] focusRes2 = afpChain.getFocusRes2();
if(focusRes1 == null) {
focusRes1 = new int[afpChain.getCa1Length()];
afpChain.setFocusRes1(focusRes1);
}
if(focusRes2 == null) {
focusRes2 = new int[afpChain.getCa2Length()];
afpChain.setFocusRes2(focusRes2);
}
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
for(int bk = 0; bk < blockNum; bk ++) {
//System.out.println("transforming "+ optLen[bk] + " " + bk);
// THIS IS TRANSFORMING THE ORIGINAL ca2 COORDINATES, NO CLONING...
// copies the atoms over to iniTwistPdb later on in modifyCod
transformOrigPDB(optLen[bk], optAln[bk][0], optAln[bk][1], ca1, ca2,afpChain,bk);
//transform pro2 according to comparison of pro1 and pro2 at give residues
if(bk > 0) { b2 = e2; }
if(bk < blockNum - 1) { //bend at the middle of two consecutive blocks
e2 = optAln[bk][1][optLen[bk] - 1];
e2 = (optAln[bk + 1][1][0] - e2)/ 2 + e2;
}
else { e2 = ca2.length; }
//System.out.println("modifyCod: " + b2 + " " + e2);
cloneAtomRange(optTwistPdb, ca2, b2, e2);
//bound[bk] = e2;
for(int i = 0; i < optLen[bk]; i ++) {
// System.out.println("bk " + bk + " i " + i + " optLen:" + optLen[bk] + " " + optAln[bk][0][i]);
focusRes1[focusResn] = optAln[bk][0][i];
focusRes2[focusResn] = optAln[bk][1][i];
focusResn ++;
}
}
int totalLenOpt = focusResn;
if(debug) System.out.println(String.format("calrmsdopt for %d residues\n", focusResn));
double totalRmsdOpt = calCaRmsd(ca1, optTwistPdb, focusResn, focusRes1, focusRes2);
if ( debug ) System.out.println("got opt RMSD: " + totalRmsdOpt);
int optLength = afpChain.getOptLength();
if(totalLenOpt != optLength) {
System.err.println(String.format("Warning: final alignment length is different %d %d\n", totalLenOpt, optLength));
}
if(debug) System.out.println(String.format("final alignment length %d, rmsd %.3f\n", focusResn, totalRmsdOpt));
afpChain.setTotalLenOpt(totalLenOpt);
afpChain.setTotalRmsdOpt(totalRmsdOpt);
Group[] retGroups = StructureTools.cloneGroups(optTwistPdb);
return retGroups;
}
/**
* transform the coordinates in the ca2 according to the superimposing of the given position pairs.
* No Cloning, transforms input atoms.
*/
// orig name: transPdb
private static void transformOrigPDB(int n, int[] res1, int[] res2, Atom[] ca1, Atom[] ca2, AFPChain afpChain, int blockNr)
throws StructureException
{
if ( debug ){
System.err.println("transforming original coordinates " + n + " len1: " + ca1.length + " res1:" + res1.length + " len2: "+ ca2.length + " res2: " + res2.length);
}
Atom[] cod1 = getAtoms(ca1, res1, n,false);
Atom[] cod2 = getAtoms(ca2, res2, n,false);
//double *cod1 = pro1->Cod4Res(n, res1);
//double *cod2 = pro2->Cod4Res(n, res2);
Matrix r;
Atom t;
SVDSuperimposer svd = new SVDSuperimposer(cod1, cod2);
r = svd.getRotation();
t = svd.getTranslation();
if ( debug)
System.out.println("transPdb: transforming orig coordinates with matrix: " + r);
if ( afpChain != null ){
Matrix[] ms = afpChain.getBlockRotationMatrix();
if ( ms == null)
ms = new Matrix[afpChain.getBlockNum()];
ms[blockNr]= r;
Atom[] shifts = afpChain.getBlockShiftVector();
if ( shifts == null)
shifts = new Atom[afpChain.getBlockNum()];
shifts[blockNr] = t;
afpChain.setBlockRotationMatrix(ms);
afpChain.setBlockShiftVector(shifts);
}
for (Atom a : ca2){
//Calc.rotate(a, r);
//Calc.shift(a, t);
Calc.rotate(a.getParent(),r);
Calc.shift(a.getParent(),t);
}
}
// like Cod4Res
// most likely the clone flag is not needed
private static Atom[] getAtoms(Atom[] ca, int[] positions, int length, boolean clone){
List<Atom> atoms = new ArrayList<Atom>();
for ( int i = 0 ; i < length ; i++){
int p = positions[i];
Atom a;
if ( clone ){
a = (Atom)ca[p].clone();
a.setParent((Group)ca[p].getParent().clone());
}
else {
a = ca[p];
}
atoms.add(a);
}
return (Atom[]) atoms.toArray(new Atom[atoms.size()]);
}
/** Clones and copies the Atoms from p2 into p1 range is between r1 and r2
*
- * @param p1
+ * @param p1
* @param p2
* @param r1
* @param r2
*/
// orig name: modifyCod
private static void cloneAtomRange(Atom[] p1, Atom[] p2, int r1, int r2)
throws StructureException
{
if ( debug )
System.err.println("modifyCod from: " + r1 + " to: " + r2);
// special clone method, can;t use StructureTools.cloneCAArray, since we access the data
// slightly differently here.
List<Chain> model = new ArrayList<Chain>();
for(int i = r1; i < r2; i ++) {
Group g = p2[i].getParent();
Group newG = (Group)g.clone();
p1[i] = newG.getAtom("CA");
Chain parentC = g.getParent();
Chain newChain = null;
for( Chain c: model){
if (c.getName().equals(parentC.getName())){
newChain = c;
break;
}
}
if ( newChain == null){
newChain = new ChainImpl();
newChain.setName(parentC.getName());
model.add(newChain);
}
newChain.addGroup(newG);
} //modify caCod
}
/**
* Return the rmsd of the CAs between the input pro and this protein, at given positions.
* quite similar to transPdb but while that one transforms the whole ca2, this one only works on the res1 and res2 positions.
*
* Modifies the coordinates in the second set of Atoms (pro).
*
- * @return rmsd
+ * @return rmsd of CAs
*/
private static double calCaRmsd(Atom[] ca1, Atom[] pro, int resn, int[] res1, int[] res2) throws StructureException
{
Atom[] cod1 = getAtoms(ca1, res1,resn,false);
Atom[] cod2 = getAtoms(pro, res2,resn,false);
Matrix r;
Atom t;
if ( cod1.length == 0 || cod2.length == 0){
System.out.println("length of atoms == 0!");
return 99;
}
SVDSuperimposer svd = new SVDSuperimposer(cod1, cod2);
r = svd.getRotation();
t = svd.getTranslation();
for (Atom a : cod2){
//Calc.rotate(a, r);
//Calc.shift(a, t);
Calc.rotate(a.getParent(), r);
Calc.shift(a.getParent(), t);
}
// if ( showAlignmentSteps){
// StructureAlignmentJmol jmol = new StructureAlignmentJmol();
//
// jmol.setAtoms(cod1);
// jmol.evalString("select * ; wireframe off; spacefill off; backbone on; color chain; select ligand;color cpk; wireframe 40;spacefill 120; ");
// jmol.setTitle("calCaRmsd - pdb1");
//
// StructureAlignmentJmol jmol2 = new StructureAlignmentJmol();
// jmol2.setAtoms(cod2);
// jmol2.evalString("select * ; wireframe off; spacefill off; backbone on; color chain; select ligand;color cpk; wireframe 40;spacefill 120; ");
// jmol2.setTitle("calCaRmsd - pdb2");
// }
return SVDSuperimposer.getRMS(cod1, cod2);
}
/**
* Set the list of equivalent residues in the two proteins given a list of AFPs
*
* WARNING: changes the values for FocusRes1, focusRes2 and FocusResn in afpChain!
*
- * @param afpn the AFPChain to store results in
+ * @param afpChain the AFPChain to store resuts
+ * @param afpn nr of afp
* @param afpPositions
- * @param res1
- * @param res2
+ * @param listStart
* @return
*/
public static int afp2Res(AFPChain afpChain, int afpn, int[] afpPositions , int listStart )
{
int[] res1 = afpChain.getFocusRes1();
int[] res2 = afpChain.getFocusRes2();
int minLen = afpChain.getMinLen();
int n = 0;
List<AFP> afpSet =afpChain.getAfpSet();
for(int i = listStart; i < listStart+afpn; i ++) {
//System.out.println("i:"+i+" " + list.length + " " + afpn);
int a = afpPositions[i];
//System.out.println(String.format("afp %d %d\n", i, a));
for(int j = 0; j < afpSet.get(a).getFragLen(); j ++) {
if(n >= minLen) {
throw new RuntimeException("Error: too many residues in AFPChainer.afp2Res!");
}
res1[n] = afpSet.get(a).getP1() + j;
res2[n] = afpSet.get(a).getP2() + j;
n ++;
}
}
afpChain.setFocusRes1(res1);
afpChain.setFocusRes2(res2);
afpChain.setFocusResn(n);
if ( n == 0 ){
System.err.println("warning: n=0!!! + " + afpn + " " + listStart + " " + afpPositions.length);
}
return n;
}
}
| false | false | null | null |
diff --git a/src/org/rascalmpl/semantics/dynamic/Assignable.java b/src/org/rascalmpl/semantics/dynamic/Assignable.java
index 32ea153b1b..051a9feec6 100644
--- a/src/org/rascalmpl/semantics/dynamic/Assignable.java
+++ b/src/org/rascalmpl/semantics/dynamic/Assignable.java
@@ -1,679 +1,682 @@
package org.rascalmpl.semantics.dynamic;
import java.util.List;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IInteger;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.INode;
import org.eclipse.imp.pdb.facts.IRelation;
import org.eclipse.imp.pdb.facts.ITuple;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.ast.Expression;
import org.rascalmpl.ast.Name;
import org.rascalmpl.ast.QualifiedName;
import org.rascalmpl.interpreter.AssignableEvaluator;
import org.rascalmpl.interpreter.Evaluator;
import org.rascalmpl.interpreter.AssignableEvaluator.AssignmentOperator;
import org.rascalmpl.interpreter.asserts.Ambiguous;
import org.rascalmpl.interpreter.asserts.ImplementationError;
import org.rascalmpl.interpreter.control_exceptions.Throw;
import org.rascalmpl.interpreter.result.Result;
import org.rascalmpl.interpreter.staticErrors.AssignmentToFinalError;
import org.rascalmpl.interpreter.staticErrors.UndeclaredAnnotationError;
import org.rascalmpl.interpreter.staticErrors.UndeclaredFieldError;
import org.rascalmpl.interpreter.staticErrors.UndeclaredVariableError;
import org.rascalmpl.interpreter.staticErrors.UnexpectedTypeError;
import org.rascalmpl.interpreter.staticErrors.UninitializedVariableError;
import org.rascalmpl.interpreter.staticErrors.UnsupportedOperationError;
import org.rascalmpl.interpreter.staticErrors.UnsupportedSubscriptError;
import org.rascalmpl.interpreter.types.NonTerminalType;
public abstract class Assignable extends org.rascalmpl.ast.Assignable {
static public class Annotation extends
org.rascalmpl.ast.Assignable.Annotation {
public Annotation(INode __param1,
org.rascalmpl.ast.Assignable __param2, Name __param3) {
super(__param1, __param2, __param3);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
String label = org.rascalmpl.interpreter.utils.Names.name(this
.getAnnotation());
Result<IValue> result = this.getReceiver().interpret(
(Evaluator) __eval.__getEval());
if (result == null || result.getValue() == null) {
throw new UninitializedVariableError(this.getReceiver()
.toString(), this.getReceiver());
}
if (!__eval.__getEnv().declaresAnnotation(result.getType(), label)) {
throw new UndeclaredAnnotationError(label, result.getType(),
this);
}
try {
__eval.__setValue(__eval.newResult(result.getAnnotation(label,
__eval.__getEnv()), __eval.__getValue()));
} catch (Throw e) {
// NoSuchAnnotation
}
return __eval.recur(this, result.setAnnotation(label, __eval
.__getValue(), __eval.__getEnv()));
// result.setValue(((IConstructor)
// result.getValue()).setAnnotation(label, value.getValue()));
// return recur(this, result);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
Result<IValue> receiver = this.getReceiver().interpret(__eval);
String label = this.getAnnotation().toString();
if (!__eval.getCurrentEnvt().declaresAnnotation(receiver.getType(),
label)) {
throw new UndeclaredAnnotationError(label, receiver.getType(),
this);
}
Type type = __eval.getCurrentEnvt().getAnnotationType(
receiver.getType(), label);
IValue value = ((IConstructor) receiver.getValue())
.getAnnotation(label);
return org.rascalmpl.interpreter.result.ResultFactory.makeResult(
type, value, __eval);
}
}
static public class Bracket extends org.rascalmpl.ast.Assignable.Bracket {
public Bracket(INode __param1, org.rascalmpl.ast.Assignable __param2) {
super(__param1, __param2);
}
}
static public class Constructor extends
org.rascalmpl.ast.Assignable.Constructor {
public Constructor(INode __param1, Name __param2,
List<org.rascalmpl.ast.Assignable> __param3) {
super(__param1, __param2, __param3);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
Type valueType = __eval.__getValue().getType();
if (!valueType.isNodeType() && !valueType.isAbstractDataType()
&& !valueType.isConstructorType()) {
throw new UnexpectedTypeError(
org.rascalmpl.interpreter.AssignableEvaluator.__getTf()
.nodeType(), __eval.__getValue().getType(),
this);
}
INode node = (INode) __eval.__getValue().getValue();
Type nodeType = node.getType();
if (nodeType.isAbstractDataType()) {
nodeType = ((IConstructor) __eval.__getValue().getValue())
.getConstructorType();
}
if (!node.getName().equals(
org.rascalmpl.interpreter.utils.Names.name(this.getName()))) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.nameMismatch(node.getName(),
org.rascalmpl.interpreter.utils.Names.name(this
.getName()), this.getName(), __eval
.__getEval().getStackTrace());
}
List<org.rascalmpl.ast.Assignable> arguments = this.getArguments();
if (node.arity() != arguments.size()) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.arityMismatch(node.arity(), arguments.size(), this,
__eval.__getEval().getStackTrace());
}
IValue[] results = new IValue[arguments.size()];
Type[] resultTypes = new Type[arguments.size()];
for (int i = 0; i < arguments.size(); i++) {
Type argType = !nodeType.isConstructorType() ? org.rascalmpl.interpreter.AssignableEvaluator
.__getTf().valueType()
: nodeType.getFieldType(i);
IValue arg = node.get(i);
Result<IValue> result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(argType, arg, __eval.__getEval());
AssignableEvaluator ae = new AssignableEvaluator(__eval
.__getEnv(), null, result, __eval.__getEval());
Result<IValue> argResult = arguments.get(i).assignment(ae);
results[i] = argResult.getValue();
resultTypes[i] = argType;
}
if (!nodeType.isAbstractDataType() && !nodeType.isConstructorType()) {
return org.rascalmpl.interpreter.result.ResultFactory
.makeResult(nodeType, nodeType.make(__eval.__getEval()
.getValueFactory(), node.getName(), results),
__eval.__getEval());
}
Type constructor = __eval.__getEval().getCurrentEnvt()
.getConstructor(
node.getName(),
org.rascalmpl.interpreter.AssignableEvaluator
.__getTf().tupleType(resultTypes));
if (constructor == null) {
throw new ImplementationError("could not find constructor for "
+ node.getName()
+ " : "
+ org.rascalmpl.interpreter.AssignableEvaluator
.__getTf().tupleType(resultTypes));
}
return org.rascalmpl.interpreter.result.ResultFactory.makeResult(
constructor.getAbstractDataType(), constructor.make(__eval
.__getEval().getValueFactory(), results), __eval
.__getEval());
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
throw new ImplementationError(
"Constructor assignable does not represent a value");
}
}
static public class FieldAccess extends
org.rascalmpl.ast.Assignable.FieldAccess {
public FieldAccess(INode __param1,
org.rascalmpl.ast.Assignable __param2, Name __param3) {
super(__param1, __param2, __param3);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
Result<IValue> receiver = this.getReceiver().interpret(
(Evaluator) __eval.__getEval());
String label = org.rascalmpl.interpreter.utils.Names.name(this
.getField());
if (receiver == null || receiver.getValue() == null) {
throw new UninitializedVariableError(this.getReceiver()
.toString(), this.getReceiver());
}
if (receiver.getType().isTupleType()) {
int idx = receiver.getType().getFieldIndex(label);
if (idx < 0) {
throw new UndeclaredFieldError(label, receiver.getType(),
this);
}
__eval.__setValue(__eval.newResult(((ITuple) receiver
.getValue()).get(idx), __eval.__getValue()));
IValue result = ((ITuple) receiver.getValue()).set(idx, __eval
.__getValue().getValue());
return __eval.recur(this,
org.rascalmpl.interpreter.result.ResultFactory
.makeResult(receiver.getType(), result, __eval
.__getEval()));
}
else if (receiver.getType() instanceof NonTerminalType) {
Result<IValue> result = receiver.fieldUpdate(label, __eval.__getValue(), __eval.getCurrentEnvt().getStore());
+ __eval.__setValue(__eval.newResult(receiver.fieldAccess(label, __eval.getCurrentEnvt().getStore()), __eval
+ .__getValue()));
+
if (!result.getType().isSubtypeOf(receiver.getType())) {
throw new UnexpectedTypeError(receiver.getType(), result.getType(), __eval.getCurrentAST());
}
return __eval.recur(this, result);
}
else if (receiver.getType().isConstructorType()
|| receiver.getType().isAbstractDataType()) {
IConstructor cons = (IConstructor) receiver.getValue();
Type node = cons.getConstructorType();
/*
* TODO: remove? if (!receiver.getType().hasField(label)) {
* throw new NoSuchFieldError(receiver.getType() +
* " does not have a field named `" + label + "`", this); }
*/
if (!node.hasField(label)) {
throw new UndeclaredFieldError(label, receiver.getValue()
.getType(), this);
}
int index = node.getFieldIndex(label);
if (!__eval.__getValue().getType().isSubtypeOf(
node.getFieldType(index))) {
throw new UnexpectedTypeError(node.getFieldType(index),
__eval.__getValue().getType(), this);
}
__eval.__setValue(__eval.newResult(cons.get(index), __eval
.__getValue()));
IValue result = cons.set(index, __eval.__getValue().getValue());
return __eval.recur(this,
org.rascalmpl.interpreter.result.ResultFactory
.makeResult(receiver.getType(), result, __eval
.__getEval()));
} else if (receiver.getType().isSourceLocationType()) {
// ISourceLocation loc = (ISourceLocation) receiver.getValue();
__eval.__setValue(__eval.newResult(receiver.fieldAccess(label,
__eval.__getEnv().getStore()), __eval.__getValue()));
return __eval.recur(this, receiver.fieldUpdate(label, __eval
.__getValue(), __eval.__getEnv().getStore()));
// return recur(this, eval.sourceLocationFieldUpdate(loc, label,
// value.getValue(), value.getType(), this));
} else {
throw new UndeclaredFieldError(label, receiver.getType(), this);
}
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
Result<IValue> receiver = this.getReceiver().interpret(__eval);
String label = org.rascalmpl.interpreter.utils.Names.name(this
.getField());
if (receiver == null) {
throw new UndeclaredVariableError(
this.getReceiver().toString(), this.getReceiver());
}
Type receiverType = receiver.getType();
if (receiverType.isTupleType()) {
// the run-time tuple may not have labels, the static type can
// have labels,
// so we use the static type here.
int index = receiverType.getFieldIndex(label);
IValue result = ((ITuple) receiver.getValue()).get(index);
Type type = receiverType.getFieldType(index);
return org.rascalmpl.interpreter.result.ResultFactory
.makeResult(type, result, __eval);
} else if (receiverType.isConstructorType()
|| receiverType.isAbstractDataType()) {
IConstructor cons = (IConstructor) receiver.getValue();
Type node = cons.getConstructorType();
if (!receiverType.hasField(label, __eval.getCurrentEnvt()
.getStore())) {
throw new UndeclaredFieldError(label, receiverType, this);
}
if (!node.hasField(label)) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.noSuchField(label, this, __eval.getStackTrace());
}
int index = node.getFieldIndex(label);
return org.rascalmpl.interpreter.result.ResultFactory
.makeResult(node.getFieldType(index), cons.get(index),
__eval);
} else if (receiverType.isSourceLocationType()) {
return receiver.fieldAccess(label, new TypeStore());
} else {
throw new UndeclaredFieldError(label, receiverType, this);
}
}
}
static public class IfDefinedOrDefault extends
org.rascalmpl.ast.Assignable.IfDefinedOrDefault {
public IfDefinedOrDefault(INode __param1,
org.rascalmpl.ast.Assignable __param2, Expression __param3) {
super(__param1, __param2, __param3);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
try {
this.getReceiver().interpret((Evaluator) __eval.__getEval()); // notice
// we
// use
// 'eval'
// here
// not
// '__eval'
// if it was not defined, __eval would have thrown an exception,
// so now we can just go on
return this.getReceiver().assignment(__eval);
} catch (Throw e) {
__eval.__setValue(__eval.newResult(this.getDefaultExpression()
.interpret((Evaluator) __eval.__getEval()), __eval
.__getValue()));
__eval.__setOperator(AssignmentOperator.Default);
return this.getReceiver().assignment(__eval);
}
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
throw new ImplementationError(
"ifdefined assignable does not represent a value");
}
}
static public class Subscript extends
org.rascalmpl.ast.Assignable.Subscript {
public Subscript(INode __param1, org.rascalmpl.ast.Assignable __param2,
Expression __param3) {
super(__param1, __param2, __param3);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
Result<IValue> rec = this.getReceiver().interpret(
(Evaluator) __eval.__getEval());
Result<IValue> subscript = this.getSubscript().interpret(
(Evaluator) __eval.__getEval());
Result<IValue> result;
if (rec == null || rec.getValue() == null) {
throw new UninitializedVariableError(this.getReceiver()
.toString(), this.getReceiver());
}
if (rec.getType().isListType()
&& subscript.getType().isIntegerType()) {
try {
IList list = (IList) rec.getValue();
int index = ((IInteger) subscript.getValue()).intValue();
__eval.__setValue(__eval.newResult(list.get(index), __eval
.__getValue()));
list = list.put(index, __eval.__getValue().getValue());
result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(rec.hasInferredType() ? rec.getType()
.lub(list.getType()) : rec.getType(), list,
__eval.__getEval());
} catch (IndexOutOfBoundsException e) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.indexOutOfBounds((IInteger) subscript.getValue(),
__eval.__getEval().getCurrentAST(), __eval
.__getEval().getStackTrace());
}
} else if (rec.getType().isMapType()) {
Type keyType = rec.getType().getKeyType();
if (rec.hasInferredType()
|| subscript.getType().isSubtypeOf(keyType)) {
IValue oldValue = ((IMap) rec.getValue()).get(subscript
.getValue());
__eval.__setValue(__eval.newResult(oldValue, __eval
.__getValue()));
IMap map = ((IMap) rec.getValue()).put(
subscript.getValue(), __eval.__getValue()
.getValue());
result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(rec.hasInferredType() ? rec.getType()
.lub(map.getType()) : rec.getType(), map,
__eval.__getEval());
} else {
throw new UnexpectedTypeError(keyType, subscript.getType(),
this.getSubscript());
}
} else if (rec.getType().isNodeType()
&& subscript.getType().isIntegerType()) {
int index = ((IInteger) subscript.getValue()).intValue();
INode node = (INode) rec.getValue();
if (index >= node.arity()) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.indexOutOfBounds((IInteger) subscript.getValue(),
__eval.__getEval().getCurrentAST(), __eval
.__getEval().getStackTrace());
}
__eval.__setValue(__eval.newResult(node.get(index), __eval
.__getValue()));
node = node.set(index, __eval.__getValue().getValue());
result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(rec.getType(), node, __eval.__getEval());
} else if (rec.getType().isTupleType()
&& subscript.getType().isIntegerType()) {
int index = ((IInteger) subscript.getValue()).intValue();
ITuple tuple = (ITuple) rec.getValue();
if (index >= tuple.arity()) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.indexOutOfBounds((IInteger) subscript.getValue(),
__eval.__getEval().getCurrentAST(), __eval
.__getEval().getStackTrace());
}
__eval.__setValue(__eval.newResult(tuple.get(index), __eval
.__getValue()));
tuple = tuple.set(index, __eval.__getValue().getValue());
result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(rec.getType(), tuple, __eval.__getEval());
} else if (rec.getType().isRelationType()
&& subscript.getType().isSubtypeOf(
rec.getType().getFieldType(0))) {
IRelation rel = (IRelation) rec.getValue();
IValue sub = subscript.getValue();
if (rec.getType().getArity() != 2) {
throw new UnsupportedSubscriptError(rec.getType(),
subscript.getType(), this);
}
if (!__eval.__getValue().getType().isSubtypeOf(
rec.getType().getFieldType(1))) {
throw new UnexpectedTypeError(
rec.getType().getFieldType(1), __eval.__getValue()
.getType(), __eval.__getEval()
.getCurrentAST());
}
rel = rel.insert(__eval.__getEval().getValueFactory().tuple(
sub, __eval.__getValue().getValue()));
result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(rec.getType(), rel, __eval.__getEval());
} else {
throw new UnsupportedSubscriptError(rec.getType(), subscript
.getType(), this);
// TODO implement other subscripts
}
return __eval.recur(this, result);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
Result<IValue> receiver = this.getReceiver().interpret(__eval);
Result<IValue> subscript = this.getSubscript().interpret(__eval);
if (receiver.getType().isListType()) {
if (subscript.getType().isIntegerType()) {
IList list = (IList) receiver.getValue();
IValue result = list.get(((IInteger) subscript.getValue())
.intValue());
Type type = receiver.getType().getElementType();
return __eval.normalizedResult(type, result);
}
throw new UnexpectedTypeError(
org.rascalmpl.interpreter.Evaluator.__getTf()
.integerType(), subscript.getType(), this);
} else if (receiver.getType().isMapType()) {
Type keyType = receiver.getType().getKeyType();
if (receiver.hasInferredType()
|| subscript.getType().isSubtypeOf(keyType)) {
IValue result = ((IMap) receiver.getValue()).get(subscript
.getValue());
if (result == null) {
throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory
.noSuchKey(subscript.getValue(), this, __eval
.getStackTrace());
}
Type type = receiver.getType().getValueType();
return org.rascalmpl.interpreter.result.ResultFactory
.makeResult(type, result, __eval);
}
throw new UnexpectedTypeError(keyType, subscript.getType(),
this.getSubscript());
}
// TODO implement other subscripts
throw new UnsupportedOperationError("subscript",
receiver.getType(), this);
}
}
static public class Tuple extends org.rascalmpl.ast.Assignable.Tuple {
public Tuple(INode __param1, List<org.rascalmpl.ast.Assignable> __param2) {
super(__param1, __param2);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
List<org.rascalmpl.ast.Assignable> arguments = this.getElements();
if (!__eval.__getValue().getType().isTupleType()) {
// TODO construct a better expected type
throw new UnexpectedTypeError(
org.rascalmpl.interpreter.AssignableEvaluator.__getTf()
.tupleEmpty(), __eval.__getValue().getType(),
this);
}
Type tupleType = __eval.__getValue().getType();
ITuple tuple = (ITuple) __eval.__getValue().getValue();
IValue[] results = new IValue[arguments.size()];
Type[] resultTypes = new Type[arguments.size()];
for (int i = 0; i < arguments.size(); i++) {
Type argType = tupleType.getFieldType(i);
IValue arg = tuple.get(i);
Result<IValue> result = org.rascalmpl.interpreter.result.ResultFactory
.makeResult(argType, arg, __eval.__getEval());
AssignableEvaluator ae = new AssignableEvaluator(__eval
.__getEnv(), null, result, __eval.__getEval());
Result<IValue> argResult = arguments.get(i).assignment(ae);
results[i] = argResult.getValue();
resultTypes[i] = argResult.getType();
}
return org.rascalmpl.interpreter.result.ResultFactory.makeResult(
org.rascalmpl.interpreter.AssignableEvaluator.__getTf()
.tupleType(resultTypes), tupleType.make(__eval
.__getEval().getValueFactory(), results), __eval
.__getEval());
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
throw new ImplementationError(
"Tuple in assignable does not represent a value:" + this);
}
}
static public class Variable extends org.rascalmpl.ast.Assignable.Variable {
public Variable(INode __param1, QualifiedName __param2) {
super(__param1, __param2);
}
@Override
public Result<IValue> assignment(AssignableEvaluator __eval) {
QualifiedName qname = this.getQualifiedName();
Result<IValue> previous = __eval.__getEnv().getVariable(qname);
if (__eval.__getEnv().isNameFinal(qname)) {
throw new AssignmentToFinalError(this.getQualifiedName());
}
// System.out.println("I am assigning: " + this + "(oldvalue = " +
// previous + ")");
if (previous != null && previous.getValue() != null) {
__eval.__setValue(__eval.newResult(previous, __eval
.__getValue()));
__eval.__getEnv().storeVariable(qname, __eval.__getValue());
return __eval.__getValue();
}
switch (__eval.__getOperator()) {
case Default:
case IsDefined:
// System.out.println("And it's local: " + this);
// env.storeLocalVariable(qname, value); ?? OOPS
// env.declareVariable(value.getType(), qname.toString());
__eval.__getEnv().storeVariable(qname, __eval.__getValue());
return __eval.__getValue();
default:
throw new UninitializedVariableError(this.toString(), this);
}
// TODO implement semantics of global keyword, when not given the
// variable should be inserted in the local scope.
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
return __eval.getCurrentEnvt().getVariable(this.getQualifiedName());
}
}
public Assignable(INode __param1) {
super(__param1);
}
}
| true | false | null | null |
diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/SendToFusionTables.java b/MyTracks/src/com/google/android/apps/mytracks/io/SendToFusionTables.java
index 949d9581..4928fe84 100644
--- a/MyTracks/src/com/google/android/apps/mytracks/io/SendToFusionTables.java
+++ b/MyTracks/src/com/google/android/apps/mytracks/io/SendToFusionTables.java
@@ -1,696 +1,696 @@
/*
* 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.android.apps.mytracks.io;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.ProgressIndicator;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.io.gdata.GDataWrapper;
import com.google.android.apps.mytracks.io.gdata.GDataWrapper.QueryFunction;
import com.google.android.apps.mytracks.stats.DoubleBuffer;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.MyTracksUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.MethodOverrideIntercepter;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.javanet.NetHttpTransport;
import com.google.api.client.util.Strings;
import android.app.Activity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* A helper class used to transmit tracks to Google Fusion Tables.
* A new instance should be used for each upload.
*
* @author Leif Hendrik Wilden
*/
public class SendToFusionTables implements Runnable {
/**
* Listener invoked when sending to fusion tables completes.
*/
public interface OnSendCompletedListener {
void onSendCompleted(String tableId, boolean success, int statusMessage);
}
/** The GData service id for Fusion Tables. */
public static final String SERVICE_ID = "fusiontables";
/** The path for viewing a map visualization of a table. */
private static final String FUSIONTABLES_MAP =
"http://www.google.com/fusiontables/embedviz?" +
"viz=MAP&q=select+col0,+col1,+col2,+col3+from+%s+&h=false&" +
"lat=%f&lng=%f&z=%d&t=1&l=col2";
/** Standard base feed url for Fusion Tables. */
private static final String FUSIONTABLES_BASE_FEED_URL =
"http://www.google.com/fusiontables/api/query";
private static final int MAX_POINTS_PER_UPLOAD = 2048;
private static final String GDATA_VERSION = "2";
// This class reports upload status to the user as a completion percentage
// using a progress bar. Progress is defined as follows:
//
// 0% Getting track metadata
// 5% Creating Fusion Table (GData to FT server)
// 10%-90% Uploading the track data to Fusion Tables
// 95% Uploading waypoints
// 100% Done
private static final int PROGRESS_INITIALIZATION = 0;
private static final int PROGRESS_FUSION_TABLE_CREATE = 5;
private static final int PROGRESS_UPLOAD_DATA_MIN = 10;
private static final int PROGRESS_UPLOAD_DATA_MAX = 90;
private static final int PROGRESS_UPLOAD_WAYPOINTS = 95;
private static final int PROGRESS_COMPLETE = 100;
private final Activity context;
private final AuthManager auth;
private final long trackId;
private final ProgressIndicator progressIndicator;
private final OnSendCompletedListener onCompletion;
private final StringUtils stringUtils;
private final MyTracksProviderUtils providerUtils;
// Progress status
private int totalLocationsRead;
private int totalLocationsPrepared;
private int totalLocationsUploaded;
private int totalLocations;
private int totalSegmentsUploaded;
private HttpTransport transport;
private String tableId;
private static String MARKER_TYPE_START = "large_green";
private static String MARKER_TYPE_END = "large_red";
private static String MARKER_TYPE_WAYPOINT = "large_yellow";
static {
// We manually assign the transport to avoid having HttpTransport try to
// load it via reflection (which breaks due to ProGuard).
HttpTransport.setLowLevelHttpTransport(new NetHttpTransport());
}
public SendToFusionTables(Activity context, AuthManager auth,
long trackId, ProgressIndicator progressIndicator,
OnSendCompletedListener onCompletion) {
this.context = context;
this.auth = auth;
this.trackId = trackId;
this.progressIndicator = progressIndicator;
this.onCompletion = onCompletion;
this.stringUtils = new StringUtils(context);
this.providerUtils = MyTracksProviderUtils.Factory.get(context);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-MyTracks-" + MyTracksUtils.getMyTracksVersion(context));
headers.gdataVersion = GDATA_VERSION;
transport = new HttpTransport();
MethodOverrideIntercepter.setAsFirstFor(transport);
transport.defaultHeaders = headers;
}
@Override
public void run() {
Log.d(MyTracksConstants.TAG, "Sending to Fusion tables: trackId = " + trackId);
doUpload();
}
public static String getMapVisualizationUrl(Track track) {
// TODO(leifhendrik): Determine correct bounding box and zoom level that will show the entire track.
TripStatistics stats = track.getStatistics();
double latE6 = stats.getBottom() + (stats.getTop() - stats.getBottom()) / 2;
double lonE6 = stats.getLeft() + (stats.getRight() - stats.getLeft()) / 2;
int z = 15;
return String.format(FUSIONTABLES_MAP, track.getTableId(), latE6 / 1.E6, lonE6 / 1.E6, z);
}
private void doUpload() {
((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(auth.getAuthToken());
int statusMessageId = R.string.error_sending_to_fusiontables;
boolean success = true;
try {
progressIndicator.setProgressValue(PROGRESS_INITIALIZATION);
progressIndicator.setProgressMessage(R.string.progress_message_reading_track);
// Get the track meta-data
Track track = providerUtils.getTrack(trackId);
String originalDescription = track.getDescription();
// Create a new table:
progressIndicator.setProgressValue(PROGRESS_FUSION_TABLE_CREATE);
progressIndicator.setProgressMessage(R.string.progress_message_creating_fusiontable);
if (!createNewTable(track) || !makeTableUnlisted(tableId)) {
return;
}
progressIndicator.setProgressValue(PROGRESS_UPLOAD_DATA_MIN);
progressIndicator.setProgressMessage(R.string.progress_message_sending_fusiontables);
// Upload all of the segments of the track plus start/end markers
if (!uploadAllTrackPoints(track, originalDescription)) {
return;
}
progressIndicator.setProgressValue(PROGRESS_UPLOAD_WAYPOINTS);
// Upload all the waypoints.
if (!uploadWaypoints(track)) {
return;
}
statusMessageId = R.string.status_new_fusiontable_has_been_created;
Log.d(MyTracksConstants.TAG, "SendToFusionTables: Done: " + success);
progressIndicator.setProgressValue(PROGRESS_COMPLETE);
} finally {
final boolean finalSuccess = success;
final int finalStatusMessageId = statusMessageId;
context.runOnUiThread(new Runnable() {
public void run() {
if (onCompletion != null) {
onCompletion.onSendCompleted(
tableId, finalSuccess, finalStatusMessageId);
}
}
});
}
}
/**
* Creates a new table.
* If successful sets {@link #tableId}.
*
* @return true in case of success.
*/
private boolean createNewTable(Track track) {
Log.d(MyTracksConstants.TAG, "Creating a new fusion table.");
String query = "CREATE TABLE '" + sqlEscape(track.getName()) +
"' (name:STRING,description:STRING,geometry:LOCATION,marker:STRING)";
return runUpdate(query);
}
private boolean makeTableUnlisted(String tableId) {
Log.d(MyTracksConstants.TAG, "Setting visibility to unlisted.");
String query = "UPDATE TABLE " + tableId + " SET VISIBILITY = UNLISTED";
return runUpdate(query);
}
/**
* Formats given values SQL style. Escapes single quotes with a backslash.
*
* @param values the values to format
* @return the values formatted as: ('value1','value2',...,'value_n').
*/
private static String values(String... values) {
StringBuilder builder = new StringBuilder("(");
for (int i = 0; i < values.length; i++) {
if (i > 0) {
builder.append(',');
}
builder.append('\'');
builder.append(sqlEscape(values[i]));
builder.append('\'');
}
builder.append(')');
return builder.toString();
}
private static String sqlEscape(String value) {
return value.replaceAll("'", "''");
}
/**
* Creates a new row representing a marker.
*
* @param name the marker name
* @param description the marker description
* @param the marker location
* @return true in case of success.
*/
private boolean createNewPoint(String name, String description, Location location,
String marker) {
Log.d(MyTracksConstants.TAG, "Creating a new row with a point.");
String query = "INSERT INTO " + tableId + " (name,description,geometry,marker) VALUES "
+ values(name, description, getKmlPoint(location), marker);
return runUpdate(query);
}
/**
* Creates a new row representing a line segment.
*
* @param track the track/segment to draw
* @return true in case of success.
*/
private boolean createNewLineString(Track track) {
Log.d(MyTracksConstants.TAG, "Creating a new row with a point.");
String query = "INSERT INTO " + tableId
+ " (name,description,geometry) VALUES "
+ values(track.getName(), track.getDescription(), getKmlLineString(track));
return runUpdate(query);
}
private boolean uploadAllTrackPoints(final Track track, String originalDescription) {
SharedPreferences preferences = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
boolean metricUnits = true;
if (preferences != null) {
metricUnits = preferences.getBoolean(context.getString(R.string.metric_units_key), true);
}
Cursor locationsCursor = providerUtils.getLocationsCursor(track.getId(), 0, -1, false);
try {
if (!locationsCursor.moveToFirst()) {
Log.w(MyTracksConstants.TAG, "Unable to get any points to upload");
return false;
}
totalLocationsRead = 0;
totalLocationsPrepared = 0;
totalLocationsUploaded = 0;
totalLocations = locationsCursor.getCount();
totalSegmentsUploaded = 0;
// Limit the number of elevation readings. Ideally we would want around 250.
int elevationSamplingFrequency =
Math.max(1, (int) (totalLocations / 250.0));
Log.d(MyTracksConstants.TAG,
"Using elevation sampling factor: " + elevationSamplingFrequency
+ " on " + totalLocations);
double totalDistance = 0;
Vector<Double> distances = new Vector<Double>();
Vector<Double> elevations = new Vector<Double>();
DoubleBuffer elevationBuffer = new DoubleBuffer(MyTracksConstants.ELEVATION_SMOOTHING_FACTOR);
List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD);
Location lastLocation = null;
do {
if (totalLocationsRead % 100 == 0) {
updateTrackDataUploadProgress();
}
Location loc = providerUtils.createLocation(locationsCursor);
locations.add(loc);
if (totalLocationsRead == 0) {
// Put a marker at the first point of the first valid segment:
String name = track.getName() + " " + context.getString(R.string.start);
createNewPoint(name, "", loc, MARKER_TYPE_START);
}
// Add to the elevation profile.
if (loc != null && MyTracksUtils.isValidLocation(loc)) {
// All points go into the smoothing buffer...
elevationBuffer.setNext(metricUnits ? loc.getAltitude()
: loc.getAltitude() * UnitConversions.M_TO_FT);
if (lastLocation != null) {
double dist = lastLocation.distanceTo(loc);
totalDistance += dist;
}
// ...but only a few points are really used to keep the url short.
if (totalLocationsRead % elevationSamplingFrequency == 0) {
distances.add(totalDistance);
elevations.add(elevationBuffer.getAverage());
}
}
// If the location was not valid, it's a segment split, so make sure the
// distance between the previous segment and the new one is not accounted
// for in the next iteration.
lastLocation = loc;
// Every now and then, upload the accumulated points
if (totalLocationsRead % MAX_POINTS_PER_UPLOAD == MAX_POINTS_PER_UPLOAD - 1) {
if (!prepareAndUploadPoints(track, locations)) {
return false;
}
}
totalLocationsRead++;
} while (locationsCursor.moveToNext());
// Do a final upload with what's left
if (!prepareAndUploadPoints(track, locations)) {
return false;
}
// Put an end marker at the last point of the last valid segment:
if (lastLocation != null) {
track.setDescription("<p>" + originalDescription + "</p><p>"
+ stringUtils.generateTrackDescription(track, distances, elevations)
+ "</p>");
String name = track.getName() + " " + context.getString(R.string.end);
return createNewPoint(name, track.getDescription(), lastLocation, MARKER_TYPE_END);
}
return true;
} finally {
locationsCursor.close();
}
}
/**
* Appends the given location to the string in the format:
* longitude,latitude[,altitude]
*
* @param location the location to be added
* @param builder the string builder to use
*/
private void appendCoordinate(Location location, StringBuilder builder) {
builder
.append(location.getLongitude())
.append(",")
.append(location.getLatitude());
if (location.hasAltitude()) {
builder.append(",");
builder.append(location.getAltitude());
}
}
/**
* Gets a KML Point tag for the given location.
*
* @param location The location.
* @return the kml.
*/
private String getKmlPoint(Location location) {
StringBuilder builder = new StringBuilder("<Point><coordinates>");
appendCoordinate(location, builder);
builder.append("</coordinates></Point>");
return builder.toString();
}
/**
* Returns a KML Point tag for the given location.
*
* @param location The location.
* @return the kml.
*/
private String getKmlLineString(Track track) {
StringBuilder builder = new StringBuilder("<LineString><coordinates>");
for (Location location : track.getLocations()) {
appendCoordinate(location, builder);
builder.append(' ');
}
builder.append("</coordinates></LineString>");
return builder.toString();
}
private boolean prepareAndUploadPoints(Track track, List<Location> locations) {
updateTrackDataUploadProgress();
int numLocations = locations.size();
if (numLocations < 2) {
Log.d(MyTracksConstants.TAG, "Not preparing/uploading too few points");
totalLocationsUploaded += numLocations;
return true;
}
// Prepare/pre-process the points
ArrayList<Track> splitTracks = prepareLocations(track, locations);
// Start uploading them
for (Track splitTrack : splitTracks) {
if (totalSegmentsUploaded > 1) {
splitTrack.setName(splitTrack.getName() + " "
+ String.format(
context.getString(R.string.part), totalSegmentsUploaded));
}
totalSegmentsUploaded++;
Log.d(MyTracksConstants.TAG,
"SendToFusionTables: Prepared feature for upload w/ "
+ splitTrack.getLocations().size() + " points.");
// Transmit tracks via GData feed:
// -------------------------------
Log.d(MyTracksConstants.TAG,
"SendToFusionTables: Uploading to table " + tableId + " w/ auth " + auth);
if (!uploadTrackPoints(splitTrack)) {
Log.e(MyTracksConstants.TAG, "Uploading failed");
return false;
}
}
locations.clear();
totalLocationsUploaded += numLocations;
updateTrackDataUploadProgress();
return true;
}
/**
* Prepares a buffer of locations for transmission to google fusion tables.
*
* @param track the original track with meta data
* @param buffer a buffer of locations on the track
* @return an array of tracks each with a sub section of the points in the
* original buffer
*/
private ArrayList<Track> prepareLocations(
Track track, Iterable<Location> locations) {
ArrayList<Track> splitTracks = new ArrayList<Track>();
// Create segments from each full track:
Track segment = new Track();
TripStatistics segmentStats = segment.getStatistics();
TripStatistics trackStats = track.getStatistics();
segment.setId(track.getId());
segment.setName(track.getName());
segment.setDescription(/* track.getDescription() */ "");
segment.setCategory(track.getCategory());
segmentStats.setStartTime(trackStats.getStartTime());
segmentStats.setStopTime(trackStats.getStopTime());
boolean startNewTrackSegment = false;
for (Location loc : locations) {
if (totalLocationsPrepared % 100 == 0) {
updateTrackDataUploadProgress();
}
if (loc.getLatitude() > 90) {
startNewTrackSegment = true;
}
if (startNewTrackSegment) {
// Close up the last segment.
prepareTrackSegment(segment, splitTracks);
Log.d(MyTracksConstants.TAG,
"MyTracksSendToFusionTables: Starting new track segment...");
startNewTrackSegment = false;
segment = new Track();
segment.setId(track.getId());
segment.setName(track.getName());
segment.setDescription(/* track.getDescription() */ "");
segment.setCategory(track.getCategory());
}
if (loc.getLatitude() <= 90) {
segment.addLocation(loc);
if (segmentStats.getStartTime() < 0) {
segmentStats.setStartTime(loc.getTime());
}
}
totalLocationsPrepared++;
}
prepareTrackSegment(segment, splitTracks);
return splitTracks;
}
/**
* Prepares a track segment for sending to google fusion tables.
* The main steps are:
* - correcting end time
* - decimating locations
* - splitting into smaller tracks.
*
* The final track pieces will be put in the array list splitTracks.
*
* @param segment the original segment of the track
* @param splitTracks an array of smaller track segments
*/
private void prepareTrackSegment(
Track segment, ArrayList<Track> splitTracks) {
TripStatistics segmentStats = segment.getStatistics();
if (segmentStats.getStopTime() < 0
&& segment.getLocations().size() > 0) {
segmentStats.setStopTime(segment.getLocations().size() - 1);
}
/*
* Decimate to 2 meter precision. Fusion tables doesn't like too many
* points:
*/
MyTracksUtils.decimate(segment, 2.0);
/* If the track still has > 2500 points, split it in pieces: */
final int maxPoints = 2500;
if (segment.getLocations().size() > maxPoints) {
splitTracks.addAll(MyTracksUtils.split(segment, maxPoints));
} else if (segment.getLocations().size() >= 2) {
splitTracks.add(segment);
}
}
private boolean uploadTrackPoints(Track splitTrack) {
int numLocations = splitTrack.getLocations().size();
if (numLocations < 2) {
// Need at least two points for a polyline:
Log.w(MyTracksConstants.TAG, "Not uploading too few points");
return true;
}
return createNewLineString(splitTrack);
}
/**
* Uploads all of the waypoints associated with this track to a table.
*
* @param track The track to upload waypoints for.
*
* @return True on success.
*/
private boolean uploadWaypoints(final Track track) {
// TODO: Stream through the waypoints in chunks.
// I am leaving the number of waypoints very high which should not be a
// problem because we don't try to load them into objects all at the
// same time.
boolean success = true;
Cursor c = null;
try {
c = providerUtils.getWaypointsCursor(
track.getId(), 0,
MyTracksConstants.MAX_LOADED_WAYPOINTS_POINTS);
if (c != null) {
if (c.moveToFirst()) {
// This will skip the 1st waypoint (it carries the stats for the
// last segment).
while (c.moveToNext()) {
Waypoint wpt = providerUtils.createWaypoint(c);
Log.d(MyTracksConstants.TAG, "SendToFusionTables: Creating waypoint.");
success = createNewPoint(wpt.getName(), wpt.getDescription(), wpt.getLocation(),
MARKER_TYPE_WAYPOINT);
if (!success) {
break;
}
}
}
}
if (!success) {
Log.w(MyTracksConstants.TAG, "SendToFusionTables: upload waypoints failed.");
}
return success;
} finally {
if (c != null) {
c.close();
}
}
}
private void updateTrackDataUploadProgress() {
// The percent of the total that represents the completed part of this
// segment. We calculate it as an absolute percentage, and then scale it
// to fit the completion percentage range alloted to track data upload.
double totalPercentage =
(totalLocationsRead + totalLocationsPrepared + totalLocationsUploaded)
/ (totalLocations * 3);
double scaledPercentage = totalPercentage
* (PROGRESS_UPLOAD_DATA_MAX - PROGRESS_UPLOAD_DATA_MIN) + PROGRESS_UPLOAD_DATA_MIN;
progressIndicator.setProgressValue((int) scaledPercentage);
}
/**
* Runs an update query. Handles authentication.
*
* @param query The given SQL like query
* @return true in case of success
*/
private boolean runUpdate(final String query) {
GDataWrapper<HttpTransport> wrapper = new GDataWrapper<HttpTransport>();
wrapper.setAuthManager(auth);
wrapper.setRetryOnAuthFailure(true);
wrapper.setClient(transport);
Log.d(MyTracksConstants.TAG, "GData connection prepared: " + this.auth);
wrapper.runQuery(new QueryFunction<HttpTransport>() {
@Override
public void query(HttpTransport client)
throws IOException, GDataWrapper.ParseException, GDataWrapper.HttpException,
GDataWrapper.AuthenticationException {
HttpRequest request = transport.buildPostRequest();
request.headers.contentType = "application/x-www-form-urlencoded";
GenericUrl url = new GenericUrl(FUSIONTABLES_BASE_FEED_URL);
request.url = url;
InputStreamContent isc = new InputStreamContent();
String sql = "sql=" + URLEncoder.encode(query, "UTF-8");
isc.inputStream = new ByteArrayInputStream(Strings.toBytesUtf8(sql));
request.content = isc;
Log.d(MyTracksConstants.TAG, "Running update query " + url.toString() + ": " + sql);
- HttpResponse response = null;
+ HttpResponse response;
try {
response = request.execute();
} catch (HttpResponseException e) {
throw new GDataWrapper.HttpException(e.response.statusCode, e.getMessage());
}
boolean success = response.isSuccessStatusCode;
if (success) {
byte[] result = new byte[1024];
response.getContent().read(result);
String s = Strings.fromBytesUtf8(result);
String[] lines = s.split(Strings.LINE_SEPARATOR);
if (lines[0].equals("tableid")) {
tableId = lines[1];
Log.d(MyTracksConstants.TAG, "tableId = " + tableId);
} else {
Log.w(MyTracksConstants.TAG, "Unrecognized response: " + lines[0]);
}
} else {
Log.d(MyTracksConstants.TAG, "Query failed: " + response.statusMessage + " (" +
response.statusCode + ")");
throw new GDataWrapper.HttpException(response.statusCode, response.statusMessage);
}
}
});
return wrapper.getErrorType() == GDataWrapper.ERROR_NO_ERROR;
}
}
| true | false | null | null |
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListContentProvider.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListContentProvider.java
index 4a39d748e..0f63ac35e 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListContentProvider.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListContentProvider.java
@@ -1,229 +1,225 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.views;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.ui.AbstractTaskListFilter;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylyn.tasks.core.AbstractTask;
-import org.eclipse.mylyn.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.ui.IWorkingSet;
/**
* Provides custom content for the task list, e.g. guaranteed visibility of some elements, ability to suppress
* containers showing if nothing should show under them.
*
* TODO: move to viewer filter architecture?
*
* @author Mik Kersten
* @author Rob Elves
*/
public class TaskListContentProvider extends AbstractTaskListContentProvider {
public TaskListContentProvider(TaskListView taskListView) {
super(taskListView);
}
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
this.taskListView.expandToActiveTasks();
}
public void dispose() {
}
public Object[] getElements(Object parent) {
if (parent.equals(this.taskListView.getViewSite())) {
return applyFilter(TasksUiPlugin.getTaskListManager().getTaskList().getRootElements()).toArray();
}
return getChildren(parent);
}
/**
* @return first parent found
*/
public Object getParent(Object child) {
// Return first parent found, first search within queries then categories.
if (child instanceof AbstractTask) {
- AbstractTaskCategory category = TaskCategory.getParentTaskCategory((AbstractTask)child);
- if(category != null) return category;
-
Set<AbstractRepositoryQuery> queries = TasksUiPlugin.getTaskListManager()
.getTaskList()
- .getParentQueries(((AbstractTask) child));
+ .getQueriesForHandle(((AbstractTask) child).getHandleIdentifier());
if (queries.size() > 0) {
return queries.toArray()[0];
}
AbstractTaskContainer container = TasksUiPlugin.getTaskListManager().getTaskList().getContainerForHandle(
((AbstractTask) child).getHandleIdentifier());
if (container != null) {
return container;
}
}
// no parent found
return null;
}
+
public Object[] getChildren(Object parent) {
return getFilteredChildrenFor(parent).toArray();
}
/**
* NOTE: If parent is an ITask, this method checks if parent has unfiltered children (see bug 145194).
*/
public boolean hasChildren(Object parent) {
Object[] children = getChildren(parent);
return children != null && children.length > 0;
// if (parent instanceof AbstractRepositoryQuery) {
// AbstractRepositoryQuery query = (AbstractRepositoryQuery) parent;
// return !getFilteredChildrenFor(query).isEmpty();
// //return !query.isEmpty();
// } else if (parent instanceof AbstractTask) {
// return taskHasUnfilteredChildren((AbstractTask) parent);
// } else if (parent instanceof AbstractTaskContainer) {
// AbstractTaskContainer container = (AbstractTaskContainer) parent;
// return !getFilteredChildrenFor(container).isEmpty();
// //return !container.getChildren().isEmpty();
// }
// return false;
}
protected List<AbstractTaskContainer> applyFilter(Set<AbstractTaskContainer> roots) {
String filterText = (taskListView.getFilteredTree().getFilterControl()).getText();
if (containsNoFilterText(filterText)) {
List<AbstractTaskContainer> filteredRoots = new ArrayList<AbstractTaskContainer>();
for (AbstractTaskContainer element : roots) {
// NOTE: tasks can no longer appear as root elements
if (selectContainer(element)) {
filteredRoots.add(element);
}
}
return filteredRoots;
} else {
// only match working sets when filter is on
Set<IWorkingSet> workingSets = TaskListView.getActiveWorkingSets();
Set<AbstractTaskContainer> workingSetContainers = new HashSet<AbstractTaskContainer>();
if (workingSets.isEmpty()) {
return new ArrayList<AbstractTaskContainer>(roots);
} else {
for (IWorkingSet workingSet : workingSets) {
IAdaptable[] elements = workingSet.getElements();
for (IAdaptable adaptable : elements) {
if (adaptable instanceof AbstractTaskContainer && roots.contains(adaptable)) {
workingSetContainers.add((AbstractTaskContainer) adaptable);
}
}
}
return new ArrayList<AbstractTaskContainer>(workingSetContainers);
}
}
}
/**
* See bug 109693
*/
private boolean containsNoFilterText(String filterText) {
return filterText == null || filterText.length() == 0;
}
private boolean selectContainer(AbstractTaskContainer container) {
// if (container instanceof ScheduledTaskContainer) {
// ScheduledTaskContainer scheduleContainer = (ScheduledTaskContainer) container;
// if (TasksUiPlugin.getTaskActivityManager().isWeekDay(scheduleContainer)
// && (scheduleContainer.isPresent() || scheduleContainer.isFuture())) {
// return true;
// } else if (taskListView.isFocusedMode()) {
// return false;
// }
// }
if (filter(null, container)) {
return false;
}
return true;
}
private List<AbstractTaskContainer> getFilteredChildrenFor(Object parent) {
if (containsNoFilterText((this.taskListView.getFilteredTree().getFilterControl()).getText())) {
List<AbstractTaskContainer> children = new ArrayList<AbstractTaskContainer>();
if (parent instanceof AbstractTask) {
Set<AbstractTask> subTasks = ((AbstractTask) parent).getChildren();
for (AbstractTask t : subTasks) {
if (!filter(parent, t)) {
children.add(t);
}
}
return children;
} else if (parent instanceof AbstractTaskContainer) {
return getFilteredRootChildren((AbstractTaskContainer) parent);
}
} else {
List<AbstractTaskContainer> children = new ArrayList<AbstractTaskContainer>();
if (parent instanceof AbstractTaskContainer) {
children.addAll(((AbstractTaskContainer) parent).getChildren());
return children;
}
}
return Collections.emptyList();
}
/**
* @return all children who aren't already revealed as a sub task
*/
private List<AbstractTaskContainer> getFilteredRootChildren(AbstractTaskContainer parent) {
List<AbstractTaskContainer> result = new ArrayList<AbstractTaskContainer>();
if (TasksUiPlugin.getDefault().groupSubtasks(parent)) {
Set<AbstractTask> parentTasks = parent.getChildren();
Set<AbstractTaskContainer> parents = new HashSet<AbstractTaskContainer>();
Set<AbstractTask> children = new HashSet<AbstractTask>();
// get all children
for (AbstractTask element : parentTasks) {
for (AbstractTask abstractTask : element.getChildren()) {
children.add(abstractTask);
}
}
for (AbstractTask task : parentTasks) {
if (!filter(parent, task) && !children.contains(task)) {
parents.add(task);
}
}
result.addAll(parents);
} else {
for (AbstractTaskContainer element : parent.getChildren()) {
if (!filter(parent, element)) {
result.add(element);
}
}
}
return result;
}
protected boolean filter(Object parent, Object object) {
for (AbstractTaskListFilter filter : this.taskListView.getFilters()) {
if (!filter.select(parent, object)) {
return true;
}
}
return false;
}
}
| false | false | null | null |
diff --git a/sub/src/project/scangen/regex/RegexExpander.java b/sub/src/project/scangen/regex/RegexExpander.java
index 55b756a..89762c3 100644
--- a/sub/src/project/scangen/regex/RegexExpander.java
+++ b/sub/src/project/scangen/regex/RegexExpander.java
@@ -1,305 +1,309 @@
package project.scangen.regex;
import java.util.HashSet;
import java.util.Set;
/*
* Methodology for Regex Expansion into (,),*,|'s
*
* @author Chad Stewart
*/
public class RegexExpander {
private static int i = 0;
public static String expandRegex(String s) {
i = 0;
while (i < s.length()) {
int u;
int v;
if (s.charAt(i) == ' ') { // Encounter a space
if (s.charAt(i - 1) == '\\') {
i += 2;
} else {
s = s.substring(0, i) + s.substring(i + 1);
}
continue;
} else if (s.charAt(i) == '\\') { // Encounter a Escape
i += 2;
continue;
} else if (s.charAt(i) == ']') { // Encounter an OR block
u = s.lastIndexOf('[', i);
v = i + 1;
String sub = s.substring(u, v);
if (sub.charAt(1) == '^') { // Negation Or Block
sub = s.substring(u, s.indexOf("]", v + 1) + 1);
sub = negate(sub);
return sub;
}
// Split the OR block to deal with it
String[] strs = sub.split("-");
String[] ls = new String[strs.length - 1];
for (int i = 0; i < ls.length; i++) {
if (i > 0) {
ls[i] = "[" + strs[i].charAt(strs[i].length() - 1)
+ "-" + strs[i + 1].charAt(0) + "]";
} else
ls[i] = "[" + strs[i].charAt(strs[i].length() - 1)
+ "-" + strs[i + 1].charAt(0) + "]";
}
for (String m : ls) { // Add the OR blocks together
if (m.length() == 5) {
sub = sub.replace(m.substring(1, m.length() - 1), "");
} else
sub = sub.replace(m.substring(2, m.length() - 1), "");
}
sub = OrThisShit(sub); // Evaluate the first OR block
for (String m : ls) {
if (!sub.isEmpty())
sub = sub + "|" + expand(m); // Evaluate the spread OR blocks
}
sub = sub.replace("()|", "");
s = s.substring(0, u) + "(" + sub + ")" + s.substring(v);
i--;
} else if (s.charAt(i) == '+') { // Evaluate a +
if (s.charAt(i - 1) == ']') { // with hard brackets
u = s.lastIndexOf('[', i);
v = i;
i += s.substring(u, v).length() + 1;
s = s.substring(0, v) + s.substring(u, v) + "*"
+ s.substring(v + 2);
} else if (s.charAt(i - 1) == ')') { // with parens
String sub = findSub(s.substring(0, i));
s = s.substring(0, i) + sub + "*"
+ s.substring(i + 1, s.length());
i += sub.length();
} else { // Anything else
if (s.charAt(i - 1) == '\\') { // Escape the +
s = s.subSequence(0, i) + "(" + s.substring(i - 1, i)
+ s.substring(i - 1, i) + "*" + ")"
+ s.substring(i + 1);
} else {
s = s.subSequence(0, i) + "(" + s.substring(i - 1, i)
+ "*" + ")" + s.substring(i + 1);
i++;
}
}
}
i++;
}
//s = stripOuterParens(s);
return s;
}
public static String stripOuterParens(String s) {
int firstParen = s.indexOf("(");
if (firstParen < 0) {
return s;
}
int numParens = 1;
int maxParens = 1;
int idx = firstParen + 1;
for (; idx < s.length(); ++idx) {
char c = s.charAt(idx);
if (c == '(') {
++numParens;
++maxParens;
} else {
break;
}
}
idx = s.indexOf(")", idx);
for (; idx < s.length(); ++idx) {
char c = s.charAt(idx);
if (c == ')') {
--numParens;
if (numParens == 0) {
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, firstParen));
sb.append("(");
sb.append(s.substring(firstParen + maxParens, idx - maxParens + 1));
sb.append(")");
sb.append(s.substring(idx + 1));
return sb.toString();
}
} else {
return s;
}
}
return s;
}
/*
* Negation String Handler
*/
private static String negate(String sub) {
String mainSet = sub.substring(sub.lastIndexOf("["), sub.length());
String[] strs = mainSet.split("-");
String[] ls = new String[strs.length - 1];
for (int i = 0; i < ls.length; i++) {
if (i > 0) {
ls[i] = "[" + strs[i].charAt(strs[i].length() - 1) + "-"
+ strs[i + 1].charAt(0) + "]";
} else
ls[i] = "[" + strs[i].charAt(strs[i].length() - 1) + "-"
+ strs[i + 1].charAt(0) + "]";
}
for (String m : ls) {
if (m.length() == 5) {
mainSet = mainSet.replace(m.substring(1, m.length() - 1), "");
} else
mainSet = mainSet.replace(m.substring(2, m.length() - 1), "");
}
mainSet = OrThisShit(mainSet);
for (String m : ls) {
if (!mainSet.isEmpty())
mainSet = mainSet + "|" + expand(m);
}
mainSet = mainSet.replace("()|", "");
mainSet = mainSet.replace(")|(", "|");
Set<Character> chars = new HashSet<Character>();
int n = 1;
while (n < mainSet.length()) {
chars.add(mainSet.charAt(n));
n += 2;
}
String rem = sub.substring(0, sub.indexOf("]", 0) + 1);
rem = "[" + rem.substring(2);
strs = rem.split("-");
ls = new String[strs.length - 1];
for (int i = 0; i < ls.length; i++) {
if (i > 0) {
ls[i] = "[" + strs[i].charAt(strs[i].length() - 1) + "-"
+ strs[i + 1].charAt(0) + "]";
} else
ls[i] = "[" + strs[i].charAt(strs[i].length() - 1) + "-"
+ strs[i + 1].charAt(0) + "]";
}
for (String m : ls) {
if (m.length() == 5) {
rem = rem.replace(m.substring(1, m.length() - 1), "");
} else
rem = rem.replace(m.substring(2, m.length() - 1), "");
}
rem = OrThisShit(rem);
for (String m : ls) {
if (!rem.isEmpty())
rem = rem + "|" + expand(m);
}
rem = rem.replace("()|", "");
rem = rem.replace(")|(", "|");
n = 1;
while (n < rem.length()) {
chars.remove((rem.charAt(n)));
n += 2;
}
StringBuilder sb = new StringBuilder();
sb.append('(');
for (char c : chars) {
if (c == ' ') {
sb.append('\\');
}
sb.append(c);
sb.append('|');
}
- sb.deleteCharAt(sb.length() - 1);
+ if (!chars.isEmpty())
+ sb.deleteCharAt(sb.length() - 1);
+
sb.append(')');
return sb.toString();
}
/*
* Finds substrings (adds parens)
*/
private static String findSub(String s) {
int i = s.length() - 2;
int counter = 1;
while (counter != 0) {
if (s.charAt(i) == ')')
counter++;
else if (s.charAt(i) == '(')
counter--;
i--;
}
return s.substring(i + 1, s.length());
}
/*
* Pulls apart an OR block
*/
private static String OrThisShit(String s) {
s = s.substring(1, s.length() - 1); // Strip outer brackets
StringBuilder sb = new StringBuilder();
sb.append('(');
for (char c : s.toCharArray()) {
sb.append(c);
sb.append('|');
}
- sb.deleteCharAt(sb.length() - 1); // Remove trailing |
+ if (!s.isEmpty())
+ sb.deleteCharAt(sb.length() - 1); // Remove trailing |
+
sb.append(')');
return sb.toString();
}
/*
* Expands and OR block with a spread
*/
private static String expand(String sub)
throws StringIndexOutOfBoundsException {
char lb = sub.charAt(1);
char ub = sub.charAt(sub.length() - 2);
int indx = 1;
while (indx < sub.length() - 1) {
if (lb == ub) {
sub = "(" + sub.substring(1, indx)
+ sub.substring(indx + 1, sub.length() - 1) + ")";
i += indx - 2;
return sub;
} else if (indx == 1) {
sub = sub.substring(0, indx) + lb + "|"
+ sub.substring(indx + 1, sub.length());
lb += 1;
indx += 2;
} else {
sub = sub.substring(0, indx) + lb + "|"
+ sub.substring(indx, sub.length());
lb += 1;
indx += 2;
}
}
i += indx;
return sub;
}
}
| false | false | null | null |
diff --git a/src/test/java/org/apache/commons/net/ftp/parser/NTFTPEntryParserTest.java b/src/test/java/org/apache/commons/net/ftp/parser/NTFTPEntryParserTest.java
index 47108d0a..17a273a6 100644
--- a/src/test/java/org/apache/commons/net/ftp/parser/NTFTPEntryParserTest.java
+++ b/src/test/java/org/apache/commons/net/ftp/parser/NTFTPEntryParserTest.java
@@ -1,253 +1,253 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.ftp.parser;
import java.util.Calendar;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParser;
/**
* @author <a href="mailto:[email protected]">Steve Cohen</a>
* @version $Id$
*/
public class NTFTPEntryParserTest extends CompositeFTPParseTestFramework
{
private static final String [][] goodsamples = {
{ // DOS-style tests
"05-26-95 10:57AM 143712 $LDR$",
"05-20-97 03:31PM 681 .bash_history",
"12-05-96 05:03PM <DIR> absoft2",
"11-14-97 04:21PM 953 AUDITOR3.INI",
"05-22-97 08:08AM 828 AUTOEXEC.BAK",
"01-22-98 01:52PM 795 AUTOEXEC.BAT",
"05-13-97 01:46PM 828 AUTOEXEC.DOS",
"12-03-96 06:38AM 403 AUTOTOOL.LOG",
"12-03-96 06:38AM <DIR> 123xyz",
"01-20-97 03:48PM <DIR> bin",
"05-26-1995 10:57AM 143712 $LDR$",
// 24hr clock as used on Windows_CE
"12-05-96 17:03 <DIR> absoft2",
"05-22-97 08:08 828 AUTOEXEC.BAK",
"01-01-98 05:00 <DIR> Network",
"01-01-98 05:00 <DIR> StorageCard",
"09-13-10 20:08 <DIR> Recycled",
"09-06-06 19:00 69 desktop.ini",
"09-13-10 13:08 23 Control Panel.lnk",
"09-13-10 13:08 <DIR> My Documents",
"09-13-10 13:08 <DIR> Program Files",
"09-13-10 13:08 <DIR> Temp",
"09-13-10 13:08 <DIR> Windows",
},
{ // Unix-style tests
"-rw-r--r-- 1 root root 111325 Apr 27 2001 zxJDBC-2.0.1b1.tar.gz",
"-rw-r--r-- 1 root root 190144 Apr 27 2001 zxJDBC-2.0.1b1.zip",
"-rwxr-xr-x 2 500 500 166 Nov 2 2001 73131-testtes1.afp",
"-rw-r--r-- 1 500 500 166 Nov 9 2001 73131-testtes1.AFP",
"drwx------ 4 maxm Domain Users 512 Oct 2 10:59 .metadata",
}
};
private static final String[][] badsamples =
{
{ // DOS-style tests
"20-05-97 03:31PM 681 .bash_history",
" 0 DIR 05-19-97 12:56 local",
" 0 DIR 05-12-97 16:52 Maintenance Desktop",
},
{ // Unix-style tests
"drwxr-xr-x 2 root 99 4096Feb 23 30:01 zzplayer",
}
};
private static final String directoryBeginningWithNumber =
"12-03-96 06:38AM <DIR> 123xyz";
/**
* @see junit.framework.TestCase#TestCase(String)
*/
public NTFTPEntryParserTest (String name)
{
super(name);
}
/**
* @see org.apache.commons.net.ftp.parser.CompositeFTPParseTestFramework#getGoodListings()
*/
@Override
protected String[][] getGoodListings()
{
return goodsamples;
}
/**
* @see org.apache.commons.net.ftp.parser.CompositeFTPParseTestFramework#getBadListings()
*/
@Override
protected String[][] getBadListings()
{
return badsamples;
}
/**
* @see org.apache.commons.net.ftp.parser.FTPParseTestFramework#getParser()
*/
@Override
protected FTPFileEntryParser getParser()
{
return new CompositeFileEntryParser(new FTPFileEntryParser[]
{
new NTFTPEntryParser(),
new UnixFTPEntryParser()
});
}
/**
* @see org.apache.commons.net.ftp.parser.FTPParseTestFramework#testParseFieldsOnDirectory()
*/
@Override
public void testParseFieldsOnDirectory() throws Exception
{
FTPFile dir = getParser().parseFTPEntry("12-05-96 05:03PM <DIR> absoft2");
assertNotNull("Could not parse entry.", dir);
assertEquals("Thu Dec 05 17:03:00 1996",
df.format(dir.getTimestamp().getTime()));
assertTrue("Should have been a directory.",
dir.isDirectory());
assertEquals("absoft2", dir.getName());
assertEquals(0, dir.getSize());
dir = getParser().parseFTPEntry("12-03-96 06:38AM <DIR> 123456");
assertNotNull("Could not parse entry.", dir);
assertTrue("Should have been a directory.",
dir.isDirectory());
assertEquals("123456", dir.getName());
assertEquals(0, dir.getSize());
}
public void testParseLeadingDigits() {
FTPFile file = getParser().parseFTPEntry("05-22-97 12:08AM 5000000000 10 years and under");
assertNotNull("Could not parse entry", file);
assertEquals("10 years and under", file.getName());
assertEquals(5000000000L, file.getSize());
Calendar timestamp = file.getTimestamp();
assertNotNull("Could not parse time",timestamp);
assertEquals("Thu May 22 00:08:00 1997",df.format(timestamp.getTime()));
FTPFile dir = getParser().parseFTPEntry("12-03-96 06:38PM <DIR> 10 years and under");
assertNotNull("Could not parse entry", dir);
assertEquals("10 years and under", dir.getName());
timestamp = dir.getTimestamp();
assertNotNull("Could not parse time",timestamp);
assertEquals("Tue Dec 03 18:38:00 1996",df.format(timestamp.getTime()));
}
- public void testNET339() { // TODO enable when NET-339 is fixed
+ public void testNET339() {
FTPFile file = getParser().parseFTPEntry("05-22-97 12:08 5000000000 10 years and under");
assertNotNull("Could not parse entry", file);
assertEquals("10 years and under", file.getName());
assertEquals(5000000000L, file.getSize());
Calendar timestamp = file.getTimestamp();
assertNotNull("Could not parse time",timestamp);
assertEquals("Thu May 22 12:08:00 1997",df.format(timestamp.getTime()));
FTPFile dir = getParser().parseFTPEntry("12-03-96 06:38 <DIR> 10 years and under");
assertNotNull("Could not parse entry", dir);
assertEquals("10 years and under", dir.getName());
timestamp = dir.getTimestamp();
assertNotNull("Could not parse time",timestamp);
assertEquals("Tue Dec 03 06:38:00 1996",df.format(timestamp.getTime()));
}
/**
* @see org.apache.commons.net.ftp.parser.FTPParseTestFramework#testParseFieldsOnFile()
*/
@Override
public void testParseFieldsOnFile() throws Exception
{
FTPFile f = getParser().parseFTPEntry("05-22-97 12:08AM 5000000000 AUTOEXEC.BAK");
assertNotNull("Could not parse entry.", f);
assertEquals("Thu May 22 00:08:00 1997",
df.format(f.getTimestamp().getTime()));
assertTrue("Should have been a file.",
f.isFile());
assertEquals("AUTOEXEC.BAK", f.getName());
assertEquals(5000000000L, f.getSize());
// test an NT-unix style listing that does NOT have a leading zero
// on the hour.
f = getParser().parseFTPEntry(
"-rw-rw-r-- 1 mqm mqm 17707 Mar 12 3:33 killmq.sh.log");
assertNotNull("Could not parse entry.", f);
Calendar cal = Calendar.getInstance();
cal.setTime(f.getTimestamp().getTime());
assertEquals("hour", 3, cal.get(Calendar.HOUR));
assertTrue("Should have been a file.",
f.isFile());
assertEquals(17707, f.getSize());
}
@Override
protected void doAdditionalGoodTests(String test, FTPFile f)
{
if (test.indexOf("<DIR>") >= 0)
{
assertEquals("directory.type",
FTPFile.DIRECTORY_TYPE, f.getType());
}
}
/**
* test condition reported as bug 20259 => NET-106.
* directory with name beginning with a numeric character
* was not parsing correctly
*
* @throws Exception
*/
public void testDirectoryBeginningWithNumber() throws Exception
{
FTPFile f = getParser().parseFTPEntry(directoryBeginningWithNumber);
assertEquals("name", "123xyz", f.getName());
}
public void testDirectoryBeginningWithNumberFollowedBySpaces() throws Exception
{
FTPFile f = getParser().parseFTPEntry("12-03-96 06:38AM <DIR> 123 xyz");
assertEquals("name", "123 xyz", f.getName());
f = getParser().parseFTPEntry("12-03-96 06:38AM <DIR> 123 abc xyz");
assertNotNull(f);
assertEquals("name", "123 abc xyz", f.getName());
}
/**
* Test that group names with embedded spaces can be handled correctly
*
*/
public void testGroupNameWithSpaces() {
FTPFile f = getParser().parseFTPEntry("drwx------ 4 maxm Domain Users 512 Oct 2 10:59 .metadata");
assertNotNull(f);
assertEquals("maxm", f.getUser());
assertEquals("Domain Users", f.getGroup());
}
}
| true | false | null | null |
diff --git a/scoutmaster/src/main/java/au/org/scoutmaster/dao/ContactDao.java b/scoutmaster/src/main/java/au/org/scoutmaster/dao/ContactDao.java
index 72f2efa..1886e5f 100644
--- a/scoutmaster/src/main/java/au/org/scoutmaster/dao/ContactDao.java
+++ b/scoutmaster/src/main/java/au/org/scoutmaster/dao/ContactDao.java
@@ -1,187 +1,187 @@
package au.org.scoutmaster.dao;
import java.sql.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import au.com.vaadinutils.dao.EntityManagerProvider;
import au.org.scoutmaster.domain.Age;
import au.org.scoutmaster.domain.Contact;
import au.org.scoutmaster.domain.Contact_;
import au.org.scoutmaster.domain.Note;
import au.org.scoutmaster.domain.SectionType;
import au.org.scoutmaster.domain.Section_;
import au.org.scoutmaster.domain.Tag;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
public class ContactDao extends JpaBaseDao<Contact, Long> implements Dao<Contact, Long>
{
static private Logger logger = Logger.getLogger(ContactDao.class);
public ContactDao()
{
// inherit the default per request em.
}
public ContactDao(EntityManager em)
{
super(em);
}
@Override
public List<Contact> findAll()
{
return super.findAll(Contact.FIND_ALL);
}
@SuppressWarnings("unchecked")
public List<Contact> findByName(String firstname, String lastname)
{
Query query = entityManager.createNamedQuery(Contact.FIND_BY_NAME);
query.setParameter("firstname", firstname);
query.setParameter("lastname", lastname);
List<Contact> resultContacts = query.getResultList();
return resultContacts;
}
public Long getAge(Contact contact)
{
long age = 0;
if (contact.getBirthDate() != null)
{
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
int factor = 0;
Date date1 = contact.getBirthDate();
Date date2 = new Date(new java.util.Date().getTime());
cal1.setTime(date1);
cal2.setTime(date2);
if (cal2.get(Calendar.DAY_OF_YEAR) < cal1.get(Calendar.DAY_OF_YEAR))
{
factor = -1;
}
age = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR) + factor;
}
return age;
}
public void addNote(Contact contact, String subject, String body)
{
Note note = new Note(subject, body);
// note.setContact(this);
contact.getNotes().add(note);
}
public void attachTag(Contact contact, Tag tag)
{
// tag.addContact(this);
contact.getTags().add(tag);
}
/**
* Detaches the tag from this contact. The tag entity is not actually deleted as
* it may be used by other entities.
*
* @param tagName
*/
public void detachTag(Contact contact, String tagName)
{
Tag tagToRemove = null;
for (Tag tag : contact.getTags())
{
if (tag.isTag(tagName))
{
tagToRemove = tag;
}
}
if (tagToRemove != null)
detachTag(contact, tagToRemove);
else
logger.warn("Attempt to detach non-existant tag. tagName=" + tagName);
}
public void detachTag(Contact contact, Tag tag)
{
if (tag != null)
contact.getTags().remove(tag);
}
public Note getNote(Contact contact, String noteSubject)
{
Note found = null;
for (Note note : contact.getNotes())
{
if (note.getSubject().equals(noteSubject))
{
found = note;
break;
}
}
return found;
}
public boolean hasTag(Contact contact, Tag tag)
{
boolean hasTag = false;
for (Tag aTag : contact.getTags())
{
if (aTag.equals(tag))
{
hasTag = true;
break;
}
}
return hasTag;
}
public Age getAge(java.util.Date birthDate)
{
DateTime date = new DateTime(birthDate);
return new Age(date);
}
public SectionType getSectionEligibilty(java.util.Date birthDate)
{
DateTime date = new DateTime(new DateMidnight(birthDate));
SectionTypeDao daoSectionType = new SectionTypeDao();
return daoSectionType.getEligibleSection(date);
}
public JPAContainer<Contact> makeJPAContainer()
{
- JPAContainer<Contact> contactContainer = JPAContainerFactory.make(Contact.class, EntityManagerProvider.INSTANCE.getEntityManager());
+ JPAContainer<Contact> contactContainer = super.makeJPAContainer(Contact.class);
contactContainer.addNestedContainerProperty("phone1.phoneNo");
contactContainer.addNestedContainerProperty("phone1.primaryPhone");
contactContainer.addNestedContainerProperty("phone1.phoneType");
contactContainer.addNestedContainerProperty("phone2.phoneNo");
contactContainer.addNestedContainerProperty("phone2.primaryPhone");
contactContainer.addNestedContainerProperty("phone2.phoneType");
contactContainer.addNestedContainerProperty("phone3.phoneNo");
contactContainer.addNestedContainerProperty("phone3.primaryPhone");
contactContainer.addNestedContainerProperty("phone3.phoneType");
contactContainer.addNestedContainerProperty("address.street");
contactContainer.addNestedContainerProperty("address.city");
contactContainer.addNestedContainerProperty("address.postcode");
contactContainer.addNestedContainerProperty("address.state");
//contactContainer.addNestedContainerProperty(new Path(Contact_.role, Role_.name).toString());
contactContainer.addNestedContainerProperty(new Path(Contact_.section, Section_.name).toString());
return contactContainer;
}
}
diff --git a/scoutmaster/src/main/java/au/org/scoutmaster/dao/JpaBaseDao.java b/scoutmaster/src/main/java/au/org/scoutmaster/dao/JpaBaseDao.java
index 77d4f3e..5583468 100644
--- a/scoutmaster/src/main/java/au/org/scoutmaster/dao/JpaBaseDao.java
+++ b/scoutmaster/src/main/java/au/org/scoutmaster/dao/JpaBaseDao.java
@@ -1,121 +1,121 @@
package au.org.scoutmaster.dao;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.metamodel.SingularAttribute;
import au.com.vaadinutils.dao.EntityManagerProvider;
import com.google.gwt.thirdparty.guava.common.base.Preconditions;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
public abstract class JpaBaseDao<E, K> implements Dao<E, K>
{
protected Class<E> entityClass;
protected EntityManager entityManager;
@SuppressWarnings("unchecked")
public JpaBaseDao()
{
this.entityManager = EntityManagerProvider.INSTANCE.getEntityManager();
Preconditions.checkNotNull(this.entityManager);
// hack to get the derived classes Class type.
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
Preconditions.checkNotNull(genericSuperclass);
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
Preconditions.checkNotNull(this.entityClass);
}
@SuppressWarnings("unchecked")
public JpaBaseDao(EntityManager em)
{
this.entityManager = em;
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}
public void persist(E entity)
{
entityManager.persist(entity);
}
public E merge(E entity)
{
return entityManager.merge(entity);
}
public void remove(E entity)
{
entityManager.remove(entity);
}
public E findById(K id)
{
return entityManager.find(entityClass, id);
}
protected E findSingleBySingleParameter(String queryName, SingularAttribute<E, String> paramName, String paramValue)
{
E entity = null;
Query query = entityManager.createNamedQuery(queryName);
query.setParameter(paramName.getName(), paramValue);
@SuppressWarnings("unchecked")
List<E> entities = query.getResultList();
if (entities.size() > 0)
entity = entities.get(0);
return entity;
}
protected E findSingleBySingleParameter(String queryName, String paramName, String paramValue)
{
E entity = null;
Query query = entityManager.createNamedQuery(queryName);
query.setParameter(paramName, paramValue);
@SuppressWarnings("unchecked")
List<E> entities = query.getResultList();
if (entities.size() > 0)
entity = entities.get(0);
return entity;
}
protected List<E> findListBySingleParameter(String queryName, String paramName, String paramValue)
{
Query query = entityManager.createNamedQuery(queryName);
query.setParameter(paramName, paramValue);
@SuppressWarnings("unchecked")
List<E> entities = query.getResultList();
return entities;
}
protected List<E> findAll(String queryName)
{
Query query = entityManager.createNamedQuery(queryName);
@SuppressWarnings("unchecked")
List<E> list = query.getResultList();
return list;
}
public void flush()
{
this.entityManager.flush();
}
public JPAContainer<E> makeJPAContainer(Class<E> clazz)
{
- JPAContainer<E> container = JPAContainerFactory.make(clazz, EntityManagerProvider.INSTANCE.getEntityManager());
+ JPAContainer<E> container = JPAContainerFactory. makeBatchable(clazz, EntityManagerProvider.INSTANCE.getEntityManager());
return container;
}
abstract public JPAContainer<E> makeJPAContainer();
}
\ No newline at end of file
| false | false | null | null |
diff --git a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java
index 35194ec2f..de1a9fd7a 100644
--- a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java
+++ b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java
@@ -1,496 +1,508 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo 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.
*
* OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.fib.view.widget.browser;
import java.awt.Font;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;
import javax.swing.Icon;
import org.openflexo.antar.binding.BindingEvaluationContext;
import org.openflexo.antar.binding.BindingVariable;
import org.openflexo.antar.binding.DataBinding;
import org.openflexo.antar.expr.NotSettableContextException;
import org.openflexo.antar.expr.NullReferenceException;
import org.openflexo.antar.expr.TypeMismatchException;
import org.openflexo.fib.controller.FIBController;
import org.openflexo.fib.model.FIBAttributeNotification;
import org.openflexo.fib.model.FIBBrowser;
import org.openflexo.fib.model.FIBBrowserElement;
import org.openflexo.fib.model.FIBBrowserElement.FIBBrowserElementChildren;
import org.openflexo.fib.view.widget.FIBBrowserWidget;
import org.openflexo.localization.FlexoLocalization;
import org.openflexo.toolbox.ToolBox;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class FIBBrowserElementType implements BindingEvaluationContext, Observer {
private final class CastFunction implements Function<Object, Object>, BindingEvaluationContext {
private final FIBBrowserElementChildren children;
private Object child;
private CastFunction(FIBBrowserElementChildren children) {
this.children = children;
}
@Override
public synchronized Object apply(Object arg0) {
child = arg0;
try {
Object result = null;
try {
result = children.getCast().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
} finally {
child = null;
}
}
@Override
public Object getValue(BindingVariable variable) {
if (variable.getVariableName().equals("child")) {
return child;
} else {
return FIBBrowserElementType.this.getValue(variable);
}
}
}
private static final Logger logger = Logger.getLogger(FIBBrowserElementType.class.getPackage().getName());
private FIBBrowserModel fibBrowserModel;
private FIBBrowserElement browserElementDefinition;
private boolean isFiltered = false;
private FIBController controller;
public FIBBrowserElementType(FIBBrowserElement browserElementDefinition, FIBBrowserModel browserModel, FIBController controller) {
super();
this.controller = controller;
this.fibBrowserModel = browserModel;
this.browserElementDefinition = browserElementDefinition;
browserElementDefinition.addObserver(this);
}
public void delete() {
if (browserElementDefinition != null) {
browserElementDefinition.deleteObserver(this);
}
this.controller = null;
this.browserElementDefinition = null;
}
public FIBBrowserModel getBrowserModel() {
return fibBrowserModel;
}
@Override
public void update(Observable o, Object arg) {
if (arg instanceof FIBAttributeNotification && o == browserElementDefinition) {
FIBAttributeNotification dataModification = (FIBAttributeNotification) arg;
((FIBBrowserWidget) controller.viewForComponent(browserElementDefinition.getBrowser())).updateBrowser();
}
}
public FIBController getController() {
return controller;
}
public FIBBrowser getBrowser() {
return browserElementDefinition.getBrowser();
}
public String getLocalized(String key) {
return FlexoLocalization.localizedForKey(getController().getLocalizerForComponent(getBrowser()), key);
}
protected void setModel(FIBBrowserModel model) {
fibBrowserModel = model;
}
protected FIBBrowserModel getModel() {
return fibBrowserModel;
}
public List<DataBinding<?>> getDependencyBindings(final Object object) {
if (browserElementDefinition == null) {
return null;
}
iteratorObject = object;
List<DataBinding<?>> returned = new ArrayList<DataBinding<?>>();
returned.add(browserElementDefinition.getLabel());
returned.add(browserElementDefinition.getIcon());
returned.add(browserElementDefinition.getTooltip());
returned.add(browserElementDefinition.getEnabled());
returned.add(browserElementDefinition.getVisible());
for (FIBBrowserElementChildren children : browserElementDefinition.getChildren()) {
returned.add(children.getData());
returned.add(children.getCast());
returned.add(children.getVisible());
}
return returned;
}
public String getLabelFor(final Object object) {
if (browserElementDefinition == null) {
return "???" + object.toString();
}
if (browserElementDefinition.getLabel().isSet()) {
iteratorObject = object;
try {
return browserElementDefinition.getLabel().getBindingValue(this);
} catch (TypeMismatchException e) {
// System.out.println("While evaluating " + browserElementDefinition.getLabel());
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return object.toString();
}
public String getTooltipFor(final Object object) {
if (browserElementDefinition == null) {
return "???" + object.toString();
}
if (browserElementDefinition.getTooltip().isSet()) {
iteratorObject = object;
try {
return browserElementDefinition.getTooltip().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return browserElementDefinition.getName();
}
public Icon getIconFor(final Object object) {
if (browserElementDefinition == null) {
return null;
}
if (browserElementDefinition.getIcon().isSet()) {
iteratorObject = object;
Object returned = null;
try {
returned = browserElementDefinition.getIcon().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (returned instanceof Icon) {
return (Icon) returned;
}
return null;
} else {
return browserElementDefinition.getImageIcon();
}
}
public boolean isEnabled(final Object object) {
if (browserElementDefinition == null) {
return false;
}
if (browserElementDefinition.getEnabled().isSet()) {
iteratorObject = object;
Object enabledValue = null;
try {
enabledValue = browserElementDefinition.getEnabled().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (enabledValue != null) {
return (Boolean) enabledValue;
}
return true;
} else {
return true;
}
}
public boolean isVisible(final Object object) {
if (browserElementDefinition == null) {
return false;
}
if (isFiltered()) {
return false;
}
if (browserElementDefinition.getVisible().isSet()) {
iteratorObject = object;
try {
Boolean returned = browserElementDefinition.getVisible().getBindingValue(this);
if (returned != null) {
return returned;
}
return true;
} catch (TypeMismatchException e) {
e.printStackTrace();
return true;
} catch (NullReferenceException e) {
e.printStackTrace();
return true;
} catch (InvocationTargetException e) {
e.printStackTrace();
return true;
}
} else {
return true;
}
}
public List<Object> getChildrenFor(final Object object) {
if (browserElementDefinition == null) {
return Collections.EMPTY_LIST;
}
List<Object> returned = new ArrayList<Object>();
for (FIBBrowserElementChildren children : browserElementDefinition.getChildren()) {
if (children.isMultipleAccess()) {
// System.out.println("add all children for "+browserElementDefinition.getName()+" children "+children.getName()+" data="+children.getData());
// System.out.println("Obtain "+getChildrenListFor(children, object));
List<?> childrenObjects = getChildrenListFor(children, object);
// Might be null if some visibility was declared
if (childrenObjects != null) {
returned.addAll(childrenObjects);
}
// System.out.println("For " + object + " of " + object.getClass().getSimpleName() + " children=" + children.getData()
// + " values=" + object);
} else {
// System.out.println("add children for "+browserElementDefinition.getName()+" children "+children.getName()+" data="+children.getData());
// System.out.println("Obtain "+getChildrenFor(children, object));
// System.out.println("accessed type="+children.getAccessedType());
Object childrenObject = getChildrenFor(children, object);
// Might be null if some visibility was declared
if (childrenObject != null) {
returned.add(childrenObject);
}
// System.out.println("For " + object + " of " + object.getClass().getSimpleName() + " children=" + children.getData()
// + " value=" + childrenObject);
}
}
return returned;
}
protected Object getChildrenFor(FIBBrowserElementChildren children, final Object object) {
if (children.getData().isSet()) {
iteratorObject = object;
if (children.getVisible().isSet()) {
boolean visible;
try {
visible = children.getVisible().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
visible = true;
} catch (NullReferenceException e) {
e.printStackTrace();
visible = true;
} catch (InvocationTargetException e) {
e.printStackTrace();
visible = true;
}
if (!visible) {
// Finally we dont want to see it
return null;
}
}
Object result = null;
try {
result = children.getData().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (children.getCast().isSet()) {
return new CastFunction(children).apply(result);
}
return result;
} else {
return null;
}
}
protected List<?> getChildrenListFor(final FIBBrowserElementChildren children, final Object object) {
if (children.getData().isSet() && children.isMultipleAccess()) {
iteratorObject = object;
if (children.getVisible().isSet()) {
boolean visible;
try {
visible = children.getVisible().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
visible = true;
} catch (NullReferenceException e) {
e.printStackTrace();
visible = true;
} catch (InvocationTargetException e) {
e.printStackTrace();
visible = true;
}
if (!visible) {
// Finally we dont want to see it
return null;
}
}
Object bindingValue = null;
try {
bindingValue = children.getData().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
List<?> list = ToolBox.getListFromIterable(bindingValue);
+ List returned = list;
if (list != null && children.getCast().isSet()) {
list = Lists.transform(list, new CastFunction(children));
+ // Remove all occurences of null (caused by cast)
+ /*while (list.contains(null)) {
+ list.remove(null);
+ }*/
+ if (list.contains(null)) {
+ // The list contains null
+ // We have to consider only non-null instances of elements, but we must avoid to destroy initial list:
+ // This is the reason for what we have to clone the list while avoiding null elements
+ returned = new ArrayList<Object>();
+ for (Object o : list) {
+ if (o != null) {
+ returned.add(o);
+ }
+ }
+ }
}
- // Remove all occurences of null (caused by cast)
- while (list.contains(null)) {
- list.remove(null);
- }
- return list;
+ return returned;
} else {
return null;
}
}
public boolean isLabelEditable() {
return getBrowserElement().getIsEditable() && getBrowserElement().getEditableLabel().isSet()
&& getBrowserElement().getEditableLabel().isSettable();
}
public synchronized String getEditableLabelFor(final Object object) {
if (isLabelEditable()) {
iteratorObject = object;
try {
return browserElementDefinition.getEditableLabel().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return object.toString();
}
public synchronized void setEditableLabelFor(final Object object, String value) {
if (isLabelEditable()) {
iteratorObject = object;
try {
browserElementDefinition.getEditableLabel().setBindingValue(value, this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NotSettableContextException e) {
e.printStackTrace();
}
}
}
protected Object iteratorObject;
@Override
public synchronized Object getValue(BindingVariable variable) {
if (variable.getVariableName().equals(browserElementDefinition.getName())) {
return iteratorObject;
} else if (variable.getVariableName().equals("object")) {
return iteratorObject;
} else {
return getController().getValue(variable);
}
}
public FIBBrowserElement getBrowserElement() {
return browserElementDefinition;
}
public Font getFont(final Object object) {
if (browserElementDefinition.getDynamicFont().isSet()) {
iteratorObject = object;
try {
return browserElementDefinition.getDynamicFont().getBindingValue(this);
} catch (TypeMismatchException e) {
e.printStackTrace();
} catch (NullReferenceException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
if (getBrowserElement() != null) {
return getBrowserElement().retrieveValidFont();
}
return null;
}
public boolean isFiltered() {
return isFiltered;
}
public void setFiltered(boolean isFiltered) {
System.out.println("Element " + getBrowserElement().getName() + " filtered: " + isFiltered);
if (this.isFiltered != isFiltered) {
this.isFiltered = isFiltered;
// Later, try to implement a way to rebuild tree with same expanded nodes
fibBrowserModel.fireTreeRestructured();
}
}
}
| false | false | null | null |
diff --git a/core/jdiameter/impl/src/main/java/org/jdiameter/client/impl/parser/MessageImpl.java b/core/jdiameter/impl/src/main/java/org/jdiameter/client/impl/parser/MessageImpl.java
index f559afce..1fce83c6 100644
--- a/core/jdiameter/impl/src/main/java/org/jdiameter/client/impl/parser/MessageImpl.java
+++ b/core/jdiameter/impl/src/main/java/org/jdiameter/client/impl/parser/MessageImpl.java
@@ -1,506 +1,515 @@
package org.jdiameter.client.impl.parser;
/*
* Copyright (c) 2006 jDiameter.
* https://jdiameter.dev.java.net/
*
* License: GPL v3
*
* e-mail: [email protected]
*
*/
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.MetaData;
import org.jdiameter.client.api.IEventListener;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.controller.IPeer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageImpl implements IMessage {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(MessageImpl.class);
int state = STATE_NOT_SENT;
short version = 1, flags;
int commandCode;
long applicationId;
long hopByHopId;
boolean notMutableHopByHop;
long endToEndId;
AvpSetImpl avpSet;
boolean isNetworkRequest = false;
transient IPeer peer;
transient MessageParser parser;
transient TimerTask timerTask;
transient IEventListener listener;
+ // Cached result for getApplicationIdAvps() method. It is called extensively and takes some time.
+ // Potential place for dirt, but Application IDs don't change during message life time.
+ transient Set<ApplicationId> applicationIds;
+
/**
* Create empty message
*
* @param parser
* @param commandCode
* @param appId
*/
MessageImpl(MessageParser parser, int commandCode, long appId) {
this.commandCode = commandCode;
this.applicationId = appId;
this.parser = parser;
this.avpSet = new AvpSetImpl(parser);
this.endToEndId = parser.getNextEndToEndId();
}
/**
* Create empty message
*
* @param parser
* @param commandCode
* @param applicationId
* @param flags
* @param hopByHopId
* @param endToEndId
* @param avpSet
*/
MessageImpl(MessageParser parser, int commandCode, long applicationId, short flags, long hopByHopId, long endToEndId, AvpSetImpl avpSet) {
this(parser, commandCode, applicationId);
this.flags = flags;
this.hopByHopId = hopByHopId;
this.endToEndId = endToEndId;
if (avpSet != null) {
this.avpSet = avpSet;
}
}
/**
* Create empty message
*
* @param metaData
* @param parser
* @param commandCode
* @param appId
*/
MessageImpl(MetaData metaData, MessageParser parser, int commandCode, long appId) {
this(parser, commandCode, appId);
try {
getAvps().addAvp(Avp.ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
getAvps().addAvp(Avp.ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
}
catch (Exception e) {
logger.debug("Can not create message", e);
}
}
/**
* Create Answer
*
* @param request parent request
*/
private MessageImpl(MessageImpl request) {
this(request.parser, request.getCommandCode(), request.getHeaderApplicationId());
copyHeader(request);
setRequest(false);
parser.copyBasicAvps(this, request, true);
}
public byte getVersion() {
return (byte) version;
}
public boolean isRequest() {
return (flags & 0x80) != 0;
}
public void setRequest(boolean b) {
if (b) {
flags |= 0x80;
}
else {
flags &= 0x7F;
}
}
public boolean isProxiable() {
return (flags & 0x40) != 0;
}
public void setProxiable(boolean b) {
if (b) {
flags |= 0x40;
}
else {
flags &= 0xBF;
}
}
public boolean isError() {
return (flags & 0x20) != 0;
}
public void setError(boolean b) {
if (b) {
flags |= 0x20;
}
else {
flags &= 0xDF;
}
}
public boolean isReTransmitted() {
return (flags & 0x10) != 0;
}
public void setReTransmitted(boolean b) {
if (b) {
flags |= 0x10;
}
else {
flags &= 0xEF;
}
}
public int getCommandCode() {
return this.commandCode;
}
public String getSessionId() {
try {
Avp avpSessionId = avpSet.getAvp(Avp.SESSION_ID);
return avpSessionId != null ? avpSessionId.getUTF8String() : null;
}
catch (AvpDataException exc) {
return null;
}
}
public Answer createAnswer(long resultCode) {
MessageImpl answer = new MessageImpl(this);
try {
answer.getAvps().addAvp(Avp.RESULT_CODE, resultCode, true, false, true);
}
catch (Exception e) {
logger.debug("Can not create answer message", e);
}
answer.setRequest(false);
return answer;
}
public Answer createAnswer(long vendorId, long experementalResultCode) {
MessageImpl answer = new MessageImpl(this);
try {
AvpSet exp_code = answer.getAvps().addGroupedAvp(297, true, false);
exp_code.addAvp(Avp.VENDOR_ID, vendorId, true, false, true);
exp_code.addAvp(Avp.EXPERIMENTAL_RESULT_CODE, experementalResultCode, true, false, true);
}
catch (Exception e) {
logger.debug("Can not create answer message", e);
}
answer.setRequest(false);
return answer;
}
public long getApplicationId() {
return applicationId;
}
public ApplicationId getSingleApplicationId() {
return getSingleApplicationId(this.applicationId);
}
public ApplicationId getSingleApplicationId(long applicationId) {
Set<ApplicationId> appIds = getApplicationIdAvps();
ApplicationId first = null;
for (ApplicationId id : appIds) {
if (first == null) {
first = id;
}
if (applicationId != 0 && id.getVendorId() == 0 && applicationId == id.getAuthAppId()) {
return id;
}
if (applicationId != 0 && id.getVendorId() == 0 && applicationId == id.getAcctAppId()) {
return id;
}
if (applicationId != 0 && (applicationId == id.getAuthAppId() || applicationId == id.getAcctAppId())) {
return id;
}
}
return first;
}
public Set<ApplicationId> getApplicationIdAvps() {
+ if (this.applicationIds != null) {
+ return this.applicationIds;
+ }
+
Set<ApplicationId> rc = new LinkedHashSet<ApplicationId>();
try {
AvpSet authAppId = avpSet.getAvps(Avp.AUTH_APPLICATION_ID);
for (Avp anAuthAppId : authAppId) {
rc.add(ApplicationId.createByAuthAppId((anAuthAppId).getInteger32()));
}
AvpSet accAppId = avpSet.getAvps(Avp.ACCT_APPLICATION_ID);
for (Avp anAccAppId : accAppId) {
rc.add(ApplicationId.createByAccAppId((anAccAppId).getInteger32()));
}
AvpSet specAppId = avpSet.getAvps(Avp.VENDOR_SPECIFIC_APPLICATION_ID);
for (Avp aSpecAppId : specAppId) {
long vendorId = 0, acctApplicationId = 0, authApplicationId = 0;
AvpSet avps = (aSpecAppId).getGrouped();
for (Avp localAvp : avps) {
if (localAvp.getCode() == Avp.VENDOR_ID) {
vendorId = localAvp.getUnsigned32();
}
if (localAvp.getCode() == Avp.AUTH_APPLICATION_ID) {
authApplicationId = localAvp.getUnsigned32();
}
if (localAvp.getCode() == Avp.ACCT_APPLICATION_ID) {
acctApplicationId = localAvp.getUnsigned32();
}
}
if (authApplicationId != 0) {
rc.add(ApplicationId.createByAuthAppId(vendorId, authApplicationId));
}
if (acctApplicationId != 0) {
rc.add(ApplicationId.createByAccAppId(vendorId, acctApplicationId));
}
}
}
catch (Exception exception) {
return new LinkedHashSet<ApplicationId>();
}
- return rc;
+ this.applicationIds = rc;
+ return this.applicationIds;
}
public long getHopByHopIdentifier() {
return hopByHopId;
}
public long getEndToEndIdentifier() {
return endToEndId;
}
public AvpSet getAvps() {
return avpSet;
}
protected void copyHeader(MessageImpl request) {
endToEndId = request.endToEndId;
hopByHopId = request.hopByHopId;
version = request.version;
flags = request.flags;
peer = request.peer;
}
public Avp getResultCode() {
return getAvps().getAvp(Avp.RESULT_CODE);
}
public void setNetworkRequest(boolean isNetworkRequest) {
this.isNetworkRequest = isNetworkRequest;
}
public boolean isNetworkRequest() {
return isNetworkRequest;
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
// Inner API
public void setHopByHopIdentifier(long hopByHopId) {
if (hopByHopId < 0) {
this.hopByHopId = -hopByHopId;
this.notMutableHopByHop = true;
}
else {
if (!this.notMutableHopByHop) {
this.hopByHopId = hopByHopId;
}
}
}
public void setEndToEndIdentifier(long endByEndId) {
this.endToEndId = endByEndId;
}
public IPeer getPeer() {
return peer;
}
public void setPeer(IPeer peer) {
this.peer = peer;
}
public int getState() {
return state;
}
public long getHeaderApplicationId() {
return applicationId;
}
public void setHeaderApplicationId(long applicationId) {
this.applicationId = applicationId;
}
public int getFlags() {
return flags;
}
public void setState(int newState) {
state = newState;
}
public void createTimer(ScheduledExecutorService scheduledFacility, long timeOut, TimeUnit timeUnit) {
timerTask = new TimerTask(this);
timerTask.setTimerHandler(scheduledFacility, scheduledFacility.schedule(timerTask, timeOut, timeUnit));
}
public void runTimer() {
if (timerTask != null && !timerTask.isDone() && !timerTask.isCancelled()) {
timerTask.run();
}
}
public boolean isTimeOut() {
return timerTask != null && timerTask.isDone() && !timerTask.isCancelled();
}
public void setListener(IEventListener listener) {
this.listener = listener;
}
public IEventListener getEventListener() {
return listener;
}
public void clearTimer() {
if (timerTask != null) {
timerTask.cancel();
}
}
public String toString() {
return "MessageImpl{" + "commandCode=" + commandCode + ", flags=" + flags + '}';
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MessageImpl message = (MessageImpl) o;
return applicationId == message.applicationId && commandCode == message.commandCode &&
endToEndId == message.endToEndId && hopByHopId == message.hopByHopId;
}
public int hashCode() {
long result;
result = commandCode;
result = 31 * result + applicationId;
result = 31 * result + hopByHopId;
result = 31 * result + endToEndId;
return new Long(result).hashCode();
}
public String getDuplicationKey() {
try {
return getDuplicationKey(getAvps().getAvp(Avp.ORIGIN_HOST).getOctetString(), getEndToEndIdentifier());
}
catch (AvpDataException e) {
throw new IllegalArgumentException(e);
}
}
public String getDuplicationKey(String host, long endToEndId) {
return host + endToEndId;
}
public Object clone() {
try {
return parser.createMessage(parser.encodeMessage(this));
}
catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
protected static class TimerTask implements Runnable {
ScheduledFuture timerHandler;
MessageImpl message;
ScheduledExecutorService scheduledFacility;
public TimerTask(MessageImpl message) {
this.message = message;
}
public void setTimerHandler(ScheduledExecutorService scheduledFacility, ScheduledFuture timerHandler) {
this.scheduledFacility = scheduledFacility;
this.timerHandler = timerHandler;
}
public void run() {
try {
if (message != null && message.state != STATE_ANSWERED) {
IEventListener listener = null;
if (message.listener instanceof IEventListener) {
listener = message.listener;
}
if (listener != null && listener.isValid()) {
if (message.peer != null) {
message.peer.remMessage(message);
}
message.listener.timeoutExpired(message);
}
}
}
catch(Throwable e) {
logger.debug("Can not process timeout", e);
}
}
public void cancel() {
if (timerHandler != null) {
timerHandler.cancel(true);
if (scheduledFacility instanceof ThreadPoolExecutor && timerHandler instanceof Runnable) {
((ThreadPoolExecutor) scheduledFacility).remove((Runnable) timerHandler);
}
}
message = null;
}
public boolean isDone() {
return timerHandler != null && timerHandler.isDone();
}
public boolean isCancelled() {
return timerHandler == null || timerHandler.isCancelled();
}
}
}
| false | false | null | null |
diff --git a/src/share/classes/com/sun/tools/javafx/antlr/AbstractGeneratedParser.java b/src/share/classes/com/sun/tools/javafx/antlr/AbstractGeneratedParser.java
index 86782db4f..d03537377 100644
--- a/src/share/classes/com/sun/tools/javafx/antlr/AbstractGeneratedParser.java
+++ b/src/share/classes/com/sun/tools/javafx/antlr/AbstractGeneratedParser.java
@@ -1,606 +1,609 @@
/*
* Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.antlr;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javafx.tree.JFXTree;
import com.sun.tools.javafx.tree.JFXErroneous;
import com.sun.tools.javafx.tree.JavafxTreeMaker;
import com.sun.tools.javafx.util.MsgSym;
import org.antlr.runtime.*;
/**
* Base class for ANTLR generated parsers
*
* @author Robert Field
*/
public abstract class AbstractGeneratedParser extends Parser {
/** The factory to be used for abstract syntax tree construction.
*/
protected JavafxTreeMaker F;
/** The log to be used for error diagnostics.
*/
protected Log log;
/** The Source language setting. */
protected Source source;
/** The name table. */
protected Name.Table names;
protected java.util.Map<String, String> tokenMap = new java.util.HashMap<String, String>();
{
/*
tokenMap.put("<invalid>", "<invalid>");
tokenMap.put("<EOR>","<EOR>");
tokenMap.put("<DOWN>", "<DOWN>");
tokenMap.put("<UP>", "<UP>");
tokenMap.put("SEMI_INSERT_START", "SEMI_INSERT_START");
*/
tokenMap.put("ABSTRACT", "abstract");
tokenMap.put("ASSERT", "assert");
tokenMap.put("ATTRIBUTE","attribute");
tokenMap.put("BIND", "bind");
tokenMap.put("BOUND", "bound");
tokenMap.put("BREAK", "break");
tokenMap.put("CLASS", "class");
tokenMap.put("CONTINUE", "continue");
tokenMap.put("DELETE", "delete");
tokenMap.put("FALSE", "false");
tokenMap.put("FOR", "for");
tokenMap.put("FUNCTION", "function");
tokenMap.put("IF", "if");
tokenMap.put("IMPORT", "import");
tokenMap.put("INIT", "init");
tokenMap.put("INSERT", "insert");
tokenMap.put("LET", "let");
tokenMap.put("NEW", "new");
tokenMap.put("NOT", "not");
tokenMap.put("NULL", "null");
tokenMap.put("OVERRIDE", "override");
tokenMap.put("PACKAGE", "package");
tokenMap.put("POSTINIT", "postinit");
tokenMap.put("PRIVATE", "private");
tokenMap.put("PROTECTED", "protected");
tokenMap.put("PUBLIC", "public");
tokenMap.put("READONLY", "readonly");
tokenMap.put("RETURN", "return");
tokenMap.put("SUPER", "super");
tokenMap.put("SIZEOF", "sizeof");
tokenMap.put("STATIC", "static");
tokenMap.put("THIS", "this");
tokenMap.put("THROW", "throw");
tokenMap.put("TRY", "try");
tokenMap.put("TRUE", "true");
tokenMap.put("VAR", "var");
tokenMap.put("WHILE", "while");
tokenMap.put("POUND", "#");
tokenMap.put("LPAREN", "(");
tokenMap.put("LBRACKET", "[");
tokenMap.put("PLUSPLUS", "++");
tokenMap.put("SUBSUB", "--");
tokenMap.put("PIPE", "|");
/*
tokenMap.put("SEMI_INSERT_END", "SEMI_INSERT_END");
*/
tokenMap.put("AFTER", "after");
tokenMap.put("AND", "and");
tokenMap.put("AS", "as");
tokenMap.put("BEFORE", "before");
tokenMap.put("CATCH", "catch");
tokenMap.put("ELSE", "else");
tokenMap.put("EXCLUSIVE", "exclusive");
tokenMap.put("EXTENDS", "extends");
tokenMap.put("FINALLY", "finally");
tokenMap.put("FIRST", "first");
tokenMap.put("FROM", "from");
tokenMap.put("IN", "in");
tokenMap.put("INDEXOF", "indexof");
tokenMap.put("INSTANCEOF", "instanceof");
tokenMap.put("INTO", "into");
tokenMap.put("INVERSE", "inverse");
tokenMap.put("LAST", "last");
tokenMap.put("LAZY", "lazy");
tokenMap.put("ON", "on");
tokenMap.put("OR", "or");
tokenMap.put("REPLACE", "replace");
tokenMap.put("REVERSE", "reverse");
tokenMap.put("STEP", "step");
tokenMap.put("THEN", "then");
tokenMap.put("TYPEOF", "typeof");
tokenMap.put("WITH", "with");
tokenMap.put("WHERE", "where");
tokenMap.put("DOTDOT", "..");
tokenMap.put("RPAREN", ")");
tokenMap.put("RBRACKET", "]");
tokenMap.put("SEMI", ";");
tokenMap.put("COMMA", ",");
tokenMap.put("DOT", ".");
tokenMap.put("EQEQ", "==");
tokenMap.put("EQ", "=");
tokenMap.put("GT", ">");
tokenMap.put("LT", "<");
tokenMap.put("LTGT", "<>");
tokenMap.put("NOTEQ", "!=");
tokenMap.put("LTEQ", "<=");
tokenMap.put("GTEQ", ">=");
tokenMap.put("PLUS", "+");
tokenMap.put("SUB", "-");
tokenMap.put("STAR", "*");
tokenMap.put("SLASH", "/");
tokenMap.put("PERCENT", "%");
tokenMap.put("PLUSEQ", "+=");
tokenMap.put("SUBEQ", "-=");
tokenMap.put("STAREQ", "*=");
tokenMap.put("SLASHEQ", "/=");
tokenMap.put("PERCENTEQ", "%=");
tokenMap.put("COLON", ":");
tokenMap.put("QUES", "?");
/* imaginary tokens
tokenMap.put("MODULE", "MODULE");
tokenMap.put("MODIFIER", "MODIFIER");
tokenMap.put("CLASS_MEMBERS", "CLASS_MEMBERS");
tokenMap.put("PARAM", "PRAM");
tokenMap.put("FUNC_EXPR", "FUNC_EXPR");
tokenMap.put("STATEMENT", "STATEMENT");
tokenMap.put("EXPRESSION", "EXPRESSION");
tokenMap.put("BLOCK", "BLOCK");
tokenMap.put("MISSING_NAME", "MISSING_NAME");
tokenMap.put("SLICE_CLAUSE", "SLICE_CLAUSE");
tokenMap.put("ON_REPLACE_SLICE", "ON_REPLACE_SLICE");
tokenMap.put("ON_REPLACE", "ON_REPLACE");
tokenMap.put("ON_REPLACE_ELEMENT", "ON_REPLACE_ELEMENT");
tokenMap.put("ON_INSERT_ELEMENT", "ON_INSERT_ELEMENT");
tokenMap.put("ON_DELETE_ELEMENT", "ON_DELETE_ELEMENT");
tokenMap.put("EXPR_LIST", "EXPR_LIST");
tokenMap.put("FUNC_APPLY", "FUNC_APPLY");
tokenMap.put("NEGATIVE", "NEGATIVE");
tokenMap.put("POSTINCR", "POSTINCR");
tokenMap.put("POSTDECR", "POSTDECR");
tokenMap.put("SEQ_INDEX", "SEQ_INDEX");
tokenMap.put("SEQ_SLICE", "SEQ_SLICE");
tokenMap.put("SEQ_SLICE_EXCLUSIVE", "SEQ_SLICE_EXCLUSIVE");
tokenMap.put("OBJECT_LIT", "OBJECT_LIT");
tokenMap.put("OBJECT_LIT_PART", "OBJECT_LIT_PART");
tokenMap.put("SEQ_EMPTY", "SEQ_EMPTY");
tokenMap.put("SEQ_EXPLICIT","SEQ_EXPLICIT");
tokenMap.put("EMPTY_FORMAT_STRING", "EMPTY_FORMAT_STRING");
tokenMap.put("TYPE_NAMED", "TYPE_NAMED");
tokenMap.put("TYPE_FUNCTION", "TYPE_FUNCTION");
tokenMap.put("TYPE_ANY", "TYPE_ANY");
tokenMap.put("TYPE_UNKNOWN", "TYPE_UNKNOWN");
tokenMap.put("TYPE_ARG", "TYPE_ARG");
tokenMap.put("TYPED_ARG_LIST", "TYPED_ARG_LIST");
tokenMap.put("DOC_COMMENT", "DOC_COMMENT");
*/
tokenMap.put("DoubleQuoteBody", "double quote string literal");
tokenMap.put("SingleQuoteBody", "single quote string literal");
tokenMap.put("STRING_LITERAL", "string literal");
tokenMap.put("NextIsPercent", "%");
tokenMap.put("QUOTE_LBRACE_STRING_LITERAL", "\" { string literal");
tokenMap.put("LBRACE", "{");
tokenMap.put("RBRACE_QUOTE_STRING_LITERAL", "} \" string literal");
tokenMap.put("RBRACE_LBRACE_STRING_LITERAL", "} { string literal");
tokenMap.put("RBRACE", "}");
tokenMap.put("FORMAT_STRING_LITERAL", "format string literal");
tokenMap.put("TranslationKeyBody", "translation key body");
tokenMap.put("TRANSLATION_KEY", "translation key");
tokenMap.put("DECIMAL_LITERAL", "decimal literal");
tokenMap.put("Digits", "digits");
tokenMap.put("Exponent", "exponent");
tokenMap.put("TIME_LITERAL", "time literal");
tokenMap.put("OCTAL_LITERAL", "octal literal");
tokenMap.put("HexDigit", "hex digit");
tokenMap.put("HEX_LITERAL", "hex literal");
tokenMap.put("RangeDots", "..");
tokenMap.put("FLOATING_POINT_LITERAL", "floating point literal");
tokenMap.put("Letter", "letter");
tokenMap.put("JavaIDDigit", "java ID digit");
tokenMap.put("IDENTIFIER", "identifier");
tokenMap.put("WS", "white space");
tokenMap.put("COMMENT", "comment");
tokenMap.put("LINE_COMMENT", "line comment");
tokenMap.put("LAST_TOKEN", "last token");
}
// this field should not be accessed using the getFXTokenNames method
protected String[] fxTokenNames = null;
protected String[][] ruleMap = {
{"script", "the script contents"},
{"scriptItems", "the script contents"},
{"scriptItem", "the script contents"},
{"packageDecl", "a package declaration"},
{"importDecl", "an import declaration"},
{"importId", "an import declaration"},
{"classDefinition", "a class declaration"},
{"supers", "the 'extends' part of a class declaration"},
{"classMembers", "the members of a class declaration"},
{"classMember", "the members of a class declaration"},
{"functionDefinition", "a function declaration"},
{"initDefinition", "an 'init' block"},
{"postInitDefinition", "a 'postinit' block"},
{"functionModifierFlags", " the modifiers on a function declaration"},
{"functionModifier", " the modifiers on a function declaration"},
{"varModifierFlags", " the modifiers on a variable declaration"},
{"varModifier", " the modifiers on a variable declaration"},
{"classModifierFlags", " the modifiers on a class declaration"},
{"classModifier", " the modifiers on a class declaration"},
{"accessModifier", "an access modifier"},
{"formalParameters", " the parameters of a function declaration"},
{"formalParameter", " a formal parameter"},
{"block", "a block"},
{"blockComponent", "a component of a block"},
{"variableDeclaration", "a variable declaration"},
{"variableLabel", "a variable declaration"},
{"boundExpression", "an expression"},
{"inClause", "the 'in' clause of a 'for' expression"},
{"elseClause", "the 'else' clause of an 'if' expression"},
{"assignmentOpExpression", "an operator assignment expression"},
{"primaryExpression", "an expression"},
{"stringExpressionInner", "a string expression"},
{"bracketExpression", "a sequence creation expression"},
{"expressionList", "a list of expressions"},
{"expressionListOpt", "a list of expressions"},
{"type", "a type specification"},
{"typeArgList", "a type specification"},
{"typeArg", "a type specification"},
{"typeReference", "a type specification"},
{"cardinality", "a type specification"},
{"typeName", "a type specification"},
{"genericArgument", "a type specification"},
{"qualident", "an identifier"},
{"name", "an identifier"},
{"paramNameOpt", "an optional identifier"}
};
/* ---------- error recovery -------------- */
protected JFXErroneous errorTree;
/** initializes a new instance of GeneratedParser */
protected void initialize(Context context) {
this.F = (JavafxTreeMaker)JavafxTreeMaker.instance(context);
this.log = Log.instance(context);
this.names = Name.Table.instance(context);
this.source = Source.instance(context);
}
protected AbstractGeneratedParser(TokenStream input) {
super(input);
}
protected AbstractGeneratedParser(TokenStream input, RecognizerSharedState state) {
super(input, state);
}
+ @Override
protected void mismatch(IntStream input, int ttype, BitSet follow)
throws RecognitionException {
//System.err.println("Mismatch: " + ttype + ", Set: " + follow);
super.mismatch(input, ttype, follow);
}
protected String stackPositionDescription(String ruleName) {
// optimize for the non-error case: do sequential search
for (String[] pair : ruleMap) {
if (pair[0].equals(ruleName)) {
return pair[1];
}
}
StringBuffer sb = new StringBuffer(ruleName.length()+1);
switch (ruleName.charAt(0)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
sb.append("an ");
break;
default:
sb.append("a ");
break;
}
for (char ch : ruleName.toCharArray()) {
if (Character.isUpperCase(ch)) {
sb.append(' ');
sb.append(Character.toLowerCase(ch));
} else {
sb.append(ch);
}
}
return sb.toString();
}
protected enum TokenClassification {
KEYWORD {
String forHumans() {
return "a keyword";
}
},
DEPRECATED_KEYWORD {
String forHumans() {
return "a no longer supported keyword";
}
},
OPERATOR {
String forHumans() {
return "an operator";
}
},
IDENTIFIER {
String forHumans() {
return "an identifier";
}
},
UNKNOWN {
String forHumans() {
return "a token";
}
};
abstract String forHumans();
};
protected TokenClassification[] tokenClassMap = new TokenClassification[v3Parser.LAST_TOKEN + 1];
{
// Initiailization block.
// First, set them all to UNKNOWN
for (int index = 0; index <= v3Parser.LAST_TOKEN; index += 1) {
tokenClassMap[index] = TokenClassification.UNKNOWN;
}
// Then set them appropriately.
// If a token is added to the grammar, it will show up as UNKNOWN.
// If a token is removed from the grammar, the corresponding initialization
// will fail to compile (which is the earliest we could detect the problem).
// Keywords:
tokenClassMap[v3Parser.ABSTRACT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.ASSERT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.ATTRIBUTE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.BIND] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.BOUND] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.BREAK] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.CLASS] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.CONTINUE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.DELETE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.FALSE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.FOR] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.FUNCTION] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.IF] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.IMPORT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.INIT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.INSERT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.DEF] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.NEW] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.NON_WRITABLE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.NOT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.NULL] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.OVERRIDE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.PACKAGE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.POSTINIT] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.PRIVATE] = TokenClassification.DEPRECATED_KEYWORD;
tokenClassMap[v3Parser.PROTECTED] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.PUBLIC] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.PUBLIC_READABLE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.READABLE] = TokenClassification.DEPRECATED_KEYWORD;
tokenClassMap[v3Parser.RETURN] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.SUPER] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.SIZEOF] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.STATIC] = TokenClassification.DEPRECATED_KEYWORD;
tokenClassMap[v3Parser.THIS] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.THROW] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.TRY] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.TRUE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.VAR] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.WHILE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.AFTER] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.AND] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.AS] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.BEFORE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.CATCH] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.ELSE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.EXCLUSIVE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.EXTENDS] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.FINALLY] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.FIRST] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.FROM] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.IN] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.INDEXOF] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.INSTANCEOF] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.INTO] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.INVERSE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.LAST] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.LAZY] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.ON] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.OR] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.REPLACE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.REVERSE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.STEP] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.THEN] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.TYPEOF] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.WITH] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.WHERE] = TokenClassification.KEYWORD;
tokenClassMap[v3Parser.TWEEN] = TokenClassification.KEYWORD;
// Operators:
tokenClassMap[v3Parser.POUND] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.LPAREN] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.LBRACKET] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.PLUSPLUS] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SUBSUB] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.PIPE] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.DOTDOT] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.RPAREN] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.RBRACKET] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SEMI] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.COMMA] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.DOT] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.EQEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.EQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.GT] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.LT] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.LTGT] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.NOTEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.LTEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.GTEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.PLUS] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SUB] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.STAR] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SLASH] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.PERCENT] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.PLUSEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SUBEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.STAREQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SLASHEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.PERCENTEQ] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.COLON] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.QUES] = TokenClassification.OPERATOR;
tokenClassMap[v3Parser.SUCHTHAT] = TokenClassification.OPERATOR;
// Others:
tokenClassMap[v3Parser.IDENTIFIER] = TokenClassification.IDENTIFIER;
}
private TokenClassification classifyToken(Token t) {
TokenClassification result = TokenClassification.UNKNOWN;
int tokenType = t.getType();
if ((tokenType >= 0) && tokenType < tokenClassMap.length) {
result = tokenClassMap[tokenType];
}
return result;
}
protected String getParserName() {
return this.getClass().getName();
}
+ @Override
public String getErrorMessage(RecognitionException e, String[] tokenNames) {
java.util.List stack = getRuleInvocationStack(e, getParserName());
String stackTop = stack.get(stack.size()-1).toString();
String posDescription = stackPositionDescription(stackTop);
StringBuffer mb = new StringBuffer();
if (e instanceof MismatchedTokenException) {
MismatchedTokenException mte = (MismatchedTokenException) e;
mb.append("Sorry, I was trying to understand ");
mb.append(posDescription);
mb.append(" but I got confused when I saw ");
mb.append(getTokenErrorDisplay(e.token));
TokenClassification tokenClass = classifyToken(e.token);
if (tokenClass != TokenClassification.UNKNOWN && tokenClass != TokenClassification.OPERATOR) {
mb.append(" which is ");
mb.append(tokenClass.forHumans());
}
if (mte.expecting != Token.EOF) {
mb.append(".\n Perhaps you are missing a ");
mb.append("'" + tokenNames[mte.expecting]+"'");
}
} else if (e instanceof NoViableAltException) {
NoViableAltException nvae = (NoViableAltException) e;
mb.append("Sorry, I was trying to understand ");
mb.append(posDescription);
mb.append(" but I got confused when I saw ");
mb.append(getTokenErrorDisplay(e.token));
TokenClassification tokenClass = classifyToken(e.token);
if (tokenClass != TokenClassification.UNKNOWN && tokenClass != TokenClassification.OPERATOR) {
mb.append(" which is ");
mb.append(tokenClass.forHumans());
}
} else {
mb.append( super.getErrorMessage(e, tokenNames) );
}
return mb.toString();
}
/**
public String getTokenErrorDisplay(Token t) {
return t.toString();
}
**/
/** What is the error header, normally line/character position information? */
@Override
public void displayRecognitionError(String[] tokenNames, RecognitionException e) {
int pos = ((CommonToken)(e.token)).getStartIndex();
// String msg = getErrorMessage(e, tokenNames);
// System.err.println("ERROR: " + msg);
String msg = getErrorMessage(e, getFXTokenNames(tokenNames));
log.error(pos, MsgSym.MESSAGE_JAVAFX_GENERALERROR, msg);
}
protected String[] getFXTokenNames(String[] tokenNames) {
if (fxTokenNames != null) {
return fxTokenNames;
} else {
fxTokenNames = new String[tokenNames.length];
int count = 0;
for (String tokenName:tokenNames) {
String fxTokenName = tokenMap.get(tokenName);
if (fxTokenName == null) {
fxTokenNames[count] = tokenName;
} else {
fxTokenNames[count] = fxTokenName;
}
count++;
}
return fxTokenNames;
}
}
protected int pos(Token tok) {
//System.out.println("TOKEN: line: " + tok.getLine() + " char: " + tok.getCharPositionInLine() + " pos: " + ((CommonToken)tok).getStartIndex());
return ((CommonToken)tok).getStartIndex();
}
protected List noJFXTrees() {
return List.<JFXTree>nil();
}
+ @Override
protected Object getMissingSymbol(IntStream input,
RecognitionException e,
int expectedTokenType,
BitSet follow) {
if (expectedTokenType == Token.EOF) {
String tokenText = "<missing EOF>";
CommonToken t = new CommonToken(expectedTokenType, tokenText);
Token current = ((TokenStream)input).LT(1);
if ( current.getType() == Token.EOF ) {
current = ((TokenStream)input).LT(-1);
}
t.setLine(current.getLine());
t.setCharPositionInLine(current.getCharPositionInLine());
t.setChannel(DEFAULT_TOKEN_CHANNEL);
return t;
} else {
return super.getMissingSymbol(input, e, expectedTokenType, follow);
}
}
}
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java
index de419cdc8..b651e1b77 100644
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java
@@ -1,571 +1,570 @@
/*
* Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import java.util.IdentityHashMap;
import com.sun.tools.javac.jvm.ClassReader;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.List;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*;
import com.sun.tools.javafx.code.JavafxClassSymbol;
import com.sun.tools.javafx.code.JavafxSymtab;
import com.sun.tools.javafx.code.JavafxFlags;
import com.sun.tools.javafx.main.JavafxCompiler;
import static com.sun.tools.javafx.code.JavafxVarSymbol.*;
/** Provides operations to read a classfile into an internal
* representation. The internal representation is anchored in a
* JavafxClassSymbol which contains in its scope symbol representations
* for all other definitions in the classfile. Top-level Classes themselves
* appear as members of the scopes of PackageSymbols.
*
* We delegate actual classfile-reading to javac's ClassReader, and then
* translates the resulting ClassSymbol to JavafxClassSymbol, doing some
* renaming etc to make the resulting Symbols and Types match those produced
* by the parser. This munging is incomplete, and there are still places
* where the compiler needs to know of a class comes from the parser or a
* classfile; those places will hopefully become fewer.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavafxClassReader extends ClassReader {
protected static final Context.Key<ClassReader> backendClassReaderKey =
new Context.Key<ClassReader>();
private final JavafxDefs defs;
/** The raw class-reader, shared by the back-end. */
public ClassReader jreader;
private final Name functionClassPrefixName;
private Context ctx;
public static void registerBackendReader(final Context context, final ClassReader jreader) {
context.put(backendClassReaderKey, jreader);
}
public static void preRegister(final Context context, final ClassReader jreader) {
registerBackendReader(context, jreader);
preRegister(context);
}
public static void preRegister(final Context context) {
context.put(classReaderKey, new Context.Factory<ClassReader>() {
public JavafxClassReader make() {
JavafxClassReader reader = new JavafxClassReader(context, true);
reader.jreader = context.get(backendClassReaderKey);
return reader;
}
});
}
public static JavafxClassReader instance(Context context) {
JavafxClassReader instance = (JavafxClassReader) context.get(classReaderKey);
if (instance == null)
instance = new JavafxClassReader(context, true);
return instance;
}
/** Construct a new class reader, optionally treated as the
* definitive classreader for this invocation.
*/
protected JavafxClassReader(Context context, boolean definitive) {
super(context, definitive);
defs = JavafxDefs.instance(context);
functionClassPrefixName = names.fromString(JavafxSymtab.functionClassPrefix);
ctx = context;
}
public Name.Table getNames() {
return names;
}
/** Reassign names of classes that might have been loaded with
* their flat names. */
void fixupFullname (JavafxClassSymbol cSym, ClassSymbol jsymbol) {
if (cSym.fullname != jsymbol.fullname &&
cSym.owner.kind == PCK && jsymbol.owner.kind == TYP) {
cSym.owner.members().remove(cSym);
cSym.name = jsymbol.name;
ClassSymbol owner = enterClass(((ClassSymbol) jsymbol.owner).flatname);
cSym.owner = owner;
cSym.fullname = ClassSymbol.formFullName(cSym.name, owner);
}
}
public JavafxClassSymbol enterClass(ClassSymbol jsymbol) {
Name className = jsymbol.flatname;
boolean compound = className.endsWith(defs.interfaceSuffixName);
if (compound)
className = className.subName(0, className.len - defs.interfaceSuffixName.len);
JavafxClassSymbol cSym = (JavafxClassSymbol) enterClass(className);
//cSym.flags_field |= jsymbol.flags_field;
if (compound)
cSym.flags_field |= JavafxFlags.COMPOUND_CLASS;
else {
fixupFullname(cSym, jsymbol);
cSym.jsymbol = jsymbol;
}
return cSym;
}
/** Define a new class given its name and owner.
*/
@Override
public ClassSymbol defineClass(Name name, Symbol owner) {
ClassSymbol c = new JavafxClassSymbol(0, name, owner);
if (owner.kind == PCK)
assert classes.get(c.flatname) == null : c;
c.completer = this;
return c;
}
/* FIXME: The re-written class-reader doesn't translate annotations yet.
protected void attachAnnotations(final Symbol sym) {
int numAttributes = nextChar();
if (numAttributes != 0) {
ListBuffer<CompoundAnnotationProxy> proxies =
new ListBuffer<CompoundAnnotationProxy>();
for (int i = 0; i<numAttributes; i++) {
CompoundAnnotationProxy proxy = readCompoundAnnotation();
if (proxy.type.tsym == syms.proprietaryType.tsym)
sym.flags_field |= PROPRIETARY;
else {
proxies.append(proxy);
}
}
annotate.later(new JavafxAnnotationCompleter(sym, proxies.toList(), this));
}
}
static public class JavafxAnnotationCompleter extends AnnotationCompleter {
JavafxClassReader classReader;
public JavafxAnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l, ClassReader classReader) {
super(sym, l, classReader);
this.classReader = (JavafxClassReader)classReader;
}
// implement Annotate.Annotator.enterAnnotation()
public void enterAnnotation() {
JavaFileObject previousClassFile = classReader.currentClassFile;
try {
classReader.currentClassFile = classFile;
List<Attribute.Compound> newList = deproxyCompoundList(l);
JavafxSymtab javafxSyms = (JavafxSymtab)classReader.syms;
for (Attribute.Compound comp : newList) {
}
sym.attributes_field = ((sym.attributes_field == null)
? newList
: newList.prependList(sym.attributes_field));
} finally {
classReader.currentClassFile = previousClassFile;
}
}
}
*/
/** Map javac Type/Symbol to javafx Type/Symbol. */
IdentityHashMap<Object,Object> typeMap = new IdentityHashMap<Object,Object>();
/** Translate a List of raw JVM types to Javafx types. */
List<Type> translateTypes (List<Type> types) {
if (types == null)
return null;
List<Type> ts = (List<Type>) typeMap.get(types);
if (ts != null)
return ts;
ListBuffer<Type> rs = new ListBuffer<Type>();
for (List<Type> t = types;
t.tail != null;
t = t.tail)
rs.append(translateType(t.head));
ts = rs.toList();
typeMap.put(types, ts);
return ts;
}
/** Translate raw JVM type to Javafx type. */
Type translateType (Type type) {
if (type == null)
return null;
Type t = (Type) typeMap.get(type);
if (t != null)
return t;
switch (type.tag) {
case VOID:
t = syms.voidType;
break;
case BOOLEAN:
t = syms.booleanType;
break;
case CHAR:
t = syms.charType;
break;
case BYTE:
t = syms.byteType;
break;
case SHORT:
t = syms.shortType;
break;
case INT:
t = syms.intType;
break;
case LONG:
t = syms.longType;
break;
case DOUBLE:
t = syms.doubleType;
break;
case FLOAT:
t = syms.floatType;
break;
case TYPEVAR:
TypeVar tv = (TypeVar) type;
TypeVar tx = new TypeVar(null, (Type) null, (Type) null);
typeMap.put(type, tx); // In case of a cycle.
tx.bound = translateType(tv.bound);
tx.lower = translateType(tv.lower);
tx.tsym = new TypeSymbol(0, tv.tsym.name, tx, translateSymbol(tv.tsym.owner));
return tx;
case FORALL:
ForAll tf = (ForAll) type;
t = new ForAll(translateTypes(tf.tvars), translateType(tf.qtype));
break;
case WILDCARD:
WildcardType wt = (WildcardType) type;
t = new WildcardType(translateType(wt.type), wt.kind,
translateTypeSymbol(wt.tsym));
break;
case CLASS:
TypeSymbol tsym = type.tsym;
if (tsym instanceof ClassSymbol) {
if (tsym.name.endsWith(defs.interfaceSuffixName)) {
t = enterClass((ClassSymbol) tsym).type;
break;
}
final ClassType ctype = (ClassType) type;
if (ctype.isCompound()) {
t = types.makeCompoundType(translateTypes(ctype.interfaces_field), translateType(ctype.supertype_field));
break;
}
Name flatname = ((ClassSymbol) tsym).flatname;
Type deloc = defs.delocationize(flatname);
if (deloc != null) {
if (deloc == syms.intType || deloc == syms.doubleType || deloc == syms.booleanType) {
return deloc;
}
if (ctype.typarams_field != null && ctype.typarams_field.size() == 1) {
if (deloc == syms.objectType) {
return translateType(ctype.typarams_field.head);
}
if (deloc == ((JavafxSymtab) syms).javafx_SequenceType) {
Type tparam = translateType(ctype.typarams_field.head);
WildcardType tpType = new WildcardType(tparam, BoundKind.EXTENDS, tparam.tsym);
t = new ClassType(Type.noType, List.<Type>of(tpType), ((JavafxSymtab) syms).javafx_SequenceType.tsym);
break;
}
}
}
if (flatname.startsWith(functionClassPrefixName)
&& flatname != functionClassPrefixName) {
t = ((JavafxSymtab) syms).makeFunctionType(translateTypes(ctype.typarams_field));
break;
}
TypeSymbol sym = translateTypeSymbol(tsym);
ClassType ntype;
if (tsym.type == type)
ntype = (ClassType) sym.type;
else
ntype = new ClassType(Type.noType, List.<Type>nil(), sym) {
boolean completed = false;
@Override
public Type getEnclosingType() {
if (!completed) {
completed = true;
tsym.complete();
super.setEnclosingType(translateType(ctype.getEnclosingType()));
}
return super.getEnclosingType();
}
@Override
public void setEnclosingType(Type outer) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object t) {
return super.equals(t);
}
@Override
public int hashCode() {
return super.hashCode();
}
};
typeMap.put(type, ntype); // In case of a cycle.
ntype.typarams_field = translateTypes(type.getTypeArguments());
return ntype;
}
break;
case ARRAY:
t = new ArrayType(translateType(((ArrayType) type).elemtype), syms.arrayClass);
break;
case METHOD:
t = new MethodType(translateTypes(type.getParameterTypes()),
translateType(type.getReturnType()),
translateTypes(type.getThrownTypes()),
syms.methodClass);
break;
default:
t = type; // FIXME
}
typeMap.put(type, t);
return t;
}
TypeSymbol translateTypeSymbol(TypeSymbol tsym) {
if (tsym == syms.predefClass)
return tsym;
ClassSymbol csym = (ClassSymbol) tsym; // FIXME
return enterClass(csym);
}
Symbol translateSymbol(Symbol sym) {
if (sym == null)
return null;
Symbol s = (Symbol) typeMap.get(sym);
if (s != null)
return s;
if (sym instanceof PackageSymbol)
s = enterPackage(((PackageSymbol) sym).fullname);
else if (sym instanceof MethodSymbol) {
Name name = sym.name;
long flags = sym.flags_field;
Symbol owner = translateSymbol(sym.owner);
Type type = translateType(sym.type);
String nameString = name.toString();
int boundStringIndex = nameString.indexOf(JavafxDefs.boundFunctionDollarSuffix);
if (boundStringIndex != -1) {
// this is a bound function
// remove the bound suffix, and mark as bound
name = names.fromString(nameString.substring(0, boundStringIndex));
flags |= JavafxFlags.BOUND;
}
MethodSymbol m = new MethodSymbol(flags, name, type, owner);
((ClassSymbol) owner).members_field.enter(m);
s = m;
}
else
s = translateTypeSymbol((TypeSymbol) sym);
typeMap.put(sym, s);
return s;
}
@Override
public void complete(Symbol sym) throws CompletionFailure {
if (jreader.sourceCompleter == null)
jreader.sourceCompleter = JavafxCompiler.instance(ctx);
if (sym instanceof PackageSymbol) {
PackageSymbol psym = (PackageSymbol) sym;
PackageSymbol jpackage;
if (psym == syms.unnamedPackage)
jpackage = jreader.syms.unnamedPackage;
else
jpackage = jreader.enterPackage(psym.fullname);
jpackage.complete();
if (psym.members_field == null) psym.members_field = new Scope(psym);
for (Scope.Entry e = jpackage.members_field.elems;
e != null; e = e.sibling) {
if (e.sym instanceof ClassSymbol) {
ClassSymbol jsym = (ClassSymbol) e.sym;
if (jsym.name.endsWith(defs.interfaceSuffixName))
continue;
JavafxClassSymbol csym = enterClass(jsym);
psym.members_field.enter(csym);
csym.classfile = jsym.classfile;
csym.jsymbol = jsym;
}
}
} else {
sym.owner.complete();
JavafxClassSymbol csym = (JavafxClassSymbol) sym;
ClassSymbol jsymbol = csym.jsymbol;
csym.jsymbol = jsymbol = jreader.loadClass(csym.flatname);
fixupFullname(csym, jsymbol);
typeMap.put(jsymbol, csym);
jsymbol.classfile = ((ClassSymbol) sym).classfile;
ClassType ct = (ClassType)csym.type;
ClassType jt = (ClassType)jsymbol.type;
csym.members_field = new Scope(csym);
- //TODO: include annoations
- // csym.flags_field = flagsFromAnnotationsAndFlags(jsymbol);
- csym.flags_field = jsymbol.flags_field;
+ // flags are derived from flag bits and access modifier annoations
+ csym.flags_field = flagsFromAnnotationsAndFlags(jsymbol);
ct.typarams_field = translateTypes(jt.typarams_field);
ct.setEnclosingType(translateType(jt.getEnclosingType()));
ct.supertype_field = translateType(jt.supertype_field);
ListBuffer<Type> interfaces = new ListBuffer<Type>();
Type iface = null;
if (jt.interfaces_field != null) { // true for ErrorType
for (List<Type> it = jt.interfaces_field;
it.tail != null;
it = it.tail) {
Type itype = it.head;
if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName)
csym.flags_field |= JavafxFlags.FX_CLASS;
else if (itype.tsym.name.endsWith(defs.interfaceSuffixName)) {
iface = itype;
iface.tsym.complete();
assert (csym.fullname.len + defs.interfaceSuffixName.len ==
((ClassSymbol) itype.tsym).fullname.len) &&
((ClassSymbol) itype.tsym).fullname.startsWith(csym.fullname);
csym.flags_field |= JavafxFlags.COMPOUND_CLASS;
}
else {
itype = translateType(itype);
interfaces.append(itype);
}
}
}
if (iface != null) {
for (List<Type> it = ((ClassType) iface.tsym.type).interfaces_field;
it.tail != null;
it = it.tail) {
Type itype = it.head;
if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName)
csym.flags_field |= JavafxFlags.FX_CLASS;
else {
itype = translateType(itype);
interfaces.append(itype);
csym.addSuperType(itype);
}
}
}
ct.interfaces_field = interfaces.toList();
// Now translate the members.
// Do an initial "reverse" pass so we copy the order.
List<Symbol> syms = List.nil();
for (Scope.Entry e = jsymbol.members_field.elems;
e != null; e = e.sibling) {
if ((e.sym.flags_field & SYNTHETIC) != 0)
continue;
syms = syms.prepend(e.sym);
}
handleSyms:
for (List<Symbol> l = syms; l.nonEmpty(); l=l.tail) {
Name name = l.head.name;
long flags = flagsFromAnnotationsAndFlags(l.head);
if ((flags & PRIVATE) != 0)
continue;
boolean sawSourceNameAnnotation = false;
JavafxSymtab javafxSyms = (JavafxSymtab) this.syms;
for (Attribute.Compound a : l.head.getAnnotationMirrors()) {
if (a.type.tsym.flatName() == javafxSyms.javafx_staticAnnotationType.tsym.flatName()) {
flags |= Flags.STATIC;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_defAnnotationType.tsym.flatName()) {
flags |= JavafxFlags.IS_DEF;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_publicReadableAnnotationType.tsym.flatName()) {
flags |= JavafxFlags.PUBLIC_READABLE;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_inheritedAnnotationType.tsym.flatName()) {
continue handleSyms;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_sourceNameAnnotationType.tsym.flatName()) {
Attribute aa = a.member(name.table.value);
Object sourceName = aa.getValue();
if (sourceName instanceof String) {
name = names.fromString((String) sourceName);
sawSourceNameAnnotation = true;
}
}
}
if (l.head instanceof MethodSymbol) {
if (! sawSourceNameAnnotation &&
(name == defs.runMethodName || name == defs.initializeName ||
name == defs.postInitName || name == defs.userInitName ||
name == defs.addTriggersName ||
name == names.clinit ||
name.startsWith(defs.attributeGetPrefixName) ||
name.startsWith(defs.applyDefaultsPrefixName) ||
name.endsWith(defs.implFunctionSuffixName)))
continue;
// This should be merged with translateSymbol.
// But that doesn't work for some unknown reason. FIXME
Type type = translateType(l.head.type);
String nameString = name.toString();
int boundStringIndex = nameString.indexOf(JavafxDefs.boundFunctionDollarSuffix);
if (boundStringIndex != -1) {
// this is a bound function
// remove the bound suffix, and mark as bound
name = names.fromString(nameString.substring(0, boundStringIndex));
flags |= JavafxFlags.BOUND;
}
MethodSymbol m = new MethodSymbol(flags, name, type, csym);
csym.members_field.enter(m);
}
else if (l.head instanceof VarSymbol) {
Type type = translateType(l.head.type);
VarSymbol v = new VarSymbol(flags, name, type, csym);
csym.members_field.enter(v);
}
else {
l.head.flags_field = flags;
csym.members_field.enter(translateSymbol(l.head));
}
}
}
}
private long flagsFromAnnotationsAndFlags(Symbol sym) {
long initialFlags = sym.flags_field;
long nonAccessFlags = initialFlags & ~JavafxFlags.AccessFlags;
long accessFlags = initialFlags & JavafxFlags.AccessFlags;
JavafxSymtab javafxSyms = (JavafxSymtab) this.syms;
for (Attribute.Compound a : sym.getAnnotationMirrors()) {
if (a.type.tsym.flatName() == javafxSyms.javafx_privateAnnotationType.tsym.flatName()) {
accessFlags = Flags.PRIVATE;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_protectedAnnotationType.tsym.flatName()) {
accessFlags = Flags.PROTECTED;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_packageAnnotationType.tsym.flatName()) {
accessFlags = JavafxFlags.PACKAGE_ACCESS;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_publicAnnotationType.tsym.flatName()) {
accessFlags = Flags.PUBLIC;
} else if (a.type.tsym.flatName() == javafxSyms.javafx_scriptPrivateAnnotationType.tsym.flatName()) {
accessFlags = 0L;
}
}
return nonAccessFlags | accessFlags;
}
}
| false | false | null | null |
diff --git a/integration-tests/CT/css-services-test-suite/discover-services-728/src/main/java/org/societies/integration/test/ct/discoverservices/NominalTestCaseUpperTester.java b/integration-tests/CT/css-services-test-suite/discover-services-728/src/main/java/org/societies/integration/test/ct/discoverservices/NominalTestCaseUpperTester.java
index 60ecee0be..e38eca9d1 100644
--- a/integration-tests/CT/css-services-test-suite/discover-services-728/src/main/java/org/societies/integration/test/ct/discoverservices/NominalTestCaseUpperTester.java
+++ b/integration-tests/CT/css-services-test-suite/discover-services-728/src/main/java/org/societies/integration/test/ct/discoverservices/NominalTestCaseUpperTester.java
@@ -1,135 +1,137 @@
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.integration.test.ct.discoverservices;
import static org.junit.Assert.fail;
import java.util.List;
import java.util.concurrent.Future;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.societies.api.schema.servicelifecycle.model.Service;
+import org.societies.api.schema.servicelifecycle.model.ServiceType;
/**
* Upper Tester for the Nominal Test Case of #728
*
* @author <a href="mailto:[email protected]">Sancho Rêgo</a> (PTIN)
*
*/
public class NominalTestCaseUpperTester {
private static Logger LOG = LoggerFactory.getLogger(NominalTestCaseUpperTester.class);
/**
* The other node's JID
*/
private static final String REMOTEJID = "othercss.societies.local";
/**
* Test case number
*/
public static int testCaseNumber;
/**
* This method is called only one time, at the very beginning of the process
* (after the constructor) in order to initialize the process.
*/
@BeforeClass
public static void initialization() {
LOG.info("[#728] Initialization");
LOG.info("[#728] Prerequisite: The CSS is created");
LOG.info("[#728] Prerequisite: The user is logged to the CSS");
}
/**
* This method is called before every @Test methods.
*/
@Before
public void setUp() {
if(LOG.isDebugEnabled()) LOG.debug("[#728] NominalTestCaseUpperTester::setUp");
}
/**
* This method is called after every @Test methods
*/
@After
public void tearDown() {
if(LOG.isDebugEnabled()) LOG.debug("[#728] NominalTestCaseUpperTester:: teardown");
}
/**
* Do the test
*/
@Test
public void testDiscoverServices(){
LOG.info("[#728] Testing Remote Discover Services");
try{
//STEP 1: Get the Services
if(LOG.isDebugEnabled()) LOG.debug("[#728] Getting remote Services from " + REMOTEJID);
Future<List<Service>> asyncResult = TestCase728.getServiceDiscovery().getServices(REMOTEJID);
List<Service> resultList = asyncResult.get();
//STEP 2: Check if we retrieved two services
if(LOG.isDebugEnabled()) LOG.debug("[#728] Retrieved " + resultList.size() + " services.");
- Assert.assertEquals("[#728] Checking if we retrieved exactly two services!", 2, resultList.size());
+ Assert.assertEquals("[#728] Checking if we retrieved exactly three services!", 3, resultList.size());
//STEP 3 & 4: Check if our current node isn't othercss.societies.local
String localJid = TestCase728.getCommManager().getIdManager().getThisNetworkNode().getJid();
if(LOG.isDebugEnabled()) LOG.debug("[#728] Current JID is " + localJid);
Assert.assertFalse("[#728] Current JID is same as Remote Jid!", localJid.equals(REMOTEJID));
//STEP 5, 6, 7 & 8
for(Service service: resultList){
String serviceJid = service.getServiceInstance().getXMPPNode();
if(LOG.isDebugEnabled()) LOG.debug("[#728] Service " + service.getServiceName() + " has jid " + serviceJid);
- Assert.assertEquals("[#728] Service JID is not the correct one!", REMOTEJID, serviceJid);
- Assert.assertTrue(service.getServiceName().equals("Calculator Service") || service.getServiceName().equals("FortuneCookie Service"));
+ if(!service.getServiceType().equals(ServiceType.DEVICE))
+ Assert.assertEquals("[#728] Service JID is not the correct one!", REMOTEJID, serviceJid);
+ Assert.assertTrue(service.getServiceName().equals("Calculator Service") || service.getServiceName().equals("FortuneCookie Service") || service.getServiceName().equals("RFiD System"));
}
} catch(Exception ex){
LOG.error("Error while running test: " + ex);
ex.printStackTrace();
fail("Exception occured");
}
}
}
diff --git a/platform-infrastructure/service-lifecycle/service-discovery/src/main/java/org/societies/platform/servicelifecycle/serviceRegistry/model/RegistryEntry.java b/platform-infrastructure/service-lifecycle/service-discovery/src/main/java/org/societies/platform/servicelifecycle/serviceRegistry/model/RegistryEntry.java
index 83723e1f9..b77094c24 100644
--- a/platform-infrastructure/service-lifecycle/service-discovery/src/main/java/org/societies/platform/servicelifecycle/serviceRegistry/model/RegistryEntry.java
+++ b/platform-infrastructure/service-lifecycle/service-discovery/src/main/java/org/societies/platform/servicelifecycle/serviceRegistry/model/RegistryEntry.java
@@ -1,482 +1,482 @@
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.platform.servicelifecycle.serviceRegistry.model;
import java.io.Serializable;
import java.net.URI;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.eclipse.jetty.util.log.Log;
import org.societies.api.schema.servicelifecycle.model.Service;
import org.societies.api.schema.servicelifecycle.model.ServiceImplementation;
import org.societies.api.schema.servicelifecycle.model.ServiceInstance;
import org.societies.api.schema.servicelifecycle.model.ServiceResourceIdentifier;
import org.societies.api.schema.servicelifecycle.model.ServiceStatus;
import org.societies.api.schema.servicelifecycle.model.ServiceType;
/**
* This is the Class accepted by the ServiceRegistry when a service wants to
* register. This Object contains attributes used to retrieve services shared
* from/to a CSS/CIS and also information to retrieve organization that has
* developed the service.
*
* @author apanazzolo
* @version 1.0
* @created 06-dic-2011 12.12.57
*/
@Entity
@Table(name = "RegistryEntry")
public class RegistryEntry implements Serializable {
/**
*
*/
private static final long serialVersionUID = 9064750069927104572L;
// private String serviceIdentifier;
// private ServiceResourceIdentifier serviceIdentifier;
private ServiceResourceIdentifierDAO serviceIdentifier;
/**
* the service endPoint.
*/
private String serviceEndPoint;
/**
* An alias name for the service
*/
private String serviceName;
/**
* A "long" description of the service
*/
private String serviceDescription;
/**
* The signature of the author
*/
private String authorSignature;
private String serviceType;
private String serviceLocation;
private ServiceInstanceDAO serviceInstance;
private String serviceStatus;
private String privacyPolicy;
private String securityPolicy;
private String serviceCategory;
private String contextSource;
/**
* @param serviceEndpointURI
* @param cSSIDInstalled
* @param hash
* @param lifetime
* @param serviceName
* @param serviceDescription
* @param authorSignature
* @param serviceInstance
*/
public RegistryEntry(ServiceResourceIdentifier serviceIdentifier,
String serviceEndPoint, String serviceName,
String serviceDescription, String authorSignature, String privacyPolicy, String securityPolicy, String serviceCategory,
ServiceType type, String location, String contextSource,
ServiceInstance serviceInstance, ServiceStatus serviceStatus) {
super();
this.serviceIdentifier = new ServiceResourceIdentifierDAO(
serviceIdentifier.getIdentifier().toString(),
serviceIdentifier.getServiceInstanceIdentifier());
this.serviceName = serviceName;
this.serviceDescription = serviceDescription;
this.authorSignature = authorSignature;
this.serviceEndPoint = serviceEndPoint;
this.privacyPolicy = privacyPolicy;
this.securityPolicy = securityPolicy;
this.serviceCategory = serviceCategory;
this.contextSource = contextSource;
this.serviceType = type.toString();
this.serviceLocation = location;
this.serviceStatus = serviceStatus.toString();
this.serviceInstance = new ServiceInstanceDAO(
serviceInstance.getFullJid(), serviceInstance.getCssJid(), serviceInstance.getParentJid(),serviceInstance.getXMPPNode(),
new ServiceResourceIdentifierDAO(serviceInstance.getParentIdentifier().getIdentifier().toString(),
serviceInstance.getParentIdentifier().getServiceInstanceIdentifier()),
new ServiceImplementationDAO(serviceInstance.getServiceImpl()
.getServiceNameSpace(), serviceInstance
.getServiceImpl().getServiceProvider(), serviceInstance
.getServiceImpl().getServiceVersion(),serviceInstance
.getServiceImpl().getServiceClient()));
}
public RegistryEntry() {
super();
}
@Column(name = "ServiceName")
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
- @Column(name = "ServiceDescription")
+ @Column(name = "ServiceDescription", length = 1024)
public String getServiceDescription() {
return serviceDescription;
}
public void setServiceDescription(String serviceDescription) {
this.serviceDescription = serviceDescription;
}
@Column(name = "AuthorSignature")
public String getAuthorSignature() {
return authorSignature;
}
public void setAuthorSignature(String authorSignature) {
this.authorSignature = authorSignature;
}
@Column(name = "PrivacyPolicy")
public String getPrivacyPolicy() {
return privacyPolicy;
}
public void setPrivacyPolicy(String privacyPolicy) {
this.privacyPolicy = privacyPolicy;
}
@Column(name = "SecurityPolicy")
public String getSecurityPolicy() {
return securityPolicy;
}
public void setSecurityPolicy(String securityPolicy) {
this.securityPolicy = securityPolicy;
}
@Column(name = "ServiceCategory")
public String getServiceCategory() {
return serviceCategory;
}
public void setServiceCategory(String serviceCategory) {
this.serviceCategory = serviceCategory;
}
@Column(name = "ContextSource")
public String getContextSource() {
return contextSource;
}
public void setContextSource(String contextSource) {
this.contextSource = contextSource;
}
// @Column(name = "ServiceIdentifier")
// @Id
// @Target(value = ServiceResourceIdentifierDAO.class)
@EmbeddedId
public ServiceResourceIdentifierDAO getServiceIdentifier() {
return this.serviceIdentifier;
}
public void setServiceIdentifier(
ServiceResourceIdentifierDAO serviceIdentifier) {
this.serviceIdentifier = serviceIdentifier;
}
public Service createServiceFromRegistryEntry() {
Service returnedService = null;
try {
ServiceType tmpServiceType = null;
String tmpServiceLocation = null;
ServiceStatus tmpServiceStatus = null;
/*
* Retrieve the service type from the service and create the
* appropriate enumeration type
*/
if (serviceType.equals(ServiceType.THIRD_PARTY_CLIENT.toString())) {
tmpServiceType = ServiceType.THIRD_PARTY_CLIENT;
} else {
if (serviceType.equals(ServiceType.THIRD_PARTY_SERVER.toString())) {
tmpServiceType = ServiceType.THIRD_PARTY_SERVER;
} else {
if (serviceType.equals(ServiceType.THIRD_PARTY_WEB.toString())) {
tmpServiceType = ServiceType.THIRD_PARTY_WEB;
} else {
if (serviceType.equals(ServiceType.DEVICE.toString())) {
tmpServiceType = ServiceType.DEVICE;
} else {
if (serviceType.equals(ServiceType.THIRD_PARTY_ANDROID.toString())) {
tmpServiceType = ServiceType.THIRD_PARTY_ANDROID;
}
}
}
}
}
/* Same as before but for service location */
/*
if (serviceLocation.equals(ServiceLocation.LOCAL.toString())) {
tmpServiceLocation = ServiceLocation.LOCAL;
} else {
if (serviceLocation.equals(ServiceLocation.REMOTE.toString())) {
tmpServiceLocation = ServiceLocation.REMOTE;
}
}
*/
tmpServiceLocation = serviceLocation;
/* Same but for the serviceStatus */
if (serviceStatus.equals(ServiceStatus.STARTED.toString())) {
tmpServiceStatus = ServiceStatus.STARTED;
} else {
if (serviceStatus.equals(ServiceStatus.STOPPED.toString())) {
tmpServiceStatus = ServiceStatus.STOPPED;
} else {
tmpServiceStatus = ServiceStatus.UNAVAILABLE;
}
}
returnedService = new Service();
returnedService.setAuthorSignature(this.authorSignature);
returnedService.setServiceDescription(this.serviceDescription);
returnedService.setServiceEndpoint(serviceEndPoint);
returnedService.setPrivacyPolicy(this.privacyPolicy);
returnedService.setContextSource(this.contextSource);
returnedService.setSecurityPolicy(this.securityPolicy);
returnedService.setServiceCategory(this.serviceCategory);
ServiceInstance si = new ServiceInstance();
si.setFullJid(this.serviceInstance.getFullJid());
si.setCssJid(this.serviceInstance.getCssJid());
si.setParentJid(this.serviceInstance.getParentJid());
si.setXMPPNode(this.serviceInstance.getXMPPNode());
ServiceResourceIdentifier parentIdentifier = new ServiceResourceIdentifier();
parentIdentifier.setIdentifier(new URI(this.serviceInstance.getParentIdentifier().getIdentifier()));
parentIdentifier.setServiceInstanceIdentifier(this.serviceInstance.getParentIdentifier().getInstanceId());
si.setParentIdentifier(parentIdentifier);
ServiceImplementation servImpl = new ServiceImplementation();
servImpl.setServiceNameSpace(this.serviceInstance.getServiceImpl()
.getServiceNameSpace());
servImpl.setServiceProvider(this.serviceInstance.getServiceImpl()
.getServiceProvider());
servImpl.setServiceVersion(this.serviceInstance.getServiceImpl()
.getServiceVersion());
servImpl.setServiceClient(this.serviceInstance.getServiceImpl().getServiceClient());
si.setServiceImpl(servImpl);
returnedService.setServiceInstance(si);
returnedService.setServiceLocation(tmpServiceLocation);
returnedService.setServiceName(serviceName);
returnedService.setServiceStatus(tmpServiceStatus);
returnedService.setServiceType(tmpServiceType);
ServiceResourceIdentifier serviceResourceIdentifier = new ServiceResourceIdentifier();
serviceResourceIdentifier.setIdentifier(new URI(this
.getServiceIdentifier().getIdentifier()));
serviceResourceIdentifier.setServiceInstanceIdentifier(this
.getServiceIdentifier().getInstanceId());
returnedService.setServiceIdentifier(serviceResourceIdentifier);
} catch (Exception e) {
e.printStackTrace();
}
return returnedService;
}
@Column(name = "ServiceType")
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
- @Column(name = "ServiceLocation")
+ @Column(name = "ServiceLocation", length = 512)
public String getServiceLocation() {
return serviceLocation;
}
public void setServiceLocation(String serviceLocation) {
this.serviceLocation = serviceLocation;
}
@Column(name = "ServiceEndPoint")
public String getServiceEndPoint() {
return serviceEndPoint;
}
public void setServiceEndPoint(String serviceEndPoint) {
this.serviceEndPoint = serviceEndPoint;
}
@OneToOne(cascade = CascadeType.ALL)
public ServiceInstanceDAO getServiceInstance() {
return serviceInstance;
}
public void setServiceInstance(ServiceInstanceDAO serviceInstance) {
this.serviceInstance = serviceInstance;
}
@Column(name = "ServiceStatus")
public String getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public void updateRegistryEntry(Service service) {
if (service.getServiceCategory() != null) {
this.setServiceCategory(service.getServiceCategory());
}
if (service.getAuthorSignature() != null) {
this.setAuthorSignature(service.getAuthorSignature());
}
if (service.getServiceDescription() != null) {
this
.setServiceDescription(service.getServiceDescription());
}
if (service.getServiceEndpoint() != null) {
this.setServiceEndPoint(service.getServiceEndpoint());
}
if (service.getServiceInstance() != null) {
if (service.getServiceInstance().getFullJid() != null) {
this.getServiceInstance().setFullJid(
service.getServiceInstance().getFullJid());
}
if (service.getServiceInstance().getCssJid() != null) {
this.getServiceInstance().setCssJid(
service.getServiceInstance().getCssJid());
}
if (service.getServiceInstance().getParentJid() != null) {
this.getServiceInstance().setParentJid(
service.getServiceInstance().getParentJid());
}
if (service.getServiceInstance().getXMPPNode() != null) {
this.getServiceInstance().setXMPPNode(
service.getServiceInstance().getXMPPNode());
}
if(service.getServiceInstance().getParentIdentifier() != null){
this.getServiceInstance().getParentIdentifier().setIdentifier(service.getServiceInstance().getParentIdentifier().getIdentifier().toString());
this.getServiceInstance().getParentIdentifier().setInstanceId(service.getServiceInstance().getParentIdentifier().getServiceInstanceIdentifier());
}
if (service.getServiceInstance().getServiceImpl() != null) {
if (service.getServiceInstance().getServiceImpl()
.getServiceNameSpace() != null) {
this
.getServiceInstance()
.getServiceImpl()
.setServiceNameSpace(
service.getServiceInstance()
.getServiceImpl()
.getServiceNameSpace());
}
if (service.getServiceInstance().getServiceImpl()
.getServiceProvider() != null) {
this
.getServiceInstance()
.getServiceImpl()
.setServiceProvider(
service.getServiceInstance()
.getServiceImpl()
.getServiceProvider());
}
if (service.getServiceInstance().getServiceImpl()
.getServiceVersion() != null) {
this
.getServiceInstance()
.getServiceImpl()
.setServiceVersion(
service.getServiceInstance()
.getServiceImpl()
.getServiceVersion());
}
if (service.getServiceInstance().getServiceImpl()
.getServiceClient() != null) {
this
.getServiceInstance()
.getServiceImpl()
.setServiceClient(
service.getServiceInstance()
.getServiceImpl()
.getServiceClient());
}
}
}
if (service.getServiceLocation()!=null){
this.setServiceLocation(service.getServiceLocation());
}
if (service.getServiceName()!=null){
this.setServiceName(service.getServiceName());
}
if (service.getServiceStatus()!=null){
this.setServiceStatus(service.getServiceStatus().toString());
}
if (service.getServiceType()!=null){
this.setServiceType(service.getServiceType().toString());
}
if (service.getPrivacyPolicy() != null) {
this.setPrivacyPolicy(service.getPrivacyPolicy());
}
if (service.getSecurityPolicy() != null) {
this.setSecurityPolicy(service.getSecurityPolicy());
}
if (service.getContextSource() != null) {
this.setContextSource(service.getContextSource());
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/mikera/vectorz/ArrayVector.java b/src/main/java/mikera/vectorz/ArrayVector.java
index 9e724aff..e907170f 100644
--- a/src/main/java/mikera/vectorz/ArrayVector.java
+++ b/src/main/java/mikera/vectorz/ArrayVector.java
@@ -1,450 +1,450 @@
package mikera.vectorz;
import java.nio.DoubleBuffer;
import java.util.Arrays;
import mikera.vectorz.impl.ArrayIndexScalar;
import mikera.vectorz.impl.ArraySubVector;
import mikera.vectorz.impl.JoinedArrayVector;
import mikera.vectorz.util.DoubleArrays;
import mikera.vectorz.util.VectorzException;
/**
* Base class for vectors backed by a double[] array.
*
* The double array can be directly accessed for performance purposes
*
* @author Mike
*/
@SuppressWarnings("serial")
public abstract class ArrayVector extends AVector {
public abstract double[] getArray();
public abstract int getArrayOffset();
/**
* Returns a vector referencing a sub-vector of the current vector
*
* @param offset
* @param length
* @return
*/
public ArraySubVector subVector(int offset, int length) {
int len=this.length();
if ((offset + length) > len)
throw new IndexOutOfBoundsException("Upper bound " + len
+ " breached:" + (offset + length));
if (offset < 0)
throw new IndexOutOfBoundsException("Lower bound breached:"
+ offset);
return new ArraySubVector(this, offset, length);
}
@Override
public AScalar slice(int position) {
assert((position>=0) && (position<length()));
return new ArrayIndexScalar(getArray(),getArrayOffset()+position);
}
public boolean isPackedArray() {
return (getArrayOffset()==0)&&(length()==getArray().length);
}
@Override
public boolean isView() {
// ArrayVector is usually a view
return true;
}
@Override
public void toDoubleBuffer(DoubleBuffer dest) {
dest.put(getArray(),getArrayOffset(),length());
}
@Override
public void copyTo(double[] data, int offset) {
System.arraycopy(getArray(), getArrayOffset(), data, offset, length());
}
@Override
public void fillRange(int offset, int length, double value) {
- assert ((offset>=0)||((offset+length)<=length()));
+ assert ((offset>=0)&&(length>=0)&&((offset+length)<=length()));
double[] arr=getArray();
int off=getArrayOffset();
Arrays.fill(arr, off+offset, off+offset+length, value);
}
@Override
public void set(AVector a) {
assert(a.length()==length());
a.copyTo(getArray(),getArrayOffset());
}
@Override
public void set(AVector a, int offset) {
assert(offset>=0);
assert(offset+length()<=a.length());
a.copyTo(offset, this, 0, length());
}
@Override
public void set(int offset, double[] data, int dataOffset, int length) {
System.arraycopy(data, dataOffset, getArray(), getArrayOffset()+offset, length);
}
@Override
public void setElements(double[] values, int offset, int length) {
assert(length==this.length());
System.arraycopy(values, offset, getArray(), getArrayOffset(), length);
}
@Override
public void getElements(double[] dest, int offset) {
System.arraycopy(getArray(), getArrayOffset(), dest, offset, length());
}
@Override
public void add(AVector src) {
if (src instanceof ArrayVector) {
add ((ArrayVector)src,0);
return;
}
int length=length();
src.addToArray(0,getArray(),getArrayOffset(),length);
}
public void add(ArrayVector v) {
assert(length()==v.length());
add(v,0);
}
@Override
public void add(AVector src, int srcOffset) {
if (src instanceof ArrayVector) {
add ((ArrayVector)src,srcOffset);
return;
}
int length=length();
src.addToArray(srcOffset,getArray(),getArrayOffset(),length);
}
@Override
public void add(int offset, AVector src) {
if (src instanceof ArrayVector) {
add (offset, (ArrayVector)src);
return;
}
int length=src.length();
src.addToArray(0,getArray(),getArrayOffset()+offset,length);
}
public void add(int offset, ArrayVector src) {
int length=src.length();
DoubleArrays.add(src.getArray(), src.getArrayOffset(), getArray(), offset+getArrayOffset(), length);
}
public void add(int offset, ArrayVector src, int srcOffset, int length) {
DoubleArrays.add(src.getArray(), src.getArrayOffset()+srcOffset, getArray(), offset+getArrayOffset(), length);
}
@Override
public void addMultiple(AVector v, double factor) {
if (v instanceof ArrayVector) {
addMultiple ((ArrayVector)v,factor);
return;
}
int length=length();
v.addMultipleToArray(factor,0,getArray(),getArrayOffset(),length);
}
@Override
public void scaleAdd(double factor, double constant) {
DoubleArrays.scaleAdd(getArray(), getArrayOffset(), length(), factor, constant);
}
@Override
public void add(double constant) {
DoubleArrays.add(getArray(), getArrayOffset(), length(), constant);
}
@Override
public void addProduct(AVector a, int aOffset, AVector b, int bOffset, double factor) {
int length=length();
double[] array=getArray();
int offset=getArrayOffset();
a.addProductToArray(factor, aOffset, b, bOffset, array, offset, length);
}
@Override
public void addToArray(int offset, double[] array, int arrayOffset, int length) {
double[] data=getArray();
int dataOffset=getArrayOffset()+offset;
for (int i=0; i<length; i++) {
array[i+arrayOffset]+=data[i+dataOffset];
}
}
@Override public void addProduct(AVector a, AVector b, double factor) {
int len=length();
assert(len==a.length());
assert(len==b.length());
double[] array=getArray();
int offset=getArrayOffset();
a.addProductToArray(factor,0,b,0,array,offset,len);
}
@Override
public void addMultipleToArray(double factor,int offset, double[] array, int arrayOffset, int length) {
double[] data=getArray();
int dataOffset=getArrayOffset()+offset;
for (int i=0; i<length; i++) {
array[i+arrayOffset]+=factor*data[i+dataOffset];
}
}
@Override
public void addProductToArray(double factor, int offset, AVector other,int otherOffset, double[] array, int arrayOffset, int length) {
if (other instanceof ArrayVector) {
addProductToArray(factor,offset,(ArrayVector)other,otherOffset,array,arrayOffset,length);
return;
}
assert(offset>=0);
assert(offset+length<=length());
double[] thisArray=getArray();
offset+=getArrayOffset();
for (int i=0; i<length; i++) {
array[i+arrayOffset]+=factor*thisArray[i+offset]*other.get(i+otherOffset);
}
}
@Override
public void addProductToArray(double factor, int offset, ArrayVector other,int otherOffset, double[] array, int arrayOffset, int length) {
assert(offset>=0);
assert(offset+length<=length());
double[] otherArray=other.getArray();
otherOffset+=other.getArrayOffset();
double[] thisArray=getArray();
offset+=getArrayOffset();
for (int i=0; i<length; i++) {
array[i+arrayOffset]+=factor*thisArray[i+offset]*otherArray[i+otherOffset];
}
}
public void add(ArrayVector src, int srcOffset) {
int length=length();
double[] vdata=src.getArray();
double[] data=getArray();
int offset=getArrayOffset();
int voffset=src.getArrayOffset()+srcOffset;
for (int i = 0; i < length; i++) {
data[offset+i] += vdata[voffset + i];
}
}
@Override
public void addAt(int i, double v) {
assert((i>=0)&&(i<length()));
double[] data=getArray();
int offset=getArrayOffset();
data[i+offset]+=v;
}
@Override
public void abs() {
int len=length();
double[] data=getArray();
int offset=getArrayOffset();
for (int i=0; i<len; i++) {
double val=data[i+offset];
if (val<0) data[i+offset]=-val;
}
}
@Override
public void applyOp(Op op) {
op.applyTo(getArray(), getArrayOffset(), length());
}
@Override
public double elementSum() {
return DoubleArrays.elementSum(getArray(), getArrayOffset(), length());
}
@Override
public long nonZeroCount() {
return DoubleArrays.nonZeroCount(getArray(), getArrayOffset(), length());
}
@Override
public void square() {
DoubleArrays.square(getArray(), getArrayOffset(), length());
}
/**
* Sets each component of the vector to its sign value (-1, 0 or 1)
*/
public void signum() {
DoubleArrays.signum(getArray(), getArrayOffset(), length());
}
@Override
public void multiply(AVector v) {
v.multiplyTo(getArray(), getArrayOffset());
}
@Override
public void multiply(double[] data, int offset) {
int len=length();
double[] cdata=getArray();
int coffset=getArrayOffset();
for (int i = 0; i < len; i++) {
data[i+offset]=cdata[i+coffset]*data[i+offset];
}
}
@Override
public void multiplyTo(double[] data, int offset) {
DoubleArrays.arraymultiply(getArray(), getArrayOffset(), data,offset,length());
}
@Override
public void divide(AVector v) {
v.divideTo(getArray(), getArrayOffset());
}
@Override
public void divide(double[] data, int offset) {
int len=length();
double[] cdata=getArray();
int coffset=getArrayOffset();
for (int i = 0; i < len; i++) {
set(i,cdata[i+coffset]/data[i+offset]);
}
}
@Override
public void divideTo(double[] data, int offset) {
DoubleArrays.arraydivide(getArray(), getArrayOffset(), data,offset,length());
}
@Override
public void copyTo(int start, AVector dest, int destOffset, int length) {
if (dest instanceof ArrayVector) {
copyTo(start,(ArrayVector)dest,destOffset,length);
return;
}
double[] src=getArray();
int off=getArrayOffset();
for (int i = 0; i < length; i++) {
dest.set(destOffset+i,src[off+start+i]);
}
}
public void copyTo(int offset, ArrayVector dest, int destOffset, int length) {
double[] src=getArray();
int off=getArrayOffset();
double[] dst=dest.getArray();
System.arraycopy(src, off+offset, dst, dest.getArrayOffset()+destOffset, length);
}
@Override
public void copyTo(int offset, double[] dest, int destOffset, int length) {
double[] src=getArray();
int off=getArrayOffset();
System.arraycopy(src, off+offset, dest, destOffset, length);
}
public void addMultiple(ArrayVector v, double factor) {
int vlength=v.length();
int length=length();
if (vlength != length) {
throw new Error("Source vector has different size: " + vlength);
}
double[] data=getArray();
int offset=getArrayOffset();
double[] vdata=v.getArray();
int voffset=v.getArrayOffset();
for (int i = 0; i < length; i++) {
data[offset+i] += vdata[voffset + i]*factor;
}
}
@Override
public double magnitudeSquared() {
int length=length();
double[] data=getArray();
int offset=getArrayOffset();
double result=0.0;
for (int i=0; i<length; i++) {
double v=data[offset+i];
result+=v*v;
}
return result;
}
@Override
public double magnitude() {
return Math.sqrt(magnitudeSquared());
}
@Override
public void fill(double value) {
int offset=getArrayOffset();
Arrays.fill(getArray(), offset, offset+length(),value);
}
@Override
public void pow(double exponent) {
int len=length();
double[] data=getArray();
int offset=getArrayOffset();
DoubleArrays.pow(data,offset,len,exponent);
}
@Override
public void reciprocal() {
DoubleArrays.reciprocal(getArray(),getArrayOffset(),length());
}
@Override
public void clamp(double min, double max) {
DoubleArrays.clamp(getArray(),getArrayOffset(),length(),min,max);
}
@Override
public void multiply(double factor) {
DoubleArrays.multiply(getArray(), getArrayOffset(),length(),factor);
}
@Override
public AVector join(AVector v) {
if (v instanceof ArrayVector) return join((ArrayVector)v);
if (v instanceof JoinedArrayVector) return join((JoinedArrayVector)v);
return super.join(v);
}
public AVector join(ArrayVector v) {
if ((v.getArray()==getArray())&&((getArrayOffset()+length())==v.getArrayOffset())) {
return Vectorz.wrap(getArray(),getArrayOffset(),length()+v.length());
}
return JoinedArrayVector.joinVectors(this, v);
}
public JoinedArrayVector join(JoinedArrayVector v) {
return JoinedArrayVector.wrap(this).join(v);
}
@Override
public void validate() {
int length=length();
double[] data=getArray();
int offset=getArrayOffset();
if ((offset<0)||(offset+length>data.length)) throw new VectorzException("ArrayVector out of bounds");
super.validate();
}
}
| true | false | null | null |
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaAttachmentHandler.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaAttachmentHandler.java
index 5e3bed266..bb166b2c6 100644
--- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaAttachmentHandler.java
+++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaAttachmentHandler.java
@@ -1,253 +1,245 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.bugzilla.core;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.PartBase;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.mylar.internal.tasks.core.WebClientUtil;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.IAttachmentHandler;
import org.eclipse.mylar.tasks.core.LocalAttachment;
import org.eclipse.mylar.tasks.core.RepositoryAttachment;
import org.eclipse.mylar.tasks.core.TaskRepository;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class BugzillaAttachmentHandler implements IAttachmentHandler {
public static final String POST_ARGS_ATTACHMENT_DOWNLOAD = "/attachment.cgi?id=";
public static final String POST_ARGS_ATTACHMENT_UPLOAD = "/attachment.cgi";// ?action=insert";//&bugid=";
private static final String VALUE_CONTENTTYPEMETHOD_MANUAL = "manual";
private static final String VALUE_ISPATCH = "1";
private static final String VALUE_ACTION_INSERT = "insert";
private static final String ATTRIBUTE_CONTENTTYPEENTRY = "contenttypeentry";
private static final String ATTRIBUTE_CONTENTTYPEMETHOD = "contenttypemethod";
private static final String ATTRIBUTE_ISPATCH = "ispatch";
private static final String ATTRIBUTE_DATA = "data";
private static final String ATTRIBUTE_COMMENT = "comment";
private static final String ATTRIBUTE_DESCRIPTION = "description";
private static final String ATTRIBUTE_BUGID = "bugid";
private static final String ATTRIBUTE_BUGZILLA_PASSWORD = "Bugzilla_password";
private static final String ATTRIBUTE_BUGZILLA_LOGIN = "Bugzilla_login";
private static final String ATTRIBUTE_ACTION = "action";
public void downloadAttachment(TaskRepository repository, AbstractRepositoryTask task, RepositoryAttachment attachment, File file, Proxy proxySettings) throws CoreException {
try {
downloadAttachment(repository.getUrl(), repository.getUserName(), repository.getPassword(), proxySettings, attachment.getId(), file, true);
} catch (Exception e) {
throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, 0, "could not download", e));
}
}
-
-// public void downloadAttachment(TaskRepository repository, AbstractRepositoryTask task, int attachmentId, File file, Proxy proxySettings) throws CoreException {
-// try {
-// downloadAttachment(repository.getUrl(), repository.getUserName(), repository.getPassword(), proxySettings, attachmentId, file, true);
-// } catch (Exception e) {
-// throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, 0, "could not download", e));
-// }
-// }
public void uploadAttachment(TaskRepository repository, AbstractRepositoryTask task, String comment, String description, File file, String contentType, boolean isPatch, Proxy proxySettings) throws CoreException {
try {
int bugId = Integer.parseInt(AbstractRepositoryTask.getTaskId(task.getHandleIdentifier()));
uploadAttachment(repository.getUrl(), repository.getUserName(), repository.getPassword(), bugId, comment, description, file, contentType, isPatch, proxySettings);
} catch (Exception e) {
throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, 0, "could not upload", e));
}
}
private boolean uploadAttachment(String repositoryUrl, String userName, String password, int bugReportID,
String comment, String description, File sourceFile, String contentType, boolean isPatch, Proxy proxySettings)
throws IOException {
// Note: The following debug code requires http commons-logging and
// commons-logging-api jars
// System.setProperty("org.apache.commons.logging.Log",
// "org.apache.commons.logging.impl.SimpleLog");
// System.setProperty("org.apache.commons.logging.simplelog.showdatetime",
// "true");
// System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire",
// "debug");
// System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient",
// "debug");
boolean uploadResult = true;
// Protocol.registerProtocol("https", new Protocol("https", new TrustAllSslProtocolSocketFactory(), 443));
HttpClient client = new HttpClient();
WebClientUtil.setupHttpClient(client, proxySettings, repositoryUrl);
PostMethod postMethod = new PostMethod(WebClientUtil.getRequestPath(repositoryUrl) + POST_ARGS_ATTACHMENT_UPLOAD);
// My understanding is that this option causes the client to first check
// with the server to see if it will in fact recieve the post before
// actually sending the contents.
postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
try {
List<PartBase> parts = new ArrayList<PartBase>();
parts.add(new StringPart(ATTRIBUTE_ACTION, VALUE_ACTION_INSERT));
parts.add(new StringPart(ATTRIBUTE_BUGZILLA_LOGIN, userName));
parts.add(new StringPart(ATTRIBUTE_BUGZILLA_PASSWORD, password));
parts.add(new StringPart(ATTRIBUTE_BUGID, String.valueOf(bugReportID)));
parts.add(new StringPart(ATTRIBUTE_DESCRIPTION, description));
parts.add(new StringPart(ATTRIBUTE_COMMENT, comment));
parts.add(new FilePart(ATTRIBUTE_DATA, sourceFile));
if (isPatch) {
parts.add(new StringPart(ATTRIBUTE_ISPATCH, VALUE_ISPATCH));
} else {
parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEMETHOD, VALUE_CONTENTTYPEMETHOD_MANUAL));
parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEENTRY, contentType));
}
postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[1]), postMethod.getParams()));
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
InputStreamReader reader = new InputStreamReader(postMethod.getResponseBodyAsStream(), postMethod
.getResponseCharSet());
BufferedReader bufferedReader = new BufferedReader(reader);
String newLine;
while ((newLine = bufferedReader.readLine()) != null) {
if (newLine.indexOf("Invalid Username Or Password") >= 0) {
throw new IOException(
"Invalid Username Or Password - Check credentials in Task Repositories view.");
}
// TODO: test for no comment and no description etc.
}
} else {
// MylarStatusHandler.log(HttpStatus.getStatusText(status),
// BugzillaRepositoryUtil.class);
uploadResult = false;
}
// } catch (HttpException e) {
// MylarStatusHandler.log("Attachment upload failed\n" +
// e.getMessage(), BugzillaRepositoryUtil.class);
// uploadResult = false;
} finally {
postMethod.releaseConnection();
}
return uploadResult;
}
public boolean uploadAttachment(LocalAttachment attachment, String uname, String password, Proxy proxySettings) throws IOException {
File file = new File(attachment.getFilePath());
if (!file.exists() || file.length() <= 0) {
return false;
}
return uploadAttachment(attachment.getReport().getRepositoryUrl(), uname, password, Integer.parseInt(attachment.getReport().getId()),
attachment.getComment(), attachment.getDescription(), file,
attachment.getContentType(), attachment.isPatch(), proxySettings);
}
private boolean downloadAttachment(String repositoryUrl, String userName, String password,
Proxy proxySettings, int id, File destinationFile, boolean overwrite) throws IOException,
GeneralSecurityException {
BufferedInputStream in = null;
FileOutputStream outStream = null;
try {
String url = repositoryUrl + POST_ARGS_ATTACHMENT_DOWNLOAD + id;
url = BugzillaServerFacade.addCredentials(url, userName, password);
URL downloadUrl = new URL(url);
URLConnection connection = WebClientUtil.getUrlConnection(downloadUrl, proxySettings, false);
if (connection != null) {
InputStream input = connection.getInputStream();
outStream = new FileOutputStream(destinationFile);
copyByteStream(input, outStream);
return true;
}
} finally {
try {
if (in != null)
in.close();
if (outStream != null)
outStream.close();
} catch (IOException e) {
BugzillaCorePlugin.log(new Status(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, IStatus.ERROR,
"Problem closing the stream", e));
}
}
return false;
}
private void copyByteStream(InputStream in, OutputStream out) throws IOException {
if (in != null && out != null) {
BufferedInputStream inBuffered = new BufferedInputStream(in);
int bufferSize = 1000;
byte[] buffer = new byte[bufferSize];
int readCount;
BufferedOutputStream fout = new BufferedOutputStream(out);
while ((readCount = inBuffered.read(buffer)) != -1) {
if (readCount < bufferSize) {
fout.write(buffer, 0, readCount);
} else {
fout.write(buffer);
}
}
fout.flush();
fout.close();
in.close();
}
}
}
| true | false | null | null |
diff --git a/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java b/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java
index 2c5947379..53583df44 100644
--- a/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java
+++ b/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java
@@ -1,197 +1,198 @@
/*******************************************************************************
* Copyright (c) 2001, 2008 Oracle 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:
* Oracle Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jst.jsf.ui.internal.validation;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jst.jsf.common.internal.JSPUtil;
import org.eclipse.jst.jsf.core.internal.JSFCorePlugin;
import org.eclipse.jst.jsf.core.jsfappconfig.JSFAppConfigUtils;
import org.eclipse.jst.jsf.validation.internal.IJSFViewValidator;
import org.eclipse.jst.jsf.validation.internal.JSFValidatorFactory;
import org.eclipse.jst.jsf.validation.internal.ValidationPreferences;
import org.eclipse.jst.jsp.core.internal.validation.JSPValidator;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
import org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator;
import org.eclipse.wst.validation.internal.provisional.core.IReporter;
import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
/**
* @author cbateman
*
*/
public class JSFValidator extends JSPValidator implements ISourceValidator
{
// TODO: should the source validator be a separate class in jsp.ui?
// problem with simple split off is that preference must also be split off
static final boolean DEBUG;
static
{
final String value = Platform
.getDebugOption("org.eclipse.jst.jsf.ui/validation"); //$NON-NLS-1$
DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$
}
private IDocument fDocument;
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator#connect(org.eclipse.jface.text.IDocument)
*/
public void connect(final IDocument document)
{
fDocument = document;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator#disconnect(org.eclipse.jface.text.IDocument)
*/
public void disconnect(final IDocument document)
{
// finished
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator#validate(org.eclipse.jface.text.IRegion,
* org.eclipse.wst.validation.internal.provisional.core.IValidationContext,
* org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
public void validate(final IRegion dirtyRegion,
final IValidationContext helper, final IReporter reporter)
{
if (DEBUG)
{
System.out.println("exec JSPSemanticsValidator.validateRegion"); //$NON-NLS-1$
}
final IFile file = getFile(helper);
- if (fDocument instanceof IStructuredDocument)
+ if (fDocument instanceof IStructuredDocument
+ && file != null)
{
final IStructuredDocument sDoc = (IStructuredDocument) fDocument;
final IStructuredDocumentRegion[] regions = sDoc
.getStructuredDocumentRegions(dirtyRegion.getOffset(),
dirtyRegion.getLength());
if (regions != null)
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(
this, reporter, file, prefs, model);
validator.validateView(file, regions, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
}
private IFile getFile(final IValidationContext helper)
{
final String[] uris = helper.getURIs();
final IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
if (uris.length > 0)
{
return wsRoot.getFile(new Path(uris[0]));
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jst.jsp.core.internal.validation.JSPValidator#validateFile(org.eclipse.core.resources.IFile,
* org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
@Override
protected void validateFile(final IFile file, final IReporter reporter)
{
if (shouldValidate(file))
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(this,
reporter, file, prefs, model);
validator.validateView(file, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
private boolean shouldValidate(final IFile file)
{
return (JSPUtil.isJSPContentType(file)
&& JSFAppConfigUtils.isValidJSFProject(file.getProject()));
}
}
| true | true | public void validate(final IRegion dirtyRegion,
final IValidationContext helper, final IReporter reporter)
{
if (DEBUG)
{
System.out.println("exec JSPSemanticsValidator.validateRegion"); //$NON-NLS-1$
}
final IFile file = getFile(helper);
if (fDocument instanceof IStructuredDocument)
{
final IStructuredDocument sDoc = (IStructuredDocument) fDocument;
final IStructuredDocumentRegion[] regions = sDoc
.getStructuredDocumentRegions(dirtyRegion.getOffset(),
dirtyRegion.getLength());
if (regions != null)
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(
this, reporter, file, prefs, model);
validator.validateView(file, regions, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
}
| public void validate(final IRegion dirtyRegion,
final IValidationContext helper, final IReporter reporter)
{
if (DEBUG)
{
System.out.println("exec JSPSemanticsValidator.validateRegion"); //$NON-NLS-1$
}
final IFile file = getFile(helper);
if (fDocument instanceof IStructuredDocument
&& file != null)
{
final IStructuredDocument sDoc = (IStructuredDocument) fDocument;
final IStructuredDocumentRegion[] regions = sDoc
.getStructuredDocumentRegions(dirtyRegion.getOffset(),
dirtyRegion.getLength());
if (regions != null)
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(
this, reporter, file, prefs, model);
validator.validateView(file, regions, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
}
|
diff --git a/MovingWater.java b/MovingWater.java
index bfb1fbb..61425d2 100644
--- a/MovingWater.java
+++ b/MovingWater.java
@@ -1,35 +1,38 @@
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class MovingWater here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MovingWater extends Actor
{
private int acts;
private int level;
public MovingWater() {
getImage().scale(1, 20);
getImage().setTransparency(100);
level = 10;
}
@Override
public void act() {
setLocation(40, 70);
- ++acts;
- if (acts == 1) {
- getImage().scale(820, getImage().getHeight() + 2);
- acts = 0;
- level += 2;
+ if (++acts == 1) {
+ setLevel(level + 2);
}
}
public int getLevel() {
return level;
- }
+ }
+
+ public void setLevel(int lvl) {
+ getImage().scale(820, lvl);
+ acts = 0;
+ level = lvl;
+ }
}
diff --git a/SkyscraperWorld.java b/SkyscraperWorld.java
index acea389..1413c73 100644
--- a/SkyscraperWorld.java
+++ b/SkyscraperWorld.java
@@ -1,443 +1,444 @@
import greenfoot.*;
import java.io.IOException;
public class SkyscraperWorld extends World {
private final int WINNING_LEVEL = 5;
private boolean addScore;
public Counter scoreCounter;
private Player player;
private Player.PlayerType playerType;
private int levelCompletePoints;
private int timeCount = 0;
private int currentLevel;
private Ground[] Ground;
private MovingBrick[] MovingBricks;
private MovingBrick2[] MovingBricks2;
private MovingBrickUp[] MovingBricksUp;
private Brick[] Bricks;
private Coin[] Coins;
private MovingWater movingWater;
//GreenfootSound backgroundMusic = new GreenfootSound("zeerstoer.mp3");
public SkyscraperWorld(Player.PlayerType type) {
super(80, 80, 10);
playerType = type;
currentLevel = 1;
levelCompletePoints = loadLevel(currentLevel);
//backgroundMusic.playLoop();
setPaintOrder(GameOverScreen.class, /*Overlay.class,*/ Counter.class, MenuBar.class, MovingWater.class, Player.class, Coin.class, Surface.class);
/**General stuff**/
addObject(new MenuBar(), 39, 75);
scoreCounter = new Counter("Score: ");
addObject(scoreCounter, 6, 74);
}
public void act(){
// Check for death, level completion and game completion:
if((currentLevel == 1)&&(addScore == false)&&((player.getY() <= 11)&&(player.getX() >=62))){
scoreCounter.add(10);
addScore = true;
}
if((currentLevel == 2)&&(addScore == false)&&((player.getY() <= 10)&&(player.getX() >=63))){
scoreCounter.add(10);
addScore = true;
}
if (checkLevelComplete())
{
// If level is complete, call purge() to remove all objects
purge();
// Increase level
currentLevel++;
// Set level clear goal
levelCompletePoints = loadLevel(currentLevel);
}
// Crude way to "win" the game
else if (currentLevel == WINNING_LEVEL)
{
winGame();
}
// Increment counter
timeCount++;
}
public boolean checkLevelComplete()
{
if (scoreCounter.getValue() >= levelCompletePoints)
return true;
else
return false;
}
public void gameOver() {
saveHighScore();
Greenfoot.setWorld(new GameOverWorld(Game.SKYSCRAPER_GAME));
}
public void winGame() {
Greenfoot.setWorld(new HighScoreWorld(Game.SKYSCRAPER_GAME));
}
private void saveHighScore() {
HighScore highScore = HighScore.askName(scoreCounter.getValue());
try {
highScore.save(HighScore.defaultFilenameForGame(Game.SKYSCRAPER_GAME));
} catch (IOException e) {
e.printStackTrace();
}
}
public void purge()
{
if (Ground != null)
{
for (int i = 0; i < Ground.length; i++)
{
removeObject(Ground[i]);
}
}
if (Bricks != null)
{
for (int i = 0; i < Bricks.length; i++)
{
removeObject(Bricks[i]);
}
}
if (MovingBricks != null)
{
for (int i = 0; i < MovingBricks.length; i++)
{
removeObject(MovingBricks[i]);
}
}
if (MovingBricks2 != null)
{
for (int i = 0; i < MovingBricks2.length; i++)
{
removeObject(MovingBricks2[i]);
}
}
if (MovingBricksUp != null)
{
for (int i = 0; i < MovingBricksUp.length; i++)
{
removeObject(MovingBricksUp[i]);
}
}
if (Coins != null)
{
for (int i = 0; i < Coins.length; i++)
{
removeObject(Coins[i]);
}
}
removeObject(player);
- removeObject(movingWater);
+
+ movingWater.setLevel(20);
}
public int loadLevel (int lvl)
{
if (lvl == 1)
{
Ground = new Ground[15];
MovingBricks = new MovingBrick[2];
Bricks = new Brick[30];
Coins = new Coin[4];
//MovingBricks distance's
MovingBricks[0] = new MovingBrick(5, 36);
MovingBricks[1] = new MovingBrick(17, 58);
for (int i = 0; i < Ground.length; i++)
{
Ground[i] = new Ground ();
}
for (int i = 0; i < Bricks.length; i++)
{
Bricks[i] = new Brick();
}
for (int i = 0; i < Coins.length; i++)
{
Coins[i] = new Coin();
}
//first floor
addObject(Ground[0], 0, 69);
addObject(Ground[1], 3, 69);
addObject(Ground[2], 7, 69);
addObject(Ground[3], 11, 69);
addObject(Ground[4], 15, 69);
addObject(Ground[5], 19, 69);
addObject(Ground[6], 23, 69);
addObject(Ground[7], 27, 69);
addObject(Ground[8], 31, 69);
addObject(Ground[9], 35, 69);
//stairs
addObject(Bricks[0], 35, 49);
addObject(Bricks[1], 35, 53);
addObject(Bricks[2], 35, 57);
addObject(Bricks[3], 35, 61);
addObject(Bricks[4], 35, 65);
addObject(Bricks[5], 31, 65);
addObject(Bricks[6], 31, 61);
addObject(Bricks[7], 31, 57);
addObject(Bricks[8], 31, 53);
addObject(Bricks[9], 27, 65);
addObject(Bricks[10], 27, 61);
addObject(Bricks[11], 27, 57);
addObject(Bricks[12], 23, 65);
addObject(Bricks[13], 23, 61);
addObject(Bricks[14], 19, 65);
//jump parts
addObject(Bricks[15], 45, 49);
addObject(Bricks[16], 56, 49);
addObject(Bricks[17], 67, 49);
addObject(Bricks[18], 78, 49);
addObject(Bricks[19], 78, 45);
addObject(Bricks[20], 72, 33);
addObject(Bricks[21], 62, 33);
addObject(Bricks[22], 51, 33);
addObject(Bricks[23], 40, 31);
addObject(Bricks[24], 1, 27);
addObject(Bricks[25], 25, 23);
addObject(Bricks[26], 5, 23);
addObject(Bricks[27], 1, 23);
addObject(Bricks[28], 1, 14);
addObject(Bricks[29], 13, 11);
//MovingBricks locations
addObject(MovingBricks[0], 25, 27);
addObject(MovingBricks[1], 50, 11);
//Coins
addObject(Coins[0], 45, 44);
addObject(Coins[1], 62, 40);
addObject(Coins[2], 57, 27);
addObject(Coins[3], 38, 2);
//Finish
addObject(Ground[10], 62, 11);
addObject(Ground[11], 66, 11);
addObject(Ground[12], 70, 11);
addObject(Ground[13], 74, 11);
addObject(Ground[14], 78, 11);
addObject(player = Player.createPlayer(playerType), 4, 65);
addObject(movingWater = new MovingWater(), 40, 71);
return 50;
}
if(lvl == 2){
Ground = new Ground[11];
MovingBricks = new MovingBrick[1];
MovingBricksUp = new MovingBrickUp[1];
Bricks = new Brick[56];
Coins = new Coin[4];
for (int i = 0; i < Ground.length; i++)
{
Ground[i] = new Ground ();
}
for (int i = 0; i < Bricks.length; i++)
{
Bricks[i] = new Brick();
}
for (int i = 0; i < Coins.length; i++)
{
Coins[i] = new Coin();
}
//first floor
addObject(Ground[0], 0, 69);
addObject(Ground[1], 3, 69);
addObject(Ground[2], 7, 69);
addObject(Ground[3], 11, 69);
addObject(Ground[4], 15, 69);
addObject(Ground[5], 19, 69);
addObject(Ground[6], 23, 69);
addObject(Bricks[0], 15, 65);
addObject(Bricks[1], 19, 65);
addObject(Bricks[2], 23, 65);
addObject(Bricks[3], 19, 61);
addObject(Bricks[4], 23, 61);
addObject(Bricks[5], 23, 57);
addObject(Bricks[6], 23, 53);
addObject(Bricks[7], 27, 53);
addObject(Bricks[8], 31, 53);
addObject(Bricks[9], 35, 53);
addObject(Bricks[10], 39, 53);
addObject(Bricks[11], 35, 49);
addObject(Bricks[12], 39, 49);
addObject(Bricks[13], 39, 45);
addObject(Bricks[14], 0, 45);
addObject(Bricks[15], 0, 41);
addObject(Bricks[16], 0, 37);
addObject(Bricks[17], 3, 45);
addObject(Bricks[18], 3, 41);
addObject(Bricks[19], 3, 37);
addObject(Bricks[20], 7, 41);
addObject(Bricks[21], 7, 37);
addObject(Bricks[22], 11, 37);
addObject(Bricks[23], 15, 37);
addObject(Bricks[24], 19, 37);
addObject(Bricks[25], 23, 37);
addObject(Bricks[26], 27, 37);
addObject(Bricks[27], 31, 37);
addObject(Bricks[28], 31, 33);
addObject(Bricks[29], 35, 33);
addObject(Bricks[30], 35, 29);
addObject(Bricks[31], 35, 25);
addObject(Bricks[32], 35, 21);
addObject(Bricks[33], 35, 17);
addObject(Bricks[34], 35, 13);
addObject(Bricks[35], 39, 29);
addObject(Bricks[36], 43, 45);
addObject(Bricks[37], 47, 45);
addObject(Bricks[38], 51, 45);
addObject(Bricks[39], 55, 45);
addObject(Bricks[40], 47, 41);
addObject(Bricks[41], 51, 41);
addObject(Bricks[42], 55, 41);
addObject(Bricks[43], 51, 37);
addObject(Bricks[44], 55, 37);
addObject(Bricks[45], 55, 33);
addObject(Bricks[46], 55, 29);
addObject(Bricks[47], 55, 25);
addObject(Bricks[49], 55, 21);
addObject(Bricks[50], 59, 21);
addObject(Bricks[51], 63, 21);
addObject(Bricks[52], 71, 21);
addObject(Bricks[53], 71, 9);
addObject(Bricks[54], 63, 9);
addObject(Bricks[55], 55, 9);
//MovingBricks distance's
MovingBricks[0] = new MovingBrick(21, 39);
MovingBricksUp[0] = new MovingBrickUp(9, 21);
//MovingBricks locations
- addObject(MovingBricks[1], 45, 21);
- addObject(MovingBricksUp[1], 79, 15);
+ addObject(MovingBricks[0], 45, 21);
+ addObject(MovingBricksUp[0], 79, 15);
//Finish
addObject(Ground[7], 47, 9);
addObject(Ground[8], 43, 9);
addObject(Ground[9], 39, 9);
addObject(Ground[10], 35, 9);
addObject(player = Player.createPlayer(playerType), 4, 65);
return 50;
}
if (lvl == 3) {
Ground = new Ground[2];
MovingBricks = new MovingBrick[7];
MovingBricks2 = new MovingBrick2[7];
Coins = new Coin[3];
for (int i = 0; i < Ground.length; i++)
{
Ground[i] = new Ground ();
}
for (int i = 0; i < Coins.length; i++)
{
Coins[i] = new Coin();
}
//first floor
addObject(Ground[0], 8, 69);
//MovingBricks distance's
MovingBricks[0] = new MovingBrick(22, 79);
MovingBricks[1] = new MovingBrick(22, 79);
MovingBricks[2] = new MovingBrick(22, 79);
MovingBricks[3] = new MovingBrick(22, 79);
MovingBricks[4] = new MovingBrick(22, 79);
MovingBricks[5] = new MovingBrick(22, 79);
MovingBricks[6] = new MovingBrick(22, 79);
MovingBricks2[0] = new MovingBrick2(22, 79);
MovingBricks2[1] = new MovingBrick2(22, 79);
MovingBricks2[2] = new MovingBrick2(22, 79);
MovingBricks2[3] = new MovingBrick2(22, 79);
MovingBricks2[4] = new MovingBrick2(22, 79);
MovingBricks2[5] = new MovingBrick2(22, 79);
MovingBricks2[6] = new MovingBrick2(22, 79);
//MovingBricks locations
addObject(MovingBricks[0], 50, 61);
addObject(MovingBricks[1], 50, 53);
addObject(MovingBricks[2], 50, 45);
addObject(MovingBricks[3], 50, 37);
addObject(MovingBricks[4], 50, 29);
addObject(MovingBricks[5], 50, 21);
addObject(MovingBricks[6], 50, 13);
addObject(MovingBricks2[0], 50, 57);
addObject(MovingBricks2[1], 50, 49);
addObject(MovingBricks2[2], 50, 41);
addObject(MovingBricks2[3], 50, 33);
addObject(MovingBricks2[4], 50, 33);
addObject(MovingBricks2[5], 50, 25);
addObject(MovingBricks2[6], 50, 17);
//Finish
addObject(Ground[1], 10, 11);
addObject(player = Player.createPlayer(playerType), 4, 65);
return 50;
}
return 0;
}
public int getWaterLevel() {
return movingWater.getLevel();
}
public Counter getScoreCounter() {
return scoreCounter;
}
public Player getPlayer() {
return player;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java b/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java
index 0a8b9b702..fa760181a 100644
--- a/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java
+++ b/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java
@@ -1,366 +1,366 @@
/*
* Copyright 2009 The Apache Software Foundation
*
* 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.hadoop.hbase.stargate;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.httpclient.Header;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.stargate.client.Client;
import org.apache.hadoop.hbase.stargate.client.Cluster;
import org.apache.hadoop.hbase.stargate.client.Response;
import org.apache.hadoop.hbase.stargate.model.CellModel;
import org.apache.hadoop.hbase.stargate.model.CellSetModel;
import org.apache.hadoop.hbase.stargate.model.RowModel;
import org.apache.hadoop.hbase.util.Bytes;
public class TestRowResource extends MiniClusterTestCase {
private static final String TABLE = "TestRowResource";
private static final String COLUMN_1 = "a:";
private static final String COLUMN_2 = "b:";
private static final String ROW_1 = "testrow1";
private static final String VALUE_1 = "testvalue1";
private static final String ROW_2 = "testrow2";
private static final String VALUE_2 = "testvalue2";
private static final String ROW_3 = "testrow3";
private static final String VALUE_3 = "testvalue3";
private static final String ROW_4 = "testrow4";
private static final String VALUE_4 = "testvalue4";
private Client client;
private JAXBContext context;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private HBaseAdmin admin;
public TestRowResource() throws JAXBException {
super();
context = JAXBContext.newInstance(
CellModel.class,
CellSetModel.class,
RowModel.class);
marshaller = context.createMarshaller();
unmarshaller = context.createUnmarshaller();
}
@Override
protected void setUp() throws Exception {
super.setUp();
client = new Client(new Cluster().add("localhost", testServletPort));
admin = new HBaseAdmin(conf);
if (admin.tableExists(TABLE)) {
return;
}
HTableDescriptor htd = new HTableDescriptor(TABLE);
htd.addFamily(new HColumnDescriptor(COLUMN_1));
htd.addFamily(new HColumnDescriptor(COLUMN_2));
admin.createTable(htd);
}
@Override
protected void tearDown() throws Exception {
client.shutdown();
super.tearDown();
}
private Response deleteRow(String table, String row) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
Response response = client.delete(path.toString());
Thread.yield();
return response;
}
private Response deleteValue(String table, String row, String column)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
Response response = client.delete(path.toString());
Thread.yield();
return response;
}
private Response getValueXML(String table, String row, String column)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
Response response = client.get(path.toString(), MIMETYPE_XML);
return response;
}
private Response getValuePB(String table, String row, String column)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
Response response = client.get(path.toString(), MIMETYPE_PROTOBUF);
return response;
}
private Response putValueXML(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
StringWriter writer = new StringWriter();
marshaller.marshal(cellSetModel, writer);
Response response = client.put(path.toString(), MIMETYPE_XML,
Bytes.toBytes(writer.toString()));
Thread.yield();
return response;
}
private void checkValueXML(String table, String row, String column,
String value) throws IOException, JAXBException {
Response response = getValueXML(table, row, column);
assertEquals(response.getCode(), 200);
CellSetModel cellSet = (CellSetModel)
unmarshaller.unmarshal(new ByteArrayInputStream(response.getBody()));
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toString(cell.getValue()), value);
}
private Response putValuePB(String table, String row, String column,
String value) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
Response response = client.put(path.toString(), MIMETYPE_PROTOBUF,
cellSetModel.createProtobufOutput());
Thread.yield();
return response;
}
private void checkValuePB(String table, String row, String column,
String value) throws IOException {
Response response = getValuePB(table, row, column);
assertEquals(response.getCode(), 200);
CellSetModel cellSet = new CellSetModel();
cellSet.getObjectFromMessage(response.getBody());
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toString(cell.getValue()), value);
}
public void testDelete() throws IOException, JAXBException {
Response response;
response = putValueXML(TABLE, ROW_1, COLUMN_1, VALUE_1);
assertEquals(response.getCode(), 200);
response = putValueXML(TABLE, ROW_1, COLUMN_2, VALUE_2);
assertEquals(response.getCode(), 200);
checkValueXML(TABLE, ROW_1, COLUMN_1, VALUE_1);
checkValueXML(TABLE, ROW_1, COLUMN_2, VALUE_2);
response = deleteValue(TABLE, ROW_1, COLUMN_1);
assertEquals(response.getCode(), 200);
response = getValueXML(TABLE, ROW_1, COLUMN_1);
assertEquals(response.getCode(), 404);
checkValueXML(TABLE, ROW_1, COLUMN_2, VALUE_2);
response = deleteRow(TABLE, ROW_1);
assertEquals(response.getCode(), 200);
response = getValueXML(TABLE, ROW_1, COLUMN_1);
assertEquals(response.getCode(), 404);
response = getValueXML(TABLE, ROW_1, COLUMN_2);
assertEquals(response.getCode(), 404);
}
public void testSingleCellGetPutXML() throws IOException, JAXBException {
Response response = getValueXML(TABLE, ROW_1, COLUMN_1);
assertEquals(response.getCode(), 404);
response = putValueXML(TABLE, ROW_1, COLUMN_1, VALUE_1);
assertEquals(response.getCode(), 200);
checkValueXML(TABLE, ROW_1, COLUMN_1, VALUE_1);
response = putValueXML(TABLE, ROW_1, COLUMN_1, VALUE_2);
assertEquals(response.getCode(), 200);
checkValueXML(TABLE, ROW_1, COLUMN_1, VALUE_2);
response = deleteRow(TABLE, ROW_1);
assertEquals(response.getCode(), 200);
}
public void testSingleCellGetPutPB() throws IOException, JAXBException {
Response response = getValuePB(TABLE, ROW_1, COLUMN_1);
assertEquals(response.getCode(), 404);
response = putValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1);
assertEquals(response.getCode(), 200);
checkValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1);
response = putValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1);
assertEquals(response.getCode(), 200);
checkValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1);
response = putValueXML(TABLE, ROW_1, COLUMN_1, VALUE_2);
assertEquals(response.getCode(), 200);
checkValuePB(TABLE, ROW_1, COLUMN_1, VALUE_2);
response = deleteRow(TABLE, ROW_1);
assertEquals(response.getCode(), 200);
}
public void testSingleCellGetPutBinary() throws IOException {
final String path = "/" + TABLE + "/" + ROW_3 + "/" + COLUMN_1;
final byte[] body = Bytes.toBytes(VALUE_3);
Response response = client.put(path, MIMETYPE_BINARY, body);
assertEquals(response.getCode(), 200);
Thread.yield();
response = client.get(path, MIMETYPE_BINARY);
assertEquals(response.getCode(), 200);
assertTrue(Bytes.equals(response.getBody(), body));
boolean foundTimestampHeader = false;
for (Header header: response.getHeaders()) {
if (header.getName().equals("X-Timestamp")) {
foundTimestampHeader = true;
break;
}
}
assertTrue(foundTimestampHeader);
response = deleteRow(TABLE, ROW_3);
assertEquals(response.getCode(), 200);
}
public void testSingleCellGetJSON() throws IOException, JAXBException {
final String path = "/" + TABLE + "/" + ROW_4 + "/" + COLUMN_1;
Response response = client.put(path, MIMETYPE_BINARY,
Bytes.toBytes(VALUE_4));
assertEquals(response.getCode(), 200);
Thread.yield();
response = client.get(path, MIMETYPE_JSON);
assertEquals(response.getCode(), 200);
response = deleteRow(TABLE, ROW_4);
assertEquals(response.getCode(), 200);
}
public void testMultiCellGetPutXML() throws IOException, JAXBException {
String path = "/" + TABLE + "/fakerow"; // deliberate nonexistent row
CellSetModel cellSetModel = new CellSetModel();
RowModel rowModel = new RowModel(ROW_1);
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_1), Bytes.toBytes(VALUE_1)));
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_2), Bytes.toBytes(VALUE_2)));
cellSetModel.addRow(rowModel);
rowModel = new RowModel(ROW_2);
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_1), Bytes.toBytes(VALUE_3)));
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_2), Bytes.toBytes(VALUE_4)));
cellSetModel.addRow(rowModel);
StringWriter writer = new StringWriter();
marshaller.marshal(cellSetModel, writer);
Response response = client.put(path, MIMETYPE_XML,
Bytes.toBytes(writer.toString()));
Thread.yield();
// make sure the fake row was not actually created
- response = client.get(path);
+ response = client.get(path, MIMETYPE_XML);
assertEquals(response.getCode(), 404);
// check that all of the values were created
checkValueXML(TABLE, ROW_1, COLUMN_1, VALUE_1);
checkValueXML(TABLE, ROW_1, COLUMN_2, VALUE_2);
checkValueXML(TABLE, ROW_2, COLUMN_1, VALUE_3);
checkValueXML(TABLE, ROW_2, COLUMN_2, VALUE_4);
response = deleteRow(TABLE, ROW_1);
assertEquals(response.getCode(), 200);
response = deleteRow(TABLE, ROW_2);
assertEquals(response.getCode(), 200);
}
public void testMultiCellGetPutPB() throws IOException {
String path = "/" + TABLE + "/fakerow"; // deliberate nonexistent row
CellSetModel cellSetModel = new CellSetModel();
RowModel rowModel = new RowModel(ROW_1);
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_1), Bytes.toBytes(VALUE_1)));
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_2), Bytes.toBytes(VALUE_2)));
cellSetModel.addRow(rowModel);
rowModel = new RowModel(ROW_2);
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_1), Bytes.toBytes(VALUE_3)));
rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_2), Bytes.toBytes(VALUE_4)));
cellSetModel.addRow(rowModel);
Response response = client.put(path, MIMETYPE_PROTOBUF,
cellSetModel.createProtobufOutput());
Thread.yield();
// make sure the fake row was not actually created
- response = client.get(path);
+ response = client.get(path, MIMETYPE_PROTOBUF);
assertEquals(response.getCode(), 404);
// check that all of the values were created
checkValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1);
checkValuePB(TABLE, ROW_1, COLUMN_2, VALUE_2);
checkValuePB(TABLE, ROW_2, COLUMN_1, VALUE_3);
checkValuePB(TABLE, ROW_2, COLUMN_2, VALUE_4);
response = deleteRow(TABLE, ROW_1);
assertEquals(response.getCode(), 200);
response = deleteRow(TABLE, ROW_2);
assertEquals(response.getCode(), 200);
}
}
| false | false | null | null |
diff --git a/src/com/android/phone/PhoneUtils.java b/src/com/android/phone/PhoneUtils.java
index 28f0e81c..5e752e63 100644
--- a/src/com/android/phone/PhoneUtils.java
+++ b/src/com/android/phone/PhoneUtils.java
@@ -1,2859 +1,2859 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.IBluetoothHeadsetPhone;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.net.sip.SipManager;
import android.os.AsyncResult;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallManager;
import com.android.internal.telephony.CallStateException;
import com.android.internal.telephony.CallerInfo;
import com.android.internal.telephony.CallerInfoAsyncQuery;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.IExtendedNetworkService;
import com.android.internal.telephony.MmiCode;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyCapabilities;
import com.android.internal.telephony.TelephonyProperties;
import com.android.internal.telephony.cdma.CdmaConnection;
import com.android.internal.telephony.sip.SipPhone;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
/**
* Misc utilities for the Phone app.
*/
public class PhoneUtils {
private static final String LOG_TAG = "PhoneUtils";
private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
// Do not check in with VDBG = true, since that may write PII to the system log.
private static final boolean VDBG = false;
/** Control stack trace for Audio Mode settings */
private static final boolean DBG_SETAUDIOMODE_STACK = false;
/** Identifier for the "Add Call" intent extra. */
static final String ADD_CALL_MODE_KEY = "add_call_mode";
// Return codes from placeCall()
static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
static final int CALL_STATUS_FAILED = 2; // The call failed
// State of the Phone's audio modes
// Each state can move to the other states, but within the state only certain
// transitions for AudioManager.setMode() are allowed.
static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */
static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */
static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */
/** Speaker state, persisting between wired headset connection events */
private static boolean sIsSpeakerEnabled = false;
/** Hash table to store mute (Boolean) values based upon the connection.*/
private static Hashtable<Connection, Boolean> sConnectionMuteTable =
new Hashtable<Connection, Boolean>();
/** Static handler for the connection/mute tracking */
private static ConnectionHandler mConnectionHandler;
/** Phone state changed event*/
private static final int PHONE_STATE_CHANGED = -1;
/** Define for not a special CNAP string */
private static final int CNAP_SPECIAL_CASE_NO = -1;
// Extended network service interface instance
private static IExtendedNetworkService mNwService = null;
// used to cancel MMI command after 15 seconds timeout for NWService requirement
private static Message mMmiTimeoutCbMsg = null;
/** Noise suppression status as selected by user */
private static boolean sIsNoiseSuppressionEnabled = true;
/**
* Handler that tracks the connections and updates the value of the
* Mute settings for each connection as needed.
*/
private static class ConnectionHandler extends Handler {
@Override
public void handleMessage(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
switch (msg.what) {
case PHONE_STATE_CHANGED:
if (DBG) log("ConnectionHandler: updating mute state for each connection");
CallManager cm = (CallManager) ar.userObj;
// update the foreground connections, if there are new connections.
// Have to get all foreground calls instead of the active one
// because there may two foreground calls co-exist in shore period
// (a racing condition based on which phone changes firstly)
// Otherwise the connection may get deleted.
List<Connection> fgConnections = new ArrayList<Connection>();
for (Call fgCall : cm.getForegroundCalls()) {
if (!fgCall.isIdle()) {
fgConnections.addAll(fgCall.getConnections());
}
}
for (Connection cn : fgConnections) {
if (sConnectionMuteTable.get(cn) == null) {
sConnectionMuteTable.put(cn, Boolean.FALSE);
}
}
// mute is connection based operation, we need loop over
// all background calls instead of the first one to update
// the background connections, if there are new connections.
List<Connection> bgConnections = new ArrayList<Connection>();
for (Call bgCall : cm.getBackgroundCalls()) {
if (!bgCall.isIdle()) {
bgConnections.addAll(bgCall.getConnections());
}
}
for (Connection cn : bgConnections) {
if (sConnectionMuteTable.get(cn) == null) {
sConnectionMuteTable.put(cn, Boolean.FALSE);
}
}
// Check to see if there are any lingering connections here
// (disconnected connections), use old-school iterators to avoid
// concurrent modification exceptions.
Connection cn;
for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator();
cnlist.hasNext();) {
cn = cnlist.next();
if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) {
if (DBG) log("connection '" + cn + "' not accounted for, removing.");
cnlist.remove();
}
}
// Restore the mute state of the foreground call if we're not IDLE,
// otherwise just clear the mute state. This is really saying that
// as long as there is one or more connections, we should update
// the mute state with the earliest connection on the foreground
// call, and that with no connections, we should be back to a
// non-mute state.
if (cm.getState() != PhoneConstants.State.IDLE) {
restoreMuteState();
} else {
setMuteInternal(cm.getFgPhone(), false);
}
break;
}
}
}
private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder iBinder) {
if (DBG) log("Extended NW onServiceConnected");
mNwService = IExtendedNetworkService.Stub.asInterface(iBinder);
}
public void onServiceDisconnected(ComponentName arg0) {
if (DBG) log("Extended NW onServiceDisconnected");
mNwService = null;
}
};
/**
* Register the ConnectionHandler with the phone, to receive connection events
*/
public static void initializeConnectionHandler(CallManager cm) {
if (mConnectionHandler == null) {
mConnectionHandler = new ConnectionHandler();
}
// pass over cm as user.obj
cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
// Extended NW service
Intent intent = new Intent("com.android.ussd.IExtendedNetworkService");
cm.getDefaultPhone().getContext().bindService(intent,
ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE);
if (DBG) log("Extended NW bindService IExtendedNetworkService");
}
/** This class is never instantiated. */
private PhoneUtils() {
}
/**
* Answer the currently-ringing call.
*
* @return true if we answered the call, or false if there wasn't
* actually a ringing incoming call, or some other error occurred.
*
* @see #answerAndEndHolding(CallManager, Call)
* @see #answerAndEndActive(CallManager, Call)
*/
/* package */ static boolean answerCall(Call ringing) {
log("answerCall(" + ringing + ")...");
final PhoneGlobals app = PhoneGlobals.getInstance();
// If the ringer is currently ringing and/or vibrating, stop it
- // right now (before actually answering the call.)
- app.getRinger().stopRing();
+ // right now and prevent new rings (before actually answering the call)
+ app.notifier.silenceRinger();
final Phone phone = ringing.getPhone();
final boolean phoneIsCdma = (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA);
boolean answered = false;
IBluetoothHeadsetPhone btPhone = null;
// enable noise suppression
turnOnNoiseSuppression(app.getApplicationContext(), true);
if (phoneIsCdma) {
// Stop any signalInfo tone being played when a Call waiting gets answered
if (ringing.getState() == Call.State.WAITING) {
final CallNotifier notifier = app.notifier;
notifier.stopSignalInfoTone();
}
}
if (ringing != null && ringing.isRinging()) {
if (DBG) log("answerCall: call state = " + ringing.getState());
try {
if (phoneIsCdma) {
if (app.cdmaPhoneCallState.getCurrentCallState()
== CdmaPhoneCallState.PhoneCallState.IDLE) {
// This is the FIRST incoming call being answered.
// Set the Phone Call State to SINGLE_ACTIVE
app.cdmaPhoneCallState.setCurrentCallState(
CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
} else {
// This is the CALL WAITING call being answered.
// Set the Phone Call State to CONF_CALL
app.cdmaPhoneCallState.setCurrentCallState(
CdmaPhoneCallState.PhoneCallState.CONF_CALL);
// Enable "Add Call" option after answering a Call Waiting as the user
// should be allowed to add another call in case one of the parties
// drops off
app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
// If a BluetoothPhoneService is valid we need to set the second call state
// so that the Bluetooth client can update the Call state correctly when
// a call waiting is answered from the Phone.
btPhone = app.getBluetoothPhoneService();
if (btPhone != null) {
try {
btPhone.cdmaSetSecondCallState(true);
} catch (RemoteException e) {
Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
}
}
}
}
final boolean isRealIncomingCall = isRealIncomingCall(ringing.getState());
//if (DBG) log("sPhone.acceptCall");
app.mCM.acceptCall(ringing);
answered = true;
// Always reset to "unmuted" for a freshly-answered call
setMute(false);
setAudioMode();
// Check is phone in any dock, and turn on speaker accordingly
final boolean speakerActivated = activateSpeakerIfDocked(phone);
// When answering a phone call, the user will move the phone near to her/his ear
// and start conversation, without checking its speaker status. If some other
// application turned on the speaker mode before the call and didn't turn it off,
// Phone app would need to be responsible for the speaker phone.
// Here, we turn off the speaker if
// - the phone call is the first in-coming call,
// - we did not activate speaker by ourselves during the process above, and
// - Bluetooth headset is not in use.
if (isRealIncomingCall && !speakerActivated && isSpeakerOn(app)
&& !app.isBluetoothHeadsetAudioOn()) {
// This is not an error but might cause users' confusion. Add log just in case.
Log.i(LOG_TAG, "Forcing speaker off due to new incoming call...");
turnOnSpeaker(app, false, true);
}
} catch (CallStateException ex) {
Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
if (phoneIsCdma) {
// restore the cdmaPhoneCallState and btPhone.cdmaSetSecondCallState:
app.cdmaPhoneCallState.setCurrentCallState(
app.cdmaPhoneCallState.getPreviousCallState());
if (btPhone != null) {
try {
btPhone.cdmaSetSecondCallState(false);
} catch (RemoteException e) {
Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
}
}
}
}
}
return answered;
}
/**
* Smart "hang up" helper method which hangs up exactly one connection,
* based on the current Phone state, as follows:
* <ul>
* <li>If there's a ringing call, hang that up.
* <li>Else if there's a foreground call, hang that up.
* <li>Else if there's a background call, hang that up.
* <li>Otherwise do nothing.
* </ul>
* @return true if we successfully hung up, or false
* if there were no active calls at all.
*/
static boolean hangup(CallManager cm) {
boolean hungup = false;
Call ringing = cm.getFirstActiveRingingCall();
Call fg = cm.getActiveFgCall();
Call bg = cm.getFirstActiveBgCall();
if (!ringing.isIdle()) {
log("hangup(): hanging up ringing call");
hungup = hangupRingingCall(ringing);
} else if (!fg.isIdle()) {
log("hangup(): hanging up foreground call");
hungup = hangup(fg);
} else if (!bg.isIdle()) {
log("hangup(): hanging up background call");
hungup = hangup(bg);
} else {
// No call to hang up! This is unlikely in normal usage,
// since the UI shouldn't be providing an "End call" button in
// the first place. (But it *can* happen, rarely, if an
// active call happens to disconnect on its own right when the
// user is trying to hang up..)
log("hangup(): no active call to hang up");
}
if (DBG) log("==> hungup = " + hungup);
return hungup;
}
static Call getCurrentCall(Phone phone) {
Call ringing = phone.getRingingCall();
Call fg = phone.getForegroundCall();
Call bg = phone.getBackgroundCall();
if (!ringing.isIdle()) {
return ringing;
}
if (!fg.isIdle()) {
return fg;
}
if (!bg.isIdle()) {
return bg;
}
return fg;
}
static Connection getConnection(Phone phone, Call call) {
if (call == null) {
return null;
}
if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
return call.getLatestConnection();
}
return call.getEarliestConnection();
}
static class PhoneSettings {
static boolean vibOn45Secs(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("button_vibrate_45", false);
}
static boolean vibHangup(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("button_vibrate_hangup", false);
}
static boolean vibOutgoing(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("button_vibrate_outgoing", false);
}
static boolean vibCallWaiting(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("button_vibrate_call_waiting", false);
}
static boolean showInCallEvents(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("button_show_ssn_key", false);
}
}
static boolean hangupRingingCall(Call ringing) {
if (DBG) log("hangup ringing call");
int phoneType = ringing.getPhone().getPhoneType();
Call.State state = ringing.getState();
if (state == Call.State.INCOMING) {
// Regular incoming call (with no other active calls)
log("hangupRingingCall(): regular incoming call: hangup()");
return hangup(ringing);
} else if (state == Call.State.WAITING) {
// Call-waiting: there's an incoming call, but another call is
// already active.
// TODO: It would be better for the telephony layer to provide
// a "hangupWaitingCall()" API that works on all devices,
// rather than us having to check the phone type here and do
// the notifier.sendCdmaCallWaitingReject() hack for CDMA phones.
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
// CDMA: Ringing call and Call waiting hangup is handled differently.
// For Call waiting we DO NOT call the conventional hangup(call) function
// as in CDMA we just want to hangup the Call waiting connection.
log("hangupRingingCall(): CDMA-specific call-waiting hangup");
final CallNotifier notifier = PhoneGlobals.getInstance().notifier;
notifier.sendCdmaCallWaitingReject();
return true;
} else {
// Otherwise, the regular hangup() API works for
// call-waiting calls too.
log("hangupRingingCall(): call-waiting call: hangup()");
return hangup(ringing);
}
} else {
// Unexpected state: the ringing call isn't INCOMING or
// WAITING, so there's no reason to have called
// hangupRingingCall() in the first place.
// (Presumably the incoming call went away at the exact moment
// we got here, so just do nothing.)
Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call");
return false;
}
}
static boolean hangupActiveCall(Call foreground) {
if (DBG) log("hangup active call");
return hangup(foreground);
}
static boolean hangupHoldingCall(Call background) {
if (DBG) log("hangup holding call");
return hangup(background);
}
/**
* Used in CDMA phones to end the complete Call session
* @param phone the Phone object.
* @return true if *any* call was successfully hung up
*/
static boolean hangupRingingAndActive(Phone phone) {
boolean hungUpRingingCall = false;
boolean hungUpFgCall = false;
Call ringingCall = phone.getRingingCall();
Call fgCall = phone.getForegroundCall();
// Hang up any Ringing Call
if (!ringingCall.isIdle()) {
log("hangupRingingAndActive: Hang up Ringing Call");
hungUpRingingCall = hangupRingingCall(ringingCall);
}
// Hang up any Active Call
if (!fgCall.isIdle()) {
log("hangupRingingAndActive: Hang up Foreground Call");
hungUpFgCall = hangupActiveCall(fgCall);
}
return hungUpRingingCall || hungUpFgCall;
}
/**
* Trivial wrapper around Call.hangup(), except that we return a
* boolean success code rather than throwing CallStateException on
* failure.
*
* @return true if the call was successfully hung up, or false
* if the call wasn't actually active.
*/
static boolean hangup(Call call) {
try {
CallManager cm = PhoneGlobals.getInstance().mCM;
if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) {
// handle foreground call hangup while there is background call
log("- hangup(Call): hangupForegroundResumeBackground...");
cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall());
} else {
log("- hangup(Call): regular hangup()...");
call.hangup();
}
return true;
} catch (CallStateException ex) {
Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
}
return false;
}
/**
* Trivial wrapper around Connection.hangup(), except that we silently
* do nothing (rather than throwing CallStateException) if the
* connection wasn't actually active.
*/
static void hangup(Connection c) {
try {
if (c != null) {
c.hangup();
}
} catch (CallStateException ex) {
Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
}
}
static boolean answerAndEndHolding(CallManager cm, Call ringing) {
if (DBG) log("end holding & answer waiting: 1");
if (!hangupHoldingCall(cm.getFirstActiveBgCall())) {
Log.e(LOG_TAG, "end holding failed!");
return false;
}
if (DBG) log("end holding & answer waiting: 2");
return answerCall(ringing);
}
/**
* Answers the incoming call specified by "ringing", and ends the currently active phone call.
*
* This method is useful when's there's an incoming call which we cannot manage with the
* current call. e.g. when you are having a phone call with CDMA network and has received
* a SIP call, then we won't expect our telephony can manage those phone calls simultaneously.
* Note that some types of network may allow multiple phone calls at once; GSM allows to hold
* an ongoing phone call, so we don't need to end the active call. The caller of this method
* needs to check if the network allows multiple phone calls or not.
*
* @see #answerCall(Call)
* @see InCallScreen#internalAnswerCall()
*/
/* package */ static boolean answerAndEndActive(CallManager cm, Call ringing) {
if (DBG) log("answerAndEndActive()...");
// Unlike the answerCall() method, we *don't* need to stop the
// ringer or change audio modes here since the user is already
// in-call, which means that the audio mode is already set
// correctly, and that we wouldn't have started the ringer in the
// first place.
// hanging up the active call also accepts the waiting call
// while active call and waiting call are from the same phone
// i.e. both from GSM phone
if (!hangupActiveCall(cm.getActiveFgCall())) {
Log.w(LOG_TAG, "end active call failed!");
return false;
}
// since hangupActiveCall() also accepts the ringing call
// check if the ringing call was already answered or not
// only answer it when the call still is ringing
if (ringing.isRinging()) {
return answerCall(ringing);
}
return true;
}
/**
* For a CDMA phone, advance the call state upon making a new
* outgoing call.
*
* <pre>
* IDLE -> SINGLE_ACTIVE
* or
* SINGLE_ACTIVE -> THRWAY_ACTIVE
* </pre>
* @param app The phone instance.
*/
private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app) {
if (app.cdmaPhoneCallState.getCurrentCallState() ==
CdmaPhoneCallState.PhoneCallState.IDLE) {
// This is the first outgoing call. Set the Phone Call State to ACTIVE
app.cdmaPhoneCallState.setCurrentCallState(
CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
} else {
// This is the second outgoing call. Set the Phone Call State to 3WAY
app.cdmaPhoneCallState.setCurrentCallState(
CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
}
}
/**
* Dial the number using the phone passed in.
*
* If the connection is establised, this method issues a sync call
* that may block to query the caller info.
* TODO: Change the logic to use the async query.
*
* @param context To perform the CallerInfo query.
* @param phone the Phone object.
* @param number to be dialed as requested by the user. This is
* NOT the phone number to connect to. It is used only to build the
* call card and to update the call log. See above for restrictions.
* @param contactRef that triggered the call. Typically a 'tel:'
* uri but can also be a 'content://contacts' one.
* @param isEmergencyCall indicates that whether or not this is an
* emergency call
* @param gatewayUri Is the address used to setup the connection, null
* if not using a gateway
*
* @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
*/
public static int placeCall(Context context, Phone phone,
String number, Uri contactRef, boolean isEmergencyCall,
Uri gatewayUri) {
if (VDBG) {
log("placeCall()... number: '" + number + "'"
+ ", GW:'" + gatewayUri + "'"
+ ", contactRef:" + contactRef
+ ", isEmergencyCall: " + isEmergencyCall);
} else {
log("placeCall()... number: " + toLogSafePhoneNumber(number)
+ ", GW: " + (gatewayUri != null ? "non-null" : "null")
+ ", emergency? " + isEmergencyCall);
}
final PhoneGlobals app = PhoneGlobals.getInstance();
boolean useGateway = false;
if (null != gatewayUri &&
!isEmergencyCall &&
PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
useGateway = true;
}
int status = CALL_STATUS_DIALED;
Connection connection;
String numberToDial;
if (useGateway) {
// TODO: 'tel' should be a constant defined in framework base
// somewhere (it is in webkit.)
if (null == gatewayUri || !Constants.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
return CALL_STATUS_FAILED;
}
// We can use getSchemeSpecificPart because we don't allow #
// in the gateway numbers (treated a fragment delim.) However
// if we allow more complex gateway numbers sequence (with
// passwords or whatnot) that use #, this may break.
// TODO: Need to support MMI codes.
numberToDial = gatewayUri.getSchemeSpecificPart();
} else {
numberToDial = number;
}
// Remember if the phone state was in IDLE state before this call.
// After calling CallManager#dial(), getState() will return different state.
final boolean initiallyIdle = app.mCM.getState() == PhoneConstants.State.IDLE;
try {
connection = app.mCM.dial(phone, numberToDial);
} catch (CallStateException ex) {
// CallStateException means a new outgoing call is not currently
// possible: either no more call slots exist, or there's another
// call already in the process of dialing or ringing.
Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
return CALL_STATUS_FAILED;
// Note that it's possible for CallManager.dial() to return
// null *without* throwing an exception; that indicates that
// we dialed an MMI (see below).
}
int phoneType = phone.getPhoneType();
// On GSM phones, null is returned for MMI codes
if (null == connection) {
if (phoneType == PhoneConstants.PHONE_TYPE_GSM && gatewayUri == null) {
if (DBG) log("dialed MMI code: " + number);
status = CALL_STATUS_DIALED_MMI;
// Set dialed MMI command to service
if (mNwService != null) {
try {
mNwService.setMmiString(number);
if (DBG) log("Extended NW bindService setUssdString (" + number + ")");
} catch (RemoteException e) {
mNwService = null;
}
}
} else {
status = CALL_STATUS_FAILED;
}
} else {
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
updateCdmaCallStateOnNewOutgoingCall(app);
}
// Clean up the number to be displayed.
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
number = CdmaConnection.formatDialString(number);
}
number = PhoneNumberUtils.extractNetworkPortion(number);
number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
number = PhoneNumberUtils.formatNumber(number);
if (gatewayUri == null) {
// phone.dial() succeeded: we're now in a normal phone call.
// attach the URI to the CallerInfo Object if it is there,
// otherwise just attach the Uri Reference.
// if the uri does not have a "content" scheme, then we treat
// it as if it does NOT have a unique reference.
String content = context.getContentResolver().SCHEME_CONTENT;
if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
Object userDataObject = connection.getUserData();
if (userDataObject == null) {
connection.setUserData(contactRef);
} else {
// TODO: This branch is dead code, we have
// just created the connection which has
// no user data (null) by default.
if (userDataObject instanceof CallerInfo) {
((CallerInfo) userDataObject).contactRefUri = contactRef;
} else {
((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
contactRef;
}
}
}
} else {
// Get the caller info synchronously because we need the final
// CallerInfo object to update the dialed number with the one
// requested by the user (and not the provider's gateway number).
CallerInfo info = null;
String content = phone.getContext().getContentResolver().SCHEME_CONTENT;
if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
info = CallerInfo.getCallerInfo(context, contactRef);
}
// Fallback, lookup contact using the phone number if the
// contact's URI scheme was not content:// or if is was but
// the lookup failed.
if (null == info) {
info = CallerInfo.getCallerInfo(context, number);
}
info.phoneNumber = number;
connection.setUserData(info);
}
setAudioMode();
if (DBG) log("about to activate speaker");
// Check is phone in any dock, and turn on speaker accordingly
final boolean speakerActivated = activateSpeakerIfDocked(phone);
// See also similar logic in answerCall().
if (initiallyIdle && !speakerActivated && isSpeakerOn(app)
&& !app.isBluetoothHeadsetAudioOn()) {
// This is not an error but might cause users' confusion. Add log just in case.
Log.i(LOG_TAG, "Forcing speaker off when initiating a new outgoing call...");
PhoneUtils.turnOnSpeaker(app, false, true);
}
}
return status;
}
private static String toLogSafePhoneNumber(String number) {
if (VDBG) {
// When VDBG is true we emit PII.
return number;
}
// Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
// sanitized phone numbers.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);
if (c == '-' || c == '@' || c == '.') {
builder.append(c);
} else {
builder.append('x');
}
}
return builder.toString();
}
/**
* Wrapper function to control when to send an empty Flash command to the network.
* Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
* to the network prior to placing a 3-way call for it to be successful.
*/
static void sendEmptyFlash(Phone phone) {
if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
Call fgCall = phone.getForegroundCall();
if (fgCall.getState() == Call.State.ACTIVE) {
// Send the empty flash
if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
switchHoldingAndActive(phone.getBackgroundCall());
}
}
}
/**
* @param heldCall is the background call want to be swapped
*/
static void switchHoldingAndActive(Call heldCall) {
log("switchHoldingAndActive()...");
try {
CallManager cm = PhoneGlobals.getInstance().mCM;
if (heldCall.isIdle()) {
// no heldCall, so it is to hold active call
cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
} else {
// has particular heldCall, so to switch
cm.switchHoldingAndActive(heldCall);
}
setAudioMode(cm);
} catch (CallStateException ex) {
Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
}
}
/**
* Restore the mute setting from the earliest connection of the
* foreground call.
*/
static Boolean restoreMuteState() {
Phone phone = PhoneGlobals.getInstance().mCM.getFgPhone();
//get the earliest connection
Connection c = phone.getForegroundCall().getEarliestConnection();
// only do this if connection is not null.
if (c != null) {
int phoneType = phone.getPhoneType();
// retrieve the mute value.
Boolean shouldMute = null;
// In CDMA, mute is not maintained per Connection. Single mute apply for
// a call where call can have multiple connections such as
// Three way and Call Waiting. Therefore retrieving Mute state for
// latest connection can apply for all connection in that call
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
shouldMute = sConnectionMuteTable.get(
phone.getForegroundCall().getLatestConnection());
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
shouldMute = sConnectionMuteTable.get(c);
}
if (shouldMute == null) {
if (DBG) log("problem retrieving mute value for this connection.");
shouldMute = Boolean.FALSE;
}
// set the mute value and return the result.
setMute (shouldMute.booleanValue());
return shouldMute;
}
return Boolean.valueOf(getMute());
}
static void mergeCalls() {
mergeCalls(PhoneGlobals.getInstance().mCM);
}
static void mergeCalls(CallManager cm) {
int phoneType = cm.getFgPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
log("mergeCalls(): CDMA...");
PhoneGlobals app = PhoneGlobals.getInstance();
if (app.cdmaPhoneCallState.getCurrentCallState()
== CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
// Set the Phone Call State to conference
app.cdmaPhoneCallState.setCurrentCallState(
CdmaPhoneCallState.PhoneCallState.CONF_CALL);
// Send flash cmd
// TODO: Need to change the call from switchHoldingAndActive to
// something meaningful as we are not actually trying to swap calls but
// instead are merging two calls by sending a Flash command.
log("- sending flash...");
switchHoldingAndActive(cm.getFirstActiveBgCall());
}
} else {
try {
log("mergeCalls(): calling cm.conference()...");
cm.conference(cm.getFirstActiveBgCall());
} catch (CallStateException ex) {
Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
}
}
}
static void separateCall(Connection c) {
try {
if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
c.separate();
} catch (CallStateException ex) {
Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
}
}
/**
* Handle the MMIInitiate message and put up an alert that lets
* the user cancel the operation, if applicable.
*
* @param context context to get strings.
* @param mmiCode the MmiCode object being started.
* @param buttonCallbackMessage message to post when button is clicked.
* @param previousAlert a previous alert used in this activity.
* @return the dialog handle
*/
static Dialog displayMMIInitiate(Context context,
MmiCode mmiCode,
Message buttonCallbackMessage,
Dialog previousAlert) {
if (DBG) log("displayMMIInitiate: " + mmiCode);
if (previousAlert != null) {
previousAlert.dismiss();
}
// The UI paradigm we are using now requests that all dialogs have
// user interaction, and that any other messages to the user should
// be by way of Toasts.
//
// In adhering to this request, all MMI initiating "OK" dialogs
// (non-cancelable MMIs) that end up being closed when the MMI
// completes (thereby showing a completion dialog) are being
// replaced with Toasts.
//
// As a side effect, moving to Toasts for the non-cancelable MMIs
// also means that buttonCallbackMessage (which was tied into "OK")
// is no longer invokable for these dialogs. This is not a problem
// since the only callback messages we supported were for cancelable
// MMIs anyway.
//
// A cancelable MMI is really just a USSD request. The term
// "cancelable" here means that we can cancel the request when the
// system prompts us for a response, NOT while the network is
// processing the MMI request. Any request to cancel a USSD while
// the network is NOT ready for a response may be ignored.
//
// With this in mind, we replace the cancelable alert dialog with
// a progress dialog, displayed until we receive a request from
// the the network. For more information, please see the comments
// in the displayMMIComplete() method below.
//
// Anything that is NOT a USSD request is a normal MMI request,
// which will bring up a toast (desribed above).
// Optional code for Extended USSD running prompt
if (mNwService != null) {
if (DBG) log("running USSD code, displaying indeterminate progress.");
// create the indeterminate progress dialog and display it.
ProgressDialog pd = new ProgressDialog(context);
CharSequence textmsg = "";
try {
textmsg = mNwService.getMmiRunningText();
} catch (RemoteException e) {
mNwService = null;
textmsg = context.getText(R.string.ussdRunning);
}
if (DBG) log("Extended NW displayMMIInitiate (" + textmsg + ")");
pd.setMessage(textmsg);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
pd.show();
// trigger a 15 seconds timeout to clear this progress dialog
mMmiTimeoutCbMsg = buttonCallbackMessage;
try {
mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000);
} catch(NullPointerException e) {
mMmiTimeoutCbMsg = null;
}
return pd;
}
boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
if (!isCancelable) {
if (DBG) log("not a USSD code, displaying status toast.");
CharSequence text = context.getText(R.string.mmiStarted);
Toast.makeText(context, text, Toast.LENGTH_SHORT)
.show();
return null;
} else {
if (DBG) log("running USSD code, displaying indeterminate progress.");
// create the indeterminate progress dialog and display it.
ProgressDialog pd = new ProgressDialog(context);
pd.setMessage(context.getText(R.string.ussdRunning));
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
pd.show();
return pd;
}
}
/**
* Handle the MMIComplete message and fire off an intent to display
* the message.
*
* @param context context to get strings.
* @param mmiCode MMI result.
* @param previousAlert a previous alert used in this activity.
*/
static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
Message dismissCallbackMessage,
AlertDialog previousAlert) {
final PhoneGlobals app = PhoneGlobals.getInstance();
CharSequence text;
int title = 0; // title for the progress dialog, if needed.
MmiCode.State state = mmiCode.getState();
if (DBG) log("displayMMIComplete: state=" + state);
// Clear timeout trigger message
if(mMmiTimeoutCbMsg != null) {
try{
mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what);
if (DBG) log("Extended NW displayMMIComplete removeMsg");
} catch (NullPointerException e) {
}
mMmiTimeoutCbMsg = null;
}
switch (state) {
case PENDING:
// USSD code asking for feedback from user.
text = mmiCode.getMessage();
if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
break;
case CANCELLED:
text = null;
break;
case COMPLETE:
if (app.getPUKEntryActivity() != null) {
// if an attempt to unPUK the device was made, we specify
// the title and the message here.
title = com.android.internal.R.string.PinMmi;
text = context.getText(R.string.puk_unlocked);
break;
}
// All other conditions for the COMPLETE mmi state will cause
// the case to fall through to message logic in common with
// the FAILED case.
case FAILED:
text = mmiCode.getMessage();
if (DBG) log("- using text from MMI message: '" + text + "'");
break;
default:
throw new IllegalStateException("Unexpected MmiCode state: " + state);
}
if (previousAlert != null) {
previousAlert.dismiss();
}
// Check to see if a UI exists for the PUK activation. If it does
// exist, then it indicates that we're trying to unblock the PUK.
if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
if (DBG) log("displaying PUK unblocking progress dialog.");
// create the progress dialog, make sure the flags and type are
// set correctly.
ProgressDialog pd = new ProgressDialog(app);
pd.setTitle(title);
pd.setMessage(text);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
// display the dialog
pd.show();
// indicate to the Phone app that the progress dialog has
// been assigned for the PUK unlock / SIM READY process.
app.setPukEntryProgressDialog(pd);
} else {
// In case of failure to unlock, we'll need to reset the
// PUK unlock activity, so that the user may try again.
if (app.getPUKEntryActivity() != null) {
app.setPukEntryActivity(null);
}
// A USSD in a pending state means that it is still
// interacting with the user.
if (state != MmiCode.State.PENDING) {
if (DBG) log("MMI code has finished running.");
// Replace response message with Extended Mmi wording
if (mNwService != null) {
try {
text = mNwService.getUserMessage(text);
} catch (RemoteException e) {
mNwService = null;
}
}
if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
if (text == null || text.length() == 0)
return;
// displaying system alert dialog on the screen instead of
// using another activity to display the message. This
// places the message at the forefront of the UI.
AlertDialog newDialog = new AlertDialog.Builder(context)
.setMessage(text)
.setPositiveButton(R.string.ok, null)
.setCancelable(true)
.create();
newDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
newDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
newDialog.show();
} else {
if (DBG) log("USSD code has requested user input. Constructing input dialog.");
// USSD MMI code that is interacting with the user. The
// basic set of steps is this:
// 1. User enters a USSD request
// 2. We recognize the request and displayMMIInitiate
// (above) creates a progress dialog.
// 3. Request returns and we get a PENDING or COMPLETE
// message.
// 4. These MMI messages are caught in the PhoneApp
// (onMMIComplete) and the InCallScreen
// (mHandler.handleMessage) which bring up this dialog
// and closes the original progress dialog,
// respectively.
// 5. If the message is anything other than PENDING,
// we are done, and the alert dialog (directly above)
// displays the outcome.
// 6. If the network is requesting more information from
// the user, the MMI will be in a PENDING state, and
// we display this dialog with the message.
// 7. User input, or cancel requests result in a return
// to step 1. Keep in mind that this is the only
// time that a USSD should be canceled.
// inflate the layout with the scrolling text area for the dialog.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
// get the input field.
final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
// specify the dialog's click listener, with SEND and CANCEL logic.
final DialogInterface.OnClickListener mUSSDDialogListener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
phone.sendUssdResponse(inputText.getText().toString());
break;
case DialogInterface.BUTTON_NEGATIVE:
if (mmiCode.isCancelable()) {
mmiCode.cancel();
}
break;
}
}
};
// build the dialog
final AlertDialog newDialog = new AlertDialog.Builder(context)
.setMessage(text)
.setView(dialogView)
.setPositiveButton(R.string.send_button, mUSSDDialogListener)
.setNegativeButton(R.string.cancel, mUSSDDialogListener)
.setCancelable(false)
.create();
// attach the key listener to the dialog's input field and make
// sure focus is set.
final View.OnKeyListener mUSSDDialogInputListener =
new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_CALL:
case KeyEvent.KEYCODE_ENTER:
if(event.getAction() == KeyEvent.ACTION_DOWN) {
phone.sendUssdResponse(inputText.getText().toString());
newDialog.dismiss();
}
return true;
}
return false;
}
};
inputText.setOnKeyListener(mUSSDDialogInputListener);
inputText.requestFocus();
// set the window properties of the dialog
newDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
newDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
// now show the dialog!
newDialog.show();
}
}
}
/**
* Cancels the current pending MMI operation, if applicable.
* @return true if we canceled an MMI operation, or false
* if the current pending MMI wasn't cancelable
* or if there was no current pending MMI at all.
*
* @see displayMMIInitiate
*/
static boolean cancelMmiCode(Phone phone) {
List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
int count = pendingMmis.size();
if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
boolean canceled = false;
if (count > 0) {
// assume that we only have one pending MMI operation active at a time.
// I don't think it's possible to enter multiple MMI codes concurrently
// in the phone UI, because during the MMI operation, an Alert panel
// is displayed, which prevents more MMI code from being entered.
MmiCode mmiCode = pendingMmis.get(0);
if (mmiCode.isCancelable()) {
mmiCode.cancel();
canceled = true;
}
}
//clear timeout message and pre-set MMI command
if (mNwService != null) {
try {
mNwService.clearMmiString();
} catch (RemoteException e) {
mNwService = null;
}
}
if (mMmiTimeoutCbMsg != null) {
mMmiTimeoutCbMsg = null;
}
return canceled;
}
public static class VoiceMailNumberMissingException extends Exception {
VoiceMailNumberMissingException() {
super();
}
VoiceMailNumberMissingException(String msg) {
super(msg);
}
}
/**
* Given an Intent (which is presumably the ACTION_CALL intent that
* initiated this outgoing call), figure out the actual phone number we
* should dial.
*
* Note that the returned "number" may actually be a SIP address,
* if the specified intent contains a sip: URI.
*
* This method is basically a wrapper around PhoneUtils.getNumberFromIntent(),
* except it's also aware of the EXTRA_ACTUAL_NUMBER_TO_DIAL extra.
* (That extra, if present, tells us the exact string to pass down to the
* telephony layer. It's guaranteed to be safe to dial: it's either a PSTN
* phone number with separators and keypad letters stripped out, or a raw
* unencoded SIP address.)
*
* @return the phone number corresponding to the specified Intent, or null
* if the Intent has no action or if the intent's data is malformed or
* missing.
*
* @throws VoiceMailNumberMissingException if the intent
* contains a "voicemail" URI, but there's no voicemail
* number configured on the device.
*/
public static String getInitialNumber(Intent intent)
throws PhoneUtils.VoiceMailNumberMissingException {
if (DBG) log("getInitialNumber(): " + intent);
String action = intent.getAction();
if (TextUtils.isEmpty(action)) {
return null;
}
// If the EXTRA_ACTUAL_NUMBER_TO_DIAL extra is present, get the phone
// number from there. (That extra takes precedence over the actual data
// included in the intent.)
if (intent.hasExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL)) {
String actualNumberToDial =
intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL);
if (DBG) {
log("==> got EXTRA_ACTUAL_NUMBER_TO_DIAL; returning '"
+ toLogSafePhoneNumber(actualNumberToDial) + "'");
}
return actualNumberToDial;
}
return getNumberFromIntent(PhoneGlobals.getInstance(), intent);
}
/**
* Gets the phone number to be called from an intent. Requires a Context
* to access the contacts database, and a Phone to access the voicemail
* number.
*
* <p>If <code>phone</code> is <code>null</code>, the function will return
* <code>null</code> for <code>voicemail:</code> URIs;
* if <code>context</code> is <code>null</code>, the function will return
* <code>null</code> for person/phone URIs.</p>
*
* <p>If the intent contains a <code>sip:</code> URI, the returned
* "number" is actually the SIP address.
*
* @param context a context to use (or
* @param intent the intent
*
* @throws VoiceMailNumberMissingException if <code>intent</code> contains
* a <code>voicemail:</code> URI, but <code>phone</code> does not
* have a voicemail number set.
*
* @return the phone number (or SIP address) that would be called by the intent,
* or <code>null</code> if the number cannot be found.
*/
private static String getNumberFromIntent(Context context, Intent intent)
throws VoiceMailNumberMissingException {
Uri uri = intent.getData();
String scheme = uri.getScheme();
// The sip: scheme is simple: just treat the rest of the URI as a
// SIP address.
if (Constants.SCHEME_SIP.equals(scheme)) {
return uri.getSchemeSpecificPart();
}
// Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
// the other cases (i.e. tel: and voicemail: and contact: URIs.)
final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
// Check for a voicemail-dialing request. If the voicemail number is
// empty, throw a VoiceMailNumberMissingException.
if (Constants.SCHEME_VOICEMAIL.equals(scheme) &&
(number == null || TextUtils.isEmpty(number)))
throw new VoiceMailNumberMissingException();
return number;
}
/**
* Returns the caller-id info corresponding to the specified Connection.
* (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
* extract a phone number from the specified Connection, and feed that
* number into CallerInfo.getCallerInfo().)
*
* The returned CallerInfo may be null in certain error cases, like if the
* specified Connection was null, or if we weren't able to get a valid
* phone number from the Connection.
*
* Finally, if the getCallerInfo() call did succeed, we save the resulting
* CallerInfo object in the "userData" field of the Connection.
*
* NOTE: This API should be avoided, with preference given to the
* asynchronous startGetCallerInfo API.
*/
static CallerInfo getCallerInfo(Context context, Connection c) {
CallerInfo info = null;
if (c != null) {
//See if there is a URI attached. If there is, this means
//that there is no CallerInfo queried yet, so we'll need to
//replace the URI with a full CallerInfo object.
Object userDataObject = c.getUserData();
if (userDataObject instanceof Uri) {
info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
if (info != null) {
c.setUserData(info);
}
} else {
if (userDataObject instanceof CallerInfoToken) {
//temporary result, while query is running
info = ((CallerInfoToken) userDataObject).currentInfo;
} else {
//final query result
info = (CallerInfo) userDataObject;
}
if (info == null) {
// No URI, or Existing CallerInfo, so we'll have to make do with
// querying a new CallerInfo using the connection's phone number.
String number = c.getAddress();
if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
if (!TextUtils.isEmpty(number)) {
info = CallerInfo.getCallerInfo(context, number);
if (info != null) {
c.setUserData(info);
}
}
}
}
}
return info;
}
/**
* Class returned by the startGetCallerInfo call to package a temporary
* CallerInfo Object, to be superceded by the CallerInfo Object passed
* into the listener when the query with token mAsyncQueryToken is complete.
*/
public static class CallerInfoToken {
/**indicates that there will no longer be updates to this request.*/
public boolean isFinal;
public CallerInfo currentInfo;
public CallerInfoAsyncQuery asyncQuery;
}
/**
* Start a CallerInfo Query based on the earliest connection in the call.
*/
static CallerInfoToken startGetCallerInfo(Context context, Call call,
CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
Connection conn = null;
int phoneType = call.getPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
conn = call.getLatestConnection();
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
conn = call.getEarliestConnection();
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
return startGetCallerInfo(context, conn, listener, cookie);
}
/**
* place a temporary callerinfo object in the hands of the caller and notify
* caller when the actual query is done.
*/
static CallerInfoToken startGetCallerInfo(Context context, Connection c,
CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
CallerInfoToken cit;
if (c == null) {
//TODO: perhaps throw an exception here.
cit = new CallerInfoToken();
cit.asyncQuery = null;
return cit;
}
Object userDataObject = c.getUserData();
// There are now 3 states for the Connection's userData object:
//
// (1) Uri - query has not been executed yet
//
// (2) CallerInfoToken - query is executing, but has not completed.
//
// (3) CallerInfo - query has executed.
//
// In each case we have slightly different behaviour:
// 1. If the query has not been executed yet (Uri or null), we start
// query execution asynchronously, and note it by attaching a
// CallerInfoToken as the userData.
// 2. If the query is executing (CallerInfoToken), we've essentially
// reached a state where we've received multiple requests for the
// same callerInfo. That means that once the query is complete,
// we'll need to execute the additional listener requested.
// 3. If the query has already been executed (CallerInfo), we just
// return the CallerInfo object as expected.
// 4. Regarding isFinal - there are cases where the CallerInfo object
// will not be attached, like when the number is empty (caller id
// blocking). This flag is used to indicate that the
// CallerInfoToken object is going to be permanent since no
// query results will be returned. In the case where a query
// has been completed, this flag is used to indicate to the caller
// that the data will not be updated since it is valid.
//
// Note: For the case where a number is NOT retrievable, we leave
// the CallerInfo as null in the CallerInfoToken. This is
// something of a departure from the original code, since the old
// code manufactured a CallerInfo object regardless of the query
// outcome. From now on, we will append an empty CallerInfo
// object, to mirror previous behaviour, and to avoid Null Pointer
// Exceptions.
if (userDataObject instanceof Uri) {
// State (1): query has not been executed yet
//create a dummy callerinfo, populate with what we know from URI.
cit = new CallerInfoToken();
cit.currentInfo = new CallerInfo();
cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
(Uri) userDataObject, sCallerInfoQueryListener, c);
cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
cit.isFinal = false;
c.setUserData(cit);
if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
} else if (userDataObject == null) {
// No URI, or Existing CallerInfo, so we'll have to make do with
// querying a new CallerInfo using the connection's phone number.
String number = c.getAddress();
if (DBG) {
log("PhoneUtils.startGetCallerInfo: new query for phone number...");
log("- number (address): " + toLogSafePhoneNumber(number));
log("- c: " + c);
log("- phone: " + c.getCall().getPhone());
int phoneType = c.getCall().getPhone().getPhoneType();
log("- phoneType: " + phoneType);
switch (phoneType) {
case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
default: log(" ==> Unknown phone type"); break;
}
}
cit = new CallerInfoToken();
cit.currentInfo = new CallerInfo();
// Store CNAP information retrieved from the Connection (we want to do this
// here regardless of whether the number is empty or not).
cit.currentInfo.cnapName = c.getCnapName();
cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
// by ContactInfo later
cit.currentInfo.numberPresentation = c.getNumberPresentation();
cit.currentInfo.namePresentation = c.getCnapNamePresentation();
if (VDBG) {
log("startGetCallerInfo: number = " + number);
log("startGetCallerInfo: CNAP Info from FW(1): name="
+ cit.currentInfo.cnapName
+ ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
}
// handling case where number is null (caller id hidden) as well.
if (!TextUtils.isEmpty(number)) {
// Check for special CNAP cases and modify the CallerInfo accordingly
// to be sure we keep the right information to display/log later
number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
cit.currentInfo.numberPresentation);
cit.currentInfo.phoneNumber = number;
// For scenarios where we may receive a valid number from the network but a
// restricted/unavailable presentation, we do not want to perform a contact query
// (see note on isFinal above). So we set isFinal to true here as well.
if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
cit.isFinal = true;
} else {
if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
number, sCallerInfoQueryListener, c);
cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
cit.isFinal = false;
}
} else {
// This is the case where we are querying on a number that
// is null or empty, like a caller whose caller id is
// blocked or empty (CLIR). The previous behaviour was to
// throw a null CallerInfo object back to the user, but
// this departure is somewhat cleaner.
if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
cit.isFinal = true; // please see note on isFinal, above.
}
c.setUserData(cit);
if (DBG) {
log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
}
} else if (userDataObject instanceof CallerInfoToken) {
// State (2): query is executing, but has not completed.
// just tack on this listener to the queue.
cit = (CallerInfoToken) userDataObject;
// handling case where number is null (caller id hidden) as well.
if (cit.asyncQuery != null) {
cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
listener.getClass().toString());
} else {
// handling case where number/name gets updated later on by the network
String updatedNumber = c.getAddress();
if (DBG) {
log("startGetCallerInfo: updatedNumber initially = "
+ toLogSafePhoneNumber(updatedNumber));
}
if (!TextUtils.isEmpty(updatedNumber)) {
// Store CNAP information retrieved from the Connection
cit.currentInfo.cnapName = c.getCnapName();
// This can still get overwritten by ContactInfo
cit.currentInfo.name = cit.currentInfo.cnapName;
cit.currentInfo.numberPresentation = c.getNumberPresentation();
cit.currentInfo.namePresentation = c.getCnapNamePresentation();
updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
updatedNumber, cit.currentInfo.numberPresentation);
cit.currentInfo.phoneNumber = updatedNumber;
if (DBG) {
log("startGetCallerInfo: updatedNumber="
+ toLogSafePhoneNumber(updatedNumber));
}
if (VDBG) {
log("startGetCallerInfo: CNAP Info from FW(2): name="
+ cit.currentInfo.cnapName
+ ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
} else if (DBG) {
log("startGetCallerInfo: CNAP Info from FW(2)");
}
// For scenarios where we may receive a valid number from the network but a
// restricted/unavailable presentation, we do not want to perform a contact query
// (see note on isFinal above). So we set isFinal to true here as well.
if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
cit.isFinal = true;
} else {
cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
updatedNumber, sCallerInfoQueryListener, c);
cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
cit.isFinal = false;
}
} else {
if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
if (cit.currentInfo == null) {
cit.currentInfo = new CallerInfo();
}
// Store CNAP information retrieved from the Connection
cit.currentInfo.cnapName = c.getCnapName(); // This can still get
// overwritten by ContactInfo
cit.currentInfo.name = cit.currentInfo.cnapName;
cit.currentInfo.numberPresentation = c.getNumberPresentation();
cit.currentInfo.namePresentation = c.getCnapNamePresentation();
if (VDBG) {
log("startGetCallerInfo: CNAP Info from FW(3): name="
+ cit.currentInfo.cnapName
+ ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
} else if (DBG) {
log("startGetCallerInfo: CNAP Info from FW(3)");
}
cit.isFinal = true; // please see note on isFinal, above.
}
}
} else {
// State (3): query is complete.
// The connection's userDataObject is a full-fledged
// CallerInfo instance. Wrap it in a CallerInfoToken and
// return it to the user.
cit = new CallerInfoToken();
cit.currentInfo = (CallerInfo) userDataObject;
cit.asyncQuery = null;
cit.isFinal = true;
// since the query is already done, call the listener.
if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
}
return cit;
}
/**
* Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
* we use with all our CallerInfoAsyncQuery.startQuery() requests.
*/
private static final int QUERY_TOKEN = -1;
static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
new CallerInfoAsyncQuery.OnQueryCompleteListener () {
/**
* When the query completes, we stash the resulting CallerInfo
* object away in the Connection's "userData" (where it will
* later be retrieved by the in-call UI.)
*/
public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
if (DBG) log("query complete, updating connection.userdata");
Connection conn = (Connection) cookie;
// Added a check if CallerInfo is coming from ContactInfo or from Connection.
// If no ContactInfo, then we want to use CNAP information coming from network
if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
// If the number presentation has not been set by
// the ContactInfo, use the one from the
// connection.
// TODO: Need a new util method to merge the info
// from the Connection in a CallerInfo object.
// Here 'ci' is a new CallerInfo instance read
// from the DB. It has lost all the connection
// info preset before the query (see PhoneUtils
// line 1334). We should have a method to merge
// back into this new instance the info from the
// connection object not set by the DB. If the
// Connection already has a CallerInfo instance in
// userData, then we could use this instance to
// fill 'ci' in. The same routine could be used in
// PhoneUtils.
if (0 == ci.numberPresentation) {
ci.numberPresentation = conn.getNumberPresentation();
}
} else {
// No matching contact was found for this number.
// Return a new CallerInfo based solely on the CNAP
// information from the network.
CallerInfo newCi = getCallerInfo(null, conn);
// ...but copy over the (few) things we care about
// from the original CallerInfo object:
if (newCi != null) {
newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
newCi.geoDescription = ci.geoDescription; // To get geo description string
ci = newCi;
}
}
if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
conn.setUserData(ci);
}
};
/**
* Returns a single "name" for the specified given a CallerInfo object.
* If the name is null, return defaultString as the default value, usually
* context.getString(R.string.unknown).
*/
static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
String compactName = null;
if (ci != null) {
if (TextUtils.isEmpty(ci.name)) {
// Perform any modifications for special CNAP cases to
// the phone number being displayed, if applicable.
compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
ci.numberPresentation);
} else {
// Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
compactName = ci.name;
}
}
if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
// If we're still null/empty here, then check if we have a presentation
// string that takes precedence that we could return, otherwise display
// "unknown" string.
if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
compactName = context.getString(R.string.private_num);
} else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
compactName = context.getString(R.string.payphone);
} else {
compactName = context.getString(R.string.unknown);
}
}
if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
return compactName;
}
/**
* Returns true if the specified Call is a "conference call", meaning
* that it owns more than one Connection object. This information is
* used to trigger certain UI changes that appear when a conference
* call is active (like displaying the label "Conference call", and
* enabling the "Manage conference" UI.)
*
* Watch out: This method simply checks the number of Connections,
* *not* their states. So if a Call has (for example) one ACTIVE
* connection and one DISCONNECTED connection, this method will return
* true (which is unintuitive, since the Call isn't *really* a
* conference call any more.)
*
* @return true if the specified call has more than one connection (in any state.)
*/
static boolean isConferenceCall(Call call) {
// CDMA phones don't have the same concept of "conference call" as
// GSM phones do; there's no special "conference call" state of
// the UI or a "manage conference" function. (Instead, when
// you're in a 3-way call, all we can do is display the "generic"
// state of the UI.) So as far as the in-call UI is concerned,
// Conference corresponds to generic display.
final PhoneGlobals app = PhoneGlobals.getInstance();
int phoneType = call.getPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
|| ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
&& !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
return true;
}
} else {
List<Connection> connections = call.getConnections();
if (connections != null && connections.size() > 1) {
return true;
}
}
return false;
// TODO: We may still want to change the semantics of this method
// to say that a given call is only really a conference call if
// the number of ACTIVE connections, not the total number of
// connections, is greater than one. (See warning comment in the
// javadoc above.)
// Here's an implementation of that:
// if (connections == null) {
// return false;
// }
// int numActiveConnections = 0;
// for (Connection conn : connections) {
// if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
// if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
// if (numActiveConnections > 1) {
// return true;
// }
// }
// return false;
}
/**
* Launch the Dialer to start a new call.
* This is just a wrapper around the ACTION_DIAL intent.
*/
/* package */ static boolean startNewCall(final CallManager cm) {
final PhoneGlobals app = PhoneGlobals.getInstance();
// Sanity-check that this is OK given the current state of the phone.
if (!okToAddCall(cm)) {
Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
dumpCallManager();
return false;
}
// if applicable, mute the call while we're showing the add call UI.
if (cm.hasActiveFgCall()) {
setMuteInternal(cm.getActiveFgCall().getPhone(), true);
// Inform the phone app that this mute state was NOT done
// voluntarily by the User.
app.setRestoreMuteOnInCallResume(true);
}
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// when we request the dialer come up, we also want to inform
// it that we're going through the "add call" option from the
// InCallScreen / PhoneUtils.
intent.putExtra(ADD_CALL_MODE_KEY, true);
try {
app.startActivity(intent);
} catch (ActivityNotFoundException e) {
// This is rather rare but possible.
// Note: this method is used even when the phone is encrypted. At that moment
// the system may not find any Activity which can accept this Intent.
Log.e(LOG_TAG, "Activity for adding calls isn't found.");
return false;
}
return true;
}
/**
* Turns on/off speaker.
*
* @param context Context
* @param flag True when speaker should be on. False otherwise.
* @param store True when the settings should be stored in the device.
*/
/* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
final PhoneGlobals app = PhoneGlobals.getInstance();
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(flag);
// record the speaker-enable value
if (store) {
sIsSpeakerEnabled = flag;
}
// Update the status bar icon
app.notificationMgr.updateSpeakerNotification(flag);
// We also need to make a fresh call to PhoneApp.updateWakeState()
// any time the speaker state changes, since the screen timeout is
// sometimes different depending on whether or not the speaker is
// in use.
app.updateWakeState();
// Update the Proximity sensor based on speaker state
app.updateProximitySensorMode(app.mCM.getState());
app.mCM.setEchoSuppressionEnabled(flag);
}
/**
* Restore the speaker mode, called after a wired headset disconnect
* event.
*/
static void restoreSpeakerMode(Context context) {
if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
// change the mode if needed.
if (isSpeakerOn(context) != sIsSpeakerEnabled) {
turnOnSpeaker(context, sIsSpeakerEnabled, false);
}
}
static boolean isSpeakerOn(Context context) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
return audioManager.isSpeakerphoneOn();
}
static void turnOnNoiseSuppression(Context context, boolean flag) {
if (DBG) log("turnOnNoiseSuppression: " + flag);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
return;
}
int nsp = android.provider.Settings.System.getInt(context.getContentResolver(),
android.provider.Settings.System.NOISE_SUPPRESSION,
1);
String aParam = context.getResources().getString(R.string.in_call_noise_suppression_audioparameter);
String[] aPValues = aParam.split("=");
if(aPValues[0].length() == 0) {
aPValues[0] = "noise_suppression";
}
if(aPValues[1].length() == 0) {
aPValues[1] = "on";
}
if(aPValues[2].length() == 0) {
aPValues[2] = "off";
}
if (nsp == 1 && flag) {
if (DBG) log("turnOnNoiseSuppression: " + aPValues[0] + "=" + aPValues[1]);
audioManager.setParameters(aPValues[0] + "=" + aPValues[1]);
} else {
if (DBG) log("turnOnNoiseSuppression: " + aPValues[0] + "=" + aPValues[2]);
audioManager.setParameters(aPValues[0] + "=" + aPValues[2]);
}
}
/**
*
* Mute / umute the foreground phone, which has the current foreground call
*
* All muting / unmuting from the in-call UI should go through this
* wrapper.
*
* Wrapper around Phone.setMute() and setMicrophoneMute().
* It also updates the connectionMuteTable and mute icon in the status bar.
*
*/
static void setMute(boolean muted) {
CallManager cm = PhoneGlobals.getInstance().mCM;
// make the call to mute the audio
setMuteInternal(cm.getFgPhone(), muted);
// update the foreground connections to match. This includes
// all the connections on conference calls.
for (Connection cn : cm.getActiveFgCall().getConnections()) {
if (sConnectionMuteTable.get(cn) == null) {
if (DBG) log("problem retrieving mute value for this connection.");
}
sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
}
}
/**
* Internally used muting function.
*/
private static void setMuteInternal(Phone phone, boolean muted) {
final PhoneGlobals app = PhoneGlobals.getInstance();
Context context = phone.getContext();
boolean routeToAudioManager =
context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
if (routeToAudioManager) {
AudioManager audioManager =
(AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE);
if (DBG) log("setMuteInternal: using setMicrophoneMute(" + muted + ")...");
audioManager.setMicrophoneMute(muted);
} else {
if (DBG) log("setMuteInternal: using phone.setMute(" + muted + ")...");
phone.setMute(muted);
}
app.notificationMgr.updateMuteNotification();
}
/**
* Get the mute state of foreground phone, which has the current
* foreground call
*/
static boolean getMute() {
final PhoneGlobals app = PhoneGlobals.getInstance();
boolean routeToAudioManager =
app.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
if (routeToAudioManager) {
AudioManager audioManager =
(AudioManager) app.getSystemService(Context.AUDIO_SERVICE);
return audioManager.isMicrophoneMute();
} else {
return app.mCM.getMute();
}
}
/* package */ static void setAudioMode() {
setAudioMode(PhoneGlobals.getInstance().mCM);
}
/**
* Sets the audio mode per current phone state.
*/
/* package */ static void setAudioMode(CallManager cm) {
if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState());
Context context = PhoneGlobals.getInstance();
AudioManager audioManager = (AudioManager)
context.getSystemService(Context.AUDIO_SERVICE);
int modeBefore = audioManager.getMode();
cm.setAudioMode();
int modeAfter = audioManager.getMode();
if (modeBefore != modeAfter) {
// Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
} else {
if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: "
+ audioModeToString(modeBefore));
}
}
private static String audioModeToString(int mode) {
switch (mode) {
case AudioManager.MODE_INVALID: return "MODE_INVALID";
case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
default: return String.valueOf(mode);
}
}
/**
* Handles the wired headset button while in-call.
*
* This is called from the PhoneApp, not from the InCallScreen,
* since the HEADSETHOOK button means "mute or unmute the current
* call" *any* time a call is active, even if the user isn't actually
* on the in-call screen.
*
* @return true if we consumed the event.
*/
/* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) {
if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount());
final PhoneGlobals app = PhoneGlobals.getInstance();
// If the phone is totally idle, we ignore HEADSETHOOK events
// (and instead let them fall through to the media player.)
if (phone.getState() == PhoneConstants.State.IDLE) {
return false;
}
// Ok, the phone is in use.
// The headset button button means "Answer" if an incoming call is
// ringing. If not, it toggles the mute / unmute state.
//
// And in any case we *always* consume this event; this means
// that the usual mediaplayer-related behavior of the headset
// button will NEVER happen while the user is on a call.
final boolean hasRingingCall = !phone.getRingingCall().isIdle();
final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
if (hasRingingCall &&
event.getRepeatCount() == 0 &&
event.getAction() == KeyEvent.ACTION_UP) {
// If an incoming call is ringing, answer it (just like with the
// CALL button):
int phoneType = phone.getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
answerCall(phone.getRingingCall());
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
if (hasActiveCall && hasHoldingCall) {
if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
answerAndEndActive(app.mCM, phone.getRingingCall());
} else {
if (DBG) log("handleHeadsetHook: ringing ==> answer!");
// answerCall() will automatically hold the current
// active call, if there is one.
answerCall(phone.getRingingCall());
}
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
} else {
// No incoming ringing call.
if (event.isLongPress()) {
if (DBG) log("handleHeadsetHook: longpress -> hangup");
hangup(app.mCM);
}
else if (event.getAction() == KeyEvent.ACTION_UP &&
event.getRepeatCount() == 0) {
Connection c = phone.getForegroundCall().getLatestConnection();
// If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook.
if (c != null && !PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(),
PhoneGlobals.getInstance())) {
if (getMute()) {
if (DBG) log("handleHeadsetHook: UNmuting...");
setMute(false);
} else {
if (DBG) log("handleHeadsetHook: muting...");
setMute(true);
}
}
}
}
// Even if the InCallScreen is the current activity, there's no
// need to force it to update, because (1) if we answered a
// ringing call, the InCallScreen will imminently get a phone
// state change event (causing an update), and (2) if we muted or
// unmuted, the setMute() call automagically updates the status
// bar, and there's no "mute" indication in the InCallScreen
// itself (other than the menu item, which only ever stays
// onscreen for a second anyway.)
// TODO: (2) isn't entirely true anymore. Once we return our result
// to the PhoneApp, we ask InCallScreen to update its control widgets
// in case we changed mute or speaker state and phones with touch-
// screen [toggle] buttons need to update themselves.
return true;
}
/**
* Look for ANY connections on the phone that qualify as being
* disconnected.
*
* @return true if we find a connection that is disconnected over
* all the phone's call objects.
*/
/* package */ static boolean hasDisconnectedConnections(Phone phone) {
return hasDisconnectedConnections(phone.getForegroundCall()) ||
hasDisconnectedConnections(phone.getBackgroundCall()) ||
hasDisconnectedConnections(phone.getRingingCall());
}
/**
* Iterate over all connections in a call to see if there are any
* that are not alive (disconnected or idle).
*
* @return true if we find a connection that is disconnected, and
* pending removal via
* {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
*/
private static final boolean hasDisconnectedConnections(Call call) {
// look through all connections for non-active ones.
for (Connection c : call.getConnections()) {
if (!c.isAlive()) {
return true;
}
}
return false;
}
//
// Misc UI policy helper functions
//
/**
* @return true if we're allowed to swap calls, given the current
* state of the Phone.
*/
/* package */ static boolean okToSwapCalls(CallManager cm) {
int phoneType = cm.getDefaultPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
// CDMA: "Swap" is enabled only when the phone reaches a *generic*.
// state by either accepting a Call Waiting or by merging two calls
PhoneGlobals app = PhoneGlobals.getInstance();
return (app.cdmaPhoneCallState.getCurrentCallState()
== CdmaPhoneCallState.PhoneCallState.CONF_CALL);
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
// GSM: "Swap" is available if both lines are in use and there's no
// incoming call. (Actually we need to verify that the active
// call really is in the ACTIVE state and the holding call really
// is in the HOLDING state, since you *can't* actually swap calls
// when the foreground call is DIALING or ALERTING.)
return !cm.hasActiveRingingCall()
&& (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
&& (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
/**
* @return true if we're allowed to merge calls, given the current
* state of the Phone.
*/
/* package */ static boolean okToMergeCalls(CallManager cm) {
int phoneType = cm.getFgPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
// CDMA: "Merge" is enabled only when the user is in a 3Way call.
PhoneGlobals app = PhoneGlobals.getInstance();
return ((app.cdmaPhoneCallState.getCurrentCallState()
== CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
&& !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
} else {
// GSM: "Merge" is available if both lines are in use and there's no
// incoming call, *and* the current conference isn't already
// "full".
// TODO: shall move all okToMerge logic to CallManager
return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
&& cm.hasActiveBgCall()
&& cm.canConference(cm.getFirstActiveBgCall());
}
}
/**
* @return true if the UI should let you add a new call, given the current
* state of the Phone.
*/
/* package */ static boolean okToAddCall(CallManager cm) {
Phone phone = cm.getActiveFgCall().getPhone();
// "Add call" is never allowed in emergency callback mode (ECM).
if (isPhoneInEcm(phone)) {
return false;
}
int phoneType = phone.getPhoneType();
final Call.State fgCallState = cm.getActiveFgCall().getState();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
// CDMA: "Add call" button is only enabled when:
// - ForegroundCall is in ACTIVE state
// - After 30 seconds of user Ignoring/Missing a Call Waiting call.
PhoneGlobals app = PhoneGlobals.getInstance();
return ((fgCallState == Call.State.ACTIVE)
&& (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
// GSM: "Add call" is available only if ALL of the following are true:
// - There's no incoming ringing call
// - There's < 2 lines in use
// - The foreground call is ACTIVE or IDLE or DISCONNECTED.
// (We mainly need to make sure it *isn't* DIALING or ALERTING.)
final boolean hasRingingCall = cm.hasActiveRingingCall();
final boolean hasActiveCall = cm.hasActiveFgCall();
final boolean hasHoldingCall = cm.hasActiveBgCall();
final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
return !hasRingingCall
&& !allLinesTaken
&& ((fgCallState == Call.State.ACTIVE)
|| (fgCallState == Call.State.IDLE)
|| (fgCallState == Call.State.DISCONNECTED));
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
/**
* Based on the input CNAP number string,
* @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
* Otherwise, return CNAP_SPECIAL_CASE_NO.
*/
private static int checkCnapSpecialCases(String n) {
if (n.equals("PRIVATE") ||
n.equals("P") ||
n.equals("RES")) {
if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
return PhoneConstants.PRESENTATION_RESTRICTED;
} else if (n.equals("UNAVAILABLE") ||
n.equals("UNKNOWN") ||
n.equals("UNA") ||
n.equals("U")) {
if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
return PhoneConstants.PRESENTATION_UNKNOWN;
} else {
if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
return CNAP_SPECIAL_CASE_NO;
}
}
/**
* Handles certain "corner cases" for CNAP. When we receive weird phone numbers
* from the network to indicate different number presentations, convert them to
* expected number and presentation values within the CallerInfo object.
* @param number number we use to verify if we are in a corner case
* @param presentation presentation value used to verify if we are in a corner case
* @return the new String that should be used for the phone number
*/
/* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
String number, int presentation) {
// Obviously we return number if ci == null, but still return number if
// number == null, because in these cases the correct string will still be
// displayed/logged after this function returns based on the presentation value.
if (ci == null || number == null) return number;
if (DBG) {
log("modifyForSpecialCnapCases: initially, number="
+ toLogSafePhoneNumber(number)
+ ", presentation=" + presentation + " ci " + ci);
}
// "ABSENT NUMBER" is a possible value we could get from the network as the
// phone number, so if this happens, change it to "Unknown" in the CallerInfo
// and fix the presentation to be the same.
if (number.equals(context.getString(R.string.absent_num))
&& presentation == PhoneConstants.PRESENTATION_ALLOWED) {
number = context.getString(R.string.unknown);
ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
}
// Check for other special "corner cases" for CNAP and fix them similarly. Corner
// cases only apply if we received an allowed presentation from the network, so check
// if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
// match the presentation passed in for verification (meaning we changed it previously
// because it's a corner case and we're being called from a different entry point).
if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
|| (ci.numberPresentation != presentation
&& presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
int cnapSpecialCase = checkCnapSpecialCases(number);
if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
// For all special strings, change number & numberPresentation.
if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
number = context.getString(R.string.private_num);
} else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
number = context.getString(R.string.unknown);
}
if (DBG) {
log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
+ "; presentation now=" + cnapSpecialCase);
}
ci.numberPresentation = cnapSpecialCase;
}
}
if (DBG) {
log("modifyForSpecialCnapCases: returning number string="
+ toLogSafePhoneNumber(number));
}
return number;
}
//
// Support for 3rd party phone service providers.
//
/**
* Check if all the provider's info is present in the intent.
* @param intent Expected to have the provider's extra.
* @return true if the intent has all the extras to build the
* in-call screen's provider info overlay.
*/
/* package */ static boolean hasPhoneProviderExtras(Intent intent) {
if (null == intent) {
return false;
}
final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri);
}
/**
* Copy all the expected extras set when a 3rd party provider is
* used from the source intent to the destination one. Checks all
* the required extras are present, if any is missing, none will
* be copied.
* @param src Intent which may contain the provider's extras.
* @param dst Intent where a copy of the extras will be added if applicable.
*/
/* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) {
if (!hasPhoneProviderExtras(src)) {
Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing.");
return;
}
dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE,
src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE));
dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI,
src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI));
}
/**
* Get the provider's label from the intent.
* @param context to lookup the provider's package name.
* @param intent with an extra set to the provider's package name.
* @return The provider's application label. null if an error
* occurred during the lookup of the package name or the label.
*/
/* package */ static CharSequence getProviderLabel(Context context, Intent intent) {
String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
PackageManager pm = context.getPackageManager();
try {
ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
return pm.getApplicationLabel(info);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
/**
* Get the provider's icon.
* @param context to lookup the provider's icon.
* @param intent with an extra set to the provider's package name.
* @return The provider's application icon. null if an error occured during the icon lookup.
*/
/* package */ static Drawable getProviderIcon(Context context, Intent intent) {
String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
PackageManager pm = context.getPackageManager();
try {
return pm.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
/**
* Return the gateway uri from the intent.
* @param intent With the gateway uri extra.
* @return The gateway URI or null if not found.
*/
/* package */ static Uri getProviderGatewayUri(Intent intent) {
String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
return TextUtils.isEmpty(uri) ? null : Uri.parse(uri);
}
/**
* Return a formatted version of the uri's scheme specific
* part. E.g for 'tel:12345678', return '1-234-5678'.
* @param uri A 'tel:' URI with the gateway phone number.
* @return the provider's address (from the gateway uri) formatted
* for user display. null if uri was null or its scheme was not 'tel:'.
*/
/* package */ static String formatProviderUri(Uri uri) {
if (null != uri) {
if (Constants.SCHEME_TEL.equals(uri.getScheme())) {
return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart());
} else {
return uri.toString();
}
}
return null;
}
/**
* Check if a phone number can be route through a 3rd party
* gateway. The number must be a global phone number in numerical
* form (1-800-666-SEXY won't work).
*
* MMI codes and the like cannot be used as a dial number for the
* gateway either.
*
* @param number To be dialed via a 3rd party gateway.
* @return true If the number can be routed through the 3rd party network.
*/
/* package */ static boolean isRoutableViaGateway(String number) {
if (TextUtils.isEmpty(number)) {
return false;
}
number = PhoneNumberUtils.stripSeparators(number);
if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
return false;
}
number = PhoneNumberUtils.extractNetworkPortion(number);
return PhoneNumberUtils.isGlobalPhoneNumber(number);
}
/**
* This function is called when phone answers or places a call.
* Check if the phone is in a car dock or desk dock.
* If yes, turn on the speaker, when no wired or BT headsets are connected.
* Otherwise do nothing.
* @return true if activated
*/
private static boolean activateSpeakerIfDocked(Phone phone) {
if (DBG) log("activateSpeakerIfDocked()...");
boolean activated = false;
if (PhoneGlobals.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
PhoneGlobals app = PhoneGlobals.getInstance();
if (!app.isHeadsetPlugged() && !app.isBluetoothHeadsetAudioOn()) {
turnOnSpeaker(phone.getContext(), true, true);
activated = true;
}
}
return activated;
}
/**
* Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
*/
/* package */ static boolean isPhoneInEcm(Phone phone) {
if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
// For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
// TODO: There ought to be a better API for this than just
// exposing a system property all the way up to the app layer,
// probably a method like "inEcm()" provided by the telephony
// layer.
String ecmMode =
SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
if (ecmMode != null) {
return ecmMode.equals("true");
}
}
return false;
}
/**
* Returns the most appropriate Phone object to handle a call
* to the specified number.
*
* @param cm the CallManager.
* @param scheme the scheme from the data URI that the number originally came from.
* @param number the phone number, or SIP address.
*/
public static Phone pickPhoneBasedOnNumber(CallManager cm,
String scheme, String number, String primarySipUri) {
if (DBG) {
log("pickPhoneBasedOnNumber: scheme " + scheme
+ ", number " + toLogSafePhoneNumber(number)
+ ", sipUri "
+ (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null"));
}
if (primarySipUri != null) {
Phone phone = getSipPhoneFromUri(cm, primarySipUri);
if (phone != null) return phone;
}
return cm.getDefaultPhone();
}
public static Phone getGsmPhone(CallManager cm) {
for (Phone phone: cm.getAllPhones()) {
if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM) {
return phone;
}
}
return null;
}
public static Phone getSipPhoneFromUri(CallManager cm, String target) {
for (Phone phone : cm.getAllPhones()) {
if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
String sipUri = ((SipPhone) phone).getSipUri();
if (target.equals(sipUri)) {
if (DBG) log("- pickPhoneBasedOnNumber:" +
"found SipPhone! obj = " + phone + ", "
+ phone.getClass());
return phone;
}
}
}
return null;
}
/**
* Returns true when the given call is in INCOMING state and there's no foreground phone call,
* meaning the call is the first real incoming call the phone is having.
*/
public static boolean isRealIncomingCall(Call.State state) {
return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
}
private static boolean sVoipSupported = false;
static {
PhoneGlobals app = PhoneGlobals.getInstance();
sVoipSupported = SipManager.isVoipSupported(app)
&& app.getResources().getBoolean(com.android.internal.R.bool.config_built_in_sip_phone)
&& app.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
}
/**
* @return true if this device supports voice calls using the built-in SIP stack.
*/
static boolean isVoipSupported() {
return sVoipSupported;
}
/**
* On GSM devices, we never use short tones.
* On CDMA devices, it depends upon the settings.
*/
public static boolean useShortDtmfTones(Phone phone, Context context) {
int phoneType = phone.getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
return false;
} else if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
int toneType = android.provider.Settings.System.getInt(
context.getContentResolver(),
Settings.System.DTMF_TONE_TYPE_WHEN_DIALING,
CallFeaturesSetting.DTMF_TONE_TYPE_NORMAL);
if (toneType == CallFeaturesSetting.DTMF_TONE_TYPE_NORMAL) {
return true;
} else {
return false;
}
} else if (phoneType == PhoneConstants.PHONE_TYPE_SIP) {
return false;
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
public static String getPresentationString(Context context, int presentation) {
String name = context.getString(R.string.unknown);
if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
name = context.getString(R.string.private_num);
} else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
name = context.getString(R.string.payphone);
}
return name;
}
public static void sendViewNotificationAsync(Context context, Uri contactUri) {
if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
intent.setClassName("com.android.contacts",
"com.android.contacts.ViewNotificationService");
context.startService(intent);
}
//
// General phone and call state debugging/testing code
//
/* package */ static void dumpCallState(Phone phone) {
PhoneGlobals app = PhoneGlobals.getInstance();
Log.d(LOG_TAG, "dumpCallState():");
Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
+ ", state = " + phone.getState());
StringBuilder b = new StringBuilder(128);
Call call = phone.getForegroundCall();
b.setLength(0);
b.append(" - FG call: ").append(call.getState());
b.append(" isAlive ").append(call.getState().isAlive());
b.append(" isRinging ").append(call.getState().isRinging());
b.append(" isDialing ").append(call.getState().isDialing());
b.append(" isIdle ").append(call.isIdle());
b.append(" hasConnections ").append(call.hasConnections());
Log.d(LOG_TAG, b.toString());
call = phone.getBackgroundCall();
b.setLength(0);
b.append(" - BG call: ").append(call.getState());
b.append(" isAlive ").append(call.getState().isAlive());
b.append(" isRinging ").append(call.getState().isRinging());
b.append(" isDialing ").append(call.getState().isDialing());
b.append(" isIdle ").append(call.isIdle());
b.append(" hasConnections ").append(call.hasConnections());
Log.d(LOG_TAG, b.toString());
call = phone.getRingingCall();
b.setLength(0);
b.append(" - RINGING call: ").append(call.getState());
b.append(" isAlive ").append(call.getState().isAlive());
b.append(" isRinging ").append(call.getState().isRinging());
b.append(" isDialing ").append(call.getState().isDialing());
b.append(" isIdle ").append(call.isIdle());
b.append(" hasConnections ").append(call.hasConnections());
Log.d(LOG_TAG, b.toString());
final boolean hasRingingCall = !phone.getRingingCall().isIdle();
final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
b.setLength(0);
b.append(" - hasRingingCall ").append(hasRingingCall);
b.append(" hasActiveCall ").append(hasActiveCall);
b.append(" hasHoldingCall ").append(hasHoldingCall);
b.append(" allLinesTaken ").append(allLinesTaken);
Log.d(LOG_TAG, b.toString());
// On CDMA phones, dump out the CdmaPhoneCallState too:
if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
if (app.cdmaPhoneCallState != null) {
Log.d(LOG_TAG, " - CDMA call state: "
+ app.cdmaPhoneCallState.getCurrentCallState());
} else {
Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!");
}
}
// Watch out: the isRinging() call below does NOT tell us anything
// about the state of the telephony layer; it merely tells us whether
// the Ringer manager is currently playing the ringtone.
boolean ringing = app.getRinger().isRinging();
Log.d(LOG_TAG, " - Ringer state: " + ringing);
}
private static void log(String msg) {
Log.d(LOG_TAG, msg);
}
static void dumpCallManager() {
Call call;
CallManager cm = PhoneGlobals.getInstance().mCM;
StringBuilder b = new StringBuilder(128);
Log.d(LOG_TAG, "############### dumpCallManager() ##############");
// TODO: Don't log "cm" itself, since CallManager.toString()
// already spews out almost all this same information.
// We should fix CallManager.toString() to be more minimal, and
// use an explicit dumpState() method for the verbose dump.
// Log.d(LOG_TAG, "CallManager: " + cm
// + ", state = " + cm.getState());
Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
b.setLength(0);
call = cm.getActiveFgCall();
b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
b.append(call);
b.append( " State: ").append(cm.getActiveFgCallState());
b.append( " Conn: ").append(cm.getFgCallConnections());
Log.d(LOG_TAG, b.toString());
b.setLength(0);
call = cm.getFirstActiveBgCall();
b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
b.append(call);
b.append( " State: ").append(cm.getFirstActiveBgCall().getState());
b.append( " Conn: ").append(cm.getBgCallConnections());
Log.d(LOG_TAG, b.toString());
b.setLength(0);
call = cm.getFirstActiveRingingCall();
b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
b.append(call);
b.append( " State: ").append(cm.getFirstActiveRingingCall().getState());
Log.d(LOG_TAG, b.toString());
for (Phone phone : CallManager.getInstance().getAllPhones()) {
if (phone != null) {
Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
+ ", state = " + phone.getState());
b.setLength(0);
call = phone.getForegroundCall();
b.append(" - FG call: ").append(call);
b.append( " State: ").append(call.getState());
b.append( " Conn: ").append(call.hasConnections());
Log.d(LOG_TAG, b.toString());
b.setLength(0);
call = phone.getBackgroundCall();
b.append(" - BG call: ").append(call);
b.append( " State: ").append(call.getState());
b.append( " Conn: ").append(call.hasConnections());
Log.d(LOG_TAG, b.toString());b.setLength(0);
call = phone.getRingingCall();
b.append(" - RINGING call: ").append(call);
b.append( " State: ").append(call.getState());
b.append( " Conn: ").append(call.hasConnections());
Log.d(LOG_TAG, b.toString());
}
}
Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
}
/**
* @return if the context is in landscape orientation.
*/
public static boolean isLandscape(Context context) {
return context.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
}
}
| true | false | null | null |
diff --git a/src/com/android/camera/ui/CameraSwitcher.java b/src/com/android/camera/ui/CameraSwitcher.java
index fffe06f6..d7227681 100644
--- a/src/com/android/camera/ui/CameraSwitcher.java
+++ b/src/com/android/camera/ui/CameraSwitcher.java
@@ -1,268 +1,287 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.ui;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
+import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.android.camera.R;
import com.android.gallery3d.common.ApiHelper;
public class CameraSwitcher extends RotateImageView
implements OnClickListener, OnTouchListener {
private static final String TAG = "CAM_Switcher";
+ private static final int SWITCHER_POPUP_ANIM_DURATION = 200;
public interface CameraSwitchListener {
public void onCameraSelected(int i);
public void onShowSwitcherPopup();
}
private CameraSwitchListener mListener;
private int mCurrentIndex;
private int[] mDrawIds;
private int mItemSize;
private View mPopup;
private View mParent;
private boolean mShowingPopup;
private boolean mNeedsAnimationSetup;
private Drawable mIndicator;
+ private float mTranslationX = 0;
+ private float mTranslationY = 0;
+
private AnimatorListener mHideAnimationListener;
private AnimatorListener mShowAnimationListener;
public CameraSwitcher(Context context) {
super(context);
init(context);
}
public CameraSwitcher(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
mItemSize = context.getResources().getDimensionPixelSize(R.dimen.switcher_size);
setOnClickListener(this);
mIndicator = context.getResources().getDrawable(R.drawable.ic_switcher_menu_indicator);
}
public void setDrawIds(int[] drawids) {
mDrawIds = drawids;
}
public void setCurrentIndex(int i) {
mCurrentIndex = i;
setImageResource(mDrawIds[i]);
}
public void setSwitchListener(CameraSwitchListener l) {
mListener = l;
}
@Override
public void onClick(View v) {
showSwitcher();
mListener.onShowSwitcherPopup();
}
private void onCameraSelected(int ix) {
hidePopup();
if ((ix != mCurrentIndex) && (mListener != null)) {
setCurrentIndex(ix);
mListener.onCameraSelected(ix);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mIndicator.setBounds(getDrawable().getBounds());
mIndicator.draw(canvas);
}
private void initPopup() {
mParent = LayoutInflater.from(getContext()).inflate(R.layout.switcher_popup,
(ViewGroup) getParent());
LinearLayout content = (LinearLayout) mParent.findViewById(R.id.content);
mPopup = content;
mPopup.setVisibility(View.INVISIBLE);
mNeedsAnimationSetup = true;
for (int i = mDrawIds.length - 1; i >= 0; i--) {
RotateImageView item = new RotateImageView(getContext());
item.setImageResource(mDrawIds[i]);
item.setBackgroundResource(R.drawable.bg_pressed);
final int index = i;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onCameraSelected(index);
}
});
switch (mDrawIds[i]) {
case R.drawable.ic_switch_camera:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_camera));
break;
case R.drawable.ic_switch_video:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_video));
break;
case R.drawable.ic_switch_pan:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_panorama));
break;
case R.drawable.ic_switch_photosphere:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_photosphere));
break;
default:
break;
}
content.addView(item, new LinearLayout.LayoutParams(mItemSize, mItemSize));
}
}
public boolean showsPopup() {
return mShowingPopup;
}
public boolean isInsidePopup(MotionEvent evt) {
if (!showsPopup()) return false;
return evt.getX() >= mPopup.getLeft()
&& evt.getX() < mPopup.getRight()
&& evt.getY() >= mPopup.getTop()
&& evt.getY() < mPopup.getBottom();
}
private void hidePopup() {
mShowingPopup = false;
setVisibility(View.VISIBLE);
if (mPopup != null && !animateHidePopup()) {
mPopup.setVisibility(View.INVISIBLE);
}
mParent.setOnTouchListener(null);
}
private void showSwitcher() {
mShowingPopup = true;
if (mPopup == null) {
initPopup();
}
mPopup.setVisibility(View.VISIBLE);
if (!animateShowPopup()) {
setVisibility(View.INVISIBLE);
}
mParent.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (showsPopup()) {
hidePopup();
}
return true;
}
@Override
public void setOrientation(int degree, boolean animate) {
super.setOrientation(degree, animate);
ViewGroup content = (ViewGroup) mPopup;
if (content == null) return;
for (int i = 0; i < content.getChildCount(); i++) {
RotateImageView iv = (RotateImageView) content.getChildAt(i);
iv.setOrientation(degree, animate);
}
}
+ private void updateInitialTranslations() {
+ if (getResources().getConfiguration().orientation
+ == Configuration.ORIENTATION_PORTRAIT) {
+ mTranslationX = -getWidth() / 2 ;
+ mTranslationY = getHeight();
+ } else {
+ mTranslationX = getWidth();
+ mTranslationY = getHeight() / 2;
+ }
+ }
private void popupAnimationSetup() {
if (!ApiHelper.HAS_VIEW_PROPERTY_ANIMATOR) {
return;
}
+ updateInitialTranslations();
mPopup.setScaleX(0.3f);
mPopup.setScaleY(0.3f);
- mPopup.setTranslationX(-getWidth() / 2);
- mPopup.setTranslationY(getHeight());
+ mPopup.setTranslationX(mTranslationX);
+ mPopup.setTranslationY(mTranslationY);
mNeedsAnimationSetup = false;
}
private boolean animateHidePopup() {
if (!ApiHelper.HAS_VIEW_PROPERTY_ANIMATOR) {
return false;
}
if (mHideAnimationListener == null) {
mHideAnimationListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Verify that we weren't canceled
if (!showsPopup()) {
mPopup.setVisibility(View.INVISIBLE);
}
}
};
}
mPopup.animate()
.alpha(0f)
.scaleX(0.3f).scaleY(0.3f)
- .translationX(-getWidth() / 2)
- .translationY(getHeight())
+ .translationX(mTranslationX)
+ .translationY(mTranslationY)
+ .setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(mHideAnimationListener);
- animate().alpha(1f).setListener(null);
+ animate().alpha(1f).setDuration(SWITCHER_POPUP_ANIM_DURATION)
+ .setListener(null);
return true;
}
private boolean animateShowPopup() {
if (!ApiHelper.HAS_VIEW_PROPERTY_ANIMATOR) {
return false;
}
if (mNeedsAnimationSetup) {
popupAnimationSetup();
}
if (mShowAnimationListener == null) {
mShowAnimationListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Verify that we weren't canceled
if (showsPopup()) {
setVisibility(View.INVISIBLE);
}
}
};
}
mPopup.animate()
.alpha(1f)
.scaleX(1f).scaleY(1f)
.translationX(0)
.translationY(0)
+ .setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(null);
- animate().alpha(0f)
+ animate().alpha(0f).setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(mShowAnimationListener);
return true;
}
}
| false | false | null | null |
diff --git a/x10.compiler/src/x10/ast/X10Binary_c.java b/x10.compiler/src/x10/ast/X10Binary_c.java
index 0d7401ae4..2fc2756aa 100644
--- a/x10.compiler/src/x10/ast/X10Binary_c.java
+++ b/x10.compiler/src/x10/ast/X10Binary_c.java
@@ -1,1160 +1,1160 @@
/*
* 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 x10.ast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import polyglot.ast.AmbExpr;
import polyglot.ast.Binary;
import polyglot.ast.Binary_c;
import polyglot.ast.BooleanLit;
import polyglot.ast.Call;
import polyglot.ast.Expr;
import polyglot.ast.Field;
import polyglot.ast.IntLit;
import polyglot.ast.IntLit.Kind;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.Precedence;
import polyglot.ast.Prefix;
import polyglot.ast.Receiver;
import polyglot.ast.StringLit;
import polyglot.ast.Term;
import polyglot.ast.TypeNode;
import polyglot.ast.Binary.Operator;
import polyglot.types.ClassDef;
import polyglot.types.ClassType;
import polyglot.types.Context;
import polyglot.types.Flags;
import polyglot.types.MethodDef;
import polyglot.types.Name;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.types.Types;
import polyglot.util.CodeWriter;
import polyglot.util.CollectionUtil;
import x10.util.CollectionFactory;
import polyglot.util.InternalCompilerError;
import polyglot.util.Pair;
import polyglot.util.Position;
import polyglot.visit.CFGBuilder;
import polyglot.visit.ContextVisitor;
import polyglot.visit.FlowGraph;
import polyglot.visit.NodeVisitor;
import polyglot.visit.PrettyPrinter;
import x10.constraint.XFailure;
import x10.constraint.XLit;
import x10.constraint.XTerm;
import x10.constraint.XTerms;
import x10.errors.Errors;
import x10.errors.Warnings;
import x10.types.MethodInstance;
import x10.types.X10ClassType;
import x10.types.X10Use;
import x10.types.checker.Checker;
import x10.types.checker.Converter;
import x10.types.checker.PlaceChecker;
import x10.types.constants.*;
import x10.types.constraints.BuiltInTypeRules;
/**
* An immutable representation of a binary operation Expr op Expr.
* Overridden from Java to allow distributions, regions, points and places to
* participate in binary operations.
*
* @author vj Jan 21, 2005
*/
public class X10Binary_c extends Binary_c implements X10Binary {
protected Expr left;
protected Operator op;
protected Expr right;
protected Precedence precedence;
/**
* @param pos
* @param left
* @param op
* @param right
*/
public X10Binary_c(Position pos, Expr left, Operator op, Expr right) {
super(pos, left, op, right);
assert(left != null && op != null && right != null);
this.left = left;
this.op = op;
this.right = right;
this.precedence = op.precedence();
if (op == ADD && (left instanceof StringLit || right instanceof StringLit)) {
this.precedence = Precedence.STRING_ADD;
}
invert = false;
}
private boolean invert;
public boolean invert() {
return invert;
}
public X10Binary_c invert(boolean invert) {
if (invert == this.invert) return this;
X10Binary_c n = (X10Binary_c) copy();
n.invert = invert;
return n;
}
private MethodInstance mi;
public MethodInstance methodInstance() {
return mi;
}
public X10Binary_c methodInstance(MethodInstance mi) {
if (mi == this.mi) return this;
X10Binary_c n = (X10Binary_c) copy();
n.mi = mi;
return n;
}
// FIXME: need to figure out if the implementation is pure (can't assume that for user-overloadable operators)
protected static boolean isPureOperation(Type left, Operator op, Type right) {
switch (op) {
case ADD:
case SUB:
case MUL:
return true;
case DIV:
case MOD:
return false; // division/modulus can throw an exception, thus is not pure
case EQ:
case NE:
case GT:
case LT:
case GE:
case LE:
return true;
case SHL:
case SHR:
case USHR:
return true;
case BIT_AND:
case BIT_OR:
case BIT_XOR:
return true;
case COND_AND:
case COND_OR:
return true;
case ARROW:
case DOT_DOT:
return false;
}
return false;
}
public boolean isConstant() {
if (left.isConstant() && right.isConstant() && isPureOperation(left.type(), op, right.type())) {
if (op == EQ || op == NE) {
// Additional checks for type equality because conversions not applied for ==
Type lt = left.type();
Type rt = right.type();
TypeSystem xts = (TypeSystem) lt.typeSystem();
if (lt == null || rt == null)
return false;
if (lt.isClass() && rt.isClass()) {
X10ClassType ltc = (X10ClassType)lt.toClass();
X10ClassType rtc = (X10ClassType)rt.toClass();
if (ltc.isX10Struct() || rtc.isX10Struct()) {
return xts.typeBaseEquals(ltc, rtc, xts.emptyContext());
}
}
}
return true;
}
return false;
}
public ConstantValue constantValue() {
ConstantValue result = superConstantValue();
if (result != null)
return result;
if (!isConstant())
return null;
Type lt = left.type();
Type rt = right.type();
TypeSystem xts = (TypeSystem) lt.typeSystem();
Context context = (Context) xts.emptyContext();
// [IP] An optimization: a struct and null can never be equal
if (op == EQ) {
if (xts.isStructType(lt) && rt.isNull())
return ConstantValue.makeBoolean(false);
if (xts.isStructType(rt) && lt.isNull())
return ConstantValue.makeBoolean(false);
}
if (op == NE) {
if (xts.isStructType(lt) && rt.isNull())
return ConstantValue.makeBoolean(true);
if (xts.isStructType(rt) && lt.isNull())
return ConstantValue.makeBoolean(true);
return null;
}
return null;
}
private ConstantValue superConstantValue() {
if (!isConstant()) {
return null;
}
ConstantValue lv = left.constantValue();
ConstantValue rv = right.constantValue();
if (lv == null || rv == null) {
System.out.println("AJA "+this+" ::: "+lv+" ::: "+rv);
System.out.println(left+" "+left.getClass());
}
if (op == ADD && (lv instanceof StringValue || rv instanceof StringValue)) {
// toString() on a ConstantValue gives the same String as toString on the value itself.
return ConstantValue.makeString(lv.toString() + rv.toString());
}
if (op == EQ && (lv instanceof StringValue && rv instanceof StringValue)) {
return ConstantValue.makeBoolean(((StringValue) lv).value().equals(((StringValue)rv).value()));
}
if (op == NE && (lv instanceof StringValue && rv instanceof StringValue)) {
return ConstantValue.makeBoolean(!((StringValue) lv).value().equals(((StringValue)rv).value()));
}
if (lv instanceof BooleanValue && rv instanceof BooleanValue) {
boolean l = ((BooleanValue) lv).value();
boolean r = ((BooleanValue)rv).value();
if (op == EQ) return ConstantValue.makeBoolean(l == r);
if (op == NE) return ConstantValue.makeBoolean(l != r);
if (op == BIT_AND) return ConstantValue.makeBoolean(l & r);
if (op == BIT_OR) return ConstantValue.makeBoolean(l | r);
if (op == BIT_XOR) return ConstantValue.makeBoolean(l ^ r);
if (op == COND_AND) return ConstantValue.makeBoolean(l && r);
if (op == COND_OR) return ConstantValue.makeBoolean(l || r);
}
try {
if (lv instanceof DoubleValue || rv instanceof DoubleValue) {
// args promoted to double if needed and result will be a double
double l = lv.doubleValue();
double r = rv.doubleValue();
if (op == ADD) return ConstantValue.makeDouble(l + r);
if (op == SUB) return ConstantValue.makeDouble(l - r);
if (op == MUL) return ConstantValue.makeDouble(l * r);
if (op == DIV) return ConstantValue.makeDouble(l / r);
if (op == MOD) return ConstantValue.makeDouble(l % r);
if (op == EQ) return ConstantValue.makeBoolean(l == r);
if (op == NE) return ConstantValue.makeBoolean(l != r);
if (op == LT) return ConstantValue.makeBoolean(l < r);
if (op == LE) return ConstantValue.makeBoolean(l <= r);
if (op == GE) return ConstantValue.makeBoolean(l >= r);
if (op == GT) return ConstantValue.makeBoolean(l > r);
}
if (lv instanceof FloatValue || rv instanceof FloatValue) {
// args promoted to float if needed and result will be a float
float l = lv.floatValue();
float r = rv.floatValue();
if (op == ADD) return ConstantValue.makeFloat(l + r);
if (op == SUB) return ConstantValue.makeFloat(l - r);
if (op == MUL) return ConstantValue.makeFloat(l * r);
if (op == DIV) return ConstantValue.makeFloat(l / r);
if (op == MOD) return ConstantValue.makeFloat(l % r);
if (op == EQ) return ConstantValue.makeBoolean(l == r);
if (op == NE) return ConstantValue.makeBoolean(l != r);
if (op == LT) return ConstantValue.makeBoolean(l < r);
if (op == LE) return ConstantValue.makeBoolean(l <= r);
if (op == GE) return ConstantValue.makeBoolean(l >= r);
if (op == GT) return ConstantValue.makeBoolean(l > r);
}
if (lv instanceof CharValue || rv instanceof CharValue) {
long l = lv.integralValue();
long r = rv.integralValue();
if (op == ADD) return ConstantValue.makeChar((char)(l + r));
if (op == SUB) return ConstantValue.makeChar((char)(l -r));
if (op == EQ) return ConstantValue.makeBoolean(l == r);
if (op == NE) return ConstantValue.makeBoolean(l != r);
if (op == LT) return ConstantValue.makeBoolean(l < r);
if (op == LE) return ConstantValue.makeBoolean(l <= r);
if (op == GE) return ConstantValue.makeBoolean(l >= r);
if (op == GT) return ConstantValue.makeBoolean(l > r);
}
if (lv instanceof IntegralValue || rv instanceof IntegralValue) {
long l = lv.integralValue();
long r = rv.integralValue();
IntLit.Kind lk = null;
IntLit.Kind rk = null;
if (lv instanceof IntegralValue) {
lk = ((IntegralValue)lv).kind();
}
if (rv instanceof IntegralValue) {
rk = ((IntegralValue)rv).kind();
}
- IntLit.Kind resultKind = lk == rk ? lk : meet(lk, rk);
-
- if (op == ADD) return ConstantValue.makeIntegral(l + r, resultKind);
- if (op == SUB) return ConstantValue.makeIntegral(l -r, resultKind);
- if (op == MUL) return ConstantValue.makeIntegral(l * r, resultKind);
- if (op == DIV) return ConstantValue.makeIntegral(l / r, resultKind);;
- if (op == MOD) return ConstantValue.makeIntegral(l % r, resultKind);;
+
+ if (op == ADD) return ConstantValue.makeIntegral(l + r, meet(lk, rk));
+ if (op == SUB) return ConstantValue.makeIntegral(l -r, meet(lk, rk));
+ if (op == MUL) return ConstantValue.makeIntegral(l * r, meet(lk, rk));
+ if (op == DIV) return ConstantValue.makeIntegral(l / r, meet(lk, rk));;
+ if (op == MOD) return ConstantValue.makeIntegral(l % r, meet(lk, rk));;
if (op == EQ) return ConstantValue.makeBoolean(l == r);
if (op == NE) return ConstantValue.makeBoolean(l != r);
- if (op == BIT_AND) return ConstantValue.makeIntegral(l & r, resultKind);;
- if (op == BIT_OR) return ConstantValue.makeIntegral(l | r, resultKind);
- if (op == BIT_XOR) return ConstantValue.makeIntegral(l ^ r, resultKind);
- if (op == SHL) return ConstantValue.makeIntegral(l << r, resultKind);
+ if (op == BIT_AND) return ConstantValue.makeIntegral(l & r, meet(lk, rk));;
+ if (op == BIT_OR) return ConstantValue.makeIntegral(l | r, meet(lk, rk));
+ if (op == BIT_XOR) return ConstantValue.makeIntegral(l ^ r, meet(lk, rk));
+ if (op == SHL) return ConstantValue.makeIntegral(l << r, lk);
if (op == SHR) {
if (lk.isSigned()) {
- return ConstantValue.makeIntegral(l >> r, resultKind);
+ return ConstantValue.makeIntegral(l >> r, lk);
} else {
- return ConstantValue.makeIntegral(l >>> r, resultKind);
+ return ConstantValue.makeIntegral(l >>> r, lk);
}
}
- if (op == USHR) return ConstantValue.makeIntegral(l >>> r, resultKind);
- if (resultKind.isSigned()) {
+ if (op == USHR) return ConstantValue.makeIntegral(l >>> r, lk);
+ if (meet(lk, rk).isSigned()) {
if (op == LT) return ConstantValue.makeBoolean(l < r);
if (op == LE) return ConstantValue.makeBoolean(l <= r);
if (op == GE) return ConstantValue.makeBoolean(l >= r);
if (op == GT) return ConstantValue.makeBoolean(l > r);
} else {
long lAdj = l + Long.MIN_VALUE;
long rAdj = r + Long.MIN_VALUE;
if (op == LT) return ConstantValue.makeBoolean(lAdj < rAdj);
if (op == LE) return ConstantValue.makeBoolean(lAdj <= rAdj);
if (op == GE) return ConstantValue.makeBoolean(lAdj >= rAdj);
if (op == GT) return ConstantValue.makeBoolean(lAdj > rAdj);
}
}
} catch (ArithmeticException e) {
// Actually unreachable because MOD/DIV are not pure.
// Therefore isConstant will return false.
// However, leave in place for future in case we remove the isPure check in isConstant
return null;
}
return null;
}
private Kind meet(Kind lk, Kind rk) {
+ if (lk == rk) return lk;
if (lk == IntLit.Kind.ULONG || rk == IntLit.Kind.ULONG) return IntLit.Kind.ULONG;
if (lk == IntLit.Kind.LONG || rk == IntLit.Kind.LONG) return IntLit.Kind.LONG;
if (lk == IntLit.Kind.UINT || rk == IntLit.Kind.UINT) return IntLit.Kind.UINT;
if (lk == IntLit.Kind.INT || rk == IntLit.Kind.INT) return IntLit.Kind.INT;
if (lk == IntLit.Kind.USHORT || rk == IntLit.Kind.USHORT) return IntLit.Kind.USHORT;
if (lk == IntLit.Kind.SHORT || rk == IntLit.Kind.SHORT) return IntLit.Kind.SHORT;
if (lk == IntLit.Kind.UBYTE || rk == IntLit.Kind.UBYTE) return IntLit.Kind.UBYTE;
if (lk == IntLit.Kind.BYTE || rk == IntLit.Kind.BYTE) return IntLit.Kind.BYTE;
throw new InternalCompilerError("Unknown meet of kinds "+lk+" "+rk);
}
/** If the expression was parsed as an ambiguous expression, return a Receiver that would have parsed the same way. Otherwise, return null. */
private static Receiver toReceiver(NodeFactory nf, Expr e) {
if (e instanceof AmbExpr) {
AmbExpr e1 = (AmbExpr) e;
return nf.AmbReceiver(e.position(), null, e1.name());
}
if (e instanceof Field) {
Field f = (Field) e;
if (f.target() instanceof Expr) {
Prefix p = toPrefix(nf, (Expr) f.target());
if (p == null)
return null;
return nf.AmbReceiver(e.position(), p, f.name());
}
else {
return nf.AmbReceiver(e.position(), f.target(), f.name());
}
}
return null;
}
/** If the expression was parsed as an ambiguous expression, return a Prefix that would have parsed the same way. Otherwise, return null. */
private static Prefix toPrefix(NodeFactory nf, Expr e) {
if (e instanceof AmbExpr) {
AmbExpr e1 = (AmbExpr) e;
return nf.AmbPrefix(e.position(), null, e1.name());
}
if (e instanceof Field) {
Field f = (Field) e;
if (f.target() instanceof Expr) {
Prefix p = toPrefix(nf, (Expr) f.target());
if (p == null)
return null;
return nf.AmbPrefix(e.position(), p, f.name());
}
else {
return nf.AmbPrefix(e.position(), f.target(), f.name());
}
}
return null;
}
// HACK: T1==T2 can sometimes be parsed as e1==e2. Correct that.
@Override
public Node typeCheckOverride(Node parent, ContextVisitor tc) {
if (op == EQ) {
NodeFactory nf = (NodeFactory) tc.nodeFactory();
Receiver t1 = toReceiver(nf, left);
Receiver t2 = toReceiver(nf, right);
if (t1 != null && t2 != null) {
Node n1 = this.visitChild(t1, tc);
Node n2 = this.visitChild(t2, tc);
if (n1 instanceof TypeNode && n2 instanceof TypeNode) {
SubtypeTest n = nf.SubtypeTest(position(), (TypeNode) n1, (TypeNode) n2, true);
n = (SubtypeTest) n.typeCheck(tc);
return n;
}
}
}
return null;
}
public static Name binaryMethodName(Binary.Operator op) {
Map<Binary.Operator,String> methodNameMap = CollectionFactory.newHashMap();
methodNameMap.put(ADD, "operator+");
methodNameMap.put(SUB, "operator-");
methodNameMap.put(MUL, "operator*");
methodNameMap.put(DIV, "operator/");
methodNameMap.put(MOD, "operator%");
methodNameMap.put(BIT_AND, "operator&");
methodNameMap.put(BIT_OR, "operator|");
methodNameMap.put(BIT_XOR, "operator^");
methodNameMap.put(COND_OR, "operator||");
methodNameMap.put(COND_AND, "operator&&");
methodNameMap.put(SHL, "operator<<");
methodNameMap.put(SHR, "operator>>");
methodNameMap.put(USHR, "operator>>>");
methodNameMap.put(LT, "operator<");
methodNameMap.put(GT, "operator>");
methodNameMap.put(LE, "operator<=");
methodNameMap.put(GE, "operator>=");
methodNameMap.put(DOT_DOT, "operator..");
methodNameMap.put(ARROW, "operator->");
methodNameMap.put(LARROW, "operator<-");
methodNameMap.put(FUNNEL, "operator-<");
methodNameMap.put(LFUNNEL, "operator>-");
methodNameMap.put(STARSTAR, "operator**");
methodNameMap.put(TWIDDLE, "operator~");
methodNameMap.put(NTWIDDLE, "operator!~");
methodNameMap.put(BANG, "operator!");
String methodName = methodNameMap.get(op);
if (methodName == null)
return null;
return Name.makeUnchecked(methodName);
}
public static final String INVERSE_OPERATOR_PREFIX = "inverse_";
public static Name invBinaryMethodName(Binary.Operator op) {
Name n = binaryMethodName(op);
if (n == null)
return null;
return Name.makeUnchecked(INVERSE_OPERATOR_PREFIX + n.toString());
}
public static boolean isInv(Name name) {
return name.toString().startsWith(INVERSE_OPERATOR_PREFIX);
}
private static Type promote(TypeSystem ts, Type t1, Type t2) {
if (ts.isByte(t1)) {
return t2;
}
if (ts.isShort(t1)) {
if (ts.isByte(t2))
return t1;
return t2;
}
if (ts.isInt(t1)) {
if (ts.isByte(t2) || ts.isShort(t2))
return t1;
return t2;
}
if (ts.isLong(t1)) {
if (ts.isByte(t2) || ts.isShort(t2) || ts.isInt(t2))
return t1;
return t2;
}
if (ts.isUByte(t1)) {
return t2;
}
if (ts.isUShort(t1)) {
if (ts.isUByte(t2))
return t1;
return t2;
}
if (ts.isUInt(t1)) {
if (ts.isUByte(t2) || ts.isUShort(t2))
return t1;
return t2;
}
if (ts.isULong(t1)) {
if (ts.isUByte(t2) || ts.isUShort(t2) || ts.isUInt(t2))
return t1;
return t2;
}
if (ts.isFloat(t1)) {
if (ts.isByte(t2) || ts.isShort(t2) || ts.isInt(t2) || ts.isLong(t2))
return t1;
if (ts.isUByte(t2) || ts.isUShort(t2) || ts.isUInt(t2) || ts.isULong(t2))
return t1;
return t2;
}
if (ts.isDouble(t1)) {
return t1;
}
return null;
}
/**
* Type check a binary expression. Must take care of various cases because
* of operators on regions, distributions, points, places and arrays.
* An alternative implementation strategy is to resolve each into a method
* call.
*/
public Node typeCheck(ContextVisitor tc) {
TypeSystem xts = (TypeSystem) tc.typeSystem();
Context context = (Context) tc.context();
Type lbase = Types.baseType(left.type());
Type rbase = Types.baseType(right.type());
if (xts.hasUnknown(lbase) || xts.hasUnknown(rbase))
return this.type(xts.unknownType(position()));
if (op == EQ || op == NE || op == LT || op == GT || op == LE || op == GE) {
// XTENLANG-2156
//Object lv = left.isConstant() ? left.constantValue() : null;
//Object rv = right.isConstant() ? right.constantValue() : null;
//
//// If comparing signed vs. unsigned, check if one operand is a constant convertible to the other (base) type.
//// If so, insert the conversion and check again.
//
//if ((xts.isSigned(lbase) && xts.isUnsigned(rbase)) || (xts.isUnsigned(lbase) && xts.isSigned(rbase))) {
// try {
// if (lv != null && xts.numericConversionValid(rbase, lbase, lv, context)) {
// Expr e = Converter.attemptCoercion(tc, left, rbase);
// if (e == left)
// return this.type(xts.Boolean());
// if (e != null)
// return Converter.check(this.left(e), tc);
// }
// if (rv != null && xts.numericConversionValid(lbase, rbase, rv, context)) {
// Expr e = Converter.attemptCoercion(tc, right, lbase);
// if (e == right)
// return this.type(xts.Boolean());
// if (e != null)
// return Converter.check(this.right(e), tc);
// }
// } catch (SemanticException e) { } // FIXME
//}
if (xts.isUnsigned(lbase) && xts.isSigned(rbase))
Errors.issue(tc.job(),
new Errors.CannotCompareUnsignedVersusSignedValues(position()));
if (xts.isSigned(lbase) && xts.isUnsigned(rbase))
Errors.issue(tc.job(),
new Errors.CannotCompareSignedVersusUnsignedValues(position()));
}
if (op == EQ || op == NE) {
// == and != are allowed if the *unconstrained* types can be cast to each other without coercions.
// Coercions are handled above for numerics. No other coercions are allowed.
// Constraints are ignored so that things like x==k will not cause compile-time errors
// when x is a final variable initialized to a constant != k.
// Yoav: I remove the constraints from inside generic arguments as well (see XTENLANG-2022)
Type lbbase = Types.stripConstraints(lbase);
Type rbbase = Types.stripConstraints(rbase);
if (xts.isCastValid(lbbase, rbbase, context) || xts.isCastValid(rbbase, lbbase, context)) {
return type(xts.Boolean());
}
//
// if (xts.isImplicitCastValid(lbase, rbase, context) || xts.isImplicitCastValid(rbase, lbase, context)) {
// assert false : "isCastValid but isImplicitCastValid not for " + lbase + " and " + rbase;
// return type(xts.Boolean());
// }
Errors.issue(tc.job(),
new Errors.OperatorMustHaveOperandsOfComparabletype(lbase, rbase, position()));
return this.type(xts.Boolean());
}
X10Call c = desugarBinaryOp(this, tc);
if (c != null) {
MethodInstance mi = (MethodInstance) c.methodInstance();
Warnings.checkErrorAndGuard(tc,mi, this);
X10Binary_c result = (X10Binary_c) this.methodInstance(mi).type(c.type());
// rebuild the binary using the call's arguments. We'll actually use the call node after desugaring.
if (mi.flags().isStatic()) {
return result.left(c.arguments().get(0)).right(c.arguments().get(1));
}
else if (!c.name().id().equals(invBinaryMethodName(this.operator()))) {
assert (c.name().id().equals(binaryMethodName(this.operator())));
return result.left((Expr) c.target()).right(c.arguments().get(0));
}
else {
return result.invert(true).left(c.arguments().get(0)).right((Expr) c.target());
}
}
Type l = left.type();
Type r = right.type();
if (!xts.hasUnknown(l) && !xts.hasUnknown(r)) {
if (op == COND_OR || op == COND_AND) {
Type result = xts.Boolean();
if (op == COND_OR)
return this.type(xts.Boolean());
if (l.isBoolean() && r.isBoolean()) {
return this.type(BuiltInTypeRules.adjustReturnTypeForConjunction(l,r, context));
}
}
Errors.issue(tc.job(),
new Errors.NoOperationFoundForOperands(op, l, r, position()));
}
return this.type(xts.unknownType(position()));
}
public static X10Call_c typeCheckCall(ContextVisitor tc, X10Call_c call) {
List<Type> typeArgs = new ArrayList<Type>(call.typeArguments().size());
for (TypeNode tn : call.typeArguments()) {
typeArgs.add(tn.type());
}
List<Type> argTypes = new ArrayList<Type>(call.arguments().size());
for (Expr e : call.arguments()) {
Type et = e.type();
argTypes.add(et);
}
Type targetType = call.target().type();
MethodInstance mi = null;
List<Expr> args = null;
// First try to find the method without implicit conversions.
Pair<MethodInstance, List<Expr>> p = Checker.findMethod(tc, call, targetType, call.name().id(), typeArgs, argTypes);
mi = p.fst();
args = p.snd();
if (mi.error() != null) {
try {
// Now, try to find the method with implicit conversions, making them explicit.
p = Checker.tryImplicitConversions(call, tc, targetType, call.name().id(), typeArgs, argTypes);
mi = p.fst();
args = p.snd();
} catch (SemanticException e) {
// FIXME: [IP] The exception may indicate that there's an ambiguity, which is better than reporting that a method is not found.
int i = 3;
}
}
Type rt = Checker.rightType(mi.rightType(), mi.x10Def(), call.target(), tc.context());
call = (X10Call_c) call.methodInstance(mi).type(rt);
call = (X10Call_c) call.arguments(args);
return call;
}
public static X10Call_c searchInstance1(Name methodName, Position pos, ContextVisitor tc, Expr first, Expr second) {
NodeFactory nf = tc.nodeFactory();
// Check if there is a method with the appropriate name and type with the left operand as receiver.
X10Call_c n2 = (X10Call_c) nf.X10Call(pos, first, nf.Id(pos, methodName), Collections.<TypeNode>emptyList(), Collections.singletonList(second));
n2 = typeCheckCall(tc, n2);
MethodInstance mi2 = (MethodInstance) n2.methodInstance();
if (mi2.error() == null && !mi2.def().flags().isStatic())
return n2;
return null;
}
public static X10Call_c searchInstance(Name methodName, Position pos, ContextVisitor tc, Expr first, Expr second) {
if (methodName != null) {
X10Call_c res = searchInstance1(methodName,pos,tc,first,second);
if (res!=null) return res;
// maybe the left operand can be cast to the right operand (e.g., Byte+Int should use Int.operator+(Int) and not Byte.operator+(Byte))
Expr newFirst = Converter.attemptCoercion(
tc, first,
Types.baseType(second.type())); // I use baseType because the constraints are irrelevant for resolution (and it can cause an error if the constraint contain "place23423423")
if (newFirst!=first && newFirst!=null) {
return searchInstance1(methodName,pos,tc,newFirst,second);
}
}
return null;
}
public static X10Call_c desugarBinaryOp(Binary n, ContextVisitor tc) {
Expr left = n.left();
Expr right = n.right();
Binary.Operator op = n.operator();
Position pos = n.position();
TypeSystem xts = tc.typeSystem();
Type l = left.type();
Type r = right.type();
// Equality operators are special
if (op == EQ || op == NE)
return null;
// Conditional operators on Booleans are special
if ((op == COND_OR || op == COND_AND) && l.isBoolean() && r.isBoolean())
return null;
NodeFactory nf = tc.nodeFactory();
Name methodName = X10Binary_c.binaryMethodName(op);
Name invMethodName = X10Binary_c.invBinaryMethodName(op);
// TODO: byte+byte should convert both bytes to int and search int
// For now, we have to define byte+byte in byte.x10.
X10Call_c virtual_left;
X10Call_c virtual_right;
X10Call_c static_left = null;
X10Call_c static_right = null;
virtual_right = searchInstance(invMethodName,pos,tc,right,left);
virtual_left = searchInstance(methodName,pos,tc,left,right);
if (methodName != null) {
// Check if there is a static method of the left type with the appropriate name and type.
X10Call_c n4 = (X10Call_c) nf.X10Call(pos, nf.CanonicalTypeNode(pos, Types.ref(l)),
nf.Id(pos, methodName), Collections.<TypeNode>emptyList(),
CollectionUtil.list(left, right));
n4 = typeCheckCall(tc, n4);
MethodInstance mi4 = (MethodInstance) n4.methodInstance();
if (mi4.error() == null && mi4.def().flags().isStatic())
static_left = n4;
}
if (methodName != null && !xts.hasSameClassDef(l, r)) {
// Check if there is a static method of the right type with the appropriate name and type.
X10Call_c n3 = (X10Call_c) nf.X10Call(pos, nf.CanonicalTypeNode(pos, Types.ref(r)),
nf.Id(pos, methodName), Collections.<TypeNode>emptyList(),
CollectionUtil.list(left, right));
n3 = typeCheckCall(tc, n3);
MethodInstance mi3 = (MethodInstance) n3.methodInstance();
if (mi3.error() == null && mi3.def().flags().isStatic())
static_right = n3;
}
List<X10Call_c> defs = new ArrayList<X10Call_c>();
if (virtual_left != null) defs.add(virtual_left);
if (virtual_right != null) defs.add(virtual_right);
if (static_left != null) defs.add(static_left);
if (static_right != null) defs.add(static_right);
if (defs.size() == 0) {
if (methodName == null)
return null;
// Create a fake static method in the left type with the appropriate name and type.
X10Call_c fake = (X10Call_c) nf.Call(pos, nf.CanonicalTypeNode(pos, left.type()), nf.Id(pos, methodName), left, right);
fake = typeCheckCall(tc, fake);
return fake;
}
List<X10Call_c> best = new ArrayList<X10Call_c>();
X10Binary_c.Conversion bestConversion = X10Binary_c.Conversion.UNKNOWN;
for (int i = 0; i < defs.size(); i++) {
X10Call_c n1 = defs.get(i);
// Check if n needs a conversion
Expr[] actuals = new Expr[] {
n1.arguments().size() != 2 ? (Expr) n1.target() : n1.arguments().get(0),
n1.arguments().size() != 2 ? n1.arguments().get(0) : n1.arguments().get(1),
};
boolean inverse = isInv(n1.name().id());
Expr[] original = new Expr[] {
inverse ? right : left,
inverse ? left : right,
};
X10Binary_c.Conversion conversion = X10Binary_c.conversionNeeded(actuals, original);
if (bestConversion.harder(conversion)) {
best.clear();
best.add(n1);
bestConversion = conversion;
}
else if (conversion.harder(bestConversion)) {
// best is still the best
}
else { // all other things being equal
MethodDef md = n1.methodInstance().def();
Type td = Types.get(md.container());
ClassDef cd = def(td);
boolean isBetter = false;
for (Iterator<X10Call_c> ci = best.iterator(); ci.hasNext(); ) {
X10Call_c c = ci.next();
MethodDef bestmd = c.methodInstance().def();
if (bestmd == md) break; // same method by a different path; already in best
Type besttd = Types.get(bestmd.container());
if (xts.isUnknown(besttd) || xts.isUnknown(td)) {
// going to create a fake one anyway; might as well get more data
isBetter = true;
continue;
}
ClassDef bestcd = def(besttd);
assert (bestcd != null && cd != null);
if (cd != bestcd && xts.descendsFrom(cd, bestcd)) {
// we found the method of a subclass; remove the superclass one
ci.remove();
isBetter = true;
assert (bestConversion == conversion);
bestConversion = conversion;
}
else if (cd != bestcd && xts.descendsFrom(bestcd, cd)) {
// best is still the best
isBetter = false;
break;
}
else {
isBetter = true;
}
}
if (isBetter)
best.add(n1);
}
}
assert (best.size() != 0);
X10Call_c result = best.get(0);
if (best.size() > 1) {
List<MethodInstance> bestmis = new ArrayList<MethodInstance>();
Type rt = null;
boolean rtset = false;
ClassType ct = null;
boolean ctset = false;
// See if all matches have the same container and return type, and save that to avoid losing information.
for (X10Call_c c : best) {
MethodInstance xmi = c.methodInstance();
bestmis.add(xmi);
if (!rtset) {
rt = xmi.returnType();
rtset = true;
} else if (rt != null && !xts.typeEquals(rt, xmi.returnType(), tc.context())) {
if (xts.typeBaseEquals(rt, xmi.returnType(), tc.context())) {
rt = Types.baseType(rt);
} else {
rt = null;
}
}
if (!ctset) {
ct = xmi.container().toClass();
ctset = true;
} else if (ct != null && !xts.typeEquals(ct, xmi.container(), tc.context())) {
if (xts.typeBaseEquals(ct, xmi.container(), tc.context())) {
ct = Types.baseType(ct).toClass();
} else {
ct = null;
}
}
}
if (ct == null) ct = l.toClass(); // arbitrarily pick the left operand
SemanticException error = new Errors.AmbiguousOperator(op, bestmis, pos);
MethodInstance mi = xts.createFakeMethod(ct, Flags.PUBLIC.Static(), methodName,
Collections.<Type>emptyList(), CollectionUtil.list(l, r), error);
if (rt != null) mi = mi.returnType(rt);
result = (X10Call_c) nf.X10Call(pos, nf.CanonicalTypeNode(pos, Types.ref(ct)),
nf.Id(pos, methodName), Collections.<TypeNode>emptyList(),
CollectionUtil.list(left, right)).methodInstance(mi).type(mi.returnType());
}
{
MethodInstance mi = result.methodInstance();
boolean inverse = isInv(mi.name());
left = result.arguments().size() != 2 ? (Expr) result.target() : result.arguments().get(0);
right = result.arguments().size() != 2 ? result.arguments().get(0) : result.arguments().get(1);
Type lbase = Types.baseType(left.type());
Type rbase = Types.baseType(right.type());
Context context = (Context) tc.context();
// Add support for patching up the return type of Region's operator*().
// The rank of the result is a+b, if the rank of the left arg is a and of the right arg is b,
// and a and b are literals. Further the result is rect if both args are rect, and zeroBased
// if both args are zeroBased.
if (op == Binary.MUL && xts.typeEquals(xts.Region(), lbase, context)
&& xts.typeEquals(xts.Region(), rbase, context)) {
Type type = result.type();
type = BuiltInTypeRules.adjustReturnTypeForRegionMult(left, right, type, context);
mi = mi.returnType(type);
result = (X10Call_c) result.methodInstance(mi).type(type);
}
// Add support for patching up the return type of IntRegion's operator*().
// The rank of the result is 2. Further the result is zeroBased if both args are zeroBased.
if (op == Binary.MUL && xts.typeEquals(xts.IntRange(), lbase, context)
&& xts.typeEquals(xts.IntRange(), rbase, context)) {
Type type = result.type();
type = BuiltInTypeRules.adjustReturnTypeForRangeRangeMult(left, right, type, context);
mi = mi.returnType(type);
result = (X10Call_c) result.methodInstance(mi).type(type);
}
// Add support for patching up the return type of Int's operator..(),
// The result is zeroBased if the left arg is 0.
if (op == Binary.DOT_DOT && xts.typeEquals(xts.Int(), lbase, context)
&& xts.typeEquals(xts.Int(), rbase, context)) {
Type type = result.type();
type = BuiltInTypeRules.adjustReturnTypeForIntRange(left, right, type, context);
mi = mi.returnType(type);
result = (X10Call_c) result.methodInstance(mi).type(type);
}
}
try {
result = (X10Call_c) PlaceChecker.makeReceiverLocalIfNecessary(result, tc);
} catch (SemanticException e) {
MethodInstance mi = (MethodInstance) result.methodInstance();
if (mi.error() == null)
result = (X10Call_c) result.methodInstance(mi.error(e));
}
if (n.isConstant())
result = result.constantValue(n.constantValue());
return result;
}
/**
* Get the class that defines type t. Only returns null if
* t is a parameter type or an unknown type.
*/
public static ClassDef def(Type t) {
Type base = Types.baseType(t);
if (base instanceof ClassType)
return ((ClassType) base).def();
return null;
}
public static enum Conversion {
NONE { boolean harder(Conversion a) { return false; } },
IMPLICIT { boolean harder(Conversion a) { return a == NONE; } },
EXPLICIT { boolean harder(Conversion a) { return a == NONE || a == IMPLICIT; } },
UNKNOWN { boolean harder(Conversion a) { return a != UNKNOWN; } };
abstract boolean harder(Conversion b);
}
public static Conversion conversionNeeded(Expr[] actuals, Expr[] original) {
Conversion result = Conversion.NONE;
for (int k = 0; k < actuals.length; k++) {
if (actuals[k] != original[k]) {
if (result == Conversion.NONE)
result = Conversion.IMPLICIT;
if (actuals[k] instanceof X10Call) {
X10Call c = (X10Call) actuals[k];
if (c.methodInstance().name() == Converter.operator_as) {
result = Conversion.EXPLICIT;
}
}
}
}
return result;
}
public static Expr coerceToString(ContextVisitor tc, Expr e) throws SemanticException {
TypeSystem ts = tc.typeSystem();
if (!e.type().isSubtype(ts.String(), tc.context())) {
NodeFactory nf = tc.nodeFactory();
e = nf.X10Call(e.position(), nf.CanonicalTypeNode(e.position(), ts.String()),
nf.Id(e.position(), Name.make("valueOf")),
Collections.<TypeNode>emptyList(), Collections.singletonList(e));
return (Expr) e.del().disambiguate(tc).typeCheck(tc).checkConstants(tc);
}
return e;
}
/** Get the left operand of the expression. */
public Expr left() {
return this.left;
}
/** Set the left operand of the expression. */
public Binary left(Expr left) {
X10Binary_c n = (X10Binary_c) copy();
n.left = left;
return n;
}
/** Get the operator of the expression. */
public Operator operator() {
return this.op;
}
/** Set the operator of the expression. */
public Binary operator(Operator op) {
X10Binary_c n = (X10Binary_c) copy();
n.op = op;
return n;
}
/** Get the right operand of the expression. */
public Expr right() {
return this.right;
}
/** Set the right operand of the expression. */
public Binary right(Expr right) {
X10Binary_c n = (X10Binary_c) copy();
n.right = right;
return n;
}
/** Get the precedence of the expression. */
public Precedence precedence() {
return this.precedence;
}
public Binary precedence(Precedence precedence) {
X10Binary_c n = (X10Binary_c) copy();
n.precedence = precedence;
return n;
}
/** Reconstruct the expression. */
protected Binary_c reconstruct(Expr left, Expr right) {
if (left != this.left || right != this.right) {
X10Binary_c n = (X10Binary_c) copy();
n.left = left;
n.right = right;
return n;
}
return this;
}
/** Visit the children of the expression. */
public Node visitChildren(NodeVisitor v) {
Expr left = (Expr) visitChild(this.left, v);
Expr right = (Expr) visitChild(this.right, v);
return reconstruct(left, right);
}
/** Get the throwsArithmeticException of the expression. */
public boolean throwsArithmeticException() {
// conservatively assume that any division or mod may throw
// ArithmeticException this is NOT true-- floats and doubles don't
// throw any exceptions ever...
return op == DIV || op == MOD;
}
public String toString() {
return left + " " + op + " " + right;
}
/** Write the expression to an output file. */
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
printSubExpr(left, true, w, tr);
w.write(" ");
w.write(op.toString());
w.allowBreak(type() == null || type().isJavaPrimitive() ? 2 : 0, " ");
printSubExpr(right, false, w, tr);
}
public void dump(CodeWriter w) {
super.dump(w);
if (type != null) {
w.allowBreak(4, " ");
w.begin(0);
w.write("(type " + type + ")");
w.end();
}
w.allowBreak(4, " ");
w.begin(0);
w.write("(operator " + op + ")");
w.end();
}
public Term firstChild() {
return left;
}
public <S> List<S> acceptCFG(CFGBuilder v, List<S> succs) {
if (op == COND_AND || op == COND_OR) {
// short-circuit
if (left instanceof BooleanLit) {
BooleanLit b = (BooleanLit) left;
if ((b.value() && op == COND_OR) || (! b.value() && op == COND_AND)) {
v.visitCFG(left, this, EXIT);
}
else {
v.visitCFG(left, right, ENTRY);
v.visitCFG(right, this, EXIT);
}
}
else {
if (op == COND_AND) {
// AND operator
// short circuit means that left is false
v.visitCFG(left, FlowGraph.EDGE_KEY_TRUE, right,
ENTRY, FlowGraph.EDGE_KEY_FALSE, this, EXIT);
}
else {
// OR operator
// short circuit means that left is true
v.visitCFG(left, FlowGraph.EDGE_KEY_FALSE, right,
ENTRY, FlowGraph.EDGE_KEY_TRUE, this, EXIT);
}
v.visitCFG(right, FlowGraph.EDGE_KEY_TRUE, this,
EXIT, FlowGraph.EDGE_KEY_FALSE, this, EXIT);
}
}
else {
if (left.type().isBoolean() && right.type().isBoolean()) {
v.visitCFG(left, FlowGraph.EDGE_KEY_TRUE, right,
ENTRY, FlowGraph.EDGE_KEY_FALSE, right, ENTRY);
v.visitCFG(right, FlowGraph.EDGE_KEY_TRUE, this,
EXIT, FlowGraph.EDGE_KEY_FALSE, this, EXIT);
}
else {
v.visitCFG(left, right, ENTRY);
v.visitCFG(right, this, EXIT);
}
}
return succs;
}
public List<Type> throwTypes(TypeSystem ts) {
if (throwsArithmeticException()) {
return Collections.<Type>singletonList(ts.ArithmeticException());
}
return Collections.<Type>emptyList();
}
}
| false | false | null | null |
diff --git a/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartDisplayPeer.java b/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartDisplayPeer.java
index b19233d..bbd929b 100644
--- a/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartDisplayPeer.java
+++ b/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartDisplayPeer.java
@@ -1,205 +1,215 @@
/*
* This file is part of the Echo2 Chart Library.
* Copyright (C) 2005 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package nextapp.echo2.chart.webcontainer;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import nextapp.echo2.app.Component;
+import nextapp.echo2.app.Extent;
import nextapp.echo2.app.update.ServerComponentUpdate;
import nextapp.echo2.chart.app.ChartDisplay;
import nextapp.echo2.webcontainer.ComponentSynchronizePeer;
import nextapp.echo2.webcontainer.ContainerInstance;
import nextapp.echo2.webcontainer.DomUpdateSupport;
import nextapp.echo2.webcontainer.PartialUpdateManager;
import nextapp.echo2.webcontainer.PartialUpdateParticipant;
import nextapp.echo2.webcontainer.RenderContext;
import nextapp.echo2.webcontainer.RenderState;
+import nextapp.echo2.webcontainer.propertyrender.ExtentRender;
import nextapp.echo2.webrender.ServerMessage;
import nextapp.echo2.webrender.Service;
import nextapp.echo2.webrender.WebRenderServlet;
import nextapp.echo2.webrender.servermessage.DomUpdate;
import nextapp.echo2.webrender.service.JavaScriptService;
/**
* <code>ComponentSynchronizePeer</code> implementation for
* <code>ChartDisplay</code> components.
*/
public class ChartDisplayPeer
implements ComponentSynchronizePeer, DomUpdateSupport {
+
+ protected static final int DEFAULT_WIDTH = 400;
+ protected static final int DEFAULT_HEIGHT = 300;
/**
* Service to provide supporting JavaScript library.
*/
private static final Service CHART_DISPLAY_SERVICE = JavaScriptService.forResource("Echo2Chart.ChartDisplay",
"/nextapp/echo2/chart/webcontainer/resource/js/ChartDisplay.js");
static {
WebRenderServlet.getServiceRegistry().add(CHART_DISPLAY_SERVICE);
}
/**
* <code>RenderState</code> implementation (stores generated image
* to be rendered).
*/
private class ChartRenderState
implements RenderState {
private int version;
}
private PartialUpdateManager partialUpdateManager;
/**
* <code>PartialUpdateParticipant</code> to handle updates to chart requiring graphic image to be updated.
*/
private PartialUpdateParticipant chartContentChangedUpdateParticipant = new PartialUpdateParticipant() {
/**
* @see nextapp.echo2.webcontainer.PartialUpdateParticipant#renderProperty(nextapp.echo2.webcontainer.RenderContext,
* nextapp.echo2.app.update.ServerComponentUpdate)
*/
public void renderProperty(RenderContext rc, ServerComponentUpdate update) {
renderSetImageDirective(rc, (ChartDisplay) update.getParent());
}
/**
* @see nextapp.echo2.webcontainer.PartialUpdateParticipant#canRenderProperty(nextapp.echo2.webcontainer.RenderContext,
* nextapp.echo2.app.update.ServerComponentUpdate)
*/
public boolean canRenderProperty(RenderContext rc, ServerComponentUpdate update) {
return true;
}
};
/**
* Default constructor.
*/
public ChartDisplayPeer() {
partialUpdateManager = new PartialUpdateManager();
partialUpdateManager.add(ChartDisplay.CHART_CONTENT_CHANGED_PROPERTY, chartContentChangedUpdateParticipant);
}
/**
* @see nextapp.echo2.webcontainer.ComponentSynchronizePeer#getContainerId(nextapp.echo2.app.Component)
*/
public String getContainerId(Component child) {
throw new UnsupportedOperationException("ChartDisplay component does not support children.");
}
/**
* @see nextapp.echo2.webcontainer.ComponentSynchronizePeer#renderAdd(nextapp.echo2.webcontainer.RenderContext,
* nextapp.echo2.app.update.ServerComponentUpdate, java.lang.String,
* nextapp.echo2.app.Component)
*/
public void renderAdd(RenderContext rc, ServerComponentUpdate update, String targetId, Component component) {
DocumentFragment htmlFragment = rc.getServerMessage().getDocument().createDocumentFragment();
renderHtml(rc, update, htmlFragment, component);
DomUpdate.renderElementAdd(rc.getServerMessage(), targetId, htmlFragment);
}
/**
* @see nextapp.echo2.webcontainer.ComponentSynchronizePeer#renderDispose(nextapp.echo2.webcontainer.RenderContext,
* nextapp.echo2.app.update.ServerComponentUpdate,
* nextapp.echo2.app.Component)
*/
public void renderDispose(RenderContext rc, ServerComponentUpdate update, Component component) {
// Do nothing.
}
/**
* @see nextapp.echo2.webcontainer.DomUpdateSupport#renderHtml(nextapp.echo2.webcontainer.RenderContext,
* nextapp.echo2.app.update.ServerComponentUpdate, org.w3c.dom.Node, nextapp.echo2.app.Component)
*/
public void renderHtml(RenderContext rc, ServerComponentUpdate update, Node parentNode, Component component) {
ChartDisplay chartDisplay = (ChartDisplay) component;
synchronized (chartDisplay) {
Document document = rc.getServerMessage().getDocument();
String elementId = ContainerInstance.getElementId(chartDisplay);
Element divElement = document.createElement("div");
divElement.setAttribute("id", elementId);
if (chartDisplay.getChart() != null) {
+ int width = ExtentRender.toPixels((Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_WIDTH),
+ DEFAULT_WIDTH);
+ int height = ExtentRender.toPixels((Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_HEIGHT),
+ DEFAULT_HEIGHT);
int version = incrementImageVersion(rc, chartDisplay);
Element imgElement = document.createElement("img");
imgElement.setAttribute("id", elementId + "_image");
imgElement.setAttribute("src", ChartImageService.getUri(rc, chartDisplay, version));
+ imgElement.setAttribute("style", "width:" + width + "px;height:" + height + "px;");
divElement.appendChild(imgElement);
}
parentNode.appendChild(divElement);
}
}
private int incrementImageVersion(RenderContext rc, ChartDisplay chartDisplay) {
ChartRenderState renderState = (ChartRenderState) rc.getContainerInstance().getRenderState(chartDisplay);
if (renderState == null) {
renderState = new ChartRenderState();
rc.getContainerInstance().setRenderState(chartDisplay, renderState);
} else {
++renderState.version;
}
return renderState.version;
}
/**
* Renders a 'set-image' directive to update the displayed chart on the
* client.
*
* @param rc the relevant <code>RenderContext</code>
* @param chartDisplay the <code>ChartDisplay</code> to update
*/
private void renderSetImageDirective(RenderContext rc, ChartDisplay chartDisplay) {
rc.getServerMessage().addLibrary(CHART_DISPLAY_SERVICE.getId());
int version = incrementImageVersion(rc, chartDisplay);
Element setImageElement = rc.getServerMessage().appendPartDirective(ServerMessage.GROUP_ID_POSTUPDATE,
"Echo2Chart.MessageProcessor", "set-image");
setImageElement.setAttribute("eid", ContainerInstance.getElementId(chartDisplay));
setImageElement.setAttribute("new-image", ChartImageService.getUri(rc, chartDisplay, version));
}
/**
* @see nextapp.echo2.webcontainer.ComponentSynchronizePeer#renderUpdate(nextapp.echo2.webcontainer.RenderContext,
* nextapp.echo2.app.update.ServerComponentUpdate, java.lang.String)
*/
public boolean renderUpdate(RenderContext rc, ServerComponentUpdate update, String targetId) {
// Determine if fully replacing the component is required.
if (partialUpdateManager.canProcess(rc, update)) {
partialUpdateManager.process(rc, update);
} else {
DomUpdate.renderElementRemove(rc.getServerMessage(), ContainerInstance.getElementId(update.getParent()));
renderAdd(rc, update, targetId, update.getParent());
}
return true;
}
}
diff --git a/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartImageService.java b/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartImageService.java
index 365e388..8dfb871 100644
--- a/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartImageService.java
+++ b/src/webcontainer/java/nextapp/echo2/chart/webcontainer/ChartImageService.java
@@ -1,140 +1,137 @@
/*
* This file is part of the Echo2 Chart Library.
* Copyright (C) 2005 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package nextapp.echo2.chart.webcontainer;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import org.jfree.chart.JFreeChart;
import nextapp.echo2.app.Extent;
import nextapp.echo2.chart.app.ChartDisplay;
import nextapp.echo2.webcontainer.ContainerInstance;
import nextapp.echo2.webcontainer.RenderContext;
import nextapp.echo2.webcontainer.image.PngEncoder;
import nextapp.echo2.webcontainer.propertyrender.ExtentRender;
import nextapp.echo2.webrender.Connection;
import nextapp.echo2.webrender.ContentType;
import nextapp.echo2.webrender.Service;
import nextapp.echo2.webrender.WebRenderServlet;
/**
* <code>Service</code> to render chart images.
*/
public class ChartImageService
implements Service {
-
- private static final int DEFAULT_WIDTH = 400;
- private static final int DEFAULT_HEIGHT = 300;
/**
* Parameter keys used in generating service URI.
*/
private static final String[] URI_PARAMETER_KEYS = {"chartId", "v"};
/**
* Returns the appropriate URI to display a chart for a specific
* <code>ChartDisplay</code> component.
*
* @param rc the relevant <code>RenderContext</code>
* @param chartDisplay the rendering <code>ChartDisplay</code>
* @param version the version number of the chart
* (incremented when chart is re-rendered due to an update)
* @return the URI
*/
static final String getUri(RenderContext rc, ChartDisplay chartDisplay, int version) {
return rc.getContainerInstance().getServiceUri(INSTANCE, URI_PARAMETER_KEYS, new String[]{chartDisplay.getRenderId(),
Integer.toString(version)});
}
/**
* Singleton instance.
*/
private static final ChartImageService INSTANCE = new ChartImageService();
static {
WebRenderServlet.getServiceRegistry().add(INSTANCE);
}
/** Self-instantiated singleton. */
private ChartImageService() { }
/**
* @see nextapp.echo2.webrender.Service#getId()
*/
public String getId() {
return "Echo2Chart.ImageService";
}
/**
* @see nextapp.echo2.webrender.Service#getVersion()
*/
public int getVersion() {
return DO_NOT_CACHE;
}
/**
* @see nextapp.echo2.webrender.Service#service(nextapp.echo2.webrender.Connection)
*/
public void service(Connection conn) throws IOException {
try {
ContainerInstance containerInstance = (ContainerInstance) conn.getUserInstance();
HttpServletRequest request = conn.getRequest();
String chartId = request.getParameter("chartId");
ChartDisplay chartDisplay = (ChartDisplay) containerInstance.getApplicationInstance().getComponentByRenderId(chartId);
synchronized (chartDisplay) {
if (chartDisplay == null || !chartDisplay.isRenderVisible()) {
throw new IllegalArgumentException("Invalid chart id.");
}
int width = ExtentRender.toPixels((Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_WIDTH),
- DEFAULT_WIDTH);
+ ChartDisplayPeer.DEFAULT_WIDTH);
int height = ExtentRender.toPixels((Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_HEIGHT),
- DEFAULT_HEIGHT);
+ ChartDisplayPeer.DEFAULT_HEIGHT);
JFreeChart chart = chartDisplay.getChart();
BufferedImage image;
synchronized (chart) {
image = chart.createBufferedImage(width, height);
}
PngEncoder encoder = new PngEncoder(image, true, null, 3);
conn.setContentType(ContentType.IMAGE_PNG);
OutputStream out = conn.getOutputStream();
encoder.encode(out);
}
} catch (IOException ex) {
// Internet Explorer appears to enjoy making half-hearted requests for images, wherein it resets the connection
// leaving us with an IOException. This exception is silently eaten.
ex.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/grails/src/commons/grails/util/GenerateUtils.java b/grails/src/commons/grails/util/GenerateUtils.java
index c5204b1b0..6548f120e 100644
--- a/grails/src/commons/grails/util/GenerateUtils.java
+++ b/grails/src/commons/grails/util/GenerateUtils.java
@@ -1,99 +1,98 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grails.util;
+import groovy.lang.GroovyClassLoader;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
-import org.codehaus.groovy.grails.commons.spring.SpringConfig;
+import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.scaffolding.GrailsTemplateGenerator;
import org.springframework.binding.support.Assert;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springmodules.beans.factory.drivers.xml.XmlApplicationContextDriver;
-import groovy.lang.GroovyClassLoader;
+import org.springframework.mock.web.MockServletContext;
/**
* Utility class for generating Grails artifacts likes views, controllers etc.
*
* @author Graeme Rocher
* @since 10-Feb-2006
*/
public class GenerateUtils {
private static Log LOG = LogFactory.getLog(RunTests.class);
private static final String VIEWS = "view";
private static final String CONTROLLER = "controller";
private static final String ALL = "all";
public static void main(String[] args) throws Exception {
if(args.length < 2)
return;
String type = args[0];
String domainClassName = args[1];
ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml");
GrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class);
GrailsDomainClass domainClass = getDomainCallFromApplication(application,domainClassName);
// bootstrap application to try hibernate domain classes
if(domainClass == null) {
- SpringConfig config = new SpringConfig(application);
- ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)
- new XmlApplicationContextDriver().getApplicationContext(
- config.getBeanReferences(), parent);
+ GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent);
+ ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(new MockServletContext());
Assert.notNull(appCtx);
}
// retry
domainClass = getDomainCallFromApplication(application,domainClassName);
if(domainClass == null) {
LOG.debug("Unable to generate ["+type+"] domain class not found for name ["+domainClassName+"]");
return;
}
GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
GrailsTemplateGenerator generator = (GrailsTemplateGenerator)gcl.parseClass(gcl.getResourceAsStream("org/codehaus/groovy/grails/scaffolding/DefaultGrailsTemplateGenerator.groovy"))
.newInstance();
if(VIEWS.equals(type) || ALL.equals(type)) {
LOG.info("Generating views for domain class ["+domainClass.getName()+"]");
generator.generateViews(domainClass,".");
}
else if(CONTROLLER.equals(type)|| ALL.equals(type)) {
LOG.info("Generating controller for domain class ["+domainClass.getName()+"]");
generator.generateController(domainClass,".");
}
else {
LOG.info("Grails was unable to generate templates for unsupported type ["+type+"]");
}
}
private static GrailsDomainClass getDomainCallFromApplication(GrailsApplication application, String domainClassName) {
GrailsDomainClass domainClass = application.getGrailsDomainClass(domainClassName);
if(domainClass == null) {
domainClass = application.getGrailsDomainClass(domainClassName.substring(0,1).toUpperCase() + domainClassName.substring(1));
}
return domainClass;
}
}
diff --git a/grails/src/commons/grails/util/GrailsUtil.java b/grails/src/commons/grails/util/GrailsUtil.java
index bd0002be2..6322e79fd 100644
--- a/grails/src/commons/grails/util/GrailsUtil.java
+++ b/grails/src/commons/grails/util/GrailsUtil.java
@@ -1,55 +1,55 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT c;pWARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grails.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication;
-import org.codehaus.groovy.grails.commons.spring.SpringConfig;
+import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
+import org.springframework.mock.web.MockServletContext;
import org.springframework.util.Assert;
-import org.springmodules.beans.factory.drivers.xml.XmlApplicationContextDriver;
/**
*
* Grails utility methods for command line and GUI applications
*
* @author Graeme Rocher
* @since 0.2
*
* @version $Revision$
* First Created: 02-Jun-2006
* Last Updated: $Date$
*
*/
public class GrailsUtil {
private static final Log LOG = LogFactory.getLog(GrailsUtil.class);
public static ApplicationContext bootstrapGrailsFromClassPath() {
LOG.info("Loading Grails environment");
ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml");
DefaultGrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class);
- SpringConfig config = new SpringConfig(application);
- ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)
- new XmlApplicationContextDriver().getApplicationContext(
- config.getBeanReferences(), parent);
+
+ GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent);
+
+ ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(new MockServletContext());
Assert.notNull(appCtx);
return appCtx;
}
}
| false | false | null | null |
diff --git a/conversations/src/main/java/org/jboss/webbeans/examples/conversations/Conversations.java b/conversations/src/main/java/org/jboss/webbeans/examples/conversations/Conversations.java
index 7a089eb6e..670e9d405 100644
--- a/conversations/src/main/java/org/jboss/webbeans/examples/conversations/Conversations.java
+++ b/conversations/src/main/java/org/jboss/webbeans/examples/conversations/Conversations.java
@@ -1,96 +1,96 @@
package org.jboss.webbeans.examples.conversations;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Named;
import javax.context.Conversation;
import javax.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Current;
import javax.inject.Produces;
import org.jboss.webbeans.conversation.ConversationIdGenerator;
+import org.jboss.webbeans.conversation.ConversationInactivityTimeout;
import org.jboss.webbeans.conversation.ConversationManager;
-import org.jboss.webbeans.conversation.bindings.ConversationInactivityTimeout;
@SessionScoped
@Named("conversations")
public class Conversations implements Serializable {
@Current private Conversation conversation;
@Current private ConversationIdGenerator id;
@Current private ConversationManager conversationManager;
private String cid;
public Conversations()
{
}
@Produces
@ConversationInactivityTimeout
@Example
public static long getConversationTimeoutInMilliseconds()
{
return 10000;
}
public String end()
{
conversation.end();
return "home";
}
public void begin()
{
conversation.begin();
}
public String beginAndRedirect()
{
conversation.begin();
return "home";
}
public void noop()
{
}
public String noopAndRedirect()
{
return "home";
}
public Iterable<Conversation> getConversationList()
{
return conversationManager.getLongRunningConversations();
}
public List<SelectItem> getLongRunningConversations()
{
List<SelectItem> longRunningConversations = new ArrayList<SelectItem>();
for (Conversation conversation : conversationManager.getLongRunningConversations())
{
longRunningConversations.add(new SelectItem(conversation.getId(), conversation.getId()));
}
return longRunningConversations;
}
public void switchConversation()
{
conversation.begin(cid);
}
public String getCid()
{
return cid;
}
public void setCid(String cid)
{
this.cid = cid;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/java/is/idega/idegaweb/egov/cases/presentation/OpenCases.java b/src/java/is/idega/idegaweb/egov/cases/presentation/OpenCases.java
index b1f81e7..8813404 100644
--- a/src/java/is/idega/idegaweb/egov/cases/presentation/OpenCases.java
+++ b/src/java/is/idega/idegaweb/egov/cases/presentation/OpenCases.java
@@ -1,303 +1,303 @@
/*
* $Id$ Created on Nov 7, 2005
*
* Copyright (C) 2005 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf. Use is subject to license terms.
*/
package is.idega.idegaweb.egov.cases.presentation;
import is.idega.idegaweb.egov.cases.business.CaseWriter;
import is.idega.idegaweb.egov.cases.data.CaseCategory;
import is.idega.idegaweb.egov.cases.data.CaseType;
import is.idega.idegaweb.egov.cases.data.GeneralCase;
import is.idega.idegaweb.egov.cases.util.CasesConstants;
import java.rmi.RemoteException;
import java.util.Collection;
import javax.ejb.FinderException;
import com.idega.block.process.business.CasesRetrievalManager;
import com.idega.block.process.data.CaseLog;
import com.idega.block.process.presentation.UserCases;
import com.idega.business.IBORuntimeException;
import com.idega.core.builder.data.ICPage;
import com.idega.core.file.data.ICFile;
import com.idega.event.IWPageEventListener;
import com.idega.presentation.IWContext;
import com.idega.presentation.Layer;
import com.idega.presentation.Span;
import com.idega.presentation.text.Heading1;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.Label;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
public class OpenCases extends CasesProcessor implements IWPageEventListener {
public static final String pageType = "openCases";
protected ICPage iMyCasesPage;
-
+
@Override
protected String getBlockID() {
return OpenCases.pageType;
}
public boolean actionPerformed(IWContext iwc) {
if (iwc.isParameterSet(PARAMETER_CASE_PK)) {
Object casePK = iwc.getParameter(PARAMETER_CASE_PK);
try {
getCasesBusiness(iwc).takeCase(casePK, iwc.getCurrentUser(), iwc);
return true;
}
catch (RemoteException re) {
throw new IBORuntimeException(re);
}
catch (FinderException fe) {
fe.printStackTrace();
}
}
return false;
}
@Override
protected void showProcessor(IWContext iwc, Object casePK) throws RemoteException {
Form form = new Form();
form.setStyleClass("adminForm");
form.setStyleClass("overview");
form.setEventListener(this.getClass());
if (this.iMyCasesPage != null) {
form.setPageToSubmitTo(this.iMyCasesPage);
}
form.addParameter(UserCases.PARAMETER_ACTION, "");
form.maintainParameter(PARAMETER_CASE_PK);
GeneralCase theCase = null;
try {
theCase = getCasesBusiness().getGeneralCase(casePK);
}
catch (FinderException fe) {
fe.printStackTrace();
throw new IBORuntimeException(fe);
}
CaseCategory category = theCase.getCaseCategory();
CaseCategory parentCategory = category.getParent();
CaseType type = theCase.getCaseType();
ICFile attachment = theCase.getAttachment();
User owner = theCase.getOwner();
IWTimestamp created = new IWTimestamp(theCase.getCreated());
form.add(getPersonInfo(iwc, owner));
Heading1 heading = new Heading1(getResourceBundle().getLocalizedString(getPrefix() + "case_overview", "Case overview"));
heading.setStyleClass("subHeader");
heading.setStyleClass("topSubHeader");
form.add(heading);
Layer section = new Layer(Layer.DIV);
section.setStyleClass("formSection");
form.add(section);
if (theCase.isPrivate()) {
section.add(getAttentionLayer(getResourceBundle().getLocalizedString(getPrefix() + "case.is_private", "The sender wishes that this case be handled as confidential.")));
}
Layer caseType = new Layer(Layer.SPAN);
caseType.add(new Text(type.getName()));
Layer caseCategory = new Layer(Layer.SPAN);
caseCategory.add(new Text(category.getLocalizedCategoryName(iwc.getCurrentLocale())));
Layer message = new Layer(Layer.SPAN);
message.add(new Text(theCase.getMessage()));
Layer createdDate = new Layer(Layer.SPAN);
createdDate.add(new Text(created.getLocaleDateAndTime(iwc.getCurrentLocale(), IWTimestamp.SHORT, IWTimestamp.SHORT)));
Layer formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
Label label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("case_nr", "Case nr"));
formItem.add(label);
formItem.add(new Span(new Text(theCase.getPrimaryKey().toString())));
section.add(formItem);
if (getCasesBusiness().useTypes()) {
Layer element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("case_type", "Case type"));
element.add(label);
element.add(caseType);
section.add(element);
}
if (parentCategory != null) {
Layer parentCaseCategory = new Layer(Layer.SPAN);
parentCaseCategory.add(new Text(parentCategory.getLocalizedCategoryName(iwc.getCurrentLocale())));
Layer element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("case_category", "Case category"));
element.add(label);
element.add(parentCaseCategory);
section.add(element);
element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("sub_case_category", "Sub case category"));
element.add(label);
element.add(caseCategory);
section.add(element);
}
else {
Layer element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("case_category", "Case category"));
element.add(label);
element.add(caseCategory);
section.add(element);
}
Layer element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("created_date", "Created date"));
element.add(label);
element.add(createdDate);
section.add(element);
if (attachment != null) {
Link link = new Link(new Text(attachment.getName()));
link.setFile(attachment);
link.setTarget(Link.TARGET_BLANK_WINDOW);
Layer attachmentSpan = new Layer(Layer.SPAN);
attachmentSpan.add(link);
element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("attachment", "Attachment"));
element.add(label);
element.add(attachmentSpan);
section.add(element);
}
if (theCase.getSubject() != null) {
formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("regarding", "Regarding"));
formItem.add(label);
formItem.add(new Span(new Text(theCase.getSubject())));
section.add(formItem);
}
element = new Layer(Layer.DIV);
element.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("message", "Message"));
element.add(label);
element.add(message);
section.add(element);
Layer clear = new Layer(Layer.DIV);
clear.setStyleClass("Clear");
section.add(clear);
@SuppressWarnings("unchecked")
Collection<CaseLog> logs = getCasesBusiness(iwc).getCaseLogs(theCase);
if (!logs.isEmpty()) {
for (CaseLog log : logs) {
form.add(getHandlerLayer(iwc, this.getResourceBundle(), theCase, log));
}
}
Layer bottom = new Layer(Layer.DIV);
bottom.setStyleClass("bottom");
form.add(bottom);
Link back = getButtonLink(getResourceBundle().getLocalizedString("back", "Back"));
back.setStyleClass("homeButton");
back.addParameter(UserCases.PARAMETER_ACTION, String.valueOf(ACTION_VIEW));
bottom.add(back);
Link pdf = getDownloadButtonLink(getResourceBundle().getLocalizedString("fetch_pdf", "Fetch PDF"), CaseWriter.class);
pdf.addParameter(getCasesBusiness().getSelectedCaseParameter(), theCase.getPrimaryKey().toString());
bottom.add(pdf);
if (iwc.getAccessController().hasRole(CasesConstants.ROLE_CASES_SUPER_ADMIN, iwc)) {
Link next = getButtonLink(getResourceBundle().getLocalizedString(getPrefix() + "allocate_case", "Allocate case"));
next.addParameter(UserCases.PARAMETER_ACTION, String.valueOf(ACTION_ALLOCATION_FORM));
next.maintainParameter(PARAMETER_CASE_PK, iwc);
bottom.add(next);
}
Link next = getButtonLink(theCase.getCaseStatus().equals(getCasesBusiness().getCaseStatusPending()) ? getResourceBundle().getLocalizedString(getPrefix() + "take_over_case", "Take over case") : getResourceBundle().getLocalizedString(getPrefix() + "take_case", "Take case"));
next.setValueOnClick(UserCases.PARAMETER_ACTION, String.valueOf(ACTION_PROCESS));
next.setToFormSubmit(form);
bottom.add(next);
add(form);
}
@Override
protected void save(IWContext iwc) throws RemoteException {
String casePK = iwc.getParameter(PARAMETER_CASE_PK);
// Object caseCategoryPK = iwc.isParameterSet(PARAMETER_CASE_CATEGORY_PK) ? iwc.getParameter(PARAMETER_CASE_CATEGORY_PK) : null;
// Object subCaseCategoryPK = iwc.isParameterSet(PARAMETER_SUB_CASE_CATEGORY_PK) ? iwc.getParameter(PARAMETER_SUB_CASE_CATEGORY_PK) : null;
// Object caseTypePK = iwc.isParameterSet(PARAMETER_CASE_TYPE_PK) ? iwc.getParameter(PARAMETER_CASE_TYPE_PK) : null;
if (casePK != null) {
try {
GeneralCase theCase = getCasesBusiness(iwc).getGeneralCase(new Integer(casePK));
Object userPK = iwc.getParameter(PARAMETER_USER);
String message = iwc.getParameter(PARAMETER_MESSAGE);
User user = getUserBusiness().getUser(new Integer(userPK.toString()));
getCasesBusiness(iwc).allocateCase(theCase, user, message, iwc.getCurrentUser(), iwc);
}
catch (RemoteException e) {
throw new IBORuntimeException(e);
}
catch (FinderException e) {
e.printStackTrace();
}
}
}
@Override
public boolean showCheckBox() {
return true;
}
public void setMyCasesPage(ICPage myCasesPage) {
this.iMyCasesPage = myCasesPage;
}
@Override
protected void initializeTableSorter(IWContext iwc) throws RemoteException {
StringBuffer buffer = new StringBuffer();
buffer.append("$(document).ready(function() { $('#" + getBlockID() + "').tablesorter( { headers: { " + (getCasesBusiness().useTypes() ? 3 : 2) + ": { sorter: false }, " + (getCasesBusiness().useTypes() ? 6 : 5) + ": { sorter: false}" + (showCheckBox() ? ", " + (getCasesBusiness().useTypes() ? 7 : 6) + ": { sorter: false}" : "") + "}, sortList: [[0,0]] } ); } );");
if (getParentPage() != null) {
super.getParentPage().getAssociatedScript().addFunction("tableSorter", buffer.toString());
}
}
@Override
public String getCasesProcessorType() {
return CasesRetrievalManager.CASE_LIST_TYPE_OPEN;
}
}
\ No newline at end of file
diff --git a/src/java/is/idega/idegaweb/egov/cases/presentation/beans/CasesListBuilderImpl.java b/src/java/is/idega/idegaweb/egov/cases/presentation/beans/CasesListBuilderImpl.java
index 65c258e..c4cb4f5 100644
--- a/src/java/is/idega/idegaweb/egov/cases/presentation/beans/CasesListBuilderImpl.java
+++ b/src/java/is/idega/idegaweb/egov/cases/presentation/beans/CasesListBuilderImpl.java
@@ -1,930 +1,932 @@
package is.idega.idegaweb.egov.cases.presentation.beans;
import is.idega.idegaweb.egov.cases.business.CaseArtifactsProvider;
import is.idega.idegaweb.egov.cases.business.CasesBusiness;
import is.idega.idegaweb.egov.cases.presentation.CasesProcessor;
import is.idega.idegaweb.egov.cases.presentation.CasesStatistics;
import is.idega.idegaweb.egov.cases.util.CasesConstants;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.faces.component.UIComponent;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.idega.block.process.business.CaseBusiness;
import com.idega.block.process.business.CaseManagersProvider;
import com.idega.block.process.business.CasesRetrievalManager;
import com.idega.block.process.business.ProcessConstants;
import com.idega.block.process.data.Case;
import com.idega.block.process.data.CaseStatus;
import com.idega.block.process.presentation.UserCases;
import com.idega.block.process.presentation.beans.CaseListPropertiesBean;
import com.idega.block.process.presentation.beans.CasePresentation;
import com.idega.block.process.presentation.beans.GeneralCasesListBuilder;
import com.idega.block.web2.business.JQuery;
import com.idega.block.web2.business.JQueryPlugin;
import com.idega.builder.bean.AdvancedProperty;
import com.idega.business.IBOLookup;
import com.idega.business.IBOLookupException;
import com.idega.core.accesscontrol.business.CredentialBusiness;
import com.idega.core.builder.data.ICPage;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWMainApplication;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.CSSSpacer;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.ListNavigator;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.paging.PagedDataCollection;
import com.idega.presentation.text.Break;
import com.idega.presentation.text.Heading3;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.ListItem;
import com.idega.presentation.text.Lists;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.CheckBox;
import com.idega.presentation.ui.HiddenInput;
import com.idega.user.data.User;
import com.idega.util.CoreConstants;
import com.idega.util.CoreUtil;
import com.idega.util.IWTimestamp;
import com.idega.util.ListUtil;
import com.idega.util.PresentationUtil;
import com.idega.util.StringUtil;
import com.idega.util.expression.ELUtil;
import com.idega.util.text.Name;
@Scope(BeanDefinition.SCOPE_SINGLETON)
@Service(GeneralCasesListBuilder.SPRING_BEAN_IDENTIFIER)
public class CasesListBuilderImpl implements GeneralCasesListBuilder {
private static final Logger LOGGER = Logger.getLogger(CasesListBuilderImpl.class.getName());
@Autowired
private JQuery jQuery;
private CaseManagersProvider caseManagersProvider;
private String caseContainerStyle = "casesListCaseContainer";
private String bodyItem = "casesListBodyContainerItem";
private String oldBodyItem = "old_" + bodyItem;
private String lastRowStyle = "lastRow";
private String caseIdParName = "caseid";
private String usePDFDownloadColumnParName = "usepdfdownloadcolumn";
private String allowPDFSigningParName = "allowpdfsigning";
private String resolveCaseId(IWContext iwc) {
List<CasesRetrievalManager> managers = null;
try {
managers = getCaseManagersProvider().getCaseManagers();
} catch(Exception e) {
LOGGER.log(Level.WARNING, "Error getting cases managers", e);
}
if (ListUtil.isEmpty(managers)) {
return iwc.getParameter(CasesProcessor.PARAMETER_CASE_PK);
}
String caseId = null;
for (Iterator<CasesRetrievalManager> managersIter = managers.iterator(); (managersIter.hasNext() && StringUtil.isEmpty(caseId));) {
caseId = managersIter.next().resolveCaseId(iwc);
}
return caseId;
}
private Layer createHeader(IWContext iwc, Layer container, int totalCases, boolean searchResults, CaseListPropertiesBean properties) {
PresentationUtil.addStyleSheetToHeader(iwc, getBundle(iwc).getVirtualPathWithFileNameString("style/case.css"));
IWResourceBundle iwrb = getResourceBundle(iwc);
Layer searchInfo = searchResults ? getSearchQueryInfo(iwc) : null;
if (totalCases < 1) {
if (searchResults) {
container.add(new Heading3(iwrb.getLocalizedString("no_cases_found", "No cases were found by your query!")));
container.add(searchInfo);
}
else {
container.add(new Heading3(iwrb.getLocalizedString("no_case_exist", "There are no cases")));
}
return container;
}
addResources(resolveCaseId(iwc), iwc, getBundle(iwc), properties.getType());
if (searchResults) {
StringBuilder message = new StringBuilder(iwrb.getLocalizedString("search_for_cases_results", "Your search results")).append(CoreConstants.SPACE);
message.append("(").append(totalCases).append("):");
container.add(new Heading3(message.toString()));
container.add(searchInfo);
}
Layer casesContainer = new Layer();
container.add(casesContainer);
Layer headers = new Layer();
casesContainer.add(headers);
headers.setStyleClass("casesListHeadersContainer");
String headerItem = "casesListHeadersContainerItem";
if (properties.isShowCaseNumberColumn()) {
// Number
addLayerToCasesList(headers, new Text(iwrb.getLocalizedString("case_nr", "Case nr.")), headerItem, "CaseNumber");
}
// Sender
if (properties.isShowCreatorColumn()) {
addLayerToCasesList(headers, new Text(iwrb.getLocalizedString("sender", "Sender")), headerItem, "Sender");
}
// Description
addLayerToCasesList(headers, new Text(iwrb.getLocalizedString("description", "Description")), headerItem, "Description");
// Creation date
addLayerToCasesList(headers, new Text(iwrb.getLocalizedString(StringUtil.isEmpty(properties.getDateCustomLabelLocalizationKey()) ?
"created_date" : properties.getDateCustomLabelLocalizationKey(), "Created date")), headerItem, "CreatedDate");
// Status
addLayerToCasesList(headers, new Text(iwrb.getLocalizedString("status", "Status")), headerItem, "Status");
// Toggler - controller
addLayerToCasesList(headers, new Text(iwrb.getLocalizedString("view", "View")), headerItem, "Toggler");
// Handle case
if (properties.isShowCheckBoxes()) {
addLayerToCasesList(headers, Text.getNonBrakingSpace(), headerItem, "MultiHandle");
}
headers.add(new CSSSpacer());
return casesContainer;
}
private Layer createBody(Layer casesContainer) {
Layer casesBodyContainer = new Layer();
casesContainer.add(casesBodyContainer);
casesBodyContainer.setStyleClass("casesListBodyContainer");
return casesBodyContainer;
}
private void prepareCellToBeGridExpander(Layer layer, String caseId, String gridViewerId, CaseListPropertiesBean properties) {
if (layer == null) {
return;
}
layer.setStyleClass(CasesConstants.CASES_LIST_GRID_EXPANDER_STYLE_CLASS);
layer.setMarkupAttribute(caseIdParName, caseId);
layer.setMarkupAttribute("customerviewid", gridViewerId);
layer.setMarkupAttribute(usePDFDownloadColumnParName, String.valueOf(properties.isUsePDFDownloadColumn()));
layer.setMarkupAttribute(allowPDFSigningParName, String.valueOf(properties.isAllowPDFSigning()));
layer.setMarkupAttribute("hideemptysection", String.valueOf(properties.isHideEmptySection()));
if (!StringUtil.isEmpty(properties.getCommentsManagerIdentifier())) {
layer.setMarkupAttribute("commentsmanageridentifier", properties.getCommentsManagerIdentifier());
}
layer.setMarkupAttribute("showattachmentstatistics", properties.isShowAttachmentStatistics());
layer.setMarkupAttribute("showonlycreatorincontacts", properties.isShowOnlyCreatorInContacts());
layer.setMarkupAttribute("onlysubscribedcases", properties.isOnlySubscribedCases());
}
private IWTimestamp getCaseCreatedValue(CasePresentation theCase, CaseListPropertiesBean properties) {
if (StringUtil.isEmpty(properties.getDateCustomValueVariable())) {
return new IWTimestamp(theCase.getCreated());
}
CaseArtifactsProvider artifactsProvider = getCaseArtifactsProvider();
if (artifactsProvider == null) {
return new IWTimestamp(theCase.getCreated());
}
Timestamp value = null;
try {
value = artifactsProvider.getVariableValue(theCase.getId(), properties.getDateCustomValueVariable());
} catch (ClassCastException e) {
LOGGER.log(Level.WARNING, "Error while resolving date!", e);
}
if (value == null) {
return new IWTimestamp(theCase.getCreated());
}
return new IWTimestamp(value);
}
private CaseArtifactsProvider getCaseArtifactsProvider() {
try {
return ELUtil.getInstance().getBean("bpmCaseArtifactsProvider");
} catch(Exception e) {
LOGGER.log(Level.WARNING, "Error getting bean: " + CaseArtifactsProvider.class, e);
}
return null;
}
private Layer addRowToCasesList(IWContext iwc, Layer casesBodyContainer, CasePresentation theCase, CaseStatus caseStatusReview, Locale l,
boolean isUserList, int rowsCounter, @SuppressWarnings("rawtypes") Map pages, String emailAddress, boolean descriptionIsEditable,
CaseListPropertiesBean properties) {
Layer caseContainer = new Layer();
casesBodyContainer.add(caseContainer);
caseContainer.setStyleClass(caseContainerStyle);
if (!StringUtil.isEmpty(theCase.getProcessName())) {
caseContainer.setStyleClass(theCase.getProcessName());
}
User owner = theCase.getOwner();
IWTimestamp created = getCaseCreatedValue(theCase, properties);
if (rowsCounter == 0) {
caseContainer.setStyleClass("firstRow");
}
if (theCase.isPrivate()) {
caseContainer.setStyleClass("isPrivate");
}
String caseStatusCode = null;
CaseStatus status = theCase.getCaseStatus();
if (status != null && caseStatusReview != null) {
if (status.equals(caseStatusReview)) {
caseContainer.setStyleClass("isReview");
}
caseStatusCode = status.getStatus();
if (!StringUtil.isEmpty(caseStatusCode)) {
caseContainer.setStyleClass(caseStatusCode);
}
}
Layer numberContainer = null;
if (properties.isShowCaseNumberColumn()) {
// Number
numberContainer = addLayerToCasesList(caseContainer, null, bodyItem, "CaseNumber");
String identifier = theCase.getCaseIdentifier();
numberContainer.setStyleClass("firstColumn");
if (identifier == null) {
numberContainer.add(theCase.getPrimaryKey().toString());
} else {
if (theCase.isBpm()) {
String systemEmailAddress = getEmailAddressMailtoFormattedWithSubject(emailAddress, identifier);
if (!StringUtil.isEmpty(systemEmailAddress) && !systemEmailAddress.equals(identifier)) {
IWResourceBundle iwrb = getResourceBundle(iwc);
Link sendEmail = new Link(getBundle(iwc).getImage("images/email.png", getTitleSendEmail(iwrb)), systemEmailAddress);
numberContainer.add(sendEmail);
numberContainer.add(Text.getNonBrakingSpace());
}
}
numberContainer.add(identifier);
}
}
boolean showCheckBoxes = !theCase.isBpm() ? properties.isShowCheckBoxes() : false;
Layer customerView = null;
String caseId = theCase.getPrimaryKey().toString();
String gridViewerId = null;
if (theCase.isBpm()) {
customerView = new Layer();
gridViewerId = customerView.getId();
}
if (theCase.isBpm()) {
prepareCellToBeGridExpander(numberContainer, caseId, gridViewerId, properties);
}
// Sender
if (properties.isShowCreatorColumn()) {
Layer senderContainer = addLayerToCasesList(caseContainer, null, bodyItem, "Sender");
senderContainer.add(owner == null ? new Text(CoreConstants.MINUS) : new Text(new Name(owner.getFirstName(), owner.getMiddleName(),
owner.getLastName()).getName(l)));
if (theCase.isBpm()) {
prepareCellToBeGridExpander(senderContainer, caseId, gridViewerId, properties);
}
}
// Description
Layer descriptionContainer = addLayerToCasesList(caseContainer, null, bodyItem, "Description");
if (descriptionIsEditable) {
descriptionContainer.setStyleClass("casesListBodyItemIsEditable");
descriptionContainer.setMarkupAttribute(caseIdParName, caseId);
}
String subject = theCase.getSubject();
if (subject != null && subject.length() > 100) {
subject = new StringBuilder(subject.substring(0, 100)).append(CoreConstants.DOT).append(CoreConstants.DOT).append(CoreConstants.DOT).toString();
}
descriptionContainer.add(new Text(subject == null ? CoreConstants.MINUS : subject));
// Creation date
Layer creationDateContainer = addLayerToCasesList(caseContainer, null, bodyItem, "CreationDate");
if (properties.isShowCreationTimeInDateColumn()) {
creationDateContainer.setStyleClass("showOnlyDateValueForCaseInCasesListRow");
}
creationDateContainer.add(new Text(properties.isShowCreationTimeInDateColumn() ? created.getLocaleDateAndTime(l, IWTimestamp.SHORT, IWTimestamp.SHORT) :
created.getLocaleDate(l, IWTimestamp.SHORT)));
if (theCase.isBpm()) {
prepareCellToBeGridExpander(creationDateContainer, caseId, gridViewerId, properties);
}
// Status
String localizedStatus = theCase.getLocalizedStatus();
Layer statusContainer = addLayerToCasesList(caseContainer, new Text(StringUtil.isEmpty(localizedStatus) ? CoreConstants.MINUS : localizedStatus),
bodyItem, "Status");
if (theCase.isBpm()) {
prepareCellToBeGridExpander(statusContainer, caseId, gridViewerId, properties);
}
if (!StringUtil.isEmpty(caseStatusCode)) {
statusContainer.setStyleClass(caseStatusCode);
}
// Controller
UIComponent childForContainer = null;
if (!theCase.isBpm()) {
Image view = getBundle(iwc).getImage("edit.png", getResourceBundle(iwc).getLocalizedString("view_case", "View case"));
if (isUserList) {
childForContainer = getLinkToViewUserCase(iwc, theCase, view, pages, theCase.getCode(), status, properties.isAddCredentialsToExernalUrls());
}
else {
childForContainer = getProcessLink(iwc, view, theCase);
}
}
else {
childForContainer = Text.getNonBrakingSpace(10);
}
Layer togglerContainer = addLayerToCasesList(caseContainer, childForContainer, !theCase.isBpm() ? oldBodyItem : bodyItem, "Toggler");
if (theCase.isBpm()) {
togglerContainer.setStyleClass("expand");
togglerContainer.setMarkupAttribute("changeimage", "true");
prepareCellToBeGridExpander(togglerContainer, caseId, gridViewerId, properties);
}
// Handle case
if (showCheckBoxes) {
CheckBox box = new CheckBox(CasesProcessor.PARAMETER_CASE_PK, theCase.getPrimaryKey().toString());
Layer multiHandleContainer = addLayerToCasesList(caseContainer, box, bodyItem, "MultiHandle");
multiHandleContainer.setStyleClass("lastColumn");
}
if (rowsCounter % 2 == 0) {
caseContainer.setStyleClass("evenRow");
}
else {
caseContainer.setStyleClass("oddRow");
}
caseContainer.add(new CSSSpacer());
if (customerView != null) {
caseContainer.add(customerView);
customerView.setStyleAttribute("display", "none");
}
return caseContainer;
}
private String getEmailAddressMailtoFormattedWithSubject(String emailAddress, String subject) {
if (emailAddress == null || CoreConstants.EMPTY.equals(emailAddress)) {
return subject;
}
return new StringBuilder("mailto:").append(emailAddress).append("?subject=(").append(subject).append(")").toString();
}
public String getEmailAddressMailtoFormattedWithSubject(String subject) {
return getEmailAddressMailtoFormattedWithSubject(getDefaultEmail(), subject);
}
private boolean isDescriptionEditable(String type, boolean isAdmin) {
boolean descriptionIsEditable = CasesRetrievalManager.CASE_LIST_TYPE_OPEN.equals(type);
if (!descriptionIsEditable) {
descriptionIsEditable = CasesRetrievalManager.CASE_LIST_TYPE_MY.equals(type) && isAdmin;
}
return descriptionIsEditable;
}
private boolean isSearchResultsList(String caseProcessorType) {
return ProcessConstants.CASE_LIST_TYPE_SEARCH_RESULTS.equals(caseProcessorType);
}
private Layer getCasesListContainer(boolean searchResults) {
Layer container = new Layer();
container.setStyleClass(GeneralCasesListBuilder.MAIN_CASES_LIST_CONTAINER_STYLE);
if (searchResults) {
container.setMarkupAttribute("searchresult", Boolean.TRUE.toString());
}
return container;
}
@SuppressWarnings("unchecked")
private Layer getSearchQueryInfo(IWContext iwc) {
Layer container = new Layer();
container.setStyleClass("userCasesSearchQueryInfoContainer");
Object o = iwc.getSessionAttribute(GeneralCasesListBuilder.USER_CASES_SEARCH_QUERY_BEAN_ATTRIBUTE);
if (!(o instanceof List)) {
container.setStyleAttribute("display", "none");
return container;
}
List<AdvancedProperty> searchCriterias = (List<AdvancedProperty>) o;
IWResourceBundle iwrb = getResourceBundle(iwc);
if (ListUtil.isEmpty(searchCriterias)) {
container.add(new Heading3(iwrb.getLocalizedString("cases_list_builder.there_are_no_searh_criterias", "There are no search criterias")));
return container;
}
String localizedSearchInfo = iwrb.getLocalizedString("cases_list_builder.search_was_executed_by_following_criterias", "Searching by");
if (!localizedSearchInfo.endsWith(":")) {
localizedSearchInfo = new StringBuilder(localizedSearchInfo).append(":").toString();
}
container.add(new Heading3(localizedSearchInfo));
container.add(new Break());
Lists criterias = new Lists();
container.add(criterias);
for (AdvancedProperty searchCriteria: searchCriterias) {
ListItem criteria = new ListItem();
criterias.add(criteria);
criteria.add(new StringBuilder(iwrb.getLocalizedString(searchCriteria.getId(), searchCriteria.getId())).append(CoreConstants.COLON)
.append(CoreConstants.SPACE).append(searchCriteria.getValue()).toString());
}
return container;
}
public UIComponent getCasesList(IWContext iwc, PagedDataCollection<CasePresentation> cases, CaseListPropertiesBean properties) {
String type = properties.getType();
boolean showStatistics = properties.isShowStatistics();
Collection<CasePresentation> casesInList = cases == null ? null : cases.getCollection();
String emailAddress = getDefaultEmail();
boolean descriptionIsEditable = isDescriptionEditable(type, iwc.isSuperAdmin());
boolean searchResults = isSearchResultsList(type);
Layer container = getCasesListContainer(searchResults);
addProperties(container, properties);
int totalCases = getTotalCases(cases, searchResults, properties);
addNavigator(iwc, container, cases, properties, totalCases, searchResults);
IWResourceBundle iwrb = getResourceBundle(iwc);
CasesBusiness casesBusiness = getCasesBusiness(iwc);
if (casesBusiness == null) {
container.add(new Heading3(iwrb.getLocalizedString("cases_list.can_not_get_cases_list", "Sorry, error occurred - can not generate cases list.")));
return container;
}
Layer casesContainer = createHeader(iwc, container, totalCases, searchResults, properties);
if (totalCases < 1) {
return container;
}
Layer casesBodyContainer = createBody(casesContainer);
int rowsCounter = 0;
Layer caseContainer = null;
Locale l = iwc.getCurrentLocale();
CaseStatus caseStatusReview = null;
try {
caseStatusReview = casesBusiness.getCaseStatusReview();
} catch (RemoteException e) {
e.printStackTrace();
}
for (CasePresentation theCase: casesInList) {
caseContainer = addRowToCasesList(iwc, casesBodyContainer, theCase, caseStatusReview, l, false, rowsCounter, null, emailAddress, descriptionIsEditable,
properties);
rowsCounter++;
}
if (caseContainer != null) {
caseContainer.setStyleClass(lastRowStyle);
}
if (showStatistics) {
addStatistics(iwc, container, casesInList);
}
return container;
}
private void addNavigator(IWContext iwc, Layer container, PagedDataCollection<CasePresentation> cases, CaseListPropertiesBean properties, int totalCases,
boolean searchResults) {
int pageSize = properties.getPageSize();
int page = properties.getPage();
String instanceId = properties.getInstanceId();
String componentId = properties.getComponentId();
if (pageSize > 0 && instanceId != null && componentId != null && totalCases > 0) {
PresentationUtil.addStyleSheetToHeader(iwc, iwc.getIWMainApplication().getBundle(ProcessConstants.IW_BUNDLE_IDENTIFIER)
.getVirtualPathWithFileNameString("style/process.css"));
Layer navigationLayer = new Layer(Layer.DIV);
navigationLayer.setStyleClass("caseNavigation");
container.add(navigationLayer);
container.add(new CSSSpacer());
IWResourceBundle resourceBundle = iwc.getIWMainApplication().getBundle(ProcessConstants.IW_BUNDLE_IDENTIFIER).getResourceBundle(iwc);
ListNavigator navigator = new ListNavigator("userCases", totalCases);
navigator.setFirstItemText(resourceBundle.getLocalizedString("page", "Page") + ":");
navigator.setDropdownEntryName(resourceBundle.getLocalizedString("cases", "cases"));
navigator.setPageSize(pageSize);
navigator.setCurrentPage(page);
- StringBuilder navigationParams = new StringBuilder();
- navigationParams.append("'").append(instanceId).append("'");
- navigationParams.append(", '").append(componentId).append("'");
- navigator.setNavigationFunction("gotoCasesListPage(this.id, '#PAGE#', '" + pageSize + "', " + navigationParams + ");");
- navigator.setDropdownFunction("changeCasesListPageSize(this.id, this.value, " + navigationParams + ");");
+ if (properties.getUseJavascriptForPageSwitching()) {
+ StringBuilder navigationParams = new StringBuilder();
+ navigationParams.append("'").append(instanceId).append("'");
+ navigationParams.append(", '").append(componentId).append("'");
+ navigator.setNavigationFunction("gotoCasesListPage(this.id, '#PAGE#', '" + pageSize + "', " + navigationParams + ");");
+ navigator.setDropdownFunction("changeCasesListPageSize(this.id, this.value, " + navigationParams + ");");
+ }
if (!StringUtil.isEmpty(properties.getCriteriasId())) {
navigator.setNavigatorIdentifier(properties.getCriteriasId());
}
if (searchResults) {
HiddenInput search = new HiddenInput("casesSearchResults", Boolean.TRUE.toString());
search.setStyleClass("casesListNavigatorForSearchResults");
navigationLayer.add(search);
}
navigationLayer.add(navigator);
}
}
private void addStatistics(IWContext iwc, Layer container, Collection<CasePresentation> cases) {
container.add(new CSSSpacer());
Layer statisticsContainer = new Layer();
container.add(statisticsContainer);
statisticsContainer.setStyleClass("casesListCasesStatisticsContainer");
statisticsContainer.add(getCasesStatistics(iwc, cases));
}
private void addProperties(Layer container, CaseListPropertiesBean properties) {
container.getId();
if (!StringUtil.isEmpty(properties.getInstanceId())) {
HiddenInput input = new HiddenInput("casesListInstanceIdProperty", properties.getInstanceId());
input.setStyleClass("casesListInstanceIdProperty");
container.add(input);
}
addStatusesProperties(container, "casesListStatusesToShow", properties.getStatusesToShow());
addStatusesProperties(container, "casesListStatusesToHide", properties.getStatusesToHide());
if (!ListUtil.isEmpty(properties.getCaseCodes())) {
addStatusesProperties(container, "casesListCaseCodes", properties.getCaseCodes());
}
}
private void addStatusesProperties(Layer container, String className, List<String> statuses) {
HiddenInput status = new HiddenInput(className);
status.setStyleClass(className);
status.setValue(ListUtil.isEmpty(statuses) ? CoreConstants.EMPTY : ListUtil.convertListOfStringsToCommaseparatedString(statuses));
container.add(status);
}
private int getTotalCases(PagedDataCollection<CasePresentation> cases, boolean searchResults, CaseListPropertiesBean properties) {
Collection<CasePresentation> casesInList = cases == null ? null : cases.getCollection();
int total = ListUtil.isEmpty(casesInList) ? 0 : searchResults ?
properties.getFoundResults() > 0 ?properties.getFoundResults() : casesInList == null ? 0 : cases.getTotalCount()
: casesInList == null ? 0 : casesInList.size();
return searchResults ? total : cases == null ? 0 : cases.getTotalCount();
}
public UIComponent getUserCasesList(IWContext iwc, PagedDataCollection<CasePresentation> cases, @SuppressWarnings("rawtypes") Map pages,
CaseListPropertiesBean properties) {
String type = properties.getType();
boolean showStatistics = properties.isShowStatistics();
String emailAddress = getDefaultEmail();
boolean descriptionIsEditable = isDescriptionEditable(type, iwc.isSuperAdmin());
boolean searchResults = isSearchResultsList(type);
Layer container = getCasesListContainer(searchResults);
Collection<CasePresentation> casesInList = cases == null ? null : cases.getCollection();
int totalCases = getTotalCases(cases, searchResults, properties);
addProperties(container, properties);
addNavigator(iwc, container, cases, properties, totalCases, searchResults);
IWResourceBundle iwrb = getResourceBundle(iwc);
CasesBusiness casesBusiness = getCasesBusiness(iwc);
if (casesBusiness == null) {
container.add(new Heading3(iwrb.getLocalizedString("cases_list.can_not_get_cases_list", "Sorry, error occurred - can not generate cases list.")));
return container;
}
Layer casesContainer = createHeader(iwc, container, totalCases, searchResults, properties);
if (totalCases < 1) {
return container;
}
Layer casesBodyContainer = createBody(casesContainer);
int rowsCounter = 0;
Layer caseContainer = null;
Locale l = iwc.getCurrentLocale();
CaseStatus caseStatusReview = null;
try {
caseStatusReview = casesBusiness.getCaseStatusReview();
} catch (RemoteException e) {
e.printStackTrace();
}
for (CasePresentation theCase: casesInList) {
caseContainer = addRowToCasesList(iwc, casesBodyContainer, theCase, caseStatusReview, l, true, rowsCounter, pages, emailAddress, descriptionIsEditable,
properties);
rowsCounter++;
}
caseContainer.setStyleClass(lastRowStyle);
if (showStatistics) {
addStatistics(iwc, container, casesInList);
}
return container;
}
private String getDefaultEmail() {
try {
return IWMainApplication.getDefaultIWMainApplication().getSettings().getProperty(CoreConstants.PROP_SYSTEM_ACCOUNT);
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private Link getLinkToViewUserCase(IWContext iwc, CasePresentation theCase, Image viewCaseImage, @SuppressWarnings("rawtypes") Map pages, String caseCode,
CaseStatus caseStatus, boolean addCredentialsToExernalUrls) {
CaseBusiness caseBusiness = null;
try {
caseBusiness = (CaseBusiness) IBOLookup.getServiceInstance(iwc, CaseBusiness.class);
} catch (IBOLookupException e) {
e.printStackTrace();
}
if (caseBusiness == null) {
return null;
}
ICPage page = getPage(pages, caseCode, caseStatus == null ? null : caseStatus.getStatus());
String caseUrl = theCase.getUrl();
if (page != null) {
Link link = new Link(viewCaseImage);
link.setStyleClass("caseEdit");
link.setToolTip(getToolTipForLink(iwc));
try {
link.addParameter(caseBusiness.getSelectedCaseParameter(), theCase.getPrimaryKey().toString());
} catch (RemoteException e) {
e.printStackTrace();
} catch (EJBException e) {
e.printStackTrace();
}
link.setPage(page);
return link;
} else if (caseUrl != null) {
Link link = new Link(viewCaseImage, caseUrl);
link.setStyleClass("caseEdit");
link.setToolTip(getResourceBundle(iwc).getLocalizedString("view_case", "View case"));
if (addCredentialsToExernalUrls) {
try {
getCredentialBusiness(iwc).addCredentialsToLink(link, iwc);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return link;
}
return null;
}
private ICPage getPage(@SuppressWarnings("rawtypes") Map pages, String caseCode, String caseStatus) {
if (pages == null) {
return null;
}
try {
Object object = pages.get(caseCode);
if (object instanceof ICPage) {
return (ICPage) object;
}
else if (object instanceof Map) {
@SuppressWarnings("rawtypes")
Map statusMap = (Map) object;
return (ICPage) statusMap.get(caseStatus);
}
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private String getToolTipForLink(IWContext iwc) {
return getResourceBundle(iwc).getLocalizedString("view_case", "View case");
}
private Link getProcessLink(IWContext iwc, PresentationObject object, CasePresentation theCase) {
Link process = new Link(object);
WebContext webContext = WebContextFactory.get();
if (webContext != null) {
process.setURL(webContext.getCurrentPage());
}
process.setToolTip(getToolTipForLink(iwc));
process.addParameter(CasesProcessor.PARAMETER_CASE_PK, theCase.getPrimaryKey().toString());
process.addParameter(UserCases.PARAMETER_ACTION, CasesProcessor.ACTION_PROCESS);
process.setStyleClass("old_casesListBodyContainerItemLink");
return process;
}
private void addResources(String caseId, IWContext iwc, IWBundle bundle, String type) {
List<String> scripts = new ArrayList<String>();
scripts.add(jQuery.getBundleURIToJQueryLib());
scripts.add(jQuery.getBundleURIToJQueryPlugin(JQueryPlugin.EDITABLE));
scripts.add(bundle.getVirtualPathWithFileNameString(CasesConstants.CASES_LIST_HELPER_JAVA_SCRIPT_FILE));
scripts.add(CoreConstants.DWR_ENGINE_SCRIPT);
scripts.add(CoreConstants.DWR_UTIL_SCRIPT);
scripts.add("/dwr/interface/CasesEngine.js");
if (caseId == null || CoreConstants.EMPTY.equals(caseId)) {
caseId = iwc.getParameter(CasesProcessor.PARAMETER_CASE_PK + "_id");
}
StringBuilder action = new StringBuilder("initializeCasesList(");
if (caseId == null || CoreConstants.EMPTY.equals(action)) {
action.append("null");
}
else {
action.append("'").append(caseId).append("'");
}
action.append(", [");
// Localizations: array as parameter
IWResourceBundle iwrb = getResourceBundle(iwc);
action.append("'").append(iwrb.getLocalizedString("click_to_edit", "Click to edit...")).append("'");
action.append(", '").append(iwrb.getLocalizedString("error_occurred_confirm_to_reload_page",
"Oops! Error occurred. Reloading current page might help to avoid it. Do you want to reload current page?")).append("'");
action.append(", '").append(iwrb.getLocalizedString("loading", "Loading...")).append("'");
action.append("], true);"); // TODO: set false after debug
if (!CoreUtil.isSingleComponentRenderingProcess(iwc)) {
action = new StringBuilder("jQuery(window).load(function() {").append(action.toString()).append("});");
}
// Adding resources
PresentationUtil.addJavaScriptSourcesLinesToHeader(iwc, scripts);
PresentationUtil.addJavaScriptActionToBody(iwc, "if(CASE_GRID_CASE_PROCESSOR_TYPE == null) var CASE_GRID_CASE_PROCESSOR_TYPE = \"" + type.toString() +
"\";");
PresentationUtil.addJavaScriptActionToBody(iwc, action.toString());
}
private CasesBusiness getCasesBusiness(IWApplicationContext iwac) {
try {
return (CasesBusiness) IBOLookup.getServiceInstance(iwac, CasesBusiness.class);
} catch (IBOLookupException e) {
e.printStackTrace();
}
return null;
}
private CredentialBusiness getCredentialBusiness(IWApplicationContext iwac) {
try {
return (CredentialBusiness) IBOLookup.getServiceInstance(iwac, CredentialBusiness.class);
}
catch (IBOLookupException e) {
e.printStackTrace();
}
return null;
}
private IWBundle getBundle(IWContext iwc) {
return iwc.getIWMainApplication().getBundle(CasesConstants.IW_BUNDLE_IDENTIFIER);
}
private IWResourceBundle getResourceBundle(IWContext iwc) {
if (iwc == null) {
iwc = CoreUtil.getIWContext();
}
return getBundle(iwc).getResourceBundle(iwc);
}
private Layer addLayerToCasesList(Layer container, UIComponent child, String defaultStyleClass, String suffixForStyleClass) {
Layer layer = new Layer();
container.add(layer);
if (defaultStyleClass != null) {
layer.setStyleClass(defaultStyleClass);
if (suffixForStyleClass != null) {
layer.setStyleClass(defaultStyleClass + suffixForStyleClass);
}
}
if (child != null) {
layer.add(child);
}
return layer;
}
public UIComponent getCaseManagerView(IWContext iwc, Integer caseId, String type) {
try {
Case theCase = getCasesBusiness(iwc).getCase(caseId);
CasesRetrievalManager caseManager;
if(theCase.getCaseManagerType() != null)
caseManager = getCaseManagersProvider().getCaseManager();
else
caseManager = null;
if(caseManager != null) {
UIComponent caseAssets = caseManager.getView(iwc, caseId, type, theCase.getCaseManagerType());
if(caseAssets != null)
return caseAssets;
else
Logger.getLogger(getClass().getName()).log(Level.WARNING, "No case assets component resolved from case manager: " + caseManager.getType() +
" by case pk: "+theCase.getPrimaryKey().toString());
} else
Logger.getLogger(getClass().getName()).log(Level.WARNING, "No case manager resolved by type="+theCase.getCaseManagerType());
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Exception while resolving case manager view", e);
}
return null;
}
public CaseManagersProvider getCaseManagersProvider() {
return caseManagersProvider;
}
@Autowired
public void setCaseManagersProvider(CaseManagersProvider caseManagersProvider) {
this.caseManagersProvider = caseManagersProvider;
}
public UIComponent getCasesStatistics(IWContext iwc, Collection<CasePresentation> cases) {
CasesStatistics statistics = new CasesStatistics();
statistics.setCases(cases);
statistics.setUseStatisticsByCaseType(Boolean.FALSE);
return statistics;
}
public String getSendEmailImage() {
return IWMainApplication.getDefaultIWMainApplication().getBundle(CasesConstants.IW_BUNDLE_IDENTIFIER).getVirtualPathWithFileNameString("images/email.png");
}
private String getTitleSendEmail(IWResourceBundle iwrb) {
String notFoundValue = "Send e-mail";
return iwrb == null ? notFoundValue : iwrb.getLocalizedString("send_email", notFoundValue);
}
public String getTitleSendEmail() {
return getTitleSendEmail(getResourceBundle(CoreUtil.getIWContext()));
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/Perms.java b/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/Perms.java
index d0f96161..72301ff5 100644
--- a/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/Perms.java
+++ b/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/Perms.java
@@ -1,162 +1,162 @@
package fr.ribesg.bukkit.ncuboid;
import fr.ribesg.bukkit.ncuboid.beans.Flag;
import fr.ribesg.bukkit.ncuboid.beans.FlagAtt;
import org.bukkit.command.CommandSender;
import java.util.HashMap;
import java.util.Map;
public class Perms {
// Cuboid node permissions
private static final String ADMIN = "ncuboid.admin";
private static final String USER = "ncuboid.user";
private static final String SEE_INVISIBLE_CUBOID = "ncuboid.seeinvisible";
private static final String CMD_GENERAL = "ncuboid.cmd.cuboid";
private static final String CMD_RELOAD = "ncuboid.cmd.reload";
private static final String CMD_CREATE = "ncuboid.cmd.create";
private static final String CMD_DELETE = "ncuboid.cmd.delete";
private static final String CMD_FLAG = "ncuboid.cmd.flag";
private static final String CMD_FLAGATTRIBUTE = "ncuboid.cmd.flagattribute";
- private static final String CMD_ALLOW = "ncuboid.cmd.allow";
- private static final String CMD_DENY = "ncuboid.cmd.deny";
+ private static final String CMD_ADMIN = "ncuboid.cmd.admin";
+ private static final String CMD_USER = "ncuboid.cmd.user";
// Flag permissions
private static Map<Flag, String> flagPermissions;
private static String getFlagPermission(final Flag f) {
if (flagPermissions == null) {
flagPermissions = new HashMap<>(Flag.values().length);
flagPermissions.put(Flag.BOOSTER, "ncuboid.flag.booster");
flagPermissions.put(Flag.BUILD, "ncuboid.flag.build");
flagPermissions.put(Flag.CHAT, "ncuboid.flag.chat");
flagPermissions.put(Flag.CHEST, "ncuboid.flag.chest");
flagPermissions.put(Flag.CLOSED, "ncuboid.flag.closed");
flagPermissions.put(Flag.CREATIVE, "ncuboid.flag.creative");
flagPermissions.put(Flag.DROP, "ncuboid.flag.drop");
flagPermissions.put(Flag.ENDERMANGRIEF, "ncuboid.flag.endermangrief");
flagPermissions.put(Flag.EXPLOSION_BLOCK, "ncuboid.flag.explosionblock");
flagPermissions.put(Flag.EXPLOSION_ITEM, "ncuboid.flag.explosionitem");
flagPermissions.put(Flag.EXPLOSION_PLAYER, "ncuboid.flag.explosionplayer");
flagPermissions.put(Flag.FARM, "ncuboid.flag.farm");
flagPermissions.put(Flag.FEED, "ncuboid.flag.feed");
flagPermissions.put(Flag.FIRE, "ncuboid.flag.fire");
flagPermissions.put(Flag.GOD, "ncuboid.flag.god");
flagPermissions.put(Flag.HEAL, "ncuboid.flag.heal");
flagPermissions.put(Flag.HIDDEN, "ncuboid.flag.hidden");
flagPermissions.put(Flag.INVISIBLE, "ncuboid.flag.invisible");
flagPermissions.put(Flag.JAIL, "ncuboid.flag.jail");
flagPermissions.put(Flag.MOB, "ncuboid.flag.mob");
flagPermissions.put(Flag.PASS, "ncuboid.flag.pass");
flagPermissions.put(Flag.PERMANENT, "ncuboid.flag.permanent");
flagPermissions.put(Flag.PICKUP, "ncuboid.flag.pickup");
flagPermissions.put(Flag.PVP, "ncuboid.flag.pvp");
flagPermissions.put(Flag.SNOW, "ncuboid.flag.snow");
flagPermissions.put(Flag.TELEPORT, "ncuboid.flag.teleport");
flagPermissions.put(Flag.USE, "ncuboid.flag.use");
flagPermissions.put(Flag.WARPGATE, "ncuboid.flag.warpgate");
}
return flagPermissions.get(f);
}
// Flag attributes permissions, linked to their related Flag permission
private static Map<FlagAtt, String> flagAttributesPermissions;
private static String getFlagAttributePermission(final FlagAtt fa) {
if (flagAttributesPermissions == null) {
flagAttributesPermissions = new HashMap<>(FlagAtt.values().length);
flagAttributesPermissions.put(FlagAtt.HEAL_AMOUNT, "ncuboid.flag.heal");
flagAttributesPermissions.put(FlagAtt.HEAL_TIMER, "ncuboid.flag.heal");
flagAttributesPermissions.put(FlagAtt.HEAL_MIN_HEALTH, "ncuboid.flag.heal");
flagAttributesPermissions.put(FlagAtt.HEAL_MAX_HEALTH, "ncuboid.flag.heal");
flagAttributesPermissions.put(FlagAtt.FEED_AMOUNT, "ncuboid.flag.feed");
flagAttributesPermissions.put(FlagAtt.FEED_TIMER, "ncuboid.flag.feed");
flagAttributesPermissions.put(FlagAtt.FEED_MIN_FOOD, "ncuboid.flag.feed");
flagAttributesPermissions.put(FlagAtt.FEED_MAX_FOOD, "ncuboid.flag.feed");
flagAttributesPermissions.put(FlagAtt.EXPLOSION_BLOCK_DROP, "ncuboid.flag.explosionblock");
flagAttributesPermissions.put(FlagAtt.EXTERNAL_POINT, "ncuboid.flag.pass");
flagAttributesPermissions.put(FlagAtt.INTERNAL_POINT, "ncuboid.flag.closed");
flagAttributesPermissions.put(FlagAtt.BOOSTER_VECTOR, "ncuboid.flag.booster");
}
return flagAttributesPermissions.get(fa);
}
public static boolean isAdmin(final CommandSender sender) {
return sender.isOp() || sender.hasPermission(ADMIN);
}
public static boolean hasFlag(final CommandSender sender, final Flag f) {
final String perm = getFlagPermission(f);
boolean user;
switch (f) {
case BUILD:
case CHEST:
case ENDERMANGRIEF:
case EXPLOSION_BLOCK:
case EXPLOSION_ITEM:
case EXPLOSION_PLAYER:
case FARM:
case FIRE:
case MOB:
case SNOW:
case USE:
user = true;
break;
default:
user = false;
break;
}
return isAdmin(sender) || sender.hasPermission(perm) || user && sender.hasPermission(USER);
}
public static boolean hasFlagAttribute(final CommandSender sender, final FlagAtt fa) {
final String perm = getFlagAttributePermission(fa);
boolean user;
switch (fa) {
case EXPLOSION_BLOCK_DROP:
user = true;
break;
default:
user = false;
break;
}
return isAdmin(sender) || sender.hasPermission(perm) || user && sender.hasPermission(USER);
}
public static boolean hasSeeInvisibleCuboid(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(SEE_INVISIBLE_CUBOID);
}
public static boolean hasGeneral(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(CMD_GENERAL) || sender.hasPermission(USER);
}
public static boolean hasReload(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(CMD_RELOAD);
}
public static boolean hasCreate(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(CMD_CREATE) || sender.hasPermission(USER);
}
public static boolean hasDelete(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(CMD_DELETE) || sender.hasPermission(USER);
}
public static boolean hasFlag(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(CMD_FLAG) || sender.hasPermission(USER);
}
public static boolean hasFlagAttribute(final CommandSender sender) {
return isAdmin(sender) || sender.hasPermission(CMD_FLAGATTRIBUTE) || sender.hasPermission(USER);
}
public static boolean hasAdmin(final CommandSender sender) {
- return isAdmin(sender) || sender.hasPermission(CMD_ALLOW) || sender.hasPermission(USER);
+ return isAdmin(sender) || sender.hasPermission(CMD_ADMIN) || sender.hasPermission(USER);
}
public static boolean hasUser(final CommandSender sender) {
- return isAdmin(sender) || sender.hasPermission(CMD_DENY) || sender.hasPermission(USER);
+ return isAdmin(sender) || sender.hasPermission(CMD_USER) || sender.hasPermission(USER);
}
}
| false | false | null | null |
diff --git a/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java b/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java
index a8580de..14ad946 100644
--- a/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java
+++ b/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java
@@ -1,324 +1,324 @@
package fi.vincit.jmobster.processor.languages.javascript.writer;/*
* Copyright 2012 Juha Siponen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fi.vincit.jmobster.processor.languages.BaseDataWriter;
import fi.vincit.jmobster.util.itemprocessor.ItemHandler;
import fi.vincit.jmobster.util.itemprocessor.ItemProcessor;
import fi.vincit.jmobster.util.itemprocessor.ItemStatus;
import fi.vincit.jmobster.util.writer.DataWriter;
/**
* Higher level abstraction for DataWriter that can write
* JavaScript to DataWriter. By default the writer checks that
* all functions and blocks are closed when the writer is closed.
* This feature can be turned of with {@link JavaScriptWriter#lenientModeOn}.
*/
@SuppressWarnings( "UnusedReturnValue" )
public class JavaScriptWriter extends BaseDataWriter<JavaScriptWriter> {
private static final String COMMENT_START = "/*";
private static final String COMMENT_LINE_START = " * ";
private static final String COMMENT_END = " */";
private static final String VARIABLE = "var";
private static final String BLOCK_START = "{";
private static final String BLOCK_END = "}";
private static final String ARRAY_START = "[";
private static final String ARRAY_END = "]";
private static final String ARRAY_SEPARATOR = ", ";
private static final String FUNCTION_ARG_START = "(";
private static final String FUNCTION_ARG_END = ")";
private static final String KEY_VALUE_SEPARATOR = ": ";
private static final String LIST_SEPARATOR = ",";
private static final String FUNCTION_DEF = "function";
private static final String STATEMENT_END = ";";
private static final String QUOTE = "\"";
private static final String ASSIGN = " = ";
private static final char KEYWORD_SEPARATOR = ' ';
private String space = " ";
private boolean lenientModeOn = false;
// Sanity checks.
private int functionsOpen = 0;
private int blocksOpen = 0;
private int functionCallsOpen = 0;
private boolean JSONmode = false;
private abstract static class ItemWriter<T> implements ItemHandler<T> {
private final JavaScriptWriter writer;
ItemWriter( JavaScriptWriter writer ) {
this.writer = writer;
}
JavaScriptWriter getWriter() {
return writer;
}
}
// TODO: Test that this works now as it should. Used to be as static variable which is VERY wrong
private final ItemWriter<Object> arrayWriter = new ItemWriter<Object>(this) {
@Override
public void process( Object item, ItemStatus status ) {
getWriter().write(item.toString(), ARRAY_SEPARATOR, !status.isLastItem());
}
};
public JavaScriptWriter(DataWriter writer) {
super(writer);
}
/**
* Start named function and starts a new block.
* @param name Function name
* @param arguments Function arguments
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startNamedFunction(String name, String... arguments) {
return write(FUNCTION_DEF + space).writeFunctionArgsAndStartBlock(name, arguments);
}
/**
* Start anonymous function and starts a new block.
* @param arguments Function arguments
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startAnonFunction(String... arguments) {
return write(FUNCTION_DEF).writeFunctionArgsAndStartBlock( "", arguments );
}
/**
* Writes function arguments and starts block
* @param arguments Function arguments
* @return Writer itself for chaining writes
*/
private JavaScriptWriter writeFunctionArgsAndStartBlock(String name, String... arguments) {
startFunctionCall(name);
ItemHandler<String> argumentProcessor = new ItemHandler<String>() {
@Override
public void process(String argument, ItemStatus status) {
write(argument, LIST_SEPARATOR + space, status.isNotLastItem());
}
};
ItemProcessor.process(argumentProcessor, arguments);
endFunctionCall().writeSpace();
return startBlock();
}
/**
* Ends function and blocks.
* @return Writer itself for chaining writes
* @param status Writes list separator item is last
*/
public JavaScriptWriter endFunction( ItemStatus status ) {
--functionsOpen;
return endBlock(status);
}
/**
* Stars a new block. Following lines will be indented.
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startBlock() {
++blocksOpen;
return writeLine( BLOCK_START ).indent();
}
/**
* Ends block. Indents back. Writes list separator (default ",") if isLast is false.
* @param status Writes list separator if item is last
* @return Writer itself for chaining writes
*/
public JavaScriptWriter endBlock(ItemStatus status) {
--blocksOpen;
return indentBack().write( BLOCK_END ).writeLine("", LIST_SEPARATOR, status.isNotLastItem());
}
/**
* Start function call with block statement inside
* @param name Name of the function
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startFunctionCallBlock(String name) {
return startFunctionCall(name).startBlock();
}
/**
* End function call with block statement
* @param status Writes list separator if item is last
* @return Writer itself for chaining writes
*/
public JavaScriptWriter endFunctionCallBlock(ItemStatus status) {
--blocksOpen;
--functionCallsOpen;
return indentBack().write( BLOCK_END + ")" ).writeLine( "", LIST_SEPARATOR, status.isNotLastItem() );
}
public JavaScriptWriter endBlockStatement() {
write(BLOCK_END).endStatement();
return this;
}
/**
* Writes object key (also the separator, default ":")
* @param key Key name
* @return Writer itself for chaining writes
*/
public JavaScriptWriter writeKey(String key) {
return write("", QUOTE, JSONmode).write( key, QUOTE, JSONmode ).write( KEY_VALUE_SEPARATOR );
}
/**
* Writes object key and value. Writes list separator (default ",") if isLast is false.
* @param key Key name
* @param value Value
* @param status Writes list separator item is last
* @return Writer itself for chaining writes
*/
public JavaScriptWriter writeKeyValue(String key, String value, ItemStatus status) {
return writeKey(key).write(value).writeLine("", LIST_SEPARATOR, status.isNotLastItem());
}
/**
* Writes array of objects. Objects must have {@link Object#toString()} method
* implemented.
* @param status Writes list separator item is last
* @param objects Objects to write
* @return Writer itself for chaining writes
*/
public JavaScriptWriter writeArray(ItemStatus status, Object... objects) {
write(ARRAY_START);
ItemProcessor.process(arrayWriter, objects);
write(ARRAY_END);
write("", LIST_SEPARATOR, status.isNotLastItem());
writeLine("");
return this;
}
public JavaScriptWriter writeVariable(String name, String value) {
return writeVariable(name, value, VariableType.STRING);
}
public JavaScriptWriter endStatement() {
return writeLine(STATEMENT_END);
}
public static enum VariableType {
STRING, BLOCK, OTHER
}
public JavaScriptWriter writeVariable(String name, String value, VariableType type) {
final String quoteMark = type == VariableType.STRING ? QUOTE : "";
write(VARIABLE).write(KEYWORD_SEPARATOR).write(name).write(ASSIGN);
if( type != VariableType.BLOCK ) {
write(quoteMark).write(value).write(quoteMark).endStatement();
} else {
writeLine(BLOCK_START);
}
return this;
}
public JavaScriptWriter startFunctionCall(String functionName) {
++functionCallsOpen;
write(functionName).write(FUNCTION_ARG_START);
return this;
}
public JavaScriptWriter endFunctionCall() {
--functionCallsOpen;
write(FUNCTION_ARG_END);
return this;
}
public JavaScriptWriter writeComment(String comment) {
writeLine(COMMENT_START);
write(COMMENT_LINE_START);
writeLine(comment);
writeLine(COMMENT_END);
return this;
}
/**
* Writes space. Use this to enable easy to setup compact writing that
* can ignore spaces. To disable spaces use {@link JavaScriptWriter#setSpace(String)}
* method.
* @return Writer itself for chaining writes.
*/
public JavaScriptWriter writeSpace() {
write(space);
return this;
}
/**
* @throws IllegalStateException If lenient mode is on and the writer has unclosed functions or blocks.
*/
@Override
public void close() {
super.close();
if( !lenientModeOn ) {
if( functionsOpen > 0 ) {
- throw new IllegalStateException("There are still " + functionsOpen + "unclosed functions");
+ throw new IllegalStateException("There are still " + functionsOpen + " unclosed functions");
} else if( functionsOpen < 0 ) {
throw new IllegalStateException("Too many functions closed. " + Math.abs(functionsOpen) + " times too many.");
}
if( blocksOpen > 0 ) {
- throw new IllegalStateException("There are still " + blocksOpen + "unclosed blocks");
+ throw new IllegalStateException("There are still " + blocksOpen + " unclosed blocks");
} else if( blocksOpen < 0 ) {
throw new IllegalStateException("Too many blocks closed. " + Math.abs(blocksOpen) + " times too many.");
}
if( functionCallsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionCallsOpen + " unclosed function calls");
} else if( functionCallsOpen < 0 ) {
throw new IllegalStateException("Too many function calls closed. " + Math.abs(functionCallsOpen) + " times too many.");
}
}
}
// Setters and getters
/**
* If set to false (default) {@link JavaScriptWriter#close()} will
* check that functions and blocks have been closed properly. If errors are found,
* exception will be thrown. If set to true, no checks are made and no exceptions
* are thrown.
* @param lenientModeOn Should the writer ignore obvious errors.
*/
public void setLenientMode( boolean lenientModeOn ) {
this.lenientModeOn = lenientModeOn;
}
/**
* Sets space sequence.
* @param space Space sequence
*/
public void setSpace(String space) {
this.space = space;
}
public void setJSONmode(boolean JSONmode) {
this.JSONmode = JSONmode;
}
}
| false | true | public void close() {
super.close();
if( !lenientModeOn ) {
if( functionsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionsOpen + "unclosed functions");
} else if( functionsOpen < 0 ) {
throw new IllegalStateException("Too many functions closed. " + Math.abs(functionsOpen) + " times too many.");
}
if( blocksOpen > 0 ) {
throw new IllegalStateException("There are still " + blocksOpen + "unclosed blocks");
} else if( blocksOpen < 0 ) {
throw new IllegalStateException("Too many blocks closed. " + Math.abs(blocksOpen) + " times too many.");
}
if( functionCallsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionCallsOpen + " unclosed function calls");
} else if( functionCallsOpen < 0 ) {
throw new IllegalStateException("Too many function calls closed. " + Math.abs(functionCallsOpen) + " times too many.");
}
}
}
| public void close() {
super.close();
if( !lenientModeOn ) {
if( functionsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionsOpen + " unclosed functions");
} else if( functionsOpen < 0 ) {
throw new IllegalStateException("Too many functions closed. " + Math.abs(functionsOpen) + " times too many.");
}
if( blocksOpen > 0 ) {
throw new IllegalStateException("There are still " + blocksOpen + " unclosed blocks");
} else if( blocksOpen < 0 ) {
throw new IllegalStateException("Too many blocks closed. " + Math.abs(blocksOpen) + " times too many.");
}
if( functionCallsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionCallsOpen + " unclosed function calls");
} else if( functionCallsOpen < 0 ) {
throw new IllegalStateException("Too many function calls closed. " + Math.abs(functionCallsOpen) + " times too many.");
}
}
}
|
diff --git a/application/src/fi/local/social/network/activities/PeopleActivity.java b/application/src/fi/local/social/network/activities/PeopleActivity.java
index 7a3a115..902b115 100644
--- a/application/src/fi/local/social/network/activities/PeopleActivity.java
+++ b/application/src/fi/local/social/network/activities/PeopleActivity.java
@@ -1,75 +1,76 @@
package fi.local.social.network.activities;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import fi.local.social.network.R;
public class PeopleActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] mockup_values=new String[]{"Alex Yang","Tom Cruise","Tom Hanks","Jason Stathon","Joe Hu"};
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.people_item, R.id.label, mockup_values));
//ListView listView = getListView();
//listView.setTextFilterEnabled(true);
}
@Override
protected void onListItemClick(ListView l, View view, int position, long id) {
startActivity(new Intent(getApplicationContext(), ChatActivity.class));
//Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.layout.menu_people_nearby, menu);
return true;
}
//When a user clicks on an option menu item, a toast with the item title shows up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle item selection
switch (item.getItemId()) {
case R.id.friends:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.event_list:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), EventsActivity.class));
return true;
case R.id.groups:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.settings:
- Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
+ //Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
+ startActivity(new Intent(getApplicationContext(), SettingActivity.class));
return true;
case R.id.new_event:
startActivity(new Intent(getApplicationContext(), NewEventActivity.class));
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
break;
}
return false;
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle item selection
switch (item.getItemId()) {
case R.id.friends:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.event_list:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), EventsActivity.class));
return true;
case R.id.groups:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.settings:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.new_event:
startActivity(new Intent(getApplicationContext(), NewEventActivity.class));
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
break;
}
return false;
}
| public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle item selection
switch (item.getItemId()) {
case R.id.friends:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.event_list:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), EventsActivity.class));
return true;
case R.id.groups:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.settings:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), SettingActivity.class));
return true;
case R.id.new_event:
startActivity(new Intent(getApplicationContext(), NewEventActivity.class));
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
break;
}
return false;
}
|
diff --git a/gui-project/src/webviewbrowser/WebViewBrowser.java b/gui-project/src/webviewbrowser/WebViewBrowser.java
index 2c447b4..58fae5c 100644
--- a/gui-project/src/webviewbrowser/WebViewBrowser.java
+++ b/gui-project/src/webviewbrowser/WebViewBrowser.java
@@ -1,700 +1,702 @@
/*
* Copyright (c) 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* 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 Oracle Corporation 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 webviewbrowser;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Separator;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextAreaBuilder;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import static javafx.scene.layout.Region.USE_COMPUTED_SIZE;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import net.sf.saxon.s9api.SaxonApiException;
/**
* Demonstrates a WebView object accessing a web page.
*
* @see javafx.scene.web.WebView
* @see javafx.scene.web.WebEngine
*/
public class WebViewBrowser extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Pane root = new WebViewPane();
Scene scene = new Scene(root, 1280, 900);
scene.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
}
});
// Dropping over surface
scene.setOnDragDropped(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
success = true;
String filePath;
for (File file:db.getFiles()) {
filePath = file.getAbsolutePath();
locationField.setText(filePath);
}
}
event.setDropCompleted(success);
event.consume();
}
});
primaryStage.setScene(scene);
primaryStage.getIcons().add(new Image("file:xmlspectrum-icon.png"));
primaryStage.setTitle("XMLSpectrum-FX");
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX
* application. main() serves only as fallback in case the
* application can not be launched through deployment artifacts,
* e.g., in IDEs with limited FX support. NetBeans ignores main().
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private TextField locationField = null;
private TextArea statusField = null;
private WebEngine eng = null;
private HTMLRender hr = new HTMLRender();
private AnchorPane textVBox = null;
private RowConstraints row2;
private RowConstraints row3;
private boolean useTextArea = false;
private TextArea textArea = null;
/**
* Create a resizable WebView pane
*/
public class WebViewPane extends Pane {
public WebViewPane() {
VBox.setVgrow(this, Priority.ALWAYS);
((Pane)this).setStyle("-fx-background-color:#daeafa;");
setMaxWidth(Double.MAX_VALUE);
setMaxHeight(Double.MAX_VALUE);
try {
hr.init();
} catch (SaxonApiException ex) {
Logger.getLogger(WebViewBrowser.class.getName()).log(Level.SEVERE, null, ex);
}
WebView view = new WebView();
view.setMinSize(500, 200);
view.setPrefSize(500, 200);
String classPath = new java.io.File("").getAbsolutePath();
String helpURL = "file:///" + classPath + "/docs/readme.html";
eng = view.getEngine();
eng.load(helpURL);
String fontURL = "file:///" + classPath + "/fonts/SourceCodePro-Regular.ttf";
Font.loadFont(fontURL, 10);
locationField = new TextField("");
locationField.setMaxHeight(25);
locationField.setPromptText("Enter URL or local path or drag and drop files here");
locationField.setStyle("-fx-background-color:white; -fx-text-fill:black; border-width:1px; margin:2px");
statusField = new TextArea("");
statusField.setMaxHeight(36);
statusField.setText("Status: Ready");
statusField.setEditable(false);
statusField.setStyle("-fx-text-fill: #2030a0;"+
"-fx-background-color: #cadaea;"+
"-fx-font-family: 'Monospaced';");
final VBox vBox = addVBox();
final VBox vBoxRight = addVBoxRight();
textVBox = addTextVBox();
Button goButton = new Button("Run");
goButton.setPrefWidth(100);
goButton.setDefaultButton(true);
EventHandler<ActionEvent> goAction;
goAction = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String sourceText = (useTextArea)? textArea.getText() : locationField.getText();
runRenderingTask(sourceText, !useTextArea);
}
};
goButton.setOnAction(goAction);
locationField.setOnAction(goAction);
eng.locationProperty().addListener(new ChangeListener<String>() {
@Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
//locationField.setText(newValue);
}
});
Label title1 = new Label(" XMLSpectrum");
Label title2 = new Label("");
title1.setFont(Font.font("Arial", FontWeight.BOLD, 16));
title2.setFont(Font.font("Arial", FontWeight.NORMAL, 16));
Image image = new Image("file:xmlspectrum-icon.png");
title1.setMinHeight(30);
title1.setAlignment(Pos.CENTER);
title1.setPrefHeight(USE_PREF_SIZE);
title1.setMinWidth(150);
title1.setGraphic(new ImageView(image));
title1.setTextFill(Color.web("#6a9aba"));
title2.setTextFill(Color.web("#6a9aba"));
//
GridPane grid = new GridPane();
grid.setVgap(5);
grid.setHgap(5);
GridPane.setConstraints(title1, 0, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.NEVER, Priority.SOMETIMES);
GridPane.setConstraints(locationField, 1, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.SOMETIMES);
GridPane.setConstraints(goButton, 2, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.NEVER, Priority.SOMETIMES);
GridPane.setConstraints(title2, 3, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.NEVER, Priority.SOMETIMES);
GridPane.setConstraints(textVBox, 1, 1, 2, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
GridPane.setConstraints(view, 1, 2, 2, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.SOMETIMES);
GridPane.setConstraints(vBox, 0, 1, 1, 2, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.SOMETIMES);
GridPane.setConstraints(vBoxRight, 3, 1, 1, 2, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.SOMETIMES);
GridPane.setConstraints(statusField, 0, 3, 3, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
grid.getColumnConstraints().addAll(
new ColumnConstraints(200,200,200, Priority.NEVER, HPos.RIGHT, true),
new ColumnConstraints(100, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true),
new ColumnConstraints(100,100,100, Priority.NEVER, HPos.RIGHT, true),
new ColumnConstraints(200,200,200, Priority.NEVER, HPos.RIGHT, true)
);
grid.getChildren().addAll(title1, vBox, locationField, goButton, title2, textVBox, view, vBoxRight, statusField);
RowConstraints row1 = new RowConstraints();
row2 = new RowConstraints();
row3 = new RowConstraints();
RowConstraints row4 = new RowConstraints();
row1.setMaxHeight(30);
row1.setMinHeight(30);
row1.setVgrow(Priority.ALWAYS);
vBox.setMinHeight(100);
textVBox.setMaxHeight(0);
row2.setMaxHeight(0);
row3.setPrefHeight(USE_COMPUTED_SIZE);
//row3.setFillHeight(true);
row3.setVgrow(Priority.SOMETIMES);
row4.setMaxHeight(40);
row4.setMinHeight(40);
row4.setFillHeight(true);
//grid.setGridLinesVisible(true);
grid.getRowConstraints().addAll(row1,row2,row3, row4);
getChildren().add(grid);
}
private void resetStatusText(){
statusField.setText("");
}
private void runRenderingTask(String inputURI, Boolean inputIsURI){
resetStatusText();
try {
Map paramMap = getXslParameters();
hr.run(paramMap, inputURI, inputIsURI,
new FXListener(){
@Override
public void callback(String outPath){
String pfx = outPath.substring(0,1);
if (pfx.equals("[")){
statusField.appendText(outPath + "\n");
}else {
String fullHTMLString = "";
try {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
- fullHTMLString = HTMLRender.getFileContent("file:///" + outPath);
- int start = fullHTMLString.indexOf("<pre");
+ // br fix required because html output-method seems to be affected by xhtml namespace
+ fullHTMLString = HTMLRender.getFileContent("file:///" + outPath).replace("<br></br>", "<br />");
+ int start = fullHTMLString.indexOf("style=") + 7;
int end = fullHTMLString.lastIndexOf("</pre>") + 6;
- String preString = fullHTMLString.substring(start, end);
+ String divString = "<pre style=\"white-space: nowrap; ";
+ String preString = divString + fullHTMLString.substring(start, end);
content.putString(preString);
clipboard.setContent(content);
} catch (Exception e){}
eng.loadContent(fullHTMLString);
//eng.load("file:///" + outPath);
}
}
}
);
} catch (SaxonApiException ex) {
Logger.getLogger(WebViewBrowser.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(WebViewBrowser.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Map<String, String> getXslParameters(){
Map<String, String> m = new HashMap<String, String>();
String useToc = this.getSelectedTOC();
m.put("indent", getSelectedIndent());
m.put("auto-trim", getSelectedTrim());
m.put("color-theme", getSelectedColor());
m.put("font-name", getSelectedFont());
m.put("force-newline", getSelectedNL());
m.put("format-mixed-content", getSelectedMC());
if (getSelectedDocType().equals("deltaxml")){
m.put("document-type-prefix", "deltaxml");
}
m.put("css-inline", ((useToc.equals("yes"))? "no":"yes"));
m.put("document-type", getSelectedDocType());
m.put("link-names", useToc);
return m;
}
@Override protected void layoutChildren() {
List<Node> managed = getManagedChildren();
double width = getWidth();
double height = getHeight();
double top = getInsets().getTop();
double right = getInsets().getRight();
double left = getInsets().getLeft();
double bottom = getInsets().getBottom();
for (int i = 0; i < managed.size(); i++) {
Node child = managed.get(i);
layoutInArea(child, left, top,
width - left - right, height - top - bottom,
0, Insets.EMPTY, true, true, HPos.CENTER, VPos.CENTER);
}
}
private ToggleGroup fontGroup = new ToggleGroup();
private ToggleGroup colorGroup = new ToggleGroup();
private ToggleGroup trimGroup = new ToggleGroup();
private ToggleGroup indentGroup = new ToggleGroup();
private ToggleGroup NLGroup = new ToggleGroup();
private ToggleGroup MCGroup = new ToggleGroup();
private ToggleGroup OGroup = new ToggleGroup();
private ToggleGroup docGroup = new ToggleGroup();
private ToggleGroup tocGroup = new ToggleGroup();
public String getSelectedFont(){
return (String) fontGroup.getSelectedToggle().getUserData();
}
public String getSelectedColor(){
return (String) colorGroup.getSelectedToggle().getUserData();
}
public String getSelectedTrim(){
return (String) trimGroup.getSelectedToggle().getUserData();
}
public String getSelectedIndent(){
return (String) ((RadioButton)indentGroup.getSelectedToggle()).getUserData();
}
public String getSelectedNL(){
return (String) NLGroup.getSelectedToggle().getUserData();
}
public String getSelectedMC(){
return (String) MCGroup.getSelectedToggle().getUserData();
}
public String getSelectedDocType(){
return (String) docGroup.getSelectedToggle().getUserData();
}
public String getSelectedTOC(){
return (String) tocGroup.getSelectedToggle().getUserData();
}
private AnchorPane addTextVBox(){
final TextArea area = TextAreaBuilder.create()
.prefWidth(USE_COMPUTED_SIZE)
.prefHeight(USE_COMPUTED_SIZE)
.wrapText(true)
.build();
area.setStyle("-fx-text-fill: white;"+
"-fx-text-fill: black;"+
"-fx-background-color: white;"+
"-fx-font-family: 'Monospaced';");
textArea = area;
//VBox vBox = new VBox();
AnchorPane vBox = new AnchorPane();
AnchorPane.setTopAnchor(textArea, 2.0);
AnchorPane.setLeftAnchor(textArea, 2.0);
AnchorPane.setRightAnchor(textArea, 2.0);
AnchorPane.setBottomAnchor(textArea, 2.0);
vBox.getChildren().add(area);
return vBox;
}
private VBox addVBox() {
VBox vbox = new VBox();
vbox.setStyle("-fx-background-color:#daeafa;");
vbox.setPadding(new Insets(10));
vbox.setSpacing(7);
RadioButton rbUseTextArea = new RadioButton("Text Area");
rbUseTextArea.setToggleGroup(OGroup);
RadioButton rbUseFileSource = new RadioButton("File (drag and drop)");
rbUseFileSource.setSelected(true);
rbUseFileSource.setToggleGroup(OGroup);
addBlueTitle(vbox, "Transform Settings");
addTitle(vbox, "Source");
vbox.getChildren().add(rbUseTextArea);
vbox.getChildren().add(rbUseFileSource);
vbox.getChildren().add(new Separator());
rbUseTextArea.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
row2.setMinHeight(60);
row2.setMaxHeight(250);
textVBox.setMaxHeight(USE_COMPUTED_SIZE);
//textVBox.setStyle("-fx-background-color:blue;");
row2.setPrefHeight(USE_COMPUTED_SIZE);
locationField.setEditable(false);
locationField.setStyle("-fx-background-color:#ececec; -fx-text-fill:black; border-width:1");
textArea.prefHeightProperty().bind(textVBox.prefHeightProperty());
useTextArea = true;
}
});
rbUseFileSource.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
textVBox.setMaxHeight(0);
row2.setMinHeight(0);
row2.setMaxHeight(0);
locationField.setEditable(true);
locationField.setStyle("-fx-background-color:white; -fx-text-fill:black; border-width:1");
useTextArea = false;
}
});
addTitle(vbox, "Font");
RadioButton rb1 = new RadioButton("Monospaced");
rb1.setUserData("");
rb1.setToggleGroup(fontGroup);
RadioButton rb2 = new RadioButton("Source Code Pro");
rb2.setUserData("scp");
rb2.setSelected(true);
rb2.setToggleGroup(fontGroup);
vbox.getChildren().add(rb1);
vbox.getChildren().add(rb2);
vbox.getChildren().add(new Separator());
addTitle(vbox, "Color Theme");
RadioButton crb1 = new RadioButton("Solarized-Dark");
crb1.setUserData("dark");
crb1.setToggleGroup(colorGroup);
crb1.setSelected(true);
RadioButton crb2 = new RadioButton("Solarized-Light");
crb2.setUserData("light");
crb2.setToggleGroup(colorGroup);
RadioButton crb5 = new RadioButton("GitHub (Light)");
crb5.setUserData("github");
crb5.setToggleGroup(colorGroup);
RadioButton crb6 = new RadioButton("GitHub (Blue)");
crb6.setUserData("github-blue");
crb6.setToggleGroup(colorGroup);
RadioButton crb3 = new RadioButton("RoboTicket");
crb3.setUserData("roboticket-grey");
crb3.setToggleGroup(colorGroup);
RadioButton crb4 = new RadioButton("Tomorrow-Night");
crb4.setUserData("tomorrow-night");
crb4.setToggleGroup(colorGroup);
RadioButton crb7 = new RadioButton("PG-Light");
crb7.setUserData("pg-light");
crb7.setToggleGroup(colorGroup);
vbox.getChildren().add(crb1);
vbox.getChildren().add(crb2);
vbox.getChildren().add(crb5);
vbox.getChildren().add(crb6);
vbox.getChildren().add(crb7);
vbox.getChildren().add(crb3);
vbox.getChildren().add(crb4);
vbox.getChildren().add(new Separator());
//
addTitle(vbox, "Language");
RadioButton drb1 = new RadioButton("Auto");
drb1.setUserData("");
drb1.setToggleGroup(docGroup);
drb1.setSelected(true);
RadioButton drb2 = new RadioButton("XSLT");
drb2.setUserData("xslt");
drb2.setToggleGroup(docGroup);
RadioButton drb3 = new RadioButton("XQuery/XPath");
drb3.setUserData("xquery");
drb3.setToggleGroup(docGroup);
RadioButton drb4 = new RadioButton("XML Schema");
drb4.setUserData("xsd");
drb4.setToggleGroup(docGroup);
RadioButton drb5 = new RadioButton("XProc");
drb5.setUserData("xproc");
drb5.setToggleGroup(docGroup);
RadioButton drb6 = new RadioButton("Schematron");
drb6.setUserData("schematron");
drb6.setToggleGroup(docGroup);
RadioButton drb7 = new RadioButton("DeltaXML");
drb7.setUserData("deltaxml");
drb7.setToggleGroup(docGroup);
vbox.getChildren().add(drb1);
vbox.getChildren().add(drb2);
vbox.getChildren().add(drb3);
vbox.getChildren().add(drb4);
vbox.getChildren().add(drb5);
vbox.getChildren().add(drb6);
vbox.getChildren().add(drb7);
vbox.getChildren().add(new Separator());
//
addTitle(vbox, "XSLT Project");
RadioButton tocrb1 = new RadioButton("Yes");
tocrb1.setUserData("yes");
tocrb1.setToggleGroup(tocGroup);
RadioButton tocrb2 = new RadioButton("No");
tocrb2.setUserData("no");
tocrb2.setToggleGroup(tocGroup);
tocrb2.setSelected(true);
vbox.getChildren().add(tocrb1);
vbox.getChildren().add(tocrb2);
return vbox;
}
private VBox addVBoxRight() {
VBox vbox = new VBox();
vbox.setStyle("-fx-background-color:#daeafa;");
vbox.setPadding(new Insets(10));
vbox.setSpacing(7);
RadioButton trb1 = new RadioButton("On");
trb1.setUserData("yes");
trb1.setToggleGroup(trimGroup);
trb1.setSelected(true);
RadioButton trb2 = new RadioButton("Off");
trb2.setUserData("no");
trb2.setToggleGroup(trimGroup);
addBlueTitle(vbox, "XML/XSLT Formatting");
addTitle(vbox, "XML: Auto-Trim");
vbox.getChildren().add(trb1);
vbox.getChildren().add(trb2);
vbox.getChildren().add(new Separator());
addTitle(vbox, "XML Indent (Chars)");
RadioButton irb1 = new RadioButton("-1 (No alignment)");
irb1.setUserData("-1");
irb1.setToggleGroup(indentGroup);
RadioButton irb2 = new RadioButton("0");
irb2.setUserData("0");
irb2.setToggleGroup(indentGroup);
RadioButton irb3 = new RadioButton("2");
irb3.setUserData("2");
irb3.setSelected(true);
irb3.setToggleGroup(indentGroup);
RadioButton irb4 = new RadioButton("3");
irb4.setUserData("3");
irb4.setToggleGroup(indentGroup);
vbox.getChildren().add(irb1);
vbox.getChildren().add(irb2);
vbox.getChildren().add(irb3);
vbox.getChildren().add(irb4);
vbox.getChildren().add(new Separator());
RadioButton nrb1 = new RadioButton("On");
nrb1.setUserData("yes");
nrb1.setToggleGroup(NLGroup);
RadioButton nrb2 = new RadioButton("Off");
nrb2.setSelected(true);
nrb2.setUserData("no");
nrb2.setToggleGroup(NLGroup);
addTitle(vbox, "XML: Force NewLines");
vbox.getChildren().add(nrb1);
vbox.getChildren().add(nrb2);
vbox.getChildren().add(new Separator());
RadioButton mrb1 = new RadioButton("On");
mrb1.setUserData("yes");
mrb1.setToggleGroup(MCGroup);
RadioButton mrb2 = new RadioButton("Off");
mrb2.setSelected(true);
mrb2.setUserData("no");
mrb2.setToggleGroup(MCGroup);
addTitle(vbox, "XML: Indent Mixed-Content");
vbox.getChildren().add(mrb1);
vbox.getChildren().add(mrb2);
vbox.getChildren().add(new Separator());
String classPath = new java.io.File("").getAbsolutePath().replace('\\', '/');
addBlueTitle(vbox, "Documentation");
newHyperlink(vbox, "XMLSpectrum Guide", classPath + "/docs/readme.html", true);
vbox.getChildren().add(new Separator());
addBlueTitle(vbox, "Samples");
newHyperlink(vbox, "Sample #1: XQuery", classPath + "/samples/search-ui.xqy", false);
newHyperlink(vbox, "Sample #2: XSLT", classPath + "/samples/xpathcolorer-x.xsl", false);
newHyperlink(vbox, "Sample #3: XProc", classPath + "/samples/xproccorb.xpl", false);
newHyperlink(vbox, "Sample #4: XML Schema", classPath + "/samples/schema-assert.xsd", false);
return vbox;
}
private Hyperlink newHyperlink(VBox vbox, String label, String path, Boolean isUrl){
Hyperlink hl1 = new Hyperlink(label);
hl1.setStyle("-fx-text-fill: #6a9aba;");
hl1.setUserData("file:///" + path);
VBox.setMargin(hl1, new Insets(0, 0, 0, 8));
vbox.getChildren().add(hl1);
if (isUrl){
hl1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
eng.load(((String)((Control)e.getTarget()).getUserData()));
}
});
} else {
hl1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
String filePath = ((String)((Control)e.getTarget()).getUserData());
System.out.println("newpath: " + filePath);
String sourceText = setSourceText(filePath);
runRenderingTask(sourceText, !useTextArea);
}
private String setSourceText(String filePath) {
String sourceText;
if (useTextArea){
sourceText = HTMLRender.getFileContent(filePath);
textArea.setText(sourceText);
} else {
sourceText = filePath;
locationField.setText(filePath);
}
return sourceText;
}
});
}
return hl1;
}
public void addTitle(VBox vbox, String titleText) {
Text title = new Text(titleText);
title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
vbox.getChildren().add(title);
}
public void addBlueTitle(VBox vbox, String titleText) {
Label title = new Label(titleText);
title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
title.setTextFill(Color.web("#6a9aba"));
vbox.getChildren().add(title);
}
}
}
| false | false | null | null |
diff --git a/spring-richclient/support/src/main/java/org/springframework/richclient/command/CommandGroupModelBuilder.java b/spring-richclient/support/src/main/java/org/springframework/richclient/command/CommandGroupModelBuilder.java
index 8a18b933..eca3d005 100644
--- a/spring-richclient/support/src/main/java/org/springframework/richclient/command/CommandGroupModelBuilder.java
+++ b/spring-richclient/support/src/main/java/org/springframework/richclient/command/CommandGroupModelBuilder.java
@@ -1,154 +1,154 @@
package org.springframework.richclient.command;
import java.util.Iterator;
/**
* CommandGroupModelBuilder is a helper class that allows to build Object Models
* derived from ready command-group structures.
*
* These command-group structures are tree-like structures that this class will
* traverse. Actual building of specific matching object models (often also
* trees) is done through callbacks to specific buildXXXModel methods. (which
* are abstract on this generic traversing base-class)
*
* Actual use assumes one sublasses and implements those required abstract
* methods.
*
* Internally this class will traverse the commandGroup-structure and offer
* subclasses the opportunity to build up his matching model matching the
* command-group nesting by calling the various buildXXXModel methods.
*/
public abstract class CommandGroupModelBuilder
{
/**
* Builds the real root object that will be returned from
* {@link #buildModel(CommandGroup)}.
*
* @param commandGroup
* at the root of the structure
* @return the top level object model to build.
*/
protected abstract Object buildRootModel(CommandGroup commandGroup);
/**
* Allows the implementation subclass to decide (by overriding) if
* traversing the structure should continue deeper down.
*
* Implementations can decide based on the current visited commandGroup and
* the level information.
*
* Default implementation at this abstract class level, is to keep on going
* down the structure. (subclasses should only override when needing to
* change that.)
*
* @param commandGroup
* currently visited.
* @param level
* in the structure we are at ATM
* @return <code>true</code> if children of the group should be visted,
* <code>false</code> if not.
*/
protected boolean continueDeeper(CommandGroup commandGroup, int level)
{
return true;
}
/**
* Allows the implementation subclass to build a mapping object-model
* corresponding to a visited leaf node in the command-group structure.
* <i>(Note: for non-leaf nodes the
- * {@link #buildGroupModel(Object, CommandGroup, int) version is called)</i>
+ * {@link #buildGroupModel(Object, CommandGroup, int) version is called)}</i>
*
* Since the parentModel is also passed in, the implementation can use it to
* downcast that and possibly hook up the new client-structure.
*
* @param parentModel
* the objectmodel that was created for the parent-command.
* @param command
* currently visited command in the structure.
* @param level
* in the structure we are at ATM
* @return the top level object model to build.
*/
protected abstract Object buildChildModel(Object parentModel, AbstractCommand command, int level);
/**
* Allows the implementation subclass to build a mapping object-model
* corresponding to a visited non-leaf node in the command-group structure.
* <i>(Note: for leaf nodes the
- * {@link #buildChildModel(Object, CommandGroup, int) version is called)</i>
+ * {@link #buildChildModel(Object, CommandGroup, int) version is called)}</i>
*
* Since the parentModel is also passed in, this implementation can use it
* to downcast and decide to hook up the new client-structure.
*
* In a same manner the object-structure returned by this method will be
* passed down in the tree as the parentModel for nested nodes.
*
* In general, if an implementation subclass is not building extra stuff for
* a particular command at a particular level, then it is generally wise to
* just pass down the parentModel.
*
* @param parentModel
* the objectmodel that was created for the parent-command.
* @param command
* currently visited command in the structure.
* @param level
* in the structure we are at ATM
* @return the top level object model to build.
*/
protected abstract Object buildGroupModel(Object parentModel, CommandGroup commandGroup, int level);
/**
* Main service method of this method to call.
*
* This builds the complete mapping object-model by traversing the complete
* passed in command-group structure by performing the appropriate callbacks
* to the subclass implementations of {@link #buildRootModel(CommandGroup)},
* {@link #buildChildModel(Object, AbstractCommand, int)}, and
* {@link #buildGroupModel(Object, CommandGroup, int)}.
*
* Additionally,
*
* @param commandGroup
* the root of the structure for which an mapping objectmodel
* will be built.
* @return the build object model
*/
public final Object buildModel(CommandGroup commandGroup)
{
Object model = buildRootModel(commandGroup);
recurse(commandGroup, model, 0);
return model;
}
private void recurse(AbstractCommand childCommand, Object parentModel, int level)
{
if (childCommand instanceof CommandGroup)
{
CommandGroup commandGroup = (CommandGroup) childCommand;
parentModel = buildGroupModel(parentModel, commandGroup, level);
if (continueDeeper(commandGroup, level))
{
Iterator members = commandGroup.memberIterator();
while (members.hasNext())
{
GroupMember member = (GroupMember) members.next();
AbstractCommand memberCommand = member.getCommand();
recurse(memberCommand, parentModel, level + 1);
}
}
}
else
{
buildChildModel(parentModel, childCommand, level);
}
}
}
| false | false | null | null |
diff --git a/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java b/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java
index fc1e3675..be28e8d0 100644
--- a/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java
+++ b/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java
@@ -1,97 +1,97 @@
package org.compass.core.lucene.engine;
import java.io.IOException;
import java.util.List;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.Searchable;
import org.apache.lucene.search.Searcher;
import org.compass.core.engine.SearchEngineException;
import org.compass.core.engine.SearchEngineInternalSearch;
import org.compass.core.lucene.engine.manager.LuceneSearchEngineIndexManager;
/**
* A Lucene specific search "internals", allowing for Lucene {@link IndexReader} and {@link Searcher}
* access.
*
* @author kimchy
*/
public class LuceneSearchEngineInternalSearch implements SearchEngineInternalSearch, LuceneDelegatedClose {
private MultiSearcher searcher;
protected MultiReader reader;
private boolean closed;
private List indexHolders;
/**
* Creates a new instance, with a searcher and index holders which will be used
* to release when calling close.
*
* @param searcher The searcher, which is also used to construct the reader
* @param indexHolders Holders to be released when calling close.
*/
public LuceneSearchEngineInternalSearch(MultiSearcher searcher, List indexHolders) {
this.searcher = searcher;
this.indexHolders = indexHolders;
}
/**
* Returns <code>true</code> if it represents an empty index scope.
*/
public boolean isEmpty() {
return searcher == null || searcher.getSearchables().length == 0;
}
/**
* Returns a Lucene {@link Searcher}.
*/
public Searcher getSearcher() {
return this.searcher;
}
/**
* Returns a Lucene {@link IndexReader}.
*/
public IndexReader getReader() throws SearchEngineException {
if (reader != null) {
return this.reader;
}
Searchable[] searchables = searcher.getSearchables();
IndexReader[] readers = new IndexReader[searchables.length];
for (int i = 0; i < searchables.length; i++) {
readers[i] = ((IndexSearcher) searchables[i]).getIndexReader();
}
try {
reader = new MultiReader(readers);
} catch (IOException e) {
- throw new SearchEngineException("Failed to open readers for highlighting", e);
+ throw new SearchEngineException("Failed to open readers", e);
}
return this.reader;
}
/**
* Closes this instance of Lucene search "internals". This is an optional operation
* since Compass will take care of closing it when commit/rollback is called on the
* transaction.
*/
public void close() throws SearchEngineException {
if (closed) {
return;
}
closed = true;
if (indexHolders != null) {
for (int i = 0; i < indexHolders.size(); i++) {
LuceneSearchEngineIndexManager.LuceneIndexHolder indexHolder =
(LuceneSearchEngineIndexManager.LuceneIndexHolder) indexHolders.get(i);
indexHolder.release();
}
}
}
}
| true | true | public IndexReader getReader() throws SearchEngineException {
if (reader != null) {
return this.reader;
}
Searchable[] searchables = searcher.getSearchables();
IndexReader[] readers = new IndexReader[searchables.length];
for (int i = 0; i < searchables.length; i++) {
readers[i] = ((IndexSearcher) searchables[i]).getIndexReader();
}
try {
reader = new MultiReader(readers);
} catch (IOException e) {
throw new SearchEngineException("Failed to open readers for highlighting", e);
}
return this.reader;
}
| public IndexReader getReader() throws SearchEngineException {
if (reader != null) {
return this.reader;
}
Searchable[] searchables = searcher.getSearchables();
IndexReader[] readers = new IndexReader[searchables.length];
for (int i = 0; i < searchables.length; i++) {
readers[i] = ((IndexSearcher) searchables[i]).getIndexReader();
}
try {
reader = new MultiReader(readers);
} catch (IOException e) {
throw new SearchEngineException("Failed to open readers", e);
}
return this.reader;
}
|
diff --git a/src/com/hp/hpl/jena/rdf/arp/JenaReader.java b/src/com/hp/hpl/jena/rdf/arp/JenaReader.java
index 2d599253b..d85c24d62 100644
--- a/src/com/hp/hpl/jena/rdf/arp/JenaReader.java
+++ b/src/com/hp/hpl/jena/rdf/arp/JenaReader.java
@@ -1,650 +1,653 @@
/*
(c) Copyright 2001, 2002, 2003, Hewlett-Packard Development Company, LP
[See end of file]
*/
package com.hp.hpl.jena.rdf.arp;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.rdf.model.impl.*;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.shared.*;
import com.hp.hpl.jena.shared.impl.PrefixMappingImpl;
import com.hp.hpl.jena.datatypes.*;
import java.io.*;
import java.net.*;
import java.util.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
/** Interface between Jena and ARP.
*
* @author jjc
*/
public class JenaReader implements RDFReader, ARPErrorNumbers {
private final class JRStatementHandler implements StatementHandler {
static private final int BULK_UPDATE_SIZE = 1000;
private final BulkUpdateHandler bulk;
final Triple triples[];
int ix = 0;
private JRStatementHandler( BulkUpdateHandler bulk) {
super();
this.bulk = bulk;
triples = new Triple[BULK_UPDATE_SIZE];
}
public void statement(
AResource subj,
AResource pred,
AResource obj) {
try {
triples[ix++]=convert(subj,pred,obj);
} catch (JenaException e) {
errorHandler.error(e);
}
if (ix==BULK_UPDATE_SIZE)
bulkUpdate();
}
public void statement(
AResource subj,
AResource pred,
ALiteral lit) {
try {
triples[ix++]=convert(subj,pred,lit);
} catch (JenaException e) {
errorHandler.error(e);
}
if (ix==BULK_UPDATE_SIZE)
bulkUpdate();
}
private void bulkUpdate() {
try {
if (ix == BULK_UPDATE_SIZE)
bulk.add(triples);
else
bulk.add(Arrays.asList(triples).subList(0,ix));
- ix = 0;
+
}
catch (JenaException e) {
errorHandler.error(e);
}
+ finally {
+ ix = 0;
+ }
}
}
static private final int BULK_UPDATE_SIZE = 1000;
/** Sets the reader for the languages RDF/XML and RDF/XML-ABBREV to be JenaReader.
* @param m The Model on which to set the reader properties.
*/
static public void useMe(Model m) {
m.setReaderClassName("RDF/XML", JenaReader.class.getName());
m.setReaderClassName("RDF/XML-ABBREV", JenaReader.class.getName());
}
static private final String saxFeaturesURL = "http://xml.org/sax/features/";
static private final String saxPropertiesURL =
"http://xml.org/sax/properties/";
static private final String apacheFeaturesURL =
"http://apache.org/xml/features/";
static private final String apachePropertiesURL =
"http://apache.org/xml/properties/";
static private final String arpPropertiesURL =
"http://jena.hpl.hp.com/arp/properties/";
static private final int arpPropertiesURLLength = arpPropertiesURL.length();
/** Creates new JenaReader
*/
public JenaReader() {
arpf = ARPFilter.create();
}
private ARPFilter arpf;
private Model model;
public void read(Model model, String url) throws JenaException {
try {
URLConnection conn = new URL(url).openConnection();
String encoding = conn.getContentEncoding();
if (encoding == null)
read(model, conn.getInputStream(), url);
else
read(
model,
new InputStreamReader(conn.getInputStream(), encoding),
url);
} catch (FileNotFoundException e) {
throw new DoesNotExistException( url );
} catch (IOException e) {
throw new JenaException(e);
}
}
/** Converts an ARP literal into a Jena Literal.
* @param lit The ARP literal.
* @return The Jena Literal.
* @deprecated Should never have been public.
*/
static public Literal translate(ALiteral lit) {
return new LiteralImpl(
lit.toString(),
lit.getLang(),
lit.isWellFormedXML(),
null);
}
static Node convert(ALiteral lit) {
String dtURI = lit.getDatatypeURI();
if (dtURI == null)
return Node.createLiteral(lit.toString(), lit.getLang(), false);
else {
if (lit.isWellFormedXML()) {
return Node.createLiteral(lit.toString(),null, true);
} else {
RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtURI);
return Node.createLiteral(lit.toString(),null,dt);
}
}
}
static Node convert(AResource r){
if (r.isAnonymous()) {
String id = r.getAnonymousID();
Node rr = (Node) r.getUserData();
if (rr == null) {
rr = Node.createAnon();
r.setUserData(rr);
}
return rr;
} else {
return Node.createURI(r.getURI());
}
}
static Triple convert(AResource s,AResource p, AResource o){
return Triple.create(convert(s),convert(p),convert(o));
}
static Triple convert(AResource s,AResource p, ALiteral o){
return Triple.create(convert(s),convert(p),convert(o));
}
/** Converts an ARP resource into a Jena property.
* @param r The ARP resource.
* @throws JenaException If r is anonymous, or similarly ill-formed.
* @return The Jena property.
* @deprecated Should never have been public.
*/
static public Property translatePred(AResource r) throws JenaException {
return new PropertyImpl(r.getURI());
}
/**
* Reads from reader, using base URI xmlbase, adding triples to model.
* If xmlbase is "" then relative URIs may be added to model.
* @param model A model to add triples to.
* @param reader The RDF/XML document.
* @param xmlBase The base URI of the document or "".
*/
private void read(Model m, InputSource inputS, String xmlBase)
throws JenaException {
model = m;
if (xmlBase != null && !xmlBase.equals("")) {
try {
URI uri = new URI(xmlBase);
} catch (MalformedURIException e) {
errorHandler.error(e);
}
}
arpf.setNamespaceHandler(new NamespaceHandler() {
public void startPrefixMapping(String prefix, String uri) {
if (PrefixMappingImpl.isNiceURI(uri))
model.setNsPrefix(prefix, uri);
}
public void endPrefixMapping(String prefix) {
}
});
read(model.getGraph(), inputS, xmlBase);
}
synchronized private void read(final Graph g, InputSource inputS, String xmlBase) {
try {
g.getEventManager().notifyEvent( g, GraphEvents.startRead );
final BulkUpdateHandler bulk = g.getBulkUpdateHandler();
inputS.setSystemId(xmlBase);
JRStatementHandler handler =new JRStatementHandler(bulk);
arpf.setStatementHandler(handler);
arpf.setErrorHandler(new ARPSaxErrorHandler(errorHandler));
arpf.parse(inputS, xmlBase);
handler.bulkUpdate();
} catch (IOException e) {
throw new WrappedIOException(e);
} catch (SAXException e) {
throw new JenaException(e);
} finally {
g.getEventManager().notifyEvent( g, GraphEvents.finishRead );
}
}
/**
* Reads from reader, using base URI xmlbase, adding triples to model.
* If xmlbase is "" then relative URIs may be added to model.
* @param model A model to add triples to.
* @param reader The RDF/XML document.
* @param xmlBase The base URI of the document or "".
*/
public void read(final Model model, Reader reader, String xmlBase)
throws JenaException {
read(model, new InputSource(reader), xmlBase);
}
/**
* Reads from reader, using base URI xmlbase, adding triples to graph.
* If xmlbase is "" then relative URIs may be added to graph.
* @param g A graph to add triples to.
* @param reader The RDF/XML document.
* @param xmlBase The base URI of the document or "".
*/
public void read(Graph g, Reader reader, String xmlBase)
throws JenaException {
read(g, new InputSource(reader), xmlBase);
}
/**
* Reads from inputStream, using base URI xmlbase, adding triples to model.
* If xmlbase is "" then relative URIs may be added to model.
* @param model A model to add triples to.
* @param in The RDF/XML document stream.
* @param xmlBase The base URI of the document or "".
*/
public void read(final Model model, InputStream in, String xmlBase)
throws JenaException {
read(model, new InputSource(in), xmlBase);
}
/**
* Reads from inputStream, using base URI xmlbase, adding triples to graph.
* If xmlbase is "" then relative URIs may be added to graph.
* @param g A graph to add triples to.
* @param in The RDF/XML document stream.
* @param xmlBase The base URI of the document or "".
*/
public void read(Graph g, InputStream in, String xmlBase)
{
read(g, new InputSource(in), xmlBase);
}
RDFErrorHandler errorHandler = new RDFDefaultErrorHandler();
/**
Change the error handler.
*<p>
* Note that errors of class {@link ParseException}
* can be promoted using the {@link ParseException#promote}
* method.
* See ARP documentation for {@link org.xml.sax.ErrorHandler} for the
* details of error promotion.
* @param errHandler The new error handler.
* @return The old error handler.
*/
public RDFErrorHandler setErrorHandler(RDFErrorHandler errHandler) {
RDFErrorHandler old = this.errorHandler;
this.errorHandler = errHandler;
return old;
}
/**
*
* Change a property of the RDF or XML parser.
* <p>
* This method is untested.
* <p>
* I do not believe that many of the XML features or properties are in fact
* useful for ARP users.
* The ARP properties allow fine-grained control over error reporting.
* <p>
* This interface can be used to set and get:
* <dl>
* <dt>
* SAX2 features</dt>
* <dd>
* See <a href="http://xml.apache.org/xerces-j/features.html">Xerces features</a>.
* Value should be given as a String "true" or "false" or a Boolean.
* </dd>
* <dt>
* SAX2 properties
* </dt>
* <dd>
* See <a href="http://xml.apache.org/xerces-j/properties.html">Xerces properties</a>.
* </dd>
* <dt>
* Xerces features
* </dt>
* <dd>
* See <a href="http://xml.apache.org/xerces-j/features.html">Xerces features</a>.
* Value should be given as a String "true" or "false" or a Boolean.
* </dd>
* <dt>
* Xerces properties
* </dt>
* <dd>
* See <a href="http://xml.apache.org/xerces-j/properties.html">Xerces properties</a>.
* </dd>
* <dt>
* ARP properties
* </dt>
* <dd>
* These are referred to either by their property name, (see below) or by
* an absolute URL of the form <code>http://jena.hpl.hp.com/arp/properties/<PropertyName></code>.
* The value should be a String, an Integer or a Boolean depending on the property.
* <br>
* ARP property names and string values are case insensitive.
* <br>
* <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0">
* <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
* <TD COLSPAN=4><FONT SIZE="+2">
* <B>ARP Properties</B></FONT></TD>
* </TR>
* <tr BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
* <th>Property Name</th>
* <th>Description</th>
* <th>Value class</th>
* <th>Legal Values</th>
* </tr>
* <tr BGCOLOR="white" CLASS="TableRowColor">
* <td><CODE>error-mode</CODE></td>
* <td>
* {@link ARP#setDefaultErrorMode}<br>
* {@link ARP#setLaxErrorMode}<br>
* {@link ARP#setStrictErrorMode}<br>
* {@link ARP#setStrictErrorMode(int)}<br>
* </td>
* <td>String</td>
* <td><CODE>default</CODE><br>
* <CODE>lax</CODE><br>
* <CODE>strict</CODE><br>
* <CODE>strict-ignore</CODE><br>
* <CODE>strict-warning</CODE><br>
* <CODE>strict-error</CODE><br>
* <CODE>strict-fatal</CODE><br></td>
* </tr>
* <tr BGCOLOR="white" CLASS="TableRowColor">
* <td><CODE>embedding</CODE></td>
* <td>
* {@link ARP#setEmbedding}
* </td>
* <td>String or Boolean</td>
* <td><CODE>true</CODE> or <CODE>false</CODE></td>
* </tr>
* <tr BGCOLOR="white" CLASS="TableRowColor">
* <td>
* <code>ERR_<XXX></code><br>
* <code>WARN_<XXX></code><br>
* <code>IGN_<XXX></code></td>
* <td>
* {@link ARPErrorNumbers}<br>
* Any of the error condition numbers listed.<br>
* {@link ARP#setErrorMode(int, int)}
* </td>
* <td>String or Integer</td>
* <td>{@link ARPErrorNumbers#EM_IGNORE EM_IGNORE}<br>
* {@link ARPErrorNumbers#EM_WARNING EM_WARNING}<br>
* {@link ARPErrorNumbers#EM_ERROR EM_ERROR}<br>
* {@link ARPErrorNumbers#EM_FATAL EM_FATAL}<br>
* </td>
* </tr>
* </table>
* </dd>
* </dl>
*
* @param str The property to set.
* @param value The new value; values of class String will be converted into appropriate classes. Values of
* class Boolean or Integer will be used for appropriate properties.
* @throws JenaException For bad values.
* @return The old value, or null if none, or old value is inaccesible.
*/
public Object setProperty(String str, Object value) throws JenaException {
Object obj = value;
if (str.startsWith("http:")) {
if (str.startsWith(arpPropertiesURL)) {
return setArpProperty(
str.substring(arpPropertiesURLLength),
obj);
}
if (str.startsWith(saxPropertiesURL)
|| str.startsWith(apachePropertiesURL)) {
Object old;
try {
old = arpf.getProperty(str);
} catch (SAXNotSupportedException ns) {
old = null;
} catch (SAXNotRecognizedException nr) {
errorHandler.error(new UnknownPropertyException(str));
return null;
}
try {
arpf.setProperty(str, obj);
} catch (SAXNotSupportedException ns) {
errorHandler.error(new JenaException(ns));
} catch (SAXNotRecognizedException nr) {
errorHandler.error(new UnknownPropertyException(str));
return null;
}
return old;
}
if (str.startsWith(saxFeaturesURL)
|| str.startsWith(apacheFeaturesURL)) {
Boolean old;
try {
old = new Boolean(arpf.getFeature(str));
} catch (SAXNotSupportedException ns) {
old = null;
} catch (SAXNotRecognizedException nr) {
errorHandler.error(new UnknownPropertyException(str));
return null;
}
try {
arpf.setFeature(str, ((Boolean) obj).booleanValue());
} catch (SAXNotSupportedException ns) {
errorHandler.error(new JenaException(ns));
} catch (SAXNotRecognizedException nr) {
errorHandler.error(new UnknownPropertyException(str));
return null;
} catch (ClassCastException cc) {
errorHandler.error(
new JenaException(
new SAXNotSupportedException(
"Feature: '"
+ str
+ "' can only have a boolean value.")));
}
return old;
}
}
return setArpProperty(str, obj);
}
static public int errorCode(String upper) {
Class c = ARPErrorNumbers.class;
try {
java.lang.reflect.Field fld = c.getField(upper);
return fld.getInt(null);
} catch (Exception e) {
return -1;
}
}
static public String errorCodeName(int errNo) {
Class c = ARPErrorNumbers.class;
java.lang.reflect.Field flds[] = c.getDeclaredFields();
for (int i = 0; i < flds.length; i++) {
try {
if (flds[i].getInt(null) == errNo)
return flds[i].getName();
} catch (Exception e) {
}
}
return null;
}
/**Supported proprties:
* error-mode (String) default, lax, strict, strict-ignore, strict-warning, strict-error, strict-fatal
* embedding (String/Boolean) true, false
* ERR_* (String/Integer) em_warning, em_fatal, em_ignore, em_error
* IGN_* ditto
* WARN_* ditto
*/
private Object setArpProperty(String str, Object v) {
str = str.toUpperCase();
if (v == null)
v = "";
if (v instanceof String) {
v = ((String) v).toUpperCase();
}
if (str.equals("ERROR-MODE")) {
if (v instanceof String) {
String val = (String) v;
if (val.equals("LAX")) {
arpf.setLaxErrorMode();
return null;
}
if (val.equals("DEFAULT")) {
arpf.setDefaultErrorMode();
return null;
}
if (val.equals("STRICT")) {
arpf.setStrictErrorMode();
return null;
}
if (val.equals("STRICT-WARNING")) {
arpf.setStrictErrorMode(EM_WARNING);
return null;
}
if (val.equals("STRICT-FATAL")) {
arpf.setStrictErrorMode(EM_FATAL);
return null;
}
if (val.equals("STRICT-IGNORE")) {
arpf.setStrictErrorMode(EM_IGNORE);
return null;
}
if (val.equals("STRICT-ERROR")) {
arpf.setStrictErrorMode(EM_ERROR);
return null;
}
}
errorHandler.error(
new IllegalArgumentException(
"Property \"ERROR-MODE\" takes the following values: "
+ "\"default\", \"lax\", \"strict\", \"strict-ignore\", \"strict-warning\", \"strict-error\", \"strict-fatal\"."));
return null;
}
if (str.equals("EMBEDDING")) {
if (v instanceof String) {
v = Boolean.valueOf((String) v);
}
if (!(v instanceof Boolean)) {
// Illegal value.
errorHandler.error(
new IllegalArgumentException("Property \"EMBEDDING\" requires a boolean value."));
boolean old = arpf.setEmbedding(false);
arpf.setEmbedding(old);
return new Boolean(old);
} else {
return new Boolean(
arpf.setEmbedding(((Boolean) v).booleanValue()));
}
}
if (str.startsWith("ERR_")
|| str.startsWith("IGN_")
|| str.startsWith("WARN_")) {
int cond = errorCode(str);
if (cond == -1) {
// error, see end of function.
} else {
if (v instanceof String) {
if (!((String) v).startsWith("EM_")) {
// error, see below.
} else {
int val = errorCode((String) v);
if (val == -1) {
// error, see below.
} else {
int rslt = arpf.setErrorMode(cond, val);
return new Integer(rslt);
}
}
} else if (v instanceof Integer) {
int val = ((Integer) v).intValue();
switch (val) {
case EM_IGNORE :
case EM_WARNING :
case EM_ERROR :
case EM_FATAL :
int rslt = arpf.setErrorMode(cond, val);
return new Integer(rslt);
default :
// error, see below.
}
}
// Illegal value.
errorHandler.error(
new IllegalArgumentException(
"Property \""
+ str
+ "\" cannot have value: "
+ v.toString()));
int old = arpf.setErrorMode(cond, EM_ERROR);
arpf.setErrorMode(cond, old);
return new Integer(old);
}
}
errorHandler.error(new UnknownPropertyException(str));
return null;
}
/** Create a instance of ModelMem() and set it to use JenaReader as its default reader.
* @deprecated This Reader is now the default.
* @return A new in-memory Jena model.
*/
static public Model memModel() {
Model rslt = ModelFactory.createDefaultModel();
useMe(rslt);
return rslt;
}
}
/*
* (c) Copyright 2001 Hewlett-Packard Development Company, LP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * * $Id: JenaReader.java,v 1.24 2004-06-30 09:52:17 chris-dollin Exp $
+ * * $Id: JenaReader.java,v 1.25 2004-10-05 15:49:52 jeremy_carroll Exp $
AUTHOR: Jeremy J. Carroll
*/
\ No newline at end of file
| false | false | null | null |
diff --git a/luaj-vm/src/debug/org/luaj/debug/net/j2se/DebugSupportImpl.java b/luaj-vm/src/debug/org/luaj/debug/net/j2se/DebugSupportImpl.java
index 30c1d24..6610266 100644
--- a/luaj-vm/src/debug/org/luaj/debug/net/j2se/DebugSupportImpl.java
+++ b/luaj-vm/src/debug/org/luaj/debug/net/j2se/DebugSupportImpl.java
@@ -1,169 +1,169 @@
/*******************************************************************************
* Copyright (c) 2007 LuaJ. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.debug.net.j2se;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.luaj.debug.DebugMessage;
import org.luaj.debug.net.DebugSupport;
/**
* J2SE version of DebugSupport. The luaj-vm opens a port accepting the debug
* client connections. The current implementation allows the vm to accept one
* and only one debug client connection at any time.
*/
public class DebugSupportImpl extends DebugSupport {
protected int numClientConnectionsAllowed;
protected int numClientConnections = 0;
protected ServerSocket serverSocket;
protected int debugPort;
protected ClientConnectionTask clientConnectionTask;
/**
* Creates an instance of DebugSupportImpl at the given port
* @param debugPort
* @throws IOException
*/
public DebugSupportImpl(int debugPort) throws IOException {
this(debugPort, 1);
this.serverSocket
= new ServerSocket(debugPort, this.numClientConnectionsAllowed);
}
/**
* Creates a debugging service on the given port. The service will support
* <code>numClientConnections</code> debug client connections.
* @param port Debug port
* @param connections
* @throws IOException
*/
protected DebugSupportImpl(int port, int connections) throws IOException {
if (port < 0 || port > 0xFFFF) {
throw new IllegalArgumentException("port value out of range: " + port);
}
if (connections <= 0) {
throw new IllegalArgumentException("numClientConnections value must be greater than zero");
}
this.debugPort = port;
this.numClientConnectionsAllowed = connections;
}
public void start() throws IOException {
if (this.vm == null) {
throw new IllegalStateException(
"DebugLuaState is not set. Please call setDebugStackState first.");
}
setState(RUNNING);
System.out.println("LuaJ debug server is listening on port: " + debugPort);
new Thread(new Runnable() {
public void run() {
while (isRunning()) {
try {
acceptClientConnection();
} catch (IOException e) {}
}
}
}).start();
}
public synchronized void incrementClientCount() {
this.numClientConnections++;
}
public synchronized void decrementClientCount() {
this.numClientConnections--;
}
public synchronized int getClientCount() {
return this.numClientConnections;
}
public synchronized void stop() {
setState(STOPPED);
if (clientConnectionTask != null) {
disconnect(clientConnectionTask.getSessionId());
}
dispose();
}
/*
* (non-Javadoc)
* @see org.luaj.debug.event.DebugEventListener#notifyDebugEvent(org.luaj.debug.DebugMessage)
*/
public void notifyDebugEvent(DebugMessage event) {
if (clientConnectionTask != null) {
clientConnectionTask.notifyDebugEvent(event);
}
}
public synchronized void disconnect() {
disconnect(clientConnectionTask.getSessionId());
}
public synchronized void disconnect(int id) {
if (clientConnectionTask.getSessionId() == id) {
clientConnectionTask.disconnect();
clientConnectionTask = null;
} else {
throw new RuntimeException("Internal Error: mismatching sesion Id");
}
}
public void acceptClientConnection() throws IOException {
try {
Socket clientSocket = serverSocket.accept();
int count = getClientCount();
if (count == numClientConnectionsAllowed) {
clientSocket.close();
} else {
synchronized(this) {
incrementClientCount();
this.clientConnectionTask = new ClientConnectionTask(this, clientSocket);
new Thread(clientConnectionTask).start();
}
}
- } finally {
+ } catch (IOException e) {
dispose();
}
}
protected synchronized void dispose() {
if (this.clientConnectionTask != null) {
clientConnectionTask.dispose();
clientConnectionTask = null;
}
if (this.serverSocket != null) {
try {
serverSocket.close();
serverSocket = null;
} catch (IOException e) {}
}
}
}
| true | false | null | null |
diff --git a/src/main/java/org/basex/BaseXServer.java b/src/main/java/org/basex/BaseXServer.java
index 04334701d..c14d0418b 100644
--- a/src/main/java/org/basex/BaseXServer.java
+++ b/src/main/java/org/basex/BaseXServer.java
@@ -1,342 +1,343 @@
package org.basex;
import static org.basex.core.Text.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.basex.core.Main;
import org.basex.core.Prop;
import org.basex.io.BufferInput;
import org.basex.io.IO;
import org.basex.io.PrintOutput;
import org.basex.server.ClientSession;
import org.basex.server.LocalSession;
import org.basex.server.Log;
import org.basex.server.LoginException;
import org.basex.server.ServerProcess;
import org.basex.server.Session;
import org.basex.util.Args;
import org.basex.util.Performance;
import org.basex.util.StringList;
import org.basex.util.Token;
import org.basex.util.Util;
/**
* This is the starter class for running the database server. It handles
* concurrent requests from multiple users.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
* @author Andreas Weiler
*/
public class BaseXServer extends Main {
/** Quiet mode (no logging). */
protected boolean quiet;
/** Start as daemon. */
protected boolean service;
/** Log. */
protected Log log;
/** User query. */
private String commands;
/** Server socket. */
private ServerSocket server;
+ /** Server socket. */
+ ServerSocket tserver;
/** Flag for server activity. */
boolean running;
/** Stop file. */
IO stop;
/** TriggerListener. */
private TriggerListener tl;
/**
* Main method, launching the server process. Command-line arguments are
* listed with the {@code -h} argument.
* @param args command-line arguments
*/
public static void main(final String[] args) {
new BaseXServer(args);
}
/**
* Constructor.
* @param args command-line arguments
*/
public BaseXServer(final String... args) {
super(args);
check(success);
final int port = context.prop.num(Prop.SERVERPORT);
if(service) {
Util.outln(start(port, getClass(), args));
Performance.sleep(1000);
return;
}
log = new Log(context, quiet);
log.write(SERVERSTART);
stop = stopFile(port);
try {
server = new ServerSocket(port);
// guarantee correct shutdown...
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log.write(SERVERSTOPPED);
log.close();
Util.outln(SERVERSTOPPED);
}
});
new Thread(this).start();
while(!running)
Performance.sleep(100);
Util.outln(CONSOLE + (console ? CONSOLE2 : SERVERSTART), SERVERMODE);
// execute command-line arguments
if(commands != null) {
final Boolean b = execute(commands);
check(b == null || b);
}
if(console) quit(console());
} catch(final Exception ex) {
log.write(ex.getMessage());
Util.errln(Util.server(ex));
check(false);
}
}
@Override
public final void run() {
running = true;
tl = new TriggerListener();
tl.start();
while(running) {
try {
final Socket s = server.accept();
final ServerProcess sp = new ServerProcess(s, context, log);
if(stop.exists()) {
if(!stop.delete()) log.write(Util.info(DBNOTDELETED, stop));
quit(false);
} else if(sp.init()) {
context.add(sp);
}
} catch(final IOException ex) {
// socket was closed..
break;
}
}
}
/**
* Generates a stop file for the specified port.
* @param port server port
* @return stop file
*/
private static IO stopFile(final int port) {
return IO.get(Prop.TMP + Util.name(BaseXServer.class) + port);
}
@Override
public void quit(final boolean user) {
if(!running) return;
running = false;
super.quit(user);
try {
// close interactive input if server was stopped by another process
if(console) System.in.close();
+ tserver.close();
server.close();
} catch(final IOException ex) {
log.write(ex.getMessage());
Util.stack(ex);
}
console = false;
context.close();
}
@Override
protected final Session session() {
if(session == null) session = new LocalSession(context, out);
return session;
}
@Override
protected boolean parseArguments(final String[] args) {
final Args arg = new Args(args, this, SERVERINFO, Util.info(CONSOLE,
SERVERMODE));
boolean daemon = false;
while(arg.more()) {
if(arg.dash()) {
final char c = arg.next();
if(c == 'c') {
// send database commands
commands = arg.remaining();
} else if(c == 'd') {
// activate debug mode
context.prop.set(Prop.DEBUG, true);
} else if(c == 'D') {
// hidden flag: daemon mode
daemon = true;
} else if(c == 'i') {
// activate interactive mode
console = true;
} else if(c == 'p') {
// parse server port
context.prop.set(Prop.SERVERPORT, arg.num());
} else if(c == 's') {
// set service flag
service = !daemon;
} else if(c == 'z') {
// suppress logging
quiet = true;
} else {
arg.check(false);
}
} else {
arg.check(false);
if(arg.string().equalsIgnoreCase("stop")) {
stop(context.prop.num(Prop.SERVERPORT),
context.prop.num(Prop.TRIGGERPORT));
Performance.sleep(1000);
return false;
}
}
}
return arg.finish();
}
/**
* Stops the server of this instance.
*/
public final void stop() {
try {
stop.write(Token.EMPTY);
new Socket(LOCALHOST, context.prop.num(Prop.TRIGGERPORT));
new Socket(LOCALHOST, context.prop.num(Prop.SERVERPORT));
} catch(final IOException ex) {
Util.errln(Util.server(ex));
}
}
// STATIC METHODS ===========================================================
/**
* Starts the specified class in a separate process.
* @param port server port
* @param clz class to start
* @param args command-line arguments
* @return error string or {@code null}
*/
public static String start(final int port, final Class<?> clz,
final String... args) {
// check if server is already running (needs some time)
if(ping(LOCALHOST, port)) return SERVERBIND;
final StringList sl = new StringList();
final String[] largs = { "java", "-Xmx" + Runtime.getRuntime().maxMemory(),
"-cp", System.getProperty("java.class.path"), clz.getName(), "-D", };
for(final String a : largs)
sl.add(a);
for(final String a : args)
sl.add(a);
try {
new ProcessBuilder(sl.toArray()).start();
// try to connect to the new server instance
for(int c = 0; c < 5; ++c) {
if(ping(LOCALHOST, port)) return SERVERSTART;
Performance.sleep(100);
}
} catch(final IOException ex) {
Util.notexpected(ex);
}
return SERVERERROR;
}
/**
* Checks if a server is running.
* @param host host
* @param port server port
* @return boolean success
*/
public static boolean ping(final String host, final int port) {
try {
// connect server with invalid login data
new ClientSession(host, port, "", "");
return false;
} catch(final IOException ex) {
// if login was checked, server is running
return ex instanceof LoginException;
}
}
/**
* Stops the server.
* @param port server port
* @param tport trigger port
*/
public static void stop(final int port, final int tport) {
final IO stop = stopFile(port);
try {
stop.write(Token.EMPTY);
new Socket(LOCALHOST, tport);
new Socket(LOCALHOST, port);
while(ping(LOCALHOST, port))
Performance.sleep(100);
Util.outln(SERVERSTOPPED);
} catch(final IOException ex) {
stop.delete();
Util.errln(Util.server(ex));
}
}
/**
* Inner class to listen for trigger registrations.
*
* @author BaseX Team 2005-11, BSD License
* @author Andreas Weiler
*/
private class TriggerListener extends Thread {
- /** Server socket. */
- ServerSocket tserver;
/**
* Constructor.
*/
public TriggerListener() {
try {
- this.tserver = new ServerSocket(context.prop.num(Prop.TRIGGERPORT));
+ tserver = new ServerSocket(context.prop.num(Prop.TRIGGERPORT));
} catch(IOException ex) {
log.write(ex.getMessage());
Util.errln(Util.server(ex));
}
}
@Override
public void run() {
while(running) {
try {
final Socket socket = tserver.accept();
if(stop.exists()) {
tserver.close();
break;
}
BufferInput buf = new BufferInput(socket.getInputStream());
String id = buf.readString();
for(ServerProcess s : context.sessions) {
if(String.valueOf(s.getId()).equals(id)) {
s.tsocket = socket;
s.tout = PrintOutput.get(socket.getOutputStream());
}
}
} catch(IOException e) { break; }
}
}
}
}
| false | false | null | null |
diff --git a/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java b/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java
index 163097070..93616534e 100644
--- a/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java
+++ b/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java
@@ -1,117 +1,118 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* 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.0 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.bonitasoft.forms.server.accessor.api;
import java.io.Serializable;
import java.util.Map;
import org.bonitasoft.console.common.server.utils.BPMExpressionEvaluationException;
import org.bonitasoft.engine.api.ProcessAPI;
import org.bonitasoft.engine.api.ProcessRuntimeAPI;
import org.bonitasoft.engine.expression.Expression;
import org.bonitasoft.engine.expression.ExpressionEvaluationException;
import org.bonitasoft.forms.server.accessor.widget.impl.XMLExpressionsUtil;
import org.bonitasoft.forms.server.api.impl.util.FormFieldValuesUtil;
/**
* @author Colin PUY
*
*/
public class ExpressionEvaluatorEngineClient {
private ProcessAPI processApi;
public ExpressionEvaluatorEngineClient(ProcessAPI processApi) {
this.processApi = processApi;
}
public Map<String, Serializable> evaluateExpressionsOnActivityInstance(long activityInstanceID,
Map<Expression, Map<String, Serializable>> expressionsWithContext) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnActivityInstance(activityInstanceID, expressionsWithContext);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on activity instance " + activityInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnProcessInstance(long processInstanceID, Map<Expression, Map<String, Serializable>> expressions)
throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnProcessInstance(processInstanceID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on process instance " + processInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnProcessDefinition(long processDefinitionID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnProcessDefinition(processDefinitionID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on process definition " + processDefinitionID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnCompletedActivityInstance(long activityInstanceID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnCompletedActivityInstance(activityInstanceID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on completed activity instance " + activityInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnCompletedProcessInstance(long processInstanceID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionOnCompletedProcessInstance(processInstanceID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on completed process instance " + processInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsAtProcessInstanciation(long processInstanceID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsAtProcessInstanciation(processInstanceID, expressions);
}catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on completed process instance " + processInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
private ProcessRuntimeAPI getProcessAPI() {
return processApi;
}
private String buildEvaluationMessageLogDetail(final ExpressionEvaluationException e) {
String[] splitExpressionName = null;
String expressionParentName = "unknown";
String expressionParentAttribute = "unknown";
if(e.getExpressionName()!=null){
splitExpressionName = e.getExpressionName().split(FormFieldValuesUtil.EXPRESSION_KEY_SEPARATOR);
if(splitExpressionName.length==2){
expressionParentName = splitExpressionName[0];
expressionParentAttribute = splitExpressionName[1];
+ return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
}
}
- return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
+ return "Error on expression evaluation for the expression with name ["+ e.getExpressionName() +"].";
}
}
| false | true | private String buildEvaluationMessageLogDetail(final ExpressionEvaluationException e) {
String[] splitExpressionName = null;
String expressionParentName = "unknown";
String expressionParentAttribute = "unknown";
if(e.getExpressionName()!=null){
splitExpressionName = e.getExpressionName().split(FormFieldValuesUtil.EXPRESSION_KEY_SEPARATOR);
if(splitExpressionName.length==2){
expressionParentName = splitExpressionName[0];
expressionParentAttribute = splitExpressionName[1];
}
}
return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
}
| private String buildEvaluationMessageLogDetail(final ExpressionEvaluationException e) {
String[] splitExpressionName = null;
String expressionParentName = "unknown";
String expressionParentAttribute = "unknown";
if(e.getExpressionName()!=null){
splitExpressionName = e.getExpressionName().split(FormFieldValuesUtil.EXPRESSION_KEY_SEPARATOR);
if(splitExpressionName.length==2){
expressionParentName = splitExpressionName[0];
expressionParentAttribute = splitExpressionName[1];
return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
}
}
return "Error on expression evaluation for the expression with name ["+ e.getExpressionName() +"].";
}
|
diff --git a/src/edu/nrao/dss/client/forms/DataForm.java b/src/edu/nrao/dss/client/forms/DataForm.java
index 68b6166..7475310 100644
--- a/src/edu/nrao/dss/client/forms/DataForm.java
+++ b/src/edu/nrao/dss/client/forms/DataForm.java
@@ -1,411 +1,413 @@
// Copyright (C) 2011 Associated Universities, Inc. Washington DC, USA.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// Correspondence concerning GBT software should be addressed as follows:
// GBT Operations
// National Radio Astronomy Observatory
// P. O. Box 2
// Green Bank, WV 24944-0002 USA
package edu.nrao.dss.client.forms;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Math;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.Radio;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.core.client.GWT;
import edu.nrao.dss.client.Functions;
import edu.nrao.dss.client.forms.fields.GeneralCheckbox;
import edu.nrao.dss.client.forms.fields.GeneralRadioGroup;
import edu.nrao.dss.client.forms.fields.GeneralText;
public class DataForm extends BasicForm {
private GeneralText rSigRef, nAverageRef, resolution, bw;
//private GeneralCombo nOverlap;
private GeneralCheckbox averagePol, differenceSignal;
private GeneralRadioGroup smoothing, smoothing_factor;
private Radio vel_res_rest_frame, freq_res_topo, freq_res_rest_frame, vel_res_topo_frame, freq_res_topo_frame;
private Label smoothing_factor_inst, rSigRefInst, nAverageRefInst;
private FieldSet smoothingFieldSet, sigRefSet;
private Float restFreq, topoFreq, srcVelocity, redshift, bandwidth;
private String doppler, frame, mode;
public DataForm() {
super("Data Reduction");
}
// Initial Layout
public void initLayout() {
setCollapsible(true);
rSigRef = new GeneralText("r_sig_ref","Ratio of time On vs Reference");
rSigRef.setLabelStyle("display:none");
rSigRef.setValue("1");
rSigRefInst = new Label("Ratio of observing time spent on-source/on-frequency to that spent on a reference position/reference frequency.");
//nOverlap = new GeneralCombo("nOverlap","Enter number of spectral windows centered", new ArrayList<String>(Arrays.asList("1","2")));
averagePol = new GeneralCheckbox();
averagePol.setId("avg_pol");
averagePol.setName("avg_pol");
averagePol.setValueAttribute("true");
averagePol.setBoxLabel("Average Orthognal Polarizations");
averagePol.setLabelSeparator("");
averagePol.setValue(true);
differenceSignal = new GeneralCheckbox();
differenceSignal.setId("diff_signal");
differenceSignal.setName("diff_signal");
differenceSignal.setValueAttribute("true");
differenceSignal.setBoxLabel("Difference Signal and Reference Observations");
differenceSignal.setLabelSeparator("");
differenceSignal.setValue(true);
nAverageRef = new GeneralText("no_avg_ref","Number of Reference Observations");
nAverageRef.setValue("1");
nAverageRef.setLabelStyle("display:none");
nAverageRefInst = new Label("In data reduction you have the option to average multiple reference observations in order to improve the noise. Enter number of reference observations that will be averaged together.");
smoothing = new GeneralRadioGroup("smoothing");
smoothing.setFieldLabel("Smooth On-source Data to a Desired");
smoothing.setName("smoothing");
smoothing.setId("smoothing");
smoothing.setOrientation(Orientation.VERTICAL);
smoothing.addListener(Events.Change, new Listener<FieldEvent> () {
@Override
public void handleEvent(FieldEvent be) {
updateBW();
}
});
vel_res_rest_frame = new Radio();
vel_res_rest_frame.setBoxLabel("Velocity Resolution in the Rest Frame");
vel_res_rest_frame.setValueAttribute("velocity_resolution_rest");
vel_res_rest_frame.setName("velocity_resolution_rest");
vel_res_rest_frame.setValue(true);
smoothing.add(vel_res_rest_frame);
freq_res_topo = new Radio();
freq_res_topo.setBoxLabel("Frequency Resolution in the Topocentric");
freq_res_topo.setValueAttribute("frequency_resolution_topo");
freq_res_topo.setName("frequency_resolution_topo");
smoothing.add(freq_res_topo);
freq_res_rest_frame = new Radio();
freq_res_rest_frame.setBoxLabel("Frequency Resolution in the Rest Frame");
freq_res_rest_frame.setValueAttribute("frequency_resolution_rest");
freq_res_rest_frame.setName("frequency_resolution_rest");
smoothing.add(freq_res_rest_frame);
vel_res_topo_frame = new Radio();
vel_res_topo_frame.setBoxLabel("Velocity Resolution in the Topocentric Frame");
vel_res_topo_frame.setValueAttribute("velocity_resolution_topo");
vel_res_topo_frame.setName("velocity_resolution_topo");
vel_res_topo_frame.hide();
smoothing.add(vel_res_topo_frame);
freq_res_topo_frame = new Radio();
freq_res_topo_frame.setBoxLabel("Frequency Resolution in the Topocentric Frame");
freq_res_topo_frame.setValueAttribute("frequency_resolution_topo_frame");
freq_res_topo_frame.setName("frequency_resolution_topo_frame");
freq_res_topo_frame.hide();
smoothing.add(freq_res_topo_frame);
resolution = new GeneralText("smoothing_resolution", "Desired Resolution (km/s)");
resolution.setMaxLength(6);
resolution.setValidator(new Validator () {
@Override
public String validate(Field<?> field, String value) {
if (value.isEmpty() || value.equals("-")) {
return null;
}
if (Float.valueOf(value) == 0){
return "Resolution cannot be zero.";
}
return null;
}
});
resolution.addListener(Events.Valid, new Listener<FieldEvent> () {
@Override
public void handleEvent(FieldEvent be) {
updateBW();
}
});
smoothing.addListener(Events.Change, new Listener<FieldEvent> () {
@Override
public void handleEvent(FieldEvent be) {
if (smoothing.getValue().getValueAttribute().equals("velocity_resolution_rest")) {
resolution.setFieldLabel("Desired Resolution (km/s)");
} else {
resolution.setFieldLabel("Desired Resolution (MHz)");
}
}
});
smoothing_factor_inst = new Label("To improve signal-to-noise you can smooth reference observations to a resolution that is a few times courser than the signal observation. Select the factor by which you want to smooth the reference observation:");
smoothing_factor = new GeneralRadioGroup("smoothing_factor");
smoothing_factor.setName("smoothing_factor");
smoothing_factor.setId("smoothing_factor");
smoothing_factor.setFieldLabel("Smoothing Factor");
Radio choice = new Radio();
choice.setBoxLabel("1");
choice.setValue(true);
choice.setValueAttribute("1");
choice.setName("1");
smoothing_factor.add(choice);
choice = new Radio();
choice.setBoxLabel("2");
choice.setValueAttribute("2");
choice.setName("2");
smoothing_factor.add(choice);
choice = new Radio();
choice.setBoxLabel("4");
choice.setValueAttribute("4");
choice.setName("4");
smoothing_factor.add(choice);
choice = new Radio();
choice.setBoxLabel("8");
choice.setValueAttribute("8");
choice.setName("8");
smoothing_factor.add(choice);
smoothingFieldSet = new FieldSet();
smoothingFieldSet.setHeading("Smoothing");
FormLayout layout = new FormLayout();
layout.setLabelWidth(200);
smoothingFieldSet.setLayout(layout);
sigRefSet = new FieldSet();
FormLayout layout2 = new FormLayout();
layout2.setLabelWidth(200);
sigRefSet.setLayout(layout2);
bw = new GeneralText("bw", "Resolution (MHz)");
//bw.setFieldLabel("Resolution (MHz)");
bw.setId("bw");
bw.setName("bw");
bw.setLabelSeparator(":");
bw.hide();
//initial state
rSigRef.hide();
rSigRefInst.hide();
smoothing.hide();
resolution.hide();
resolution.setAllowBlank(true);
smoothing_factor_inst.hide();
smoothing_factor.hide();
smoothingFieldSet.hide();
FormData fd = new FormData(60, 20);
//attaching fields
sigRefSet.add(rSigRefInst);
sigRefSet.add(rSigRef, fd);
sigRefSet.add(nAverageRefInst);
sigRefSet.add(nAverageRef, fd);
add(sigRefSet);
//add(nOverlap);
add(averagePol);
add(differenceSignal);
smoothingFieldSet.add(smoothing);
smoothingFieldSet.add(resolution);
smoothingFieldSet.add(bw);
smoothingFieldSet.add(smoothing_factor_inst);
smoothingFieldSet.add(smoothing_factor);
add(smoothingFieldSet);
//attaching fields
}
// class HandleSmoothing implements Listener<FieldEvent> {
// public void handleEvent(FieldEvent fe) {
// if (smoothing.getValue()) {
// smoothingResolution.show();
// bw.show();
// bwRef.show();
// } else {
// smoothingResolution.hide();
// bw.hide();
// bwRef.hide();
// }
// }
// }
private void updateBW() {
if (resolution.getValue() == null || resolution.getValue().equals("")) {
return;
}
if (!mode.equals("Spectral Line") & bandwidth != null){
bw.setValue("" + bandwidth);
return;
}
double c = 2.99792458e5;
String smoothing_option = smoothing.getValue().getValueAttribute();
if (smoothing_option.equals("frequency_resolution_topo")) {
bw.setValue(resolution.getValue());
} else if (smoothing_option.equals("frequency_resolution_rest")) {
Float deltaFreq = Float.valueOf(resolution.getValue());
double f01 = Functions.velocity2Frequency(doppler, restFreq + deltaFreq / 2, srcVelocity, redshift);
double f02 = Functions.velocity2Frequency(doppler, restFreq - deltaFreq / 2, srcVelocity, redshift);
bw.setValue("" + Math.abs(f01 - f02));
} else if (smoothing_option.equals("velocity_resolution_rest")) {
Float deltaVelocity = Float.valueOf(resolution.getValue());
float velocity;
if (doppler.equals("Redshift")) {
velocity = (float) (redshift * c);
} else {
velocity = srcVelocity;
}
float v1 = velocity + deltaVelocity / 2;
float v2 = velocity - deltaVelocity / 2;
double f01 = Functions.velocity2Frequency(doppler, restFreq, v1, v1 / c);
double f02 = Functions.velocity2Frequency(doppler, restFreq, v2, v2 / c);
bw.setValue("" + Math.abs(f01 - f02));
} else if (smoothing_option.equals("velocity_resolution_topo")) {
Float deltaVelocity = Float.valueOf(resolution.getValue());
double res = topoFreq * deltaVelocity / c;
bw.setValue("" + res);
} else if (smoothing_option.equals("frequency_resolution_topo_frame")) {
bw.setValue(resolution.getValue());
}
}
public void notify(String name, String value) {
// handler for mode
if (name.equals("switching")) {
if (value.equals("Total Power")) {
rSigRef.hide();
rSigRefInst.hide();
} else {
rSigRef.show();
rSigRefInst.show();
}
} else if (name.equals("mode")) {
mode = value;
if (value.equals("Spectral Line")) {
smoothing.show();
resolution.show();
resolution.setAllowBlank(false);
smoothing_factor_inst.show();
smoothing_factor.show();
smoothingFieldSet.show();
} else {
smoothing.hide();
resolution.hide();
resolution.setAllowBlank(true);
resolution.setValue("1");
smoothing_factor_inst.hide();
smoothing_factor.hide();
smoothingFieldSet.hide();
}
if (value.equals("Total Power")) {
differenceSignal.hide();
} else {
differenceSignal.show();
}
} else if (name.equals("polarization")) {
- if (value.equals("Dual")) {
- averagePol.setValue(true);
- } else {
- averagePol.setValue(false);
+ if (!value.equals("NOTHING")) {
+ if (value.equals("Dual")) {
+ averagePol.setValue(true);
+ } else {
+ averagePol.setValue(false);
+ }
}
} else if (name.equals("bandwidth") & !value.equals("NOTHING")) {
bandwidth = Float.valueOf(value);
}
if (name.equals("rest_freq")) {
restFreq = Float.valueOf(value);
} else if (name.equals("topocentric_freq")) {
topoFreq = Float.valueOf(value);
} else if (name.equals("redshift")) {
redshift = Float.valueOf(value);
} else if (name.equals("source_velocity")) {
srcVelocity = Float.valueOf(value);
} else if (name.equals("frame")) {
if(!value.equals(frame)) {
if (value.equals("Topocentric Frame")) {
vel_res_topo_frame.show();
vel_res_topo_frame.setValue(true);
freq_res_topo_frame.show();
vel_res_rest_frame.hide();
freq_res_topo.hide();
freq_res_rest_frame.hide();
} else {
vel_res_topo_frame.hide();
freq_res_topo_frame.hide();
vel_res_rest_frame.show();
vel_res_rest_frame.setValue(true);
freq_res_topo.show();
freq_res_rest_frame.show();
}
frame = value;
}
}else if (name.equals("doppler")) {
doppler = value;
}
updateBW();
// if (name.equals("backend")) {
// if (value.equals("Spectrometer")) {
// nOverlap.show();
// } else {
// nOverlap.hide();
// }
//
// }
}
public void validate() {
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/runtimes/java/platforms/androidJNI/AndroidProject/src/com/mosync/java/android/TextBox.java b/runtimes/java/platforms/androidJNI/AndroidProject/src/com/mosync/java/android/TextBox.java
index 5b1b73421..aa1435988 100644
--- a/runtimes/java/platforms/androidJNI/AndroidProject/src/com/mosync/java/android/TextBox.java
+++ b/runtimes/java/platforms/androidJNI/AndroidProject/src/com/mosync/java/android/TextBox.java
@@ -1,384 +1,384 @@
/* Copyright (C) 2010 MoSync AB
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; see the file COPYING. If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
package com.mosync.java.android;
import static com.mosync.internal.generated.MAAPI_consts.EVENT_TYPE_FOCUS_GAINED;
import static com.mosync.internal.generated.MAAPI_consts.EVENT_TYPE_TEXTBOX;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_FLAG_INITIAL_CAPS_SENTENCE;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_FLAG_INITIAL_CAPS_WORD;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_FLAG_NON_PREDICTIVE;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_FLAG_PASSWORD;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_FLAG_SENSITIVE;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_FLAG_UNEDITABLE;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_RES_CANCEL;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_RES_OK;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_ANY;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_DECIMAL;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_EMAILADDR;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_NUMERIC;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_PHONENUMBER;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_URL;
import static com.mosync.internal.generated.MAAPI_consts.MA_TB_TYPE_SINGLE_LINE;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.lang.String;
import com.mosync.internal.android.MoSyncThread;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* This class is an implementation of a text box dialog.
* It shows a fullscreen text fiels with OK and Cancel buttons.
*
* Clicking OK retrieves the text entered by the user and puts it into
* a buffer specified in the maTextBox IOCtl, pushes a MoSync event and
* then dismisses the dialog.
* Clicking cancel only dismisses the dialog.
*/
public class TextBox extends Activity implements OnClickListener {
public static final String savedInstanceString = "savedInstance";
public Handler mHandler;
private Button mOkButton;
private Button mCancelButton;
private EditText mEdit;
private TextView mLabel;
private int mOutputMemPtr;
private int mConstraints;
/**
* Constructor.
*/
/**
* Converts MoSync input constraints android ones.
*
* @param mosyncInputConstraints The MoSync input type to be converted.
* See maapi.idl for a list of input types,
* section "maTextBox", "constraints".
* @return An integer corresponding to the relevant
* android input type.
*/
private int convertInputConstraints(int mosyncInputConstraints)
{
int type = mosyncInputConstraints & 0x0000F;
int flag = mosyncInputConstraints & 0xFF000;
int androidInputConstraints = 0x00000;
// Process the type
switch (type)
{
case MA_TB_TYPE_ANY:
androidInputConstraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case MA_TB_TYPE_EMAILADDR:
androidInputConstraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case MA_TB_TYPE_NUMERIC:
androidInputConstraints =
InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case MA_TB_TYPE_PHONENUMBER:
androidInputConstraints = InputType.TYPE_CLASS_PHONE;
break;
case MA_TB_TYPE_URL:
androidInputConstraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_URI;
break;
case MA_TB_TYPE_DECIMAL:
androidInputConstraints =
InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL |
InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case MA_TB_TYPE_SINGLE_LINE:
androidInputConstraints =
InputType.TYPE_CLASS_TEXT;
break;
// Default case is normal text with several lines
default:
androidInputConstraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
}
// Process the flag
switch (flag)
{
case MA_TB_FLAG_PASSWORD:
androidInputConstraints |=
InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case MA_TB_FLAG_UNEDITABLE:
// Uneditable is not available on android
break;
case MA_TB_FLAG_SENSITIVE:
// Sensitive is the same as no suggesions in that context
// because we do not store the text entered in any kind of dictionary
// OOPS! TYPE_TEXT_FLAG_NO_SUGGESTIONS Not available in android 1.5
//androidInputConstraints |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case MA_TB_FLAG_NON_PREDICTIVE:
// OOPS! TYPE_TEXT_FLAG_NO_SUGGESTIONS Not available in android 1.5
//androidInputConstraints |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case MA_TB_FLAG_INITIAL_CAPS_WORD:
androidInputConstraints |= InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case MA_TB_FLAG_INITIAL_CAPS_SENTENCE:
androidInputConstraints |=
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
// Default case is still normal text with several lines
default:
break;
}
return androidInputConstraints;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set a handler to this thread
mHandler= new Handler();
// Fullscreen mode
// Commented out fullscreen mode, as fullscreen does not make
// sense for the textbox activity.
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// this.getWindow().setFlags(
// WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Get screen dimansions
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
// Get parameters from the parent activity
Bundle bundle = this.getIntent().getExtras();
String title = bundle.getString("TITLE");
String text = bundle.getString("TEXT");
mOutputMemPtr = bundle.getInt("OUTPUT");
mConstraints = bundle.getInt("CONSTRAINTS");
// This is the max number of characters - 1 (for null char).
int maxLength = bundle.getInt("MAXSIZE") - 1;
// Truncate default input text to maxLength.
if (text.length() > maxLength)
{
text = text.substring(0, maxLength);
}
// Initialize layout components
mEdit = new EditText(this);
mEdit.setWidth(width);
mEdit.setHeight(height/3);
// The commented out line below creates a bug on HTC Desire.
// mEdit.setGravity(Gravity.TOP);
if( savedInstanceState != null)
{
String savedString = savedInstanceState.getString(savedInstanceString);
mEdit.setText(savedString);
}
else
mEdit.setText(text);
mEdit.setInputType( this.convertInputConstraints(mConstraints) );
// Set an InputFilter to restrict input length.
mEdit.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(maxLength)
});
mCancelButton = new Button(this);
mCancelButton.setText("Cancel");
mCancelButton.setId(1000);
mCancelButton.setOnClickListener(this);
mOkButton = new Button(this);
mOkButton.setText("OK");
mOkButton.setId(1001);
mOkButton.setOnClickListener(this);
mLabel = new TextView(this);
mLabel.setText(title);
// Use ScrollView for scrollable content (available only in Portrait mode).
LinearLayout mainLayout = new LinearLayout(this);
ScrollView scrollView = new ScrollView(this);
mainLayout.addView(scrollView);
// Add buttons to a sub-layout
LinearLayout horizontalLayout = new LinearLayout(this);
horizontalLayout.addView(mCancelButton);
horizontalLayout.addView(mOkButton);
// Add components to the global layout
LinearLayout verticalLayout = new LinearLayout(this);
verticalLayout.setOrientation(LinearLayout.VERTICAL);
verticalLayout.addView(mLabel);
verticalLayout.addView(mEdit);
verticalLayout.addView(horizontalLayout);
scrollView.addView(verticalLayout);
// Show the global layout
setContentView(mainLayout);
}
public void onSaveInstanceState( Bundle savedInstanceState )
{
// now, save the text if something overlaps this Activity
savedInstanceState.putString( savedInstanceString, mEdit.getText().toString() );
}
@Override
protected void onStop()
{
super.onStop();
// Send a focus gained event
// when going back to MoSync view
int[] event = new int[3];
event[0] = EVENT_TYPE_FOCUS_GAINED;
event[1] = 0;
event[2] = 0;
MoSyncThread.getInstance().postEvent(event);
}
@Override
protected void onRestart()
{
super.onRestart();
}
@Override
protected void onResume()
{
super.onResume();
}
@Override
protected void onPause()
{
super.onPause();
}
@Override
protected void onStart()
{
super.onStart();
}
/**
* Handles the new configurations when the screen rotates.
* @param newConfig Object that holds configuration info.
*/
@Override
public void onConfigurationChanged(Configuration newConfig)
{
Log.i("MoSync Textbox", "onConfigurationChanged");
// Just pass to superclass, we do not do anything special here.
super.onConfigurationChanged(newConfig);
}
@Override
public void onClick(View v)
{
MoSyncThread mosyncThread = MoSyncThread.getInstance();
if (v.getId() == mOkButton.getId())
{
Log.i("InputBox", "OK clicked.");
String output = mEdit.getText().toString();
// TODO: We could add a check that maxLength is not exceeded.
// In this case, make maxLength an instance variable, rename
// it to mMaxLength.
// Write text directly to the MoSync memory
char[] ca = output.toCharArray();
- ByteBuffer buffer = mosyncThread.getMemorySlice(mOutputMemPtr, (ca.length + 1) * 2);
+ ByteBuffer buffer = mosyncThread.getMemorySlice(mOutputMemPtr, (ca.length + 1) * 2).order(null);
// NOTE: THIS DIFFERS FROM WHAT IS BEING OUTPUT IN THE mCancelButton check,
// where bytes are used instead. Really strange -- is this wchars or smthg? Why?
CharBuffer cb = buffer.asCharBuffer();
cb.put(ca);
cb.put((char)0);
// Notice that data is available
int[] event = new int[3];
event[0] = EVENT_TYPE_TEXTBOX;
event[1] = MA_TB_RES_OK;
event[2] = output.length();
mosyncThread.postEvent(event);
Log.i("InputBox", "event" + output.length());
Log.i("InputBox", "event" + event[1]);
finish();
}
if (v.getId() == mCancelButton.getId())
{
Log.i("InputBox", "Cancel clicked.");
String output = mEdit.getText().toString();
// Write text directly to the MoSync memory
byte[] ba = output.getBytes();
- ByteBuffer buffer = mosyncThread.getMemorySlice(mOutputMemPtr, ba.length + 1);
+ ByteBuffer buffer = mosyncThread.getMemorySlice(mOutputMemPtr, ba.length + 1).order(null);
buffer.put(ba);
buffer.put((byte)0);
// Notice that the user clicked cancel
int[] event = new int[3];
event[0] = EVENT_TYPE_TEXTBOX;
event[1] = MA_TB_RES_CANCEL;
event[2] = 0;
mosyncThread.postEvent(event);
finish();
}
}
}
| false | false | null | null |
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index a43c299cf..13dbb461f 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -1,3799 +1,3800 @@
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Logger;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Map.Position;
import net.sf.freecol.common.model.PathNode;
import net.sf.freecol.common.util.EmptyIterator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Represents all pieces that can be moved on the map-board.
* This includes: colonists, ships, wagon trains e.t.c.
*
* <br><br>
*
* Every <code>Unit</code> is owned by a {@link Player} and has a
* {@link Location}.
*/
public class Unit extends FreeColGameObject implements Location, Locatable, Ownable {
public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
private static final Logger logger = Logger.getLogger(Unit.class.getName());
/** The type of a unit; used only for gameplaying purposes NOT painting purposes. */
public static final int FREE_COLONIST = 0,
EXPERT_FARMER = 1,
EXPERT_FISHERMAN = 2,
EXPERT_FUR_TRAPPER = 3,
EXPERT_SILVER_MINER = 4,
EXPERT_LUMBER_JACK = 5,
EXPERT_ORE_MINER = 6,
MASTER_SUGAR_PLANTER = 7,
MASTER_COTTON_PLANTER = 8,
MASTER_TOBACCO_PLANTER = 9,
FIREBRAND_PREACHER = 10,
ELDER_STATESMAN = 11,
MASTER_CARPENTER = 12,
MASTER_DISTILLER = 13,
MASTER_WEAVER = 14,
MASTER_TOBACCONIST = 15,
MASTER_FUR_TRADER = 16,
MASTER_BLACKSMITH = 17,
MASTER_GUNSMITH = 18,
SEASONED_SCOUT = 19,
HARDY_PIONEER = 20,
VETERAN_SOLDIER = 21,
JESUIT_MISSIONARY = 22,
INDENTURED_SERVANT = 23,
PETTY_CRIMINAL = 24,
INDIAN_CONVERT = 25,
BRAVE = 26,
COLONIAL_REGULAR = 27,
KINGS_REGULAR = 28,
CARAVEL = 29,
FRIGATE = 30,
GALLEON = 31,
MAN_O_WAR = 32,
MERCHANTMAN = 33,
PRIVATEER = 34,
ARTILLERY = 35,
DAMAGED_ARTILLERY = 36,
TREASURE_TRAIN = 37,
WAGON_TRAIN = 38,
MILKMAID = 39,
UNIT_COUNT = 40;
/** A state a Unit can have. */
public static final int ACTIVE = 0,
FORTIFY = 1,
SENTRY = 2,
IN_COLONY = 3,
PLOW = 4,
BUILD_ROAD = 5,
TO_EUROPE = 6,
IN_EUROPE = 7,
TO_AMERICA = 8,
NUMBER_OF_STATES = 9;
/**
* A move type.
* @see #getMoveType
*/
public static final int MOVE = 0,
MOVE_HIGH_SEAS = 1,
ATTACK = 2,
EMBARK = 3,
DISEMBARK = 4,
ENTER_INDIAN_VILLAGE_WITH_FREE_COLONIST = 5,
ENTER_INDIAN_VILLAGE_WITH_SCOUT = 6,
ENTER_INDIAN_VILLAGE_WITH_MISSIONARY = 7,
ENTER_FOREIGN_COLONY_WITH_SCOUT = 8,
ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS = 9,
EXPLORE_LOST_CITY_RUMOUR = 10,
ILLEGAL_MOVE = 11;
public static final int ATTACK_GREAT_LOSS = -2,
ATTACK_LOSS = -1,
ATTACK_EVADES = 0,
ATTACK_WIN = 1,
ATTACK_GREAT_WIN = 2,
ATTACK_DONE_SETTLEMENT = 3; // The last defender of the settlement has died.
public static final int MUSKETS_TO_ARM_INDIAN = 25,
HORSES_TO_MOUNT_INDIAN = 25;
private int type;
private UnitType unitType;
private boolean armed,
mounted,
missionary;
private int movesLeft; // Always use getMovesLeft()
private int state;
private int workLeft; // expressed in number of turns, '-1' if a Unit can stay in its state forever
private int numberOfTools;
private int hitpoints; // For now; only used by ships when repairing.
private Player owner;
private UnitContainer unitContainer;
private GoodsContainer goodsContainer;
private Location entryLocation;
private Location location;
private IndianSettlement indianSettlement = null; // only used by BRAVE.
private Location destination = null;
// to be used only for type == TREASURE_TRAIN
private int treasureAmount;
private int workType; // What type of goods this unit produces in its occupation.
private int turnsOfTraining = 0;
private int trainingType = -1;
/**
* The amount of goods carried by this unit.
* This variable is only used by the clients.
* A negative value signals that the variable
* is not in use.
*
* @see #getVisibleGoodsCount()
*/
private int visibleGoodsCount;
/**
* This constructor should only be used by subclasses.
*/
protected Unit() {
}
/**
* Initiate a new <code>Unit</code> of a specified type with the state set
* to {@link #ACTIVE} if a carrier and {@link #SENTRY} otherwise. The
* {@link Location} is set to <i>null</i>.
*
* @param game The <code>Game</code> in which this <code>Unit</code> belong.
* @param owner The Player owning the unit.
* @param type The type of the unit.
*/
public Unit(Game game, Player owner, int type) {
this(game, null, owner, type, isCarrier(type)?ACTIVE:SENTRY);
}
/**
* Initiate a new <code>Unit</code> with the specified parameters.
*
* @param game The <code>Game</code> in which this <code>Unit</code> belong.
* @param location The <code>Location</code> to place this <code>Unit</code> upon.
* @param owner The <code>Player</code> owning this unit.
* @param type The type of the unit.
* @param s The initial state for this Unit (one of {@link #ACTIVE}, {@link #FORTIFY}...).
*/
public Unit(Game game, Location location, Player owner, int type, int s) {
this(game, location, owner, type, s,
(type == VETERAN_SOLDIER),
(type == SEASONED_SCOUT),
(type == HARDY_PIONEER) ? 100 : 0,
(type == JESUIT_MISSIONARY));
}
/**
* Initiate a new <code>Unit</code> with the specified parameters.
*
* @param game The <code>Game</code> in which this <code>Unit</code> belong.
* @param location The <code>Location</code> to place this <code>Unit</code> upon.
* @param owner The <code>Player</code> owning this unit.
* @param type The type of the unit.
* @param s The initial state for this Unit (one of {@link #ACTIVE}, {@link #FORTIFY}...).
* @param armed Determines wether the unit should be armed or not.
* @param mounted Determines wether the unit should be mounted or not.
* @param numberOfTools The number of tools the unit will be carrying.
* @param missionary Determines wether this unit should be dressed like a missionary or not.
*/
public Unit(Game game, Location location, Player owner, int type, int s,
boolean armed, boolean mounted, int numberOfTools, boolean missionary) {
super(game);
visibleGoodsCount = -1;
unitContainer = new UnitContainer(game, this);
goodsContainer = new GoodsContainer(game, this);
this.owner = owner;
this.type = type;
unitType = FreeCol.specification.unitType( type );
this.armed = armed;
this.mounted = mounted;
this.numberOfTools = numberOfTools;
this.missionary = missionary;
setLocation(location);
state = s;
workLeft = -1;
workType = Goods.FOOD;
this.movesLeft = getInitialMovesLeft();
setHitpoints(getInitialHitpoints(getType()));
getOwner().invalidateCanSeeTiles();
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param game The <code>Game</code> in which this <code>Unit</code> belong.
* @param element The DOM-element ("Document Object Model") made to represent this "Unit".
*/
public Unit(Game game, Element element) {
super(game, element);
readFromXMLElement(element);
}
/**
* Returns the current amount of treasure in this unit.
* Should be type of TREASURE_TRAIN.
* @return The amount of treasure.
*/
public int getTreasureAmount() {
if (getType() == TREASURE_TRAIN) {
return treasureAmount;
}
throw new IllegalStateException();
}
/**
* The current amount of treasure in this unit.
* Should be type of TREASURE_TRAIN.
* @param amt The amount of treasure
*/
public void setTreasureAmount(int amt) {
if (getType() == TREASURE_TRAIN) {
this.treasureAmount = amt;
} else {
throw new IllegalStateException();
}
}
/**
* Sells the given goods from this unit to the given settlement.
* The owner of this unit gets the gold and the owner of
* the settlement is charged for the deal.
*
* @param settlement The <code>Settlement</code> to trade with.
* @param goods The <code>Goods</code> to be traded.
* @param gold The money to be given for the goods.
*/
public void trade(Settlement settlement, Goods goods, int gold) {
if (getTile().getDistanceTo(settlement.getTile()) > 1) {
logger.warning("Unit not adjacent to settlement!");
throw new IllegalStateException("Unit not adjacent to settlement!");
}
if (goods.getLocation() != this) {
logger.warning("Goods not onboard this unit!");
throw new IllegalStateException("Goods not onboard this unit!");
}
if (getMovesLeft() <= 0) {
logger.warning("No more moves!");
throw new IllegalStateException("No more moves left!");
}
goods.setLocation(settlement);
/*
Value already tested. This test is needed because the opponent's
amount of gold is hidden for the client:
*/
if (settlement.getOwner().getGold() - gold >= 0) {
settlement.getOwner().modifyGold(-gold);
}
setMovesLeft(0);
getOwner().modifyGold(gold);
if (settlement instanceof IndianSettlement) {
int value = ((IndianSettlement) settlement).getPrice(goods) / 1000;
settlement.getOwner().modifyTension(getOwner(), -value);
}
}
/**
* Transfers the given goods from this unit to the given settlement.
* @param settlement The <code>Settlement</code> to deliver a gift to.
* @param goods The <code>Goods</code> to be delivered as a gift.
*/
public void deliverGift(Settlement settlement, Goods goods) {
if (getTile().getDistanceTo(settlement.getTile()) > 1) {
logger.warning("Unit not adjacent to settlement!");
throw new IllegalStateException("Unit not adjacent to settlement!");
}
if (goods.getLocation() != this) {
logger.warning("Goods not onboard this unit!");
throw new IllegalStateException("Goods not onboard this unit!");
}
if (getMovesLeft() <= 0) {
logger.warning("No more moves left!");
throw new IllegalStateException("No more moves left!");
}
int type = goods.getType();
int amount = goods.getAmount();
goods.setLocation(settlement);
setMovesLeft(0);
if (settlement instanceof IndianSettlement) {
int value = ((IndianSettlement) settlement).getPrice(goods) / 100;
settlement.getOwner().modifyTension(getOwner(), -value);
} else {
addModelMessage(settlement.getOwner(), "model.unit.gift",
new String[][] {{"%player%", getOwner().getNationAsString()},
{"%type%", Goods.getName(type)},
{"%amount%", Integer.toString(amount)}},
ModelMessage.DEFAULT);
}
}
/**
* Checks if the treasure train can be cashed in at it's
* current <code>Location</code>.
*
* @return <code>true</code> if the treasure train can be
* cashed in.
* @exception IllegalStateException if this unit is not a treasure train.
*/
public boolean canCashInTreasureTrain() {
return canCashInTreasureTrain(getLocation());
}
/**
* Checks if the treasure train can be cashed in at the
* given <code>Location</code>.
*
* @param location The <code>Location</code>.
* @return <code>true</code> if the treasure train can be
* cashed in.
* @exception IllegalStateException if this unit is not a treasure train.
*/
public boolean canCashInTreasureTrain(Location location) {
if (getType() != TREASURE_TRAIN) {
throw new IllegalStateException("Not a treasure train");
}
return location instanceof Tile && location.getTile().getColony() != null
|| location instanceof Europe
|| (location instanceof Unit && ((Unit) location).getLocation() instanceof Europe);
}
/**
* Transfers the gold carried by this unit to the {@link Player owner}.
*
* @exception IllegalStateException if this unit is not a treasure train.
* or if it cannot be cashed in at it's current
* location.
*/
public void cashInTreasureTrain() {
if (getType() != TREASURE_TRAIN) {
throw new IllegalStateException("Not a treasure train");
}
if (canCashInTreasureTrain()) {
boolean inEurope = (getLocation() instanceof Unit && ((Unit) getLocation()).getLocation() instanceof Europe);
int cashInAmount = (getOwner().hasFather(FoundingFather.HERNAN_CORTES) || inEurope) ? getTreasureAmount() : getTreasureAmount() / 2; // TODO: Use tax
FreeColGameObject o = getOwner();
if (inEurope) {
o = getOwner().getEurope();
}
getOwner().modifyGold(cashInAmount);
addModelMessage(o, "model.unit.cashInTreasureTrain",
new String[][] {{"%amount%", Integer.toString(getTreasureAmount())},
{"%cashInAmount%", Integer.toString(cashInAmount)}},
ModelMessage.DEFAULT);
dispose();
} else {
throw new IllegalStateException("Cannot cash in treasure train at the current location.");
}
}
/**
* Checks if this <code>Unit</code> is a colonist. A <code>Unit</code>
* is a colonist if it can build a new <code>Colony</code>.
*
* @return <i>true</i> if this unit is a colonist and
* <i>false</i> otherwise.
*/
public boolean isColonist() {
return unitType.hasAbility( "found-colony" );
}
/**
* Gets the number of turns this unit has to train to
* become the current {@link #getTrainingType training type}.
*
* @return The turns of training needed to become the current
* training type, or <code>Integer.MAX_VALUE</code> if
* if no training type is specified.
* @see #getTrainingType
* @see #getTurnsOfTraining
*/
public int getNeededTurnsOfTraining() {
if (trainingType != -1) {
return 2 + getSkillLevel(trainingType);
}
return Integer.MAX_VALUE;
}
/**
* Gets the skill level.
* @return The level of skill for this unit. A higher
* value signals a more advanced type of units.
*/
public int getSkillLevel() {
return getSkillLevel(getType());
}
/**
* Gets the skill level of the given type of <code>Unit</code>.
*
* @param unitTypeIndex The type of <code>Unit</code>.
* @return The level of skill for the given unit. A higher
* value signals a more advanced type of units.
*/
public static int getSkillLevel( int unitTypeIndex ) {
UnitType unitType = FreeCol.specification.unitType(unitTypeIndex);
if ( unitType.hasSkill() ) {
return unitType.skill;
}
throw new IllegalStateException();
}
/**
* Gets the number of turns this unit has been training.
*
* @return The number of turns of training this
* <code>Unit</code> has received.
* @see #setTurnsOfTraining
* @see #getTrainingType
* @see #getNeededTurnsOfTraining
*/
public int getTurnsOfTraining() {
return turnsOfTraining;
}
/**
* Sets the number of turns this unit has been training.
* @param turnsOfTraining The number of turns of training this
* <code>Unit</code> has received.
* @see #getNeededTurnsOfTraining
*/
public void setTurnsOfTraining(int turnsOfTraining) {
this.turnsOfTraining = turnsOfTraining;
}
/**
* Gets the unit type this <code>Unit</code> is training for.
*
* @return The type of <code>Unit</code> which this
* <code>Unit</code> is currently working to become.
* @see #getTurnsOfTraining
* @see #setTrainingType
*/
public int getTrainingType() {
return trainingType;
}
/**
* Sets the unit type this <code>Unit</code> is training for.
* Use <code>-1</code> for no type at all.
*
* @param trainingType The type of <code>Unit</code> which this
* <code>Unit</code> should currently working to become.
* @see #getTurnsOfTraining
* @see #getTrainingType
*/
public void setTrainingType(int trainingType) {
if (getType() == PETTY_CRIMINAL || getType() == INDENTURED_SERVANT) {
this.trainingType = FREE_COLONIST;
} else {
this.trainingType = trainingType;
}
}
/**
* Gets the type of goods this unit is producing in its current occupation.
* @return The type of goods this unit would produce.
*/
public int getWorkType() {
if (getLocation() instanceof Building) {
return ((Building) getLocation()).getGoodsOutputType();
}
return workType;
}
/**
* Sets the type of goods this unit is producing in its current occupation.
* @param type The type of goods to attempt to produce.
*/
public void setWorkType(int type) {
if (!Goods.isFarmedGoods(type)) {
return;
}
workType = type;
}
/**
* Gets the type of goods this unit is an expert
* at producing.
*
* @return The type of goods or <code>-1</code> if this unit is not an
* expert at producing any type of goods.
* @see ColonyTile#getExpertForProducing
*/
public int getExpertWorkType() {
GoodsType expertProduction = unitType.expertProduction;
return (expertProduction != null) ? expertProduction.index : -1;
}
/**
* Returns the destination of this unit.
*
* @return The destination of this unit.
*/
public Location getDestination() {
return destination;
}
/**
* Sets the destination of this unit.
*
* @param newDestination The new destination of this unit.
*/
public void setDestination(Location newDestination) {
this.destination = newDestination;
}
/**
* Finds a shortest path from the current <code>Tile</code>
* to the one specified. Only paths on water are allowed if
* <code>isNaval()</code> and only paths on land if not.
*
* <br><br>
*
* The <code>Tile</code> at the <code>end</code> will not be
* checked against the legal moves of this <code>Unit</code>.
*
* @param end The <code>Tile</code> in which the path ends.
* @return A <code>PathNode</code> for the first tile in the path. Calling
* {@link PathNode#getTile} on this object, will return the
* <code>Tile</code> right after the specified starting tile, and
* {@link PathNode#getDirection} will return the direction you
* need to take in order to reach that tile.
* This method returns <code>null</code> if no path is found.
* @see Map#findPath(Tile, Tile, int)
* @see Map#findPath(Unit, Tile , Tile)
* @exception NullPointerException if <code>end == null</code>
*/
public PathNode findPath(Tile end) {
if (getTile() == null) {
logger.warning("getTile() == null for " + getName() + " at location: " + getLocation());
}
return getGame().getMap().findPath(this, getTile(), end);
}
/**
* Returns the number of turns this <code>Unit</code> will have to use
* in order to reach the given <code>Tile</code>.
*
* @param end The <code>Tile</code> to be reached by this <code>Unit</code>.
* @return The number of turns it will take to reach the <code>end</code>,
* or <code>Integer.MAX_VALUE</code> if no path can be found.
*/
public int getTurnsToReach(Tile end) {
return getTurnsToReach(getTile(), end);
}
/**
* Returns the number of turns this <code>Unit</code> will have to use
* in order to reach the given <code>Tile</code>.
*
* @param start The <code>Tile</code> to start the search from.
* @param end The <code>Tile</code> to be reached by this <code>Unit</code>.
* @return The number of turns it will take to reach the <code>end</code>,
* or <code>Integer.MAX_VALUE</code> if no path can be found.
*/
public int getTurnsToReach(Tile start, Tile end) {
if (start == end) {
return 0;
}
if (getLocation() instanceof Unit) {
PathNode p = getGame().getMap().findPath(this, start, end, (Unit) getLocation());
if (p != null) {
return p.getTotalTurns();
}
}
PathNode p = getGame().getMap().findPath(this, start, end);
if (p != null) {
return p.getTotalTurns();
}
return Integer.MAX_VALUE;
}
/**
* Gets the cost of moving this <code>Unit</code> onto the given <code>Tile</code>.
* A call to {@link #getMoveType(Tile)} will return <code>ILLEGAL_MOVE</code>, if {@link #getMoveCost}
* returns a move cost larger than the {@link #getMovesLeft moves left}.
*
* @param target The <code>Tile</code> this <code>Unit</code> will move onto.
* @return The cost of moving this unit onto the given <code>Tile</code>.
* @see Tile#getMoveCost
*/
public int getMoveCost(Tile target) {
// Remember to also change map.findPath(...) if you change anything here.
int cost = target.getMoveCost(getTile());
// Using +2 in order to make 1/3 and 2/3 move count as 3/3.
if (cost > getMovesLeft()) {
if (getMovesLeft() + 2 >= getInitialMovesLeft() || cost <= getMovesLeft() + 2) {
return getMovesLeft();
}
return cost;
} else if ((isNaval() || getType() == WAGON_TRAIN) && target.getSettlement() != null) {
return getMovesLeft();
} else {
return cost;
}
}
/**
* Returns true if this unit can enter a settlement in order to trade.
*
* @param settlement The settlement to enter.
* @return <code>true</code> if this <code>Player</code> can trade
* with the given <code>Settlement</code>. The unit will for
* instance need to be a {@link #isCarrier carrier} and have
* goods onboard.
*/
public boolean canTradeWith(Settlement settlement) {
return (isCarrier() &&
goodsContainer.getGoodsCount() > 0 &&
getOwner().getStance(settlement.getOwner()) != Player.WAR &&
((settlement instanceof IndianSettlement) ||
getOwner().hasFather(FoundingFather.JAN_DE_WITT)));
}
/**
* Gets the type of a move made in a specified direction.
*
* @param direction The direction of the move.
* @return The move type. Notice: <code>Unit.ILLEGAL_MOVE</code>
* when there are no moves left.
*/
public int getMoveType(int direction) {
if (getTile() == null) {
throw new IllegalStateException("getTile() == null");
}
Tile target = getGame().getMap().getNeighbourOrNull(direction, getTile());
return getMoveType(target);
}
/**
* Gets the type of a move that is made when moving to the
* specified <code>Tile</code> from the current one.
*
* @param target The target tile of the move
* @return The move type. Notice: <code>Unit.ILLEGAL_MOVE</code>
* when there are no moves left.
*/
public int getMoveType(Tile target) {
if (getTile() == null) {
throw new IllegalStateException("getTile() == null");
} else if (isUnderRepair()) {
return ILLEGAL_MOVE;
} else if (getMovesLeft() <= 0) {
return ILLEGAL_MOVE;
} else {
if (isNaval()) {
return getNavalMoveType(target);
}
return getLandMoveType(target);
}
}
/**
* Gets the type of a move that is made when moving to the
* specified <code>Tile</code> from the current one.
*
* @param target The target tile of the move
* @return The move type. Notice: <code>Unit.ILLEGAL_MOVE</code>
* when there are no moves left.
*/
private int getNavalMoveType(Tile target) {
if (target == null) { // TODO: do not allow "MOVE_HIGH_SEAS" north and south.
if (getOwner().canMoveToEurope()) {
return MOVE_HIGH_SEAS;
} else {
return ILLEGAL_MOVE;
}
} else if (target.isLand()) {
Settlement settlement = target.getSettlement();
if (settlement != null) {
if (settlement.getOwner() == getOwner()) {
return MOVE;
} else if (canTradeWith(settlement)) {
return ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS;
} else {
logger.fine("Trying to enter another player's settlement with " +
getName());
return ILLEGAL_MOVE;
}
} else if (target.getDefendingUnit(this) != null &&
target.getDefendingUnit(this).getOwner() != getOwner()) {
logger.fine("Trying to sail into tile occupied by enemy units with " +
getName());
return ILLEGAL_MOVE;
} else {
// Check for disembark.
Iterator unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = (Unit) unitIterator.next();
if (u.getMovesLeft() > 0) {
return DISEMBARK;
}
}
logger.fine("No units to disembark from " + getName());
return ILLEGAL_MOVE;
}
} else if (target.getDefendingUnit(this) != null &&
target.getDefendingUnit(this).getOwner() != getOwner()) {
// enemy units at sea
if (isOffensiveUnit()) {
return ATTACK;
} else {
return ILLEGAL_MOVE;
}
} else if (target.getType() == Tile.HIGH_SEAS) {
if (getOwner().canMoveToEurope()) {
return MOVE_HIGH_SEAS;
} else {
return MOVE;
}
} else {
// this must be ocean
return MOVE;
}
}
/**
* Gets the type of a move that is made when moving to the
* specified <code>Tile</code> from the current one.
*
* @param target The target tile of the move
* @return The move type. Notice: <code>Unit.ILLEGAL_MOVE</code>
* when there are no moves left.
*/
private int getLandMoveType(Tile target) {
if (target == null) {
// only naval units are allowed to do this
logger.fine("Trying to enter null tile with land unit " + getName());
return ILLEGAL_MOVE;
}
if (target.isLand()) {
Settlement settlement = target.getSettlement();
if (settlement != null) {
if (settlement.getOwner() == getOwner()) {
// our colony
return MOVE;
} else if (canTradeWith(settlement)) {
return ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS;
} else if (!getTile().isLand()) {
logger.fine("Trying to disembark into foreign colony with " +
getName());
return ILLEGAL_MOVE;
} else if (settlement instanceof IndianSettlement) {
if (isScout()) {
return ENTER_INDIAN_VILLAGE_WITH_SCOUT;
} else if (isMissionary()) {
return ENTER_INDIAN_VILLAGE_WITH_MISSIONARY;
} else if (isOffensiveUnit()) {
return ATTACK;
} else if (((getType() == FREE_COLONIST) ||
(getType() == INDENTURED_SERVANT))) {
return ENTER_INDIAN_VILLAGE_WITH_FREE_COLONIST;
} else {
logger.fine("Trying to enter Indian settlement with " +
getName());
return ILLEGAL_MOVE;
}
} else if (settlement instanceof Colony) {
if (isScout()) {
return ENTER_FOREIGN_COLONY_WITH_SCOUT;
} else if (isOffensiveUnit()) {
return ATTACK;
} else {
logger.fine("Trying to enter foreign colony with " +
getName());
return ILLEGAL_MOVE;
}
}
} else if (target.getDefendingUnit(this) != null &&
target.getDefendingUnit(this).getOwner() != getOwner()) {
if (getTile().isLand()) {
if (isOffensiveUnit()) {
return ATTACK;
} else {
logger.fine("Trying to attack with civilian " + getName());
return ILLEGAL_MOVE;
}
} else {
logger.fine("Attempting marine assault with " + getName());
return ILLEGAL_MOVE;
}
} else if (getMoveCost(target) > getMovesLeft()) {
return ILLEGAL_MOVE;
} else if (target.hasLostCityRumour()) {
return EXPLORE_LOST_CITY_RUMOUR;
} else {
return MOVE;
}
} else {
// check for embarkation
if (target.getFirstUnit() == null ||
target.getFirstUnit().getNation() != getNation()) {
logger.fine("Trying to embark on tile occupied by foreign units with " +
getName());
return ILLEGAL_MOVE;
} else {
Iterator unitIterator = target.getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = (Unit) unitIterator.next();
if (u.getSpaceLeft() >= getTakeSpace()) {
return EMBARK;
}
}
logger.fine("Trying to board full vessel with " +
getName());
return ILLEGAL_MOVE;
}
}
logger.info("Default illegal move for " + getName());
return ILLEGAL_MOVE;
}
/**
* Sets the <code>movesLeft</code>.
*
* @param movesLeft The new amount of moves left this
* <code>Unit</code> should have. If <code>movesLeft < 0</code>
* then <code>movesLeft = 0</code>.
*/
public void setMovesLeft(int movesLeft) {
if (movesLeft < 0) {
movesLeft = 0;
}
this.movesLeft = movesLeft;
}
/**
* Gets the amount of space this <code>Unit</code> takes when put on a carrier.
*
* @return The space this <code>Unit</code> takes.
*/
public int getTakeSpace() {
if (getType() == TREASURE_TRAIN) {
return 6;
} else if (isCarrier()) {
return 100000; // Not possible to put on a carrier.
} else {
return 1;
}
}
/**
* Gets the line of sight of this <code>Unit</code>. That is the
* distance this <code>Unit</code> can spot new tiles, enemy unit e.t.c.
*
* @return The line of sight of this <code>Unit</code>.
*/
public int getLineOfSight() {
int type = getType();
if (isScout() || type == FRIGATE || type == GALLEON || type == MAN_O_WAR || type == PRIVATEER) {
return 2;
} else if (getOwner().hasFather(FoundingFather.HERNANDO_DE_SOTO)) {
return 2;
} else {
return 1;
}
}
/**
* Checks if this <code>Unit</code> is a scout.
*
* @return <i>true</i> if this <code>Unit</code> is a scout and
* <i>false</i> otherwise.
*/
public boolean isScout() {
return isMounted() && ! isArmed();
}
/**
* Moves this unit in the specified direction.
*
* @param direction The direction
* @see #getMoveType(int)
* @exception IllegalStateException If the move is illegal.
*/
public void move(int direction) {
int type = getMoveType(direction);
// For debugging:
switch (type) {
case MOVE:
case MOVE_HIGH_SEAS:
case EXPLORE_LOST_CITY_RUMOUR:
break;
case ATTACK:
case EMBARK:
case ENTER_INDIAN_VILLAGE_WITH_FREE_COLONIST:
case ENTER_INDIAN_VILLAGE_WITH_SCOUT:
case ENTER_INDIAN_VILLAGE_WITH_MISSIONARY:
case ENTER_FOREIGN_COLONY_WITH_SCOUT:
case ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS:
case ILLEGAL_MOVE:
default:
throw new IllegalStateException("\nIllegal move requested: " + type
+ " while trying to move a " + getName() + " located at "
+ getTile().getPosition().toString() + ". Direction: "
+ direction + " Moves Left: " + getMovesLeft());
}
setState(ACTIVE);
setStateToAllChildren(SENTRY);
Tile newTile = getGame().getMap().getNeighbourOrNull(direction, getTile());
int moveCost = getMoveCost(newTile);
if (newTile != null) {
setLocation(newTile);
} else {
throw new IllegalStateException("Illegal move requested!");
}
setMovesLeft(getMovesLeft() - moveCost);
}
/**
* Embarks this unit onto the specified unit.
*
* @param unit The unit to embark onto.
* @exception IllegalStateException If the embark is illegal.
* NullPointerException If <code>unit == null</code>.
*/
public void embark(Unit unit) {
if (unit == null) {
throw new NullPointerException();
}
if (getMoveType(unit.getTile()) != EMBARK) {
throw new IllegalStateException("Illegal disembark requested!");
}
setLocation(unit);
setMovesLeft(getMovesLeft() - 3);
}
/**
* Boards a carrier that is on the same tile.
*
* @param carrier The carrier this unit shall embark.
* @exception IllegalStateException If the carrier is on another tile than this unit.
*/
public void boardShip(Unit carrier) {
if (isCarrier()) {
throw new IllegalStateException("A carrier cannot board another carrier!");
}
if (getTile() == carrier.getTile() && carrier.getState() != TO_EUROPE && carrier.getState() != TO_AMERICA) {
setLocation(carrier);
setState(SENTRY);
} else {
throw new IllegalStateException("It is not allowed to board a ship on another tile.");
}
if (getTile() != null && getTile().getColony() != null && getTile().getColony().getUnitCount() <= 0) {
getTile().getColony().dispose();
}
}
/**
* Leave the ship. This method should only be invoked if the ship is in a harbour.
*
* @exception IllegalStateException If not in harbour.
* @exception ClassCastException If not this unit is located on a ship.
*/
public void leaveShip() {
Unit carrier = (Unit) getLocation();
Location l = carrier.getLocation();
if (l instanceof Europe && carrier.getState() != TO_EUROPE && carrier.getState() != TO_AMERICA) {
setLocation(l);
} else if (getTile().getSettlement() != null) {
setLocation(getTile());
} else {
throw new IllegalStateException("A unit may only leave a ship while in a harbour.");
}
setState(ACTIVE);
}
/**
* Sets the given state to all the units that si beeing carried.
* @param state The state.
*/
public void setStateToAllChildren(int state) {
if (isCarrier()) {
Iterator i = getUnitIterator();
while (i.hasNext()) {
((Unit) i.next()).setState(state);
}
}
}
/**
* Adds a locatable to this <code>Unit</code>.
* @param locatable The <code>Locatable</code> to add to this <code>Unit</code>.
*/
public void add(Locatable locatable) {
if (isCarrier()) {
if (locatable instanceof Unit) {
if (getSpaceLeft() <= 0 || getType() == WAGON_TRAIN) {
throw new IllegalStateException();
}
unitContainer.addUnit((Unit) locatable);
} else if (locatable instanceof Goods) {
goodsContainer.addGoods((Goods) locatable);
if (getSpaceLeft() < 0) {
throw new IllegalStateException("Not enough space for the given locatable!");
}
} else {
logger.warning("Tried to add an unrecognized 'Locatable' to a unit.");
}
} else {
logger.warning("Tried to add a 'Locatable' to a non-carrier unit.");
}
}
/**
* Removes a <code>Locatable</code> from this <code>Unit</code>.
* @param locatable The <code>Locatable</code> to remove from this <code>Unit</code>.
*/
public void remove(Locatable locatable) {
if (isCarrier()) {
if (locatable instanceof Unit) {
unitContainer.removeUnit((Unit) locatable);
} else if (locatable instanceof Goods) {
goodsContainer.removeGoods((Goods) locatable);
} else {
logger.warning("Tried to remove an unrecognized 'Locatable' from a unit.");
}
} else {
logger.warning("Tried to remove a 'Locatable' from a non-carrier unit.");
}
}
/**
* Checks if this <code>Unit</code> contains the specified
* <code>Locatable</code>.
*
* @param locatable The <code>Locatable</code> to test the
* presence of.
* @return <ul>
* <li><i>true</i> if the specified <code>Locatable</code>
* is on this <code>Unit</code> and
* <li><i>false</i> otherwise.
* </ul>
*/
public boolean contains(Locatable locatable) {
if (isCarrier()) {
if (locatable instanceof Unit) {
return unitContainer.contains((Unit) locatable);
} else if (locatable instanceof Goods) {
return goodsContainer.contains((Goods) locatable);
} else {
return false;
}
} else {
logger.warning("Tried to remove a 'Locatable' from a non-carrier unit.");
return false;
}
}
/**
* Checks wether or not the specified locatable may be added to this
* <code>Unit</code>. The locatable cannot be added is this
* <code>Unit</code> if it is not a carrier or if there is no room left.
*
* @param locatable The <code>Locatable</code> to test the addabillity of.
* @return The result.
*/
public boolean canAdd(Locatable locatable) {
if (isCarrier()) {
if ((getType() == WAGON_TRAIN || getType() == BRAVE) && locatable instanceof Unit) {
return false;
}
if (locatable instanceof Unit) {
return getSpaceLeft() >= locatable.getTakeSpace();
} else if (locatable instanceof Goods) {
Goods g = (Goods) locatable;
return getSpaceLeft() > 0 ||
(getGoodsContainer().getGoodsCount(g.getType()) % 100 != 0
&& getGoodsContainer().getGoodsCount(g.getType()) % 100 + g.getAmount() <= 100);
} else { // Is there another class that implements Locatable ??
logger.warning("Oops, not implemented...");
return false;
}
} else {
return false;
}
}
/**
* Gets the amount of Units at this Location.
* @return The amount of Units at this Location.
*/
public int getUnitCount() {
return isCarrier() ? unitContainer.getUnitCount() : 0;
}
/**
* Gets the first <code>Unit</code> beeing carried by this <code>Unit</code>.
* @return The <code>Unit</code>.
*/
public Unit getFirstUnit() {
return isCarrier() ? unitContainer.getFirstUnit() : null;
}
/**
* Checks if this unit is visible to the given player.
* @param player The <code>Player</code>.
* @return <code>true</code> if this <code>Unit</code> is
* visible to the given <code>Player</code>.
*/
public boolean isVisibleTo(Player player) {
if (player == getOwner()) {
return true;
}
return getTile() != null && player.canSee(getTile())
&& (getTile().getSettlement() == null
|| getTile().getSettlement().getOwner() == player
|| !getGameOptions().getBoolean(GameOptions.UNIT_HIDING))
&& (!(getLocation() instanceof Unit)
|| ((Unit) getLocation()).getOwner() == player
|| !getGameOptions().getBoolean(GameOptions.UNIT_HIDING));
}
/**
* Gets the last <code>Unit</code> beeing carried by this <code>Unit</code>.
* @return The <code>Unit</code>.
*/
public Unit getLastUnit() {
return isCarrier() ? unitContainer.getLastUnit() : null;
}
/**
* Gets a <code>Iterator</code> of every <code>Unit</code> directly located on this
* <code>Location</code>.
*
* @return The <code>Iterator</code>.
*/
public Iterator getUnitIterator() {
if ( isCarrier() && getType() != WAGON_TRAIN ) {
return unitContainer.getUnitIterator();
}
return EmptyIterator.SHARED_INSTANCE;
}
/**
* Gets a <code>Iterator</code> of every <code>Unit</code> directly located on this
* <code>Location</code>.
*
* @return The <code>Iterator</code>.
*/
public Iterator getGoodsIterator() {
if (isCarrier()) {
return goodsContainer.getGoodsIterator();
} else { // TODO: Make a better solution:
return (new ArrayList()).iterator();
}
}
public GoodsContainer getGoodsContainer() {
return goodsContainer;
}
public UnitContainer getUnitContainer() {
return unitContainer;
}
/**
* Sets this <code>Unit</code> to work in the
* specified <code>WorkLocation</code>.
*
* @param workLocation The place where this <code>Unit</code> shall
* be out to work.
* @exception IllegalStateException If the <code>workLocation</code> is
* on another {@link Tile} than this <code>Unit</code>.
*/
public void work(WorkLocation workLocation) {
if (workLocation.getTile() != getTile()) {
throw new IllegalStateException("Can only set a 'Unit' to a 'WorkLocation' that is on the same 'Tile'.");
}
if (armed) setArmed(false);
if (mounted) setMounted(false);
if (isPioneer()) setNumberOfTools(0);
setLocation(workLocation);
}
/**
* Sets the location of this Unit.
* @param newLocation The new Location of the Unit.
*/
public void setLocation(Location newLocation) {
if (location != null) {
location.remove(this);
}
location = newLocation;
if (location != null) {
location.add(this);
}
// Check for adjacent units owned by a player that our owner has not met before:
if (getGame().getMap() != null &&
location != null &&
location instanceof Tile && !isNaval()) {
Iterator tileIterator = getGame().getMap().getAdjacentIterator(getTile().getPosition());
while (tileIterator.hasNext()) {
Tile t = getGame().getMap().getTile((Position) tileIterator.next());
if (t == null) {
continue;
}
if (getOwner() == null) {
logger.warning("owner == null");
throw new NullPointerException();
}
if (t.getSettlement() != null &&
!t.getSettlement().getOwner().hasContacted(getOwner().getNation())) {
t.getSettlement().getOwner().setContacted(getOwner(), true);
getOwner().setContacted(t.getSettlement().getOwner(), true);
} else if (t.isLand()
&& t.getFirstUnit() != null &&
!t.getFirstUnit().getOwner().hasContacted(getOwner().getNation())) {
t.getFirstUnit().getOwner().setContacted(getOwner(), true);
getOwner().setContacted(t.getFirstUnit().getOwner(), true);
}
}
}
getOwner().setExplored(this);
}
/**
* Sets the <code>IndianSettlement</code> that owns this unit.
* @param indianSettlement The <code>IndianSettlement</code> that
* should now be owning this <code>Unit</code>.
*/
public void setIndianSettlement(IndianSettlement indianSettlement) {
if (this.indianSettlement != null) {
this.indianSettlement.removeOwnedUnit(this);
}
this.indianSettlement = indianSettlement;
if (indianSettlement != null) {
indianSettlement.addOwnedUnit(this);
}
}
/**
* Gets the <code>IndianSettlement</code> that owns this unit.
* @return The <code>IndianSettlement</code>.
*/
public IndianSettlement getIndianSettlement() {
return indianSettlement;
}
/**
* Gets the location of this Unit.
* @return The location of this Unit.
*/
public Location getLocation() {
return location;
}
/**
* Puts this <code>Unit</code> outside the {@link Colony} by moving
* it to the {@link Tile} below.
*/
public void putOutsideColony() {
if (getTile().getSettlement() == null) {
throw new IllegalStateException();
}
setLocation(getTile());
setMovesLeft(0);
if (getTile().getColony().getUnitCount() <= 0) {
getTile().getColony().dispose();
}
}
/**
* Checks if this unit can be armed in the current location.
* @return <code>true</code> if it can be armed at the current
* location.
*/
public boolean canBeArmed() {
return isArmed() || getGoodsDumpLocation() != null && getGoodsDumpLocation().getGoodsCount(Goods.MUSKETS) >= 50 ||
(location instanceof Europe || location instanceof Unit && ((Unit) location).getLocation() instanceof Europe) &&
getOwner().getGold() >= getGame().getMarket().getBidPrice(Goods.MUSKETS, 50);
}
/**
* Checks if this unit can be mounted in the current location.
* @return <code>true</code> if it can mount a horse at the current
* location.
*/
public boolean canBeMounted() {
return isMounted() || getGoodsDumpLocation() != null && getGoodsDumpLocation().getGoodsCount(Goods.HORSES) >= 50 ||
(location instanceof Europe || location instanceof Unit && ((Unit) location).getLocation() instanceof Europe)
&& getOwner().getGold() >= getGame().getMarket().getBidPrice(Goods.HORSES, 50);
}
/**
* Checks if this unit can be equiped with tools in the current location.
* @return <code>true</code> if it can be equipped with tools at the current
* location.
*/
public boolean canBeEquippedWithTools() {
return isPioneer() || getGoodsDumpLocation() != null && getGoodsDumpLocation().getGoodsCount(Goods.TOOLS) >= 20 ||
(location instanceof Europe || location instanceof Unit && ((Unit) location).getLocation() instanceof Europe)
&& getOwner().getGold() >= getGame().getMarket().getBidPrice(Goods.TOOLS, 20);
}
/**
* Checks if this unit can be dressed as a missionary at the current location.
* @return <code>true</code> if it can be dressed as a missionary at the current
* location.
*/
public boolean canBeDressedAsMissionary() {
return isMissionary() || ((location instanceof Europe || location instanceof Unit && ((Unit) location).getLocation()
instanceof Europe) || getTile() != null && getTile().getColony().getBuilding(Building.CHURCH).isBuilt());
}
/**
* Sets the armed attribute of this unit.
* @param b <i>true</i> if this unit should be armed and <i>false</i> otherwise.
* @param isCombat Whether this is a result of combat. That is; do not pay
* for the muskets.
*
*/
public void setArmed(boolean b, boolean isCombat) {
setMovesLeft(0);
if (isCombat) {
armed = b; // No questions asked.
return;
}
if (b) {
if (isPioneer()) {
setNumberOfTools(0);
}
if (isMissionary()) {
setMissionary(false);
}
}
if ((b) && (!armed)) {
if (getGoodsDumpLocation() != null) {
if (getGoodsDumpLocation().getGoodsCount(Goods.MUSKETS) < 50) {
return;
}
getGoodsDumpLocation().removeGoods(Goods.MUSKETS, 50);
armed = true;
} else if (isInEurope()) {
getGame().getMarket().buy(Goods.MUSKETS, 50, getOwner());
armed = true;
} else {
logger.warning("Attempting to arm a soldier outside of a colony or Europe!");
}
} else if ((!b) && (armed)) {
armed = false;
if (getGoodsDumpLocation() != null) {
getGoodsDumpLocation().addGoods(Goods.MUSKETS, 50);
} else if (isInEurope()) {
getGame().getMarket().sell(Goods.MUSKETS, 50, getOwner());
} else {
throw new IllegalStateException();
}
}
}
/**
* Sets the armed attribute of this unit.
* @param b <i>true</i> if this unit should be armed and <i>false</i> otherwise.
*/
public void setArmed(boolean b) {
setArmed(b, false);
}
/**
* Checks if this <code>Unit</code> is currently armed.
* @return <i>true</i> if this unit is armed and <i>false</i> otherwise.
*/
public boolean isArmed() {
return armed;
}
/**
* Sets the mounted attribute of this unit.
* @param b <i>true</i> if this unit should be mounted and <i>false</i> otherwise.
* @param isCombat Whether this is a result of combat.
*/
public void setMounted(boolean b, boolean isCombat) {
setMovesLeft(0);
if (isCombat) {
mounted = b; // No questions asked.
return;
}
if (b) {
if (isPioneer()) {
setNumberOfTools(0);
}
if (isMissionary()) {
setMissionary(false);
}
}
if ((b) && (!mounted)) {
if (getGoodsDumpLocation() != null) {
if (getGoodsDumpLocation().getGoodsCount(Goods.HORSES) < 50) {
throw new IllegalStateException();
}
getGoodsDumpLocation().removeGoods(Goods.HORSES, 50);
mounted = true;
} else if (isInEurope()) {
getGame().getMarket().buy(Goods.HORSES, 50, getOwner());
mounted = true;
} else {
logger.warning("Attempting to mount a colonist outside of a colony or Europe!");
}
} else if ((!b) && (mounted)) {
mounted = false;
if (getGoodsDumpLocation() != null) {
getGoodsDumpLocation().addGoods(Goods.HORSES, 50);
} else if (isInEurope()) {
getGame().getMarket().sell(Goods.HORSES, 50, getOwner());
}
}
}
/**
* Sets the mounted attribute of this unit.
* @param b <i>true</i> if this unit should be mounted and <i>false</i> otherwise.
*/
public void setMounted(boolean b) {
setMounted(b, false);
}
/**
* Checks if this <code>Unit</code> is currently mounted.
* @return <i>true</i> if this unit is mounted and <i>false</i> otherwise.
*/
public boolean isMounted() {
return mounted;
}
/**
* Checks if this <code>Unit</code> is located in Europe.
* That is; either directly or onboard a carrier which is in Europe.
* @return The result.
*/
public boolean isInEurope() {
return getTile() == null;
}
/**
* Sets the unit to be a missionary.
*
* @param b <i>true</i> if the unit should be a missionary and <i>false</i> otherwise.
*/
public void setMissionary(boolean b) {
setMovesLeft(0);
if (b) {
if (!isInEurope() && !getTile().getColony().getBuilding(Building.CHURCH).isBuilt()) {
throw new IllegalStateException("Can only dress as a missionary when the unit is located in Europe or a Colony with a church.");
} else {
if (isPioneer()) {
setNumberOfTools(0);
}
if (isArmed()) {
setArmed(false);
}
if (isMounted()) {
setMounted(false);
}
}
}
missionary = b;
}
/**
* Checks if this <code>Unit</code> is a missionary.
* @return 'true' if this colonist is dressed as a missionary, 'false' otherwise.
*/
public boolean isMissionary() {
return missionary;
}
/**
* Buys goods of a specified type and amount and adds it to this <code>Unit</code>.
* Can only be used when the <code>Unit</code> is a carrier and is located in
* {@link Europe}.
*
* @param type The type of goods to buy.
* @param amount The amount of goods to buy.
*/
public void buyGoods(int type, int amount) {
if (!isCarrier() || !(getLocation() instanceof Europe && getState() != TO_EUROPE && getState() != TO_AMERICA)) {
throw new IllegalStateException("Cannot buy goods when not a carrier or in Europe.");
}
try {
getGame().getMarket().buy(type, amount, getOwner());
goodsContainer.addGoods(type, amount);
} catch(IllegalStateException ise) {
this.addModelMessage(this, "notEnoughGold", null,
ModelMessage.DEFAULT);
}
}
/**
* Sets how many tools this unit is carrying.
* @param numberOfTools The number to set it to.
*/
public void setNumberOfTools(int numberOfTools) {
setMovesLeft(0);
if (numberOfTools >= 20) {
if (isMounted()) {
setMounted(false);
}
if (isArmed()) {
setArmed(false);
}
if (isMissionary()) {
setMissionary(false);
}
}
int changeAmount = 0;
/*if (numberOfTools > 100) {
logger.warning("Attempting to give a pioneer a number of greater than 100!");
}*/
if (numberOfTools > 100) {
numberOfTools = 100;
}
if ((numberOfTools % 20) != 0) {
//logger.warning("Attempting to give a pioneer a number of tools that is not a multiple of 20!");
numberOfTools -= (numberOfTools % 20);
}
changeAmount = numberOfTools - this.numberOfTools;
if (changeAmount > 0) {
if (getGoodsDumpLocation() != null) {
int actualAmount = getGoodsDumpLocation().getGoodsCount(Goods.TOOLS);
if (actualAmount < changeAmount) changeAmount = actualAmount;
if ((this.numberOfTools + changeAmount) % 20 > 0) changeAmount -= (this.numberOfTools + changeAmount)%20;
if (changeAmount <= 0) return;
getGoodsDumpLocation().removeGoods(Goods.TOOLS, changeAmount);
this.numberOfTools = this.numberOfTools + changeAmount;
} else if (isInEurope()) {
int maximumAmount = ((getOwner().getGold()) / (getGame().getMarket().costToBuy(Goods.TOOLS)));
if (maximumAmount < changeAmount) changeAmount = maximumAmount;
if ((this.numberOfTools + changeAmount) % 20 > 0) changeAmount -= (this.numberOfTools + changeAmount)%20;
if (changeAmount <= 0) return;
getGame().getMarket().buy(Goods.TOOLS, changeAmount, getOwner());
this.numberOfTools = this.numberOfTools + changeAmount;
} else {
logger.warning("Attempting to create a pioneer outside of a colony or Europe!");
}
} else if (changeAmount < 0) {
this.numberOfTools = this.numberOfTools + changeAmount;
if (getGoodsDumpLocation() != null) {
getGoodsDumpLocation().addGoods(Goods.TOOLS, -changeAmount);
} else if (isInEurope()) {
getGame().getMarket().sell(Goods.TOOLS, -changeAmount, getOwner());
}
}
}
/**
* Gets the number of tools this unit is carrying.
* @return The number of tools.
*/
public int getNumberOfTools() {
return numberOfTools;
}
/**
* Checks if this <code>Unit</code> is a pioneer.
* @return <i>true</i> if it is a pioneer and <i>false</i> otherwise.
*/
public boolean isPioneer() {
return 0 < getNumberOfTools();
}
/**
* Checks if this <code>Unit</code> is able to carry {@link Locatable}s.
*
* @return 'true' if this unit can carry other units, 'false'
* otherwise.
*/
public boolean isCarrier() {
return isCarrier(getType());
}
/**
* Checks if this <code>Unit</code> is able to carry {@link Locatable}s.
*
* @param type The type used when checking.
* @return 'true' if the unit can carry other units, 'false'
* otherwise.
*/
public static boolean isCarrier(int type) {
UnitType unitType = FreeCol.specification.unitType( type );
return unitType.hasAbility("naval") || unitType.hasAbility("carry-goods");
}
/**
* Gets the owner of this Unit.
* @return The owner of this Unit.
*/
public Player getOwner() {
return owner;
}
/**
* Sets the owner of this Unit.
* @param owner The new owner of this Unit.
*/
public void setOwner(Player owner) {
Player oldOwner = this.owner;
this.owner = owner;
oldOwner.invalidateCanSeeTiles();
getOwner().setExplored(this);
}
/**
* Gets the nation the unit is serving. One of {DUTCH , ENGLISH, FRENCH,
* SPANISH}.
*
* @return The nation the unit is serving.
*/
public int getNation() {
return owner.getNation();
}
/**
* Gets the type of the unit.
* @return The type of the unit.
*/
public int getType() {
return type;
}
/**
* Sets the type of the unit.
* @param type The new type of the unit.
*/
public void setType(int type) {
this.type = type;
unitType = FreeCol.specification.unitType(type);
}
/**
* Checks if this unit is of a given type.
*
* @param type The type.
* @return <code>true</code> if the unit was of the given type and <code>false</code> otherwise.
*/
public boolean isType(int type) {
return getType() == type;
}
/**
* Returns the amount of moves this Unit has left.
* @return The amount of moves this Unit has left. If the
* <code>unit.isUnderRepair()</code> then <code>0</code>
* is always returned.
*/
public int getMovesLeft() {
return ! isUnderRepair() ? movesLeft : 0;
}
/**
* Skips this unit by setting the moves left to 0.
*/
public void skip() {
movesLeft = 0;
}
/**
* Returns the name of a unit in a human readable format. The return
* value can be used when communicating with the user.
*
* @return The given unit type as a String
* @throws IllegalArgumentException
*/
public String getName() {
String name = "";
boolean addP = false;
if (isPioneer() && getType() != HARDY_PIONEER) {
name = Messages.message("model.unit.pioneer") + " (";
addP = true;
} else if (isArmed() && getType() != KINGS_REGULAR && getType() != COLONIAL_REGULAR && getType() != BRAVE && getType() != VETERAN_SOLDIER) {
if (!isMounted()) {
name = Messages.message("model.unit.soldier") + " (";
} else {
name = Messages.message("model.unit.dragoon") + " (";
}
addP = true;
} else if (isMounted() && getType() != SEASONED_SCOUT && getType() != BRAVE) {
name = Messages.message("model.unit.scout") + " (";
addP = true;
} else if (isMissionary() && getType() != JESUIT_MISSIONARY) {
name = Messages.message("model.unit.missionary") + " (";
addP = true;
}
if (!isArmed() && !isMounted() && (getType() == KINGS_REGULAR || getType() == COLONIAL_REGULAR || getType() == VETERAN_SOLDIER)) {
name = Messages.message("model.unit.unarmed") + " ";
}
if (getType() == BRAVE) {
name = getOwner().getNationAsString() + " ";
if (isArmed() && !isMounted()) {
name += Messages.message("model.unit.armed") + " ";
} else if (isMounted()) {
name += Messages.message("model.unit.mounted") + " ";
}
}
name += getName(getType());
if (isArmed() && isMounted()) {
if (getType() == KINGS_REGULAR) {
name = Messages.message("model.unit.kingsCavalry");
addP = false;
} else if (getType() == COLONIAL_REGULAR) {
name = Messages.message("model.unit.colonialCavalry");
addP = false;
} else if (getType() == VETERAN_SOLDIER) {
name = Messages.message("model.unit.veteranDragoon");
addP = false;
} else if (getType() == BRAVE) {
name = getOwner().getNationAsString() + " " + Messages.message("model.unit.indianDragoon");
addP = false;
}
}
if (addP) {
name += ")";
}
return name;
}
/**
* Returns the name of a unit type in a human readable format. The return
* value can be used when communicating with the user.
*
* @param someType The type of <code>Unit</code>.
* @return The given unit type as a String
* @throws IllegalArgumentException
*/
public static String getName(int someType) {
return FreeCol.specification.unitType(someType).name;
}
/**
* Returns the name of this unit in a human readable format. The return
* value can be used when communicating with the user.
*
* @return The type of this Unit as a String
* @throws FreeColException
*/
/*public String getName() throws FreeColException {
return Unit.getName(getType());
}*/
/**
* Gets the amount of moves this unit has at the beginning of each turn.
* @return The amount of moves this unit has at the beginning of each turn.
*/
public int getInitialMovesLeft() {
if (isNaval()) {
int fMagellan = 0;
if(owner.hasFather(FoundingFather.FERDINAND_MAGELLAN)) {
fMagellan += 3;
}
switch (getType()) {
case CARAVEL:
return 12+fMagellan;
case FRIGATE:
return 18+fMagellan;
case GALLEON:
return 18+fMagellan;
case MAN_O_WAR:
return 18+fMagellan;
case MERCHANTMAN:
return 15+fMagellan;
case PRIVATEER:
return 24+fMagellan;
default:
logger.warning("Unit.getInitialMovesLeft(): Unit has invalid naval type.");
return 9+fMagellan;
}
} else {
if (isMounted()) {
return 12;
} else if (isMissionary()) {
return 6;
} else if (getType() == WAGON_TRAIN) {
return 6;
} else {
return 3;
}
}
}
/**
* Gets the initial hitpoints for a given type of <code>Unit</code>.
* For now this method only returns <code>5</code> that is used to
* determine the number of rounds needed to repair a unit, but
* later it can be used for indicating the health of a unit as well.
*
* <br><br>
*
* Larger values would indicate a longer repair-time.
*
* @param type The type of a <code>Unit</code>.
* @return 6
*/
public static int getInitialHitpoints(int type) {
return 6;
}
/**
* Sets the hitpoints for this unit.
*
* @param hitpoints The hitpoints this unit has. This
* is currently only used for damaged ships, but
* might get an extended use later.
* @see #getInitialHitpoints
*/
public void setHitpoints(int hitpoints) {
this.hitpoints = hitpoints;
if (hitpoints >= getInitialHitpoints(getType()) && getState() == FORTIFY) {
setState(ACTIVE);
}
}
/**
* Returns the hitpoints.
* @return The hitpoints this unit has. This is currently only
* used for damaged ships, but might get an extended use
* later.
* @see #getInitialHitpoints
*/
public int getHitpoints() {
return hitpoints;
}
/**
* Checks if this unit is under repair.
* @return <i>true</i> if under repair and <i>false</i> otherwise.
*/
public boolean isUnderRepair() {
return (hitpoints < getInitialHitpoints(getType()));
}
/**
* Sends this <code>Unit</code> to the closest
* <code>Location</code> it can get repaired.
*/
public void sendToRepairLocation() {
Location l = getOwner().getRepairLocation(this);
setLocation(l);
setState(ACTIVE);
setMovesLeft(0);
}
/**
* Gets the x-coordinate of this Unit (on the map).
* @return The x-coordinate of this Unit (on the map).
*/
public int getX() {
return (getTile() != null) ? getTile().getX() : -1;
}
/**
* Gets the y-coordinate of this Unit (on the map).
* @return The y-coordinate of this Unit (on the map).
*/
public int getY() {
return (getTile() != null) ? getTile().getY() : -1;
}
/**
* Returns a String representation of this Unit.
* @return A String representation of this Unit.
*/
public String toString() {
return getName() + " " + getMovesAsString();
}
public String getMovesAsString() {
String moves = "";
if (getMovesLeft()%3 == 0 || getMovesLeft()/3 > 0) {
moves += Integer.toString(getMovesLeft()/3);
}
if (getMovesLeft()%3 != 0) {
if (getMovesLeft()/3 > 0) {
moves += " ";
}
moves += "(" + Integer.toString(getMovesLeft() - (getMovesLeft()/3) * 3) + "/3) ";
}
moves += "/" + Integer.toString(getInitialMovesLeft()/3);
return moves;
}
/**
* Checks if this <code>Unit</code> is naval.
* @return <i>true</i> if this Unit is a naval Unit and <i>false</i> otherwise.
*/
public boolean isNaval() {
return unitType.hasAbility( "naval" );
}
/**
* Gets the state of this <code>Unit</code>.
* @return The state of this <code>Unit</code>.
*/
public int getState() {
return state;
}
/**
* Sets a new state for this Unit.
* @param s The new state for this Unit. Should be one of
* {ACTIVE, FORTIFIED, ...}.
*/
public void setState(int s) {
if (!checkSetState(s)) {
throw new IllegalStateException("Illegal state: " + s);
}
switch (s) {
case ACTIVE:
workLeft = -1;
break;
case SENTRY:
workLeft = -1;
// Make sure we don't lose our movepoints if we're on a ship -sjm
if (location instanceof Tile) {
movesLeft = 0;
}
break;
case FORTIFY:
workLeft = -1;
movesLeft = 0;
break;
case BUILD_ROAD:
case PLOW:
switch(getTile().getType()) {
case Tile.DESERT:
case Tile.PLAINS:
case Tile.PRAIRIE:
case Tile.GRASSLANDS:
case Tile.SAVANNAH: workLeft = ((getTile().isForested()) ? 4 : 3); break;
case Tile.MARSH: workLeft = ((getTile().isForested()) ? 6 : 5); break;
case Tile.SWAMP: workLeft = 7; break;
case Tile.ARCTIC:
case Tile.TUNDRA: workLeft = 4; break;
default: workLeft = -1; break;
}
getTile().takeOwnership(getOwner());
if (s == BUILD_ROAD) workLeft /= 2;
movesLeft = 0;
case TO_EUROPE:
if (state == ACTIVE && !(location instanceof Europe)) {
workLeft = 3;
} else if ((state == TO_AMERICA) && (location instanceof Europe)) {
// I think '4' was also used in the original game.
workLeft = 4 - workLeft;
}
if (getOwner().hasFather(FoundingFather.FERDINAND_MAGELLAN)) {
workLeft = workLeft/2;
}
break;
case TO_AMERICA:
if ((state == ACTIVE) && (location instanceof Europe)) {
workLeft = 3;
} else if ((state == TO_EUROPE) && (location instanceof Europe)) {
// I think '4' was also used in the original game.
workLeft = 4 - workLeft;
}
if (getOwner().hasFather(FoundingFather.FERDINAND_MAGELLAN)) {
workLeft = workLeft/2;
}
break;
default:
workLeft = -1;
}
state = s;
}
/**
* Checks if this <code>Unit</code> can be moved to Europe.
* @return <code>true</code> if this unit is adjacent to
* a <code>Tile</code> of type {@link Tile#HIGH_SEAS}.
*/
public boolean canMoveToEurope() {
if (getLocation() instanceof Europe) {
return true;
}
if (!getOwner().canMoveToEurope()) {
return false;
}
Vector surroundingTiles = getGame().getMap().getSurroundingTiles(getTile(), 1);
if (surroundingTiles.size() != 8) {
return true;
} else {
for (int i=0; i<surroundingTiles.size(); i++) {
Tile tile = (Tile) surroundingTiles.get(i);
if (tile == null || tile.getType() == Tile.HIGH_SEAS) {
return true;
}
}
}
return false;
}
/**
* Moves this unit to europe.
* @exception IllegalStateException If the move is illegal.
*/
public void moveToEurope() {
// Check if this move is illegal or not:
if (!canMoveToEurope()) {
throw new IllegalStateException("It is not allowed to move units to europe from the tile where this unit is located.");
- } else {
+ } else if (getLocation() instanceof Tile) {
+ // Don't set entry location if location isn't Tile
setEntryLocation(getLocation());
}
setState(TO_EUROPE);
setLocation(getOwner().getEurope());
}
/**
* Moves this unit to america.
* @exception IllegalStateException If the move is illegal.
*/
public void moveToAmerica() {
if (!(getLocation() instanceof Europe)) {
throw new IllegalStateException("A unit can only be moved to america from europe.");
}
setState(TO_AMERICA);
}
/**
* Checks wether this unit can plow the <code>Tile</code>
* it is currently located on or not.
* @return The result.
*/
public boolean canPlow() {
return getTile().canBePlowed() && getNumberOfTools() >= 20;
}
/**
* Checks if a <code>Unit</code> can get the given state set.
*
* @param s The new state for this Unit. Should be one of
* {ACTIVE, FORTIFIED, ...}.
* @return 'true' if the Unit's state can be changed to the
* new value, 'false' otherwise.
*/
public boolean checkSetState(int s) {
if (movesLeft <= 0 && (s == PLOW || s == BUILD_ROAD || s == FORTIFY)) {
return false;
}
switch (s) {
case ACTIVE:
return true;
case PLOW:
return canPlow();
case BUILD_ROAD:
if (getTile().hasRoad()) {
return false;
}
return (getNumberOfTools() >= 20);
case IN_COLONY:
return !isNaval();
case FORTIFY:
return (getMovesLeft() > 0);
case SENTRY:
return true;
case TO_EUROPE:
if (!isNaval()) {
return false;
}
return ((location instanceof Europe) && (getState() == TO_AMERICA))
|| (getEntryLocation() == getLocation());
case TO_AMERICA:
return (location instanceof Europe && isNaval());
default:
logger.warning("Invalid unit state: " + s);
return false;
}
}
/**
* Check if this unit can build a colony on the tile where it is located.
*
* @return <code>true</code> if this unit can build a colony on the tile where
* it is located and <code>false</code> otherwise.
*/
public boolean canBuildColony() {
return getOwner().canBuildColonies()
&& isColonist()
&& getMovesLeft() > 0
&& getTile() != null
&& getTile().isColonizeable();
}
/**
* Makes this unit build the specified colony.
* @param colony The colony this unit shall build.
*/
public void buildColony(Colony colony) {
if (!canBuildColony()) {
throw new IllegalStateException();
}
getTile().setSettlement(colony);
setLocation(colony);
if (isArmed()) setArmed(false);
if (isMounted()) setMounted(false);
if (isPioneer()) setNumberOfTools(0);
}
/**
* Returns the Tile where this Unit is located. Or null if
* its location is Europe.
*
* @return The Tile where this Unit is located. Or null if
* its location is Europe.
*/
public Tile getTile() {
return (location != null) ? location.getTile() : null;
}
/**
* Returns the amount of space left on this Unit.
* @return The amount of units/goods than can be moved onto this Unit.
*/
public int getSpaceLeft() {
int space = getInitialSpaceLeft() - getGoodsCount();
Iterator unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = (Unit) unitIterator.next();
space -= u.getTakeSpace();
}
return space;
}
/**
* Returns the amount of goods that is carried by this unit.
*
* @return The amount of goods carried by this <code>Unit</code>.
* This value might different from the one returned by
* {@link #getGoodsCount()} when the model is
* {@link Game#getViewOwner() owned by a client} and cargo
* hiding has been enabled.
*/
public int getVisibleGoodsCount() {
if (visibleGoodsCount >= 0) {
return visibleGoodsCount;
} else {
return getGoodsCount();
}
}
public int getGoodsCount() {
return goodsContainer.getGoodsCount();
}
/**
* Returns the amount of units/cargo that this unit can carry.
* @return The amount of units/cargo that this unit can carry.
*/
public int getInitialSpaceLeft() {
switch (type) {
case CARAVEL:
return 2;
case FRIGATE:
// I've got an official reference sheet from Colonization (came with the game)
// that says that the cargo space for a frigate is 2 but I'm almost 100% sure
// that it was 4 in the Colonization version that I used to play.
return 4;
case GALLEON:
return 6;
case MAN_O_WAR:
return 6;
case MERCHANTMAN:
return 4;
case PRIVATEER:
return 2;
case WAGON_TRAIN:
return 2;
case BRAVE:
return 1;
default:
return 0;
}
}
/**
* Move the given unit to the front of this carrier (make sure
* it'll be the first unit in this unit's unit list).
*
* @param u The unit to move to the front.
*/
public void moveToFront(Unit u) {
//TODO: Implement this feature.
/*if (isCarrier() && removeUnit(u)) {
units.add(0, u);
}*/
}
/**
* Get the number of turns of work left.
* @return Work left
*/
public int getWorkLeft() {
return workLeft;
}
/**
* This method does all the work.
*/
public void doAssignedWork() {
if (workLeft > 0) {
workLeft--;
// Shorter travel time to America for the REF:
if (state == TO_AMERICA && getOwner().isREF()) {
workLeft = 0;
}
if (workLeft == 0) {
workLeft = -1;
int state = getState();
switch (state) {
case TO_EUROPE:
addModelMessage(getOwner().getEurope(), "model.unit.arriveInEurope", null,
ModelMessage.DEFAULT);
if (getType() == GALLEON) {
Iterator iter = getUnitIterator();
Unit u = null;
while (iter.hasNext() && (u = (Unit) iter.next()) != null && u.getType() != TREASURE_TRAIN);
if (u != null && u.getType() == TREASURE_TRAIN) {
u.cashInTreasureTrain();
}
}
break;
case TO_AMERICA:
getGame().getModelController().setToVacantEntryLocation(this);
break;
case BUILD_ROAD:
getTile().setRoad(true);
expendTools(20);
break;
case PLOW:
if (getTile().isForested()) {
// Give Lumber to adjacent colony
// Yes, the amount of lumber may exceed 100 units,
// but this was also true for the original game, IIRC.
int lumberAmount = getTile().potential(Goods.LUMBER) * 15 + 10;
if (getTile().getColony() != null && getTile().getColony().getOwner().equals(getOwner())) {
getTile().getColony().addGoods(Goods.LUMBER, lumberAmount);
} else {
Vector surroundingTiles = getTile().getMap().getSurroundingTiles(getTile(), 1);
Vector adjacentColonies = new Vector();
for (int i=0; i<surroundingTiles.size(); i++) {
Tile t = (Tile) surroundingTiles.get(i);
if (t.getColony() != null && t.getColony().getOwner().equals(getOwner())) {
adjacentColonies.add(t.getColony());
}
}
if (adjacentColonies.size() > 0) {
int lumberPerCity = (lumberAmount / adjacentColonies.size());
for (int i=0; i<adjacentColonies.size(); i++) {
Colony c = (Colony) adjacentColonies.get(i);
// Make sure the lumber lost is being added again to the first adjacent colony:
if (i==0) {
c.addGoods(Goods.LUMBER, lumberPerCity + (lumberAmount % adjacentColonies.size()));
} else {
c.addGoods(Goods.LUMBER, lumberPerCity);
}
}
}
}
getTile().setForested(false);
} else {
getTile().setPlowed(true);
}
expendTools(20);
break;
default:
logger.warning("Unknown work completed. State: " + state);
}
setState(ACTIVE);
}
}
}
/**
* Reduces the number of tools and produces a warning if all tools
* are used up.
*
* @param amount The number of tools to remove.
*/
private void expendTools(int amount) {
numberOfTools -= amount;
if (numberOfTools == 0) {
if (getType() == HARDY_PIONEER) {
addModelMessage(this, "model.unit.noMoreToolsPioneer", null,
ModelMessage.WARNING);
} else {
addModelMessage(this, "model.unit.noMoreTools",
new String [][] {{"%name%", getName()}},
ModelMessage.WARNING);
}
}
}
/**
* Sets the <code>Location</code> in which this unit will be put
* when returning from {@link Europe}.
*
* @param entryLocation The <code>Location</code>.
* @see #getEntryLocation
*/
public void setEntryLocation(Location entryLocation) {
this.entryLocation = entryLocation;
}
/**
* Gets the <code>Location</code> in which this unit will be put
* when returning from {@link Europe}. If this <code>Unit</code>
* has not not been outside europe before, it will return the default
* value from the {@link Player} owning this <code>Unit</code>.
*
* @return The <code>Location</code>.
* @see Player#getEntryLocation
* @see #getVacantEntryLocation
*/
public Location getEntryLocation() {
return (entryLocation != null) ? entryLocation : getOwner().getEntryLocation();
}
/**
* Gets the <code>Location</code> in which this unit will be put
* when returning from {@link Europe}. If this <code>Unit</code>
* has not not been outside europe before, it will return the default
* value from the {@link Player} owning this <code>Unit</code>.
* If the tile is occupied by a enemy unit, then a nearby tile is choosen.
*
* <br><br>
* <i>WARNING:</i> Only the server has the information to determine which
* <code>Tile</code> is occupied. Use
* {@link ModelController#setToVacantEntryLocation} instead.
*
* @return The <code>Location</code>.
* @see #getEntryLocation
*/
public Location getVacantEntryLocation() {
Tile l = (Tile) getEntryLocation();
if (l.getFirstUnit() != null && l.getFirstUnit().getOwner() != getOwner()) {
int radius = 1;
while (true) {
Iterator i = getGame().getMap().getCircleIterator(l.getPosition(), false, radius);
while (i.hasNext()) {
Tile l2 = getGame().getMap().getTile((Position) i.next());
if (l2.getFirstUnit() == null || l2.getFirstUnit().getOwner() == getOwner()) {
return l2;
}
}
radius++;
}
}
return l;
}
/**
* Checks if the given unit can be recruited in <code>Europe</code>.
* @param type The type of <code>Unit</code> to be tested.
* @return <code>true</code> if the given type is the type of a
* recruitable unit and <code>false</code> otherwise.
*/
public static boolean isRecruitable(int type) {
return FreeCol.specification.unitType(type).hasAbility( "recruitable" );
}
/**
* Returns the price of this unit in Europe.
*
* @return The price of this unit when trained in Europe. '-1' is returned in case the unit cannot be bought.
*/
public int getPrice() {
if ( ARTILLERY == type ) {
return getOwner().getEurope().getArtilleryPrice();
}
return getPrice(getType());
}
/**
* Returns the price of a trained unit in Europe.
*
* @param type The type of unit of which you need the price.
* @return The price of a trained unit in Europe. '-1' is returned in case the unit cannot be bought.
*/
public static int getPrice(int type) {
if ( ARTILLERY == type ) {
throw new IllegalStateException();
}
UnitType unitType = FreeCol.specification.unitType( type );
if ( unitType.hasPrice() ) {
return unitType.price;
}
return -1;
}
/**
* Returns the current defensive power of this unit. The tile on which this
* unit is located will be taken into account.
* @param attacker The attacker of this unit.
* @return The current defensive power of this unit.
*/
public int getDefensePower(Unit attacker) {
int base_power = unitType.defence;
if (getOwner().hasFather(FoundingFather.PAUL_REVERE) && getTile() != null && getTile().getColony() != null) {
if (isColonist() && base_power == 1 && (getLocation() instanceof ColonyTile || getLocation() instanceof Building)) {
base_power = 2;
}
}
if (isArmed()) {
base_power++;
}
if (isMounted()) {
if (!isArmed() && getType() != BRAVE) {
base_power = 1;
} else {
base_power++;
}
}
int modified_power = base_power;
//TODO: <1 move point movement penalty
if (isNaval()) {
if (getGoodsCount() > 0) {
modified_power -= ((base_power * getGoodsCount()) / 8); // -12.5% penalty for every unit of cargo.
}
return modified_power;
}
if (getState() == FORTIFY) {
modified_power += (base_power / 2); // 50% fortify bonus
}
if ((getTile() != null) && (getTile().getSettlement() != null) && (getTile().getSettlement() instanceof Colony) ) {
Colony colony = ((Colony)getTile().getSettlement());
switch(colony.getBuilding(Building.STOCKADE).getLevel()) {
case Building.NOT_BUILT:
default:
modified_power += (base_power / 2); // 50% colony bonus
break;
case Building.HOUSE:
modified_power += base_power; // 100% stockade bonus
break;
case Building.SHOP:
modified_power += ((base_power * 3) / 2); // 150% fort bonus
break;
case Building.FACTORY:
modified_power += (base_power * 2); // 200% fortress bonus
break;
}
} else if (!(((attacker.getType() != BRAVE) && (getType() == KINGS_REGULAR)) || // TODO: check for REF artillery pieces
((attacker.getType() == BRAVE) && (getType() != KINGS_REGULAR))) &&
(getTile() != null)) {
// Terrain defensive bonus.
modified_power += ((base_power * getTile().defenseBonus()) / 100);
}
// Indian settlement defensive bonus.
if (getTile() != null && getTile().getSettlement() != null && getTile().getSettlement() instanceof IndianSettlement) {
modified_power += (base_power / 2); // 50% bonus
}
if ((getType() == ARTILLERY) || (getType() == DAMAGED_ARTILLERY)) {
if ((attacker.getType() == BRAVE) && (getTile().getSettlement() != null)) {
modified_power += base_power; // 100% defense bonus against an Indian raid
}
if (((getTile().getSettlement()) == null) && (getState() != FORTIFY)) {
modified_power -= ((base_power * 3) / 4); // -75% Artillery in the Open penalty
}
}
return modified_power;
}
/**
* Checks if this is an offensive unit.
*
* @return <code>true</code> if this is an offensive unit
* meaning it can attack other units.
*/
public boolean isOffensiveUnit() {
// TODO: Make this look prettier ;-)
return (getOffensePower(this) > 0);
}
/**
* Checks if this is an defensive unit.
* That is: a unit which can be used to defend a <code>Settlement</code>.
* @return <code>true</code> if this is a defensive unit
* meaning it can be used to defend a <code>Colony</code>.
* This would normally mean that a defensive unit also will
* be {@link #isOffensiveUnit offensive}.
*/
public boolean isDefensiveUnit() {
return isOffensiveUnit() && !isNaval();
}
/**
* Returns the current offensive power of this unit.
* @param target The target of the attack.
* @return The current offensive power of this unit.
*/
public int getOffensePower(Unit target) {
int base_power = unitType.offence;
if (isArmed()) {
if (base_power == 0) {
base_power = 2;
} else {
base_power++;
}
}
if (isMounted()) {
if ((!isArmed()) && (getType() != BRAVE)) {
base_power = 1;
} else {
base_power++;
}
}
int modified_power = (base_power * 3) / 2; // 50% attack bonus
//TODO: <1 move point movement penalty
if (isNaval()) {
if (getGoodsCount() > 0) {
modified_power -= ((base_power * getGoodsCount()) / 8); // -12.5% penalty for every unit of cargo.
}
if (getType() == PRIVATEER && getOwner().hasFather(FoundingFather.FRANCIS_DRAKE)) {
modified_power += (base_power * 3) / 2;
}
return modified_power;
}
if ((((getType() != BRAVE) && (target.getType() == KINGS_REGULAR)) || // TODO: check for REF artillery pieces
((getType() == BRAVE) && (target.getType() != KINGS_REGULAR))) &&
(target.getTile() != null) &&
(target.getTile().getSettlement() == null)) {
// Ambush bonus.
modified_power += ((base_power * target.getTile().defenseBonus()) / 100);
}
if (((getType() == KINGS_REGULAR)) && // TODO: check for REF artillery pieces
(target.getTile() != null) &&
(target.getTile().getSettlement() == null))
{
modified_power += (base_power / 2); // REF bombardment bonus
}
if ((getType() == ARTILLERY) || (getType() == DAMAGED_ARTILLERY)) {
if ((target.getTile() != null) && (target.getTile().getSettlement()) == null) {
modified_power -= ((base_power * 3) / 4); // -75% Artillery in the Open penalty
}
}
return modified_power;
}
/**
* Attack a unit with the given outcome.
*
* @param defender The <code>Unit</code> defending against attack.
* @param result The result of the attack.
* @param plunderGold The amount of gold to plunder in case of
* a successful attack on a <code>Settlement</code>.
*/
public void attack(Unit defender, int result, int plunderGold) {
if (defender == null) {
throw new NullPointerException();
}
if (getOwner().getStance(defender.getOwner()) == Player.ALLIANCE) {
throw new IllegalStateException("Cannot attack allied players.");
}
// make sure we are at war
if (getOwner().isEuropean() && defender.getOwner().isEuropean()) {
getOwner().setStance(defender.getOwner(), Player.WAR);
}
if (getType() == PRIVATEER) {
defender.getOwner().setAttackedByPrivateers();
}
// Wake up if you're attacking something.
// Before, a unit could stay fortified during execution of an
// attack. - sjm
state = ACTIVE;
movesLeft = 0;
Tile newTile = defender.getTile();
adjustTension(defender);
switch (result) {
case ATTACK_EVADES:
if (isNaval()) {
addModelMessage(this, "model.unit.shipEvaded",
new String [][] {{"%ship%", getName()}},
ModelMessage.DEFAULT);
} else {
logger.warning("Non-naval unit evades!");
}
break;
case ATTACK_LOSS:
if (isNaval()) {
shipDamaged();
} else {
demote(defender, false);
if (defender.getOwner().hasFather(FoundingFather.GEORGE_WASHINGTON)) {
defender.promote();
}
}
break;
case ATTACK_GREAT_LOSS:
if (isNaval()) {
shipSunk();
} else {
demote(defender, true);
defender.promote();
}
break;
case ATTACK_DONE_SETTLEMENT:
Settlement settlement = newTile.getSettlement();
if (settlement instanceof IndianSettlement) {
defender.dispose();
destroySettlement((IndianSettlement) settlement);
} else if (settlement instanceof Colony) {
captureColony((Colony) settlement, plunderGold);
} else {
throw new IllegalStateException("Unknown type of settlement.");
}
break;
case ATTACK_WIN:
if (isNaval()) {
captureGoods(defender);
defender.shipDamaged();
} else {
if (getOwner().hasFather(FoundingFather.GEORGE_WASHINGTON)) {
promote();
}
defender.demote(this, false);
}
break;
case ATTACK_GREAT_WIN:
if (isNaval()) {
captureGoods(defender);
defender.shipSunk();
} else {
promote();
defender.demote(this, true);
}
break;
default:
logger.warning("Illegal result of attack!");
throw new IllegalArgumentException("Illegal result of attack!");
}
}
/**
* Sets the damage to this ship and sends it to its repair
* location.
*/
public void shipDamaged() {
String nation = owner.getNationAsString();
Location repairLocation = getOwner().getRepairLocation(this);
String repairLocationName = Messages.message("menuBar.view.europe");
if (repairLocation instanceof Colony) {
repairLocationName = ((Colony) repairLocation).getName();
}
addModelMessage(this, "model.unit.shipDamaged",
new String [][] {{"%ship%", getName()},
{"%repairLocation%", repairLocationName},
{"%nation%", nation}},
ModelMessage.UNIT_DEMOTED);
setHitpoints(1);
getUnitContainer().disposeAllUnits();
goodsContainer.removeAbove(0);
sendToRepairLocation();
}
/**
* Sinks this ship.
*/
private void shipSunk() {
String nation = owner.getNationAsString();
addModelMessage(this, "model.unit.shipSunk",
new String [][] {{"%ship%", getName()},
{"%nation%", nation}},
ModelMessage.UNIT_DEMOTED);
dispose();
}
/**
* Demotes this unit. A unit that can not be further demoted is
* destroyed. The enemy may plunder horses and muskets.
*
* @param enemyUnit The unit we are fighting against.
* @param greatDemote <code>true</code> indicates that
* muskets/horses should be taken by the <code>enemyUnit</code>.
*/
public void demote(Unit enemyUnit, boolean greatDemote) {
String oldName = getName();
String messageID = "model.unit.unitDemoted";
String nation = owner.getNationAsString();
int type = ModelMessage.UNIT_DEMOTED;
if (getType() == ARTILLERY) {
messageID = "model.unit.artilleryDamaged";
setType(DAMAGED_ARTILLERY);
} else if (getType() == DAMAGED_ARTILLERY
|| getType() == KINGS_REGULAR) {
messageID = "model.unit.unitDestroyed";
type = ModelMessage.UNIT_LOST;
dispose();
} else if (getType() == BRAVE) {
messageID = "model.unit.unitSlaughtered";
type = ModelMessage.UNIT_LOST;
dispose();
} else if (isMounted()) {
if (isArmed()) {
// dragoon
setMounted(false, true);
if (enemyUnit.getType() == BRAVE && greatDemote) {
addModelMessage(this, "model.unit.braveMounted",
new String [][] {{"%nation%", enemyUnit.getOwner().getNationAsString()}},
ModelMessage.FOREIGN_DIPLOMACY);
enemyUnit.setMounted(true, true);
}
} else {
// scout
messageID = "model.unit.unitSlaughtered";
type = ModelMessage.UNIT_LOST;
dispose();
}
} else if (isArmed()) {
// soldier
setArmed(false, true);
if (enemyUnit.getType() == BRAVE && greatDemote) {
addModelMessage(this, "model.unit.braveArmed",
new String [][] {{"%nation%", enemyUnit.getOwner().getNationAsString()}},
ModelMessage.FOREIGN_DIPLOMACY);
enemyUnit.setArmed(true, true);
}
} else {
// civilians
if (enemyUnit.getOwner().isEuropean()) {
messageID = "model.unit.unitCaptured";
type = ModelMessage.UNIT_LOST;
setHitpoints(getInitialHitpoints(enemyUnit.getType()));
setLocation(enemyUnit.getTile());
setOwner(enemyUnit.getOwner());
} else {
messageID = "model.unit.unitSlaughtered";
type = ModelMessage.UNIT_LOST;
dispose();
}
}
String newName = getName();
addModelMessage(this, messageID,
new String [][] {{"%oldName%", oldName},
{"%newName%", newName},
{"%nation%", nation}},
type);
}
/**
* Promotes this unit.
*/
public void promote() {
String oldName = getName();
String nation = owner.getNationAsString();
if (getType() == PETTY_CRIMINAL) {
setType(INDENTURED_SERVANT);
} else if (getType() == INDENTURED_SERVANT) {
setType(FREE_COLONIST);
} else if (getType() == FREE_COLONIST) {
setType(VETERAN_SOLDIER);
} else if (getType() == VETERAN_SOLDIER && getOwner().getRebellionState() >= Player.REBELLION_IN_WAR) {
setType(COLONIAL_REGULAR);
}
String newName = getName();
if (!newName.equals(oldName)) {
addModelMessage(this, "model.unit.unitImproved",
new String[][] {{"%oldName%", oldName},
{"%newName%", getName()},
{"%nation%", nation}},
ModelMessage.UNIT_IMPROVED);
}
}
/**
* Adjusts the tension and alarm levels of the enemy unit's owner
* according to the type of attack.
*
* @param enemyUnit The unit we are attacking.
*/
public void adjustTension(Unit enemyUnit) {
Player myPlayer = getOwner();
Player enemy = enemyUnit.getOwner();
myPlayer.modifyTension(enemy, -Tension.TENSION_ADD_MINOR);
if (getIndianSettlement() != null) {
getIndianSettlement().modifyAlarm(enemy, -Tension.TENSION_ADD_UNIT_DESTROYED/2);
}
// Increases the enemy's tension levels:
if (enemy.isAI()) {
Settlement settlement = enemyUnit.getTile().getSettlement();
IndianSettlement homeTown = enemyUnit.getIndianSettlement();
if (settlement != null) {
// we are attacking a settlement
if (settlement instanceof IndianSettlement &&
((IndianSettlement) settlement).isCapital()) {
enemy.modifyTension(myPlayer, Tension.TENSION_ADD_MAJOR);
} else {
enemy.modifyTension(myPlayer, Tension.TENSION_ADD_NORMAL);
}
if (homeTown != null) {
homeTown.modifyAlarm(myPlayer, Tension.TENSION_ADD_SETTLEMENT_ATTACKED);
}
} else {
// we are attacking an enemy unit in the open
enemy.modifyTension(myPlayer, Tension.TENSION_ADD_MINOR);
if (homeTown != null) {
homeTown.modifyAlarm(myPlayer, Tension.TENSION_ADD_UNIT_DESTROYED);
}
}
}
}
/**
* Returns true if this unit is a ship that can capture enemy
* goods. That is, a privateer, frigate or man-o-war.
* @return <code>true</code> if this <code>Unit</code> is
* capable of capturing goods.
*/
public boolean canCaptureGoods() {
return unitType.hasAbility( "capture-goods" );
}
/**
* Captures the goods on board of the enemy unit.
*
* @param enemyUnit The unit we are attacking.
*/
public void captureGoods(Unit enemyUnit) {
if (!canCaptureGoods()) {
return;
}
// can capture goods; regardless attacking/defending
Iterator iter = enemyUnit.getGoodsIterator();
while(iter.hasNext() && getSpaceLeft() > 0) {
// TODO: show CaptureGoodsDialog if there's not enough
// room for everything.
Goods g = ((Goods)iter.next());
// MESSY, but will mess up the iterator if we do this
// besides, this gets cleared out later
//enemy.getGoodsContainer().removeGoods(g);
getGoodsContainer().addGoods(g);
}
}
/**
* Destroys an Indian settlement.
*
* @param settlement The Indian settlement to destroy.
*/
public void destroySettlement(IndianSettlement settlement) {
Player enemy = settlement.getOwner();
boolean wasCapital = settlement.isCapital();
Tile newTile = settlement.getTile();
ModelController modelController = getGame().getModelController();
settlement.dispose();
enemy.modifyTension(getOwner(), Tension.TENSION_ADD_MAJOR);
int randomTreasure = modelController.getRandom(getID() + "indianTreasureRandom" +
getID(), 11);
Unit tTrain = modelController.createUnit(getID() + "indianTreasure" + getID(),
newTile, getOwner(), Unit.TREASURE_TRAIN);
// Larger treasure if Hernan Cortes is present in the congress:
int bonus = (getOwner().hasFather(FoundingFather.HERNAN_CORTES)) ? 2 : 1;
// The number of Indian converts
int converts = (4 - getOwner().getDifficulty());
// Incan and Aztecs give more gold and converts
if (enemy.getNation() == Player.INCA ||
enemy.getNation() == Player.AZTEC) {
tTrain.setTreasureAmount(randomTreasure * 500 * bonus + 10000);
converts += 2;
} else {
tTrain.setTreasureAmount(randomTreasure * 50 * bonus + 300);
}
// capitals give more gold
if (wasCapital) {
tTrain.setTreasureAmount((tTrain.getTreasureAmount()*3)/2);
}
if (!getOwner().hasFather(FoundingFather.JUAN_DE_SEPULVEDA)) {
converts = converts/2;
}
for (int i = 0; i < converts; i++) {
Unit newUnit = modelController.createUnit(getID() + "indianConvert" + i,
newTile, getOwner(), Unit.INDIAN_CONVERT);
}
addModelMessage(this, "model.unit.indianTreasure",
new String[][] {{"%indian%", enemy.getNationAsString()},
{"%amount%", Integer.toString(tTrain.getTreasureAmount())}},
ModelMessage.DEFAULT);
setLocation(newTile);
}
/**
* Captures an enemy colony and plunders gold.
*
* @param colony The enemy colony to capture.
* @param plunderGold The amount of gold to plunder.
*/
public void captureColony(Colony colony, int plunderGold) {
Player enemy = colony.getOwner();
Player myPlayer = getOwner();
enemy.modifyTension(getOwner(), Tension.TENSION_ADD_MAJOR);
if (myPlayer.isEuropean()) {
addModelMessage(enemy, "model.unit.colonyCapturedBy",
new String[][] {{"%colony%", colony.getName()},
{"%amount%", Integer.toString(plunderGold)},
{"%player%", myPlayer.getNationAsString()}},
ModelMessage.DEFAULT);
colony.damageAllShips();
myPlayer.modifyGold(plunderGold);
enemy.modifyGold(-plunderGold);
colony.setOwner(myPlayer); // This also changes over all of the units...
addModelMessage(colony, "model.unit.colonyCaptured",
new String[][] {{"%colony%", colony.getName()},
{"%amount%", Integer.toString(plunderGold)}},
ModelMessage.DEFAULT);
// Demote all soldiers and clear all orders:
Iterator it = colony.getTile().getUnitIterator();
while (it.hasNext()) {
Unit u = (Unit) it.next();
if (u.getType() == Unit.VETERAN_SOLDIER
|| u.getType() == Unit.KINGS_REGULAR
|| u.getType() == Unit.COLONIAL_REGULAR) {
u.setType(Unit.FREE_COLONIST);
}
u.setState(Unit.ACTIVE);
}
setLocation(colony.getTile());
} else { // Indian:
if (colony.getUnitCount() <= 1) {
myPlayer.modifyGold(plunderGold);
enemy.modifyGold(-plunderGold);
addModelMessage(enemy, "model.unit.colonyBurning",
new String[][] {{"%colony%", colony.getName()},
{"%amount%", Integer.toString(plunderGold)}},
ModelMessage.DEFAULT);
colony.damageAllShips();
colony.dispose();
} else {
Unit victim = colony.getRandomUnit();
if (victim == null) {
return;
}
addModelMessage(enemy, "model.unit.colonistSlaughtered",
new String[][] {{"%colony%", colony.getName()},
{"%unit%", victim.getName()}},
ModelMessage.UNIT_LOST);
victim.dispose();
}
}
}
/**
* Gets the Colony this unit is in.
* @return The Colony it's in, or null if it is not in a Colony
*/
public Colony getColony() {
return getTile().getColony();
}
/**
* Clear the speciality of a <code>Unit</code>. That is, makes it a
* <code>FREE_COLONIST</code>
*/
public void clearSpeciality() {
if (isColonist() && getType() != INDIAN_CONVERT && getType() != INDENTURED_SERVANT && getType() != PETTY_CRIMINAL) {
setType(FREE_COLONIST);
}
}
/**
* Gets the Colony the goods of this unit would go to if it were to de-equip.
* @return The Colony the goods would go to, or null if there is no appropriate Colony
*/
public Colony getGoodsDumpLocation() {
if ((location instanceof Colony)) {
return ((Colony)location);
} else if (location instanceof Building) {
return (((Building)location).getColony());
} else if (location instanceof ColonyTile) {
return (((ColonyTile)location).getColony());
} else if ((location instanceof Tile) && (((Tile)location).getSettlement() != null) && (((Tile)location).getSettlement() instanceof Colony)) {
return (((Colony)(((Tile)location).getSettlement())));
} else if (location instanceof Unit) {
if ((((Unit)location).getLocation()) instanceof Colony) {
return ((Colony)(((Unit)location).getLocation()));
} else if (((((Unit)location).getLocation()) instanceof Tile) && (((Tile)(((Unit)location).getLocation())).getSettlement() != null) && (((Tile)(((Unit)location).getLocation())).getSettlement() instanceof Colony)) {
return ((Colony)(((Tile)(((Unit)location).getLocation())).getSettlement()));
}
}
return null;
}
/**
* Given a type of goods to produce in a building, returns the unit's potential to do so.
* @param goods The type of goods to be produced.
* @return The potential amount of goods to be manufactured.
*/
public int getProducedAmount(int goods) {
int base = 0;
base = getProductionUsing(getType(), goods, base);
if (base == 0) {
return 0;
}
//base += getTile().getColony().getProductionBonus();
return Math.max(base, 1);
}
/**
* Given a type of goods to produce in the field and a tile, returns the unit's potential to produce goods.
* @param goods The type of goods to be produced.
* @param tile The tile which is being worked.
* @return The potential amount of goods to be farmed.
*/
public int getFarmedPotential(int goods, Tile tile) {
if (tile == null) {
throw new NullPointerException();
}
int base = tile.potential(goods);
base = getProductionUsing(getType(), goods, base, tile);
if (getLocation() instanceof ColonyTile && !((ColonyTile) getLocation()).getWorkTile().isLand()
&& !((ColonyTile) getLocation()).getColony().getBuilding(Building.DOCK).isBuilt()) {
base = 0;
}
if (base == 0) {
return 0;
}
if (goods == Goods.FURS && getOwner().hasFather(FoundingFather.HENRY_HUDSON)) {
base *= 2;
}
if (getTile() != null && getTile().getColony() != null) {
base += getTile().getColony().getProductionBonus();
}
return Math.max(base, 1);
}
/**
* Applies unit-type specific bonuses to a goods production in a
* <code>Building</code>.
*
* @param unitType The {@link #getType type} of the unit.
* @param goodsType The type of goods that is being produced.
* @param base The production not including the unit-type specific bonuses.
* @return The production.
*/
public static int getProductionUsing(int unitType, int goodsType, int base) {
if (Goods.isFarmedGoods(goodsType)) {
throw new IllegalArgumentException("\"goodsType\" is not produced in buildings.");
}
switch (unitType) {
case MASTER_DISTILLER:
if (goodsType == Goods.RUM) {
base = 6;
} else {
base = 3;
}
break;
case MASTER_WEAVER:
if (goodsType == Goods.CLOTH) {
base = 6;
} else {
base = 3;
}
break;
case MASTER_TOBACCONIST:
if (goodsType == Goods.CIGARS) {
base = 6;
} else {
base = 3;
}
break;
case MASTER_FUR_TRADER:
if (goodsType == Goods.COATS) {
base = 6;
} else {
base = 3;
}
break;
case MASTER_BLACKSMITH:
if (goodsType == Goods.TOOLS) {
base = 6;
} else {
base = 3;
}
break;
case MASTER_GUNSMITH:
if (goodsType == Goods.MUSKETS) {
base = 6;
} else {
base = 3;
}
break;
case ELDER_STATESMAN:
if (goodsType == Goods.BELLS) {
base = 6;
} else {
base = 3;
}
break;
case FIREBRAND_PREACHER:
if (goodsType == Goods.CROSSES) {
base = 6;
} else {
base = 3;
}
break;
case MASTER_CARPENTER:
if (goodsType == Goods.HAMMERS) {
base = 6;
} else {
base = 3;
}
break;
case FREE_COLONIST:
base = 3;
break;
case INDENTURED_SERVANT:
base = 2;
break;
case PETTY_CRIMINAL:
case INDIAN_CONVERT:
base = 1;
break;
default: // Beats me who or what is working here, but he doesn't get a bonus.
base = 3;
}
return base;
}
/**
* Applies unit-type specific bonuses to a goods production on a
* <code>Tile</code>.
*
* @param unitType The {@link #getType type} of the unit.
* @param goodsType The type of goods that is being produced.
* @param base The production not including the unit-type specific bonuses.
* @param tile The <code>Tile</code> in which the given type of goods is being produced.
* @return The production.
*/
public static int getProductionUsing(int unitType, int goodsType, int base, Tile tile) {
if (!Goods.isFarmedGoods(goodsType)) {
throw new IllegalArgumentException("\"goodsType\" is produced in buildings and not on tiles.");
}
switch (unitType) {
case EXPERT_FARMER:
if ((goodsType == Goods.FOOD) && tile.isLand()) {
//TODO: Special tile stuff. He gets +6/+4 for wheat/deer tiles respectively...
base += 2;
}
break;
case EXPERT_FISHERMAN:
if ((goodsType == Goods.FOOD) && !tile.isLand()) {
//TODO: Special tile stuff. He gets +6 for a fishery tile.
base += 2;
}
break;
case EXPERT_FUR_TRAPPER:
if (goodsType == Goods.FURS) {
base *= 2;
}
break;
case EXPERT_SILVER_MINER:
if (goodsType == Goods.SILVER) {
//TODO: Mountain should be +1, not *2, but mountain didn't exist at type of writing.
base *= 2;
}
break;
case EXPERT_LUMBER_JACK:
if (goodsType == Goods.LUMBER) {
base *= 2;
}
break;
case EXPERT_ORE_MINER:
if (goodsType == Goods.ORE) {
base *= 2;
}
break;
case MASTER_SUGAR_PLANTER:
if (goodsType == Goods.SUGAR) {
base *= 2;
}
break;
case MASTER_COTTON_PLANTER:
if (goodsType == Goods.COTTON) {
base *= 2;
}
break;
case MASTER_TOBACCO_PLANTER:
if (goodsType == Goods.TOBACCO) {
base *= 2;
}
break;
case INDIAN_CONVERT:
if ((goodsType == Goods.FOOD)
|| (goodsType == Goods.SUGAR)
|| (goodsType == Goods.COTTON)
|| (goodsType == Goods.TOBACCO)
|| (goodsType == Goods.FURS)
|| (goodsType == Goods.ORE
|| (goodsType == Goods.SILVER))) {
base += 1;
}
break;
default: // Beats me who or what is working here, but he doesn't get a bonus.
break;
}
return base;
}
public static int getNextHammers(int type) {
UnitType unitType = FreeCol.specification.unitType( type );
if ( unitType.canBeBuilt() ) {
return unitType.hammersRequired;
}
return -1;
}
public static int getNextTools(int type) {
UnitType unitType = FreeCol.specification.unitType( type );
if ( unitType.canBeBuilt() ) {
return unitType.toolsRequired;
}
return -1;
}
/**
* Removes all references to this object.
*/
public void dispose() {
if (isCarrier()) {
unitContainer.dispose();
goodsContainer.dispose();
}
if (location != null) {
location.remove(this);
}
setIndianSettlement(null);
getOwner().invalidateCanSeeTiles();
super.dispose();
}
/**
* Prepares the <code>Unit</code> for a new turn.
*/
public void newTurn() {
movesLeft = getInitialMovesLeft();
doAssignedWork();
}
/**
* Make a XML-representation of this object.
*
* @param document The document to use when creating new componenets.
* @return The DOM-element ("Document Object Model") made to represent this "Unit".
*/
public Element toXMLElement(Player player, Document document, boolean showAll, boolean toSavedGame) {
Element unitElement = document.createElement(getXMLElementTagName());
unitElement.setAttribute("ID", getID());
unitElement.setAttribute("type", Integer.toString(type));
unitElement.setAttribute("armed", Boolean.toString(armed));
unitElement.setAttribute("mounted", Boolean.toString(mounted));
unitElement.setAttribute("missionary", Boolean.toString(missionary));
unitElement.setAttribute("movesLeft", Integer.toString(movesLeft));
unitElement.setAttribute("state", Integer.toString(state));
unitElement.setAttribute("workLeft", Integer.toString(workLeft));
unitElement.setAttribute("numberOfTools", Integer.toString(numberOfTools));
unitElement.setAttribute("owner", owner.getID());
unitElement.setAttribute("turnsOfTraining", Integer.toString(turnsOfTraining));
unitElement.setAttribute("trainingType", Integer.toString(trainingType));
unitElement.setAttribute("workType", Integer.toString(workType));
unitElement.setAttribute("treasureAmount", Integer.toString(treasureAmount));
unitElement.setAttribute("hitpoints", Integer.toString(hitpoints));
if (indianSettlement != null) {
unitElement.setAttribute("indianSettlement", indianSettlement.getID());
}
if (entryLocation != null) {
unitElement.setAttribute("entryLocation", entryLocation.getID());
}
if (location != null) {
if (showAll || player == getOwner() || !(location instanceof Building || location instanceof ColonyTile)) {
unitElement.setAttribute("location", location.getID());
} else {
unitElement.setAttribute("location", getTile().getColony().getID());
}
}
if (destination != null) {
unitElement.setAttribute("destination", destination.getID());
}
// Do not show enemy units hidden in a carrier:
if (isCarrier()) {
if (showAll || getOwner().equals(player) || !getGameOptions().getBoolean(GameOptions.UNIT_HIDING) && player.canSee(getTile())) {
unitElement.appendChild(unitContainer.toXMLElement(player, document, showAll, toSavedGame));
unitElement.appendChild(goodsContainer.toXMLElement(player, document, showAll, toSavedGame));
} else {
unitElement.setAttribute("visibleGoodsCount", Integer.toString(getGoodsCount()));
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), this);
emptyUnitContainer.setID(unitContainer.getID());
unitElement.appendChild(emptyUnitContainer.toXMLElement(player, document, showAll, toSavedGame));
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), this);
emptyGoodsContainer.setID(unitContainer.getID());
unitElement.appendChild(emptyGoodsContainer.toXMLElement(player, document, showAll, toSavedGame));
}
}
return unitElement;
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param unitElement The DOM-element ("Document Object Model") made to represent this "Unit".
*/
public void readFromXMLElement(Element unitElement) {
setID(unitElement.getAttribute("ID"));
type = Integer.parseInt(unitElement.getAttribute("type"));
unitType = FreeCol.specification.unitType( type );
armed = Boolean.valueOf(unitElement.getAttribute("armed")).booleanValue();
mounted = Boolean.valueOf(unitElement.getAttribute("mounted")).booleanValue();
missionary = Boolean.valueOf(unitElement.getAttribute("missionary")).booleanValue();
movesLeft = Integer.parseInt(unitElement.getAttribute("movesLeft"));
state = Integer.parseInt(unitElement.getAttribute("state"));
workLeft = Integer.parseInt(unitElement.getAttribute("workLeft"));
numberOfTools = Integer.parseInt(unitElement.getAttribute("numberOfTools"));
owner = (Player) getGame().getFreeColGameObject(unitElement.getAttribute("owner"));
turnsOfTraining = Integer.parseInt(unitElement.getAttribute("turnsOfTraining"));
trainingType = Integer.parseInt(unitElement.getAttribute("trainingType"));
if (unitElement.hasAttribute("indianSettlement")) {
indianSettlement = (IndianSettlement) getGame().getFreeColGameObject(unitElement.getAttribute("indianSettlement"));
} else {
setIndianSettlement(null);
}
if (unitElement.hasAttribute("hitpoints")) {
hitpoints = Integer.parseInt(unitElement.getAttribute("hitpoints"));
} else { // Support for PRE-0.0.3 protocols:
hitpoints = getInitialHitpoints(getType());
}
if (unitElement.hasAttribute("treasureAmount")) {
treasureAmount = Integer.parseInt(unitElement.getAttribute("treasureAmount"));
} else {
treasureAmount = 0;
}
if (unitElement.hasAttribute("destination")) {
destination = (Location) getGame().getFreeColGameObject(unitElement.getAttribute("destination"));
} else {
destination = null;
}
if (unitElement.hasAttribute("workType")) {
workType = Integer.parseInt(unitElement.getAttribute("workType"));
}
if (unitElement.hasAttribute("visibleGoodsCount")) {
visibleGoodsCount = Integer.parseInt(unitElement.getAttribute("visibleGoodsCount"));
} else {
visibleGoodsCount = -1;
}
if (owner == null) {
logger.warning("VERY BAD: Can't find player with ID " + unitElement.getAttribute("owner") + "!");
}
if (unitElement.hasAttribute("entryLocation")) {
entryLocation = (Location) getGame().getFreeColGameObject(unitElement.getAttribute("entryLocation"));
}
if (unitElement.hasAttribute("location")) {
location = (Location) getGame().getFreeColGameObject(unitElement.getAttribute("location"));
/*
In this case, 'location == null' can only occur if the location specified in the
XML-Element does not exists:
*/
if (location == null) {
logger.warning("The unit's location could not be found.");
throw new NullPointerException("The unit's location could not be found.");
}
}
if (isCarrier()) {
Element unitContainerElement = getChildElement(unitElement, UnitContainer.getXMLElementTagName());
if (unitContainerElement != null) {
if (unitContainer != null) {
unitContainer.readFromXMLElement(unitContainerElement);
} else {
unitContainer = new UnitContainer(getGame(), this, unitContainerElement);
}
} else {
// Probably an old (incompatible) save game (will cause an error if this is a client):
logger.warning("Carrier did not have a \"unitContainer\"-tag.");
unitContainer = new UnitContainer(getGame(), this);
}
Element goodsContainerElement = getChildElement(unitElement, GoodsContainer.getXMLElementTagName());
if (goodsContainerElement != null) {
if (goodsContainer != null) {
goodsContainer.readFromXMLElement(goodsContainerElement);
} else {
goodsContainer = new GoodsContainer(getGame(), this, goodsContainerElement);
}
} else {
// Probably an old (incompatible) save game (will cause an error if this is a client):
logger.warning("Carrier did not have a \"goodsContainer\"-tag.");
goodsContainer = new GoodsContainer(getGame(), this);
}
}
getOwner().invalidateCanSeeTiles();
}
/**
* Gets the tag name of the root element representing this object.
* @return "unit.
*/
public static String getXMLElementTagName() {
return "unit";
}
}
| true | false | null | null |
diff --git a/src/org/eclipse/core/tests/resources/regression/AllTests.java b/src/org/eclipse/core/tests/resources/regression/AllTests.java
index 8d27c93..ef2a4ef 100644
--- a/src/org/eclipse/core/tests/resources/regression/AllTests.java
+++ b/src/org/eclipse/core/tests/resources/regression/AllTests.java
@@ -1,73 +1,74 @@
/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
+ * Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.resources.regression;
import junit.framework.*;
public class AllTests extends TestCase {
/**
* AllTests constructor comment.
* @param name java.lang.String
*/
public AllTests() {
super(null);
}
/**
* AllTests constructor comment.
* @param name java.lang.String
*/
public AllTests(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(Bug_006708.suite());
suite.addTest(Bug_025457.suite());
suite.addTest(Bug_026294.suite());
suite.addTest(Bug_027271.suite());
suite.addTest(Bug_028981.suite());
suite.addTest(Bug_029116.suite());
suite.addTest(Bug_029671.suite());
suite.addTest(Bug_029851.suite());
suite.addTest(Bug_032076.suite());
suite.addTest(Bug_044106.suite());
suite.addTest(Bug_092108.suite());
suite.addTest(Bug_097608.suite());
suite.addTest(Bug_098740.suite());
suite.addTest(Bug_126104.suite());
suite.addTest(Bug_127562.suite());
suite.addTest(Bug_132510.suite());
suite.addTest(Bug_134364.suite());
suite.addTest(Bug_147232.suite());
suite.addTest(Bug_160251.suite());
suite.addTest(Bug_165892.suite());
suite.addTest(Bug_226264.suite());
suite.addTest(Bug_231301.suite());
suite.addTest(Bug_233939.suite());
suite.addTest(Bug_265810.suite());
suite.addTest(Bug_264182.suite());
suite.addTest(Bug_288315.suite());
+ suite.addTest(Bug_329836.suite());
suite.addTest(Bug_331445.suite());
suite.addTest(IFileTest.suite());
suite.addTest(IFolderTest.suite());
suite.addTest(IProjectTest.suite());
suite.addTest(IResourceTest.suite());
suite.addTest(IWorkspaceTest.suite());
suite.addTest(LocalStoreRegressionTests.suite());
suite.addTest(NLTest.suite());
suite.addTest(PR_1GEAB3C_Test.suite());
suite.addTest(PR_1GH2B0N_Test.suite());
suite.addTest(PR_1GHOM0N_Test.suite());
return suite;
}
}
diff --git a/src/org/eclipse/core/tests/resources/regression/Bug_329836.java b/src/org/eclipse/core/tests/resources/regression/Bug_329836.java
index 99a45bf..5c22f6f 100644
--- a/src/org/eclipse/core/tests/resources/regression/Bug_329836.java
+++ b/src/org/eclipse/core/tests/resources/regression/Bug_329836.java
@@ -1,59 +1,76 @@
/*******************************************************************************
- * Copyright (c) 2010 IBM Corporation and others.
+ * Copyright (c) 2010, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.resources.regression;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.filesystem.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.tests.resources.ResourceTest;
/**
* Test for bug 329836
*/
public class Bug_329836 extends ResourceTest {
public Bug_329836() {
super();
}
public Bug_329836(String name) {
super(name);
}
public void testBug() {
if (!Platform.getOS().equals(Platform.OS_MACOSX))
return;
IFileStore fileStore = getTempStore().getChild(getUniqueString());
createFileInFileSystem(fileStore);
// set EFS.ATTRIBUTE_READ_ONLY which also sets EFS.IMMUTABLE on Mac
IFileInfo info = fileStore.fetchInfo();
info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
try {
fileStore.putInfo(info, EFS.SET_ATTRIBUTES, getMonitor());
} catch (CoreException e) {
fail("1.0", e);
}
// read the info again
info = fileStore.fetchInfo();
// check that attributes are really set
assertTrue("2.0", info.getAttribute(EFS.ATTRIBUTE_READ_ONLY));
assertTrue("3.0", info.getAttribute(EFS.ATTRIBUTE_IMMUTABLE));
+
+ // unset EFS.ATTRIBUTE_READ_ONLY which also unsets EFS.IMMUTABLE on Mac
+
+ info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, false);
+ try {
+ fileStore.putInfo(info, EFS.SET_ATTRIBUTES, getMonitor());
+ } catch (CoreException e) {
+ fail("4.0", e);
+ }
+
+ // read the info again
+ info = fileStore.fetchInfo();
+
+ // check that attributes are really unset
+ assertFalse("5.0", info.getAttribute(EFS.ATTRIBUTE_READ_ONLY));
+ assertFalse("6.0", info.getAttribute(EFS.ATTRIBUTE_IMMUTABLE));
+
}
public static Test suite() {
return new TestSuite(Bug_329836.class);
}
}
diff --git a/src/org/eclipse/core/tests/resources/session/AllTests.java b/src/org/eclipse/core/tests/resources/session/AllTests.java
index e209000..31937c8 100644
--- a/src/org/eclipse/core/tests/resources/session/AllTests.java
+++ b/src/org/eclipse/core/tests/resources/session/AllTests.java
@@ -1,56 +1,57 @@
/*******************************************************************************
- * Copyright (c) 2004, 2010 IBM Corporation and others.
+ * Copyright (c) 2004, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.resources.session;
import junit.framework.*;
public class AllTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(SampleSessionTest.suite());
suite.addTest(TestBug93473.suite());
suite.addTest(TestSave.suite());
suite.addTest(Test1G1N9GZ.suite());
suite.addTest(TestCloseNoSave.suite());
suite.addTest(TestMultiSnap.suite());
suite.addTest(TestSaveCreateProject.suite());
suite.addTest(TestSaveSnap.suite());
suite.addTest(TestSaveWithClosedProject.suite());
suite.addTest(TestSnapSaveSnap.suite());
suite.addTest(TestBug6995.suite());
suite.addTest(TestInterestingProjectPersistence.suite());
suite.addTest(TestBuilderDeltaSerialization.suite());
suite.addTest(Test1GALH44.suite());
suite.addTest(TestMissingBuilder.suite());
suite.addTest(TestClosedProjectLocation.suite());
suite.addTest(FindDeletedMembersTest.suite());
suite.addTest(TestBug20127.suite());
suite.addTest(TestBug12575.suite());
suite.addTest(WorkspaceDescriptionTest.suite());
suite.addTest(TestBug30015.suite());
suite.addTest(TestMasterTableCleanup.suite());
suite.addTest(ProjectPreferenceSessionTest.suite());
suite.addTest(TestBug113943.suite());
suite.addTest(TestCreateLinkedResourceInHiddenProject.suite());
suite.addTest(Bug_266907.suite());
suite.addTest(TestBug297635.suite());
+ suite.addTest(TestBug323833.suite());
// this one comes from org.eclipse.core.tests.resources.saveparticipant
// comment this out until we have a better solution for running these tests
// (keeping their contents inside this plugin as subdirs and dynamically installing
// seems to be a promising approach)
//suite.addTest(SaveParticipantTest.suite());
//session tests from other packages
suite.addTest(org.eclipse.core.tests.resources.regression.TestMultipleBuildersOfSameType.suite());
suite.addTest(org.eclipse.core.tests.resources.usecase.SnapshotTest.suite());
suite.addTest(ProjectDescriptionDynamicTest.suite());
return suite;
}
}
| false | false | null | null |
diff --git a/src/com/android/launcher2/Workspace.java b/src/com/android/launcher2/Workspace.java
index 9e32dd5..20515c0 100644
--- a/src/com/android/launcher2/Workspace.java
+++ b/src/com/android/launcher2/Workspace.java
@@ -1,1475 +1,1478 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.ComponentName;
import android.content.res.TypedArray;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.os.Parcel;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.Scroller;
import android.widget.TextView;
import java.util.ArrayList;
/**
* The workspace is a wide area with a wallpaper and a finite number of screens. Each
* screen contains a number of icons, folders or widgets the user can interact with.
* A workspace is meant to be used with a fixed width only.
*/
public class Workspace extends ViewGroup implements DropTarget, DragSource, DragScroller {
@SuppressWarnings({"UnusedDeclaration"})
private static final String TAG = "Launcher.Workspace";
private static final int INVALID_SCREEN = -1;
/**
* The velocity at which a fling gesture will cause us to snap to the next screen
*/
private static final int SNAP_VELOCITY = 1000;
private final WallpaperManager mWallpaperManager;
private int mDefaultScreen;
private boolean mFirstLayout = true;
private int mCurrentScreen;
private int mNextScreen = INVALID_SCREEN;
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
/**
* CellInfo for the cell that is currently being dragged
*/
private CellLayout.CellInfo mDragInfo;
/**
* Target drop area calculated during last acceptDrop call.
*/
private int[] mTargetCell = null;
private float mLastMotionX;
private float mLastMotionY;
private final static int TOUCH_STATE_REST = 0;
private final static int TOUCH_STATE_SCROLLING = 1;
private int mTouchState = TOUCH_STATE_REST;
private OnLongClickListener mLongClickListener;
private Launcher mLauncher;
private DragController mDragController;
/**
* Cache of vacant cells, used during drag events and invalidated as needed.
*/
private CellLayout.CellInfo mVacantCache = null;
private int[] mTempCell = new int[2];
private int[] mTempEstimate = new int[2];
private boolean mAllowLongPress = true;
private int mTouchSlop;
private int mMaximumVelocity;
final Rect mDrawerBounds = new Rect();
final Rect mClipBounds = new Rect();
int mDrawerContentHeight;
int mDrawerContentWidth;
private Drawable mPreviousIndicator;
private Drawable mNextIndicator;
private boolean mFading = true;
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
*/
public Workspace(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
* @param defStyle Unused.
*/
public Workspace(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mWallpaperManager = WallpaperManager.getInstance(context);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Workspace, defStyle, 0);
mDefaultScreen = a.getInt(R.styleable.Workspace_defaultScreen, 1);
a.recycle();
setHapticFeedbackEnabled(false);
initWorkspace();
}
/**
* Initializes various states for this workspace.
*/
private void initWorkspace() {
mScroller = new Scroller(getContext());
mCurrentScreen = mDefaultScreen;
Launcher.setScreen(mCurrentScreen);
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
public void addView(View child, int index, LayoutParams params) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, index, params);
}
@Override
public void addView(View child) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child);
}
@Override
public void addView(View child, int index) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, index);
}
@Override
public void addView(View child, int width, int height) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, width, height);
}
@Override
public void addView(View child, LayoutParams params) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, params);
}
/**
* @return The open folder on the current screen, or null if there is none
*/
Folder getOpenFolder() {
CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
return (Folder) child;
}
}
return null;
}
ArrayList<Folder> getOpenFolders() {
final int screens = getChildCount();
ArrayList<Folder> folders = new ArrayList<Folder>(screens);
for (int screen = 0; screen < screens; screen++) {
CellLayout currentScreen = (CellLayout) getChildAt(screen);
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
folders.add((Folder) child);
break;
}
}
}
return folders;
}
boolean isDefaultScreenShowing() {
return mCurrentScreen == mDefaultScreen;
}
/**
* Returns the index of the currently displayed screen.
*
* @return The index of the currently displayed screen.
*/
int getCurrentScreen() {
return mCurrentScreen;
}
/**
* Returns how many screens there are.
*/
int getScreenCount() {
return getChildCount();
}
/**
* Computes a bounding rectangle for a range of cells
*
* @param cellX X coordinate of upper left corner expressed as a cell position
* @param cellY Y coordinate of upper left corner expressed as a cell position
* @param cellHSpan Width in cells
* @param cellVSpan Height in cells
* @param rect Rectnagle into which to put the results
*/
public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, RectF rect) {
((CellLayout)getChildAt(mCurrentScreen)).cellToRect(cellX, cellY,
cellHSpan, cellVSpan, rect);
}
/**
* Sets the current screen.
*
* @param currentScreen
*/
void setCurrentScreen(int currentScreen) {
if (!mScroller.isFinished()) mScroller.abortAnimation();
clearVacantCache();
mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1));
scrollTo(mCurrentScreen * getWidth(), 0);
+ mPreviousIndicator.setLevel(currentScreen);
+ mNextIndicator.setLevel(currentScreen);
+ updateWallpaperOffset();
invalidate();
}
/**
* Adds the specified child in the current screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void addInCurrentScreen(View child, int x, int y, int spanX, int spanY) {
addInScreen(child, mCurrentScreen, x, y, spanX, spanY, false);
}
/**
* Adds the specified child in the current screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
* @param insert When true, the child is inserted at the beginning of the children list.
*/
void addInCurrentScreen(View child, int x, int y, int spanX, int spanY, boolean insert) {
addInScreen(child, mCurrentScreen, x, y, spanX, spanY, insert);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
addInScreen(child, screen, x, y, spanX, spanY, false);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
* @param insert When true, the child is inserted at the beginning of the children list.
*/
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
if (screen < 0 || screen >= getChildCount()) {
throw new IllegalStateException("The screen must be >= 0 and < " + getChildCount());
}
clearVacantCache();
final CellLayout group = (CellLayout) getChildAt(screen);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp == null) {
lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
} else {
lp.cellX = x;
lp.cellY = y;
lp.cellHSpan = spanX;
lp.cellVSpan = spanY;
}
group.addView(child, insert ? 0 : -1, lp);
if (!(child instanceof Folder)) {
child.setHapticFeedbackEnabled(false);
child.setOnLongClickListener(mLongClickListener);
}
if (child instanceof DropTarget) {
mDragController.addDropTarget((DropTarget)child);
}
}
void addWidget(View view, Widget widget) {
addInScreen(view, widget.screen, widget.cellX, widget.cellY, widget.spanX,
widget.spanY, false);
}
void addWidget(View view, Widget widget, boolean insert) {
addInScreen(view, widget.screen, widget.cellX, widget.cellY, widget.spanX,
widget.spanY, insert);
}
CellLayout.CellInfo findAllVacantCells(boolean[] occupied) {
CellLayout group = (CellLayout) getChildAt(mCurrentScreen);
if (group != null) {
return group.findAllVacantCells(occupied, null);
}
return null;
}
private void clearVacantCache() {
if (mVacantCache != null) {
mVacantCache.clearVacantCells();
mVacantCache = null;
}
}
/**
* Returns the coordinate of a vacant cell for the current screen.
*/
boolean getVacantCell(int[] vacant, int spanX, int spanY) {
CellLayout group = (CellLayout) getChildAt(mCurrentScreen);
if (group != null) {
return group.getVacantCell(vacant, spanX, spanY);
}
return false;
}
/**
* Adds the specified child in the current screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void fitInCurrentScreen(View child, int spanX, int spanY) {
fitInScreen(child, mCurrentScreen, spanX, spanY);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void fitInScreen(View child, int screen, int spanX, int spanY) {
if (screen < 0 || screen >= getChildCount()) {
throw new IllegalStateException("The screen must be >= 0 and < " + getChildCount());
}
final CellLayout group = (CellLayout) getChildAt(screen);
boolean vacant = group.getVacantCell(mTempCell, spanX, spanY);
if (vacant) {
group.addView(child,
new CellLayout.LayoutParams(mTempCell[0], mTempCell[1], spanX, spanY));
child.setHapticFeedbackEnabled(false);
child.setOnLongClickListener(mLongClickListener);
if (child instanceof DropTarget) {
mDragController.addDropTarget((DropTarget)child);
}
}
}
/**
* Registers the specified listener on each screen contained in this workspace.
*
* @param l The listener used to respond to long clicks.
*/
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLongClickListener = l;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).setOnLongClickListener(l);
}
}
private void updateWallpaperOffset() {
updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft));
}
private void updateWallpaperOffset(int scrollRange) {
mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
mWallpaperManager.setWallpaperOffsets(getWindowToken(), mScrollX / (float) scrollRange, 0);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
mScrollX = mScroller.getCurrX();
mScrollY = mScroller.getCurrY();
updateWallpaperOffset();
postInvalidate();
} else if (mNextScreen != INVALID_SCREEN) {
mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1));
mPreviousIndicator.setLevel(mCurrentScreen);
mNextIndicator.setLevel(mCurrentScreen);
Launcher.setScreen(mCurrentScreen);
mNextScreen = INVALID_SCREEN;
clearChildrenCache();
}
}
public void startFading(boolean dest) {
mFading = dest;
invalidate();
}
@Override
protected void dispatchDraw(Canvas canvas) {
/*
final boolean allAppsOpaque = mLauncher.isAllAppsOpaque();
if (mFading == allAppsOpaque) {
invalidate();
} else {
mFading = !allAppsOpaque;
}
if (allAppsOpaque) {
// If the launcher is up, draw black.
canvas.drawARGB(0xff, 0, 0, 0);
return;
}
*/
boolean restore = false;
int restoreCount = 0;
// For the fade. If view gets setAlpha(), use that instead.
float scale = mScale;
if (scale < 0.999f) {
int sx = mScrollX;
int alpha = (scale < 0.5f) ? (int)(255 * 2 * scale) : 255;
restoreCount = canvas.saveLayerAlpha(sx, 0, sx+getWidth(), getHeight(), alpha,
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
restore = true;
if (scale < 0.999f) {
int w = getWidth();
w += 2 * mCurrentScreen * w;
int dx = w/2;
int h = getHeight();
int dy = (h/2) - (h/4);
canvas.translate(dx, dy);
canvas.scale(scale, scale);
canvas.translate(-dx, -dy);
}
}
// ViewGroup.dispatchDraw() supports many features we don't need:
// clip to padding, layout animation, animation listener, disappearing
// children, etc. The following implementation attempts to fast-track
// the drawing dispatch by drawing only what we know needs to be drawn.
boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN
&& scale > 0.999f;
// If we are not scrolling or flinging, draw only the current screen
if (fastDraw) {
drawChild(canvas, getChildAt(mCurrentScreen), getDrawingTime());
} else {
final long drawingTime = getDrawingTime();
// If we are flinging, draw only the current screen and the target screen
if (mNextScreen >= 0 && mNextScreen < getChildCount() &&
Math.abs(mCurrentScreen - mNextScreen) == 1) {
drawChild(canvas, getChildAt(mCurrentScreen), drawingTime);
drawChild(canvas, getChildAt(mNextScreen), drawingTime);
} else {
// If we are scrolling, draw all of our children
final int count = getChildCount();
for (int i = 0; i < count; i++) {
drawChild(canvas, getChildAt(i), drawingTime);
}
}
}
if (restore) {
canvas.restoreToCount(restoreCount);
}
}
private float mScale = 1.0f;
public void setScale(float scale) {
mScale = scale;
invalidate();
}
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mDragController.setWindowToken(getWindowToken());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
// The children are given the same width and height as the workspace
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
if (mFirstLayout) {
setHorizontalScrollBarEnabled(false);
scrollTo(mCurrentScreen * width, 0);
setHorizontalScrollBarEnabled(true);
updateWallpaperOffset(width * (getChildCount() - 1));
mFirstLayout = false;
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int childLeft = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
final int childWidth = child.getMeasuredWidth();
child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
childLeft += childWidth;
}
}
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
int screen = indexOfChild(child);
if (screen != mCurrentScreen || !mScroller.isFinished()) {
if (!mLauncher.isWorkspaceLocked()) {
snapToScreen(screen);
}
return true;
}
return false;
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
if (!mLauncher.isAllAppsVisible()) {
final Folder openFolder = getOpenFolder();
if (openFolder != null) {
return openFolder.requestFocus(direction, previouslyFocusedRect);
} else {
int focusableScreen;
if (mNextScreen != INVALID_SCREEN) {
focusableScreen = mNextScreen;
} else {
focusableScreen = mCurrentScreen;
}
getChildAt(focusableScreen).requestFocus(direction, previouslyFocusedRect);
}
}
return false;
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (direction == View.FOCUS_LEFT) {
if (getCurrentScreen() > 0) {
snapToScreen(getCurrentScreen() - 1);
return true;
}
} else if (direction == View.FOCUS_RIGHT) {
if (getCurrentScreen() < getChildCount() - 1) {
snapToScreen(getCurrentScreen() + 1);
return true;
}
}
return super.dispatchUnhandledMove(focused, direction);
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (!mLauncher.isAllAppsVisible()) {
final Folder openFolder = getOpenFolder();
if (openFolder == null) {
getChildAt(mCurrentScreen).addFocusables(views, direction);
if (direction == View.FOCUS_LEFT) {
if (mCurrentScreen > 0) {
getChildAt(mCurrentScreen - 1).addFocusables(views, direction);
}
} else if (direction == View.FOCUS_RIGHT){
if (mCurrentScreen < getChildCount() - 1) {
getChildAt(mCurrentScreen + 1).addFocusables(views, direction);
}
}
} else {
openFolder.addFocusables(views, direction);
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (mLauncher.isWorkspaceLocked() || mLauncher.isAllAppsVisible()) {
return false;
}
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final boolean workspaceLocked = mLauncher.isWorkspaceLocked();
final boolean allAppsVisible = mLauncher.isAllAppsVisible();
if (workspaceLocked || allAppsVisible) {
return false; // We don't want the events. Let them fall through to the all apps view.
}
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
/*
* Shortcut the most recurring case: the user is in the dragging
* state and he is moving his finger. We want to intercept this
* motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
return true;
}
final float x = ev.getX();
final float y = ev.getY();
switch (action) {
case MotionEvent.ACTION_MOVE:
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionX is set to the y value
* of the down event.
*/
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int touchSlop = mTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || yMoved) {
if (xMoved) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
enableChildrenCache(mCurrentScreen - 1, mCurrentScreen + 1);
}
// Either way, cancel any pending longpress
if (mAllowLongPress) {
mAllowLongPress = false;
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentScreen = getChildAt(mCurrentScreen);
currentScreen.cancelLongPress();
}
}
break;
case MotionEvent.ACTION_DOWN:
// Remember location of down touch
mLastMotionX = x;
mLastMotionY = y;
mAllowLongPress = true;
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when
* being flinged.
*/
mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (mTouchState != TOUCH_STATE_SCROLLING) {
final CellLayout currentScreen = (CellLayout)getChildAt(mCurrentScreen);
if (!currentScreen.lastDownOnOccupiedCell()) {
// Send a tap to the wallpaper if the last down was on empty space
mWallpaperManager.sendWallpaperCommand(getWindowToken(),
"android.wallpaper.tap", (int) ev.getX(), (int) ev.getY(), 0, null);
}
}
// Release the drag
clearChildrenCache();
mTouchState = TOUCH_STATE_REST;
mAllowLongPress = false;
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
/**
* If one of our descendant views decides that it could be focused now, only
* pass that along if it's on the current screen.
*
* This happens when live folders requery, and if they're off screen, they
* end up calling requestFocus, which pulls it on screen.
*/
@Override
public void focusableViewAvailable(View focused) {
View current = getChildAt(mCurrentScreen);
View v = focused;
while (true) {
if (v == current) {
super.focusableViewAvailable(focused);
return;
}
if (v == this) {
return;
}
ViewParent parent = v.getParent();
if (parent instanceof View) {
v = (View)v.getParent();
} else {
return;
}
}
}
void enableChildrenCache(int fromScreen, int toScreen) {
if (fromScreen > toScreen) {
fromScreen = toScreen;
toScreen = fromScreen;
}
final int count = getChildCount();
fromScreen = Math.max(fromScreen, 0);
toScreen = Math.min(toScreen, count - 1);
for (int i = fromScreen; i <= toScreen; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(true);
layout.setChildrenDrawingCacheEnabled(true);
}
}
void clearChildrenCache() {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(false);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mLauncher.isWorkspaceLocked()) {
return false; // We don't want the events. Let them fall through to the all apps view.
}
if (mLauncher.isAllAppsVisible()) {
// Cancel any scrolling that is in progress.
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
snapToScreen(mCurrentScreen);
return false; // We don't want the events. Let them fall through to the all apps view.
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
final float x = ev.getX();
switch (action) {
case MotionEvent.ACTION_DOWN:
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mLastMotionX = x;
break;
case MotionEvent.ACTION_MOVE:
if (mTouchState == TOUCH_STATE_SCROLLING) {
// Scroll to follow the motion event
final int deltaX = (int) (mLastMotionX - x);
mLastMotionX = x;
if (deltaX < 0) {
if (mScrollX > 0) {
scrollBy(Math.max(-mScrollX, deltaX), 0);
updateWallpaperOffset();
}
} else if (deltaX > 0) {
final int availableToScroll = getChildAt(getChildCount() - 1).getRight() -
mScrollX - getWidth();
if (availableToScroll > 0) {
scrollBy(Math.min(availableToScroll, deltaX), 0);
updateWallpaperOffset();
}
} else {
awakenScrollBars();
}
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_SCROLLING) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int velocityX = (int) velocityTracker.getXVelocity();
if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
// Fling hard enough to move left
snapToScreen(mCurrentScreen - 1);
} else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
// Fling hard enough to move right
snapToScreen(mCurrentScreen + 1);
} else {
snapToDestination();
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
mTouchState = TOUCH_STATE_REST;
break;
case MotionEvent.ACTION_CANCEL:
mTouchState = TOUCH_STATE_REST;
}
return true;
}
private void snapToDestination() {
final int screenWidth = getWidth();
final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth;
snapToScreen(whichScreen);
}
void snapToScreen(int whichScreen) {
//if (!mScroller.isFinished()) return;
whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
clearVacantCache();
enableChildrenCache(mCurrentScreen, whichScreen);
final int screenDelta = Math.abs(whichScreen - mCurrentScreen);
mNextScreen = whichScreen;
mPreviousIndicator.setLevel(mNextScreen);
mNextIndicator.setLevel(mNextScreen);
View focusedChild = getFocusedChild();
if (focusedChild != null && screenDelta != 0 && focusedChild == getChildAt(mCurrentScreen)) {
focusedChild.clearFocus();
}
final int newX = whichScreen * getWidth();
final int delta = newX - mScrollX;
final int duration = screenDelta * 300;
awakenScrollBars(duration);
mScroller.startScroll(mScrollX, 0, delta, 0, duration);
invalidate();
}
void startDrag(CellLayout.CellInfo cellInfo) {
View child = cellInfo.cell;
// Make sure the drag was started by a long press as opposed to a long click.
// Note that Search takes focus when clicked rather than entering touch mode
if (!child.isInTouchMode() && !(child instanceof Search)) {
return;
}
mDragInfo = cellInfo;
mDragInfo.screen = mCurrentScreen;
CellLayout current = ((CellLayout) getChildAt(mCurrentScreen));
current.onDragChild(child);
mDragController.startDrag(child, this, child.getTag(), DragController.DRAG_ACTION_MOVE);
invalidate();
}
@Override
protected Parcelable onSaveInstanceState() {
final SavedState state = new SavedState(super.onSaveInstanceState());
state.currentScreen = mCurrentScreen;
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
if (savedState.currentScreen != -1) {
mCurrentScreen = savedState.currentScreen;
Launcher.setScreen(mCurrentScreen);
}
}
void addApplicationShortcut(ApplicationInfo info, CellLayout.CellInfo cellInfo) {
addApplicationShortcut(info, cellInfo, false);
}
void addApplicationShortcut(ApplicationInfo info, CellLayout.CellInfo cellInfo,
boolean insertAtFirst) {
final CellLayout layout = (CellLayout) getChildAt(cellInfo.screen);
final int[] result = new int[2];
layout.cellToPoint(cellInfo.cellX, cellInfo.cellY, result);
onDropExternal(result[0], result[1], info, layout, insertAtFirst);
}
public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
final CellLayout cellLayout = getCurrentDropLayout();
if (source != this) {
onDropExternal(x - xOffset, y - yOffset, dragInfo, cellLayout);
} else {
// Move internally
if (mDragInfo != null) {
final View cell = mDragInfo.cell;
int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen;
if (index != mDragInfo.screen) {
final CellLayout originalCellLayout = (CellLayout) getChildAt(mDragInfo.screen);
originalCellLayout.removeView(cell);
cellLayout.addView(cell);
}
mTargetCell = estimateDropCell(x - xOffset, y - yOffset,
mDragInfo.spanX, mDragInfo.spanY, cell, cellLayout, mTargetCell);
cellLayout.onDropChild(cell, mTargetCell);
final ItemInfo info = (ItemInfo) cell.getTag();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
LauncherModel.moveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, index, lp.cellX, lp.cellY);
}
}
}
public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
clearVacantCache();
}
public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
}
public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
clearVacantCache();
}
private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout) {
onDropExternal(x, y, dragInfo, cellLayout, false);
}
private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout,
boolean insertAtFirst) {
// Drag from somewhere else
ItemInfo info = (ItemInfo) dragInfo;
View view;
switch (info.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (info.container == NO_ID) {
// Came from all apps -- make a copy
info = new ApplicationInfo((ApplicationInfo) info);
}
view = mLauncher.createShortcut(R.layout.application, cellLayout,
(ApplicationInfo) info);
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
(ViewGroup) getChildAt(mCurrentScreen), ((UserFolderInfo) info));
break;
default:
throw new IllegalStateException("Unknown item type: " + info.itemType);
}
cellLayout.addView(view, insertAtFirst ? 0 : -1);
view.setHapticFeedbackEnabled(false);
view.setOnLongClickListener(mLongClickListener);
if (view instanceof DropTarget) {
mDragController.addDropTarget((DropTarget) view);
}
mTargetCell = estimateDropCell(x, y, 1, 1, view, cellLayout, mTargetCell);
cellLayout.onDropChild(view, mTargetCell);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentScreen, lp.cellX, lp.cellY);
}
/**
* Return the current {@link CellLayout}, correctly picking the destination
* screen while a scroll is in progress.
*/
private CellLayout getCurrentDropLayout() {
int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen;
return (CellLayout) getChildAt(index);
}
/**
* {@inheritDoc}
*/
public boolean acceptDrop(DragSource source, int x, int y,
int xOffset, int yOffset, DragView dragView, Object dragInfo) {
final CellLayout layout = getCurrentDropLayout();
final CellLayout.CellInfo cellInfo = mDragInfo;
final int spanX = cellInfo == null ? 1 : cellInfo.spanX;
final int spanY = cellInfo == null ? 1 : cellInfo.spanY;
if (mVacantCache == null) {
final View ignoreView = cellInfo == null ? null : cellInfo.cell;
mVacantCache = layout.findAllVacantCells(null, ignoreView);
}
return mVacantCache.findCellForSpan(mTempEstimate, spanX, spanY, false);
}
/**
* {@inheritDoc}
*/
public Rect estimateDropLocation(DragSource source, int x, int y,
int xOffset, int yOffset, DragView dragView, Object dragInfo, Rect recycle) {
final CellLayout layout = getCurrentDropLayout();
final CellLayout.CellInfo cellInfo = mDragInfo;
final int spanX = cellInfo == null ? 1 : cellInfo.spanX;
final int spanY = cellInfo == null ? 1 : cellInfo.spanY;
final View ignoreView = cellInfo == null ? null : cellInfo.cell;
final Rect location = recycle != null ? recycle : new Rect();
// Find drop cell and convert into rectangle
int[] dropCell = estimateDropCell(x - xOffset, y - yOffset,
spanX, spanY, ignoreView, layout, mTempCell);
if (dropCell == null) {
return null;
}
layout.cellToPoint(dropCell[0], dropCell[1], mTempEstimate);
location.left = mTempEstimate[0];
location.top = mTempEstimate[1];
layout.cellToPoint(dropCell[0] + spanX, dropCell[1] + spanY, mTempEstimate);
location.right = mTempEstimate[0];
location.bottom = mTempEstimate[1];
return location;
}
/**
* Calculate the nearest cell where the given object would be dropped.
*/
private int[] estimateDropCell(int pixelX, int pixelY,
int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
// Create vacant cell cache if none exists
if (mVacantCache == null) {
mVacantCache = layout.findAllVacantCells(null, ignoreView);
}
// Find the best target drop location
return layout.findNearestVacantArea(pixelX, pixelY,
spanX, spanY, mVacantCache, recycle);
}
void setLauncher(Launcher launcher) {
mLauncher = launcher;
}
public void setDragController(DragController dragController) {
mDragController = dragController;
}
public void onDropCompleted(View target, boolean success) {
clearVacantCache();
if (success){
if (target != this && mDragInfo != null) {
final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
cellLayout.removeView(mDragInfo.cell);
if (mDragInfo.cell instanceof DropTarget) {
mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
}
//final Object tag = mDragInfo.cell.getTag();
}
} else {
if (mDragInfo != null) {
final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
cellLayout.onDropAborted(mDragInfo.cell);
}
}
mDragInfo = null;
}
public void scrollLeft() {
clearVacantCache();
if (mNextScreen == INVALID_SCREEN && mCurrentScreen > 0 && mScroller.isFinished()) {
snapToScreen(mCurrentScreen - 1);
}
}
public void scrollRight() {
clearVacantCache();
if (mNextScreen == INVALID_SCREEN && mCurrentScreen < getChildCount() -1 &&
mScroller.isFinished()) {
snapToScreen(mCurrentScreen + 1);
}
}
public int getScreenForView(View v) {
int result = -1;
if (v != null) {
ViewParent vp = v.getParent();
int count = getChildCount();
for (int i = 0; i < count; i++) {
if (vp == getChildAt(i)) {
return i;
}
}
}
return result;
}
/**
* Find a search widget on the given screen
*/
private Search findSearchWidget(CellLayout screen) {
final int count = screen.getChildCount();
for (int i = 0; i < count; i++) {
View v = screen.getChildAt(i);
if (v instanceof Search) {
return (Search) v;
}
}
return null;
}
/**
* Gets the first search widget on the current screen, if there is one.
* Returns <code>null</code> otherwise.
*/
public Search findSearchWidgetOnCurrentScreen() {
CellLayout currentScreen = (CellLayout)getChildAt(mCurrentScreen);
return findSearchWidget(currentScreen);
}
public Folder getFolderForTag(Object tag) {
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentScreen = ((CellLayout) getChildAt(screen));
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
Folder f = (Folder) child;
if (f.getInfo() == tag) {
return f;
}
}
}
}
return null;
}
public View getViewForTag(Object tag) {
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentScreen = ((CellLayout) getChildAt(screen));
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
if (child.getTag() == tag) {
return child;
}
}
}
return null;
}
/**
* @return True is long presses are still allowed for the current touch
*/
public boolean allowLongPress() {
return mAllowLongPress;
}
/**
* Set true to allow long-press events to be triggered, usually checked by
* {@link Launcher} to accept or block dpad-initiated long-presses.
*/
public void setAllowLongPress(boolean allowLongPress) {
mAllowLongPress = allowLongPress;
}
void removeShortcutsForPackage(String packageName) {
final ArrayList<View> childrenToRemove = new ArrayList<View>();
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
int childCount = layout.getChildCount();
childrenToRemove.clear();
for (int j = 0; j < childCount; j++) {
final View view = layout.getChildAt(j);
Object tag = view.getTag();
if (tag instanceof ApplicationInfo) {
final ApplicationInfo info = (ApplicationInfo) tag;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
final Intent intent = info.intent;
final ComponentName name = intent.getComponent();
if (Intent.ACTION_MAIN.equals(intent.getAction()) &&
name != null && packageName.equals(name.getPackageName())) {
LauncherModel.deleteItemFromDatabase(mLauncher, info);
childrenToRemove.add(view);
}
} else if (tag instanceof UserFolderInfo) {
final UserFolderInfo info = (UserFolderInfo) tag;
final ArrayList<ApplicationInfo> contents = info.contents;
final ArrayList<ApplicationInfo> toRemove = new ArrayList<ApplicationInfo>(1);
final int contentsCount = contents.size();
boolean removedFromFolder = false;
for (int k = 0; k < contentsCount; k++) {
final ApplicationInfo appInfo = contents.get(k);
final Intent intent = appInfo.intent;
final ComponentName name = intent.getComponent();
if (Intent.ACTION_MAIN.equals(intent.getAction()) &&
name != null && packageName.equals(name.getPackageName())) {
toRemove.add(appInfo);
LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
removedFromFolder = true;
}
}
contents.removeAll(toRemove);
if (removedFromFolder) {
final Folder folder = getOpenFolder();
if (folder != null) folder.notifyDataSetChanged();
}
}
}
childCount = childrenToRemove.size();
for (int j = 0; j < childCount; j++) {
View child = childrenToRemove.get(j);
layout.removeViewInLayout(child);
if (child instanceof DropTarget) {
mDragController.removeDropTarget((DropTarget)child);
}
}
if (childCount > 0) {
layout.requestLayout();
layout.invalidate();
}
}
}
void updateShortcutsForPackage(String packageName) {
final PackageManager pm = mLauncher.getPackageManager();
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
int childCount = layout.getChildCount();
for (int j = 0; j < childCount; j++) {
final View view = layout.getChildAt(j);
Object tag = view.getTag();
if (tag instanceof ApplicationInfo) {
ApplicationInfo info = (ApplicationInfo) tag;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
final Intent intent = info.intent;
final ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null &&
packageName.equals(name.getPackageName())) {
final Drawable icon = AppInfoCache.getIconDrawable(pm, info);
if (icon != null && icon != info.icon) {
info.icon.setCallback(null);
info.icon = Utilities.createIconThumbnail(icon, mContext);
info.filtered = true;
((TextView) view).setCompoundDrawablesWithIntrinsicBounds(null,
info.icon, null, null);
}
}
}
}
}
}
void moveToDefaultScreen(boolean animate) {
if (animate) {
snapToScreen(mDefaultScreen);
} else {
setCurrentScreen(mDefaultScreen);
}
getChildAt(mDefaultScreen).requestFocus();
}
void setIndicators(Drawable previous, Drawable next) {
mPreviousIndicator = previous;
mNextIndicator = next;
previous.setLevel(mCurrentScreen);
next.setLevel(mCurrentScreen);
}
public static class SavedState extends BaseSavedState {
int currentScreen = -1;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentScreen = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(currentScreen);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
void show() {
setVisibility(VISIBLE);
}
void hide() {
}
}
| true | false | null | null |
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/util/OlapExpressionCompiler.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/util/OlapExpressionCompiler.java
index ac00da390..8f36ded27 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/util/OlapExpressionCompiler.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/util/OlapExpressionCompiler.java
@@ -1,270 +1,272 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.util;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.data.api.DimLevel;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Node;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ScriptOrFnNode;
import org.mozilla.javascript.Token;
/**
*
*/
public class OlapExpressionCompiler
{
/**
* Get referenced Script Object (dimension, data, measure, etc) according to given object name.
* @param expr
* @param objectName
* @return
*/
public static String getReferencedScriptObject( IBaseExpression expr, String objectName )
{
if ( expr instanceof IScriptExpression )
{
return getReferencedScriptObject( ((IScriptExpression)expr), objectName );
}
else if ( expr instanceof IConditionalExpression )
{
String dimName = null;
IScriptExpression expr1 = ((IConditionalExpression)expr).getExpression( );
dimName = getReferencedScriptObject( expr1, objectName );
if ( dimName!= null )
return dimName;
IScriptExpression op1 = ((IConditionalExpression)expr).getOperand1( );
dimName = getReferencedScriptObject( op1, objectName );
if ( dimName!= null )
return dimName;
IScriptExpression op2 = ((IConditionalExpression)expr).getOperand2( );
dimName = getReferencedScriptObject( op2, objectName );
return dimName;
}
return null;
}
/**
*
* @param expr
* @param objectName
* @return
*/
private static String getReferencedScriptObject( IScriptExpression expr, String objectName )
{
if ( expr == null )
return null;
else
return getReferencedScriptObject( expr.getText( ), objectName);
}
/**
*
* @param expr
* @param objectName
* @return
*/
public static String getReferencedScriptObject( String expr, String objectName )
{
+ if( expr == null )
+ return null;
Context cx = Context.enter();
CompilerEnvirons ce = new CompilerEnvirons();
Parser p = new Parser( ce, cx.getErrorReporter( ) );
ScriptOrFnNode tree = p.parse( expr, null, 0 );
return getScriptObjectName( tree, objectName );
}
/**
*
* @param expr
* @param bindings
* @return
* @throws DataException
*/
public static Set getReferencedDimLevel( IBaseExpression expr, List bindings ) throws DataException
{
return getReferencedDimLevel( expr, bindings, false );
}
/**
* Get set of reference DimLevels.
* @param expr
* @param bindings
* @param onlyFromDirectReferenceExpr
* @return
* @throws DataException
*/
public static Set getReferencedDimLevel( IBaseExpression expr, List bindings, boolean onlyFromDirectReferenceExpr ) throws DataException
{
if ( expr instanceof IScriptExpression )
{
return getReferencedDimLevel( ((IScriptExpression)expr), bindings, onlyFromDirectReferenceExpr );
}
else if ( expr instanceof IConditionalExpression )
{
Set result = new HashSet();
IScriptExpression expr1 = ((IConditionalExpression)expr).getExpression( );
result.addAll( getReferencedDimLevel( expr1, bindings, onlyFromDirectReferenceExpr ));
IScriptExpression op1 = ((IConditionalExpression)expr).getOperand1( );
result.addAll( getReferencedDimLevel( op1, bindings,onlyFromDirectReferenceExpr ));
IScriptExpression op2 = ((IConditionalExpression)expr).getOperand2( );
result.addAll( getReferencedDimLevel( op2, bindings,onlyFromDirectReferenceExpr ));
return result;
}
return null;
}
/**
*
* @param expr
* @param bindings
* @param onlyFromDirectReferenceExpr
* @return
* @throws DataException
*/
private static Set getReferencedDimLevel( IScriptExpression expr, List bindings, boolean onlyFromDirectReferenceExpr ) throws DataException
{
if( expr == null )
return new HashSet();
Set result = new HashSet();
Context cx = Context.enter();
CompilerEnvirons ce = new CompilerEnvirons();
Parser p = new Parser( ce, cx.getErrorReporter( ) );
ScriptOrFnNode tree = p.parse( expr.getText( ), null, 0 );
populateDimLevels( tree, result, bindings, onlyFromDirectReferenceExpr );
return result;
}
/**
*
* @param n
* @param result
* @param bindings
* @param onlyFromDirectReferenceExpr
* @throws DataException
*/
private static void populateDimLevels( Node n, Set result, List bindings, boolean onlyFromDirectReferenceExpr ) throws DataException
{
if ( n == null )
return;
if ( onlyFromDirectReferenceExpr )
{
if ( n.getType( ) == Token.SCRIPT )
{
if ( n.getFirstChild( ) == null
|| n.getFirstChild( ).getType( ) != Token.EXPR_RESULT )
return;
if ( n.getFirstChild( ).getFirstChild( ) == null
||( n.getFirstChild( ).getFirstChild( ).getType( ) != Token.GETPROP
&& n.getFirstChild( ).getFirstChild( ).getType( ) != Token.GETELEM ))
return;
}
}
if ( n.getFirstChild( ) != null
&& ( n.getType( ) == Token.GETPROP || n.getType( ) == Token.GETELEM )
&& n.getFirstChild( ).getType( ) == Token.NAME )
{
if ( "dimension".equals( n.getFirstChild( ).getString( ) ) )
{
if ( n.getLastChild( ) != null && n.getNext( ) != null )
{
String dimName = n.getLastChild( ).getString( );
String levelName = n.getNext( ).getString( );
DimLevel dimLevel = new DimLevel( dimName, levelName );
if ( !result.contains( dimLevel ) )
result.add( dimLevel );
}
}
else if ( "data".equals( n.getFirstChild( ).getString( ) ) )
{
if ( n.getLastChild( ) != null )
{
String bindingName = n.getLastChild( ).getString( );
IBinding binding = getBinding( bindings, bindingName );
if ( binding != null )
{
result.addAll( getReferencedDimLevel( binding.getExpression( ),
bindings, onlyFromDirectReferenceExpr ) );
}
}
}
}
populateDimLevels( n.getFirstChild( ), result, bindings, onlyFromDirectReferenceExpr );
populateDimLevels( n.getLastChild( ), result, bindings, onlyFromDirectReferenceExpr );
}
/**
* Get binding
*
* @param bindings
* @param bindingName
* @return
* @throws DataException
*/
private static IBinding getBinding( List bindings, String bindingName ) throws DataException
{
for( int i = 0; i < bindings.size( ); i++ )
{
if ( ((IBinding)bindings.get( i )).getBindingName( ).equals( bindingName ))
return (IBinding)bindings.get( i );
}
return null;
}
/**
*
* @param n
* @param objectName
* @return
*/
private static String getScriptObjectName( Node n , String objectName )
{
if ( n == null )
return null;
String result = null;
if ( n.getType( ) == Token.NAME )
{
if( objectName.equals( n.getString( ) ))
{
Node dimNameNode = n.getNext( );
if ( dimNameNode == null || dimNameNode.getType( )!= Token.STRING )
return null;
return dimNameNode.getString( );
}
}
result = getScriptObjectName( n.getFirstChild( ), objectName );
if ( result == null )
result = getScriptObjectName( n.getLastChild( ), objectName );
return result;
}
}
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/ICubeQueryUtil.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/ICubeQueryUtil.java
index 981598041..2c8d19809 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/ICubeQueryUtil.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/ICubeQueryUtil.java
@@ -1,48 +1,57 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.data.adapter.api;
import java.util.List;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
/**
*
*/
public interface ICubeQueryUtil
{
/**
* Utility method to acquire referable bindings, either in cube filter or
* cube sort.
*
* @param targetLevel
* @param bindings
* @param isSort
* @return
* @throws AdapterException
*/
- public abstract List getReferableBindings( String targetLevel,
+ public List getReferableBindings( String targetLevel,
ICubeQueryDefinition cubeQueryDefn, boolean isSort ) throws AdapterException;
/**
* Return a list of ILevelDefinition instances that referenced by
*
* @param targetLevel
* @param bindingExpr
* @param queryDefn
* @return
* @throws AdapterException
*/
- public abstract List getReferencedLevels( String targetLevel,
+ public List getReferencedLevels( String targetLevel,
String bindingExpr, ICubeQueryDefinition queryDefn ) throws AdapterException;
+
+ /**
+ * Return the measure name referenced by the expression.
+ *
+ * @param expr
+ * @return
+ * @throws AdapterException
+ */
+ public String getReferencedMeasureName( String expr ) throws AdapterException;
}
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java
index b72658a38..1e13e49ff 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java
@@ -1,202 +1,210 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.data.adapter.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IDimensionDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IEdgeDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IHierarchyDefinition;
import org.eclipse.birt.data.engine.olap.api.query.ILevelDefinition;
import org.eclipse.birt.data.engine.olap.data.api.DimLevel;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionCompiler;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionUtil;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.ICubeQueryUtil;
/**
*
*/
public class CubeQueryUtil implements ICubeQueryUtil
{
/**
* @throws DataException
*
*/
public List getReferableBindings( String targetLevel,
ICubeQueryDefinition cubeDefn, boolean isSort )
throws AdapterException
{
try
{
List bindings = cubeDefn.getBindings( );
if ( bindings == null )
return new ArrayList( );
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
List result = new ArrayList( );
for ( int i = 0; i < bindings.size( ); i++ )
{
IBinding binding = (IBinding) bindings.get( i );
Set refDimLevel = OlapExpressionCompiler.getReferencedDimLevel( binding.getExpression( ),
bindings,
isSort );
if ( refDimLevel.size( ) > 1 )
continue;
if ( !refDimLevel.contains( target ) )
{
List aggrOns = binding.getAggregatOns( );
for ( int j = 0; j < aggrOns.size( ); j++ )
{
DimLevel dimLevel = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j )
.toString( ) );
if ( dimLevel.equals( target ) )
{
//Only add to result list if the target dimLevel is the leaf level
//of its own edge that referenced in aggrOns list.
if( j == aggrOns.size( ) -1 )
result.add( binding );
else
{
DimLevel next = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j+1 )
.toString( ) );
if ( getAxisQualifierLevel( next,
cubeDefn.getEdge( getAxisQualifierEdgeType( dimLevel,
cubeDefn ) ) ) == null )
continue;
else
result.add( binding );
}
break;
}
}
continue;
}
result.add( binding );
}
return result;
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.DataRequestSession#getReferencedLevels(java.lang.String, java.lang.String, org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition)
*/
public List getReferencedLevels( String targetLevel,
String bindingExpr, ICubeQueryDefinition queryDefn ) throws AdapterException
{
try
{
List result = new ArrayList();
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
String bindingName = OlapExpressionCompiler.getReferencedScriptObject( bindingExpr, "data" );
if( bindingName == null )
return result;
IBinding binding = null;
List bindings = queryDefn.getBindings( );
for( int i = 0; i < bindings.size( ); i++ )
{
IBinding bd = (IBinding)bindings.get( i );
if( bd.getBindingName( ).equals( bindingName ))
{
binding = bd;
break;
}
}
if( bindingName == null )
{
return result;
}
List aggrOns = binding.getAggregatOns( );
IEdgeDefinition axisQualifierEdge = queryDefn.getEdge( this.getAxisQualifierEdgeType( target,
queryDefn ) );
for( int i = 0; i < aggrOns.size( ); i++ )
{
DimLevel dimLevel = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( i ).toString( ) );
ILevelDefinition lvl = getAxisQualifierLevel( dimLevel, axisQualifierEdge);
if( lvl != null )
result.add( lvl );
}
return result;
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
private ILevelDefinition getAxisQualifierLevel( DimLevel dimLevel, IEdgeDefinition edge )
{
if( edge == null )
return null;
List dims = edge.getDimensions( );
for( int i = 0; i < dims.size( ); i++ )
{
IDimensionDefinition dim = (IDimensionDefinition)dims.get( i );
if( !dim.getName( ).equals( dimLevel.getDimensionName( ) ))
return null;
IHierarchyDefinition hier = (IHierarchyDefinition)dim.getHierarchy( ).get(0);
List levels = hier.getLevels( );
for( int j = 0; j < levels.size( ); j++ )
{
ILevelDefinition level = (ILevelDefinition)levels.get( j );
if( level.getName( ).equals( dimLevel.getLevelName( ) ))
return level;
}
}
return null;
}
/**
*
* @param dimLevel
* @param queryDefn
* @return
*/
private int getAxisQualifierEdgeType( DimLevel dimLevel, ICubeQueryDefinition queryDefn )
{
IEdgeDefinition edge = queryDefn.getEdge( ICubeQueryDefinition.COLUMN_EDGE );
if( edge == null )
return ICubeQueryDefinition.ROW_EDGE;
List dims = edge.getDimensions( );
for( int i = 0; i < dims.size( ); i++ )
{
IDimensionDefinition dim = (IDimensionDefinition)dims.get( i );
if( dim.getName( ).equals( dimLevel.getDimensionName( ) ))
{
return ICubeQueryDefinition.ROW_EDGE;
}
}
return ICubeQueryDefinition.COLUMN_EDGE;
}
-
+ /**
+ *
+ * @param expr
+ * @return
+ */
+ public String getReferencedMeasureName( String expr )
+ {
+ return OlapExpressionCompiler.getReferencedScriptObject( expr, "measure" );
+ }
}
| false | false | null | null |
diff --git a/felux/src/main/java/com/lifecity/felux/ItemListFragment.java b/felux/src/main/java/com/lifecity/felux/ItemListFragment.java
index 62ad623..fde2971 100644
--- a/felux/src/main/java/com/lifecity/felux/ItemListFragment.java
+++ b/felux/src/main/java/com/lifecity/felux/ItemListFragment.java
@@ -1,308 +1,309 @@
package com.lifecity.felux;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.lifecity.felux.items.Item;
import java.util.List;
/**
*
*/
public abstract class ItemListFragment<T> extends ListFragment implements ItemDetailCallbacks<Item>, FeluxManagerCallbacks {
protected ArrayAdapter<T> adapter;
protected List<T> items;
protected FeluxManager manager;
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
public static String TAG;
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
protected ItemListCallbacks itemListCallbacks = emptyItemListCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
protected int mActivatedPosition = ListView.INVALID_POSITION;
protected static class EmptyItemListCallbacks implements ItemListCallbacks<Item> {
@Override
public void onItemSelected(int position, Item item) {
}
@Override
public void onItemAdded(Item item) {
}
@Override
public void onItemUpdated(Item item) {
}
}
public void setFeluxManager(FeluxManager manager) {
this.manager = manager;
}
public int getNumItems() {
return items.size();
}
public T getItemAt(int index) {
return items.get(index);
}
/**
*/
protected static ItemListCallbacks emptyItemListCallbacks = new EmptyItemListCallbacks();
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemListFragment() {
setRetainInstance(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
-
- adapter = new ArrayAdapter<T>(
- getActivity(),
- android.R.layout.simple_list_item_activated_1,
- android.R.id.text1,
- items
- );
-
- setListAdapter(adapter);
setHasOptionsMenu(true);
+ updateAdapter();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_list, container, false);
}
@Override
@SuppressWarnings("unchecked")
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
// Restore the previously serialized activated item position.
ListView listView = getListView();
int position = listView.getCount() == 0 ? -1 : listView.getCheckedItemPosition();
if (position < 0 && items.size() > 0) {
position = 0;
listView.setItemChecked(position, true);
}
itemListCallbacks.onItemSelected(position, position < 0 ? null : items.get(position));
getActivity().invalidateOptionsMenu();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof ItemListCallbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
itemListCallbacks = (ItemListCallbacks) activity;
}
@Override
public void onPause() {
super.onPause();
Log.i(this.getClass().getSimpleName(), "onPause");
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
itemListCallbacks = emptyItemListCallbacks;
Log.i(this.getClass().getSimpleName(), "onDetach");
}
@Override
@SuppressWarnings("unchecked")
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
itemListCallbacks.onItemSelected(0, items.get(position));
getActivity().invalidateOptionsMenu();
}
@SuppressWarnings("unchecked")
public void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
itemListCallbacks.onItemSelected(-1, null);
} else {
getListView().setItemChecked(position, true);
itemListCallbacks.onItemSelected(position, items.get(position));
}
getActivity().invalidateOptionsMenu();
mActivatedPosition = position;
}
@SuppressWarnings("unchecked")
public void addItem(T item) {
items.add(item);
adapter.notifyDataSetChanged();
itemListCallbacks.onItemAdded(item);
}
public void removeItem(T item) {
int oldPosition = selectedPosition();
int newPosition = oldPosition == 0 ? 0 : oldPosition - 1;
items.remove(item);
adapter.notifyDataSetChanged();
if (items.size() == 0) {
newPosition = -1;
}
setActivatedPosition(newPosition);
}
public void moveItem(T item, boolean down) {
int oldPosition = selectedPosition();
int newPosition;
if (down) {
if (oldPosition < (items.size() - 1)) {
newPosition = oldPosition + 1;
} else {
return;
}
} else {
if (oldPosition > 0) {
newPosition = oldPosition - 1;
} else {
return;
}
}
T temp = items.get(newPosition);
items.set(newPosition, item);
items.set(oldPosition, temp);
adapter.notifyDataSetChanged();
setActivatedPosition(newPosition);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_list_menu, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
int position = selectedPosition();
MenuItem upItem = menu.findItem(R.id.item_moveup);
MenuItem downItem = menu.findItem(R.id.item_movedown);
MenuItem copyItem = menu.findItem(R.id.item_copy);
MenuItem removeItem = menu.findItem(R.id.item_remove);
copyItem.setVisible(items.size() > 0);
removeItem.setVisible(items.size() > 0);
if (position >= 0 && items.size() > 0) {
if (upItem != null) {
upItem.setVisible(position > 0);
}
if (downItem != null) {
downItem.setVisible(position < (items.size() - 1));
}
} else {
if (upItem != null) {
upItem.setVisible(false);
}
if (downItem != null) {
downItem.setVisible(false);
}
}
}
public int selectedPosition() {
return getListView().getCheckedItemPosition();
}
public T selectedItem() {
return items.get(selectedPosition());
}
@Override
@SuppressWarnings("unchecked")
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_moveup:
moveItem(selectedItem(), false);
return true;
case R.id.item_movedown:
moveItem(selectedItem(), true);
return true;
case R.id.item_copy:
addItem((T)((Item)selectedItem()).copy());
return true;
case R.id.item_remove:
ConfirmDialogFragment dialog = new ConfirmDialogFragment("Delete", "Are you sure you want to delete this?", new ConfirmDialogFragment.ConfirmDialogListener() {
@Override
public void onConfirm() {
removeItem(selectedItem());
getActivity().invalidateOptionsMenu();
}
});
dialog.show(getActivity().getSupportFragmentManager(), "confirm_remove_dialog_tag");
return true;
/*case R.id.item_edit:
startActionMode();
return true;
*/
case R.id.item_add:
getActivity().invalidateOptionsMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
@SuppressWarnings("unchecked")
public void onItemDetailUpdated(Item item) {
adapter.notifyDataSetChanged();
itemListCallbacks.onItemUpdated(item);
}
@Override
public void onItemDetailAdded(Item item) {
setActivatedPosition(items.size() - 1);
}
+ private void updateAdapter() {
+ adapter = new ArrayAdapter<T>(
+ getActivity(),
+ android.R.layout.simple_list_item_activated_1,
+ android.R.id.text1,
+ items
+ );
+
+ setListAdapter(adapter);
+ }
+
@Override
public void onItemsLoaded(FeluxManager manager) {
- adapter.clear();
- adapter.addAll(items);
- adapter.notifyDataSetChanged();
+ updateAdapter();
if (adapter.getCount() > 0) {
setActivatedPosition(0);
}
}
}
| false | false | null | null |
diff --git a/src/calculator/Calculator.java b/src/calculator/Calculator.java
index 1e86f55..8d96310 100644
--- a/src/calculator/Calculator.java
+++ b/src/calculator/Calculator.java
@@ -1,20 +1,20 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-package calculator;
-
-/**
- *
- * @author Maxxx
- */
-public class Calculator {
-
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- Calc abc=new Calc();
- abc.setVisible(true);
- }
-}
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package calculator;
+
+/**
+ *
+ * @author Maxxx
+ */
+public class Calculator {
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String[] args) {
+ Calc abc=new Calc();
+ abc.setVisible(true);
+ }
+}
| true | false | null | null |
diff --git a/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java b/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java
index ff868f0..7e747d9 100644
--- a/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java
+++ b/src/main/java/org/apache/maven/plugins/shade/DefaultShader.java
@@ -1,372 +1,366 @@
package org.apache.maven.plugins.shade;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipException;
import org.apache.maven.plugins.shade.relocation.Relocator;
import org.apache.maven.plugins.shade.resource.ResourceTransformer;
import org.apache.maven.plugins.shade.filter.Filter;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.IOUtil;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingClassAdapter;
/**
* @author Jason van Zyl
* @plexus.component
*/
public class DefaultShader
extends AbstractLogEnabled
implements Shader
{
public void shade( Set jars, File uberJar, List filters, List relocators, List resourceTransformers )
throws IOException
{
Set resources = new HashSet();
RelocatorRemapper remapper = new RelocatorRemapper( relocators );
uberJar.getParentFile().mkdirs();
JarOutputStream jos = new JarOutputStream( new FileOutputStream( uberJar ) );
for ( Iterator i = jars.iterator(); i.hasNext(); )
{
File jar = (File) i.next();
List jarFilters = getFilters( jar, filters );
JarFile jarFile = new JarFile( jar );
for ( Enumeration j = jarFile.entries(); j.hasMoreElements(); )
{
JarEntry entry = (JarEntry) j.nextElement();
String name = entry.getName();
if ( "META-INF/INDEX.LIST".equals( name ) )
{
//we cannot allow the jar indexes to be copied over or the
//jar is useless. Ideally, we could create a new one
//later
continue;
}
String mappedName = remapper.map( name );
InputStream is = jarFile.getInputStream( entry );
if ( !entry.isDirectory() && !isFiltered( jarFilters, name ) )
{
int idx = mappedName.lastIndexOf( '/' );
if ( idx != -1 )
{
//make sure dirs are created
String dir = mappedName.substring( 0, idx );
if ( !resources.contains( dir ) )
{
addDirectory( resources, jos, dir );
}
}
if ( name.endsWith( ".class" ) )
{
addRemappedClass( remapper, jos, jar, name, is );
}
else
{
if ( !resourceTransformed( resourceTransformers, mappedName, is ) )
{
// Avoid duplicates that aren't accounted for by the resource transformers
if ( resources.contains( mappedName ) )
{
continue;
}
addResource( resources, jos, mappedName, is );
}
}
}
IOUtil.close( is );
}
jarFile.close();
}
for ( Iterator i = resourceTransformers.iterator(); i.hasNext(); )
{
ResourceTransformer transformer = (ResourceTransformer) i.next();
if ( transformer.hasTransformedResource() )
{
transformer.modifyOutputStream( jos );
}
}
IOUtil.close( jos );
}
private List getFilters( File jar, List filters )
{
List list = new ArrayList();
for ( int i = 0; i < filters.size(); i++ )
{
Filter filter = (Filter) filters.get( i );
if ( filter.canFilter( jar ) )
{
list.add( filter );
}
}
return list;
}
private void addDirectory( Set resources, JarOutputStream jos, String name )
throws IOException
{
if ( name.lastIndexOf( '/' ) > 0 )
{
String parent = name.substring( 0, name.lastIndexOf( '/' ) );
if ( !resources.contains( parent ) )
{
addDirectory( resources, jos, parent );
}
}
//directory entries must end in "/"
JarEntry entry = new JarEntry( name + "/" );
jos.putNextEntry( entry );
resources.add( name );
}
private void addRemappedClass( RelocatorRemapper remapper, JarOutputStream jos, File jar, String name,
InputStream is )
throws IOException
{
if ( !remapper.hasRelocators() )
{
try
{
jos.putNextEntry( new JarEntry( name ) );
IOUtil.copy( is, jos );
}
catch ( ZipException e )
{
getLogger().warn( "We have a duplicate " + name + " in " + jar );
}
return;
}
ClassReader cr = new ClassReader( is );
ClassWriter cw = new ClassWriter( cr, 0 );
ClassVisitor cv = new RemappingClassAdapter( cw, remapper );
cr.accept( cv, ClassReader.EXPAND_FRAMES );
byte[] renamedClass = cw.toByteArray();
// Need to take the .class off for remapping evaluation
String mappedName = remapper.map( name.substring( 0, name.indexOf( '.' ) ) );
try
{
// Now we put it back on so the class file is written out with the right extension.
jos.putNextEntry( new JarEntry( mappedName + ".class" ) );
IOUtil.copy( renamedClass, jos );
}
catch ( ZipException e )
{
getLogger().warn( "We have a duplicate " + mappedName + " in " + jar );
}
}
private boolean isFiltered( List filters, String name )
{
for ( int i = 0; i < filters.size(); i++ )
{
Filter filter = (Filter) filters.get( i );
if ( filter.isFiltered( name ) )
{
return true;
}
}
return false;
}
private boolean resourceTransformed( List resourceTransformers, String name, InputStream is )
throws IOException
{
boolean resourceTransformed = false;
for ( Iterator k = resourceTransformers.iterator(); k.hasNext(); )
{
ResourceTransformer transformer = (ResourceTransformer) k.next();
if ( transformer.canTransformResource( name ) )
{
transformer.processResource( is );
resourceTransformed = true;
break;
}
}
return resourceTransformed;
}
private void addResource( Set resources, JarOutputStream jos, String name, InputStream is )
throws IOException
{
jos.putNextEntry( new JarEntry( name ) );
IOUtil.copy( is, jos );
resources.add( name );
}
class RelocatorRemapper
extends Remapper
{
List relocators;
public RelocatorRemapper( List relocators )
{
this.relocators = relocators;
}
public boolean hasRelocators()
{
return !relocators.isEmpty();
}
public Object mapValue( Object object )
{
if ( object instanceof String )
{
String name = (String) object;
String value = name;
for ( Iterator i = relocators.iterator(); i.hasNext(); )
{
Relocator r = (Relocator) i.next();
- if ( r.canRelocatePath( name ) )
- {
- value = r.relocatePath( name );
- break;
- }
-
if ( r.canRelocateClass( name ) )
{
value = r.relocateClass( name );
break;
+ }
+ else if ( r.canRelocatePath( name ) )
+ {
+ value = r.relocatePath( name );
+ break;
}
+
if ( name.length() > 0 && name.charAt( 0 ) == '[' )
{
int count = 0;
while ( name.length() > 0 && name.charAt(0) == '[' )
{
name = name.substring( 1 );
++count;
}
if ( name.length() > 0
&& name.charAt( 0 ) == 'L'
&& name.charAt( name.length() - 1 ) == ';' )
{
name = name.substring( 1, name.length() - 1 );
if ( r.canRelocatePath( name ) )
{
value = 'L' + r.relocatePath( name ) + ';';
while ( count > 0 )
{
value = '[' + value;
--count;
}
break;
}
if ( r.canRelocateClass( name ) )
{
value = 'L' + r.relocateClass( name ) + ';';
while (count > 0)
{
value = '[' + value;
--count;
}
break;
}
}
}
}
-
return value;
}
- else
- {
- object = super.mapValue( object );
- }
- return object;
+ return super.mapValue( object );
}
public String map( String name )
{
String value = name;
for ( Iterator i = relocators.iterator(); i.hasNext(); )
{
Relocator r = (Relocator) i.next();
if ( r.canRelocatePath( name ) )
{
value = r.relocatePath( name );
break;
}
}
-
return value;
}
}
}
diff --git a/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java b/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java
index f9f4445..cb7fe18 100644
--- a/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java
+++ b/src/main/java/org/apache/maven/plugins/shade/relocation/SimpleRelocator.java
@@ -1,118 +1,118 @@
package org.apache.maven.plugins.shade.relocation;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.codehaus.plexus.util.SelectorUtils;
/**
* @author Jason van Zyl
* @author Mauro Talevi
*/
public class SimpleRelocator
implements Relocator
{
private String pattern;
private String pathPattern;
private String shadedPattern;
private String shadedPathPattern;
private Set excludes;
public SimpleRelocator( String patt, String shadedPattern, List excludes )
{
this.pattern = patt.replace( '/', '.' );
this.pathPattern = patt.replace( '.', '/' );
if ( shadedPattern != null )
{
this.shadedPattern = shadedPattern.replace( '/', '.' );
this.shadedPathPattern = shadedPattern.replace( '.', '/' );
}
else
{
this.shadedPattern = "hidden." + this.pattern;
this.shadedPathPattern = "hidden/" + this.pathPattern;
}
if ( excludes != null && !excludes.isEmpty() )
{
this.excludes = new LinkedHashSet();
for ( Iterator i = excludes.iterator(); i.hasNext(); )
{
String e = (String) i.next();
String classExclude = e.replace( '.', '/' );
this.excludes.add( classExclude );
if ( classExclude.endsWith( "/*" ) )
{
String packageExclude = classExclude.substring( 0, classExclude.lastIndexOf( '/' ) );
this.excludes.add( packageExclude );
}
}
}
}
public boolean canRelocatePath( String path )
{
if ( path.endsWith( ".class" ) )
{
path = path.substring( 0, path.length() - 6 );
}
if ( excludes != null )
{
for ( Iterator i = excludes.iterator(); i.hasNext(); )
{
String exclude = (String) i.next();
if ( SelectorUtils.matchPath( exclude, path, true ) )
{
return false;
}
}
}
return path.startsWith( pathPattern );
}
public boolean canRelocateClass( String clazz )
{
- return canRelocatePath( clazz.replace( '.', '/' ) );
+ return !clazz.contains("/") && canRelocatePath( clazz.replace( '.', '/' ) );
}
public String relocatePath( String path )
{
return path.replaceFirst( pathPattern, shadedPathPattern );
}
public String relocateClass( String clazz )
{
return clazz.replaceFirst( pattern, shadedPattern );
}
}
| false | false | null | null |
diff --git a/src/com/ichi2/anki/Media.java b/src/com/ichi2/anki/Media.java
index 7c1220d7..34ad3b99 100644
--- a/src/com/ichi2/anki/Media.java
+++ b/src/com/ichi2/anki/Media.java
@@ -1,332 +1,332 @@
/****************************************************************************************
* Copyright (c) 2011 Kostas Spyropoulos <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import android.database.Cursor;
import android.util.Log;
import java.io.File;
-import java.io.FileInputStream;
-import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Class with static functions related with media handling (images and sounds).
*/
public class Media {
// TODO: Javadoc.
private static final Pattern mMediaRegexps[] = {
Pattern.compile("(?i)(\\[sound:([^]]+)\\])"),
Pattern.compile("(?i)(<img[^>]+src=[\"']?([^\"'>]+)[\"']?[^>]*>)")
};
private static final Pattern regPattern = Pattern.compile("\\((\\d+)\\)$");
// File Handling
// *************
/**
* Copy PATH to MEDIADIR, and return new filename.
* If a file with the same md5sum exists in the DB, return that.
* If a file with the same name exists, return a unique name.
* This does not modify the media table.
*
* @param deck The deck whose media we are dealing with
* @param path The path and filename of the media file we are adding
* @return The new filename.
*/
public static String copyToMedia(Deck deck, String path) {
// See if have duplicate contents
String newpath = null;
Cursor cursor = null;
try {
cursor = deck.getDB().getDatabase().rawQuery("SELECT filename FROM media WHERE originalPath = '" +
Utils.fileChecksum(path) + "'", null);
if (cursor.moveToNext()) {
newpath = cursor.getString(0);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
if (newpath == null) {
File file = new File(path);
String base = file.getName();
String mdir = deck.mediaDir(true);
newpath = uniquePath(mdir, base);
if (!file.renameTo(new File(newpath))) {
Log.e(AnkiDroidApp.TAG, "Couldn't move media file " + path + " to " + newpath);
}
}
return newpath.substring(newpath.lastIndexOf("/") + 1);
}
/**
* Makes sure the filename of the media is unique.
* If the filename matches an existing file, then a counter of the form " (x)" is appended before the media file
* extension, where x = 1, 2, 3... as needed so that the filename is unique.
*
* @param dir The path to the media file, excluding the filename
* @param base The filename of the file without the path
*/
private static String uniquePath(String dir, String base) {
// Remove any dangerous characters
base = base.replaceAll("[][<>:/\\", "");
// Find a unique name
int extensionOffset = base.lastIndexOf(".");
String root = base.substring(0, extensionOffset);
String ext = base.substring(extensionOffset);
File file = null;
while (true) {
file = new File(dir, root + ext);
if (!file.exists()) {
break;
}
Matcher regMatcher = regPattern.matcher(root);
if (!regMatcher.find()) {
root = root + " (1)";
} else {
int num = Integer.parseInt(regMatcher.group(1));
root = root.substring(regMatcher.start()) + " (" + num + ")";
}
}
return dir + "/" + root + ext;
}
// DB Routines
// ***********
/**
* Updates the field size of a media record.
* The field size is used to store the count of how many times is this media referenced in question and answer
* fields of the cards in the deck.
*
* @param deck The deck that contains the media we are dealing with
* @param file The full path of the media in question
*/
public static void updateMediaCount(Deck deck, String file) {
updateMediaCount(deck, file, 1);
}
public static void updateMediaCount(Deck deck, String file, int count) {
String mdir = deck.mediaDir();
if (deck.getDB().queryScalar("SELECT 1 FROM media WHERE filename = '" + file + "'") == 1l) {
deck.getDB().getDatabase().execSQL(String.format(Utils.ENGLISH_LOCALE,
"UPDATE media SET size = size + %d, created = %f WHERE filename = '%s'",
count, Utils.now(), file));
} else if (count > 0) {
String sum = Utils.fileChecksum(file);
deck.getDB().getDatabase().execSQL(String.format(Utils.ENGLISH_LOCALE, "INSERT INTO media " +
"(id, filename, size, created, originalPath, description) " +
"VALUES (%d, '%s', %d, %f, '%s', '')", Utils.genID(), file, count, Utils.now(), sum));
}
}
/**
* Deletes from media table any entries that are not referenced in question or answer of any card.
*
* @param deck The deck that this operation will be performed on
*/
public static void removeUnusedMedia(Deck deck) {
ArrayList<Long> ids = deck.getDB().queryColumn(Long.class, "SELECT id FROM media WHERE size = 0", 0);
for (Long id : ids) {
deck.getDB().getDatabase().execSQL(String.format(Utils.ENGLISH_LOCALE, "INSERT INTO mediaDeleted " +
"VALUES (%d, %f)", id.longValue(), Utils.now()));
}
deck.getDB().getDatabase().execSQL("DELETE FROM media WHERE size = 0");
}
// String manipulation
// *******************
public static ArrayList<String> mediaFiles(String string) {
return mediaFiles(string, false);
}
public static ArrayList<String> mediaFiles(String string, boolean remote) {
boolean isLocal = false;
ArrayList<String> l = new ArrayList<String>();
for (Pattern reg : mMediaRegexps) {
Matcher m = reg.matcher(string);
while (m.find()) {
isLocal = !m.group(2).toLowerCase().matches("(https?|ftp)://");
if (!remote && isLocal) {
l.add(m.group(2));
} else if (remote && !isLocal) {
l.add(m.group(2));
}
}
}
return l;
}
/**
* Removes references of media from a string.
*
* @param txt The string to be cleared of any media references
* @return The cleared string without any media references
*/
public static String stripMedia(String txt) {
for (Pattern reg : mMediaRegexps) {
txt = reg.matcher(txt).replaceAll("");
}
return txt;
}
// Rebuilding DB
// *************
/**
* Rebuilds the reference counts, potentially deletes unused media files,
*
* @param deck The deck to perform the operation on
* @param delete If true, then unused (unreferenced in question/answer fields) media files will be deleted
* @param dirty If true, then the modified field of deck will be updated
* @return Nothing, but the original python code returns a list of unreferenced media files and a list
* of missing media files (referenced in question/answer fields, but with the actual files missing)
*/
public static void rebuildMediaDir(Deck deck) {
rebuildMediaDir(deck, false, true);
}
public static void rebuildMediaDir(Deck deck, boolean delete) {
rebuildMediaDir(deck, delete, true);
}
public static void rebuildMediaDir(Deck deck, boolean delete, boolean dirty) {
String mdir = deck.mediaDir();
if (mdir == null) {
return;
}
//Set all ref counts to 0
deck.getDB().getDatabase().execSQL("UPDATE media SET size = 0");
// Look through the cards for media references
Cursor cursor = null;
String txt = null;
Map<String, Integer> refs = new HashMap<String, Integer>();
Set<String> normrefs = new HashSet<String>();
try {
cursor = deck.getDB().getDatabase().rawQuery("SELECT question, answer FROM cards", null);
while (cursor.moveToNext()) {
for (int i = 0; i < 2; i++) {
txt = cursor.getString(i);
for (String f : mediaFiles(txt)) {
if (refs.containsKey(f)) {
refs.put(f, refs.get(f) + 1);
} else {
refs.put(f, 1);
- normrefs.add(Normalizer.normalize(f, Normalizer.Form.NFC));
+ // normrefs.add(Normalizer.normalize(f, Normalizer.Form.NFC));
+ normrefs.add(f);
}
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// Update ref counts
for (String fname : refs.keySet()) {
updateMediaCount(deck, fname, refs.get(fname));
}
String fname = null;
//If there is no media dir, then there is nothing to find.
if(mdir != null) {
// Find unused media
Set<String> unused = new HashSet<String>();
File mdirfile = new File(mdir);
if (mdirfile.exists()) {
fname = null;
for (File f : mdirfile.listFiles()) {
if (!f.isFile()) {
// Ignore directories
continue;
}
- fname = Normalizer.normalize(f.getName(), Normalizer.Form.NFC);
+ // fname = Normalizer.normalize(f.getName(), Normalizer.Form.NFC);
+ fname = f.getName();
if (!normrefs.contains(fname)) {
unused.add(fname);
}
}
}
// Optionally delete
if (delete) {
for (String fn : unused) {
File file = new File(mdir + "/" + fn);
try {
if (!file.delete()) {
Log.e(AnkiDroidApp.TAG, "Couldn't delete unused media file " + mdir + "/" + fn);
}
} catch (SecurityException e) {
Log.e(AnkiDroidApp.TAG, "Security exception while deleting unused media file " + mdir + "/" + fn);
}
}
}
}
// Remove entries in db for unused media
removeUnusedMedia(deck);
// Check md5s are up to date
cursor = null;
String path = null;
fname = null;
String md5 = null;
deck.getDB().getDatabase().beginTransaction();
try {
cursor = deck.getDB().getDatabase().rawQuery("SELECT filename, created, originalPath FROM media", null);
while (cursor.moveToNext()) {
fname = cursor.getString(0);
md5 = cursor.getString(2);
path = mdir + "/" + fname;
File file = new File(path);
if (!file.exists()) {
if (!md5.equals("")) {
deck.getDB().getDatabase().execSQL("UPDATE media SET originalPath = '', created = " +
cursor.getString(1) + ", filename = '" + fname + "'");
}
} else {
String sum = Utils.fileChecksum(path);
if (!md5.equals(sum)) {
deck.getDB().getDatabase().execSQL("UPDATE media SET originalPath = '" + sum +
"', created = " + cursor.getString(1) + ", filename = '" + fname + "'");
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
deck.getDB().getDatabase().setTransactionSuccessful();
deck.getDB().getDatabase().endTransaction();
// Update deck and get return info
if (dirty) {
deck.flushMod();
}
// In contrast to the python code we don't return anything. In the original python code, the return
// values are used in a function (media.onCheckMediaDB()) that we don't have in AnkiDroid.
}
}
| false | false | null | null |
diff --git a/android/Airliners/src/net/taviscaron/airliners/activities/AircraftInfoActivity.java b/android/Airliners/src/net/taviscaron/airliners/activities/AircraftInfoActivity.java
index de455da..976521e 100644
--- a/android/Airliners/src/net/taviscaron/airliners/activities/AircraftInfoActivity.java
+++ b/android/Airliners/src/net/taviscaron/airliners/activities/AircraftInfoActivity.java
@@ -1,149 +1,151 @@
package net.taviscaron.airliners.activities;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import net.taviscaron.airliners.R;
import net.taviscaron.airliners.fragments.AircraftInfoFragment;
import net.taviscaron.airliners.model.AircraftPhoto;
import net.taviscaron.airliners.views.AlbumNavigationBar;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Shows aircraft information
* @author Andrei Senchuk
*/
public class AircraftInfoActivity extends SherlockFragmentActivity implements AircraftInfoFragment.StateListener {
public static final String AIRCRAFT_INFO_ACTION = "net.taviscaron.airliners.AIRCRAFT_INFO";
public static final String AIRCRAFT_ID_KEY = "aircraftId";
private AircraftInfoFragment fragment;
private AlbumNavigationBar albumNavigationBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aircraft_info);
fragment = (AircraftInfoFragment)getSupportFragmentManager().findFragmentById(R.id.aircraft_info_fragment);
albumNavigationBar = (AlbumNavigationBar)findViewById(R.id.aircraft_info_album_nav_bar);
albumNavigationBar.setListener(albumNavigationBarListener);
// state is not restoring
if(savedInstanceState == null) {
String id = null;
Intent intent = getIntent();
if(intent != null) {
if(AIRCRAFT_INFO_ACTION.equals(intent.getAction())) {
id = intent.getStringExtra(AIRCRAFT_ID_KEY);
} else if(Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
Matcher matcher = Pattern.compile("/photo(/.*?)*?/(\\d+)").matcher(uri.getPath());
if(matcher.find()) {
id = matcher.group(2);
}
}
}
if(id != null) {
fragment.loadAircraft(id);
}
} else {
AircraftPhoto photo = fragment.getAircraftPhoto();
onAircraftInfoLoaded(photo);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.aircraft_info_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.aircraft_info_action_set_wallpaper:
setImageAsWallpaper();
break;
case R.id.aircraft_info_action_share:
shareAircraftPhoto();
break;
default:
result = super.onOptionsItemSelected(item);
break;
}
return result;
}
private void setImageAsWallpaper() {
String photoPath = fragment.getAircraftPhotoPath();
if(photoPath != null && new File(photoPath).exists()) {
startActivity(new Intent(SetWallpaperActivity.SET_WALLPAPER_ACTION).putExtra(SetWallpaperActivity.IMAGE_PATH_EXTRA, photoPath));
}
}
private void shareAircraftPhoto() {
String photoPath = fragment.getAircraftPhotoPath();
AircraftPhoto aircraftPhoto = fragment.getAircraftPhoto();
if(photoPath == null || aircraftPhoto == null) {
return;
}
File photoFile = new File(photoPath);
if(photoFile.exists()) {
String siteUrl = getString(R.string.config_site_photo_url, aircraftPhoto.getId());
String text = String.format("%s %s %s", aircraftPhoto.getAirline(), aircraftPhoto.getAircraft(), siteUrl);
Uri photoUri = Uri.fromFile(photoFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.action_share)));
}
}
@Override
public void onAircraftInfoLoadStarted(String id) {
albumNavigationBar.setEnabled(false);
}
@Override
public void onAircraftInfoLoaded(AircraftPhoto photo) {
albumNavigationBar.setEnabled(true);
- long count = photo.getCount();
- long pos = photo.getPos();
- if(pos >= 0 && pos <= count) {
- albumNavigationBar.setPosition(pos, count);
+ if(photo != null) {
+ long count = photo.getCount();
+ long pos = photo.getPos();
+ if(pos >= 0 && pos <= count) {
+ albumNavigationBar.setPosition(pos, count);
+ }
}
}
private final AlbumNavigationBar.AlbumNavigationBarListener albumNavigationBarListener = new AlbumNavigationBar.AlbumNavigationBarListener() {
@Override
public void next() {
AircraftPhoto aircraftPhoto = fragment.getAircraftPhoto();
if(aircraftPhoto != null && aircraftPhoto.getNext() != null) {
fragment.loadAircraft(aircraftPhoto.getNext());
}
}
@Override
public void prev() {
AircraftPhoto aircraftPhoto = fragment.getAircraftPhoto();
if(aircraftPhoto != null && aircraftPhoto.getPrev() != null) {
fragment.loadAircraft(aircraftPhoto.getPrev());
}
}
};
}
| true | false | null | null |
Subsets and Splits