diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/compiler/src/main/java/dagger/internal/codegen/FullGraphProcessor.java b/compiler/src/main/java/dagger/internal/codegen/FullGraphProcessor.java
index 5d43ab75..1911fef6 100644
--- a/compiler/src/main/java/dagger/internal/codegen/FullGraphProcessor.java
+++ b/compiler/src/main/java/dagger/internal/codegen/FullGraphProcessor.java
@@ -1,253 +1,255 @@
/*
* Copyright (C) 2012 Square, 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 dagger.internal.codegen;
import dagger.Module;
import dagger.Provides;
import dagger.internal.Binding;
import dagger.internal.Linker;
import dagger.internal.ProblemDetector;
import dagger.internal.SetBinding;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.inject.Singleton;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.StandardLocation;
/**
* Performs full graph analysis on a module.
*/
@SupportedAnnotationTypes("dagger.Module")
public final class FullGraphProcessor extends AbstractProcessor {
private final Set<String> delayedModuleNames = new LinkedHashSet<String>();
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
/**
* Perform full-graph analysis on complete modules. This checks that all of
* the module's dependencies are satisfied.
*/
@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) {
if (!env.processingOver()) {
// Storing module names for later retrieval as the element instance is invalidated across
// passes.
for (Element e : env.getElementsAnnotatedWith(Module.class)) {
if (!(e instanceof TypeElement)) {
error("@Module applies to a type, " + e.getSimpleName() + " is a " + e.getKind(), e);
continue;
}
delayedModuleNames.add(((TypeElement) e).getQualifiedName().toString());
}
return true;
}
Set<Element> modules = new LinkedHashSet<Element>();
for (String moduleName : delayedModuleNames) {
modules.add(processingEnv.getElementUtils().getTypeElement(moduleName));
}
for (Element element : modules) {
Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element);
if (!annotation.get("complete").equals(Boolean.TRUE)) {
continue;
}
TypeElement moduleType = (TypeElement) element;
Map<String, Binding<?>> bindings = processCompleteModule(moduleType);
try {
new ProblemDetector().detectProblems(bindings.values());
} catch (IllegalStateException e) {
error("Graph validation failed: " + e.getMessage(), moduleType);
continue;
}
try {
writeDotFile(moduleType, bindings);
} catch (IOException e) {
error("Graph visualization failed: " + e, moduleType);
}
}
return true;
}
private void error(String message, Element element) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
}
private Map<String, Binding<?>> processCompleteModule(TypeElement rootModule) {
Map<String, TypeElement> allModules = new LinkedHashMap<String, TypeElement>();
collectIncludesRecursively(rootModule, allModules);
Linker linker = new Linker(null, new CompileTimePlugin(processingEnv),
new ReportingErrorHandler(processingEnv, rootModule.getQualifiedName().toString()));
// Linker requires synchronization for calls to requestBinding and linkAll.
// We know statically that we're single threaded, but we synchronize anyway
// to make the linker happy.
synchronized (linker) {
Map<String, Binding<?>> baseBindings = new LinkedHashMap<String, Binding<?>>();
Map<String, Binding<?>> overrideBindings = new LinkedHashMap<String, Binding<?>>();
for (TypeElement module : allModules.values()) {
Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, module);
boolean overrides = (Boolean) annotation.get("overrides");
Map<String, Binding<?>> addTo = overrides ? overrideBindings : baseBindings;
// Gather the entry points from the annotation.
for (Object entryPoint : (Object[]) annotation.get("entryPoints")) {
linker.requestBinding(GeneratorKeys.rawMembersKey((TypeMirror) entryPoint),
module.getQualifiedName().toString(), false);
}
// Gather the static injections.
// TODO.
// Gather the enclosed @Provides methods.
for (Element enclosed : module.getEnclosedElements()) {
Provides provides = enclosed.getAnnotation(Provides.class);
if (provides == null) {
continue;
}
ExecutableElement providerMethod = (ExecutableElement) enclosed;
String key = GeneratorKeys.get(providerMethod);
ProviderMethodBinding binding = new ProviderMethodBinding(key, providerMethod);
switch (provides.type()) {
case UNIQUE:
ProviderMethodBinding clobbered = (ProviderMethodBinding) addTo.put(key, binding);
if (clobbered != null) {
- processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
- "Multiple bindings for " + key
- + " found in override module(s) - cannot override an override: "
- + shortMethodName(clobbered.method)
- + ", " + shortMethodName(binding.method),
+ String msg = "Duplicate bindings for " + key;
+ if (overrides) {
+ msg += " in override module(s) - cannot override an override";
+ }
+ msg += ": " + shortMethodName(clobbered.method)
+ + ", " + shortMethodName(binding.method);
+ processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg,
binding.method);
}
break;
case SET:
String elementKey = GeneratorKeys.getElementKey(providerMethod);
SetBinding.add(addTo, elementKey, binding);
break;
default:
throw new AssertionError("Unknown @Provides type " + provides.type());
}
}
}
linker.installBindings(baseBindings);
linker.installBindings(overrideBindings);
// Link the bindings. This will traverse the dependency graph, and report
// errors if any dependencies are missing.
return linker.linkAll();
}
}
private String shortMethodName(ExecutableElement method) {
return method.getEnclosingElement().getSimpleName().toString()
+ "." + method.getSimpleName() + "()";
}
private void collectIncludesRecursively(TypeElement module, Map<String, TypeElement> result) {
Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, module);
if (annotation == null) {
// TODO(tbroyer): pass annotation information
error("No @Module on " + module, module);
return;
}
// Add the module.
result.put(module.getQualifiedName().toString(), module);
// Recurse for each included module.
Types typeUtils = processingEnv.getTypeUtils();
List<Object> seedModules = new ArrayList<Object>();
seedModules.addAll(Arrays.asList((Object[]) annotation.get("includes")));
if (!annotation.get("addsTo").equals(Void.class)) seedModules.add(annotation.get("addsTo"));
for (Object include : seedModules) {
if (!(include instanceof TypeMirror)) {
// TODO(tbroyer): pass annotation information
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
"Unexpected value for include: " + include + " in " + module, module);
continue;
}
TypeElement includedModule = (TypeElement) typeUtils.asElement((TypeMirror) include);
collectIncludesRecursively(includedModule, result);
}
}
static class ProviderMethodBinding extends Binding<Object> {
private final ExecutableElement method;
private final Binding<?>[] parameters;
protected ProviderMethodBinding(String provideKey, ExecutableElement method) {
super(provideKey, null, method.getAnnotation(Singleton.class) != null, method.toString());
this.method = method;
this.parameters = new Binding[method.getParameters().size()];
}
@Override public void attach(Linker linker) {
for (int i = 0; i < method.getParameters().size(); i++) {
VariableElement parameter = method.getParameters().get(i);
String parameterKey = GeneratorKeys.get(parameter);
parameters[i] = linker.requestBinding(parameterKey, method.toString());
}
}
@Override public Object get() {
throw new AssertionError("Compile-time binding should never be called to inject.");
}
@Override public void injectMembers(Object t) {
throw new AssertionError("Compile-time binding should never be called to inject.");
}
@Override public void getDependencies(Set<Binding<?>> get, Set<Binding<?>> injectMembers) {
Collections.addAll(get, parameters);
}
}
void writeDotFile(TypeElement module, Map<String, Binding<?>> bindings) throws IOException {
JavaFileManager.Location location = StandardLocation.SOURCE_OUTPUT;
String path = CodeGen.getPackage(module).getQualifiedName().toString();
String file = module.getQualifiedName().toString().substring(path.length() + 1) + ".dot";
FileObject resource = processingEnv.getFiler().createResource(location, path, file, module);
Writer writer = resource.openWriter();
DotWriter dotWriter = new DotWriter(writer);
new GraphVisualizer().write(bindings, dotWriter);
dotWriter.close();
}
}
| true | true | private Map<String, Binding<?>> processCompleteModule(TypeElement rootModule) {
Map<String, TypeElement> allModules = new LinkedHashMap<String, TypeElement>();
collectIncludesRecursively(rootModule, allModules);
Linker linker = new Linker(null, new CompileTimePlugin(processingEnv),
new ReportingErrorHandler(processingEnv, rootModule.getQualifiedName().toString()));
// Linker requires synchronization for calls to requestBinding and linkAll.
// We know statically that we're single threaded, but we synchronize anyway
// to make the linker happy.
synchronized (linker) {
Map<String, Binding<?>> baseBindings = new LinkedHashMap<String, Binding<?>>();
Map<String, Binding<?>> overrideBindings = new LinkedHashMap<String, Binding<?>>();
for (TypeElement module : allModules.values()) {
Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, module);
boolean overrides = (Boolean) annotation.get("overrides");
Map<String, Binding<?>> addTo = overrides ? overrideBindings : baseBindings;
// Gather the entry points from the annotation.
for (Object entryPoint : (Object[]) annotation.get("entryPoints")) {
linker.requestBinding(GeneratorKeys.rawMembersKey((TypeMirror) entryPoint),
module.getQualifiedName().toString(), false);
}
// Gather the static injections.
// TODO.
// Gather the enclosed @Provides methods.
for (Element enclosed : module.getEnclosedElements()) {
Provides provides = enclosed.getAnnotation(Provides.class);
if (provides == null) {
continue;
}
ExecutableElement providerMethod = (ExecutableElement) enclosed;
String key = GeneratorKeys.get(providerMethod);
ProviderMethodBinding binding = new ProviderMethodBinding(key, providerMethod);
switch (provides.type()) {
case UNIQUE:
ProviderMethodBinding clobbered = (ProviderMethodBinding) addTo.put(key, binding);
if (clobbered != null) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Multiple bindings for " + key
+ " found in override module(s) - cannot override an override: "
+ shortMethodName(clobbered.method)
+ ", " + shortMethodName(binding.method),
binding.method);
}
break;
case SET:
String elementKey = GeneratorKeys.getElementKey(providerMethod);
SetBinding.add(addTo, elementKey, binding);
break;
default:
throw new AssertionError("Unknown @Provides type " + provides.type());
}
}
}
linker.installBindings(baseBindings);
linker.installBindings(overrideBindings);
// Link the bindings. This will traverse the dependency graph, and report
// errors if any dependencies are missing.
return linker.linkAll();
}
}
| private Map<String, Binding<?>> processCompleteModule(TypeElement rootModule) {
Map<String, TypeElement> allModules = new LinkedHashMap<String, TypeElement>();
collectIncludesRecursively(rootModule, allModules);
Linker linker = new Linker(null, new CompileTimePlugin(processingEnv),
new ReportingErrorHandler(processingEnv, rootModule.getQualifiedName().toString()));
// Linker requires synchronization for calls to requestBinding and linkAll.
// We know statically that we're single threaded, but we synchronize anyway
// to make the linker happy.
synchronized (linker) {
Map<String, Binding<?>> baseBindings = new LinkedHashMap<String, Binding<?>>();
Map<String, Binding<?>> overrideBindings = new LinkedHashMap<String, Binding<?>>();
for (TypeElement module : allModules.values()) {
Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, module);
boolean overrides = (Boolean) annotation.get("overrides");
Map<String, Binding<?>> addTo = overrides ? overrideBindings : baseBindings;
// Gather the entry points from the annotation.
for (Object entryPoint : (Object[]) annotation.get("entryPoints")) {
linker.requestBinding(GeneratorKeys.rawMembersKey((TypeMirror) entryPoint),
module.getQualifiedName().toString(), false);
}
// Gather the static injections.
// TODO.
// Gather the enclosed @Provides methods.
for (Element enclosed : module.getEnclosedElements()) {
Provides provides = enclosed.getAnnotation(Provides.class);
if (provides == null) {
continue;
}
ExecutableElement providerMethod = (ExecutableElement) enclosed;
String key = GeneratorKeys.get(providerMethod);
ProviderMethodBinding binding = new ProviderMethodBinding(key, providerMethod);
switch (provides.type()) {
case UNIQUE:
ProviderMethodBinding clobbered = (ProviderMethodBinding) addTo.put(key, binding);
if (clobbered != null) {
String msg = "Duplicate bindings for " + key;
if (overrides) {
msg += " in override module(s) - cannot override an override";
}
msg += ": " + shortMethodName(clobbered.method)
+ ", " + shortMethodName(binding.method);
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg,
binding.method);
}
break;
case SET:
String elementKey = GeneratorKeys.getElementKey(providerMethod);
SetBinding.add(addTo, elementKey, binding);
break;
default:
throw new AssertionError("Unknown @Provides type " + provides.type());
}
}
}
linker.installBindings(baseBindings);
linker.installBindings(overrideBindings);
// Link the bindings. This will traverse the dependency graph, and report
// errors if any dependencies are missing.
return linker.linkAll();
}
}
|
diff --git a/src/org/torproject/ernie/db/ConsensusHealthChecker.java b/src/org/torproject/ernie/db/ConsensusHealthChecker.java
index 18a8f71..a6e5889 100644
--- a/src/org/torproject/ernie/db/ConsensusHealthChecker.java
+++ b/src/org/torproject/ernie/db/ConsensusHealthChecker.java
@@ -1,858 +1,858 @@
/* Copyright 2010 The Tor Project
* See LICENSE for licensing information */
package org.torproject.ernie.db;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.*;
import org.apache.commons.codec.binary.*;
/*
* TODO Possible extensions:
* - Include consensus signatures and tell by which Tor versions the
* consensus will be accepted (and by which not)
*/
public class ConsensusHealthChecker {
private String mostRecentValidAfterTime = null;
private byte[] mostRecentConsensus = null;
/**
* Logger for this class.
*/
private Logger logger;
private SortedMap<String, byte[]> mostRecentVotes =
new TreeMap<String, byte[]>();
public ConsensusHealthChecker() {
/* Initialize logger. */
this.logger = Logger.getLogger(
ConsensusHealthChecker.class.getName());
}
public void processConsensus(String validAfterTime, byte[] data) {
if (this.mostRecentValidAfterTime == null ||
this.mostRecentValidAfterTime.compareTo(validAfterTime) < 0) {
this.mostRecentValidAfterTime = validAfterTime;
this.mostRecentVotes.clear();
this.mostRecentConsensus = data;
}
}
public void processVote(String validAfterTime, String dirSource,
byte[] data) {
if (this.mostRecentValidAfterTime == null ||
this.mostRecentValidAfterTime.compareTo(validAfterTime) < 0) {
this.mostRecentValidAfterTime = validAfterTime;
this.mostRecentVotes.clear();
this.mostRecentConsensus = null;
}
if (this.mostRecentValidAfterTime.equals(validAfterTime)) {
this.mostRecentVotes.put(dirSource, data);
}
}
public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(new String(
this.mostRecentConsensus)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(
new String(voteBytes)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " does not support consensus "
+ "method " + consensusConsensusMethod.split(" ")[1] + ": "
+ voteConsensusMethods);
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " supports consensus method "
+ consensusConsensusMethod.split(" ")[1] + ": "
+ voteConsensusMethods);
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " recommends other client "
+ "versions than the consensus: " + voteClientVersions);
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " recommends the same client "
+ "versions as the consensus: " + voteClientVersions);
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " recommends other server "
+ "versions than the consensus: " + voteServerVersions);
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " recommends the same server "
+ "versions as the consensus: " + voteServerVersions);
}
/* Write consensus parameters. */
boolean conflictOrInvalid = false;
Set<String> validParameters = new HashSet<String>(Arrays.asList(
"circwindow,CircuitPriorityHalflifeMsec".split(",")));
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else {
for (String param : voteParams.split(" ")) {
if (!param.equals("params") &&
(!consensusParams.contains(param) ||
!validParameters.contains(param.split("=")[0]))) {
conflictOrInvalid = true;
break;
}
}
}
if (conflictOrInvalid) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " sets conflicting or invalid "
+ "consensus parameters: " + voteParams);
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " sets only non-conflicting and "
+ "valid consensus parameters: " + voteParams);
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + "'s certificate expires in the "
+ "next 14 days: " + voteDirKeyExpires);
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + "'s certificate does not "
+ "expire in the next 14 days: " + voteDirKeyExpires);
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
/* Check if we're missing a vote. TODO make this configurable */
SortedSet<String> knownAuthorities = new TreeSet<String>(
Arrays.asList(("dannenberg,dizum,gabelmoo,ides,maatuska,moria1,"
+ "tor26,urras").split(",")));
for (String dir : allKnownVotes) {
knownAuthorities.remove(dir);
}
if (!knownAuthorities.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String dir : knownAuthorities) {
sb.append(", " + dir);
}
this.logger.warning("We're missing votes from the following "
+ "directory authorities: " + sb.toString().substring(2));
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"research.html\">Research</a>\n"
+ " <a href=\"status.html\">Status</a>\n"
+ " <br/>\n"
+ " <font size=\"2\">\n"
+ " <a href=\"exonerator.html\">ExoneraTor</a>\n"
- + " <a href=\"relaysearch.html\">Relay Search</a>\n"
+ + " <a href=\"relay-search.html\">Relay Search</a>\n"
+ " <a class=\"current\">Consensus Health</a>\n"
+ " <a href=\"log.html\">Last Log</a>\n"
+ " </font>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
this.logger.warning("The last consensus published at "
+ this.mostRecentValidAfterTime + " is more than 3 hours "
+ "old.");
} else {
bw.write(this.mostRecentValidAfterTime);
this.logger.fine("The last consensus published at "
+ this.mostRecentValidAfterTime + " is less than 3 hours "
+ "old.");
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td><br/><b>Fingerprint</b></td>"
+ "<td><br/><b>Nickname</b></td>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n");
if (consensusAssignedFlags.containsKey(relayKey) &&
consensusAssignedFlags.get(relayKey).contains(" Named")) {
bw.write(" <td id=\"" + nickname + "\">"
+ fingerprint + "</td>\n");
} else {
bw.write(" <td>" + fingerprint + "</td>\n");
}
bw.write(" <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>This material is supported in part by the "
+ "National Science Foundation under Grant No. "
+ "CNS-0959138. Any opinions, finding, and conclusions "
+ "or recommendations expressed in this material are "
+ "those of the author(s) and do not necessarily reflect "
+ "the views of the National Science Foundation.</p>\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " <p>Data on this site is freely available under a "
+ "<a href=\"http://creativecommons.org/publicdomain/"
+ "zero/1.0/\">CC0 no copyright declaration</a>: To the "
+ "extent possible under law, the Tor Project has waived "
+ "all copyright and related or neighboring rights in "
+ "the data. Graphs are licensed under a <a "
+ "href=\"http://creativecommons.org/licenses/by/3.0/"
+ "us/\">Creative Commons Attribution 3.0 United States "
+ "License</a>.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
}
| true | true | public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(new String(
this.mostRecentConsensus)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(
new String(voteBytes)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " does not support consensus "
+ "method " + consensusConsensusMethod.split(" ")[1] + ": "
+ voteConsensusMethods);
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " supports consensus method "
+ consensusConsensusMethod.split(" ")[1] + ": "
+ voteConsensusMethods);
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " recommends other client "
+ "versions than the consensus: " + voteClientVersions);
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " recommends the same client "
+ "versions as the consensus: " + voteClientVersions);
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " recommends other server "
+ "versions than the consensus: " + voteServerVersions);
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " recommends the same server "
+ "versions as the consensus: " + voteServerVersions);
}
/* Write consensus parameters. */
boolean conflictOrInvalid = false;
Set<String> validParameters = new HashSet<String>(Arrays.asList(
"circwindow,CircuitPriorityHalflifeMsec".split(",")));
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else {
for (String param : voteParams.split(" ")) {
if (!param.equals("params") &&
(!consensusParams.contains(param) ||
!validParameters.contains(param.split("=")[0]))) {
conflictOrInvalid = true;
break;
}
}
}
if (conflictOrInvalid) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " sets conflicting or invalid "
+ "consensus parameters: " + voteParams);
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " sets only non-conflicting and "
+ "valid consensus parameters: " + voteParams);
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + "'s certificate expires in the "
+ "next 14 days: " + voteDirKeyExpires);
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + "'s certificate does not "
+ "expire in the next 14 days: " + voteDirKeyExpires);
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
/* Check if we're missing a vote. TODO make this configurable */
SortedSet<String> knownAuthorities = new TreeSet<String>(
Arrays.asList(("dannenberg,dizum,gabelmoo,ides,maatuska,moria1,"
+ "tor26,urras").split(",")));
for (String dir : allKnownVotes) {
knownAuthorities.remove(dir);
}
if (!knownAuthorities.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String dir : knownAuthorities) {
sb.append(", " + dir);
}
this.logger.warning("We're missing votes from the following "
+ "directory authorities: " + sb.toString().substring(2));
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"research.html\">Research</a>\n"
+ " <a href=\"status.html\">Status</a>\n"
+ " <br/>\n"
+ " <font size=\"2\">\n"
+ " <a href=\"exonerator.html\">ExoneraTor</a>\n"
+ " <a href=\"relaysearch.html\">Relay Search</a>\n"
+ " <a class=\"current\">Consensus Health</a>\n"
+ " <a href=\"log.html\">Last Log</a>\n"
+ " </font>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
this.logger.warning("The last consensus published at "
+ this.mostRecentValidAfterTime + " is more than 3 hours "
+ "old.");
} else {
bw.write(this.mostRecentValidAfterTime);
this.logger.fine("The last consensus published at "
+ this.mostRecentValidAfterTime + " is less than 3 hours "
+ "old.");
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td><br/><b>Fingerprint</b></td>"
+ "<td><br/><b>Nickname</b></td>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n");
if (consensusAssignedFlags.containsKey(relayKey) &&
consensusAssignedFlags.get(relayKey).contains(" Named")) {
bw.write(" <td id=\"" + nickname + "\">"
+ fingerprint + "</td>\n");
} else {
bw.write(" <td>" + fingerprint + "</td>\n");
}
bw.write(" <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>This material is supported in part by the "
+ "National Science Foundation under Grant No. "
+ "CNS-0959138. Any opinions, finding, and conclusions "
+ "or recommendations expressed in this material are "
+ "those of the author(s) and do not necessarily reflect "
+ "the views of the National Science Foundation.</p>\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " <p>Data on this site is freely available under a "
+ "<a href=\"http://creativecommons.org/publicdomain/"
+ "zero/1.0/\">CC0 no copyright declaration</a>: To the "
+ "extent possible under law, the Tor Project has waived "
+ "all copyright and related or neighboring rights in "
+ "the data. Graphs are licensed under a <a "
+ "href=\"http://creativecommons.org/licenses/by/3.0/"
+ "us/\">Creative Commons Attribution 3.0 United States "
+ "License</a>.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
| public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(new String(
this.mostRecentConsensus)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(
new String(voteBytes)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " does not support consensus "
+ "method " + consensusConsensusMethod.split(" ")[1] + ": "
+ voteConsensusMethods);
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " supports consensus method "
+ consensusConsensusMethod.split(" ")[1] + ": "
+ voteConsensusMethods);
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " recommends other client "
+ "versions than the consensus: " + voteClientVersions);
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " recommends the same client "
+ "versions as the consensus: " + voteClientVersions);
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " recommends other server "
+ "versions than the consensus: " + voteServerVersions);
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " recommends the same server "
+ "versions as the consensus: " + voteServerVersions);
}
/* Write consensus parameters. */
boolean conflictOrInvalid = false;
Set<String> validParameters = new HashSet<String>(Arrays.asList(
"circwindow,CircuitPriorityHalflifeMsec".split(",")));
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else {
for (String param : voteParams.split(" ")) {
if (!param.equals("params") &&
(!consensusParams.contains(param) ||
!validParameters.contains(param.split("=")[0]))) {
conflictOrInvalid = true;
break;
}
}
}
if (conflictOrInvalid) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + " sets conflicting or invalid "
+ "consensus parameters: " + voteParams);
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + " sets only non-conflicting and "
+ "valid consensus parameters: " + voteParams);
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
this.logger.warning(dirSource + "'s certificate expires in the "
+ "next 14 days: " + voteDirKeyExpires);
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
this.logger.fine(dirSource + "'s certificate does not "
+ "expire in the next 14 days: " + voteDirKeyExpires);
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
/* Check if we're missing a vote. TODO make this configurable */
SortedSet<String> knownAuthorities = new TreeSet<String>(
Arrays.asList(("dannenberg,dizum,gabelmoo,ides,maatuska,moria1,"
+ "tor26,urras").split(",")));
for (String dir : allKnownVotes) {
knownAuthorities.remove(dir);
}
if (!knownAuthorities.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String dir : knownAuthorities) {
sb.append(", " + dir);
}
this.logger.warning("We're missing votes from the following "
+ "directory authorities: " + sb.toString().substring(2));
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"research.html\">Research</a>\n"
+ " <a href=\"status.html\">Status</a>\n"
+ " <br/>\n"
+ " <font size=\"2\">\n"
+ " <a href=\"exonerator.html\">ExoneraTor</a>\n"
+ " <a href=\"relay-search.html\">Relay Search</a>\n"
+ " <a class=\"current\">Consensus Health</a>\n"
+ " <a href=\"log.html\">Last Log</a>\n"
+ " </font>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
this.logger.warning("The last consensus published at "
+ this.mostRecentValidAfterTime + " is more than 3 hours "
+ "old.");
} else {
bw.write(this.mostRecentValidAfterTime);
this.logger.fine("The last consensus published at "
+ this.mostRecentValidAfterTime + " is less than 3 hours "
+ "old.");
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td><br/><b>Fingerprint</b></td>"
+ "<td><br/><b>Nickname</b></td>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n");
if (consensusAssignedFlags.containsKey(relayKey) &&
consensusAssignedFlags.get(relayKey).contains(" Named")) {
bw.write(" <td id=\"" + nickname + "\">"
+ fingerprint + "</td>\n");
} else {
bw.write(" <td>" + fingerprint + "</td>\n");
}
bw.write(" <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>This material is supported in part by the "
+ "National Science Foundation under Grant No. "
+ "CNS-0959138. Any opinions, finding, and conclusions "
+ "or recommendations expressed in this material are "
+ "those of the author(s) and do not necessarily reflect "
+ "the views of the National Science Foundation.</p>\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " <p>Data on this site is freely available under a "
+ "<a href=\"http://creativecommons.org/publicdomain/"
+ "zero/1.0/\">CC0 no copyright declaration</a>: To the "
+ "extent possible under law, the Tor Project has waived "
+ "all copyright and related or neighboring rights in "
+ "the data. Graphs are licensed under a <a "
+ "href=\"http://creativecommons.org/licenses/by/3.0/"
+ "us/\">Creative Commons Attribution 3.0 United States "
+ "License</a>.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
|
diff --git a/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java b/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java
index 92e5568..65fd887 100644
--- a/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java
+++ b/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java
@@ -1,27 +1,27 @@
/*
* AuthenticationCanceledException.java
*
* Created on 19. Oktober 2006, 09:19
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package de.cismet.security.exceptions;
/**
*
* @author Sebastian
*/
public class AuthenticationCanceledException extends Exception {
/** Creates a new instance of AuthenticationCanceledException */
public AuthenticationCanceledException() {
- super("The HTTP authentication was canceled by user");
+ super("The HTTP authentication was canceled by user"); //NOI18N
}
public AuthenticationCanceledException(String message) {
super(message);
}
}
| true | true | public AuthenticationCanceledException() {
super("The HTTP authentication was canceled by user");
}
| public AuthenticationCanceledException() {
super("The HTTP authentication was canceled by user"); //NOI18N
}
|
diff --git a/test/src/main/java/org/jvnet/hudson/test/GroovyHudsonTestCase.java b/test/src/main/java/org/jvnet/hudson/test/GroovyHudsonTestCase.java
index 2953e6350..bba691f6e 100644
--- a/test/src/main/java/org/jvnet/hudson/test/GroovyHudsonTestCase.java
+++ b/test/src/main/java/org/jvnet/hudson/test/GroovyHudsonTestCase.java
@@ -1,63 +1,63 @@
package org.jvnet.hudson.test;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.Stapler;
import groovy.lang.Closure;
import hudson.model.RootAction;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.tasks.Builder;
import hudson.Launcher;
import java.util.UUID;
import java.io.IOException;
/**
* {@link HudsonTestCase} with more convenience methods for Groovy.
*
* @author Kohsuke Kawaguchi
*/
public abstract class GroovyHudsonTestCase extends HudsonTestCase {
/**
* Executes the given closure on the server, in the context of an HTTP request.
* This is useful for testing some methods that require {@link StaplerRequest} and {@link StaplerResponse}.
*
* <p>
* The closure will get the request and response as parameters.
*/
public Object executeOnServer(final Closure c) throws Throwable {
final Throwable[] t = new Throwable[1];
final Object[] r = new Object[1];
ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class);
UUID id = UUID.randomUUID();
cea.add(id,new Runnable() {
public void run() {
try {
- r[0] = c.call(new Object[]{Stapler.getCurrentRequest(),Stapler.getCurrentResponse()});
+ r[0] = c.call();
} catch (Throwable e) {
t[0] = e;
}
}
});
createWebClient().goTo("closures/?uuid="+id);
if (t[0]!=null)
throw t[0];
return r[0];
}
/**
* Wraps a closure as a {@link Builder}.
*/
public Builder builder(final Closure c) {
return new TestBuilder() {
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
Object r = c.call(new Object[]{build,launcher,listener});
if (r instanceof Boolean) return (Boolean)r;
return true;
}
};
}
}
| true | true | public Object executeOnServer(final Closure c) throws Throwable {
final Throwable[] t = new Throwable[1];
final Object[] r = new Object[1];
ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class);
UUID id = UUID.randomUUID();
cea.add(id,new Runnable() {
public void run() {
try {
r[0] = c.call(new Object[]{Stapler.getCurrentRequest(),Stapler.getCurrentResponse()});
} catch (Throwable e) {
t[0] = e;
}
}
});
createWebClient().goTo("closures/?uuid="+id);
if (t[0]!=null)
throw t[0];
return r[0];
}
| public Object executeOnServer(final Closure c) throws Throwable {
final Throwable[] t = new Throwable[1];
final Object[] r = new Object[1];
ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class);
UUID id = UUID.randomUUID();
cea.add(id,new Runnable() {
public void run() {
try {
r[0] = c.call();
} catch (Throwable e) {
t[0] = e;
}
}
});
createWebClient().goTo("closures/?uuid="+id);
if (t[0]!=null)
throw t[0];
return r[0];
}
|
diff --git a/DND/src/edu/teco/dnd/module/ModuleMain.java b/DND/src/edu/teco/dnd/module/ModuleMain.java
index 6294f44..c66d151 100644
--- a/DND/src/edu/teco/dnd/module/ModuleMain.java
+++ b/DND/src/edu/teco/dnd/module/ModuleMain.java
@@ -1,231 +1,231 @@
package edu.teco.dnd.module;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ChannelFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import edu.teco.dnd.module.config.ConfigReader;
import edu.teco.dnd.module.config.JsonConfig;
import edu.teco.dnd.module.messages.generalModule.MissingApplicationHandler;
import edu.teco.dnd.module.messages.generalModule.ShutdownModuleHandler;
import edu.teco.dnd.module.messages.generalModule.ShutdownModuleMessage;
import edu.teco.dnd.module.messages.infoReq.RequestApplicationInformationMessage;
import edu.teco.dnd.module.messages.infoReq.RequestApplicationInformationMessageHandler;
import edu.teco.dnd.module.messages.infoReq.RequestModuleInfoMessage;
import edu.teco.dnd.module.messages.infoReq.RequestModuleInfoMsgHandler;
import edu.teco.dnd.module.messages.joinStartApp.JoinApplicationMessage;
import edu.teco.dnd.module.messages.joinStartApp.JoinApplicationMessageHandler;
import edu.teco.dnd.module.messages.joinStartApp.StartApplicationMessage;
import edu.teco.dnd.module.messages.killApp.KillAppMessage;
import edu.teco.dnd.module.messages.loadStartBlock.BlockMessage;
import edu.teco.dnd.module.messages.loadStartBlock.LoadClassMessage;
import edu.teco.dnd.module.messages.values.ValueMessage;
import edu.teco.dnd.module.messages.values.ValueMessageAdapter;
import edu.teco.dnd.module.messages.values.WhoHasBlockMessage;
import edu.teco.dnd.module.permissions.ApplicationSecurityManager;
import edu.teco.dnd.network.UDPMulticastBeacon;
import edu.teco.dnd.network.logging.Log4j2LoggerFactory;
import edu.teco.dnd.network.tcp.ClientBootstrapChannelFactory;
import edu.teco.dnd.network.tcp.ServerBootstrapChannelFactory;
import edu.teco.dnd.network.tcp.TCPConnectionManager;
import edu.teco.dnd.server.TCPProtocol;
import edu.teco.dnd.util.IndexedThreadFactory;
import edu.teco.dnd.util.NetConnection;
/**
* The main class that is started on a ModuleInfo.
*/
public final class ModuleMain {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LogManager.getLogger(ModuleMain.class);
/**
* Default path for config file.
*/
public static final String DEFAULT_CONFIG_PATH = "module.cfg";
/**
* The default address used for multicast.
*/
public static final InetSocketAddress DEFAULT_MULTICAST_ADDRESS = new InetSocketAddress("225.0.0.1", 5000);
/**
* Should never be instantiated.
*/
private ModuleMain() {
}
/**
* @param args
* ;-)
*/
public static void main(final String[] args) {
final Set<EventLoopGroup> eventLoopGroups = new HashSet<EventLoopGroup>();
TCPConnectionManager tcpConnectionManager;
final ConfigReader moduleConfig;
InternalLoggerFactory.setDefaultFactory(new Log4j2LoggerFactory());
String configPath = DEFAULT_CONFIG_PATH;
if (args.length > 0) {
LOGGER.debug("argument 0 is \"{}\"", args[0]);
if ("--help".equals(args[0]) || "-h".equals(args[0])) {
System.out.println("Parameters: [--help| $pathToConfig]");
System.out.println("\t--help: print this message");
System.out.println("\t$pathToConfig the path to the used config file.");
System.exit(0);
} else {
configPath = args[0];
}
}
moduleConfig = getModuleConfig(configPath);
if (moduleConfig == null) {
System.exit(1);
}
tcpConnectionManager = prepareNetwork(moduleConfig, eventLoopGroups);
try {
System.setSecurityManager(new ApplicationSecurityManager());
} catch (SecurityException se) {
LOGGER.fatal("Can not set SecurityManager.");
// FIXME: just calling exit is probably a bad idea
System.exit(-1);
}
ModuleShutdownHook shutdownHook = new ModuleShutdownHook(eventLoopGroups);
synchronized (shutdownHook) {
Module module = null;
try {
module = new Module(moduleConfig, tcpConnectionManager, shutdownHook);
} catch (final NoSuchAlgorithmException e) {
System.err.println("Missing algorithm: " + e);
System.exit(1);
}
registerHandlerAdapter(moduleConfig, tcpConnectionManager, module);
}
- System.out.println("ModuleInfo is up and running.");
+ System.out.println("Module is up and running.");
}
/**
* read the configuration file into a ConfigReader.
*
* @param configPath
* path to configuration file
* @return a configReader with the read configuration.
*/
private static ConfigReader getModuleConfig(final String configPath) {
ConfigReader moduleConfig = null;
try {
moduleConfig = new JsonConfig(configPath);
} catch (IOException e) {
LOGGER.warn("could not open file: \"{}\"", configPath);
return null;
} catch (Exception e) {
LOGGER.warn("could not load config: \"{}\"", configPath);
e.printStackTrace();
return null;
}
return moduleConfig;
}
/**
* prepares the modules network. Notably sets up a TCPConnectionManager according to the given configuration.
*
* @param moduleConfig
* the configuration used for setup.
* @param eventLoopGroups
* set that will be filled with started threadGroups. Can be used to shut them down later.
* @return a newly setup TCPConnectionManager.
*/
private static TCPConnectionManager prepareNetwork(ConfigReader moduleConfig,
final Set<EventLoopGroup> eventLoopGroups) {
UDPMulticastBeacon udpMulticastBeacon;
final EventLoopGroup networkGroup = new NioEventLoopGroup(0, new IndexedThreadFactory("network-"));
final EventLoopGroup applicationGroup = new NioEventLoopGroup(0, new IndexedThreadFactory("application-"));
final EventLoopGroup beaconGroup = new OioEventLoopGroup(0, new IndexedThreadFactory("beacon-"));
eventLoopGroups.add(networkGroup);
eventLoopGroups.add(applicationGroup);
eventLoopGroups.add(beaconGroup);
final ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(networkGroup, applicationGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
final Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(networkGroup);
clientBootstrap.channel(NioSocketChannel.class);
final TCPConnectionManager tcpConnMan =
new TCPConnectionManager(new ServerBootstrapChannelFactory(serverBootstrap),
new ClientBootstrapChannelFactory(clientBootstrap), applicationGroup, moduleConfig.getUuid());
for (final InetSocketAddress address : moduleConfig.getListen()) {
tcpConnMan.startListening(address);
}
udpMulticastBeacon = new UDPMulticastBeacon(new ChannelFactory<OioDatagramChannel>() {
@Override
public OioDatagramChannel newChannel() {
return new OioDatagramChannel();
}
}, beaconGroup, applicationGroup, moduleConfig.getUuid(), moduleConfig.getAnnounceInterval(), TimeUnit.SECONDS);
udpMulticastBeacon.addListener(tcpConnMan);
final List<InetSocketAddress> announce = Arrays.asList(moduleConfig.getAnnounce());
udpMulticastBeacon.setAnnounceAddresses(announce);
for (final NetConnection address : moduleConfig.getMulticast()) {
udpMulticastBeacon.addAddress(address.getInterface(), address.getAddress());
}
return tcpConnMan;
}
/**
* Registers Message Handlers and adapters for the module on the TCPConnectionManager. This is ModuleInfo specific
* and not used by deploy.
*
* @param moduleConfig
* the configuration according to which the module is set up.
* @param tcpConnMan
* TCPConnectionManager to register handlers on.
* @param module
* the Module the various handlers should use later.
*/
private static void registerHandlerAdapter(ConfigReader moduleConfig, TCPConnectionManager tcpConnMan, Module module) {
new TCPProtocol().initialize(tcpConnMan);
tcpConnMan.registerTypeAdapter(ValueMessage.class, new ValueMessageAdapter(module));
tcpConnMan.addHandler(JoinApplicationMessage.class, new JoinApplicationMessageHandler(module));
tcpConnMan.addHandler(RequestApplicationInformationMessage.class,
new RequestApplicationInformationMessageHandler(moduleConfig.getUuid(), module));
tcpConnMan.addHandler(RequestModuleInfoMessage.class, new RequestModuleInfoMsgHandler(moduleConfig));
tcpConnMan.addHandler(LoadClassMessage.class, new MissingApplicationHandler());
tcpConnMan.addHandler(BlockMessage.class, new MissingApplicationHandler());
tcpConnMan.addHandler(StartApplicationMessage.class, new MissingApplicationHandler());
tcpConnMan.addHandler(KillAppMessage.class, new MissingApplicationHandler());
tcpConnMan.addHandler(ValueMessage.class, new MissingApplicationHandler());
tcpConnMan.addHandler(WhoHasBlockMessage.class, new MissingApplicationHandler());
tcpConnMan.addHandler(ShutdownModuleMessage.class, new ShutdownModuleHandler(module));
}
}
| true | true | public static void main(final String[] args) {
final Set<EventLoopGroup> eventLoopGroups = new HashSet<EventLoopGroup>();
TCPConnectionManager tcpConnectionManager;
final ConfigReader moduleConfig;
InternalLoggerFactory.setDefaultFactory(new Log4j2LoggerFactory());
String configPath = DEFAULT_CONFIG_PATH;
if (args.length > 0) {
LOGGER.debug("argument 0 is \"{}\"", args[0]);
if ("--help".equals(args[0]) || "-h".equals(args[0])) {
System.out.println("Parameters: [--help| $pathToConfig]");
System.out.println("\t--help: print this message");
System.out.println("\t$pathToConfig the path to the used config file.");
System.exit(0);
} else {
configPath = args[0];
}
}
moduleConfig = getModuleConfig(configPath);
if (moduleConfig == null) {
System.exit(1);
}
tcpConnectionManager = prepareNetwork(moduleConfig, eventLoopGroups);
try {
System.setSecurityManager(new ApplicationSecurityManager());
} catch (SecurityException se) {
LOGGER.fatal("Can not set SecurityManager.");
// FIXME: just calling exit is probably a bad idea
System.exit(-1);
}
ModuleShutdownHook shutdownHook = new ModuleShutdownHook(eventLoopGroups);
synchronized (shutdownHook) {
Module module = null;
try {
module = new Module(moduleConfig, tcpConnectionManager, shutdownHook);
} catch (final NoSuchAlgorithmException e) {
System.err.println("Missing algorithm: " + e);
System.exit(1);
}
registerHandlerAdapter(moduleConfig, tcpConnectionManager, module);
}
System.out.println("ModuleInfo is up and running.");
}
| public static void main(final String[] args) {
final Set<EventLoopGroup> eventLoopGroups = new HashSet<EventLoopGroup>();
TCPConnectionManager tcpConnectionManager;
final ConfigReader moduleConfig;
InternalLoggerFactory.setDefaultFactory(new Log4j2LoggerFactory());
String configPath = DEFAULT_CONFIG_PATH;
if (args.length > 0) {
LOGGER.debug("argument 0 is \"{}\"", args[0]);
if ("--help".equals(args[0]) || "-h".equals(args[0])) {
System.out.println("Parameters: [--help| $pathToConfig]");
System.out.println("\t--help: print this message");
System.out.println("\t$pathToConfig the path to the used config file.");
System.exit(0);
} else {
configPath = args[0];
}
}
moduleConfig = getModuleConfig(configPath);
if (moduleConfig == null) {
System.exit(1);
}
tcpConnectionManager = prepareNetwork(moduleConfig, eventLoopGroups);
try {
System.setSecurityManager(new ApplicationSecurityManager());
} catch (SecurityException se) {
LOGGER.fatal("Can not set SecurityManager.");
// FIXME: just calling exit is probably a bad idea
System.exit(-1);
}
ModuleShutdownHook shutdownHook = new ModuleShutdownHook(eventLoopGroups);
synchronized (shutdownHook) {
Module module = null;
try {
module = new Module(moduleConfig, tcpConnectionManager, shutdownHook);
} catch (final NoSuchAlgorithmException e) {
System.err.println("Missing algorithm: " + e);
System.exit(1);
}
registerHandlerAdapter(moduleConfig, tcpConnectionManager, module);
}
System.out.println("Module is up and running.");
}
|
diff --git a/src/com/quackware/tric/ui/MyPreferenceActivity.java b/src/com/quackware/tric/ui/MyPreferenceActivity.java
index 984b382..c01d9a4 100644
--- a/src/com/quackware/tric/ui/MyPreferenceActivity.java
+++ b/src/com/quackware/tric/ui/MyPreferenceActivity.java
@@ -1,127 +1,127 @@
package com.quackware.tric.ui;
import java.util.ArrayList;
import com.quackware.tric.MyApplication;
import com.quackware.tric.R;
import com.quackware.tric.service.CollectionService;
import com.quackware.tric.stats.Stats;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.text.InputType;
public class MyPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
buildPreferenceActivity();
}
@Override
public void onResume()
{
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause()
{
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
//The general structure of preferences will remain the same, however we do need to populate it based on the Stats collection.
private void buildPreferenceActivity()
{
ArrayList<Stats> stats = MyApplication.getStats();
PreferenceScreen phonePs = (PreferenceScreen)findPreference("button_phonestats_category_key");
PreferenceScreen socialPs = (PreferenceScreen)findPreference("button_socialstats_category_key");
PreferenceScreen appPs = (PreferenceScreen)findPreference("button_appstats_category_key");
for(Stats s : stats)
{
PreferenceScreen ps = generatePreferenceScreen(s);
if(s.getType().equals("PhoneStats"))
{
phonePs.addPreference(ps);
}
else if(s.getType().equals("SocialStats"))
{
socialPs.addPreference(ps);
}
else if(s.getType().equals("AppStats"))
{
appPs.addPreference(ps);
}
else
{
//Unknown type.
}
}
}
private PreferenceScreen generatePreferenceScreen(Stats s)
{
CheckBoxPreference sharePreference = new CheckBoxPreference(this);
sharePreference.setKey("checkbox_share_" + s.getName());
sharePreference.setTitle(getString(R.string.pref_share_title));
sharePreference.setSummary(getString(R.string.pref_share_summary));
sharePreference.setDefaultValue(false);
CheckBoxPreference collectPreference = new CheckBoxPreference(this);
collectPreference.setKey("checkbox_collect_" + s.getName());
collectPreference.setTitle(getString(R.string.pref_collect_title));
collectPreference.setSummary(getString(R.string.pref_collect_summary));
collectPreference.setDefaultValue(true);
EditTextPreference collectionIntervalPreference = new EditTextPreference(this);
collectionIntervalPreference.setKey("edittext_collectinterval_" + s.getName());
collectionIntervalPreference.setTitle(getString(R.string.pref_collectinterval_title));
collectionIntervalPreference.setSummary(getString(R.string.pref_collectinterval_summary));
- collectionIntervalPreference.setDefaultValue(s.getDefaultCollectionInterval());
- collectionIntervalPreference.setDependency("checkbox_collect_" + s.getName());
+ collectionIntervalPreference.setDefaultValue("" + s.getDefaultCollectionInterval());
+ //collectionIntervalPreference.setDependency("checkbox_collect_" + s.getName());
collectionIntervalPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
PreferenceScreen ps = getPreferenceManager().createPreferenceScreen(this);
ps.setKey("button_" + s.getName());
ps.setPersistent(false);
ps.setTitle(s.getName() + " tric");
ps.addPreference(collectPreference);
ps.addPreference(collectionIntervalPreference);
ps.addPreference(sharePreference);
return ps;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//Get service for callback.
CollectionService service = MyApplication.getService();
//First check what preference changed.
if(key.startsWith("checkbox_share_"))
{
//todo later.
}
else if(key.startsWith("checkbox_collect_"))
{
String statsName = key.replace("checkbox_collect_", "");
service.refreshStatsInfo(MyApplication.getStatsByName(statsName));
}
else if(key.startsWith("edittext_collectinterval_"))
{
String statsName = key.replace("edittext_collectinterval_", "");
service.refreshStatsInfo(MyApplication.getStatsByName(statsName));
}
}
}
| true | true | private PreferenceScreen generatePreferenceScreen(Stats s)
{
CheckBoxPreference sharePreference = new CheckBoxPreference(this);
sharePreference.setKey("checkbox_share_" + s.getName());
sharePreference.setTitle(getString(R.string.pref_share_title));
sharePreference.setSummary(getString(R.string.pref_share_summary));
sharePreference.setDefaultValue(false);
CheckBoxPreference collectPreference = new CheckBoxPreference(this);
collectPreference.setKey("checkbox_collect_" + s.getName());
collectPreference.setTitle(getString(R.string.pref_collect_title));
collectPreference.setSummary(getString(R.string.pref_collect_summary));
collectPreference.setDefaultValue(true);
EditTextPreference collectionIntervalPreference = new EditTextPreference(this);
collectionIntervalPreference.setKey("edittext_collectinterval_" + s.getName());
collectionIntervalPreference.setTitle(getString(R.string.pref_collectinterval_title));
collectionIntervalPreference.setSummary(getString(R.string.pref_collectinterval_summary));
collectionIntervalPreference.setDefaultValue(s.getDefaultCollectionInterval());
collectionIntervalPreference.setDependency("checkbox_collect_" + s.getName());
collectionIntervalPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
PreferenceScreen ps = getPreferenceManager().createPreferenceScreen(this);
ps.setKey("button_" + s.getName());
ps.setPersistent(false);
ps.setTitle(s.getName() + " tric");
ps.addPreference(collectPreference);
ps.addPreference(collectionIntervalPreference);
ps.addPreference(sharePreference);
return ps;
}
| private PreferenceScreen generatePreferenceScreen(Stats s)
{
CheckBoxPreference sharePreference = new CheckBoxPreference(this);
sharePreference.setKey("checkbox_share_" + s.getName());
sharePreference.setTitle(getString(R.string.pref_share_title));
sharePreference.setSummary(getString(R.string.pref_share_summary));
sharePreference.setDefaultValue(false);
CheckBoxPreference collectPreference = new CheckBoxPreference(this);
collectPreference.setKey("checkbox_collect_" + s.getName());
collectPreference.setTitle(getString(R.string.pref_collect_title));
collectPreference.setSummary(getString(R.string.pref_collect_summary));
collectPreference.setDefaultValue(true);
EditTextPreference collectionIntervalPreference = new EditTextPreference(this);
collectionIntervalPreference.setKey("edittext_collectinterval_" + s.getName());
collectionIntervalPreference.setTitle(getString(R.string.pref_collectinterval_title));
collectionIntervalPreference.setSummary(getString(R.string.pref_collectinterval_summary));
collectionIntervalPreference.setDefaultValue("" + s.getDefaultCollectionInterval());
//collectionIntervalPreference.setDependency("checkbox_collect_" + s.getName());
collectionIntervalPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
PreferenceScreen ps = getPreferenceManager().createPreferenceScreen(this);
ps.setKey("button_" + s.getName());
ps.setPersistent(false);
ps.setTitle(s.getName() + " tric");
ps.addPreference(collectPreference);
ps.addPreference(collectionIntervalPreference);
ps.addPreference(sharePreference);
return ps;
}
|
diff --git a/common/logisticspipes/routing/PathFinder.java b/common/logisticspipes/routing/PathFinder.java
index b0f85039..711e303a 100644
--- a/common/logisticspipes/routing/PathFinder.java
+++ b/common/logisticspipes/routing/PathFinder.java
@@ -1,176 +1,184 @@
/**
* Copyright (c) Krapht, 2011
*
* "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package logisticspipes.routing;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import logisticspipes.interfaces.routing.IDirectRoutingConnection;
import logisticspipes.pipes.basic.CoreRoutedPipe;
import logisticspipes.pipes.basic.RoutedPipe;
import logisticspipes.proxy.SimpleServiceLocator;
import net.minecraft.src.IInventory;
import net.minecraft.src.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.api.core.Position;
import buildcraft.transport.TileGenericPipe;
import buildcraft.transport.pipes.PipeItemsIron;
import buildcraft.transport.pipes.PipeItemsObsidian;
/**
* Examines all pipe connections and their forks to locate all connected routers
*/
class PathFinder {
/**
* Recurse through all exists of a pipe to find instances of PipeItemsRouting. maxVisited and maxLength are safeguards for
* recursion runaways.
*
* @param startPipe - The TileGenericPipe to start the search from
* @param maxVisited - The maximum number of pipes to visit, regardless of recursion level
* @param maxLength - The maximum recurse depth, i.e. the maximum length pipe that is supported
* @return
*/
public static HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, int maxVisited, int maxLength) {
PathFinder newSearch = new PathFinder(maxVisited, maxLength);
return newSearch.getConnectedRoutingPipes(startPipe, new LinkedList<TileGenericPipe>(), null);
}
public static HashMap<RoutedPipe, ExitRoute> paintAndgetConnectedRoutingPipes(TileGenericPipe startPipe, ForgeDirection startOrientation, int maxVisited, int maxLength, IPaintPath pathPainter) {
PathFinder newSearch = new PathFinder(maxVisited, maxLength);
LinkedList<TileGenericPipe> visited = new LinkedList<TileGenericPipe>();
visited.add(startPipe);
Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, startOrientation);
p.moveForwards(1);
TileEntity entity = startPipe.worldObj.getBlockTileEntity((int)p.x, (int)p.y, (int)p.z);
if (!(entity instanceof TileGenericPipe && ((TileGenericPipe)entity).pipe.isPipeConnected(startPipe))){
return new HashMap<RoutedPipe, ExitRoute>();
}
return newSearch.getConnectedRoutingPipes((TileGenericPipe) entity, visited, pathPainter);
}
private PathFinder(int maxVisited, int maxLength) {
this.maxVisited = maxVisited;
this.maxLength = maxLength;
}
private int maxVisited;
private int maxLength;
private HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, LinkedList<TileGenericPipe> visited, IPaintPath pathPainter) {
HashMap<RoutedPipe, ExitRoute> foundPipes = new HashMap<RoutedPipe, ExitRoute>();
//Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured
if (maxVisited-- < 1) {
return foundPipes;
}
- //Break recursion after certain amount of nodes visited or if we end up where we have been before
- if (visited.size() > maxLength || visited.contains(startPipe)) {
+ //Break recursion after certain amount of nodes visited
+ if (visited.size() > maxLength) {
return foundPipes;
}
//Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call
if (startPipe.pipe instanceof RoutedPipe && visited.size() != 0) {
foundPipes.put((RoutedPipe) startPipe.pipe, new ExitRoute(ForgeDirection.UNKNOWN, visited.size(), false));
return foundPipes;
}
//Visited is checked after, so we can reach the same target twice to allow to keep the shortest path
visited.add(startPipe);
//Iron and obsidean pipes will separate networks
if (startPipe instanceof TileGenericPipe && (startPipe.pipe instanceof PipeItemsIron) || (startPipe.pipe instanceof PipeItemsObsidian)){
return foundPipes;
}
if(startPipe.pipe != null) {
//Special check for unnormal pipes
try {
List<TileGenericPipe> pipez = SimpleServiceLocator.specialconnection.getConnectedPipes(startPipe);
for (TileGenericPipe specialpipe : pipez){
+ if (visited.contains(specialpipe)) {
+ //Don't go where we have been before
+ continue;
+ }
HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe, (LinkedList<TileGenericPipe>)visited.clone(), pathPainter);
for(RoutedPipe pipe : result.keySet()) {
result.get(pipe).exitOrientation = ForgeDirection.UNKNOWN;
if (!foundPipes.containsKey(pipe)) {
// New path
foundPipes.put(pipe, result.get(pipe));
}
else if (result.get(pipe).metric < foundPipes.get(pipe).metric) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipe, result.get(pipe));
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Recurse in all directions
for (int i = 0; i < 6; i++) {
Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, ForgeDirection.values()[i]);
p.moveForwards(1);
TileEntity tile = startPipe.worldObj.getBlockTileEntity((int) p.x, (int) p.y, (int) p.z);
if (tile == null) continue;
boolean isDirectConnection = false;
int resistance = 0;
if(tile instanceof IInventory) {
if(startPipe.pipe instanceof IDirectRoutingConnection) {
if(SimpleServiceLocator.connectionManager.hasDirectConnection(((RoutedPipe)startPipe.pipe).getRouter())) {
CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((RoutedPipe)startPipe.pipe).getRouter());
if(CRP != null) {
tile = CRP.container;
isDirectConnection = true;
resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance();
}
}
}
}
if (tile == null) continue;
if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile))) {
+ if (visited.contains(tile)) {
+ //Don't go where we have been before
+ continue;
+ }
int beforeRecurseCount = foundPipes.size();
HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile), (LinkedList<TileGenericPipe>)visited.clone(), pathPainter);
for(RoutedPipe pipe : result.keySet()) {
//Update Result with the direction we took
result.get(pipe).exitOrientation = ForgeDirection.values()[i];
if(isDirectConnection) {
result.get(pipe).isPipeLess = true;
}
if (!foundPipes.containsKey(pipe)) {
// New path
foundPipes.put(pipe, result.get(pipe));
//Add resistance
foundPipes.get(pipe).metric += resistance;
}
else if (result.get(pipe).metric + resistance < foundPipes.get(pipe).metric) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipe, result.get(pipe));
//Add resistance
foundPipes.get(pipe).metric += resistance;
}
}
if (foundPipes.size() > beforeRecurseCount && pathPainter != null){
p.moveBackwards(1);
pathPainter.addLaser(startPipe.worldObj, p, ForgeDirection.values()[i]);
}
}
}
return foundPipes;
}
}
| false | true | private HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, LinkedList<TileGenericPipe> visited, IPaintPath pathPainter) {
HashMap<RoutedPipe, ExitRoute> foundPipes = new HashMap<RoutedPipe, ExitRoute>();
//Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured
if (maxVisited-- < 1) {
return foundPipes;
}
//Break recursion after certain amount of nodes visited or if we end up where we have been before
if (visited.size() > maxLength || visited.contains(startPipe)) {
return foundPipes;
}
//Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call
if (startPipe.pipe instanceof RoutedPipe && visited.size() != 0) {
foundPipes.put((RoutedPipe) startPipe.pipe, new ExitRoute(ForgeDirection.UNKNOWN, visited.size(), false));
return foundPipes;
}
//Visited is checked after, so we can reach the same target twice to allow to keep the shortest path
visited.add(startPipe);
//Iron and obsidean pipes will separate networks
if (startPipe instanceof TileGenericPipe && (startPipe.pipe instanceof PipeItemsIron) || (startPipe.pipe instanceof PipeItemsObsidian)){
return foundPipes;
}
if(startPipe.pipe != null) {
//Special check for unnormal pipes
try {
List<TileGenericPipe> pipez = SimpleServiceLocator.specialconnection.getConnectedPipes(startPipe);
for (TileGenericPipe specialpipe : pipez){
HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe, (LinkedList<TileGenericPipe>)visited.clone(), pathPainter);
for(RoutedPipe pipe : result.keySet()) {
result.get(pipe).exitOrientation = ForgeDirection.UNKNOWN;
if (!foundPipes.containsKey(pipe)) {
// New path
foundPipes.put(pipe, result.get(pipe));
}
else if (result.get(pipe).metric < foundPipes.get(pipe).metric) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipe, result.get(pipe));
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Recurse in all directions
for (int i = 0; i < 6; i++) {
Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, ForgeDirection.values()[i]);
p.moveForwards(1);
TileEntity tile = startPipe.worldObj.getBlockTileEntity((int) p.x, (int) p.y, (int) p.z);
if (tile == null) continue;
boolean isDirectConnection = false;
int resistance = 0;
if(tile instanceof IInventory) {
if(startPipe.pipe instanceof IDirectRoutingConnection) {
if(SimpleServiceLocator.connectionManager.hasDirectConnection(((RoutedPipe)startPipe.pipe).getRouter())) {
CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((RoutedPipe)startPipe.pipe).getRouter());
if(CRP != null) {
tile = CRP.container;
isDirectConnection = true;
resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance();
}
}
}
}
if (tile == null) continue;
if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile))) {
int beforeRecurseCount = foundPipes.size();
HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile), (LinkedList<TileGenericPipe>)visited.clone(), pathPainter);
for(RoutedPipe pipe : result.keySet()) {
//Update Result with the direction we took
result.get(pipe).exitOrientation = ForgeDirection.values()[i];
if(isDirectConnection) {
result.get(pipe).isPipeLess = true;
}
if (!foundPipes.containsKey(pipe)) {
// New path
foundPipes.put(pipe, result.get(pipe));
//Add resistance
foundPipes.get(pipe).metric += resistance;
}
else if (result.get(pipe).metric + resistance < foundPipes.get(pipe).metric) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipe, result.get(pipe));
//Add resistance
foundPipes.get(pipe).metric += resistance;
}
}
if (foundPipes.size() > beforeRecurseCount && pathPainter != null){
p.moveBackwards(1);
pathPainter.addLaser(startPipe.worldObj, p, ForgeDirection.values()[i]);
}
}
}
return foundPipes;
}
| private HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, LinkedList<TileGenericPipe> visited, IPaintPath pathPainter) {
HashMap<RoutedPipe, ExitRoute> foundPipes = new HashMap<RoutedPipe, ExitRoute>();
//Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured
if (maxVisited-- < 1) {
return foundPipes;
}
//Break recursion after certain amount of nodes visited
if (visited.size() > maxLength) {
return foundPipes;
}
//Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call
if (startPipe.pipe instanceof RoutedPipe && visited.size() != 0) {
foundPipes.put((RoutedPipe) startPipe.pipe, new ExitRoute(ForgeDirection.UNKNOWN, visited.size(), false));
return foundPipes;
}
//Visited is checked after, so we can reach the same target twice to allow to keep the shortest path
visited.add(startPipe);
//Iron and obsidean pipes will separate networks
if (startPipe instanceof TileGenericPipe && (startPipe.pipe instanceof PipeItemsIron) || (startPipe.pipe instanceof PipeItemsObsidian)){
return foundPipes;
}
if(startPipe.pipe != null) {
//Special check for unnormal pipes
try {
List<TileGenericPipe> pipez = SimpleServiceLocator.specialconnection.getConnectedPipes(startPipe);
for (TileGenericPipe specialpipe : pipez){
if (visited.contains(specialpipe)) {
//Don't go where we have been before
continue;
}
HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe, (LinkedList<TileGenericPipe>)visited.clone(), pathPainter);
for(RoutedPipe pipe : result.keySet()) {
result.get(pipe).exitOrientation = ForgeDirection.UNKNOWN;
if (!foundPipes.containsKey(pipe)) {
// New path
foundPipes.put(pipe, result.get(pipe));
}
else if (result.get(pipe).metric < foundPipes.get(pipe).metric) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipe, result.get(pipe));
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Recurse in all directions
for (int i = 0; i < 6; i++) {
Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, ForgeDirection.values()[i]);
p.moveForwards(1);
TileEntity tile = startPipe.worldObj.getBlockTileEntity((int) p.x, (int) p.y, (int) p.z);
if (tile == null) continue;
boolean isDirectConnection = false;
int resistance = 0;
if(tile instanceof IInventory) {
if(startPipe.pipe instanceof IDirectRoutingConnection) {
if(SimpleServiceLocator.connectionManager.hasDirectConnection(((RoutedPipe)startPipe.pipe).getRouter())) {
CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((RoutedPipe)startPipe.pipe).getRouter());
if(CRP != null) {
tile = CRP.container;
isDirectConnection = true;
resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance();
}
}
}
}
if (tile == null) continue;
if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile))) {
if (visited.contains(tile)) {
//Don't go where we have been before
continue;
}
int beforeRecurseCount = foundPipes.size();
HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile), (LinkedList<TileGenericPipe>)visited.clone(), pathPainter);
for(RoutedPipe pipe : result.keySet()) {
//Update Result with the direction we took
result.get(pipe).exitOrientation = ForgeDirection.values()[i];
if(isDirectConnection) {
result.get(pipe).isPipeLess = true;
}
if (!foundPipes.containsKey(pipe)) {
// New path
foundPipes.put(pipe, result.get(pipe));
//Add resistance
foundPipes.get(pipe).metric += resistance;
}
else if (result.get(pipe).metric + resistance < foundPipes.get(pipe).metric) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipe, result.get(pipe));
//Add resistance
foundPipes.get(pipe).metric += resistance;
}
}
if (foundPipes.size() > beforeRecurseCount && pathPainter != null){
p.moveBackwards(1);
pathPainter.addLaser(startPipe.worldObj, p, ForgeDirection.values()[i]);
}
}
}
return foundPipes;
}
|
diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/MatchesExpression.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/MatchesExpression.java
index f0248687c..d5e717e06 100644
--- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/MatchesExpression.java
+++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/exps/MatchesExpression.java
@@ -1,160 +1,162 @@
/*
* 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.openjpa.jdbc.kernel.exps;
import java.util.Map;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.sql.DBDictionary;
import org.apache.openjpa.jdbc.sql.SQLBuffer;
import org.apache.openjpa.jdbc.sql.Select;
import org.apache.openjpa.kernel.exps.ExpressionVisitor;
import serp.util.Strings;
/**
* Test if a string matches a regexp.
*
* @author Abe White
*/
class MatchesExpression
implements Exp {
private final Val _val;
private final Const _const;
private final String _single;
private final String _multi;
private final String _escape;
/**
* Constructor. Supply values.
*/
public MatchesExpression(Val val, Const con,
String single, String multi, String escape) {
_val = val;
_const = con;
_single = single;
_multi = multi;
_escape = escape;
}
public ExpState initialize(Select sel, ExpContext ctx, Map contains) {
ExpState s1 = _val.initialize(sel, ctx, 0);
ExpState s2 = _const.initialize(sel, ctx, 0);
return new BinaryOpExpState(sel.and(s1.joins, s2.joins), s1, s2);
}
public void appendTo(Select sel, ExpContext ctx, ExpState state,
SQLBuffer buf) {
BinaryOpExpState bstate = (BinaryOpExpState) state;
_val.calculateValue(sel, ctx, bstate.state1, _const, bstate.state2);
_const.calculateValue(sel, ctx, bstate.state2, _val, bstate.state1);
Column col = null;
if (_val instanceof PCPath) {
Column[] cols = ((PCPath) _val).getColumns(bstate.state1);
if (cols.length == 1)
col = cols[0];
}
Object o = _const.getValue(ctx, bstate.state2);
if (o == null)
buf.append("1 <> 1");
else {
// look for ignore case flag and strip it out if present
boolean ignoreCase = false;
String str = o.toString();
int idx = str.indexOf("(?i)");
if (idx != -1) {
ignoreCase = true;
if (idx + 4 < str.length())
str = str.substring(0, idx) + str.substring(idx + 4);
else
str = str.substring(0, idx);
str = str.toLowerCase();
}
// append target
if (ignoreCase)
buf.append("LOWER(");
_val.appendTo(sel, ctx, bstate.state1, buf, 0);
if (ignoreCase)
buf.append(")");
// create a DB wildcard string by replacing the
// multi token (e.g., '.*') and the single token (e.g., ".")
// with '%' and '.' with '_'
str = replaceEscape(str, _multi, "%", _escape);
str = replaceEscape(str, _single, "_", _escape);
buf.append(" LIKE ").appendValue(str, col);
// escape out characters by using the database's escape sequence
DBDictionary dict = ctx.store.getDBDictionary();
- if (_escape != null && _escape.equals("\\")) {
- buf.append(" ESCAPE '").append(dict.searchStringEscape).append("'");
- } else
- buf.append(" ESCAPE '").append(_escape).append("'");
+ if (_escape != null) {
+ if (_escape.equals("\\"))
+ buf.append(" ESCAPE '").append(dict.searchStringEscape).append("'");
+ else
+ buf.append(" ESCAPE '").append(_escape).append("'");
+ }
}
sel.append(buf, state.joins);
}
/**
* Perform a string replacement with simplistic escape handing.
*
* @param str the source string
* @param from the string to find
* @param to the string to replace
* @param escape the string to use to escape replacement
* @return the replaced string
*/
private static String replaceEscape(String str, String from, String to,
String escape) {
String[] parts = Strings.split(str, from, Integer.MAX_VALUE);
StringBuffer repbuf = new StringBuffer();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
// if the previous part ended with an escape character, then
// escape the character and remove the previous escape;
// this doesn't support any double-escaping or other more
// sophisticated features
if (!from.equals(to) && parts[i - 1].endsWith(escape)) {
repbuf.setLength(repbuf.length() - 1);
repbuf.append(from);
} else
repbuf.append(to);
}
repbuf.append(parts[i]);
}
return repbuf.toString();
}
public void selectColumns(Select sel, ExpContext ctx, ExpState state,
boolean pks) {
BinaryOpExpState bstate = (BinaryOpExpState) state;
_val.selectColumns(sel, ctx, bstate.state1, true);
_const.selectColumns(sel, ctx, bstate.state2, true);
}
public void acceptVisit(ExpressionVisitor visitor) {
visitor.enter(this);
_val.acceptVisit(visitor);
_const.acceptVisit(visitor);
visitor.exit(this);
}
}
| true | true | public void appendTo(Select sel, ExpContext ctx, ExpState state,
SQLBuffer buf) {
BinaryOpExpState bstate = (BinaryOpExpState) state;
_val.calculateValue(sel, ctx, bstate.state1, _const, bstate.state2);
_const.calculateValue(sel, ctx, bstate.state2, _val, bstate.state1);
Column col = null;
if (_val instanceof PCPath) {
Column[] cols = ((PCPath) _val).getColumns(bstate.state1);
if (cols.length == 1)
col = cols[0];
}
Object o = _const.getValue(ctx, bstate.state2);
if (o == null)
buf.append("1 <> 1");
else {
// look for ignore case flag and strip it out if present
boolean ignoreCase = false;
String str = o.toString();
int idx = str.indexOf("(?i)");
if (idx != -1) {
ignoreCase = true;
if (idx + 4 < str.length())
str = str.substring(0, idx) + str.substring(idx + 4);
else
str = str.substring(0, idx);
str = str.toLowerCase();
}
// append target
if (ignoreCase)
buf.append("LOWER(");
_val.appendTo(sel, ctx, bstate.state1, buf, 0);
if (ignoreCase)
buf.append(")");
// create a DB wildcard string by replacing the
// multi token (e.g., '.*') and the single token (e.g., ".")
// with '%' and '.' with '_'
str = replaceEscape(str, _multi, "%", _escape);
str = replaceEscape(str, _single, "_", _escape);
buf.append(" LIKE ").appendValue(str, col);
// escape out characters by using the database's escape sequence
DBDictionary dict = ctx.store.getDBDictionary();
if (_escape != null && _escape.equals("\\")) {
buf.append(" ESCAPE '").append(dict.searchStringEscape).append("'");
} else
buf.append(" ESCAPE '").append(_escape).append("'");
}
sel.append(buf, state.joins);
}
| public void appendTo(Select sel, ExpContext ctx, ExpState state,
SQLBuffer buf) {
BinaryOpExpState bstate = (BinaryOpExpState) state;
_val.calculateValue(sel, ctx, bstate.state1, _const, bstate.state2);
_const.calculateValue(sel, ctx, bstate.state2, _val, bstate.state1);
Column col = null;
if (_val instanceof PCPath) {
Column[] cols = ((PCPath) _val).getColumns(bstate.state1);
if (cols.length == 1)
col = cols[0];
}
Object o = _const.getValue(ctx, bstate.state2);
if (o == null)
buf.append("1 <> 1");
else {
// look for ignore case flag and strip it out if present
boolean ignoreCase = false;
String str = o.toString();
int idx = str.indexOf("(?i)");
if (idx != -1) {
ignoreCase = true;
if (idx + 4 < str.length())
str = str.substring(0, idx) + str.substring(idx + 4);
else
str = str.substring(0, idx);
str = str.toLowerCase();
}
// append target
if (ignoreCase)
buf.append("LOWER(");
_val.appendTo(sel, ctx, bstate.state1, buf, 0);
if (ignoreCase)
buf.append(")");
// create a DB wildcard string by replacing the
// multi token (e.g., '.*') and the single token (e.g., ".")
// with '%' and '.' with '_'
str = replaceEscape(str, _multi, "%", _escape);
str = replaceEscape(str, _single, "_", _escape);
buf.append(" LIKE ").appendValue(str, col);
// escape out characters by using the database's escape sequence
DBDictionary dict = ctx.store.getDBDictionary();
if (_escape != null) {
if (_escape.equals("\\"))
buf.append(" ESCAPE '").append(dict.searchStringEscape).append("'");
else
buf.append(" ESCAPE '").append(_escape).append("'");
}
}
sel.append(buf, state.joins);
}
|
diff --git a/src/com/axelby/podax/Helper.java b/src/com/axelby/podax/Helper.java
index ac10956..f1c5e24 100644
--- a/src/com/axelby/podax/Helper.java
+++ b/src/com/axelby/podax/Helper.java
@@ -1,90 +1,90 @@
package com.axelby.podax;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
public class Helper {
public static boolean ensureWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting())
return false;
// always OK if we're on wifi
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI)
return true;
// check for wifi only pref
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("wifiPref", true))
{
Log.d("Podax", "Not downloading because Wifi is required and not connected");
return false;
}
// check for 3g data turned off
- if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
+ if (!netInfo.isConnected()) {
Log.d("Podax", "Not downloading because background data is turned off");
return false;
}
return true;
}
public static String getTimeString(int milliseconds) {
int seconds = milliseconds / 1000;
final int SECONDSPERHOUR = 60 * 60;
final int SECONDSPERMINUTE = 60;
int hours = seconds / SECONDSPERHOUR;
int minutes = seconds % SECONDSPERHOUR / SECONDSPERMINUTE;
seconds = seconds % SECONDSPERMINUTE;
StringBuilder builder = new StringBuilder();
if (hours > 0) {
builder.append(hours);
builder.append(":");
if (minutes < 10)
builder.append("0");
}
builder.append(minutes);
builder.append(":");
if (seconds < 10)
builder.append("0");
builder.append(seconds);
return builder.toString();
}
public static boolean isPlaying(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
if ("com.axelby.podax.PlayerService".equals(service.service.getClassName()))
return true;
return false;
}
public static boolean isGPodderInstalled(Context context) {
List<ProviderInfo> providerList = context.getPackageManager().queryContentProviders(null, 0, 0);
for (ProviderInfo provider : providerList)
if (provider.authority.equals("com.axelby.gpodder.podcasts"))
return true;
return false;
}
public static void registerMediaButtons(Context context) {
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
audioManager.registerMediaButtonEventReceiver(new ComponentName(context, MediaButtonIntentReceiver.class));
}
public static void unregisterMediaButtons(Context context) {
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
audioManager.unregisterMediaButtonEventReceiver(new ComponentName(context, MediaButtonIntentReceiver.class));
}
}
| true | true | public static boolean ensureWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting())
return false;
// always OK if we're on wifi
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI)
return true;
// check for wifi only pref
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("wifiPref", true))
{
Log.d("Podax", "Not downloading because Wifi is required and not connected");
return false;
}
// check for 3g data turned off
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
Log.d("Podax", "Not downloading because background data is turned off");
return false;
}
return true;
}
| public static boolean ensureWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting())
return false;
// always OK if we're on wifi
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI)
return true;
// check for wifi only pref
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("wifiPref", true))
{
Log.d("Podax", "Not downloading because Wifi is required and not connected");
return false;
}
// check for 3g data turned off
if (!netInfo.isConnected()) {
Log.d("Podax", "Not downloading because background data is turned off");
return false;
}
return true;
}
|
diff --git a/src/main/java/net/tsuttsu305/tundereportmapper/TunderePortMapper.java b/src/main/java/net/tsuttsu305/tundereportmapper/TunderePortMapper.java
index 0eeac50..279a572 100644
--- a/src/main/java/net/tsuttsu305/tundereportmapper/TunderePortMapper.java
+++ b/src/main/java/net/tsuttsu305/tundereportmapper/TunderePortMapper.java
@@ -1,132 +1,134 @@
/**
* TunderePortMapper - Package: net.tsuttsu305.tundereportmapper
* Created: 2013/04/23 18:08:55
*/
package net.tsuttsu305.tundereportmapper;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
/**
* TunderePortMapper (TunderePortMapper.java)
* @author tsuttsu305
*/
public class TunderePortMapper extends JavaPlugin{
private static TunderePortMapper plugin;
public static int PORT;
public static boolean StartUPOpen;
private Mapper mapper = null;
@Override
public void onEnable() {
if (Bukkit.getOnlineMode() == false){
getLogger().warning("\n\n##############################\n\n\n!!!!! OnlineMode == false !!!!!\n\n\n##############################");
getLogger().warning("Detected a license violation. Server Shutdown.");
Bukkit.shutdown();
}
plugin = this;
getConfig().options().copyDefaults(true);
getConfig().addDefault("port", 25565);
getConfig().addDefault("startUpOpen", false);
saveConfig();
PORT = getConfig().getInt("port");
StartUPOpen = getConfig().getBoolean("startUpOpen");
if (StartUPOpen){
portOpen();
}
}
private void portOpen() {
mapper = new Mapper(PORT, plugin);
try {
mapper.openTCP();
} catch (Exception e) {
e.printStackTrace();
mapper = null;
}
}
@Override
public void onDisable() {
if (mapper != null){
mapper.closeTCP();
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("port")){
- if (args.length != 2){
+ if (args.length != 1){
sender.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
if (sender instanceof Player){
Player player = (Player)sender;
if (player.hasPermission("port.admin")){
if (args[0].equalsIgnoreCase("open")){
if (mapper != null){
player.sendMessage(ChatColor.RED + "Port is already open.");
return true;
}
portOpen();
player.sendMessage(ChatColor.GREEN + "Port Open. SUCCESS");
return true;
}else if (args[0].equalsIgnoreCase("close")){
if (mapper == null){
player.sendMessage(ChatColor.RED + "Port is already close.");
return true;
}
mapper.closeTCP();
+ mapper = null;
player.sendMessage(ChatColor.GREEN + "Port close. SUCCESS");
return true;
}else{
player.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
}
}else{
if (args[0].equalsIgnoreCase("open")){
if (mapper != null){
sender.sendMessage(ChatColor.RED + "Port is already open.");
return true;
}
portOpen();
sender.sendMessage(ChatColor.GREEN + "Port Open. SUCCESS");
return true;
}else if (args[0].equalsIgnoreCase("close")){
if (mapper == null){
sender.sendMessage(ChatColor.RED + "Port is already close.");
return true;
}
mapper.closeTCP();
+ mapper = null;
sender.sendMessage(ChatColor.GREEN + "Port close. SUCCESS");
return true;
}else{
sender.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
}
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("port")){
if (args.length != 2){
sender.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
if (sender instanceof Player){
Player player = (Player)sender;
if (player.hasPermission("port.admin")){
if (args[0].equalsIgnoreCase("open")){
if (mapper != null){
player.sendMessage(ChatColor.RED + "Port is already open.");
return true;
}
portOpen();
player.sendMessage(ChatColor.GREEN + "Port Open. SUCCESS");
return true;
}else if (args[0].equalsIgnoreCase("close")){
if (mapper == null){
player.sendMessage(ChatColor.RED + "Port is already close.");
return true;
}
mapper.closeTCP();
player.sendMessage(ChatColor.GREEN + "Port close. SUCCESS");
return true;
}else{
player.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
}
}else{
if (args[0].equalsIgnoreCase("open")){
if (mapper != null){
sender.sendMessage(ChatColor.RED + "Port is already open.");
return true;
}
portOpen();
sender.sendMessage(ChatColor.GREEN + "Port Open. SUCCESS");
return true;
}else if (args[0].equalsIgnoreCase("close")){
if (mapper == null){
sender.sendMessage(ChatColor.RED + "Port is already close.");
return true;
}
mapper.closeTCP();
sender.sendMessage(ChatColor.GREEN + "Port close. SUCCESS");
return true;
}else{
sender.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("port")){
if (args.length != 1){
sender.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
if (sender instanceof Player){
Player player = (Player)sender;
if (player.hasPermission("port.admin")){
if (args[0].equalsIgnoreCase("open")){
if (mapper != null){
player.sendMessage(ChatColor.RED + "Port is already open.");
return true;
}
portOpen();
player.sendMessage(ChatColor.GREEN + "Port Open. SUCCESS");
return true;
}else if (args[0].equalsIgnoreCase("close")){
if (mapper == null){
player.sendMessage(ChatColor.RED + "Port is already close.");
return true;
}
mapper.closeTCP();
mapper = null;
player.sendMessage(ChatColor.GREEN + "Port close. SUCCESS");
return true;
}else{
player.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
}
}else{
if (args[0].equalsIgnoreCase("open")){
if (mapper != null){
sender.sendMessage(ChatColor.RED + "Port is already open.");
return true;
}
portOpen();
sender.sendMessage(ChatColor.GREEN + "Port Open. SUCCESS");
return true;
}else if (args[0].equalsIgnoreCase("close")){
if (mapper == null){
sender.sendMessage(ChatColor.RED + "Port is already close.");
return true;
}
mapper.closeTCP();
mapper = null;
sender.sendMessage(ChatColor.GREEN + "Port close. SUCCESS");
return true;
}else{
sender.sendMessage(ChatColor.RED + command.getUsage());
return true;
}
}
}
return false;
}
|
diff --git a/plugins/org.bonitasoft.studio.migration/src/org/bonitasoft/studio/migration/custom/migration/form/FileWidgetActionMigration.java b/plugins/org.bonitasoft.studio.migration/src/org/bonitasoft/studio/migration/custom/migration/form/FileWidgetActionMigration.java
index 0c69335fb9..6189f910d2 100644
--- a/plugins/org.bonitasoft.studio.migration/src/org/bonitasoft/studio/migration/custom/migration/form/FileWidgetActionMigration.java
+++ b/plugins/org.bonitasoft.studio.migration/src/org/bonitasoft/studio/migration/custom/migration/form/FileWidgetActionMigration.java
@@ -1,74 +1,82 @@
/**
* 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.studio.migration.custom.migration.form;
import org.bonitasoft.studio.common.ExpressionConstants;
import org.bonitasoft.studio.migration.utils.StringToExpressionConverter;
import org.eclipse.emf.edapt.migration.CustomMigration;
import org.eclipse.emf.edapt.migration.Instance;
import org.eclipse.emf.edapt.migration.Metamodel;
import org.eclipse.emf.edapt.migration.MigrationException;
import org.eclipse.emf.edapt.migration.Model;
/**
* @author Romain Bioteau
*
*/
public class FileWidgetActionMigration extends CustomMigration {
@Override
public void migrateAfter(Model model, Metamodel metamodel)
throws MigrationException {
for(Instance fileWidget : model.getAllInstances("form.FileWidget")){
String documentName = fileWidget.get("outputDocumentName");
if(documentName != null){
Instance storageExpression = StringToExpressionConverter.createExpressionInstance(model,
documentName,
documentName,
String.class.getName(),
ExpressionConstants.DOCUMENT_REF_TYPE,
false);
String widgetId = "field_"+fileWidget.get("name");
Instance actionExpression = StringToExpressionConverter.createExpressionInstance(model,
widgetId,
widgetId,
ExpressionConstants.DOCUMENT_VALUE_RETURN_TYPE,
ExpressionConstants.FORM_FIELD_TYPE,
false);
final Instance operator = model.newInstance("expression.Operator");
operator.set("type", ExpressionConstants.SET_DOCUMENT_OPERATOR);
+ final Instance oldOperation = fileWidget.get("action");
+ if(oldOperation != null){
+ model.delete(oldOperation);
+ }
final Instance actionOperation = StringToExpressionConverter.createOperation(model, storageExpression, operator, actionExpression);
fileWidget.set("action", actionOperation);
}
}
for(Instance imageWidget : model.getAllInstances("form.ImageWidget")){
Instance document = imageWidget.get("document");
boolean isDocument = imageWidget.get("isADocument");
if(document != null && isDocument ){
String documentName = document.get("name");
Instance inputExpression = StringToExpressionConverter.createExpressionInstance(model,
documentName,
documentName,
String.class.getName(),
ExpressionConstants.DOCUMENT_REF_TYPE,
false);
+ Instance oldExpressionInstance = imageWidget.get("imgPath");
+ if(oldExpressionInstance != null){
+ model.delete(oldExpressionInstance);
+ }
imageWidget.set("imgPath", inputExpression);
}
}
}
}
| false | true | public void migrateAfter(Model model, Metamodel metamodel)
throws MigrationException {
for(Instance fileWidget : model.getAllInstances("form.FileWidget")){
String documentName = fileWidget.get("outputDocumentName");
if(documentName != null){
Instance storageExpression = StringToExpressionConverter.createExpressionInstance(model,
documentName,
documentName,
String.class.getName(),
ExpressionConstants.DOCUMENT_REF_TYPE,
false);
String widgetId = "field_"+fileWidget.get("name");
Instance actionExpression = StringToExpressionConverter.createExpressionInstance(model,
widgetId,
widgetId,
ExpressionConstants.DOCUMENT_VALUE_RETURN_TYPE,
ExpressionConstants.FORM_FIELD_TYPE,
false);
final Instance operator = model.newInstance("expression.Operator");
operator.set("type", ExpressionConstants.SET_DOCUMENT_OPERATOR);
final Instance actionOperation = StringToExpressionConverter.createOperation(model, storageExpression, operator, actionExpression);
fileWidget.set("action", actionOperation);
}
}
for(Instance imageWidget : model.getAllInstances("form.ImageWidget")){
Instance document = imageWidget.get("document");
boolean isDocument = imageWidget.get("isADocument");
if(document != null && isDocument ){
String documentName = document.get("name");
Instance inputExpression = StringToExpressionConverter.createExpressionInstance(model,
documentName,
documentName,
String.class.getName(),
ExpressionConstants.DOCUMENT_REF_TYPE,
false);
imageWidget.set("imgPath", inputExpression);
}
}
}
| public void migrateAfter(Model model, Metamodel metamodel)
throws MigrationException {
for(Instance fileWidget : model.getAllInstances("form.FileWidget")){
String documentName = fileWidget.get("outputDocumentName");
if(documentName != null){
Instance storageExpression = StringToExpressionConverter.createExpressionInstance(model,
documentName,
documentName,
String.class.getName(),
ExpressionConstants.DOCUMENT_REF_TYPE,
false);
String widgetId = "field_"+fileWidget.get("name");
Instance actionExpression = StringToExpressionConverter.createExpressionInstance(model,
widgetId,
widgetId,
ExpressionConstants.DOCUMENT_VALUE_RETURN_TYPE,
ExpressionConstants.FORM_FIELD_TYPE,
false);
final Instance operator = model.newInstance("expression.Operator");
operator.set("type", ExpressionConstants.SET_DOCUMENT_OPERATOR);
final Instance oldOperation = fileWidget.get("action");
if(oldOperation != null){
model.delete(oldOperation);
}
final Instance actionOperation = StringToExpressionConverter.createOperation(model, storageExpression, operator, actionExpression);
fileWidget.set("action", actionOperation);
}
}
for(Instance imageWidget : model.getAllInstances("form.ImageWidget")){
Instance document = imageWidget.get("document");
boolean isDocument = imageWidget.get("isADocument");
if(document != null && isDocument ){
String documentName = document.get("name");
Instance inputExpression = StringToExpressionConverter.createExpressionInstance(model,
documentName,
documentName,
String.class.getName(),
ExpressionConstants.DOCUMENT_REF_TYPE,
false);
Instance oldExpressionInstance = imageWidget.get("imgPath");
if(oldExpressionInstance != null){
model.delete(oldExpressionInstance);
}
imageWidget.set("imgPath", inputExpression);
}
}
}
|
diff --git a/code/uci/pacman/ai/Blinky.java b/code/uci/pacman/ai/Blinky.java
index d2e26d0..15f1292 100644
--- a/code/uci/pacman/ai/Blinky.java
+++ b/code/uci/pacman/ai/Blinky.java
@@ -1,112 +1,114 @@
package code.uci.pacman.ai;
import code.uci.pacman.game.*;
import code.uci.pacman.objects.controllable.*;
/**
* This class contains the AI for the red ghost, Blinky.
* @author Team Objects/AI
*
*/
public class Blinky extends Ghost{
private Direction lastDirection;
private Direction curDirection;
private boolean isBeingControlled = false;
private final static int SPEED = 7;
public Blinky(int x, int y, boolean isPlayer) {
super("blinky.png", x, y, SPEED, isPlayer);
}
public void setDirection(Direction dir)
{
isBeingControlled = true;
curDirection = dir;
}
/*
* He tries to get you by your relative position.
* He takes the fastest route to find you. I believe he
* tries to line up with you horizontally first, then vertically.
*/
@Override
public Direction getMove() {
- if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
- this.position(this.x(), 205);
- lastDirection = Direction.LEFT;
- curDirection = Direction.UP;
- }
+ int curX = this.x();
+ int curY = this.y();
+ if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
+ this.position(this.x(), 205);
+ lastDirection = Direction.LEFT;
+ curDirection = Direction.UP;
+ }
if(isBeingControlled)
{
return curDirection;
}
// as of now, this ghost just tries to get to you as fast as possible
// with some work, it could end up being very smart
// so for now this is just an example for one way of doing this
// first check to see if in scatter mode
if (this.isScattered()) {
} else {
- int curX = this.x();
- int curY = this.y();
+ //int curX = this.x();
+ //int curY = this.y();
// check to see if in center (just spawned)
if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
this.position(this.x(), 205);
lastDirection = Direction.LEFT;
curDirection = Direction.UP;
} else {
PacMan pm = GameState.getInstance().getPacMan();
int pmX = pm.x();
int pmY = pm.y();
int horizontalDifference = curX - pmX;
int verticalDifference = curY - pmY;
Direction preferredHorizontal = horizontalDifference > 0 ? Direction.LEFT : Direction.RIGHT;
Direction preferredVertical = verticalDifference > 0 ? Direction.UP : Direction.DOWN;
boolean verticalMoreImportant = Math.abs(verticalDifference) > Math.abs(horizontalDifference);
if (verticalMoreImportant)
curDirection = preferredVertical;
else
curDirection = preferredHorizontal;
if (!this.moveIsAllowed(curDirection)) {
if (verticalMoreImportant) {
if (lastDirection == Direction.LEFT || lastDirection == Direction.RIGHT) {
curDirection = lastDirection;
if (!this.moveIsAllowed(curDirection))
curDirection = curDirection == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
} else {
curDirection = preferredHorizontal;
if (!this.moveIsAllowed(curDirection)) {
curDirection = preferredHorizontal == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
if (!this.moveIsAllowed(curDirection))
curDirection = preferredVertical == Direction.UP ? Direction.DOWN : Direction.UP;
}
}
} else {
if (lastDirection == Direction.UP || lastDirection == Direction.DOWN) {
curDirection = lastDirection;
if (!this.moveIsAllowed(curDirection))
curDirection = curDirection == Direction.UP ? Direction.DOWN : Direction.UP;
} else {
curDirection = preferredVertical;
if (!this.moveIsAllowed(curDirection)) {
curDirection = preferredVertical == Direction.UP ? Direction.DOWN : Direction.UP;
if (!this.moveIsAllowed(curDirection))
curDirection = preferredHorizontal == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
}
}
}
}
}
lastDirection = curDirection;
return curDirection;
}
return null;
}
}
| false | true | public Direction getMove() {
if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
this.position(this.x(), 205);
lastDirection = Direction.LEFT;
curDirection = Direction.UP;
}
if(isBeingControlled)
{
return curDirection;
}
// as of now, this ghost just tries to get to you as fast as possible
// with some work, it could end up being very smart
// so for now this is just an example for one way of doing this
// first check to see if in scatter mode
if (this.isScattered()) {
} else {
int curX = this.x();
int curY = this.y();
// check to see if in center (just spawned)
if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
this.position(this.x(), 205);
lastDirection = Direction.LEFT;
curDirection = Direction.UP;
} else {
PacMan pm = GameState.getInstance().getPacMan();
int pmX = pm.x();
int pmY = pm.y();
int horizontalDifference = curX - pmX;
int verticalDifference = curY - pmY;
Direction preferredHorizontal = horizontalDifference > 0 ? Direction.LEFT : Direction.RIGHT;
Direction preferredVertical = verticalDifference > 0 ? Direction.UP : Direction.DOWN;
boolean verticalMoreImportant = Math.abs(verticalDifference) > Math.abs(horizontalDifference);
if (verticalMoreImportant)
curDirection = preferredVertical;
else
curDirection = preferredHorizontal;
if (!this.moveIsAllowed(curDirection)) {
if (verticalMoreImportant) {
if (lastDirection == Direction.LEFT || lastDirection == Direction.RIGHT) {
curDirection = lastDirection;
if (!this.moveIsAllowed(curDirection))
curDirection = curDirection == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
} else {
curDirection = preferredHorizontal;
if (!this.moveIsAllowed(curDirection)) {
curDirection = preferredHorizontal == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
if (!this.moveIsAllowed(curDirection))
curDirection = preferredVertical == Direction.UP ? Direction.DOWN : Direction.UP;
}
}
} else {
if (lastDirection == Direction.UP || lastDirection == Direction.DOWN) {
curDirection = lastDirection;
if (!this.moveIsAllowed(curDirection))
curDirection = curDirection == Direction.UP ? Direction.DOWN : Direction.UP;
} else {
curDirection = preferredVertical;
if (!this.moveIsAllowed(curDirection)) {
curDirection = preferredVertical == Direction.UP ? Direction.DOWN : Direction.UP;
if (!this.moveIsAllowed(curDirection))
curDirection = preferredHorizontal == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
}
}
}
}
}
lastDirection = curDirection;
return curDirection;
}
return null;
}
| public Direction getMove() {
int curX = this.x();
int curY = this.y();
if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
this.position(this.x(), 205);
lastDirection = Direction.LEFT;
curDirection = Direction.UP;
}
if(isBeingControlled)
{
return curDirection;
}
// as of now, this ghost just tries to get to you as fast as possible
// with some work, it could end up being very smart
// so for now this is just an example for one way of doing this
// first check to see if in scatter mode
if (this.isScattered()) {
} else {
//int curX = this.x();
//int curY = this.y();
// check to see if in center (just spawned)
if ((curY > 215 && curY <= 250) && (curX >= 250 && curX <= 325)) {
this.position(this.x(), 205);
lastDirection = Direction.LEFT;
curDirection = Direction.UP;
} else {
PacMan pm = GameState.getInstance().getPacMan();
int pmX = pm.x();
int pmY = pm.y();
int horizontalDifference = curX - pmX;
int verticalDifference = curY - pmY;
Direction preferredHorizontal = horizontalDifference > 0 ? Direction.LEFT : Direction.RIGHT;
Direction preferredVertical = verticalDifference > 0 ? Direction.UP : Direction.DOWN;
boolean verticalMoreImportant = Math.abs(verticalDifference) > Math.abs(horizontalDifference);
if (verticalMoreImportant)
curDirection = preferredVertical;
else
curDirection = preferredHorizontal;
if (!this.moveIsAllowed(curDirection)) {
if (verticalMoreImportant) {
if (lastDirection == Direction.LEFT || lastDirection == Direction.RIGHT) {
curDirection = lastDirection;
if (!this.moveIsAllowed(curDirection))
curDirection = curDirection == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
} else {
curDirection = preferredHorizontal;
if (!this.moveIsAllowed(curDirection)) {
curDirection = preferredHorizontal == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
if (!this.moveIsAllowed(curDirection))
curDirection = preferredVertical == Direction.UP ? Direction.DOWN : Direction.UP;
}
}
} else {
if (lastDirection == Direction.UP || lastDirection == Direction.DOWN) {
curDirection = lastDirection;
if (!this.moveIsAllowed(curDirection))
curDirection = curDirection == Direction.UP ? Direction.DOWN : Direction.UP;
} else {
curDirection = preferredVertical;
if (!this.moveIsAllowed(curDirection)) {
curDirection = preferredVertical == Direction.UP ? Direction.DOWN : Direction.UP;
if (!this.moveIsAllowed(curDirection))
curDirection = preferredHorizontal == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
}
}
}
}
}
lastDirection = curDirection;
return curDirection;
}
return null;
}
|
diff --git a/src/friskstick/cops/commands/FriskCommand.java b/src/friskstick/cops/commands/FriskCommand.java
index 717a983..16b40f8 100644
--- a/src/friskstick/cops/commands/FriskCommand.java
+++ b/src/friskstick/cops/commands/FriskCommand.java
@@ -1,158 +1,158 @@
package friskstick.cops.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import friskstick.cops.plugin.FriskStick;
import friskstick.cops.plugin.JailPlayer;
public class FriskCommand implements CommandExecutor{
private FriskStick plugin;
JailPlayer jailed = new JailPlayer();
public FriskCommand(FriskStick plugin) {
this.plugin = plugin;
}
int index = 0;
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if(sender instanceof Player) {
player = (Player)sender;
}
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(player.hasPermission("friskstick.chat") || player.isOp()) {
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
- player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
- plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
+ player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
- player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
- plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
+ player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("%cop%", player.getName()).replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
- player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
- plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
+ player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
} else {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to frisk anyone!");
}
return true;
}
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if(sender instanceof Player) {
player = (Player)sender;
}
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(player.hasPermission("friskstick.chat") || player.isOp()) {
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
} else {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to frisk anyone!");
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if(sender instanceof Player) {
player = (Player)sender;
}
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(player.hasPermission("friskstick.chat") || player.isOp()) {
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("%cop%", player.getName()).replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
} else {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to frisk anyone!");
}
return true;
}
}
return false;
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/lib/RefUpdate.java b/org.eclipse.jgit/src/org/eclipse/jgit/lib/RefUpdate.java
index 394af2953..fcf38e695 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/lib/RefUpdate.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/lib/RefUpdate.java
@@ -1,654 +1,655 @@
/*
* Copyright (C) 2008-2010, Google Inc.
* Copyright (C) 2008, Shawn O. Pearce <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.lib;
import java.io.IOException;
import java.text.MessageFormat;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevWalk;
/**
* Creates, updates or deletes any reference.
*/
public abstract class RefUpdate {
/** Status of an update request. */
public static enum Result {
/** The ref update/delete has not been attempted by the caller. */
NOT_ATTEMPTED,
/**
* The ref could not be locked for update/delete.
* <p>
* This is generally a transient failure and is usually caused by
* another process trying to access the ref at the same time as this
* process was trying to update it. It is possible a future operation
* will be successful.
*/
LOCK_FAILURE,
/**
* Same value already stored.
* <p>
* Both the old value and the new value are identical. No change was
* necessary for an update. For delete the branch is removed.
*/
NO_CHANGE,
/**
* The ref was created locally for an update, but ignored for delete.
* <p>
* The ref did not exist when the update started, but it was created
* successfully with the new value.
*/
NEW,
/**
* The ref had to be forcefully updated/deleted.
* <p>
* The ref already existed but its old value was not fully merged into
* the new value. The configuration permitted a forced update to take
* place, so ref now contains the new value. History associated with the
* objects not merged may no longer be reachable.
*/
FORCED,
/**
* The ref was updated/deleted in a fast-forward way.
* <p>
* The tracking ref already existed and its old value was fully merged
* into the new value. No history was made unreachable.
*/
FAST_FORWARD,
/**
* Not a fast-forward and not stored.
* <p>
* The tracking ref already existed but its old value was not fully
* merged into the new value. The configuration did not allow a forced
* update/delete to take place, so ref still contains the old value. No
* previous history was lost.
*/
REJECTED,
/**
* Rejected because trying to delete the current branch.
* <p>
* Has no meaning for update.
*/
REJECTED_CURRENT_BRANCH,
/**
* The ref was probably not updated/deleted because of I/O error.
* <p>
* Unexpected I/O error occurred when writing new ref. Such error may
* result in uncertain state, but most probably ref was not updated.
* <p>
* This kind of error doesn't include {@link #LOCK_FAILURE}, which is a
* different case.
*/
IO_FAILURE,
/**
* The ref was renamed from another name
* <p>
*/
RENAMED
}
/** New value the caller wants this ref to have. */
private ObjectId newValue;
/** Does this specification ask for forced updated (rewind/reset)? */
private boolean force;
/** Identity to record action as within the reflog. */
private PersonIdent refLogIdent;
/** Message the caller wants included in the reflog. */
private String refLogMessage;
/** Should the Result value be appended to {@link #refLogMessage}. */
private boolean refLogIncludeResult;
/** Old value of the ref, obtained after we lock it. */
private ObjectId oldValue;
/** If non-null, the value {@link #oldValue} must have to continue. */
private ObjectId expValue;
/** Result of the update operation. */
private Result result = Result.NOT_ATTEMPTED;
private final Ref ref;
/**
* Is this RefUpdate detaching a symbolic ref?
*
* We need this info since this.ref will normally be peeled of in case of
* detaching a symbolic ref (HEAD for example).
*
* Without this flag we cannot decide whether the ref has to be updated or
* not in case when it was a symbolic ref and the newValue == oldValue.
*/
private boolean detachingSymbolicRef;
/**
* Construct a new update operation for the reference.
* <p>
* {@code ref.getObjectId()} will be used to seed {@link #getOldObjectId()},
* which callers can use as part of their own update logic.
*
* @param ref
* the reference that will be updated by this operation.
*/
protected RefUpdate(final Ref ref) {
this.ref = ref;
oldValue = ref.getObjectId();
refLogMessage = ""; //$NON-NLS-1$
}
/** @return the reference database this update modifies. */
protected abstract RefDatabase getRefDatabase();
/** @return the repository storing the database's objects. */
protected abstract Repository getRepository();
/**
* Try to acquire the lock on the reference.
* <p>
* If the locking was successful the implementor must set the current
* identity value by calling {@link #setOldObjectId(ObjectId)}.
*
* @param deref
* true if the lock should be taken against the leaf level
* reference; false if it should be taken exactly against the
* current reference.
* @return true if the lock was acquired and the reference is likely
* protected from concurrent modification; false if it failed.
* @throws IOException
* the lock couldn't be taken due to an unexpected storage
* failure, and not because of a concurrent update.
*/
protected abstract boolean tryLock(boolean deref) throws IOException;
/** Releases the lock taken by {@link #tryLock} if it succeeded. */
protected abstract void unlock();
/**
* @param desiredResult
* @return {@code result}
* @throws IOException
*/
protected abstract Result doUpdate(Result desiredResult) throws IOException;
/**
* @param desiredResult
* @return {@code result}
* @throws IOException
*/
protected abstract Result doDelete(Result desiredResult) throws IOException;
/**
* @param target
* @return {@link Result#NEW} on success.
* @throws IOException
*/
protected abstract Result doLink(String target) throws IOException;
/**
* Get the name of the ref this update will operate on.
*
* @return name of underlying ref.
*/
public String getName() {
return getRef().getName();
}
/** @return the reference this update will create or modify. */
public Ref getRef() {
return ref;
}
/**
* Get the new value the ref will be (or was) updated to.
*
* @return new value. Null if the caller has not configured it.
*/
public ObjectId getNewObjectId() {
return newValue;
}
/**
* Tells this RefUpdate that it is actually detaching a symbolic ref.
*/
public void setDetachingSymbolicRef() {
detachingSymbolicRef = true;
}
/**
* Set the new value the ref will update to.
*
* @param id
* the new value.
*/
public void setNewObjectId(final AnyObjectId id) {
newValue = id.copy();
}
/**
* @return the expected value of the ref after the lock is taken, but before
* update occurs. Null to avoid the compare and swap test. Use
* {@link ObjectId#zeroId()} to indicate expectation of a
* non-existant ref.
*/
public ObjectId getExpectedOldObjectId() {
return expValue;
}
/**
* @param id
* the expected value of the ref after the lock is taken, but
* before update occurs. Null to avoid the compare and swap test.
* Use {@link ObjectId#zeroId()} to indicate expectation of a
* non-existant ref.
*/
public void setExpectedOldObjectId(final AnyObjectId id) {
expValue = id != null ? id.toObjectId() : null;
}
/**
* Check if this update wants to forcefully change the ref.
*
* @return true if this update should ignore merge tests.
*/
public boolean isForceUpdate() {
return force;
}
/**
* Set if this update wants to forcefully change the ref.
*
* @param b
* true if this update should ignore merge tests.
*/
public void setForceUpdate(final boolean b) {
force = b;
}
/** @return identity of the user making the change in the reflog. */
public PersonIdent getRefLogIdent() {
return refLogIdent;
}
/**
* Set the identity of the user appearing in the reflog.
* <p>
* The timestamp portion of the identity is ignored. A new identity with the
* current timestamp will be created automatically when the update occurs
* and the log record is written.
*
* @param pi
* identity of the user. If null the identity will be
* automatically determined based on the repository
* configuration.
*/
public void setRefLogIdent(final PersonIdent pi) {
refLogIdent = pi;
}
/**
* Get the message to include in the reflog.
*
* @return message the caller wants to include in the reflog; null if the
* update should not be logged.
*/
public String getRefLogMessage() {
return refLogMessage;
}
/** @return {@code true} if the ref log message should show the result. */
protected boolean isRefLogIncludingResult() {
return refLogIncludeResult;
}
/**
* Set the message to include in the reflog.
*
* @param msg
* the message to describe this change. It may be null if
* appendStatus is null in order not to append to the reflog
* @param appendStatus
* true if the status of the ref change (fast-forward or
* forced-update) should be appended to the user supplied
* message.
*/
public void setRefLogMessage(final String msg, final boolean appendStatus) {
if (msg == null && !appendStatus)
disableRefLog();
else if (msg == null && appendStatus) {
refLogMessage = ""; //$NON-NLS-1$
refLogIncludeResult = true;
} else {
refLogMessage = msg;
refLogIncludeResult = appendStatus;
}
}
/** Don't record this update in the ref's associated reflog. */
public void disableRefLog() {
refLogMessage = null;
refLogIncludeResult = false;
}
/**
* The old value of the ref, prior to the update being attempted.
* <p>
* This value may differ before and after the update method. Initially it is
* populated with the value of the ref before the lock is taken, but the old
* value may change if someone else modified the ref between the time we
* last read it and when the ref was locked for update.
*
* @return the value of the ref prior to the update being attempted; null if
* the updated has not been attempted yet.
*/
public ObjectId getOldObjectId() {
return oldValue;
}
/**
* Set the old value of the ref.
*
* @param old
* the old value.
*/
protected void setOldObjectId(ObjectId old) {
oldValue = old;
}
/**
* Get the status of this update.
* <p>
* The same value that was previously returned from an update method.
*
* @return the status of the update.
*/
public Result getResult() {
return result;
}
private void requireCanDoUpdate() {
if (newValue == null)
throw new IllegalStateException(JGitText.get().aNewObjectIdIsRequired);
}
/**
* Force the ref to take the new value.
* <p>
* This is just a convenient helper for setting the force flag, and as such
* the merge test is performed.
*
* @return the result status of the update.
* @throws IOException
* an unexpected IO error occurred while writing changes.
*/
public Result forceUpdate() throws IOException {
force = true;
return update();
}
/**
* Gracefully update the ref to the new value.
* <p>
* Merge test will be performed according to {@link #isForceUpdate()}.
* <p>
* This is the same as:
*
* <pre>
* return update(new RevWalk(getRepository()));
* </pre>
*
* @return the result status of the update.
* @throws IOException
* an unexpected IO error occurred while writing changes.
*/
public Result update() throws IOException {
RevWalk rw = new RevWalk(getRepository());
try {
return update(rw);
} finally {
rw.release();
}
}
/**
* Gracefully update the ref to the new value.
* <p>
* Merge test will be performed according to {@link #isForceUpdate()}.
*
* @param walk
* a RevWalk instance this update command can borrow to perform
* the merge test. The walk will be reset to perform the test.
* @return the result status of the update.
* @throws IOException
* an unexpected IO error occurred while writing changes.
*/
public Result update(final RevWalk walk) throws IOException {
requireCanDoUpdate();
try {
return result = updateImpl(walk, new Store() {
@Override
Result execute(Result status) throws IOException {
if (status == Result.NO_CHANGE)
return status;
return doUpdate(status);
}
});
} catch (IOException x) {
result = Result.IO_FAILURE;
throw x;
}
}
/**
* Delete the ref.
* <p>
* This is the same as:
*
* <pre>
* return delete(new RevWalk(getRepository()));
* </pre>
*
* @return the result status of the delete.
* @throws IOException
*/
public Result delete() throws IOException {
RevWalk rw = new RevWalk(getRepository());
try {
return delete(rw);
} finally {
rw.release();
}
}
/**
* Delete the ref.
*
* @param walk
* a RevWalk instance this delete command can borrow to perform
* the merge test. The walk will be reset to perform the test.
* @return the result status of the delete.
* @throws IOException
*/
public Result delete(final RevWalk walk) throws IOException {
final String myName = getRef().getLeaf().getName();
if (myName.startsWith(Constants.R_HEADS)) {
Ref head = getRefDatabase().getRef(Constants.HEAD);
while (head.isSymbolic()) {
head = head.getTarget();
if (myName.equals(head.getName()))
return result = Result.REJECTED_CURRENT_BRANCH;
}
}
try {
return result = updateImpl(walk, new Store() {
@Override
Result execute(Result status) throws IOException {
return doDelete(status);
}
});
} catch (IOException x) {
result = Result.IO_FAILURE;
throw x;
}
}
/**
* Replace this reference with a symbolic reference to another reference.
* <p>
* This exact reference (not its traversed leaf) is replaced with a symbolic
* reference to the requested name.
*
* @param target
* name of the new target for this reference. The new target name
* must be absolute, so it must begin with {@code refs/}.
* @return {@link Result#NEW} or {@link Result#FORCED} on success.
* @throws IOException
*/
public Result link(String target) throws IOException {
if (!target.startsWith(Constants.R_REFS))
throw new IllegalArgumentException(MessageFormat.format(JGitText.get().illegalArgumentNotA, Constants.R_REFS));
if (getRefDatabase().isNameConflicting(getName()))
return Result.LOCK_FAILURE;
try {
if (!tryLock(false))
return Result.LOCK_FAILURE;
final Ref old = getRefDatabase().getRef(getName());
if (old != null && old.isSymbolic()) {
final Ref dst = old.getTarget();
if (target.equals(dst.getName()))
return result = Result.NO_CHANGE;
}
if (old != null && old.getObjectId() != null)
setOldObjectId(old.getObjectId());
final Ref dst = getRefDatabase().getRef(target);
if (dst != null && dst.getObjectId() != null)
setNewObjectId(dst.getObjectId());
return result = doLink(target);
} catch (IOException x) {
result = Result.IO_FAILURE;
throw x;
} finally {
unlock();
}
}
private Result updateImpl(final RevWalk walk, final Store store)
throws IOException {
RevObject newObj;
RevObject oldObj;
- if (getRefDatabase().isNameConflicting(getName()))
+ // don't make expensive conflict check if this is an existing Ref
+ if (oldValue == null && getRefDatabase().isNameConflicting(getName()))
return Result.LOCK_FAILURE;
try {
if (!tryLock(true))
return Result.LOCK_FAILURE;
if (expValue != null) {
final ObjectId o;
o = oldValue != null ? oldValue : ObjectId.zeroId();
if (!AnyObjectId.equals(expValue, o))
return Result.LOCK_FAILURE;
}
if (oldValue == null)
return store.execute(Result.NEW);
newObj = safeParse(walk, newValue);
oldObj = safeParse(walk, oldValue);
if (newObj == oldObj && !detachingSymbolicRef)
return store.execute(Result.NO_CHANGE);
if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj))
return store.execute(Result.FAST_FORWARD);
}
if (isForceUpdate())
return store.execute(Result.FORCED);
return Result.REJECTED;
} finally {
unlock();
}
}
private static RevObject safeParse(final RevWalk rw, final AnyObjectId id)
throws IOException {
try {
return id != null ? rw.parseAny(id) : null;
} catch (MissingObjectException e) {
// We can expect some objects to be missing, like if we are
// trying to force a deletion of a branch and the object it
// points to has been pruned from the database due to freak
// corruption accidents (it happens with 'git new-work-dir').
//
return null;
}
}
/**
* Handle the abstraction of storing a ref update. This is because both
* updating and deleting of a ref have merge testing in common.
*/
private abstract class Store {
abstract Result execute(Result status) throws IOException;
}
}
| true | true | private Result updateImpl(final RevWalk walk, final Store store)
throws IOException {
RevObject newObj;
RevObject oldObj;
if (getRefDatabase().isNameConflicting(getName()))
return Result.LOCK_FAILURE;
try {
if (!tryLock(true))
return Result.LOCK_FAILURE;
if (expValue != null) {
final ObjectId o;
o = oldValue != null ? oldValue : ObjectId.zeroId();
if (!AnyObjectId.equals(expValue, o))
return Result.LOCK_FAILURE;
}
if (oldValue == null)
return store.execute(Result.NEW);
newObj = safeParse(walk, newValue);
oldObj = safeParse(walk, oldValue);
if (newObj == oldObj && !detachingSymbolicRef)
return store.execute(Result.NO_CHANGE);
if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj))
return store.execute(Result.FAST_FORWARD);
}
if (isForceUpdate())
return store.execute(Result.FORCED);
return Result.REJECTED;
} finally {
unlock();
}
}
| private Result updateImpl(final RevWalk walk, final Store store)
throws IOException {
RevObject newObj;
RevObject oldObj;
// don't make expensive conflict check if this is an existing Ref
if (oldValue == null && getRefDatabase().isNameConflicting(getName()))
return Result.LOCK_FAILURE;
try {
if (!tryLock(true))
return Result.LOCK_FAILURE;
if (expValue != null) {
final ObjectId o;
o = oldValue != null ? oldValue : ObjectId.zeroId();
if (!AnyObjectId.equals(expValue, o))
return Result.LOCK_FAILURE;
}
if (oldValue == null)
return store.execute(Result.NEW);
newObj = safeParse(walk, newValue);
oldObj = safeParse(walk, oldValue);
if (newObj == oldObj && !detachingSymbolicRef)
return store.execute(Result.NO_CHANGE);
if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj))
return store.execute(Result.FAST_FORWARD);
}
if (isForceUpdate())
return store.execute(Result.FORCED);
return Result.REJECTED;
} finally {
unlock();
}
}
|
diff --git a/activemq-web/src/main/java/org/apache/activemq/web/MessageServletSupport.java b/activemq-web/src/main/java/org/apache/activemq/web/MessageServletSupport.java
index f59813c1d..5b07102b3 100644
--- a/activemq-web/src/main/java/org/apache/activemq/web/MessageServletSupport.java
+++ b/activemq-web/src/main/java/org/apache/activemq/web/MessageServletSupport.java
@@ -1,364 +1,364 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.web;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A useful base class for any JMS related servlet; there are various ways to
* map JMS operations to web requests so we put most of the common behaviour in
* a reusable base class. This servlet can be configured with the following init
* parameters
* <dl>
* <dt>topic</dt>
* <dd>Set to 'true' if the servlet should default to using topics rather than
* channels</dd>
* <dt>destination</dt>
* <dd>The default destination to use if one is not specifiied</dd>
* <dt></dt>
* <dd></dd>
* </dl>
*
*
*/
@SuppressWarnings("serial")
public abstract class MessageServletSupport extends HttpServlet {
private static final transient Logger LOG = LoggerFactory.getLogger(MessageServletSupport.class);
private boolean defaultTopicFlag = true;
private Destination defaultDestination;
private String destinationParameter = "destination";
private String typeParameter = "type";
private String bodyParameter = "body";
private boolean defaultMessagePersistent = true;
private int defaultMessagePriority = 5;
private long defaultMessageTimeToLive;
private String destinationOptions;
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
destinationOptions = servletConfig.getInitParameter("destinationOptions");
String name = servletConfig.getInitParameter("topic");
if (name != null) {
defaultTopicFlag = asBoolean(name);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Defaulting to use topics: " + defaultTopicFlag);
}
name = servletConfig.getInitParameter("destination");
if (name != null) {
if (defaultTopicFlag) {
defaultDestination = new ActiveMQTopic(name);
} else {
defaultDestination = new ActiveMQQueue(name);
}
}
// lets check to see if there's a connection factory set
WebClient.initContext(getServletContext());
}
public static boolean asBoolean(String param) {
return asBoolean(param, false);
}
public static boolean asBoolean(String param, boolean defaultValue) {
if (param == null) {
return defaultValue;
} else {
return param.equalsIgnoreCase("true");
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void appendParametersToMessage(HttpServletRequest request, TextMessage message) throws JMSException {
Map parameterMap = request.getParameterMap();
if (parameterMap == null) {
return;
}
Map parameters = new HashMap(parameterMap);
String correlationID = asString(parameters.remove("JMSCorrelationID"));
if (correlationID != null) {
message.setJMSCorrelationID(correlationID);
}
Long expiration = asLong(parameters.remove("JMSExpiration"));
if (expiration != null) {
message.setJMSExpiration(expiration.longValue());
}
Destination replyTo = asDestination(parameters.remove("JMSReplyTo"));
if (replyTo != null) {
message.setJMSReplyTo(replyTo);
}
String type = (String)asString(parameters.remove("JMSType"));
- if (correlationID != null) {
+ if (type != null) {
message.setJMSType(type);
}
for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String name = (String)entry.getKey();
if (!destinationParameter.equals(name) && !typeParameter.equals(name) && !bodyParameter.equals(name) && !"JMSDeliveryMode".equals(name) && !"JMSPriority".equals(name)
&& !"JMSTimeToLive".equals(name)) {
Object value = entry.getValue();
if (value instanceof Object[]) {
Object[] array = (Object[])value;
if (array.length == 1) {
value = array[0];
} else {
LOG.warn("Can't use property: " + name + " which is of type: " + value.getClass().getName() + " value");
value = null;
int size = array.length;
for (int i = 0; i < size; i++) {
LOG.debug("value[" + i + "] = " + array[i]);
}
}
}
if (value != null) {
message.setObjectProperty(name, value);
}
}
}
}
protected long getSendTimeToLive(HttpServletRequest request) {
String text = request.getParameter("JMSTimeToLive");
if (text != null) {
return asLong(text);
}
return defaultMessageTimeToLive;
}
protected int getSendPriority(HttpServletRequest request) {
String text = request.getParameter("JMSPriority");
if (text != null) {
return asInt(text);
}
return defaultMessagePriority;
}
protected boolean isSendPersistent(HttpServletRequest request) {
String text = request.getParameter("JMSDeliveryMode");
if (text != null) {
return text.trim().equalsIgnoreCase("persistent");
}
return defaultMessagePersistent;
}
protected boolean isSync(HttpServletRequest request) {
String text = request.getParameter("sync");
if (text != null) {
return true;
}
return false;
}
protected Destination asDestination(Object value) {
if (value instanceof Destination) {
return (Destination)value;
}
if (value instanceof String) {
String text = (String)value;
return ActiveMQDestination.createDestination(text, ActiveMQDestination.QUEUE_TYPE);
}
if (value instanceof String[]) {
String text = ((String[])value)[0];
if (text == null) {
return null;
}
return ActiveMQDestination.createDestination(text, ActiveMQDestination.QUEUE_TYPE);
}
return null;
}
protected Integer asInteger(Object value) {
if (value instanceof Integer) {
return (Integer)value;
}
if (value instanceof String) {
return Integer.valueOf((String)value);
}
if (value instanceof String[]) {
return Integer.valueOf(((String[])value)[0]);
}
return null;
}
protected Long asLong(Object value) {
if (value instanceof Long) {
return (Long)value;
}
if (value instanceof String) {
return Long.valueOf((String)value);
}
if (value instanceof String[]) {
return Long.valueOf(((String[])value)[0]);
}
return null;
}
protected long asLong(String name) {
return Long.parseLong(name);
}
protected int asInt(String name) {
return Integer.parseInt(name);
}
protected String asString(Object value) {
if (value instanceof String[]) {
return ((String[])value)[0];
}
if (value != null) {
return value.toString();
}
return null;
}
/**
* @return the destination to use for the current request
*/
protected Destination getDestination(WebClient client, HttpServletRequest request) throws JMSException {
String destinationName = request.getParameter(destinationParameter);
if (destinationName == null || destinationName.equals("")) {
if (defaultDestination == null) {
return getDestinationFromURI(client, request);
} else {
return defaultDestination;
}
}
return getDestination(client, request, destinationName);
}
/**
* @return the destination to use for the current request using the relative
* URI from where this servlet was invoked as the destination name
*/
protected Destination getDestinationFromURI(WebClient client, HttpServletRequest request) throws JMSException {
String uri = request.getPathInfo();
if (uri == null) {
return null;
}
// replace URI separator with JMS destination separator
if (uri.startsWith("/")) {
uri = uri.substring(1);
if (uri.length() == 0) {
return null;
}
}
uri = uri.replace('/', '.');
LOG.debug("destination uri=" + uri);
return getDestination(client, request, uri);
}
/**
* @return the Destination object for the given destination name
*/
protected Destination getDestination(WebClient client, HttpServletRequest request, String destinationName) throws JMSException {
// TODO cache destinations ???
boolean isTopic = defaultTopicFlag;
if (destinationName.startsWith("topic://")) {
isTopic = true;
} else if (destinationName.startsWith("channel://") || destinationName.startsWith("queue://")) {
isTopic = false;
} else {
isTopic = isTopic(request);
}
if (destinationName.indexOf("://") != -1) {
destinationName = destinationName.substring(destinationName.indexOf("://") + 3);
}
if (destinationOptions != null) {
destinationName += "?" + destinationOptions;
}
LOG.debug(destinationName + " (" + (isTopic ? "topic" : "queue") + ")");
if (isTopic) {
return client.getSession().createTopic(destinationName);
} else {
return client.getSession().createQueue(destinationName);
}
}
/**
* @return true if the current request is for a topic destination, else
* false if its for a queue
*/
protected boolean isTopic(HttpServletRequest request) {
String typeText = request.getParameter(typeParameter);
if (typeText == null) {
return defaultTopicFlag;
}
return typeText.equalsIgnoreCase("topic");
}
/**
* @return the text that was posted to the servlet which is used as the body
* of the message to be sent
*/
protected String getPostedMessageBody(HttpServletRequest request) throws IOException {
String answer = request.getParameter(bodyParameter);
String contentType = request.getContentType();
if (answer == null && contentType != null && contentType.toLowerCase().startsWith("text/xml")) {
// lets read the message body instead
BufferedReader reader = request.getReader();
StringBuffer buffer = new StringBuffer();
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
buffer.append(line);
buffer.append("\n");
}
return buffer.toString();
}
return answer;
}
protected String getSelector(HttpServletRequest request) throws IOException {
return request.getHeader(WebClient.selectorName);
}
}
| true | true | protected void appendParametersToMessage(HttpServletRequest request, TextMessage message) throws JMSException {
Map parameterMap = request.getParameterMap();
if (parameterMap == null) {
return;
}
Map parameters = new HashMap(parameterMap);
String correlationID = asString(parameters.remove("JMSCorrelationID"));
if (correlationID != null) {
message.setJMSCorrelationID(correlationID);
}
Long expiration = asLong(parameters.remove("JMSExpiration"));
if (expiration != null) {
message.setJMSExpiration(expiration.longValue());
}
Destination replyTo = asDestination(parameters.remove("JMSReplyTo"));
if (replyTo != null) {
message.setJMSReplyTo(replyTo);
}
String type = (String)asString(parameters.remove("JMSType"));
if (correlationID != null) {
message.setJMSType(type);
}
for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String name = (String)entry.getKey();
if (!destinationParameter.equals(name) && !typeParameter.equals(name) && !bodyParameter.equals(name) && !"JMSDeliveryMode".equals(name) && !"JMSPriority".equals(name)
&& !"JMSTimeToLive".equals(name)) {
Object value = entry.getValue();
if (value instanceof Object[]) {
Object[] array = (Object[])value;
if (array.length == 1) {
value = array[0];
} else {
LOG.warn("Can't use property: " + name + " which is of type: " + value.getClass().getName() + " value");
value = null;
int size = array.length;
for (int i = 0; i < size; i++) {
LOG.debug("value[" + i + "] = " + array[i]);
}
}
}
if (value != null) {
message.setObjectProperty(name, value);
}
}
}
}
| protected void appendParametersToMessage(HttpServletRequest request, TextMessage message) throws JMSException {
Map parameterMap = request.getParameterMap();
if (parameterMap == null) {
return;
}
Map parameters = new HashMap(parameterMap);
String correlationID = asString(parameters.remove("JMSCorrelationID"));
if (correlationID != null) {
message.setJMSCorrelationID(correlationID);
}
Long expiration = asLong(parameters.remove("JMSExpiration"));
if (expiration != null) {
message.setJMSExpiration(expiration.longValue());
}
Destination replyTo = asDestination(parameters.remove("JMSReplyTo"));
if (replyTo != null) {
message.setJMSReplyTo(replyTo);
}
String type = (String)asString(parameters.remove("JMSType"));
if (type != null) {
message.setJMSType(type);
}
for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String name = (String)entry.getKey();
if (!destinationParameter.equals(name) && !typeParameter.equals(name) && !bodyParameter.equals(name) && !"JMSDeliveryMode".equals(name) && !"JMSPriority".equals(name)
&& !"JMSTimeToLive".equals(name)) {
Object value = entry.getValue();
if (value instanceof Object[]) {
Object[] array = (Object[])value;
if (array.length == 1) {
value = array[0];
} else {
LOG.warn("Can't use property: " + name + " which is of type: " + value.getClass().getName() + " value");
value = null;
int size = array.length;
for (int i = 0; i < size; i++) {
LOG.debug("value[" + i + "] = " + array[i]);
}
}
}
if (value != null) {
message.setObjectProperty(name, value);
}
}
}
}
|
diff --git a/src/main/java/com/talis/labs/tdb/tdbloader3/tdbloader3.java b/src/main/java/com/talis/labs/tdb/tdbloader3/tdbloader3.java
index 0ff146a..bdb8167 100644
--- a/src/main/java/com/talis/labs/tdb/tdbloader3/tdbloader3.java
+++ b/src/main/java/com/talis/labs/tdb/tdbloader3/tdbloader3.java
@@ -1,271 +1,271 @@
/*
* Copyright 2010,2011 Talis Systems Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.talis.labs.tdb.tdbloader3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.tdb.TDBLoader;
import com.hp.hpl.jena.tdb.base.file.Location;
import com.hp.hpl.jena.tdb.store.DatasetGraphTDB;
import com.hp.hpl.jena.tdb.sys.Names;
import com.hp.hpl.jena.tdb.sys.SetupTDB;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.talis.labs.tdb.tdbloader3.NodeTableBuilder;
public class tdbloader3 extends Configured implements Tool {
private static final Logger log = LoggerFactory.getLogger(tdbloader3.class);
@Override
public int run(String[] args) throws Exception {
if ( args.length != 2 ) {
System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName());
ToolRunner.printGenericCommandUsage(System.err);
return -1;
}
Configuration configuration = getConf();
configuration.set("runId", String.valueOf(System.currentTimeMillis()));
boolean overrideOutput = configuration.getBoolean("overrideOutput", false);
boolean copyToLocal = configuration.getBoolean("copyToLocal", true);
boolean verify = configuration.getBoolean("verify", false);
FileSystem fs = FileSystem.get(configuration);
if ( overrideOutput ) {
fs.delete(new Path(args[1]), true);
fs.delete(new Path(args[1] + "_1"), true);
fs.delete(new Path(args[1] + "_2"), true);
fs.delete(new Path(args[1] + "_3"), true);
fs.delete(new Path(args[1] + "_4"), true);
}
if ( copyToLocal ) {
File path = new File(args[1]);
path.mkdirs();
}
Tool first = new FirstDriver(configuration);
first.run(new String[] { args[0], args[1] + "_1" });
createOffsetsFile(fs, args[1] + "_1", args[1] + "_1");
Path offsets = new Path(args[1] + "_1", "offsets.txt");
DistributedCache.addCacheFile(offsets.toUri(), configuration);
Tool second = new SecondDriver(configuration);
second.run(new String[] { args[0], args[1] + "_2" });
Tool third = new ThirdDriver(configuration);
third.run(new String[] { args[1] + "_2", args[1] + "_3" });
Tool fourth = new FourthDriver(configuration);
fourth.run(new String[] { args[1] + "_3", args[1] + "_4" });
if ( copyToLocal ) {
Location location = new Location(args[1]);
DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(location) ;
dsgDisk.sync();
dsgDisk.close();
mergeToLocalFile(fs, new Path(args[1] + "_2"), args[1], configuration);
copyToLocalFile(fs, new Path(args[1] + "_4"), new Path(args[1]));
- if (!copyToLocal) {
- // TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
- NodeTableBuilder.fixNodeTable(location);
- }
+ // TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
+ NodeTableBuilder.fixNodeTable(location);
}
if ( verify ) {
DatasetGraphTDB dsgMem = load(args[0]);
Location location = new Location(args[1]);
- // TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
- NodeTableBuilder.fixNodeTable(location);
+ if (!copyToLocal) {
+ // TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
+ NodeTableBuilder.fixNodeTable(location);
+ }
DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(location) ;
boolean isomorphic = isomorphic ( dsgMem, dsgDisk );
System.out.println ("> " + isomorphic);
}
return 0;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new tdbloader3(), args);
System.exit(exitCode);
}
private void createOffsetsFile(FileSystem fs, String input, String output) throws IOException {
log.debug("Creating offsets file...");
Map<Long, Long> offsets = new TreeMap<Long, Long>();
FileStatus[] status = fs.listStatus(new Path(input));
for (FileStatus fileStatus : status) {
Path file = fileStatus.getPath();
if ( file.getName().startsWith("part-r-") ) {
log.debug("Processing: {}", file.getName());
BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(file)));
String line = in.readLine();
String[] tokens = line.split("\\s");
long partition = Long.valueOf(tokens[0]);
long offset = Long.valueOf(tokens[1]);
log.debug("Partition {} has offset {}", partition, offset);
offsets.put(partition, offset);
}
}
Path outputPath = new Path(output, "offsets.txt");
PrintWriter out = new PrintWriter(new OutputStreamWriter( fs.create(outputPath)));
for (Long partition : offsets.keySet()) {
out.println(partition + "\t" + offsets.get(partition));
}
out.close();
log.debug("Offset file created.");
}
private void copyToLocalFile ( FileSystem fs, Path src, Path dst ) throws FileNotFoundException, IOException {
FileStatus[] status = fs.listStatus(src);
for ( FileStatus fileStatus : status ) {
Path path = fileStatus.getPath();
String pathName = path.getName();
if ( pathName.startsWith("first_") || pathName.startsWith("third_") ) {
copyToLocalFile(fs, path, dst);
}
if ( pathName.endsWith(".idn") || pathName.endsWith(".dat") ) {
fs.copyToLocalFile(path, new Path(dst, path.getName()));
}
}
}
private void mergeToLocalFile ( FileSystem fs, Path src, String outPath, Configuration configuration ) throws FileNotFoundException, IOException {
FileStatus[] status = fs.listStatus(src);
Map<String, Path> paths = new TreeMap<String, Path>();
for ( FileStatus fileStatus : status ) {
Path path = fileStatus.getPath();
String pathName = path.getName();
if ( pathName.startsWith("second-alternative_") ) {
paths.put(pathName, path);
}
}
File outFile = new File(outPath, Names.indexId2Node + ".dat");
OutputStream out = new FileOutputStream(outFile);
for (String pathName : paths.keySet()) {
Path path = new Path(src, paths.get(pathName));
log.debug("Concatenating {} into {}...", path.toUri(), outFile.getAbsoluteFile());
InputStream in = fs.open(new Path(path, Names.indexId2Node + ".dat"));
IOUtils.copyBytes(in, out, configuration, false);
in.close();
}
out.close();
}
public static boolean isomorphic(DatasetGraphTDB dsgMem, DatasetGraphTDB dsgDisk) {
if (!dsgMem.getDefaultGraph().isIsomorphicWith(dsgDisk.getDefaultGraph()))
return false;
Iterator<Node> graphsMem = dsgMem.listGraphNodes();
Iterator<Node> graphsDisk = dsgDisk.listGraphNodes();
Set<Node> seen = new HashSet<Node>();
while (graphsMem.hasNext()) {
Node graphNode = graphsMem.next();
if (dsgDisk.getGraph(graphNode) == null) return false;
if (!dsgMem.getGraph(graphNode).isIsomorphicWith(dsgDisk.getGraph(graphNode))) return false;
seen.add(graphNode);
}
while (graphsDisk.hasNext()) {
Node graphNode = graphsDisk.next();
if (!seen.contains(graphNode)) {
if (dsgMem.getGraph(graphNode) == null) return false;
if (!dsgMem.getGraph(graphNode).isIsomorphicWith(dsgDisk.getGraph(graphNode))) return false;
}
}
return true;
}
public static DatasetGraphTDB load(String inputPath) {
List<String> urls = new ArrayList<String>();
for (File file : new File(inputPath).listFiles()) {
if (file.isFile()) {
urls.add(file.getAbsolutePath());
}
}
DatasetGraphTDB dsg = TDBFactory.createDatasetGraph();
TDBLoader.load(dsg, urls);
return dsg;
}
public static String dump(DatasetGraphTDB dsgMem, DatasetGraphTDB dsgDisk) {
StringBuffer sb = new StringBuffer();
sb.append("\n");
if (!dsgMem.getDefaultGraph().isIsomorphicWith(dsgDisk.getDefaultGraph())) {
sb.append("Default graphs are not isomorphic [FAIL]\n");
sb.append(" First:\n");
dump(sb, dsgMem.getDefaultGraph());
sb.append(" Second:\n");
dump(sb, dsgDisk.getDefaultGraph());
} else {
sb.append("Default graphs are isomorphic [OK]\n");
}
return sb.toString();
}
private static void dump (StringBuffer sb, Graph graph) {
ExtendedIterator<Triple> iter = graph.find(Node.ANY, Node.ANY, Node.ANY);
while ( iter.hasNext() ) {
Triple triple = iter.next();
sb.append(triple).append("\n");
}
}
}
| false | true | public int run(String[] args) throws Exception {
if ( args.length != 2 ) {
System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName());
ToolRunner.printGenericCommandUsage(System.err);
return -1;
}
Configuration configuration = getConf();
configuration.set("runId", String.valueOf(System.currentTimeMillis()));
boolean overrideOutput = configuration.getBoolean("overrideOutput", false);
boolean copyToLocal = configuration.getBoolean("copyToLocal", true);
boolean verify = configuration.getBoolean("verify", false);
FileSystem fs = FileSystem.get(configuration);
if ( overrideOutput ) {
fs.delete(new Path(args[1]), true);
fs.delete(new Path(args[1] + "_1"), true);
fs.delete(new Path(args[1] + "_2"), true);
fs.delete(new Path(args[1] + "_3"), true);
fs.delete(new Path(args[1] + "_4"), true);
}
if ( copyToLocal ) {
File path = new File(args[1]);
path.mkdirs();
}
Tool first = new FirstDriver(configuration);
first.run(new String[] { args[0], args[1] + "_1" });
createOffsetsFile(fs, args[1] + "_1", args[1] + "_1");
Path offsets = new Path(args[1] + "_1", "offsets.txt");
DistributedCache.addCacheFile(offsets.toUri(), configuration);
Tool second = new SecondDriver(configuration);
second.run(new String[] { args[0], args[1] + "_2" });
Tool third = new ThirdDriver(configuration);
third.run(new String[] { args[1] + "_2", args[1] + "_3" });
Tool fourth = new FourthDriver(configuration);
fourth.run(new String[] { args[1] + "_3", args[1] + "_4" });
if ( copyToLocal ) {
Location location = new Location(args[1]);
DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(location) ;
dsgDisk.sync();
dsgDisk.close();
mergeToLocalFile(fs, new Path(args[1] + "_2"), args[1], configuration);
copyToLocalFile(fs, new Path(args[1] + "_4"), new Path(args[1]));
if (!copyToLocal) {
// TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
NodeTableBuilder.fixNodeTable(location);
}
}
if ( verify ) {
DatasetGraphTDB dsgMem = load(args[0]);
Location location = new Location(args[1]);
// TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
NodeTableBuilder.fixNodeTable(location);
DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(location) ;
boolean isomorphic = isomorphic ( dsgMem, dsgDisk );
System.out.println ("> " + isomorphic);
}
return 0;
}
| public int run(String[] args) throws Exception {
if ( args.length != 2 ) {
System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName());
ToolRunner.printGenericCommandUsage(System.err);
return -1;
}
Configuration configuration = getConf();
configuration.set("runId", String.valueOf(System.currentTimeMillis()));
boolean overrideOutput = configuration.getBoolean("overrideOutput", false);
boolean copyToLocal = configuration.getBoolean("copyToLocal", true);
boolean verify = configuration.getBoolean("verify", false);
FileSystem fs = FileSystem.get(configuration);
if ( overrideOutput ) {
fs.delete(new Path(args[1]), true);
fs.delete(new Path(args[1] + "_1"), true);
fs.delete(new Path(args[1] + "_2"), true);
fs.delete(new Path(args[1] + "_3"), true);
fs.delete(new Path(args[1] + "_4"), true);
}
if ( copyToLocal ) {
File path = new File(args[1]);
path.mkdirs();
}
Tool first = new FirstDriver(configuration);
first.run(new String[] { args[0], args[1] + "_1" });
createOffsetsFile(fs, args[1] + "_1", args[1] + "_1");
Path offsets = new Path(args[1] + "_1", "offsets.txt");
DistributedCache.addCacheFile(offsets.toUri(), configuration);
Tool second = new SecondDriver(configuration);
second.run(new String[] { args[0], args[1] + "_2" });
Tool third = new ThirdDriver(configuration);
third.run(new String[] { args[1] + "_2", args[1] + "_3" });
Tool fourth = new FourthDriver(configuration);
fourth.run(new String[] { args[1] + "_3", args[1] + "_4" });
if ( copyToLocal ) {
Location location = new Location(args[1]);
DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(location) ;
dsgDisk.sync();
dsgDisk.close();
mergeToLocalFile(fs, new Path(args[1] + "_2"), args[1], configuration);
copyToLocalFile(fs, new Path(args[1] + "_4"), new Path(args[1]));
// TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
NodeTableBuilder.fixNodeTable(location);
}
if ( verify ) {
DatasetGraphTDB dsgMem = load(args[0]);
Location location = new Location(args[1]);
if (!copyToLocal) {
// TODO: this is a sort of a cheat and it could go away (if it turns out to be too slow)!
NodeTableBuilder.fixNodeTable(location);
}
DatasetGraphTDB dsgDisk = SetupTDB.buildDataset(location) ;
boolean isomorphic = isomorphic ( dsgMem, dsgDisk );
System.out.println ("> " + isomorphic);
}
return 0;
}
|
diff --git a/src/play/modules/thymeleaf/dialect/ProcessorUtil.java b/src/play/modules/thymeleaf/dialect/ProcessorUtil.java
index 56acb95..2390d10 100644
--- a/src/play/modules/thymeleaf/dialect/ProcessorUtil.java
+++ b/src/play/modules/thymeleaf/dialect/ProcessorUtil.java
@@ -1,107 +1,107 @@
/*
* Copyright 2012 Satoshi Takata
*
* 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 play.modules.thymeleaf.dialect;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.thymeleaf.Arguments;
import org.thymeleaf.standard.expression.OgnlVariableExpressionEvaluator;
import play.Logger;
import play.exceptions.ActionNotFoundException;
import play.mvc.ActionInvoker;
import play.mvc.Router;
import play.mvc.Http.Request;
import play.utils.Java;
/**
* Utility class for processor expressions.
*/
class ProcessorUtil {
private static final Pattern PARAM_PATTERN = Pattern.compile("^\\s*.*?\\((.*)\\)\\s*$");
private ProcessorUtil() {
}
/**
* Parses the playframework action expressions. The string inside "()" is
* evaluated by OGNL in the current context.
*
* @param arguments
* @param attributeValue
* e.g. "Application.show(obj.id)"
* @return parsed action path
*/
@SuppressWarnings("unchecked")
static String toActionString(final Arguments arguments, String attributeValue) {
Matcher matcher = PARAM_PATTERN.matcher(attributeValue);
if (!matcher.matches()) {
return Router.reverse(attributeValue)
.toString();
}
String exp = matcher.group(1);
if (StringUtils.isBlank(exp)) {
return Router.reverse(attributeValue)
.toString();
}
- Object obj = OgnlVariableExpressionEvaluator.INSTANCE.evaluate(arguments.getConfiguration(), arguments, exp, false);
+ Object obj = PlayOgnlVariableExpressionEvaluator.INSTANCE.evaluate(arguments.getConfiguration(), arguments, exp, false);
if (obj instanceof Map) {
return Router.reverse(attributeValue, (Map<String, Object>) obj)
.toString();
}
List<?> list = obj instanceof List ? (List<?>) obj : Arrays.asList(obj);
Map<String, Object> paramMap = new HashMap<String, Object>();
String extracted = StringUtils.substringBefore(attributeValue, "(");
if (!extracted.contains(".")) {
extracted = Request.current().controller + "." + extracted;
}
Object[] actionMethods = ActionInvoker.getActionMethod(extracted);
String[] paramNames = null;
try {
paramNames = Java.parameterNames((Method) actionMethods[1]);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (paramNames.length < list.size()) {
Logger.warn("param length unmatched. %s", Arrays.toString(paramNames));
throw new ActionNotFoundException(attributeValue, null);
}
for (int i = 0; i < list.size(); i++) {
paramMap.put(paramNames[i], list.get(i));
}
return Router.reverse(extracted, paramMap)
.toString();
}
}
| true | true | static String toActionString(final Arguments arguments, String attributeValue) {
Matcher matcher = PARAM_PATTERN.matcher(attributeValue);
if (!matcher.matches()) {
return Router.reverse(attributeValue)
.toString();
}
String exp = matcher.group(1);
if (StringUtils.isBlank(exp)) {
return Router.reverse(attributeValue)
.toString();
}
Object obj = OgnlVariableExpressionEvaluator.INSTANCE.evaluate(arguments.getConfiguration(), arguments, exp, false);
if (obj instanceof Map) {
return Router.reverse(attributeValue, (Map<String, Object>) obj)
.toString();
}
List<?> list = obj instanceof List ? (List<?>) obj : Arrays.asList(obj);
Map<String, Object> paramMap = new HashMap<String, Object>();
String extracted = StringUtils.substringBefore(attributeValue, "(");
if (!extracted.contains(".")) {
extracted = Request.current().controller + "." + extracted;
}
Object[] actionMethods = ActionInvoker.getActionMethod(extracted);
String[] paramNames = null;
try {
paramNames = Java.parameterNames((Method) actionMethods[1]);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (paramNames.length < list.size()) {
Logger.warn("param length unmatched. %s", Arrays.toString(paramNames));
throw new ActionNotFoundException(attributeValue, null);
}
for (int i = 0; i < list.size(); i++) {
paramMap.put(paramNames[i], list.get(i));
}
return Router.reverse(extracted, paramMap)
.toString();
}
| static String toActionString(final Arguments arguments, String attributeValue) {
Matcher matcher = PARAM_PATTERN.matcher(attributeValue);
if (!matcher.matches()) {
return Router.reverse(attributeValue)
.toString();
}
String exp = matcher.group(1);
if (StringUtils.isBlank(exp)) {
return Router.reverse(attributeValue)
.toString();
}
Object obj = PlayOgnlVariableExpressionEvaluator.INSTANCE.evaluate(arguments.getConfiguration(), arguments, exp, false);
if (obj instanceof Map) {
return Router.reverse(attributeValue, (Map<String, Object>) obj)
.toString();
}
List<?> list = obj instanceof List ? (List<?>) obj : Arrays.asList(obj);
Map<String, Object> paramMap = new HashMap<String, Object>();
String extracted = StringUtils.substringBefore(attributeValue, "(");
if (!extracted.contains(".")) {
extracted = Request.current().controller + "." + extracted;
}
Object[] actionMethods = ActionInvoker.getActionMethod(extracted);
String[] paramNames = null;
try {
paramNames = Java.parameterNames((Method) actionMethods[1]);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (paramNames.length < list.size()) {
Logger.warn("param length unmatched. %s", Arrays.toString(paramNames));
throw new ActionNotFoundException(attributeValue, null);
}
for (int i = 0; i < list.size(); i++) {
paramMap.put(paramNames[i], list.get(i));
}
return Router.reverse(extracted, paramMap)
.toString();
}
|
diff --git a/loci/jvmlink/ConnThread.java b/loci/jvmlink/ConnThread.java
index b0b2287..1cc1be6 100644
--- a/loci/jvmlink/ConnThread.java
+++ b/loci/jvmlink/ConnThread.java
@@ -1,744 +1,744 @@
//
// ConnThread.java
//
/*
JVMLink client/server architecture for communicating between Java and
non-Java programs using sockets.
Copyright (c) 2008 Hidayath Ansari and Curtis Rueden. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the UW-Madison LOCI 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 UW-MADISON LOCI ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 loci.jvmlink;
import java.io.*;
import java.lang.reflect.Array;
import java.net.*;
import loci.formats.DataTools;
import loci.formats.ReflectException;
import loci.formats.ReflectedUniverse;
//TODO: Communicating exceptions ..
/**
* Thread for managing a client/server socket connection.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/jvmlink/ConnThread.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/jvmlink/ConnThread.java">SVN</a></dd></dl>
*/
public class ConnThread extends Thread {
// -- Constants --
public static final int MAX_PACKET_SIZE = 65536;
public static final int ORDER_VALUE = 1;
public static final int ARRAY_TYPE = 0;
public static final int INT_TYPE = 1;
public static final int STRING_TYPE = 2;
public static final int BYTE_TYPE = 3;
public static final int CHAR_TYPE = 4;
public static final int FLOAT_TYPE = 5;
public static final int BOOLEAN_TYPE = 6;
public static final int DOUBLE_TYPE = 7;
public static final int LONG_TYPE = 8;
public static final int SHORT_TYPE = 9;
public static final int NULL_TYPE = -1;
public static final int BYTE_ORDER = 0;
public static final int SETVAR = 1;
public static final int GETVAR = 2;
public static final int EXEC = 3;
public static final int EXIT = 255;
// -- Static fields --
private static int threadNumber = 0;
// -- Fields --
private Socket socket;
private JVMLinkServer server;
private ReflectedUniverse r;
private DataInputStream in;
private DataOutputStream out;
/**
* True for little endian (intel) byte order,
* false for big endian (motorola) order.
*/
private boolean little;
// -- Constructor --
public ConnThread(Socket socket, JVMLinkServer server) throws IOException {
super("JVMLink-Client-" + (++threadNumber));
this.socket = socket;
this.server = server;
r = new ReflectedUniverse();
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
little = true;
start();
}
/*
* Protocol syntax:
*
* First thing on the stream is an integer:
* 0 - byte order
* 1 - setVar
* 2 - getVar
* 3 - exec
* 255 - terminate server
*
* For byte order, the integer 1 in the desired byte order
*
* For the other commands, a string (prefixed by its length), specifying:
* setVar, getVar : identifier in question
* exec : command to be executed
*
* Then, according to which branch:
* setVar:
* 0 - array (followed by another integer specifying one of the following
* types, then an integer specifying length of array)
* 1-9 - int, string, byte, char, float, bool, double, long, short
* (in order)
*
* getVar (sends):
* 0 - array (followed by another integer specifying one of the following
* types, then length)
* 1-9 - int, string, byte, char, float, bool, double, long, short
* (in order)
*/
// -- Thread API methods --
public void run() {
boolean killServer = false;
while (true) {
try {
int command = readInt();
debug("Received command: " + getCommand(command));
if (command == EXIT) {
killServer = true;
break;
}
switch (command) {
case BYTE_ORDER:
byteOrder();
break;
case SETVAR:
setVar();
break;
case GETVAR:
getVar();
break;
case EXEC:
exec();
break;
}
}
catch (EOFException exc) {
// client disconnected
debug("EOF reached; client probably disconnected");
break;
}
catch (SocketException exc) {
// connection error
debug("Socket error; connection lost");
break;
}
catch (IOException exc) {
if (JVMLinkServer.debug) exc.printStackTrace();
try {
Thread.sleep(100);
}
catch (InterruptedException exc2) {
if (JVMLinkServer.debug) exc2.printStackTrace();
}
}
catch (ReflectException exc) {
if (JVMLinkServer.debug) exc.printStackTrace();
}
}
debug("Exiting");
try {
socket.close();
}
catch (IOException exc) {
if (JVMLinkServer.debug) exc.printStackTrace();
}
if (killServer) {
try {
server.shutServer();
}
catch (IOException exc) {
if (JVMLinkServer.debug) exc.printStackTrace();
}
}
}
// -- Helper methods --
/** Changes the byte order between big and little endian. */
private void byteOrder() throws IOException {
int bigType = in.readInt();
int littleType = DataTools.swap(bigType);
if (bigType == ORDER_VALUE) little = false; // big endian
else if (littleType == ORDER_VALUE) little = true; // little endian
else debug("Invalid byte order value: 0x" + Integer.toString(bigType, 16));
}
/**
* Performs a SETVAR command, including reading arguments
* from the input stream.
*/
private void setVar() throws IOException {
String name = readString();
int type = readInt();
Object value = null;
if (type == ARRAY_TYPE) {
int insideType = readInt();
int arrayLength = readInt();
int size = getSize(insideType);
Object theArray = null;
if (insideType == INT_TYPE) {
int[] intArray = new int[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
intArray[i + (readBytes/4)] =
DataTools.bytesToInt(b, 4*i, little);
}
readBytes += packetSize;
}
theArray = intArray;
}
else if (insideType == STRING_TYPE) {
String[] stringArray = new String[arrayLength];
for (int i=0; i<arrayLength; i++) {
stringArray[i] = readString();
}
theArray = stringArray;
}
else if (insideType == BYTE_TYPE) {
byte[] byteArray = new byte[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
in.readFully(byteArray, readBytes, packetSize);
readBytes += packetSize;
}
theArray = byteArray;
}
else if (insideType == CHAR_TYPE) {
char[] charArray = new char[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize; i++) {
charArray[i + readBytes] = (char)
((0x00 << 8) | (b[i] & 0xff));
}
readBytes += packetSize;
}
theArray = charArray;
}
else if (insideType == FLOAT_TYPE) {
float[] floatArray = new float[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
floatArray[i + readBytes/4] =
Float.intBitsToFloat(DataTools.bytesToInt(b, 4*i, little));
}
readBytes += packetSize;
}
theArray = floatArray;
}
else if (insideType == BOOLEAN_TYPE) {
boolean[] boolArray = new boolean[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize; i++) {
boolArray[i + readBytes] = b[i] != 0;
}
readBytes += packetSize;
}
theArray = boolArray;
}
else if (insideType == DOUBLE_TYPE) {
double[] doubleArray = new double[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/8; i++) {
doubleArray[i + readBytes/8] =
Double.longBitsToDouble(DataTools.bytesToLong(b, 8*i, little));
}
readBytes += packetSize;
}
theArray = doubleArray;
}
else if (insideType == LONG_TYPE) {
long[] longArray = new long[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
- byte[] b = new byte[packetSize];
+ byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/8; i++) {
longArray[i + readBytes/8] =
DataTools.bytesToLong(b, 8*i, little);
}
readBytes += packetSize;
}
theArray = longArray;
}
else if (insideType == SHORT_TYPE) {
short[] shortArray = new short[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
- for (int i=0; i<packetSize/4; i++) {
- shortArray[i + readBytes/4] =
- DataTools.bytesToShort(b, 4*i, little);
+ for (int i=0; i<packetSize/2; i++) {
+ shortArray[i + readBytes/2] =
+ DataTools.bytesToShort(b, 2*i, little);
}
readBytes += packetSize;
}
theArray = shortArray;
}
value = theArray;
}
else if (type == INT_TYPE) value = new Integer(readInt());
else if (type == STRING_TYPE) value = readString();
else if (type == BYTE_TYPE) value = new Byte(in.readByte());
else if (type == CHAR_TYPE) value = new Character((char) in.readByte());
else if (type == FLOAT_TYPE) value = new Float(readFloat());
else if (type == BOOLEAN_TYPE) value = new Boolean(in.readBoolean());
else if (type == DOUBLE_TYPE) value = new Double(readDouble());
else if (type == LONG_TYPE) value = new Long(readLong());
else if (type == SHORT_TYPE) value = new Short(readShort());
debug("setVar (" + type + "): " + name + " = " + getValue(value));
if (value != null) r.setVar(name, value);
}
/**
* Performs a GETVAR command, including reading arguments
* from the input stream and sending results to the output stream.
*/
private void getVar() throws IOException {
String name = readString();
int insideType = 0;
int type = 0;
Object value = null;
try {
value = r.getVar(name);
debug("getVar: " + name + " = " + getValue(value));
if (value instanceof int[]) {
type = ARRAY_TYPE;
insideType = INT_TYPE;
}
else if (value instanceof String[]) {
type = ARRAY_TYPE;
insideType = STRING_TYPE;
}
else if (value instanceof byte[]) {
type = ARRAY_TYPE;
insideType = BYTE_TYPE;
}
else if (value instanceof char[]) {
type = ARRAY_TYPE;
insideType = CHAR_TYPE;
}
else if (value instanceof float[]) {
type = ARRAY_TYPE;
insideType = FLOAT_TYPE;
}
else if (value instanceof boolean[]) {
type = ARRAY_TYPE;
insideType = BOOLEAN_TYPE;
}
else if (value instanceof double[]) {
type = ARRAY_TYPE;
insideType = DOUBLE_TYPE;
}
else if (value instanceof long[]) {
type = ARRAY_TYPE;
insideType = LONG_TYPE;
}
else if (value instanceof short[]) {
type = ARRAY_TYPE;
insideType = SHORT_TYPE;
}
else if (value instanceof Integer) type = INT_TYPE;
else if (value instanceof String) type = STRING_TYPE;
else if (value instanceof Byte) type = BYTE_TYPE;
else if (value instanceof Character) type = CHAR_TYPE;
else if (value instanceof Float) type = FLOAT_TYPE;
else if (value instanceof Boolean) type = BOOLEAN_TYPE;
else if (value instanceof Double) type = DOUBLE_TYPE;
else if (value instanceof Long) type = LONG_TYPE;
else if (value instanceof Short) type = SHORT_TYPE;
else type = INT_TYPE; //default
}
catch (ReflectException e) {
if (JVMLinkServer.debug) e.printStackTrace();
}
writeInt(type);
if (type == ARRAY_TYPE) {
Object theArray = value;
writeInt(insideType);
int arrayLen = Array.getLength(theArray);
writeInt(arrayLen);
if (insideType == INT_TYPE) {
writeInt(4);
int[] intArray = (int[]) theArray;
for (int i=0; i<arrayLen; i++) {
writeInt(intArray[i]);
}
if (arrayLen > 10000) {
debug("Last two elements are " +
intArray[arrayLen-1] + " and " + intArray[arrayLen-2]);
}
}
else if (insideType == STRING_TYPE) {
//untested. probably quite messed up.
writeInt(4);
String[] sArray = (String[]) theArray;
for (int i=0; i<arrayLen; i++) out.write(sArray[i].getBytes());
}
else if (insideType == BYTE_TYPE) {
writeInt(1);
byte[] bArray = (byte[]) theArray;
for (int i=0; i<arrayLen; i++) out.writeByte(bArray[i]);
}
else if (insideType == CHAR_TYPE) {
writeInt(1);
char[] cArray = (char[]) theArray;
for (int i=0; i<arrayLen; i++) out.writeByte((byte) cArray[i]);
}
else if (insideType == FLOAT_TYPE) {
writeInt(4);
float[] fArray = (float[]) theArray;
for (int i=0; i<arrayLen; i++) {
int intBits = Float.floatToIntBits(fArray[i]);
writeInt(intBits);
}
}
else if (insideType == BOOLEAN_TYPE) {
writeInt(1);
boolean[] bArray = (boolean[]) theArray;
for (int i=0; i<arrayLen; i++) out.writeBoolean(bArray[i]);
}
else if (insideType == DOUBLE_TYPE) {
writeInt(8);
double[] dArray = (double[]) theArray;
for (int i=0; i<arrayLen; i++) {
writeLong(Double.doubleToLongBits(dArray[i]));
}
}
else if (insideType == LONG_TYPE) {
writeInt(8);
long[] lArray = (long[]) theArray;
for (int i=0; i<arrayLen; i++) writeLong(lArray[i]);
}
else if (insideType == SHORT_TYPE) {
writeInt(2);
short[] sArray = (short[]) theArray;
for (int i=0; i<arrayLen; i++) writeShort(sArray[i]);
}
}
else if (type == INT_TYPE) {
int val = ((Integer) value).intValue();
writeInt(4);
writeInt(val);
}
else if (type == STRING_TYPE) {
String val = (String) value;
writeString(val);
}
else if (type == BYTE_TYPE) {
byte val = ((Byte) value).byteValue();
writeInt(1);
out.writeByte(val);
}
else if (type == CHAR_TYPE) {
char val = ((Character) value).charValue();
writeInt(1);
out.writeByte((byte) val);
}
else if (type == FLOAT_TYPE) {
float val = ((Float) value).floatValue();
writeInt(4);
writeInt(Float.floatToIntBits(val));
}
else if (type == BOOLEAN_TYPE) {
boolean val = ((Boolean) value).booleanValue();
writeInt(1);
out.writeBoolean(val);
}
else if (type == DOUBLE_TYPE) {
double val = ((Double) value).doubleValue();
writeInt(8);
writeLong(Double.doubleToLongBits(val));
}
else if (type == LONG_TYPE) {
long val = ((Long) value).longValue();
writeInt(8);
writeLong(val);
}
else if (type == SHORT_TYPE) {
short val = ((Short) value).shortValue();
writeInt(2);
writeShort(val);
}
out.flush();
}
/**
* Performs an EXEC command, including reading arguments
* from the input stream.
*/
private void exec() throws IOException, ReflectException {
String cmd = readString();
debug("exec: " + cmd);
r.exec(cmd);
}
// - I/O helper methods -
/** Reads a short from the socket with the correct endianness. */
private short readShort() throws IOException {
short value = in.readShort();
if (little) value = DataTools.swap(value);
return value;
}
/** Reads an int from the socket with the correct endianness. */
private int readInt() throws IOException {
int value = in.readInt();
if (little) value = DataTools.swap(value);
return value;
}
/** Reads a long from the socket with the correct endianness. */
private long readLong() throws IOException {
long value = in.readLong();
if (little) value = DataTools.swap(value);
return value;
}
/** Reads a float from the socket with the correct endianness. */
private float readFloat() throws IOException {
float readFloat = in.readFloat();
int intRep = Float.floatToIntBits(readFloat);
if (little) intRep = DataTools.swap(intRep);
float value = Float.intBitsToFloat(intRep);
return value;
}
/** Reads a double from the socket with the correct endianness. */
private double readDouble() throws IOException {
double readDouble = in.readDouble();
long longRep = Double.doubleToLongBits(readDouble);
if (little) longRep = DataTools.swap(longRep);
double value = Double.longBitsToDouble(longRep);
return value;
}
/** Reads a string from the socket. */
private String readString() throws IOException {
int len = readInt();
byte[] bytes = new byte[len];
in.readFully(bytes, 0, len);
return new String(bytes);
}
/** Writes the given short to the socket with the correct endianness. */
private void writeShort(short value) throws IOException {
out.writeShort(little ? DataTools.swap(value) : value);
}
/** Writes the given int to the socket with the correct endianness. */
private void writeInt(int value) throws IOException {
out.writeInt(little ? DataTools.swap(value) : value);
}
/** Writes the given long to the socket with the correct endianness. */
private void writeLong(long value) throws IOException {
out.writeLong(little ? DataTools.swap(value) : value);
}
/** Writes the given string to the socket. */
private void writeString(String value) throws IOException {
writeInt(value.length());
out.write(value.getBytes());
}
// - Debugging helper methods -
/** Prints a debugging message if debug mode is enabled. */
private void debug(String msg) {
if (JVMLinkServer.debug) System.out.println(getName() + ": " + msg);
}
// -- Static utility methods --
public static String getType(int type) {
switch (type) {
case ARRAY_TYPE:
return "ARRAY";
case INT_TYPE:
return "INT";
case STRING_TYPE:
return "STRING";
case BYTE_TYPE:
return "BYTE";
case CHAR_TYPE:
return "CHAR";
case FLOAT_TYPE:
return "FLOAT";
case BOOLEAN_TYPE:
return "BOOLEAN";
case DOUBLE_TYPE:
return "DOUBLE";
case LONG_TYPE:
return "LONG";
case SHORT_TYPE:
return "SHORT";
default:
return "UNKNOWN [" + type + "]";
}
}
public static String getCommand(int cmd) {
switch (cmd) {
case BYTE_ORDER:
return "BYTE_ORDER";
case SETVAR:
return "SETVAR";
case GETVAR:
return "GETVAR";
case EXEC:
return "EXEC";
case EXIT:
return "EXIT";
default:
return "UNKNOWN [" + cmd + "]";
}
}
public static int getSize(int type) {
switch (type) {
case BYTE_TYPE:
case CHAR_TYPE:
case BOOLEAN_TYPE:
case NULL_TYPE:
return 1;
case SHORT_TYPE:
return 2;
case INT_TYPE:
case FLOAT_TYPE:
return 4;
case DOUBLE_TYPE:
case LONG_TYPE:
return 8;
case STRING_TYPE: // string size is variable
default:
return 0;
}
}
public static String getValue(Object value) {
if (value == null) return null;
String val;
try {
int len = Array.getLength(value);
StringBuffer sb = new StringBuffer();
sb.append("[");
boolean str = false;
for (int i=0; i<len; i++) {
Object o = Array.get(value, i);
str = o instanceof String;
sb.append(str ? "\n\t" : " ");
sb.append(o);
}
sb.append(str ? "\n" : " ");
sb.append("]");
val = sb.toString();
}
catch (IllegalArgumentException exc) {
val = value.toString();
}
return val;
}
}
| false | true | private void setVar() throws IOException {
String name = readString();
int type = readInt();
Object value = null;
if (type == ARRAY_TYPE) {
int insideType = readInt();
int arrayLength = readInt();
int size = getSize(insideType);
Object theArray = null;
if (insideType == INT_TYPE) {
int[] intArray = new int[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
intArray[i + (readBytes/4)] =
DataTools.bytesToInt(b, 4*i, little);
}
readBytes += packetSize;
}
theArray = intArray;
}
else if (insideType == STRING_TYPE) {
String[] stringArray = new String[arrayLength];
for (int i=0; i<arrayLength; i++) {
stringArray[i] = readString();
}
theArray = stringArray;
}
else if (insideType == BYTE_TYPE) {
byte[] byteArray = new byte[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
in.readFully(byteArray, readBytes, packetSize);
readBytes += packetSize;
}
theArray = byteArray;
}
else if (insideType == CHAR_TYPE) {
char[] charArray = new char[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize; i++) {
charArray[i + readBytes] = (char)
((0x00 << 8) | (b[i] & 0xff));
}
readBytes += packetSize;
}
theArray = charArray;
}
else if (insideType == FLOAT_TYPE) {
float[] floatArray = new float[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
floatArray[i + readBytes/4] =
Float.intBitsToFloat(DataTools.bytesToInt(b, 4*i, little));
}
readBytes += packetSize;
}
theArray = floatArray;
}
else if (insideType == BOOLEAN_TYPE) {
boolean[] boolArray = new boolean[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize; i++) {
boolArray[i + readBytes] = b[i] != 0;
}
readBytes += packetSize;
}
theArray = boolArray;
}
else if (insideType == DOUBLE_TYPE) {
double[] doubleArray = new double[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/8; i++) {
doubleArray[i + readBytes/8] =
Double.longBitsToDouble(DataTools.bytesToLong(b, 8*i, little));
}
readBytes += packetSize;
}
theArray = doubleArray;
}
else if (insideType == LONG_TYPE) {
long[] longArray = new long[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/8; i++) {
longArray[i + readBytes/8] =
DataTools.bytesToLong(b, 8*i, little);
}
readBytes += packetSize;
}
theArray = longArray;
}
else if (insideType == SHORT_TYPE) {
short[] shortArray = new short[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
shortArray[i + readBytes/4] =
DataTools.bytesToShort(b, 4*i, little);
}
readBytes += packetSize;
}
theArray = shortArray;
}
value = theArray;
}
else if (type == INT_TYPE) value = new Integer(readInt());
else if (type == STRING_TYPE) value = readString();
else if (type == BYTE_TYPE) value = new Byte(in.readByte());
else if (type == CHAR_TYPE) value = new Character((char) in.readByte());
else if (type == FLOAT_TYPE) value = new Float(readFloat());
else if (type == BOOLEAN_TYPE) value = new Boolean(in.readBoolean());
else if (type == DOUBLE_TYPE) value = new Double(readDouble());
else if (type == LONG_TYPE) value = new Long(readLong());
else if (type == SHORT_TYPE) value = new Short(readShort());
debug("setVar (" + type + "): " + name + " = " + getValue(value));
if (value != null) r.setVar(name, value);
}
| private void setVar() throws IOException {
String name = readString();
int type = readInt();
Object value = null;
if (type == ARRAY_TYPE) {
int insideType = readInt();
int arrayLength = readInt();
int size = getSize(insideType);
Object theArray = null;
if (insideType == INT_TYPE) {
int[] intArray = new int[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
intArray[i + (readBytes/4)] =
DataTools.bytesToInt(b, 4*i, little);
}
readBytes += packetSize;
}
theArray = intArray;
}
else if (insideType == STRING_TYPE) {
String[] stringArray = new String[arrayLength];
for (int i=0; i<arrayLength; i++) {
stringArray[i] = readString();
}
theArray = stringArray;
}
else if (insideType == BYTE_TYPE) {
byte[] byteArray = new byte[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
in.readFully(byteArray, readBytes, packetSize);
readBytes += packetSize;
}
theArray = byteArray;
}
else if (insideType == CHAR_TYPE) {
char[] charArray = new char[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize; i++) {
charArray[i + readBytes] = (char)
((0x00 << 8) | (b[i] & 0xff));
}
readBytes += packetSize;
}
theArray = charArray;
}
else if (insideType == FLOAT_TYPE) {
float[] floatArray = new float[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/4; i++) {
floatArray[i + readBytes/4] =
Float.intBitsToFloat(DataTools.bytesToInt(b, 4*i, little));
}
readBytes += packetSize;
}
theArray = floatArray;
}
else if (insideType == BOOLEAN_TYPE) {
boolean[] boolArray = new boolean[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize; i++) {
boolArray[i + readBytes] = b[i] != 0;
}
readBytes += packetSize;
}
theArray = boolArray;
}
else if (insideType == DOUBLE_TYPE) {
double[] doubleArray = new double[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/8; i++) {
doubleArray[i + readBytes/8] =
Double.longBitsToDouble(DataTools.bytesToLong(b, 8*i, little));
}
readBytes += packetSize;
}
theArray = doubleArray;
}
else if (insideType == LONG_TYPE) {
long[] longArray = new long[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/8; i++) {
longArray[i + readBytes/8] =
DataTools.bytesToLong(b, 8*i, little);
}
readBytes += packetSize;
}
theArray = longArray;
}
else if (insideType == SHORT_TYPE) {
short[] shortArray = new short[arrayLength];
int readBytes = 0, totalBytes = size*arrayLength;
while (readBytes < totalBytes) {
int packetSize = MAX_PACKET_SIZE;
if (readBytes + MAX_PACKET_SIZE > totalBytes) {
packetSize = totalBytes - readBytes;
}
byte[] b = new byte[packetSize];
in.readFully(b, 0, packetSize);
for (int i=0; i<packetSize/2; i++) {
shortArray[i + readBytes/2] =
DataTools.bytesToShort(b, 2*i, little);
}
readBytes += packetSize;
}
theArray = shortArray;
}
value = theArray;
}
else if (type == INT_TYPE) value = new Integer(readInt());
else if (type == STRING_TYPE) value = readString();
else if (type == BYTE_TYPE) value = new Byte(in.readByte());
else if (type == CHAR_TYPE) value = new Character((char) in.readByte());
else if (type == FLOAT_TYPE) value = new Float(readFloat());
else if (type == BOOLEAN_TYPE) value = new Boolean(in.readBoolean());
else if (type == DOUBLE_TYPE) value = new Double(readDouble());
else if (type == LONG_TYPE) value = new Long(readLong());
else if (type == SHORT_TYPE) value = new Short(readShort());
debug("setVar (" + type + "): " + name + " = " + getValue(value));
if (value != null) r.setVar(name, value);
}
|
diff --git a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/MockAuthorizationServerFilter.java b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/MockAuthorizationServerFilter.java
index 9edd9c73..d3d358c9 100644
--- a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/MockAuthorizationServerFilter.java
+++ b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/util/MockAuthorizationServerFilter.java
@@ -1,49 +1,49 @@
/*
* 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 nl.surfnet.coin.selfservice.util;
import org.surfnet.oaaas.auth.AuthorizationServerFilter;
import org.surfnet.oaaas.auth.principal.AuthenticatedPrincipal;
import org.surfnet.oaaas.conext.SAMLAuthenticatedPrincipal;
import org.surfnet.oaaas.model.VerifyTokenResponse;
import javax.servlet.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
public class MockAuthorizationServerFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- AuthenticatedPrincipal principal = new SAMLAuthenticatedPrincipal("john.doe", Arrays.asList(new String[]{"user"}), new HashMap<String, String>(), Arrays.asList(new String[]{"showroom_shopmanager"}), "https://mujina-idp.acc.showroom.surfconext.nl/", "John Doe");
+ AuthenticatedPrincipal principal = new SAMLAuthenticatedPrincipal("john.doe", Arrays.asList(new String[]{"user"}), new HashMap<String, String>(), Arrays.asList(new String[]{"showroom_shopmanager"}), "https://mujina-idp.acc.showroom.surfconext.nl/", "John Doe", false);
VerifyTokenResponse tokenResponse = new VerifyTokenResponse("client-name-mocked", Arrays.asList(new String[]{"read"}), principal, null);
request.setAttribute(AuthorizationServerFilter.VERIFY_TOKEN_RESPONSE, tokenResponse);
chain.doFilter(request, response);
}
}
| true | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
AuthenticatedPrincipal principal = new SAMLAuthenticatedPrincipal("john.doe", Arrays.asList(new String[]{"user"}), new HashMap<String, String>(), Arrays.asList(new String[]{"showroom_shopmanager"}), "https://mujina-idp.acc.showroom.surfconext.nl/", "John Doe");
VerifyTokenResponse tokenResponse = new VerifyTokenResponse("client-name-mocked", Arrays.asList(new String[]{"read"}), principal, null);
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
AuthenticatedPrincipal principal = new SAMLAuthenticatedPrincipal("john.doe", Arrays.asList(new String[]{"user"}), new HashMap<String, String>(), Arrays.asList(new String[]{"showroom_shopmanager"}), "https://mujina-idp.acc.showroom.surfconext.nl/", "John Doe", false);
VerifyTokenResponse tokenResponse = new VerifyTokenResponse("client-name-mocked", Arrays.asList(new String[]{"read"}), principal, null);
|
diff --git a/src/main/java/sk/opendatanode/ui/HomePage.java b/src/main/java/sk/opendatanode/ui/HomePage.java
index 0d5abf9..4c77351 100644
--- a/src/main/java/sk/opendatanode/ui/HomePage.java
+++ b/src/main/java/sk/opendatanode/ui/HomePage.java
@@ -1,47 +1,47 @@
package sk.opendatanode.ui;
import java.io.IOException;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sk.opendatanode.ui.search.SearchQueryPage;
import sk.opendatanode.ui.search.SearchResultPage;
import sk.opendatanode.utils.SolrQueryHelper;
/**
* Homepage
*/
public class HomePage extends WebPage {
private static final long serialVersionUID = -3362496726021637053L;
private Logger logger = LoggerFactory.getLogger(HomePage.class);
/**
* Constructor that is invoked when page is invoked without a session.
*
* @param params
* Page parameters
*/
- public HomePage(PageParameters parameters) {
+ public HomePage(final PageParameters parameters) {
SearchQueryPage sp = new SearchQueryPage("searchPage", parameters);
add(sp);
QueryResponse response = null;
try {
response = SolrQueryHelper.search(parameters);
} catch (IOException e) {
logger.error("IOException error", e);
} catch (SolrServerException e) {
logger.error("SolrServerException",e);
}
SearchResultPage srp = new SearchResultPage("searchResultPage", parameters, response);
add(srp);
}
}
| true | true | public HomePage(PageParameters parameters) {
SearchQueryPage sp = new SearchQueryPage("searchPage", parameters);
add(sp);
QueryResponse response = null;
try {
response = SolrQueryHelper.search(parameters);
} catch (IOException e) {
logger.error("IOException error", e);
} catch (SolrServerException e) {
logger.error("SolrServerException",e);
}
SearchResultPage srp = new SearchResultPage("searchResultPage", parameters, response);
add(srp);
}
| public HomePage(final PageParameters parameters) {
SearchQueryPage sp = new SearchQueryPage("searchPage", parameters);
add(sp);
QueryResponse response = null;
try {
response = SolrQueryHelper.search(parameters);
} catch (IOException e) {
logger.error("IOException error", e);
} catch (SolrServerException e) {
logger.error("SolrServerException",e);
}
SearchResultPage srp = new SearchResultPage("searchResultPage", parameters, response);
add(srp);
}
|
diff --git a/aQute.libg/src/aQute/lib/getopt/CommandLine.java b/aQute.libg/src/aQute/lib/getopt/CommandLine.java
index 18436dd14..9a7015e88 100644
--- a/aQute.libg/src/aQute/lib/getopt/CommandLine.java
+++ b/aQute.libg/src/aQute/lib/getopt/CommandLine.java
@@ -1,580 +1,581 @@
package aQute.lib.getopt;
import java.lang.reflect.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.*;
import aQute.configurable.*;
import aQute.lib.justif.*;
import aQute.lib.markdown.*;
import aQute.libg.generics.*;
import aQute.libg.reporter.*;
import aQute.service.reporter.*;
/**
* Helps parsing command lines. This class takes target object, a primary
* command, and a list of arguments. It will then find the command in the target
* object. The method of this command must start with a "_" and take an
* parameter of Options type. Usually this is an interface that extends Options.
* The methods on this interface are options or flags (when they return
* boolean).
*/
@SuppressWarnings("unchecked")
public class CommandLine {
static int LINELENGTH = 60;
static Pattern ASSIGNMENT = Pattern.compile("(\\w[\\w\\d]*+)\\s*=\\s*([^\\s]+)\\s*");
Reporter reporter;
Justif justif = new Justif(80,30,32,70);
CommandLineMessages msg;
class Option {
public char shortcut;
public String name;
public String paramType;
public String description;
public boolean required;
}
public CommandLine(Reporter reporter) {
this.reporter = reporter;
msg = ReporterMessages.base(reporter, CommandLineMessages.class);
}
/**
* Execute a command in a target object with a set of options and arguments
* and returns help text if something fails. Errors are reported.
*/
public String execute(Object target, String cmd, List<String> input) throws Exception {
if (cmd.equals("help")) {
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);
if (input.isEmpty())
help(f, target);
else {
for (String s : input) {
help(f, target, s);
}
}
f.flush();
justif.wrap(sb);
return sb.toString();
}
//
// Find the appropriate method
//
List<String> arguments = new ArrayList<String>(input);
Map<String,Method> commands = getCommands(target);
Method m = commands.get(cmd);
if (m == null) {
msg.NoSuchCommand_(cmd);
return help(target, null, null);
}
//
// Parse the options
//
Class< ? extends Options> optionClass = (Class< ? extends Options>) m.getParameterTypes()[0];
Options options = getOptions(optionClass, arguments);
if (options == null) {
// had some error, already reported
return help(target, cmd, null);
}
// Check if we have an @Arguments annotation that
// provides patterns for the remainder arguments
Arguments argumentsAnnotation = optionClass.getAnnotation(Arguments.class);
if (argumentsAnnotation != null) {
String[] patterns = argumentsAnnotation.arg();
// Check for commands without any arguments
if (patterns.length == 0 && arguments.size() > 0) {
msg.TooManyArguments_(arguments);
return help(target, cmd, null);
}
// Match the patterns to the given command line
int i = 0;
for (; i < patterns.length; i++) {
String pattern = patterns[i];
boolean optional = pattern.matches("\\[.*\\]");
// Handle vararg
if (pattern.contains("...")) {
i = Integer.MAX_VALUE;
break;
}
// Check if we're running out of args
if (i >= arguments.size()) {
- if (!optional)
+ if (!optional) {
msg.MissingArgument_(patterns[i]);
- return help(target, cmd, optionClass);
+ return help(target, cmd, optionClass);
+ }
}
}
// Check if we have unconsumed arguments left
if (i < arguments.size()) {
msg.TooManyArguments_(arguments);
return help(target, cmd, optionClass);
}
}
if (reporter.getErrors().size() == 0) {
m.setAccessible(true);
m.invoke(target, options);
return null;
}
return help(target, cmd, optionClass);
}
public void generateDocumentation(Object target,Appendable out) {
MarkdownFormatter f = new MarkdownFormatter(out);
f.h1("Available Commands:");
Map<String,Method> commands = getCommands(target);
for(String command : commands.keySet()) {
Class< ? extends Options> specification = (Class< ? extends Options>) commands.get(command).getParameterTypes()[0];
Map<String,Method> options = getOptions(specification);
Arguments patterns = specification.getAnnotation(Arguments.class);
f.h2(command);
Description descr = specification.getAnnotation(Description.class);
if (descr != null) {
f.format(descr.value()+"%n%n");
}
f.h3("Synopsis:");
f.code(getSynopsys(command, options, patterns));
if (!options.isEmpty()) {
f.h3("Options:");
for (Entry<String,Method> entry : options.entrySet()) {
Option option = getOption(entry.getKey(), entry.getValue());
f.inlineCode("%s -%s --%s %s%s",
option.required ? " " : "[", //
option.shortcut, //
option.name,
option.paramType, //
option.required ? " " : "]");
if (option.description != null) {
f.format("%s", option.description);
f.endP();
}
}
f.format("%n");
}
}
f.flush();
}
private String help(Object target, String cmd, Class< ? extends Options> type) throws Exception {
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);
if (cmd == null)
help(f, target);
else if (type == null)
help(f, target, cmd);
else
help(f, target, cmd, type);
f.flush();
justif.wrap(sb);
return sb.toString();
}
/**
* Parse the options in a command line and return an interface that provides
* the options from this command line. This will parse up to (and including)
* -- or an argument that does not start with -
*/
public <T extends Options> T getOptions(Class<T> specification, List<String> arguments) throws Exception {
Map<String,String> properties = Create.map();
Map<String,Object> values = new HashMap<String,Object>();
Map<String,Method> options = getOptions(specification);
argloop: while (arguments.size() > 0) {
String option = arguments.get(0);
if (option.startsWith("-")) {
arguments.remove(0);
if (option.startsWith("--")) {
if ("--".equals(option))
break argloop;
// Full named option, e.g. --output
String name = option.substring(2);
Method m = options.get(name);
if (m == null) { // Maybe due to capitalization modif
m = options.get(Character.toLowerCase(name.charAt(0))+name.substring(1));
}
if (m == null)
msg.UnrecognizedOption_(name);
else
assignOptionValue(values, m, arguments, true);
} else {
// Set of single character named options like -a
charloop: for (int j = 1; j < option.length(); j++) {
char optionChar = option.charAt(j);
for (Entry<String,Method> entry : options.entrySet()) {
if (entry.getKey().charAt(0) == optionChar) {
boolean last = (j + 1) >= option.length();
assignOptionValue(values, entry.getValue(), arguments, last);
continue charloop;
}
}
msg.UnrecognizedOption_(optionChar + "");
}
}
} else {
Matcher m = ASSIGNMENT.matcher(option);
if (m.matches()) {
properties.put(m.group(1), m.group(2));
}
break;
}
}
// check if all required elements are set
for (Entry<String,Method> entry : options.entrySet()) {
Method m = entry.getValue();
String name = entry.getKey();
if (!values.containsKey(name) && isMandatory(m))
msg.OptionNotSet_(name);
}
values.put(".", arguments);
values.put(".command", this);
values.put(".properties", properties);
return Configurable.createConfigurable(specification, values);
}
/**
* Answer a list of the options specified in an options interface
*/
private Map<String,Method> getOptions(Class< ? extends Options> interf) {
Map<String,Method> map = new TreeMap<String,Method>(String.CASE_INSENSITIVE_ORDER);
for (Method m : interf.getMethods()) {
if (m.getName().startsWith("_"))
continue;
String name;
Config cfg = m.getAnnotation(Config.class);
if (cfg == null || cfg.id() == null || cfg.id().equals(Config.NULL))
name = m.getName();
else
name = cfg.id();
map.put(name, m);
}
// In case two options have the same first char, uppercase one of them
// In case 3+ --------------------------------, throw an error
char prevChar = '\0';
boolean throwOnNextMatch = false;
Map<String, Method> toModify = new HashMap<String,Method>();
for (String name : map.keySet()) {
if(Character.toLowerCase(name.charAt(0)) != name.charAt(0)) { //
throw new Error("Only commands with lower case first char are acceptable ("+name+")");
}
if(Character.toLowerCase(name.charAt(0)) == prevChar) {
if(throwOnNextMatch) {
throw new Error("3 options with same first letter (one is: "+name+")");
} else {
toModify.put(name, map.get(name));
throwOnNextMatch = true;
}
} else {
throwOnNextMatch = false;
prevChar = name.charAt(0);
}
}
for (String name : toModify.keySet()) {
map.remove(name);
String newName = Character.toUpperCase(name.charAt(0))+name.substring(1);
map.put(newName, toModify.get(name));
}
return map;
}
/**
* Assign an option, must handle flags, parameters, and parameters that can
* happen multiple times.
*
* @param options
* The command line map
* @param args
* the args input
* @param i
* where we are
* @param m
* the selected method for this option
* @param last
* if this is the last in a multi single character option
* @return
*/
public void assignOptionValue(Map<String,Object> options, Method m, List<String> args, boolean last) {
String name = m.getName();
Type type = m.getGenericReturnType();
if (isOption(m)) {
// The option is a simple flag
options.put(name, true);
} else {
// The option is followed by an argument
if (!last) {
msg.Option__WithArgumentNotLastInAbbreviation_(name, name.charAt(0), getTypeDescriptor(type));
return;
}
if (args.isEmpty()) {
msg.MissingArgument__(name, name.charAt(0));
return;
}
String parameter = args.remove(0);
if (Collection.class.isAssignableFrom(m.getReturnType())) {
Collection<Object> optionValues = (Collection<Object>) options.get(m.getName());
if (optionValues == null) {
optionValues = new ArrayList<Object>();
options.put(name, optionValues);
}
optionValues.add(parameter);
} else {
if (options.containsKey(name)) {
msg.OptionCanOnlyOccurOnce_(name);
return;
}
options.put(name, parameter);
}
}
}
/**
* Provide a help text.
*/
public void help(Formatter f,
Object target, String cmd, Class< ? extends Options> specification) {
Description descr = specification.getAnnotation(Description.class);
Arguments patterns = specification.getAnnotation(Arguments.class);
Map<String,Method> options = getOptions(specification);
String description = descr == null ? "" : descr.value();
f.format("%nNAME%n %s \t0- \t1%s%n%n", cmd, description);
f.format("SYNOPSIS%n");
f.format(getSynopsys(cmd, options, patterns));
if (!options.isEmpty()) {
f.format("%nOPTIONS%n%n");
for (Entry<String,Method> entry : options.entrySet()) {
Option option = getOption(entry.getKey(), entry.getValue());
f.format(" %s -%s, --%s %s%s \t0- \t1%s%n", option.required ? " " : "[", //
option.shortcut, //
option.name,
option.paramType, //
option.required ? " " : "]",//
option.description);
}
f.format("%n");
}
}
private Option getOption(String optionName, Method m) {
Option option = new Option();
Config cfg = m.getAnnotation(Config.class);
Description d = m.getAnnotation(Description.class);
option.shortcut = optionName.charAt(0);
option.name = Character.toLowerCase(optionName.charAt(0))+optionName.substring(1);
option.description = cfg != null ? cfg.description() : (d == null ? "" : d.value());
option.required = isMandatory(m);
String pt = getTypeDescriptor(m.getGenericReturnType());
if(pt.length() != 0)
pt += " ";
option.paramType = pt;
return option;
}
private String getSynopsys(String cmd, Map<String,Method> options, Arguments patterns) {
StringBuilder sb = new StringBuilder();
if (options.isEmpty())
sb.append(String.format(" %s ", cmd));
else
sb.append(String.format(" %s [options] ", cmd));
if (patterns == null)
sb.append(String.format(" ...%n%n"));
else {
String del = " ";
for (String pattern : patterns.arg()) {
if (pattern.equals("..."))
sb.append(String.format("%s...", del));
else
sb.append(String.format("%s<%s>", del, pattern));
del = " ";
}
sb.append(String.format("%n"));
}
return sb.toString();
}
static Pattern LAST_PART = Pattern.compile(".*[\\$\\.]([^\\$\\.]+)");
private static String lastPart(String name) {
Matcher m = LAST_PART.matcher(name);
if (m.matches())
return m.group(1);
return name;
}
/**
* Show all commands in a target
*/
public void help(Formatter f, Object target) throws Exception {
f.format("%n");
Description descr = target.getClass().getAnnotation(Description.class);
if (descr != null) {
f.format("%s%n%n", descr.value());
}
f.format("Available commands: %n%n");
for (Entry<String,Method> e : getCommands(target).entrySet()) {
Description d = e.getValue().getAnnotation(Description.class);
String desc = " ";
if ( d != null)
desc = d.value();
f.format(" %s\t0-\t1%s %n", e.getKey(), desc);
}
f.format("%n");
}
/**
* Show the full help for a given command
*/
public void help(Formatter f, Object target, String cmd) {
Method m = getCommands(target).get(cmd);
if (m == null)
f.format("No such command: %s%n", cmd);
else {
Class< ? extends Options> options = (Class< ? extends Options>) m.getParameterTypes()[0];
help(f, target, cmd, options);
}
}
/**
* Parse a class and return a list of command names
*
* @param target
* @return
*/
public Map<String,Method> getCommands(Object target) {
Map<String,Method> map = new TreeMap<String,Method>();
for (Method m : target.getClass().getMethods()) {
if (m.getParameterTypes().length == 1 && m.getName().startsWith("_")) {
Class< ? > clazz = m.getParameterTypes()[0];
if (Options.class.isAssignableFrom(clazz)) {
String name = m.getName().substring(1);
map.put(name, m);
}
}
}
return map;
}
/**
* Answer if the method is marked mandatory
*/
private boolean isMandatory(Method m) {
Config cfg = m.getAnnotation(Config.class);
if (cfg == null)
return false;
return cfg.required();
}
/**
* @param m
* @return
*/
private boolean isOption(Method m) {
return m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class;
}
/**
* Show a type in a nice way
*/
private String getTypeDescriptor(Type type) {
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type c = pt.getRawType();
if (c instanceof Class) {
if (Collection.class.isAssignableFrom((Class< ? >) c)) {
return getTypeDescriptor(pt.getActualTypeArguments()[0]) + "*";
}
}
}
if (!(type instanceof Class))
return "<>";
Class< ? > clazz = (Class< ? >) type;
if (clazz == Boolean.class || clazz == boolean.class)
return ""; // Is a flag
return "<" + lastPart(clazz.getName().toLowerCase()) + ">";
}
}
| false | true | public String execute(Object target, String cmd, List<String> input) throws Exception {
if (cmd.equals("help")) {
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);
if (input.isEmpty())
help(f, target);
else {
for (String s : input) {
help(f, target, s);
}
}
f.flush();
justif.wrap(sb);
return sb.toString();
}
//
// Find the appropriate method
//
List<String> arguments = new ArrayList<String>(input);
Map<String,Method> commands = getCommands(target);
Method m = commands.get(cmd);
if (m == null) {
msg.NoSuchCommand_(cmd);
return help(target, null, null);
}
//
// Parse the options
//
Class< ? extends Options> optionClass = (Class< ? extends Options>) m.getParameterTypes()[0];
Options options = getOptions(optionClass, arguments);
if (options == null) {
// had some error, already reported
return help(target, cmd, null);
}
// Check if we have an @Arguments annotation that
// provides patterns for the remainder arguments
Arguments argumentsAnnotation = optionClass.getAnnotation(Arguments.class);
if (argumentsAnnotation != null) {
String[] patterns = argumentsAnnotation.arg();
// Check for commands without any arguments
if (patterns.length == 0 && arguments.size() > 0) {
msg.TooManyArguments_(arguments);
return help(target, cmd, null);
}
// Match the patterns to the given command line
int i = 0;
for (; i < patterns.length; i++) {
String pattern = patterns[i];
boolean optional = pattern.matches("\\[.*\\]");
// Handle vararg
if (pattern.contains("...")) {
i = Integer.MAX_VALUE;
break;
}
// Check if we're running out of args
if (i >= arguments.size()) {
if (!optional)
msg.MissingArgument_(patterns[i]);
return help(target, cmd, optionClass);
}
}
// Check if we have unconsumed arguments left
if (i < arguments.size()) {
msg.TooManyArguments_(arguments);
return help(target, cmd, optionClass);
}
}
if (reporter.getErrors().size() == 0) {
m.setAccessible(true);
m.invoke(target, options);
return null;
}
return help(target, cmd, optionClass);
}
| public String execute(Object target, String cmd, List<String> input) throws Exception {
if (cmd.equals("help")) {
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);
if (input.isEmpty())
help(f, target);
else {
for (String s : input) {
help(f, target, s);
}
}
f.flush();
justif.wrap(sb);
return sb.toString();
}
//
// Find the appropriate method
//
List<String> arguments = new ArrayList<String>(input);
Map<String,Method> commands = getCommands(target);
Method m = commands.get(cmd);
if (m == null) {
msg.NoSuchCommand_(cmd);
return help(target, null, null);
}
//
// Parse the options
//
Class< ? extends Options> optionClass = (Class< ? extends Options>) m.getParameterTypes()[0];
Options options = getOptions(optionClass, arguments);
if (options == null) {
// had some error, already reported
return help(target, cmd, null);
}
// Check if we have an @Arguments annotation that
// provides patterns for the remainder arguments
Arguments argumentsAnnotation = optionClass.getAnnotation(Arguments.class);
if (argumentsAnnotation != null) {
String[] patterns = argumentsAnnotation.arg();
// Check for commands without any arguments
if (patterns.length == 0 && arguments.size() > 0) {
msg.TooManyArguments_(arguments);
return help(target, cmd, null);
}
// Match the patterns to the given command line
int i = 0;
for (; i < patterns.length; i++) {
String pattern = patterns[i];
boolean optional = pattern.matches("\\[.*\\]");
// Handle vararg
if (pattern.contains("...")) {
i = Integer.MAX_VALUE;
break;
}
// Check if we're running out of args
if (i >= arguments.size()) {
if (!optional) {
msg.MissingArgument_(patterns[i]);
return help(target, cmd, optionClass);
}
}
}
// Check if we have unconsumed arguments left
if (i < arguments.size()) {
msg.TooManyArguments_(arguments);
return help(target, cmd, optionClass);
}
}
if (reporter.getErrors().size() == 0) {
m.setAccessible(true);
m.invoke(target, options);
return null;
}
return help(target, cmd, optionClass);
}
|
diff --git a/src/com/jonathanedgecombe/interpreter/ast/IfStatement.java b/src/com/jonathanedgecombe/interpreter/ast/IfStatement.java
index 8f500ef..d058be2 100644
--- a/src/com/jonathanedgecombe/interpreter/ast/IfStatement.java
+++ b/src/com/jonathanedgecombe/interpreter/ast/IfStatement.java
@@ -1,72 +1,73 @@
package com.jonathanedgecombe.interpreter.ast;
import com.jonathanedgecombe.interpreter.Interpreter;
public final class IfStatement extends Statement {
private final Expression leftExpression, rightExpression;
private final Statement statement;
private final OperatorType relationalOperator;
public IfStatement(int label, Expression leftExpression, Expression rightExpression, OperatorType relationalOperator, Statement statement) {
super(label);
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
this.relationalOperator = relationalOperator;
this.statement = statement;
}
public Expression getLeftExpression() {
return leftExpression;
}
public Expression getRightExpression() {
return rightExpression;
}
public OperatorType getRelationalOperator() {
return relationalOperator;
}
public Statement getStatement() {
return statement;
}
@Override
public String toString() {
return "IF " + leftExpression + " " + relationalOperator + " " + rightExpression + " THEN " + statement + " ";
}
@Override
public void run(Interpreter interpreter) {
int left = leftExpression.evaluate(interpreter).getValue();
int right = rightExpression.evaluate(interpreter).getValue();
boolean flag;
switch (relationalOperator) {
case EQUAL:
flag = (left == right);
break;
case LESSTHAN:
flag = (left < right);
break;
case LESSTHANOREQUAL:
flag = (left <= right);
break;
case GREATERTHAN:
flag = (left > right);
break;
case GREATERTHANOREQUAL:
flag = (left >= right);
break;
case NOTEQUAL:
flag = (left != right);
+ break;
default:
flag = false;
}
if (flag) {
statement.run(interpreter);
}
}
}
| true | true | public void run(Interpreter interpreter) {
int left = leftExpression.evaluate(interpreter).getValue();
int right = rightExpression.evaluate(interpreter).getValue();
boolean flag;
switch (relationalOperator) {
case EQUAL:
flag = (left == right);
break;
case LESSTHAN:
flag = (left < right);
break;
case LESSTHANOREQUAL:
flag = (left <= right);
break;
case GREATERTHAN:
flag = (left > right);
break;
case GREATERTHANOREQUAL:
flag = (left >= right);
break;
case NOTEQUAL:
flag = (left != right);
default:
flag = false;
}
if (flag) {
statement.run(interpreter);
}
}
| public void run(Interpreter interpreter) {
int left = leftExpression.evaluate(interpreter).getValue();
int right = rightExpression.evaluate(interpreter).getValue();
boolean flag;
switch (relationalOperator) {
case EQUAL:
flag = (left == right);
break;
case LESSTHAN:
flag = (left < right);
break;
case LESSTHANOREQUAL:
flag = (left <= right);
break;
case GREATERTHAN:
flag = (left > right);
break;
case GREATERTHANOREQUAL:
flag = (left >= right);
break;
case NOTEQUAL:
flag = (left != right);
break;
default:
flag = false;
}
if (flag) {
statement.run(interpreter);
}
}
|
diff --git a/src/de/uulm/datalove/swu2gtfs/swu2gtfs.java b/src/de/uulm/datalove/swu2gtfs/swu2gtfs.java
index 1671c28..f7800b8 100644
--- a/src/de/uulm/datalove/swu2gtfs/swu2gtfs.java
+++ b/src/de/uulm/datalove/swu2gtfs/swu2gtfs.java
@@ -1,54 +1,54 @@
package de.uulm.datalove.swu2gtfs;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
public class swu2gtfs {
public static int tripCounter = 0;
public static int routeCounter = 0;
protected static HashMap<String, Route> routes = new HashMap<String, Route>(22);
public static void main(String[] args) {
new Parser(args, routes);
for( String name: routes.keySet() )
{
Route currentRoute = routes.get(name);
routeCounter++;
tripCounter = tripCounter + currentRoute.trips().size();
}
System.out.println(routeCounter + " Routes with " + tripCounter + " trips created.");
- StringBuffer shapeOutput = new StringBuffer("shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n");
+ StringBuffer shapeOutput = new StringBuffer("shape_id,shape_pt_lon,shape_pt_lat,shape_pt_sequence\n");
new uniqueTripFinder(routes, shapeOutput);
new stoptimesWriter(routes);
new tripsWriter(routes);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( "shapes.txt" ) ) );
out.write(shapeOutput.toString());
if( out != null ) out.close();
System.out.println("\nshapes.txt written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done.");
}
}
| true | true | public static void main(String[] args) {
new Parser(args, routes);
for( String name: routes.keySet() )
{
Route currentRoute = routes.get(name);
routeCounter++;
tripCounter = tripCounter + currentRoute.trips().size();
}
System.out.println(routeCounter + " Routes with " + tripCounter + " trips created.");
StringBuffer shapeOutput = new StringBuffer("shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n");
new uniqueTripFinder(routes, shapeOutput);
new stoptimesWriter(routes);
new tripsWriter(routes);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( "shapes.txt" ) ) );
out.write(shapeOutput.toString());
if( out != null ) out.close();
System.out.println("\nshapes.txt written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done.");
}
| public static void main(String[] args) {
new Parser(args, routes);
for( String name: routes.keySet() )
{
Route currentRoute = routes.get(name);
routeCounter++;
tripCounter = tripCounter + currentRoute.trips().size();
}
System.out.println(routeCounter + " Routes with " + tripCounter + " trips created.");
StringBuffer shapeOutput = new StringBuffer("shape_id,shape_pt_lon,shape_pt_lat,shape_pt_sequence\n");
new uniqueTripFinder(routes, shapeOutput);
new stoptimesWriter(routes);
new tripsWriter(routes);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( "shapes.txt" ) ) );
out.write(shapeOutput.toString());
if( out != null ) out.close();
System.out.println("\nshapes.txt written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done.");
}
|
diff --git a/srcj/com/sun/electric/technology/technologies/MoCMOS.java b/srcj/com/sun/electric/technology/technologies/MoCMOS.java
index 4bf90eb04..e27ada258 100644
--- a/srcj/com/sun/electric/technology/technologies/MoCMOS.java
+++ b/srcj/com/sun/electric/technology/technologies/MoCMOS.java
@@ -1,1264 +1,1266 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: MoCMOS.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.technology.technologies;
import com.sun.electric.database.ImmutableNodeInst;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.text.Setting;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.AbstractShapeBuilder;
import com.sun.electric.technology.DRCTemplate;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitivePort;
import com.sun.electric.technology.TechFactory;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.XMLRules;
import com.sun.electric.technology.Xml;
import com.sun.electric.tool.user.User;
import java.io.PrintWriter;
import java.util.*;
/**
* This is the MOSIS CMOS technology.
*/
public class MoCMOS extends Technology
{
/** Value for standard SCMOS rules. */ public static final int SCMOSRULES = 0;
/** Value for submicron rules. */ public static final int SUBMRULES = 1;
/** Value for deep rules. */ public static final int DEEPRULES = 2;
/** key of Variable for saving technology state. */
public static final Variable.Key TECH_LAST_STATE = Variable.newKey("TECH_last_state");
public static final Version changeOfMetal6 = Version.parseVersion("8.02o"); // Fix of bug #357
private static final Version scmosTransistorSizeBug = Version.parseVersion("8.08h");
private static final Version scmosTransistorSizeFix = Version.parseVersion("8.09d");
private static final String TECH_NAME = "mocmos";
private static final String XML_PREFIX = TECH_NAME + ".";
private static final String PREF_PREFIX = "technology/technologies/";
private static final TechFactory.Param techParamRuleSet =
new TechFactory.Param(XML_PREFIX + "MOCMOS Rule Set", PREF_PREFIX + "MoCMOSRuleSet", Integer.valueOf(1));
private static final TechFactory.Param techParamNumMetalLayers =
new TechFactory.Param(XML_PREFIX + "NumMetalLayers", PREF_PREFIX + TECH_NAME + "NumberOfMetalLayers", Integer.valueOf(6));
private static final TechFactory.Param techParamUseSecondPolysilicon =
new TechFactory.Param(XML_PREFIX +"UseSecondPolysilicon", PREF_PREFIX + TECH_NAME + "SecondPolysilicon", Boolean.TRUE);
private static final TechFactory.Param techParamDisallowStackedVias =
new TechFactory.Param(XML_PREFIX + "DisallowStackedVias", PREF_PREFIX + "MoCMOSDisallowStackedVias", Boolean.FALSE);
private static final TechFactory.Param techParamUseAlternativeActivePolyRules =
new TechFactory.Param(XML_PREFIX + "UseAlternativeActivePolyRules", PREF_PREFIX + "MoCMOSAlternateActivePolyRules", Boolean.FALSE);
private static final TechFactory.Param techParamAnalog =
new TechFactory.Param(XML_PREFIX + "Analog", PREF_PREFIX + TECH_NAME + "Analog", Boolean.FALSE);
// Tech params
private Integer paramRuleSet;
private Boolean paramUseSecondPolysilicon;
private Boolean paramDisallowStackedVias;
private Boolean paramUseAlternativeActivePolyRules;
private Boolean paramAnalog;
// nodes. Storing nodes only whe they are need in outside the constructor
/** metal-1-P/N-active-contacts */ private PrimitiveNode[] metalActiveContactNodes = new PrimitiveNode[2];
/** Scalable Transistors */ private PrimitiveNode[] scalableTransistorNodes = new PrimitiveNode[2];
// -------------------- private and protected methods ------------------------
public MoCMOS(Generic generic, TechFactory techFactory, Map<TechFactory.Param,Object> techParams, Xml.Technology t) {
super(generic, techFactory, techParams, t);
paramRuleSet = (Integer)techParams.get(techParamRuleSet);
paramNumMetalLayers = (Integer)techParams.get(techParamNumMetalLayers);
paramUseSecondPolysilicon = (Boolean)techParams.get(techParamUseSecondPolysilicon);
paramDisallowStackedVias = (Boolean)techParams.get(techParamDisallowStackedVias);
paramUseAlternativeActivePolyRules = (Boolean)techParams.get(techParamUseAlternativeActivePolyRules);
paramAnalog = (Boolean)techParams.get(techParamAnalog);
setStaticTechnology();
//setFactoryResolution(0.01); // value in lambdas 0.005um -> 0.05 lambdas
//**************************************** NODES ****************************************
metalActiveContactNodes[P_TYPE] = findNodeProto("Metal-1-P-Active-Con");
metalActiveContactNodes[N_TYPE] = findNodeProto("Metal-1-N-Active-Con");
scalableTransistorNodes[P_TYPE] = findNodeProto("P-Transistor-Scalable");
scalableTransistorNodes[N_TYPE] = findNodeProto("N-Transistor-Scalable");
for (Iterator<Layer> it = getLayers(); it.hasNext(); ) {
Layer layer = it.next();
if (!layer.getFunction().isUsed(getNumMetals(), isSecondPolysilicon() ? 2 : 1))
layer.getPureLayerNode().setNotUsed(true);
}
PrimitiveNode np = findNodeProto("P-Transistor-Scalable");
if (np != null) np.setCanShrink();
np = findNodeProto("N-Transistor-Scalable");
if (np != null) np.setCanShrink();
np = findNodeProto("NPN-Transistor");
if (np != null) np.setCanShrink();
}
/******************** SUPPORT METHODS ********************/
@Override
protected void copyState(Technology that) {
super.copyState(that);
MoCMOS mocmos = (MoCMOS)that;
paramRuleSet = mocmos.paramRuleSet;
paramNumMetalLayers = mocmos.paramNumMetalLayers;
paramUseSecondPolysilicon = mocmos.paramUseSecondPolysilicon;
paramDisallowStackedVias = mocmos.paramDisallowStackedVias;
paramUseAlternativeActivePolyRules = mocmos.paramUseAlternativeActivePolyRules;
paramAnalog = mocmos.paramAnalog;
}
@Override
protected void dumpExtraProjectSettings(PrintWriter out, Map<Setting,Object> settings) {
printlnSetting(out, settings, getRuleSetSetting());
printlnSetting(out, settings, getSecondPolysiliconSetting());
printlnSetting(out, settings, getDisallowStackedViasSetting());
printlnSetting(out, settings, getAlternateActivePolyRulesSetting());
printlnSetting(out, settings, getAnalogSetting());
}
/******************** SCALABLE TRANSISTOR DESCRIPTION ********************/
private static final int SCALABLE_ACTIVE_TOP = 0;
private static final int SCALABLE_METAL_TOP = 1;
private static final int SCALABLE_CUT_TOP = 2;
private static final int SCALABLE_ACTIVE_BOT = 3;
private static final int SCALABLE_METAL_BOT = 4;
private static final int SCALABLE_CUT_BOT = 5;
private static final int SCALABLE_ACTIVE_CTR = 6;
private static final int SCALABLE_POLY = 7;
private static final int SCALABLE_WELL = 8;
private static final int SCALABLE_SUBSTRATE = 9;
private static final int SCALABLE_TOTAL = 10;
/**
* Puts into shape builder s the polygons that describe node "n", given a set of
* NodeLayer objects to use.
* This method is overridden by specific Technologys.
* @param b shape builder where to put polygons
* @param n the ImmutableNodeInst that is being described.
* @param pn proto of the ImmutableNodeInst in this Technology
* @param primLayers an array of NodeLayer objects to convert to Poly objects.
* The prototype of this NodeInst must be a PrimitiveNode and not a Cell.
*/
@Override
protected void genShapeOfNode(AbstractShapeBuilder b, ImmutableNodeInst n, PrimitiveNode pn, Technology.NodeLayer[] primLayers) {
if (pn != scalableTransistorNodes[P_TYPE] && pn != scalableTransistorNodes[N_TYPE]) {
b.genShapeOfNode(n, pn, primLayers, null);
return;
}
genShapeOfNodeScalable(b, n, pn, null, b.isReasonable());
}
/**
* Special getShapeOfNode function for scalable transistors
* @param m
* @param n
* @param pn
* @param context
* @param reasonable
* @return Array of Poly containing layers representing a Scalable Transistor
*/
private void genShapeOfNodeScalable(AbstractShapeBuilder b, ImmutableNodeInst n, PrimitiveNode pn, VarContext context, boolean reasonable)
{
// determine special configurations (number of active contacts, inset of active contacts)
int numContacts = 2;
boolean insetContacts = false;
String pt = n.getVarValue(TRANS_CONTACT, String.class);
if (pt != null)
{
for(int i=0; i<pt.length(); i++)
{
char chr = pt.charAt(i);
if (chr == '0' || chr == '1' || chr == '2')
{
numContacts = chr - '0';
} else if (chr == 'i' || chr == 'I') insetContacts = true;
}
}
int boxOffset = 6 - numContacts * 3;
// determine width
double activeWidMax = n.size.getLambdaX() + 3;
// double nodeWid = ni.getXSize();
// double activeWidMax = nodeWid - 14;
double activeWid = activeWidMax;
Variable var = n.getVar(Schematics.ATTR_WIDTH);
if (var != null)
{
VarContext evalContext = context;
if (evalContext == null) evalContext = VarContext.globalContext;
NodeInst ni = null; // dummy node inst
String extra = var.describe(evalContext, ni);
Object o = evalContext.evalVar(var, ni);
if (o != null) extra = o.toString();
double requestedWid = TextUtils.atof(extra);
if (requestedWid > activeWid)
{
System.out.println("Warning: " + b.getCellBackup().toString() + ", " +
n.name + " requests width of " + requestedWid + " but is only " + activeWid + " wide");
}
if (requestedWid < activeWid && requestedWid > 0)
{
activeWid = requestedWid;
}
}
double shrinkGate = 0.5*(activeWidMax - activeWid);
// contacts must be 5 wide at a minimum
double shrinkCon = (int)(0.5*(activeWidMax + 2 - Math.max(activeWid, 5)));
// now compute the number of polygons
Technology.NodeLayer [] layers = pn.getNodeLayers();
assert layers.length == SCALABLE_TOTAL;
int count = SCALABLE_TOTAL - boxOffset;
Technology.NodeLayer [] newNodeLayers = new Technology.NodeLayer[count];
// load the basic layers
int fillIndex = 0;
for(int box = boxOffset; box < SCALABLE_TOTAL; box++)
{
TechPoint [] oldPoints = layers[box].getPoints();
TechPoint [] points = new TechPoint[oldPoints.length];
for(int i=0; i<oldPoints.length; i++) points[i] = oldPoints[i];
double shrinkX = 0;
TechPoint p0 = points[0];
TechPoint p1 = points[1];
double x0 = p0.getX().getAdder();
double x1 = p1.getX().getAdder();
double y0 = p0.getY().getAdder();
double y1 = p1.getY().getAdder();
switch (box)
{
case SCALABLE_ACTIVE_TOP:
case SCALABLE_METAL_TOP:
case SCALABLE_CUT_TOP:
shrinkX = shrinkCon;
if (insetContacts) {
y0 -= 0.5;
y1 -= 0.5;
}
break;
case SCALABLE_ACTIVE_BOT:
case SCALABLE_METAL_BOT:
case SCALABLE_CUT_BOT:
shrinkX = shrinkCon;
if (insetContacts) {
y0 -= 0.5;
y1 -= 0.5;
}
break;
case SCALABLE_ACTIVE_CTR: // active that passes through gate
case SCALABLE_POLY: // poly
shrinkX = shrinkGate;
break;
case SCALABLE_WELL: // well and select
case SCALABLE_SUBSTRATE:
if (insetContacts) {
y0 += 0.5;
y1 -= 0.5;
}
break;
}
x0 += shrinkX;
x1 -= shrinkX;
points[0] = p0.withX(p0.getX().withAdder(x0)).withY(p0.getY().withAdder(y0));
points[1] = p1.withX(p1.getX().withAdder(x1)).withY(p1.getY().withAdder(y1));
Technology.NodeLayer oldNl = layers[box];
if (oldNl.getRepresentation() == NodeLayer.MULTICUTBOX)
newNodeLayers[fillIndex] = Technology.NodeLayer.makeMulticut(oldNl.getLayer(), oldNl.getPortNum(),
oldNl.getStyle(), points, oldNl.getMulticutSizeX(), oldNl.getMulticutSizeY(), oldNl.getMulticutSep1D(), oldNl.getMulticutSep2D());
else
newNodeLayers[fillIndex] = new Technology.NodeLayer(oldNl.getLayer(), oldNl.getPortNum(),
oldNl.getStyle(), oldNl.getRepresentation(), points);
fillIndex++;
}
// now let the superclass convert it to Polys
b.genShapeOfNode(n, pn, newNodeLayers, null);
}
/******************** PARAMETERIZABLE DESIGN RULES ********************/
/**
* Method to build "factory" design rules, given the current technology settings.
* @return the "factory" design rules for this Technology.
* Returns null if there is an error loading the rules.
*/
@Override
protected XMLRules makeFactoryDesignRules()
{
Foundry foundry = getSelectedFoundry();
List<DRCTemplate> theRules = foundry.getRules();
XMLRules rules = new XMLRules(this);
boolean pSubstrateProcess = User.isPSubstrateProcessLayoutTechnology();
assert(foundry != null);
// load the DRC tables from the explanation table
int numMetals = getNumMetals();
int rulesMode = getRuleSet();
for(int pass=0; pass<2; pass++)
{
for(DRCTemplate rule : theRules)
{
// see if the rule applies
if (pass == 0)
{
if (rule.ruleType == DRCTemplate.DRCRuleType.NODSIZ) continue;
} else
{
if (rule.ruleType != DRCTemplate.DRCRuleType.NODSIZ) continue;
}
int when = rule.when;
boolean goodrule = true;
if ((when&(DRCTemplate.DRCMode.DE.mode()|DRCTemplate.DRCMode.SU.mode()|DRCTemplate.DRCMode.SC.mode())) != 0)
{
switch (rulesMode)
{
case DEEPRULES: if ((when&DRCTemplate.DRCMode.DE.mode()) == 0) goodrule = false; break;
case SUBMRULES: if ((when&DRCTemplate.DRCMode.SU.mode()) == 0) goodrule = false; break;
case SCMOSRULES: if ((when&DRCTemplate.DRCMode.SC.mode()) == 0) goodrule = false; break;
}
if (!goodrule) continue;
}
if ((when&(DRCTemplate.DRCMode.M2.mode()|DRCTemplate.DRCMode.M3.mode()|DRCTemplate.DRCMode.M4.mode()|DRCTemplate.DRCMode.M5.mode()|DRCTemplate.DRCMode.M6.mode())) != 0)
{
switch (numMetals)
{
case 2: if ((when&DRCTemplate.DRCMode.M2.mode()) == 0) goodrule = false; break;
case 3: if ((when&DRCTemplate.DRCMode.M3.mode()) == 0) goodrule = false; break;
case 4: if ((when&DRCTemplate.DRCMode.M4.mode()) == 0) goodrule = false; break;
case 5: if ((when&DRCTemplate.DRCMode.M5.mode()) == 0) goodrule = false; break;
case 6: if ((when&DRCTemplate.DRCMode.M6.mode()) == 0) goodrule = false; break;
}
if (!goodrule) continue;
}
if ((when&DRCTemplate.DRCMode.AC.mode()) != 0)
{
if (!isAlternateActivePolyRules()) continue;
}
if ((when&DRCTemplate.DRCMode.NAC.mode()) != 0)
{
if (isAlternateActivePolyRules()) continue;
}
if ((when&DRCTemplate.DRCMode.SV.mode()) != 0)
{
if (isDisallowStackedVias()) continue;
}
if ((when&DRCTemplate.DRCMode.NSV.mode()) != 0)
{
if (!isDisallowStackedVias()) continue;
}
if ((when&DRCTemplate.DRCMode.AN.mode()) != 0)
{
if (!isAnalog()) continue;
}
// get more information about the rule
String proc = "";
if ((when&(DRCTemplate.DRCMode.DE.mode()|DRCTemplate.DRCMode.SU.mode()|DRCTemplate.DRCMode.SC.mode())) != 0)
{
switch (rulesMode)
{
case DEEPRULES: proc = "DEEP"; break;
case SUBMRULES: proc = "SUBM"; break;
case SCMOSRULES: proc = "SCMOS"; break;
}
}
String metal = "";
if ((when&(DRCTemplate.DRCMode.M2.mode()|DRCTemplate.DRCMode.M3.mode()|DRCTemplate.DRCMode.M4.mode()|DRCTemplate.DRCMode.M5.mode()|DRCTemplate.DRCMode.M6.mode())) != 0)
{
switch (getNumMetals())
{
case 2: metal = "2m"; break;
case 3: metal = "3m"; break;
case 4: metal = "4m"; break;
case 5: metal = "5m"; break;
case 6: metal = "6m"; break;
}
if (!goodrule) continue;
}
String ruleName = rule.ruleName;
String extraString = metal + proc;
if (extraString.length() > 0 && ruleName.indexOf(extraString) == -1) {
rule = new DRCTemplate(rule);
rule.ruleName += ", " + extraString;
}
rules.loadDRCRules(this, foundry, rule, pSubstrateProcess);
}
}
return rules;
}
@Override
public SizeCorrector getSizeCorrector(Version version, Map<Setting,Object> projectSettings, boolean isJelib, boolean keepExtendOverMin) {
SizeCorrector sc = super.getSizeCorrector(version, projectSettings, isJelib, keepExtendOverMin);
int ruleSet = SUBMRULES;
Object ruleSetValue = projectSettings.get(getRuleSetSetting());
if (ruleSetValue instanceof Integer)
ruleSet = ((Integer)ruleSetValue).intValue();
if (ruleSet == SCMOSRULES && version.compareTo(scmosTransistorSizeBug) >= 0 && version.compareTo(scmosTransistorSizeFix) < 0) {
setNodeCorrection(sc, "P-Transistor", 1, 2);
setNodeCorrection(sc, "N-Transistor", 1, 2);
}
if (!keepExtendOverMin) return sc;
boolean newDefaults = version.compareTo(Version.parseVersion("8.04u")) >= 0;
int numMetals = newDefaults ? 6 : 4;
boolean isSecondPolysilicon = newDefaults ? true : false;
Object numMetalsValue = projectSettings.get(getNumMetalsSetting());
if (numMetalsValue instanceof Integer)
numMetals = ((Integer)numMetalsValue).intValue();
Object secondPolysiliconValue = projectSettings.get(getSecondPolysiliconSetting());
if (secondPolysiliconValue instanceof Boolean)
isSecondPolysilicon = ((Boolean)secondPolysiliconValue).booleanValue();
else if (secondPolysiliconValue instanceof Integer)
isSecondPolysilicon = ((Integer)secondPolysiliconValue).intValue() != 0;
if (numMetals == getNumMetals() && isSecondPolysilicon == isSecondPolysilicon() && ruleSet == getRuleSet() && version.compareTo(changeOfMetal6) >= 0)
return sc;
setArcCorrection(sc, "Polysilicon-2", ruleSet == SCMOSRULES ? 3 : 7);
setArcCorrection(sc, "Metal-3", numMetals <= 3 ? (ruleSet == SCMOSRULES ? 6 : 5) : 3);
setArcCorrection(sc, "Metal-4", numMetals <= 4 ? 6 : 3);
setArcCorrection(sc, "Metal-5", numMetals <= 5 ? 4 : 3);
if (version.compareTo(changeOfMetal6) < 0) // Fix of bug #357
setArcCorrection(sc, "Metal-6", 4);
return sc;
}
/******************** OPTIONS ********************/
private final Setting cacheRuleSet = makeIntSetting("MoCMOSRuleSet", "Technology tab", "MOSIS CMOS rule set",
techParamRuleSet.xmlPath.substring(TECH_NAME.length() + 1), 1, "SCMOS", "Submicron", "Deep");
/**
* Method to tell the current rule set for this Technology if Mosis is the foundry.
* @return the current rule set for this Technology:<BR>
* 0: SCMOS rules<BR>
* 1: Submicron rules (the default)<BR>
* 2: Deep rules
*/
public int getRuleSet() { return paramRuleSet.intValue(); }
// private static DRCTemplate.DRCMode getRuleMode()
// {
// switch (getRuleSet())
// {
// case DEEPRULES: return DRCTemplate.DRCMode.DE;
// case SUBMRULES: return DRCTemplate.DRCMode.SU;
// case SCMOSRULES: return DRCTemplate.DRCMode.SC;
// }
// return null;
// }
/**
* Method to set the rule set for this Technology.
* @return the new rule setting for this Technology, with values:<BR>
* 0: SCMOS rules<BR>
* 1: Submicron rules<BR>
* 2: Deep rules
*/
public Setting getRuleSetSetting() { return cacheRuleSet; }
private final Setting cacheSecondPolysilicon = makeBooleanSetting(getTechName() + "SecondPolysilicon", "Technology tab", getTechName().toUpperCase() + " CMOS: Second Polysilicon Layer",
techParamUseSecondPolysilicon.xmlPath.substring(TECH_NAME.length() + 1), true);
/**
* Method to tell the number of polysilicon layers in this Technology.
* The default is false.
* @return true if there are 2 polysilicon layers in this Technology.
* If false, there is only 1 polysilicon layer.
*/
public boolean isSecondPolysilicon() { return paramUseSecondPolysilicon.booleanValue(); }
/**
* Returns project preferences to tell a second polysilicon layer in this Technology.
* @return project preferences to tell a second polysilicon layer in this Technology.
*/
public Setting getSecondPolysiliconSetting() { return cacheSecondPolysilicon; }
private final Setting cacheDisallowStackedVias = makeBooleanSetting("MoCMOSDisallowStackedVias", "Technology tab", "MOSIS CMOS: Disallow Stacked Vias",
techParamDisallowStackedVias.xmlPath.substring(TECH_NAME.length() + 1), false);
/**
* Method to determine whether this Technology disallows stacked vias.
* The default is false (they are allowed).
* @return true if the MOCMOS technology disallows stacked vias.
*/
public boolean isDisallowStackedVias() { return paramDisallowStackedVias.booleanValue(); }
/**
* Returns project preferences to tell whether this Technology disallows stacked vias.
* @return project preferences to tell whether this Technology disallows stacked vias.
*/
public Setting getDisallowStackedViasSetting() { return cacheDisallowStackedVias; }
private final Setting cacheAlternateActivePolyRules = makeBooleanSetting("MoCMOSAlternateActivePolyRules", "Technology tab", "MOSIS CMOS: Alternate Active and Poly Contact Rules",
techParamUseAlternativeActivePolyRules.xmlPath.substring(TECH_NAME.length() + 1), false);
/**
* Method to determine whether this Technology is using alternate Active and Poly contact rules.
* The default is false.
* @return true if the MOCMOS technology is using alternate Active and Poly contact rules.
*/
public boolean isAlternateActivePolyRules() { return paramUseAlternativeActivePolyRules.booleanValue(); }
/**
* Returns project preferences to tell whether this Technology is using alternate Active and Poly contact rules.
* @return project preferences to tell whether this Technology is using alternate Active and Poly contact rules.
*/
public Setting getAlternateActivePolyRulesSetting() { return cacheAlternateActivePolyRules; }
private final Setting cacheAnalog = makeBooleanSetting(getTechName() + "Analog", "Technology tab", "MOSIS CMOS: Analog",
techParamAnalog.xmlPath.substring(TECH_NAME.length() + 1), false);
/**
* Method to tell whether this technology provides analog elements.
* The default is false.
* @return true if this Technology provides analog elements..
*/
public boolean isAnalog() { return paramAnalog.booleanValue(); }
/**
* Returns project preferences to tell whether this technology provides analog elements.
* @return project preferences to tell whether this technology provides analog elements.
*/
public Setting getAnalogSetting() { return cacheAnalog; }
/** set if no stacked vias allowed */ private static final int MOCMOSNOSTACKEDVIAS = 01;
// /** set for stick-figure display */ private static final int MOCMOSSTICKFIGURE = 02;
/** number of metal layers */ private static final int MOCMOSMETALS = 034;
/** 2-metal rules */ private static final int MOCMOS2METAL = 0;
/** 3-metal rules */ private static final int MOCMOS3METAL = 04;
/** 4-metal rules */ private static final int MOCMOS4METAL = 010;
/** 5-metal rules */ private static final int MOCMOS5METAL = 014;
/** 6-metal rules */ private static final int MOCMOS6METAL = 020;
/** type of rules */ private static final int MOCMOSRULESET = 0140;
/** set if submicron rules in use */ private static final int MOCMOSSUBMRULES = 0;
/** set if deep rules in use */ private static final int MOCMOSDEEPRULES = 040;
/** set if standard SCMOS rules in use */ private static final int MOCMOSSCMOSRULES = 0100;
/** set to use alternate active/poly rules */ private static final int MOCMOSALTAPRULES = 0200;
/** set to use second polysilicon layer */ private static final int MOCMOSTWOPOLY = 0400;
// /** set to show special transistors */ private static final int MOCMOSSPECIALTRAN = 01000;
/**
* Method to convert any old-style state information to the new options.
*/
/**
* Method to convert any old-style variable information to the new options.
* May be overrideen in subclasses.
* @param varName name of variable
* @param value value of variable
* @return true if variable was converted
*/
@Override
public Map<Setting,Object> convertOldVariable(String varName, Object value)
{
if (varName.equals("MoCMOSNumberOfMetalLayers") || varName.equals("MOCMOSNumberOfMetalLayers"))
return Collections.singletonMap(getNumMetalsSetting(), value);
if (varName.equals("MoCMOSSecondPolysilicon"))
return Collections.singletonMap(getSecondPolysiliconSetting(), value);
if (!varName.equalsIgnoreCase(TECH_LAST_STATE.getName())) return null;
if (!(value instanceof Integer)) return null;
int oldBits = ((Integer)value).intValue();
HashMap<Setting,Object> settings = new HashMap<Setting,Object>();
boolean oldNoStackedVias = (oldBits&MOCMOSNOSTACKEDVIAS) != 0;
settings.put(getDisallowStackedViasSetting(), new Integer(oldNoStackedVias?1:0));
int numMetals = 0;
switch (oldBits&MOCMOSMETALS)
{
case MOCMOS2METAL: numMetals = 2; break;
case MOCMOS3METAL: numMetals = 3; break;
case MOCMOS4METAL: numMetals = 4; break;
case MOCMOS5METAL: numMetals = 5; break;
case MOCMOS6METAL: numMetals = 6; break;
}
settings.put(getNumMetalsSetting(), new Integer(numMetals));
int ruleSet = 0;
switch (oldBits&MOCMOSRULESET)
{
case MOCMOSSUBMRULES: ruleSet = SUBMRULES; break;
case MOCMOSDEEPRULES: ruleSet = DEEPRULES; break;
case MOCMOSSCMOSRULES: ruleSet = SCMOSRULES; break;
}
settings.put(getRuleSetSetting(), new Integer(ruleSet));
boolean alternateContactRules = (oldBits&MOCMOSALTAPRULES) != 0;
settings.put(getAlternateActivePolyRulesSetting(), new Integer(alternateContactRules?1:0));
boolean secondPoly = (oldBits&MOCMOSTWOPOLY) != 0;
settings.put(getSecondPolysiliconSetting(), new Integer(secondPoly?1:0));
return settings;
}
/**
* This method is called from TechFactory by reflection. Don't remove.
* Returns a list of TechFactory.Params affecting this Technology
* @return list of TechFactory.Params affecting this Technology
*/
public static List<TechFactory.Param> getTechParams() {
return Arrays.asList(
techParamRuleSet,
techParamNumMetalLayers,
techParamUseSecondPolysilicon,
techParamDisallowStackedVias,
techParamUseAlternativeActivePolyRules,
techParamAnalog);
}
/**
* This method is called from TechFactory by reflection. Don't remove.
* Returns patched Xml description of this Technology for specified technology params
* @param params values of technology params
* @return patched Xml description of this Technology
*/
public static Xml.Technology getPatchedXml(Map<TechFactory.Param,Object> params) {
int ruleSet = ((Integer)params.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)params.get(techParamNumMetalLayers)).intValue();
boolean secondPolysilicon = ((Boolean)params.get(techParamUseSecondPolysilicon)).booleanValue();
boolean disallowStackedVias = ((Boolean)params.get(techParamDisallowStackedVias)).booleanValue();
boolean alternateContactRules = ((Boolean)params.get(techParamUseAlternativeActivePolyRules)).booleanValue();
boolean isAnalog = ((Boolean)params.get(techParamAnalog)).booleanValue();
Xml.Technology tech = Xml.parseTechnology(MoCMOS.class.getResource("mocmos.xml"));
if (tech == null) // errors while reading the XML file
return null;
Xml.Layer[] metalLayers = new Xml.Layer[6];
Xml.ArcProto[] metalArcs = new Xml.ArcProto[6];
Xml.ArcProto[] activeArcs = new Xml.ArcProto[2];
Xml.ArcProto[] polyArcs = new Xml.ArcProto[6];
Xml.PrimitiveNodeGroup[] metalPinNodes = new Xml.PrimitiveNodeGroup[9];
Xml.PrimitiveNodeGroup[] activePinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] polyPinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalContactNodes = new Xml.PrimitiveNodeGroup[8];
Xml.PrimitiveNodeGroup[] metalWellContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalActiveContactNodes = new Xml.PrimitiveNodeGroup[2];
List<Xml.PrimitiveNodeGroup> metal1PolyContactNodes = new ArrayList<Xml.PrimitiveNodeGroup>(4);
Xml.PrimitiveNodeGroup[] transistorNodeGroups = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] scalableTransistorNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup npnTransistorNode = tech.findNodeGroup("NPN-Transistor");
Xml.PrimitiveNodeGroup polyCapNode = tech.findNodeGroup("Poly1-Poly2-Capacitor");
- List<Xml.PrimitiveNodeGroup> analogElems = new ArrayList<Xml.PrimitiveNodeGroup>();
+ Set<Xml.PrimitiveNodeGroup> analogElems = new HashSet<Xml.PrimitiveNodeGroup>();
analogElems.add(tech.findNodeGroup("NPN-Transistor"));
analogElems.add(tech.findNodeGroup("Hi-Res-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-Active-Resistor"));
analogElems.add(tech.findNodeGroup("N-Active-Resistor"));
analogElems.add(tech.findNodeGroup("P-Well-Resistor"));
analogElems.add(tech.findNodeGroup("N-Well-Resistor"));
analogElems.add(tech.findNodeGroup("P-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-No-Silicide-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-No-Silicide-Poly-Resistor"));
+ // Remove all possible null entries (not found elements)
+ analogElems.remove(null);
assert(analogElems.size() == 10 && polyCapNode != null); // so far
for (int i = 0; i < metalLayers.length; i++) {
metalLayers[i] = tech.findLayer("Metal-" + (i + 1));
metalArcs[i] = tech.findArc("Metal-" + (i + 1));
metalPinNodes[i] = tech.findNodeGroup("Metal-" + (i + 1) + "-Pin");
if (i >= metalContactNodes.length) continue;
metalContactNodes[i] = tech.findNodeGroup("Metal-" + (i + 1)+"-Metal-" + (i + 2) + "-Con");
}
for (int i = 0; i < 2; i++) {
polyArcs[i] = tech.findArc("Polysilicon-" + (i + 1));
polyPinNodes[i] = tech.findNodeGroup("Polysilicon-" + (i + 1) + "-Pin");
metal1PolyContactNodes.add(tech.findNodeGroup("Metal-1-Polysilicon-" + (i + 1) + "-Con"));
}
metal1PolyContactNodes.add(tech.findNodeGroup("Metal-1-Polysilicon-1-2-Con"));
metal1PolyContactNodes.add(polyCapNode); // treating polyCapNode as contact for the resizing
for (int i = P_TYPE; i <= N_TYPE; i++) {
String ts = i == P_TYPE ? "P" : "N";
activeArcs[i] = tech.findArc(ts + "-Active");
activePinNodes[i] = tech.findNodeGroup(ts + "-Active-Pin");
metalWellContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Well-Con");
metalActiveContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Active-Con");
transistorNodeGroups[i] = tech.findNodeGroup(ts + "-Transistor");
scalableTransistorNodes[i] = tech.findNodeGroup(ts + "-Transistor-Scalable");
}
String rules = "";
switch (ruleSet)
{
case SCMOSRULES: rules = "now standard"; break;
case DEEPRULES: rules = "now deep"; break;
case SUBMRULES: rules = "now submicron"; break;
}
int numPolys = 1;
if (secondPolysilicon) numPolys = 2;
String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " +
numPolys + "], flex rules [" + rules + "]";
if (disallowStackedVias) description += ", stacked vias disallowed";
if (alternateContactRules) description += ", alternate contact rules";
description += ")";
tech.description = description;
Xml.NodeLayer nl;
ResizeData rd = new ResizeData(ruleSet, numMetals, alternateContactRules);
for (int i = 0; i < 6; i++) {
resizeArcPin(metalArcs[i], metalPinNodes[i], 0.5*rd.metal_width[i]);
if (i >= 5) continue;
Xml.PrimitiveNodeGroup via = metalContactNodes[i];
nl = via.nodeLayers.get(2);
nl.sizex = nl.sizey = rd.via_size[i];
nl.sep1d = rd.via_inline_spacing[i];
nl.sep2d = rd.via_array_spacing[i];
if (i + 1 >= numMetals) continue;
double halfSize = 0.5*rd.via_size[i] + rd.via_overhang[i + 1];
resizeSquare(via, halfSize, halfSize, halfSize, 0);
}
for (int i = P_TYPE; i <= N_TYPE; i++) {
double activeE = 0.5*rd.diff_width;
double wellE = activeE + rd.nwell_overhang_diff_p;
double selectE = activeE + rd.pplus_overhang_diff;
resizeArcPin(activeArcs[i], activePinNodes[i], activeE, wellE, selectE);
Xml.PrimitiveNodeGroup con = metalActiveContactNodes[i];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
con = metalWellContactNodes[i];
wellC = activeC + rd.nwell_overhang_diff_n;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
resizeSerpentineTransistor(transistorNodeGroups[i], rd);
resizeScalableTransistor(scalableTransistorNodes[i], rd);
}
resizeContacts(npnTransistorNode, rd);
{
Xml.PrimitiveNodeGroup con = metal1PolyContactNodes.get(0);
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double polyC = 0.5*rd.contact_size + rd.contact_poly_overhang;
resizeSquare(con, polyC, metalC, polyC, 0);
}
for (Xml.PrimitiveNodeGroup g : metal1PolyContactNodes)
resizeContacts(g, rd);
resizeArcPin(polyArcs[0], polyPinNodes[0], 0.5*rd.poly_width);
resizeArcPin(polyArcs[1], polyPinNodes[1], 0.5*rd.poly2_width);
for (int i = numMetals; i < 6; i++) {
metalArcs[i].notUsed = true;
metalPinNodes[i].notUsed = true;
metalContactNodes[i-1].notUsed = true;
// Remove palette rows with unused metal
assert tech.menuPalette.menuBoxes.get(3*(6 + numMetals)).get(0) == metalArcs[i];
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
}
// Clear palette box with unused contact
tech.menuPalette.menuBoxes.get(3*(6 + numMetals) - 1).clear();
if (!secondPolysilicon) {
polyArcs[1].notUsed = true;
polyPinNodes[1].notUsed = true;
metal1PolyContactNodes.get(1).notUsed = true;
metal1PolyContactNodes.get(2).notUsed = true;
// Remove palette row with polysilicon-2
assert tech.menuPalette.menuBoxes.get(3*5).get(0) == polyArcs[1];
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
}
boolean polyFlag, analogFlag;
if (isAnalog) {
analogFlag = false;
polyFlag = false;
// Clear palette box with capacitor if poly2 is on
if (!secondPolysilicon)
{
assert tech.menuPalette.menuBoxes.get(0).get(1) == polyCapNode.nodes.get(0);
// location of capacitor
tech.menuPalette.menuBoxes.get(0).remove(polyCapNode.nodes.get(0));
polyFlag = true;
}
} else {
// Clear palette box with NPN transisitor
assert tech.menuPalette.menuBoxes.get(0).get(0) == npnTransistorNode.nodes.get(0);
tech.menuPalette.menuBoxes.get(0).clear();
analogFlag = true;
polyFlag = true;
}
if (polyCapNode != null) polyCapNode.notUsed = polyFlag;
for (Xml.PrimitiveNodeGroup elem : analogElems)
{
if (elem != null) elem.notUsed = analogFlag;
}
return tech;
}
private static void resizeArcPin(Xml.ArcProto a, Xml.PrimitiveNodeGroup ng, double ... exts) {
assert a.arcLayers.size() == exts.length;
assert ng.nodeLayers.size() == exts.length;
double baseExt = exts[0];
double maxExt = 0;
for (int i = 0; i < exts.length; i++) {
Xml.ArcLayer al = a.arcLayers.get(i);
Xml.NodeLayer nl = ng.nodeLayers.get(i);
double ext = exts[i];
assert al.layer.equals(nl.layer);
assert nl.representation == Technology.NodeLayer.BOX;
al.extend.value = ext;
nl.hx.value = nl.hy.value = ext;
nl.lx.value = nl.ly.value = ext == 0 ? 0 : -ext;
maxExt = Math.max(maxExt, ext);
}
Integer version2 = Integer.valueOf(2);
if (baseExt != 0)
a.diskOffset.put(version2, Double.valueOf(baseExt));
else
a.diskOffset.clear();
ng.baseLX.value = ng.baseLY.value = baseExt != 0 ? -baseExt : 0;
ng.baseHX.value = ng.baseHY.value = baseExt;
// n.setDefSize
}
private static void resizeSquare(Xml.PrimitiveNodeGroup ng, double base, double... size) {
assert size.length == ng.nodeLayers.size();
double maxSz = 0;
for (int i = 0; i < ng.nodeLayers.size(); i++) {
Xml.NodeLayer nl = ng.nodeLayers.get(i);
assert nl.representation == Technology.NodeLayer.BOX || nl.representation == Technology.NodeLayer.MULTICUTBOX;
double sz = size[i];
assert sz >= 0;
nl.hx.value = nl.hy.value = sz;
nl.lx.value = nl.ly.value = sz == 0 ? 0 : -sz;
maxSz = Math.max(maxSz, sz);
}
Integer version1 = Integer.valueOf(1);
Integer version2 = Integer.valueOf(2);
EPoint sizeCorrector1 = ng.diskOffset.get(version1);
EPoint sizeCorrector2 = ng.diskOffset.get(version2);
if (sizeCorrector2 == null)
sizeCorrector2 = EPoint.ORIGIN;
if (sizeCorrector1 == null)
sizeCorrector1 = sizeCorrector2;
ng.baseLX.value = ng.baseLY.value = base != 0 ? -base : 0;
ng.baseHX.value = ng.baseHY.value = base;
sizeCorrector2 = EPoint.fromLambda(base, base);
ng.diskOffset.put(version2, sizeCorrector2);
if (sizeCorrector1.equals(sizeCorrector2))
ng.diskOffset.remove(version1);
else
ng.diskOffset.put(version1, sizeCorrector1);
}
private static void resizeContacts(Xml.PrimitiveNodeGroup ng, ResizeData rd) {
for (Xml.NodeLayer nl: ng.nodeLayers) {
if (nl.representation != Technology.NodeLayer.MULTICUTBOX) continue;
nl.sizex = nl.sizey = rd.contact_size;
nl.sep1d = rd.contact_spacing;
nl.sep2d = rd.contact_array_spacing;
}
}
private static void resizeSerpentineTransistor(Xml.PrimitiveNodeGroup transistor, ResizeData rd) {
Xml.NodeLayer activeTNode = transistor.nodeLayers.get(0); // active Top or Left
Xml.NodeLayer activeBNode = transistor.nodeLayers.get(1); // active Bottom or Right
Xml.NodeLayer polyCNode = transistor.nodeLayers.get(2); // poly center
Xml.NodeLayer polyLNode = transistor.nodeLayers.get(3); // poly left or Top
Xml.NodeLayer polyRNode = transistor.nodeLayers.get(4); // poly right or bottom
Xml.NodeLayer activeNode = transistor.nodeLayers.get(5); // active
Xml.NodeLayer polyNode = transistor.nodeLayers.get(6); // poly
Xml.NodeLayer wellNode = transistor.nodeLayers.get(7); // well
Xml.NodeLayer selNode = transistor.nodeLayers.get(8); // select
Xml.NodeLayer thickNode = transistor.nodeLayers.get(9); // thick
double hw = 0.5*rd.gate_width;
double hl = 0.5*rd.gate_length;
double gateX = hw;
double gateY = hl;
double polyX = gateX + rd.poly_endcap;
double polyY = gateY;
double diffX = gateX;
double diffY = gateY + rd.diff_poly_overhang;
double wellX = diffX + rd.nwell_overhang_diff_p;
double wellY = diffY + rd.nwell_overhang_diff_p;
double selX = diffX + rd.pplus_overhang_diff;
double selY = diffY + rd.pplus_overhang_diff;
double thickX = diffX + rd.thick_overhang;
double thickY = diffY + rd.thick_overhang;
resizeSerpentineLayer(activeTNode, hw, -gateX, gateX, gateY, diffY);
resizeSerpentineLayer(activeBNode, hw, -diffX, diffX, -diffY, -gateY);
resizeSerpentineLayer(polyCNode, hw, -gateX, gateX, -gateY, gateY);
resizeSerpentineLayer(polyLNode, hw, -polyX, -gateX, -polyY, polyY);
resizeSerpentineLayer(polyRNode, hw, gateX, polyX, -polyY, polyY);
resizeSerpentineLayer(activeNode, hw, -diffX, diffX, -diffY, diffY);
resizeSerpentineLayer(polyNode, hw, -polyX, polyX, -polyY, polyY);
resizeSerpentineLayer(wellNode, hw, -wellX, wellX, -wellY, wellY);
resizeSerpentineLayer(selNode, hw, -selX, selX, -selY, selY);
resizeSerpentineLayer(thickNode, hw, -thickX, thickX, -thickY, thickY);
}
private static void resizeSerpentineLayer(Xml.NodeLayer nl, double hw, double lx, double hx, double ly, double hy) {
nl.lx.value = lx;
nl.hx.value = hx;
nl.ly.value = ly;
nl.hy.value = hy;
nl.lWidth = nl.hy.k == 1 ? hy : 0;
nl.rWidth = nl.ly.k == -1 ? -ly : 0;
nl.tExtent = nl.hx.k == 1 ? hx - hw : 0;
nl.bExtent = nl.lx.k == -1 ? -lx - hw : 0;
}
private static void resizeScalableTransistor(Xml.PrimitiveNodeGroup transistor, ResizeData rd) {
Xml.NodeLayer activeTNode = transistor.nodeLayers.get(SCALABLE_ACTIVE_TOP); // active Top
Xml.NodeLayer metalTNode = transistor.nodeLayers.get(SCALABLE_METAL_TOP); // metal Top
Xml.NodeLayer cutTNode = transistor.nodeLayers.get(SCALABLE_CUT_TOP);
Xml.NodeLayer activeBNode = transistor.nodeLayers.get(SCALABLE_ACTIVE_BOT); // active Bottom
Xml.NodeLayer metalBNode = transistor.nodeLayers.get(SCALABLE_METAL_BOT); // metal Bot
Xml.NodeLayer cutBNode = transistor.nodeLayers.get(SCALABLE_CUT_BOT);
Xml.NodeLayer activeCNode = transistor.nodeLayers.get(SCALABLE_ACTIVE_CTR); // active center
Xml.NodeLayer polyCNode = transistor.nodeLayers.get(SCALABLE_POLY); // poly center
Xml.NodeLayer wellNode = transistor.nodeLayers.get(SCALABLE_WELL); // well
Xml.NodeLayer selNode = transistor.nodeLayers.get(SCALABLE_SUBSTRATE); // select
double hw = 0.5*rd.gate_width;
double hl = 0.5*rd.gate_length;
double gateX = hw;
double gateY = hl;
double polyX = gateX + rd.poly_endcap;
double polyY = gateY;
double diffX = gateX;
double diffY = gateY + rd.diff_poly_overhang;
// double wellX = diffX + rd.nwell_overhang_diff_p;
// double wellY = diffY + rd.nwell_overhang_diff_p;
// double selX = diffX + rd.pplus_overhang_diff;
// double selY = diffY + rd.pplus_overhang_diff;
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
double cutY = hl + rd.poly_diff_spacing + activeC;
resizeScalableLayer(activeTNode, -activeC, activeC, cutY - activeC, cutY + activeC);
resizeScalableLayer(metalTNode, -metalC, metalC, cutY - metalC, cutY + metalC);
resizeScalableLayer(cutTNode, 0, 0, cutY, cutY);
resizeScalableLayer(activeBNode, -activeC, activeC, -cutY - activeC, -cutY + activeC);
resizeScalableLayer(metalBNode, -metalC, metalC, -cutY - metalC, -cutY + metalC);
resizeScalableLayer(cutBNode, 0, 0, -cutY, -cutY);
resizeScalableLayer(activeCNode, -diffX, diffX, -diffY, diffY);
resizeScalableLayer(polyCNode, -polyX, polyX, -polyY, polyY);
resizeScalableLayer(wellNode, -wellC, wellC, -cutY-wellC, cutY+wellC);
resizeScalableLayer(selNode, -selectC, selectC, -cutY-selectC, cutY+selectC);
resizeContacts(transistor, rd);
}
private static void resizeScalableLayer(Xml.NodeLayer nl, double lx, double hx, double ly, double hy) {
nl.lx.value = lx;
nl.hx.value = hx;
nl.ly.value = ly;
nl.hy.value = hy;
}
private static class ResizeData {
private final double diff_width = 3; // 2.1
private final double diff_poly_overhang; // 3.4
private final double diff_contact_overhang; // 6.2 6.2b
private final double thick_overhang = 4;
private final double poly_width = 2; // 3.1
private final double poly_endcap; // 3.3
private final double poly_diff_spacing = 1; // 3.5
private final double gate_length = poly_width; // 3.1
private final double gate_width = diff_width; // 2.1
private final double gate_contact_spacing = 2; // 5.4
private final double poly2_width; // 11.1
private final double contact_size = 2; // 5.1
private final double contact_spacing; // 5.3
private final double contact_array_spacing; // 5.3
private final double contact_metal_overhang_all_sides = 1; // 7.3
private final double contact_poly_overhang; // 5.2 5.2b
private final double nplus_overhang_diff = 2; // 4.2
private final double pplus_overhang_diff = 2; // 4.2
private final double well_width;
private final double nwell_overhang_diff_p; // 2.3
private final double nwell_overhang_diff_n = 3; // 2.4
private final double[] metal_width; // 7.1 9.1 15.1 22.1 26.1 30.1
private final double[] via_size; // 8.1 14.1 21.1 25.1 29.1
private final double[] via_inline_spacing; // 8.2 14.2 21.2 25.2 29.2
private final double[] via_array_spacing; // 8.2 14.2 21.2 25.2 29.2
private final double[] via_overhang; // 8.3 14.3 21.3 25.3 29.3 30.3
ResizeData(int ruleSet, int numMetals, boolean alternateContactRules) {
switch (ruleSet) {
case SUBMRULES:
diff_poly_overhang = 3;
poly_endcap = 2;
poly2_width = 7;
contact_spacing = 3;
well_width = 12;
nwell_overhang_diff_p = 6;
switch (numMetals) {
case 2:
metal_width = new double[] { 3, 3, 0, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1 };
break;
case 3:
metal_width = new double[] { 3, 3, 5, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 2 };
break;
case 4:
metal_width = new double[] { 3, 3, 3, 6, 0, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 2 };
break;
case 5:
metal_width = new double[] { 3, 3, 3, 3, 4, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 1 };
break;
case 6:
metal_width = new double[] { 3, 3, 3, 3, 3, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 1, 1 };
break;
default:
throw new IllegalArgumentException("Illegal number of metals " + numMetals + " in SUB rule set");
}
break;
case DEEPRULES:
diff_poly_overhang = 4;
poly_endcap = 2.5;
poly2_width = 0;
contact_spacing = 4;
well_width = 12;
nwell_overhang_diff_p = 6;
switch (numMetals) {
case 5:
metal_width = new double[] { 3, 3, 3, 3, 4, 5 };
via_size = new double[] { 3, 3, 3, 3, 4 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 2 };
break;
case 6:
metal_width = new double[] { 3, 3, 3, 3, 3, 5 };
via_size = new double[] { 3, 3, 3, 3, 4 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 1, 2 };
break;
default:
throw new IllegalArgumentException("Illegal number of metals " + numMetals + " in DEEP rule set");
}
break;
case SCMOSRULES:
diff_poly_overhang = 3;
poly_endcap = 2;
poly2_width = 3;
contact_spacing = 2;
well_width = 10;
nwell_overhang_diff_p = 5;
switch (numMetals) {
case 2:
metal_width = new double[] { 3, 3, 0, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 0, 0 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1 };
break;
case 3:
metal_width = new double[] { 3, 3, 6, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 0, 0 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 2 };
break;
case 4:
metal_width = new double[] { 3, 3, 3, 6, 0, 5 };
via_size = new double[] { 2, 2, 2, 0, 0 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 2 };
break;
default:
throw new IllegalArgumentException("Illegal number of metals " + numMetals + " in SCMOS rule set");
}
break;
default:
throw new AssertionError("Illegal rule set " + ruleSet);
}
diff_contact_overhang = alternateContactRules ? 1 : 1.5;
contact_poly_overhang = alternateContactRules ? 1 : 1.5;
contact_array_spacing = contact_spacing;
via_array_spacing = via_inline_spacing;
}
}
/******************** OVERRIDES ********************/
@Override
protected State newState(Map<TechFactory.Param,Object> paramValues) {
LinkedHashMap<TechFactory.Param,Object> fixedParamValues = new LinkedHashMap<TechFactory.Param,Object>();
for (TechFactory.Param param: techFactory.getTechParams()) {
Object value = paramValues.get(param);
if (value == null || value.getClass() != param.factoryValue.getClass())
value = param.factoryValue;
fixedParamValues.put(param, value);
}
int ruleSet = ((Integer)fixedParamValues.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)fixedParamValues.get(techParamNumMetalLayers)).intValue();
if (ruleSet < SCMOSRULES || ruleSet > DEEPRULES) {
ruleSet = SUBMRULES;
fixedParamValues.put(techParamRuleSet, ruleSet);
}
int minNumMetals, maxNumMetals;
switch (ruleSet) {
case SCMOSRULES:
minNumMetals = 2;
maxNumMetals = 4;
break;
case SUBMRULES:
minNumMetals = 2;
maxNumMetals = 6;
break;
case DEEPRULES:
minNumMetals = 5;
maxNumMetals = 6;
break;
default:
throw new AssertionError();
}
if (numMetals < minNumMetals || numMetals > maxNumMetals) {
numMetals = Math.min(Math.max(numMetals, minNumMetals), maxNumMetals);
fixedParamValues.put(techParamNumMetalLayers, numMetals);
}
return super.newState(fixedParamValues);
}
/**
* Method to convert old primitive port names to their proper PortProtos.
* @param portName the unknown port name, read from an old Library.
* @param np the PrimitiveNode on which this port resides.
* @return the proper PrimitivePort to use for this name.
*/
@Override
public PrimitivePort convertOldPortName(String portName, PrimitiveNode np)
{
String[] transistorPorts = { "poly-left", "diff-top", "poly-right", "diff-bottom" };
for (int i = 0; i < transistorPorts.length; i++)
{
if (portName.endsWith(transistorPorts[i]))
return (PrimitivePort)np.findPortProto(transistorPorts[i]);
}
return super.convertOldPortName(portName, np);
}
// /**
// * Method to set the size of a transistor NodeInst in this Technology.
// * Override because for MOCMOS sense of "width" and "length" are
// * different for resistors and transistors.
// * @param ni the NodeInst
// * @param width the new width (positive values only)
// * @param length the new length (positive values only)
// */
// //@Override
// public void setPrimitiveNodeSize(NodeInst ni, double width, double length)
// {
// if (ni.getFunction().isResistor()) {
// super.setPrimitiveNodeSize(ni, length, width);
// } else {
// super.setPrimitiveNodeSize(ni, width, length);
// }
// }
/**
* Method to calculate extension of the poly gate from active layer or of the active from the poly gate.
* @param primNode
* @param poly true to calculate the poly extension
* @param rules
* @return value of the extension
*/
// private double getTransistorExtension(PrimitiveNode primNode, boolean poly, DRCRules rules)
// {
// if (rules == null)
// rules = DRC.getRules(this);
// if (!primNode.getFunction().isTransistor()) return 0.0;
//
// Technology.NodeLayer activeNode = primNode.getNodeLayers()[0]; // active
// Technology.NodeLayer polyCNode;
//
// if (scalableTransistorNodes != null && (primNode == scalableTransistorNodes[P_TYPE] || primNode == scalableTransistorNodes[N_TYPE]))
// {
// polyCNode = primNode.getNodeLayers()[SCALABLE_POLY]; // poly center
// }
// else
// {
// // Standard transistors
// polyCNode = primNode.getElectricalLayers()[2]; // poly center
// }
// DRCTemplate overhang = (poly) ?
// rules.getExtensionRule(polyCNode.getLayer(), activeNode.getLayer(), false) :
// rules.getExtensionRule(activeNode.getLayer(), polyCNode.getLayer(), false);
// return (overhang != null ? overhang.getValue(0) : 0.0);
// }
/** Return a substrate PortInst for this transistor NodeInst
* @param ni the NodeInst
* @return a PortInst for the substrate contact of the transistor
*/
@Override
public PortInst getTransistorBiasPort(NodeInst ni)
{
return ni.getPortInst(4);
}
}
| false | true | public static Xml.Technology getPatchedXml(Map<TechFactory.Param,Object> params) {
int ruleSet = ((Integer)params.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)params.get(techParamNumMetalLayers)).intValue();
boolean secondPolysilicon = ((Boolean)params.get(techParamUseSecondPolysilicon)).booleanValue();
boolean disallowStackedVias = ((Boolean)params.get(techParamDisallowStackedVias)).booleanValue();
boolean alternateContactRules = ((Boolean)params.get(techParamUseAlternativeActivePolyRules)).booleanValue();
boolean isAnalog = ((Boolean)params.get(techParamAnalog)).booleanValue();
Xml.Technology tech = Xml.parseTechnology(MoCMOS.class.getResource("mocmos.xml"));
if (tech == null) // errors while reading the XML file
return null;
Xml.Layer[] metalLayers = new Xml.Layer[6];
Xml.ArcProto[] metalArcs = new Xml.ArcProto[6];
Xml.ArcProto[] activeArcs = new Xml.ArcProto[2];
Xml.ArcProto[] polyArcs = new Xml.ArcProto[6];
Xml.PrimitiveNodeGroup[] metalPinNodes = new Xml.PrimitiveNodeGroup[9];
Xml.PrimitiveNodeGroup[] activePinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] polyPinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalContactNodes = new Xml.PrimitiveNodeGroup[8];
Xml.PrimitiveNodeGroup[] metalWellContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalActiveContactNodes = new Xml.PrimitiveNodeGroup[2];
List<Xml.PrimitiveNodeGroup> metal1PolyContactNodes = new ArrayList<Xml.PrimitiveNodeGroup>(4);
Xml.PrimitiveNodeGroup[] transistorNodeGroups = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] scalableTransistorNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup npnTransistorNode = tech.findNodeGroup("NPN-Transistor");
Xml.PrimitiveNodeGroup polyCapNode = tech.findNodeGroup("Poly1-Poly2-Capacitor");
List<Xml.PrimitiveNodeGroup> analogElems = new ArrayList<Xml.PrimitiveNodeGroup>();
analogElems.add(tech.findNodeGroup("NPN-Transistor"));
analogElems.add(tech.findNodeGroup("Hi-Res-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-Active-Resistor"));
analogElems.add(tech.findNodeGroup("N-Active-Resistor"));
analogElems.add(tech.findNodeGroup("P-Well-Resistor"));
analogElems.add(tech.findNodeGroup("N-Well-Resistor"));
analogElems.add(tech.findNodeGroup("P-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-No-Silicide-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-No-Silicide-Poly-Resistor"));
assert(analogElems.size() == 10 && polyCapNode != null); // so far
for (int i = 0; i < metalLayers.length; i++) {
metalLayers[i] = tech.findLayer("Metal-" + (i + 1));
metalArcs[i] = tech.findArc("Metal-" + (i + 1));
metalPinNodes[i] = tech.findNodeGroup("Metal-" + (i + 1) + "-Pin");
if (i >= metalContactNodes.length) continue;
metalContactNodes[i] = tech.findNodeGroup("Metal-" + (i + 1)+"-Metal-" + (i + 2) + "-Con");
}
for (int i = 0; i < 2; i++) {
polyArcs[i] = tech.findArc("Polysilicon-" + (i + 1));
polyPinNodes[i] = tech.findNodeGroup("Polysilicon-" + (i + 1) + "-Pin");
metal1PolyContactNodes.add(tech.findNodeGroup("Metal-1-Polysilicon-" + (i + 1) + "-Con"));
}
metal1PolyContactNodes.add(tech.findNodeGroup("Metal-1-Polysilicon-1-2-Con"));
metal1PolyContactNodes.add(polyCapNode); // treating polyCapNode as contact for the resizing
for (int i = P_TYPE; i <= N_TYPE; i++) {
String ts = i == P_TYPE ? "P" : "N";
activeArcs[i] = tech.findArc(ts + "-Active");
activePinNodes[i] = tech.findNodeGroup(ts + "-Active-Pin");
metalWellContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Well-Con");
metalActiveContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Active-Con");
transistorNodeGroups[i] = tech.findNodeGroup(ts + "-Transistor");
scalableTransistorNodes[i] = tech.findNodeGroup(ts + "-Transistor-Scalable");
}
String rules = "";
switch (ruleSet)
{
case SCMOSRULES: rules = "now standard"; break;
case DEEPRULES: rules = "now deep"; break;
case SUBMRULES: rules = "now submicron"; break;
}
int numPolys = 1;
if (secondPolysilicon) numPolys = 2;
String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " +
numPolys + "], flex rules [" + rules + "]";
if (disallowStackedVias) description += ", stacked vias disallowed";
if (alternateContactRules) description += ", alternate contact rules";
description += ")";
tech.description = description;
Xml.NodeLayer nl;
ResizeData rd = new ResizeData(ruleSet, numMetals, alternateContactRules);
for (int i = 0; i < 6; i++) {
resizeArcPin(metalArcs[i], metalPinNodes[i], 0.5*rd.metal_width[i]);
if (i >= 5) continue;
Xml.PrimitiveNodeGroup via = metalContactNodes[i];
nl = via.nodeLayers.get(2);
nl.sizex = nl.sizey = rd.via_size[i];
nl.sep1d = rd.via_inline_spacing[i];
nl.sep2d = rd.via_array_spacing[i];
if (i + 1 >= numMetals) continue;
double halfSize = 0.5*rd.via_size[i] + rd.via_overhang[i + 1];
resizeSquare(via, halfSize, halfSize, halfSize, 0);
}
for (int i = P_TYPE; i <= N_TYPE; i++) {
double activeE = 0.5*rd.diff_width;
double wellE = activeE + rd.nwell_overhang_diff_p;
double selectE = activeE + rd.pplus_overhang_diff;
resizeArcPin(activeArcs[i], activePinNodes[i], activeE, wellE, selectE);
Xml.PrimitiveNodeGroup con = metalActiveContactNodes[i];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
con = metalWellContactNodes[i];
wellC = activeC + rd.nwell_overhang_diff_n;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
resizeSerpentineTransistor(transistorNodeGroups[i], rd);
resizeScalableTransistor(scalableTransistorNodes[i], rd);
}
resizeContacts(npnTransistorNode, rd);
{
Xml.PrimitiveNodeGroup con = metal1PolyContactNodes.get(0);
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double polyC = 0.5*rd.contact_size + rd.contact_poly_overhang;
resizeSquare(con, polyC, metalC, polyC, 0);
}
for (Xml.PrimitiveNodeGroup g : metal1PolyContactNodes)
resizeContacts(g, rd);
resizeArcPin(polyArcs[0], polyPinNodes[0], 0.5*rd.poly_width);
resizeArcPin(polyArcs[1], polyPinNodes[1], 0.5*rd.poly2_width);
for (int i = numMetals; i < 6; i++) {
metalArcs[i].notUsed = true;
metalPinNodes[i].notUsed = true;
metalContactNodes[i-1].notUsed = true;
// Remove palette rows with unused metal
assert tech.menuPalette.menuBoxes.get(3*(6 + numMetals)).get(0) == metalArcs[i];
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
}
// Clear palette box with unused contact
tech.menuPalette.menuBoxes.get(3*(6 + numMetals) - 1).clear();
if (!secondPolysilicon) {
polyArcs[1].notUsed = true;
polyPinNodes[1].notUsed = true;
metal1PolyContactNodes.get(1).notUsed = true;
metal1PolyContactNodes.get(2).notUsed = true;
// Remove palette row with polysilicon-2
assert tech.menuPalette.menuBoxes.get(3*5).get(0) == polyArcs[1];
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
}
boolean polyFlag, analogFlag;
if (isAnalog) {
analogFlag = false;
polyFlag = false;
// Clear palette box with capacitor if poly2 is on
if (!secondPolysilicon)
{
assert tech.menuPalette.menuBoxes.get(0).get(1) == polyCapNode.nodes.get(0);
// location of capacitor
tech.menuPalette.menuBoxes.get(0).remove(polyCapNode.nodes.get(0));
polyFlag = true;
}
} else {
// Clear palette box with NPN transisitor
assert tech.menuPalette.menuBoxes.get(0).get(0) == npnTransistorNode.nodes.get(0);
tech.menuPalette.menuBoxes.get(0).clear();
analogFlag = true;
polyFlag = true;
}
if (polyCapNode != null) polyCapNode.notUsed = polyFlag;
for (Xml.PrimitiveNodeGroup elem : analogElems)
{
if (elem != null) elem.notUsed = analogFlag;
}
return tech;
}
| public static Xml.Technology getPatchedXml(Map<TechFactory.Param,Object> params) {
int ruleSet = ((Integer)params.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)params.get(techParamNumMetalLayers)).intValue();
boolean secondPolysilicon = ((Boolean)params.get(techParamUseSecondPolysilicon)).booleanValue();
boolean disallowStackedVias = ((Boolean)params.get(techParamDisallowStackedVias)).booleanValue();
boolean alternateContactRules = ((Boolean)params.get(techParamUseAlternativeActivePolyRules)).booleanValue();
boolean isAnalog = ((Boolean)params.get(techParamAnalog)).booleanValue();
Xml.Technology tech = Xml.parseTechnology(MoCMOS.class.getResource("mocmos.xml"));
if (tech == null) // errors while reading the XML file
return null;
Xml.Layer[] metalLayers = new Xml.Layer[6];
Xml.ArcProto[] metalArcs = new Xml.ArcProto[6];
Xml.ArcProto[] activeArcs = new Xml.ArcProto[2];
Xml.ArcProto[] polyArcs = new Xml.ArcProto[6];
Xml.PrimitiveNodeGroup[] metalPinNodes = new Xml.PrimitiveNodeGroup[9];
Xml.PrimitiveNodeGroup[] activePinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] polyPinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalContactNodes = new Xml.PrimitiveNodeGroup[8];
Xml.PrimitiveNodeGroup[] metalWellContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalActiveContactNodes = new Xml.PrimitiveNodeGroup[2];
List<Xml.PrimitiveNodeGroup> metal1PolyContactNodes = new ArrayList<Xml.PrimitiveNodeGroup>(4);
Xml.PrimitiveNodeGroup[] transistorNodeGroups = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] scalableTransistorNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup npnTransistorNode = tech.findNodeGroup("NPN-Transistor");
Xml.PrimitiveNodeGroup polyCapNode = tech.findNodeGroup("Poly1-Poly2-Capacitor");
Set<Xml.PrimitiveNodeGroup> analogElems = new HashSet<Xml.PrimitiveNodeGroup>();
analogElems.add(tech.findNodeGroup("NPN-Transistor"));
analogElems.add(tech.findNodeGroup("Hi-Res-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-Active-Resistor"));
analogElems.add(tech.findNodeGroup("N-Active-Resistor"));
analogElems.add(tech.findNodeGroup("P-Well-Resistor"));
analogElems.add(tech.findNodeGroup("N-Well-Resistor"));
analogElems.add(tech.findNodeGroup("P-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-No-Silicide-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-No-Silicide-Poly-Resistor"));
// Remove all possible null entries (not found elements)
analogElems.remove(null);
assert(analogElems.size() == 10 && polyCapNode != null); // so far
for (int i = 0; i < metalLayers.length; i++) {
metalLayers[i] = tech.findLayer("Metal-" + (i + 1));
metalArcs[i] = tech.findArc("Metal-" + (i + 1));
metalPinNodes[i] = tech.findNodeGroup("Metal-" + (i + 1) + "-Pin");
if (i >= metalContactNodes.length) continue;
metalContactNodes[i] = tech.findNodeGroup("Metal-" + (i + 1)+"-Metal-" + (i + 2) + "-Con");
}
for (int i = 0; i < 2; i++) {
polyArcs[i] = tech.findArc("Polysilicon-" + (i + 1));
polyPinNodes[i] = tech.findNodeGroup("Polysilicon-" + (i + 1) + "-Pin");
metal1PolyContactNodes.add(tech.findNodeGroup("Metal-1-Polysilicon-" + (i + 1) + "-Con"));
}
metal1PolyContactNodes.add(tech.findNodeGroup("Metal-1-Polysilicon-1-2-Con"));
metal1PolyContactNodes.add(polyCapNode); // treating polyCapNode as contact for the resizing
for (int i = P_TYPE; i <= N_TYPE; i++) {
String ts = i == P_TYPE ? "P" : "N";
activeArcs[i] = tech.findArc(ts + "-Active");
activePinNodes[i] = tech.findNodeGroup(ts + "-Active-Pin");
metalWellContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Well-Con");
metalActiveContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Active-Con");
transistorNodeGroups[i] = tech.findNodeGroup(ts + "-Transistor");
scalableTransistorNodes[i] = tech.findNodeGroup(ts + "-Transistor-Scalable");
}
String rules = "";
switch (ruleSet)
{
case SCMOSRULES: rules = "now standard"; break;
case DEEPRULES: rules = "now deep"; break;
case SUBMRULES: rules = "now submicron"; break;
}
int numPolys = 1;
if (secondPolysilicon) numPolys = 2;
String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " +
numPolys + "], flex rules [" + rules + "]";
if (disallowStackedVias) description += ", stacked vias disallowed";
if (alternateContactRules) description += ", alternate contact rules";
description += ")";
tech.description = description;
Xml.NodeLayer nl;
ResizeData rd = new ResizeData(ruleSet, numMetals, alternateContactRules);
for (int i = 0; i < 6; i++) {
resizeArcPin(metalArcs[i], metalPinNodes[i], 0.5*rd.metal_width[i]);
if (i >= 5) continue;
Xml.PrimitiveNodeGroup via = metalContactNodes[i];
nl = via.nodeLayers.get(2);
nl.sizex = nl.sizey = rd.via_size[i];
nl.sep1d = rd.via_inline_spacing[i];
nl.sep2d = rd.via_array_spacing[i];
if (i + 1 >= numMetals) continue;
double halfSize = 0.5*rd.via_size[i] + rd.via_overhang[i + 1];
resizeSquare(via, halfSize, halfSize, halfSize, 0);
}
for (int i = P_TYPE; i <= N_TYPE; i++) {
double activeE = 0.5*rd.diff_width;
double wellE = activeE + rd.nwell_overhang_diff_p;
double selectE = activeE + rd.pplus_overhang_diff;
resizeArcPin(activeArcs[i], activePinNodes[i], activeE, wellE, selectE);
Xml.PrimitiveNodeGroup con = metalActiveContactNodes[i];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
con = metalWellContactNodes[i];
wellC = activeC + rd.nwell_overhang_diff_n;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
resizeSerpentineTransistor(transistorNodeGroups[i], rd);
resizeScalableTransistor(scalableTransistorNodes[i], rd);
}
resizeContacts(npnTransistorNode, rd);
{
Xml.PrimitiveNodeGroup con = metal1PolyContactNodes.get(0);
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double polyC = 0.5*rd.contact_size + rd.contact_poly_overhang;
resizeSquare(con, polyC, metalC, polyC, 0);
}
for (Xml.PrimitiveNodeGroup g : metal1PolyContactNodes)
resizeContacts(g, rd);
resizeArcPin(polyArcs[0], polyPinNodes[0], 0.5*rd.poly_width);
resizeArcPin(polyArcs[1], polyPinNodes[1], 0.5*rd.poly2_width);
for (int i = numMetals; i < 6; i++) {
metalArcs[i].notUsed = true;
metalPinNodes[i].notUsed = true;
metalContactNodes[i-1].notUsed = true;
// Remove palette rows with unused metal
assert tech.menuPalette.menuBoxes.get(3*(6 + numMetals)).get(0) == metalArcs[i];
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
}
// Clear palette box with unused contact
tech.menuPalette.menuBoxes.get(3*(6 + numMetals) - 1).clear();
if (!secondPolysilicon) {
polyArcs[1].notUsed = true;
polyPinNodes[1].notUsed = true;
metal1PolyContactNodes.get(1).notUsed = true;
metal1PolyContactNodes.get(2).notUsed = true;
// Remove palette row with polysilicon-2
assert tech.menuPalette.menuBoxes.get(3*5).get(0) == polyArcs[1];
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
}
boolean polyFlag, analogFlag;
if (isAnalog) {
analogFlag = false;
polyFlag = false;
// Clear palette box with capacitor if poly2 is on
if (!secondPolysilicon)
{
assert tech.menuPalette.menuBoxes.get(0).get(1) == polyCapNode.nodes.get(0);
// location of capacitor
tech.menuPalette.menuBoxes.get(0).remove(polyCapNode.nodes.get(0));
polyFlag = true;
}
} else {
// Clear palette box with NPN transisitor
assert tech.menuPalette.menuBoxes.get(0).get(0) == npnTransistorNode.nodes.get(0);
tech.menuPalette.menuBoxes.get(0).clear();
analogFlag = true;
polyFlag = true;
}
if (polyCapNode != null) polyCapNode.notUsed = polyFlag;
for (Xml.PrimitiveNodeGroup elem : analogElems)
{
if (elem != null) elem.notUsed = analogFlag;
}
return tech;
}
|
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java
index 70fc2bbf..b0a004ec 100644
--- a/src/org/mozilla/javascript/Interpreter.java
+++ b/src/org/mozilla/javascript/Interpreter.java
@@ -1,2531 +1,2533 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape 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/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
import org.mozilla.javascript.debug.*;
public class Interpreter extends LabelTable {
public static final boolean printICode = false;
public IRFactory createIRFactory(TokenStream ts,
ClassNameHelper nameHelper, Scriptable scope)
{
return new IRFactory(ts, scope);
}
public Node transform(Node tree, TokenStream ts, Scriptable scope) {
return (new NodeTransformer()).transform(tree, null, ts, scope);
}
public Object compile(Context cx, Scriptable scope, Node tree,
Object securityDomain,
SecuritySupport securitySupport,
ClassNameHelper nameHelper)
throws IOException
{
version = cx.getLanguageVersion();
itsData = new InterpreterData(0, 0, securityDomain,
cx.hasCompileFunctionsWithDynamicScope(), false);
if (tree instanceof FunctionNode) {
FunctionNode f = (FunctionNode) tree;
InterpretedFunction result =
generateFunctionICode(cx, scope, f, securityDomain);
result.itsData.itsFunctionType = f.getFunctionType();
createFunctionObject(result, scope);
return result;
}
return generateScriptICode(cx, scope, tree, securityDomain);
}
private void generateICodeFromTree(Node tree,
VariableTable varTable,
boolean needsActivation,
Object securityDomain)
{
int theICodeTop = 0;
itsVariableTable = varTable;
itsData.itsNeedsActivation = needsActivation;
theICodeTop = generateICode(tree, theICodeTop);
itsData.itsICodeTop = theICodeTop;
if (itsEpilogLabel != -1)
markLabel(itsEpilogLabel, theICodeTop);
for (int i = 0; i < itsLabelTableTop; i++)
itsLabelTable[i].fixGotos(itsData.itsICode);
}
private Object[] generateRegExpLiterals(Context cx,
Scriptable scope,
Vector regexps)
{
Object[] result = new Object[regexps.size()];
RegExpProxy rep = cx.getRegExpProxy();
for (int i = 0; i < regexps.size(); i++) {
Node regexp = (Node) regexps.elementAt(i);
Node left = regexp.getFirstChild();
Node right = regexp.getLastChild();
result[i] = rep.newRegExp(cx, scope, left.getString(),
(left != right) ? right.getString() : null, false);
regexp.putIntProp(Node.REGEXP_PROP, i);
}
return result;
}
private InterpretedScript generateScriptICode(Context cx,
Scriptable scope,
Node tree,
Object securityDomain)
{
itsSourceFile = (String) tree.getProp(Node.SOURCENAME_PROP);
itsData.itsSourceFile = itsSourceFile;
itsFunctionList = (Vector) tree.getProp(Node.FUNCTION_PROP);
debugSource = (StringBuffer) tree.getProp(Node.DEBUGSOURCE_PROP);
if (itsFunctionList != null)
generateNestedFunctions(scope, cx, securityDomain);
Object[] regExpLiterals = null;
Vector regexps = (Vector)tree.getProp(Node.REGEXP_PROP);
if (regexps != null)
regExpLiterals = generateRegExpLiterals(cx, scope, regexps);
VariableTable varTable = (VariableTable)tree.getProp(Node.VARS_PROP);
// The default is not to generate debug information
boolean activationNeeded = cx.isGeneratingDebugChanged() &&
cx.isGeneratingDebug();
generateICodeFromTree(tree, varTable, activationNeeded, securityDomain);
itsData.itsNestedFunctions = itsNestedFunctions;
itsData.itsRegExpLiterals = regExpLiterals;
if (printICode) dumpICode(itsData);
String[] argNames = itsVariableTable.getAllNames();
short argCount = (short)itsVariableTable.getParameterCount();
InterpretedScript
result = new InterpretedScript(cx, itsData, argNames, argCount);
if (cx.debugger != null) {
cx.debugger.handleCompilationDone(cx, result, debugSource);
}
return result;
}
private void generateNestedFunctions(Scriptable scope,
Context cx,
Object securityDomain)
{
itsNestedFunctions = new InterpretedFunction[itsFunctionList.size()];
for (short i = 0; i < itsFunctionList.size(); i++) {
FunctionNode def = (FunctionNode)itsFunctionList.elementAt(i);
Interpreter jsi = new Interpreter();
jsi.itsSourceFile = itsSourceFile;
jsi.itsData = new InterpreterData(0, 0, securityDomain,
cx.hasCompileFunctionsWithDynamicScope(),
def.getCheckThis());
jsi.itsData.itsFunctionType = def.getFunctionType();
jsi.itsInFunctionFlag = true;
jsi.debugSource = debugSource;
itsNestedFunctions[i] = jsi.generateFunctionICode(cx, scope, def,
securityDomain);
def.putIntProp(Node.FUNCTION_PROP, i);
}
}
private InterpretedFunction
generateFunctionICode(Context cx, Scriptable scope,
FunctionNode theFunction, Object securityDomain)
{
itsFunctionList = (Vector) theFunction.getProp(Node.FUNCTION_PROP);
if (itsFunctionList != null)
generateNestedFunctions(scope, cx, securityDomain);
Object[] regExpLiterals = null;
Vector regexps = (Vector)theFunction.getProp(Node.REGEXP_PROP);
if (regexps != null)
regExpLiterals = generateRegExpLiterals(cx, scope, regexps);
VariableTable varTable = theFunction.getVariableTable();
boolean needsActivation = theFunction.requiresActivation() ||
(cx.isGeneratingDebugChanged() &&
cx.isGeneratingDebug());
generateICodeFromTree(theFunction.getLastChild(),
varTable, needsActivation,
securityDomain);
itsData.itsName = theFunction.getFunctionName();
itsData.itsSourceFile = (String) theFunction.getProp(
Node.SOURCENAME_PROP);
itsData.itsSource = (String)theFunction.getProp(Node.SOURCE_PROP);
itsData.itsNestedFunctions = itsNestedFunctions;
itsData.itsRegExpLiterals = regExpLiterals;
if (printICode) dumpICode(itsData);
String[] argNames = itsVariableTable.getAllNames();
short argCount = (short)itsVariableTable.getParameterCount();
InterpretedFunction
result = new InterpretedFunction(cx, itsData, argNames, argCount);
if (cx.debugger != null) {
cx.debugger.handleCompilationDone(cx, result, debugSource);
}
return result;
}
boolean itsInFunctionFlag;
Vector itsFunctionList;
InterpreterData itsData;
VariableTable itsVariableTable;
int itsTryDepth = 0;
int itsStackDepth = 0;
int itsEpilogLabel = -1;
String itsSourceFile;
int itsLineNumber = 0;
InterpretedFunction[] itsNestedFunctions = null;
private int updateLineNumber(Node node, int iCodeTop)
{
Object datum = node.getDatum();
if (datum == null || !(datum instanceof Number))
return iCodeTop;
short lineNumber = ((Number) datum).shortValue();
if (lineNumber != itsLineNumber) {
itsLineNumber = lineNumber;
if (itsData.itsLineNumberTable == null &&
Context.getCurrentContext().isGeneratingDebug())
{
itsData.itsLineNumberTable = new UintMap();
}
if (lineNumber > 0 && itsData.itsLineNumberTable != null) {
itsData.itsLineNumberTable.put(lineNumber, iCodeTop);
}
iCodeTop = addByte(TokenStream.LINE, iCodeTop);
iCodeTop = addShort(lineNumber, iCodeTop);
}
return iCodeTop;
}
private void badTree(Node node)
{
try {
out = new PrintWriter(new FileOutputStream("icode.txt", true));
out.println("Un-handled node : " + node.toString());
out.close();
}
catch (IOException x) {}
throw new RuntimeException("Un-handled node : "
+ node.toString());
}
private int generateICode(Node node, int iCodeTop) {
int type = node.getType();
Node child = node.getFirstChild();
Node firstChild = child;
switch (type) {
case TokenStream.FUNCTION : {
iCodeTop = addByte(TokenStream.CLOSURE, iCodeTop);
Node fn = (Node) node.getProp(Node.FUNCTION_PROP);
int index = fn.getExistingIntProp(Node.FUNCTION_PROP);
iCodeTop = addByte(index >> 8, iCodeTop);
iCodeTop = addByte(index & 0xff, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.SCRIPT :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
if (child.getType() != TokenStream.FUNCTION)
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
}
break;
case TokenStream.CASE :
iCodeTop = updateLineNumber(node, iCodeTop);
child = child.getNextSibling();
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
}
break;
case TokenStream.LABEL :
case TokenStream.WITH :
case TokenStream.LOOP :
case TokenStream.DEFAULT :
case TokenStream.BLOCK :
case TokenStream.VOID :
case TokenStream.NOP :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
}
break;
case TokenStream.COMMA :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
break;
case TokenStream.SWITCH : {
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
int theLocalSlot = itsData.itsMaxLocals++;
iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
/*
reminder - below we construct new GOTO nodes that aren't
linked into the tree just for the purpose of having a node
to pass to the addGoto routine. (Parallels codegen here).
Seems unnecessary.
*/
Vector cases = (Vector) node.getProp(Node.CASES_PROP);
for (int i = 0; i < cases.size(); i++) {
Node thisCase = (Node)cases.elementAt(i);
Node first = thisCase.getFirstChild();
// the case expression is the firstmost child
// the rest will be generated when the case
// statements are encountered as siblings of
// the switch statement.
iCodeTop = generateICode(first, iCodeTop);
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.SHEQ, iCodeTop);
Node target = new Node(TokenStream.TARGET);
thisCase.addChildAfter(target, first);
Node branch = new Node(TokenStream.IFEQ);
branch.putProp(Node.TARGET_PROP, target);
iCodeTop = addGoto(branch, TokenStream.IFEQ,
iCodeTop);
itsStackDepth--;
}
Node defaultNode = (Node) node.getProp(Node.DEFAULT_PROP);
if (defaultNode != null) {
Node defaultTarget = new Node(TokenStream.TARGET);
defaultNode.getFirstChild().addChildToFront(defaultTarget);
Node branch = new Node(TokenStream.GOTO);
branch.putProp(Node.TARGET_PROP, defaultTarget);
iCodeTop = addGoto(branch, TokenStream.GOTO,
iCodeTop);
}
Node breakTarget = (Node) node.getProp(Node.BREAK_PROP);
Node branch = new Node(TokenStream.GOTO);
branch.putProp(Node.TARGET_PROP, breakTarget);
iCodeTop = addGoto(branch, TokenStream.GOTO,
iCodeTop);
}
break;
case TokenStream.TARGET : {
int label = node.getIntProp(Node.LABEL_PROP, -1);
if (label == -1) {
label = acquireLabel();
node.putIntProp(Node.LABEL_PROP, label);
}
markLabel(label, iCodeTop);
// if this target has a FINALLY_PROP, it is a JSR target
// and so has a PC value on the top of the stack
if (node.getProp(Node.FINALLY_PROP) != null) {
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
}
break;
case TokenStream.EQOP :
case TokenStream.RELOP : {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
int op = node.getInt();
if (version == Context.VERSION_1_2) {
if (op == TokenStream.EQ)
op = TokenStream.SHEQ;
else if (op == TokenStream.NE)
op = TokenStream.SHNE;
}
iCodeTop = addByte(op, iCodeTop);
itsStackDepth--;
}
break;
case TokenStream.NEW :
case TokenStream.CALL : {
if (itsSourceFile != null && (itsData.itsSourceFile == null || ! itsSourceFile.equals(itsData.itsSourceFile)))
itsData.itsSourceFile = itsSourceFile;
iCodeTop = addByte(TokenStream.SOURCEFILE, iCodeTop);
int childCount = 0;
short nameIndex = -1;
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
if (nameIndex == -1) {
if (child.getType() == TokenStream.NAME)
nameIndex = (short)(itsData.itsStringTableIndex - 1);
else if (child.getType() == TokenStream.GETPROP)
nameIndex = (short)(itsData.itsStringTableIndex - 1);
}
child = child.getNextSibling();
childCount++;
}
if (node.getProp(Node.SPECIALCALL_PROP) != null) {
// embed line number and source filename
iCodeTop = addByte(TokenStream.CALLSPECIAL, iCodeTop);
iCodeTop = addShort(itsLineNumber, iCodeTop);
iCodeTop = addString(itsSourceFile, iCodeTop);
} else {
iCodeTop = addByte(type, iCodeTop);
iCodeTop = addShort(nameIndex, iCodeTop);
}
itsStackDepth -= (childCount - 1); // always a result value
// subtract from child count to account for [thisObj &] fun
if (type == TokenStream.NEW)
childCount -= 1;
else
childCount -= 2;
iCodeTop = addShort(childCount, iCodeTop);
if (childCount > itsData.itsMaxArgs)
itsData.itsMaxArgs = childCount;
iCodeTop = addByte(TokenStream.SOURCEFILE, iCodeTop);
}
break;
case TokenStream.NEWLOCAL :
case TokenStream.NEWTEMP : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
}
break;
case TokenStream.USELOCAL : {
if (node.getProp(Node.TARGET_PROP) != null)
iCodeTop = addByte(TokenStream.RETSUB, iCodeTop);
else {
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
Node temp = (Node) node.getProp(Node.LOCAL_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
}
break;
case TokenStream.USETEMP : {
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
Node temp = (Node) node.getProp(Node.TEMP_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.IFEQ :
case TokenStream.IFNE :
iCodeTop = generateICode(child, iCodeTop);
itsStackDepth--; // after the conditional GOTO, really
// fall thru...
case TokenStream.GOTO :
iCodeTop = addGoto(node, (byte) type, iCodeTop);
break;
case TokenStream.JSR : {
/*
mark the target with a FINALLY_PROP to indicate
that it will have an incoming PC value on the top
of the stack.
!!!
This only works if the target follows the JSR
in the tree.
!!!
*/
Node target = (Node)(node.getProp(Node.TARGET_PROP));
target.putProp(Node.FINALLY_PROP, node);
iCodeTop = addGoto(node, TokenStream.GOSUB, iCodeTop);
}
break;
case TokenStream.AND : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int falseTarget = acquireLabel();
iCodeTop = addGoto(falseTarget, TokenStream.IFNE,
iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
markLabel(falseTarget, iCodeTop);
}
break;
case TokenStream.OR : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int trueTarget = acquireLabel();
iCodeTop = addGoto(trueTarget, TokenStream.IFEQ,
iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
markLabel(trueTarget, iCodeTop);
}
break;
case TokenStream.GETPROP : {
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__"))
iCodeTop = addByte(TokenStream.GETPROTO, iCodeTop);
else
if (s.equals("__parent__"))
iCodeTop = addByte(TokenStream.GETSCOPEPARENT, iCodeTop);
else
badTree(node);
}
else {
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.GETPROP, iCodeTop);
itsStackDepth--;
}
}
break;
case TokenStream.DELPROP :
case TokenStream.BITAND :
case TokenStream.BITOR :
case TokenStream.BITXOR :
case TokenStream.LSH :
case TokenStream.RSH :
case TokenStream.URSH :
case TokenStream.ADD :
case TokenStream.SUB :
case TokenStream.MOD :
case TokenStream.DIV :
case TokenStream.MUL :
case TokenStream.GETELEM :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
itsStackDepth--;
break;
case TokenStream.CONVERT : {
iCodeTop = generateICode(child, iCodeTop);
Object toType = node.getProp(Node.TYPE_PROP);
if (toType == ScriptRuntime.NumberClass)
iCodeTop = addByte(TokenStream.POS, iCodeTop);
else
badTree(node);
}
break;
case TokenStream.UNARYOP :
iCodeTop = generateICode(child, iCodeTop);
switch (node.getInt()) {
case TokenStream.VOID :
iCodeTop = addByte(TokenStream.POP, iCodeTop);
iCodeTop = addByte(TokenStream.UNDEFINED, iCodeTop);
break;
case TokenStream.NOT : {
int trueTarget = acquireLabel();
int beyond = acquireLabel();
iCodeTop = addGoto(trueTarget, TokenStream.IFEQ,
iCodeTop);
iCodeTop = addByte(TokenStream.TRUE, iCodeTop);
iCodeTop = addGoto(beyond, TokenStream.GOTO,
iCodeTop);
markLabel(trueTarget, iCodeTop);
iCodeTop = addByte(TokenStream.FALSE, iCodeTop);
markLabel(beyond, iCodeTop);
}
break;
case TokenStream.BITNOT :
iCodeTop = addByte(TokenStream.BITNOT, iCodeTop);
break;
case TokenStream.TYPEOF :
iCodeTop = addByte(TokenStream.TYPEOF, iCodeTop);
break;
case TokenStream.SUB :
iCodeTop = addByte(TokenStream.NEG, iCodeTop);
break;
case TokenStream.ADD :
iCodeTop = addByte(TokenStream.POS, iCodeTop);
break;
default:
badTree(node);
break;
}
break;
case TokenStream.SETPROP : {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__"))
iCodeTop = addByte(TokenStream.SETPROTO, iCodeTop);
else
if (s.equals("__parent__"))
iCodeTop = addByte(TokenStream.SETPARENT, iCodeTop);
else
badTree(node);
}
else {
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.SETPROP, iCodeTop);
itsStackDepth -= 2;
}
}
break;
case TokenStream.SETELEM :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
itsStackDepth -= 2;
break;
case TokenStream.SETNAME :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.SETNAME, iCodeTop);
iCodeTop = addString(firstChild.getString(), iCodeTop);
itsStackDepth--;
break;
case TokenStream.TYPEOF : {
String name = node.getString();
int index = -1;
// use typeofname if an activation frame exists
// since the vars all exist there instead of in jregs
if (itsInFunctionFlag && !itsData.itsNeedsActivation)
index = itsVariableTable.getOrdinal(name);
if (index == -1) {
iCodeTop = addByte(TokenStream.TYPEOFNAME, iCodeTop);
iCodeTop = addString(name, iCodeTop);
}
else {
iCodeTop = addByte(TokenStream.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
iCodeTop = addByte(TokenStream.TYPEOF, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.PARENT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.GETPARENT, iCodeTop);
break;
case TokenStream.GETBASE :
case TokenStream.BINDNAME :
case TokenStream.NAME :
case TokenStream.STRING :
iCodeTop = addByte(type, iCodeTop);
iCodeTop = addString(node.getString(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case TokenStream.INC :
case TokenStream.DEC : {
int childType = child.getType();
switch (childType) {
case TokenStream.GETVAR : {
String name = child.getString();
if (itsData.itsNeedsActivation) {
iCodeTop = addByte(TokenStream.SCOPE, iCodeTop);
iCodeTop = addByte(TokenStream.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.PROPINC
: TokenStream.PROPDEC,
iCodeTop);
itsStackDepth--;
}
else {
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.VARINC
: TokenStream.VARDEC,
iCodeTop);
int i = itsVariableTable.getOrdinal(name);
iCodeTop = addByte(i, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
}
break;
case TokenStream.GETPROP :
case TokenStream.GETELEM : {
Node getPropChild = child.getFirstChild();
iCodeTop = generateICode(getPropChild,
iCodeTop);
getPropChild = getPropChild.getNextSibling();
iCodeTop = generateICode(getPropChild,
iCodeTop);
if (childType == TokenStream.GETPROP)
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.PROPINC
: TokenStream.PROPDEC,
iCodeTop);
else
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.ELEMINC
: TokenStream.ELEMDEC,
iCodeTop);
itsStackDepth--;
}
break;
default : {
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.NAMEINC
: TokenStream.NAMEDEC,
iCodeTop);
iCodeTop = addString(child.getString(),
iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
}
break;
case TokenStream.NUMBER : {
double num = node.getDouble();
int inum = (int)num;
if (inum == num) {
if (inum == 0) {
iCodeTop = addByte(TokenStream.ZERO, iCodeTop);
}
else if (inum == 1) {
iCodeTop = addByte(TokenStream.ONE, iCodeTop);
}
else if ((short)inum == inum) {
iCodeTop = addByte(TokenStream.SHORTNUMBER, iCodeTop);
iCodeTop = addShort(inum, iCodeTop);
}
else {
iCodeTop = addByte(TokenStream.INTNUMBER, iCodeTop);
iCodeTop = addInt(inum, iCodeTop);
}
}
else {
iCodeTop = addByte(TokenStream.NUMBER, iCodeTop);
iCodeTop = addDouble(num, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case TokenStream.POP :
case TokenStream.POPV :
iCodeTop = updateLineNumber(node, iCodeTop);
case TokenStream.ENTERWITH :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
itsStackDepth--;
break;
case TokenStream.GETTHIS :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
break;
case TokenStream.NEWSCOPE :
iCodeTop = addByte(type, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case TokenStream.LEAVEWITH :
iCodeTop = addByte(type, iCodeTop);
break;
case TokenStream.TRY : {
itsTryDepth++;
if (itsTryDepth > itsData.itsMaxTryDepth)
itsData.itsMaxTryDepth = itsTryDepth;
Node catchTarget = (Node)node.getProp(Node.TARGET_PROP);
Node finallyTarget = (Node)node.getProp(Node.FINALLY_PROP);
if (catchTarget == null) {
iCodeTop = addByte(TokenStream.TRY, iCodeTop);
iCodeTop = addShort(0, iCodeTop);
}
else
iCodeTop =
addGoto(node, TokenStream.TRY, iCodeTop);
int finallyHandler = 0;
if (finallyTarget != null) {
finallyHandler = acquireLabel();
int theLabel = finallyHandler & 0x7FFFFFFF;
itsLabelTable[theLabel].addFixup(iCodeTop);
}
iCodeTop = addShort(0, iCodeTop);
Node lastChild = null;
/*
when we encounter the child of the catchTarget, we
set the stackDepth to 1 to account for the incoming
exception object.
*/
boolean insertedEndTry = false;
while (child != null) {
if (catchTarget != null && lastChild == catchTarget) {
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
/*
When the following child is the catchTarget
(or the finallyTarget if there are no catches),
the current child is the goto at the end of
the try statemets, we need to emit the endtry
before that goto.
*/
Node nextSibling = child.getNextSibling();
if (!insertedEndTry && nextSibling != null &&
(nextSibling == catchTarget ||
nextSibling == finallyTarget))
{
iCodeTop = addByte(TokenStream.ENDTRY,
iCodeTop);
insertedEndTry = true;
}
iCodeTop = generateICode(child, iCodeTop);
lastChild = child;
child = child.getNextSibling();
}
itsStackDepth = 0;
if (finallyTarget != null) {
// normal flow goes around the finally handler stublet
int skippy = acquireLabel();
iCodeTop =
addGoto(skippy, TokenStream.GOTO, iCodeTop);
// on entry the stack will have the exception object
markLabel(finallyHandler, iCodeTop);
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int theLocalSlot = itsData.itsMaxLocals++;
iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
int finallyLabel
= finallyTarget.getExistingIntProp(Node.LABEL_PROP);
iCodeTop = addGoto(finallyLabel,
TokenStream.GOSUB, iCodeTop);
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.JTHROW, iCodeTop);
itsStackDepth = 0;
markLabel(skippy, iCodeTop);
}
itsTryDepth--;
}
break;
case TokenStream.THROW :
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.THROW, iCodeTop);
itsStackDepth--;
break;
case TokenStream.RETURN :
iCodeTop = updateLineNumber(node, iCodeTop);
if (child != null)
iCodeTop = generateICode(child, iCodeTop);
else {
iCodeTop = addByte(TokenStream.UNDEFINED, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
iCodeTop = addGoto(node, TokenStream.RETURN, iCodeTop);
itsStackDepth--;
break;
case TokenStream.GETVAR : {
String name = node.getString();
if (itsData.itsNeedsActivation) {
// SETVAR handled this by turning into a SETPROP, but
// we can't do that to a GETVAR without manufacturing
// bogus children. Instead we use a special op to
// push the current scope.
iCodeTop = addByte(TokenStream.SCOPE, iCodeTop);
iCodeTop = addByte(TokenStream.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addByte(TokenStream.GETPROP, iCodeTop);
itsStackDepth--;
}
else {
int index = itsVariableTable.getOrdinal(name);
iCodeTop = addByte(TokenStream.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
}
break;
case TokenStream.SETVAR : {
if (itsData.itsNeedsActivation) {
child.setType(TokenStream.BINDNAME);
node.setType(TokenStream.SETNAME);
iCodeTop = generateICode(node, iCodeTop);
}
else {
String name = child.getString();
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
int index = itsVariableTable.getOrdinal(name);
iCodeTop = addByte(TokenStream.SETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
}
}
break;
case TokenStream.PRIMARY:
iCodeTop = addByte(node.getInt(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case TokenStream.ENUMINIT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.ENUMINIT, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
itsStackDepth--;
break;
case TokenStream.ENUMNEXT : {
iCodeTop = addByte(TokenStream.ENUMNEXT, iCodeTop);
Node init = (Node)node.getProp(Node.ENUM_PROP);
iCodeTop = addLocalRef(init, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.ENUMDONE :
// could release the local here??
break;
case TokenStream.OBJECT : {
Node regexp = (Node) node.getProp(Node.REGEXP_PROP);
int index = regexp.getExistingIntProp(Node.REGEXP_PROP);
iCodeTop = addByte(TokenStream.OBJECT, iCodeTop);
iCodeTop = addShort(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
default :
badTree(node);
break;
}
return iCodeTop;
}
private int addLocalRef(Node node, int iCodeTop)
{
int theLocalSlot = node.getIntProp(Node.LOCAL_PROP, -1);
if (theLocalSlot == -1) {
theLocalSlot = itsData.itsMaxLocals++;
node.putIntProp(Node.LOCAL_PROP, theLocalSlot);
}
iCodeTop = addByte(theLocalSlot, iCodeTop);
if (theLocalSlot >= itsData.itsMaxLocals)
itsData.itsMaxLocals = theLocalSlot + 1;
return iCodeTop;
}
private int addGoto(Node node, int gotoOp, int iCodeTop)
{
int targetLabel;
if (node.getType() == TokenStream.RETURN) {
if (itsEpilogLabel == -1)
itsEpilogLabel = acquireLabel();
targetLabel = itsEpilogLabel;
}
else {
Node target = (Node)(node.getProp(Node.TARGET_PROP));
targetLabel = target.getIntProp(Node.LABEL_PROP, -1);
if (targetLabel == -1) {
targetLabel = acquireLabel();
target.putIntProp(Node.LABEL_PROP, targetLabel);
}
}
iCodeTop = addGoto(targetLabel, (byte) gotoOp, iCodeTop);
return iCodeTop;
}
private int addGoto(int targetLabel, int gotoOp, int iCodeTop)
{
int gotoPC = iCodeTop;
iCodeTop = addByte(gotoOp, iCodeTop);
int theLabel = targetLabel & 0x7FFFFFFF;
int targetPC = itsLabelTable[theLabel].getPC();
if (targetPC != -1) {
int offset = targetPC - gotoPC;
iCodeTop = addShort(offset, iCodeTop);
}
else {
itsLabelTable[theLabel].addFixup(gotoPC + 1);
iCodeTop = addShort(0, iCodeTop);
}
return iCodeTop;
}
private int addByte(int b, int iCodeTop) {
byte[] array = itsData.itsICode;
if (array.length == iCodeTop) {
byte[] ba = new byte[iCodeTop * 2];
System.arraycopy(array, 0, ba, 0, iCodeTop);
itsData.itsICode = array = ba;
}
array[iCodeTop++] = (byte)b;
return iCodeTop;
}
private int addShort(int s, int iCodeTop) {
byte[] array = itsData.itsICode;
if (iCodeTop + 2 > array.length) {
byte[] ba = new byte[(iCodeTop + 2) * 2];
System.arraycopy(array, 0, ba, 0, iCodeTop);
itsData.itsICode = array = ba;
}
array[iCodeTop] = (byte)(s >>> 8);
array[iCodeTop + 1] = (byte)s;
return iCodeTop + 2;
}
private int addInt(int i, int iCodeTop) {
byte[] array = itsData.itsICode;
if (iCodeTop + 4 > array.length) {
byte[] ba = new byte[(iCodeTop + 4) * 2];
System.arraycopy(array, 0, ba, 0, iCodeTop);
itsData.itsICode = array = ba;
}
array[iCodeTop] = (byte)(i >>> 24);
array[iCodeTop + 1] = (byte)(i >>> 16);
array[iCodeTop + 2] = (byte)(i >>> 8);
array[iCodeTop + 3] = (byte)i;
return iCodeTop + 4;
}
private int addDouble(double num, int iCodeTop) {
int index = itsData.itsDoubleTableIndex;
if (index == 0) {
itsData.itsDoubleTable = new double[64];
}
else if (itsData.itsDoubleTable.length == index) {
double[] na = new double[index * 2];
System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index);
itsData.itsDoubleTable = na;
}
itsData.itsDoubleTable[index] = num;
itsData.itsDoubleTableIndex = index + 1;
iCodeTop = addShort(index, iCodeTop);
return iCodeTop;
}
private int addString(String str, int iCodeTop) {
int index = itsData.itsStringTableIndex;
if (itsData.itsStringTable.length == index) {
String[] sa = new String[index * 2];
System.arraycopy(itsData.itsStringTable, 0, sa, 0, index);
itsData.itsStringTable = sa;
}
itsData.itsStringTable[index] = str;
itsData.itsStringTableIndex = index + 1;
iCodeTop = addShort(index, iCodeTop);
return iCodeTop;
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
}
private static int getTarget(byte[] iCode, int pc) {
int displacement = getShort(iCode, pc);
return pc - 1 + displacement;
}
static PrintWriter out;
static {
if (printICode) {
try {
out = new PrintWriter(new FileOutputStream("icode.txt"));
out.close();
}
catch (IOException x) {
}
}
}
private static void dumpICode(InterpreterData theData) {
if (printICode) {
try {
int iCodeLength = theData.itsICodeTop;
byte iCode[] = theData.itsICode;
String[] strings = theData.itsStringTable;
out = new PrintWriter(new FileOutputStream("icode.txt", true));
out.println("ICode dump, for " + theData.itsName
+ ", length = " + iCodeLength);
out.println("MaxStack = " + theData.itsMaxStack);
for (int pc = 0; pc < iCodeLength; ) {
out.print("[" + pc + "] ");
int token = iCode[pc] & 0xff;
String tname = TokenStream.tokenToName(token);
++pc;
switch (token) {
case TokenStream.SCOPE :
case TokenStream.GETPROTO :
case TokenStream.GETPARENT :
case TokenStream.GETSCOPEPARENT :
case TokenStream.SETPROTO :
case TokenStream.SETPARENT :
case TokenStream.DELPROP :
case TokenStream.TYPEOF :
case TokenStream.NEWSCOPE :
case TokenStream.ENTERWITH :
case TokenStream.LEAVEWITH :
case TokenStream.ENDTRY :
case TokenStream.THROW :
case TokenStream.JTHROW :
case TokenStream.GETTHIS :
case TokenStream.SETELEM :
case TokenStream.GETELEM :
case TokenStream.SETPROP :
case TokenStream.GETPROP :
case TokenStream.PROPINC :
case TokenStream.PROPDEC :
case TokenStream.ELEMINC :
case TokenStream.ELEMDEC :
case TokenStream.BITNOT :
case TokenStream.BITAND :
case TokenStream.BITOR :
case TokenStream.BITXOR :
case TokenStream.LSH :
case TokenStream.RSH :
case TokenStream.URSH :
case TokenStream.NEG :
case TokenStream.POS :
case TokenStream.SUB :
case TokenStream.MUL :
case TokenStream.DIV :
case TokenStream.MOD :
case TokenStream.ADD :
case TokenStream.POPV :
case TokenStream.POP :
case TokenStream.DUP :
case TokenStream.LT :
case TokenStream.GT :
case TokenStream.LE :
case TokenStream.GE :
case TokenStream.IN :
case TokenStream.INSTANCEOF :
case TokenStream.EQ :
case TokenStream.NE :
case TokenStream.SHEQ :
case TokenStream.SHNE :
case TokenStream.ZERO :
case TokenStream.ONE :
case TokenStream.NULL :
case TokenStream.THIS :
case TokenStream.THISFN :
case TokenStream.FALSE :
case TokenStream.TRUE :
case TokenStream.UNDEFINED :
case TokenStream.SOURCEFILE :
out.println(tname);
break;
case TokenStream.GOSUB :
case TokenStream.RETURN :
case TokenStream.GOTO :
case TokenStream.IFEQ :
case TokenStream.IFNE : {
int newPC = getTarget(iCode, pc);
out.println(tname + " " + newPC);
pc += 2;
}
break;
case TokenStream.TRY : {
int newPC1 = getTarget(iCode, pc);
int newPC2 = getTarget(iCode, pc + 2);
out.println(tname + " " + newPC1
+ " " + newPC2);
pc += 4;
}
break;
case TokenStream.RETSUB :
case TokenStream.ENUMINIT :
case TokenStream.ENUMNEXT :
case TokenStream.VARINC :
case TokenStream.VARDEC :
case TokenStream.GETVAR :
case TokenStream.SETVAR :
case TokenStream.NEWTEMP :
case TokenStream.USETEMP : {
int slot = (iCode[pc] & 0xFF);
out.println(tname + " " + slot);
pc++;
}
break;
case TokenStream.CALLSPECIAL : {
int line = getShort(iCode, pc);
String name = strings[getShort(iCode, pc + 2)];
int count = getShort(iCode, pc + 4);
out.println(tname + " " + count
+ " " + line + " " + name);
pc += 6;
}
break;
case TokenStream.OBJECT :
case TokenStream.CLOSURE :
case TokenStream.NEW :
case TokenStream.CALL : {
int count = getShort(iCode, pc + 2);
String name = strings[getShort(iCode, pc)];
out.println(tname + " " + count + " \""
+ name + "\"");
pc += 4;
}
break;
case TokenStream.SHORTNUMBER : {
int value = getShort(iCode, pc);
out.println(tname + " " + value);
pc += 2;
}
break;
case TokenStream.INTNUMBER : {
int value = getInt(iCode, pc);
out.println(tname + " " + value);
pc += 4;
}
break;
case TokenStream.NUMBER : {
int index = getShort(iCode, pc);
double value = theData.itsDoubleTable[index];
out.println(tname + " " + value);
pc += 2;
}
break;
case TokenStream.TYPEOFNAME :
case TokenStream.GETBASE :
case TokenStream.BINDNAME :
case TokenStream.SETNAME :
case TokenStream.NAME :
case TokenStream.NAMEINC :
case TokenStream.NAMEDEC :
case TokenStream.STRING :
out.println(tname + " \""
+ strings[getShort(iCode, pc)] + "\"");
pc += 2;
break;
case TokenStream.LINE : {
int line = getShort(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
}
break;
default :
out.close();
throw new RuntimeException("Unknown icode : "
+ token + " @ pc : " + (pc - 1));
}
}
out.close();
}
catch (IOException x) {}
}
}
private static void createFunctionObject(InterpretedFunction fn,
Scriptable scope)
{
fn.setPrototype(ScriptableObject.getClassPrototype(scope, "Function"));
fn.setParentScope(scope);
InterpreterData id = fn.itsData;
if (id.itsName.length() == 0)
return;
if ((id.itsFunctionType == FunctionNode.FUNCTION_STATEMENT &&
fn.itsClosure == null) ||
(id.itsFunctionType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT &&
fn.itsClosure != null))
{
ScriptRuntime.setProp(scope, fn.itsData.itsName, fn, scope);
}
}
public static Object interpret(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
NativeFunction fnOrScript,
InterpreterData theData)
throws JavaScriptException
{
int i;
Object lhs;
final int maxStack = theData.itsMaxStack;
final int maxVars = (fnOrScript.argNames == null)
? 0 : fnOrScript.argNames.length;
final int maxLocals = theData.itsMaxLocals;
final int maxTryDepth = theData.itsMaxTryDepth;
final int VAR_SHFT = maxStack;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int TRY_SCOPE_SHFT = LOCAL_SHFT + maxLocals;
// stack[0 <= i < VAR_SHFT]: stack data
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_SCOPE_SHFT]: used for newtemp/usetemp
// stack[TRY_SCOPE_SHFT <= i]: try scopes
// when 0 <= i < LOCAL_SHFT and stack[x] == DBL_MRK,
// sDbl[i] gives the number value
final Object DBL_MRK = Interpreter.DBL_MRK;
Object[] stack = new Object[TRY_SCOPE_SHFT + maxTryDepth];
double[] sDbl = new double[TRY_SCOPE_SHFT];
int stackTop = -1;
byte[] iCode = theData.itsICode;
String[] strings = theData.itsStringTable;
int pc = 0;
int iCodeLength = theData.itsICodeTop;
final Scriptable undefined = Undefined.instance;
if (maxVars != 0) {
int definedArgs = fnOrScript.argCount;
if (definedArgs != 0) {
if (definedArgs > args.length) { definedArgs = args.length; }
for (i = 0; i != definedArgs; ++i) {
stack[VAR_SHFT + i] = args[i];
}
}
for (i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
}
if (theData.itsNestedFunctions != null) {
for (i = 0; i < theData.itsNestedFunctions.length; i++)
createFunctionObject(theData.itsNestedFunctions[i], scope);
}
Object id;
Object rhs, val;
double valDbl;
boolean valBln;
int count;
int slot;
String name = null;
Object[] outArgs;
int lIntValue;
double lDbl;
int rIntValue;
double rDbl;
int[] catchStack = null;
int tryStackTop = 0;
InterpreterFrame frame = null;
if (cx.debugger != null) {
frame = new InterpreterFrame(scope, theData, fnOrScript);
cx.pushFrame(frame);
}
if (maxTryDepth != 0) {
// catchStack[2 * i]: starting pc of catch block
// catchStack[2 * i + 1]: starting pc of finally block
catchStack = new int[maxTryDepth * 2];
}
/* Save the security domain. Must restore upon normal exit.
* If we exit the interpreter loop by throwing an exception,
* set cx.interpreterSecurityDomain to null, and require the
* catching function to restore it.
*/
Object savedSecurityDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = theData.securityDomain;
Object result = undefined;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
while (pc < iCodeLength) {
try {
switch (iCode[pc] & 0xff) {
case TokenStream.ENDTRY :
tryStackTop--;
break;
case TokenStream.TRY :
i = getTarget(iCode, pc + 1);
if (i == pc) i = 0;
catchStack[tryStackTop * 2] = i;
i = getTarget(iCode, pc + 3);
if (i == (pc + 2)) i = 0;
catchStack[tryStackTop * 2 + 1] = i;
stack[TRY_SCOPE_SHFT + tryStackTop] = scope;
++tryStackTop;
pc += 4;
break;
case TokenStream.GE :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& rDbl <= lDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.LE :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& lDbl <= rDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.GT :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& rDbl < lDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.LT :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& lDbl < rDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.IN :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.INSTANCEOF :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
valBln = ScriptRuntime.instanceOf(scope, lhs, rhs);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.EQ :
--stackTop;
valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.NE :
--stackTop;
valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.SHEQ :
--stackTop;
valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.SHNE :
--stackTop;
valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.IFNE :
val = stack[stackTop];
if (val != DBL_MRK) {
valBln = !ScriptRuntime.toBoolean(val);
}
else {
valDbl = sDbl[stackTop];
valBln = !(valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount
(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
case TokenStream.IFEQ :
val = stack[stackTop];
if (val != DBL_MRK) {
valBln = ScriptRuntime.toBoolean(val);
}
else {
valDbl = sDbl[stackTop];
valBln = (valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount
(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
case TokenStream.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
case TokenStream.GOSUB :
sDbl[++stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue;
case TokenStream.RETSUB :
slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot];
continue;
case TokenStream.POP :
stackTop--;
break;
case TokenStream.DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case TokenStream.POPV :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
break;
case TokenStream.RETURN :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
pc = getTarget(iCode, pc + 1);
break;
case TokenStream.BITNOT :
rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
case TokenStream.BITAND :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
case TokenStream.BITOR :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
case TokenStream.BITXOR :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
case TokenStream.LSH :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
case TokenStream.RSH :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
case TokenStream.URSH :
rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl)
>>> rIntValue;
break;
case TokenStream.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case TokenStream.SUB :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
case TokenStream.NEG :
rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
case TokenStream.POS :
rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
case TokenStream.MUL :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
case TokenStream.DIV :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
case TokenStream.MOD :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
case TokenStream.BINDNAME :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
case TokenStream.GETBASE :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
case TokenStream.SETNAME :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
// what about class cast exception here for lhs?
stack[stackTop] = ScriptRuntime.setName
((Scriptable)lhs, rhs, scope,
strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.DELPROP :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs);
break;
case TokenStream.GETPROP :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.getProp(lhs, name, scope);
break;
case TokenStream.SETPROP :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
case TokenStream.GETELEM :
do_getElem(stack, sDbl, stackTop, scope);
--stackTop;
break;
case TokenStream.SETELEM :
do_setElem(stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case TokenStream.PROPINC :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postIncrement(lhs, name, scope);
break;
case TokenStream.PROPDEC :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postDecrement(lhs, name, scope);
break;
case TokenStream.ELEMINC :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
case TokenStream.ELEMDEC :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
case TokenStream.GETTHIS :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.getThis((Scriptable)lhs);
break;
case TokenStream.NEWTEMP :
slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
case TokenStream.USETEMP :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
case TokenStream.CALLSPECIAL :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int lineNum = getShort(iCode, pc + 1);
name = strings[getShort(iCode, pc + 3)];
count = getShort(iCode, pc + 5);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, lhs, rhs, outArgs,
thisObj, scope, name, lineNum);
pc += 6;
instructionCount = cx.instructionCount;
break;
case TokenStream.CALL :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
count = getShort(iCode, pc + 3);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined) {
- lhs = strings[getShort(iCode, pc + 1)];
+ i = getShort(iCode, pc + 1);
+ if (i != -1)
+ lhs = strings[i];
}
Scriptable calleeScope = scope;
if (theData.itsNeedsActivation) {
calleeScope = ScriptableObject.
getTopLevelScope(scope);
}
stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs,
outArgs,
calleeScope);
pc += 4; instructionCount = cx.instructionCount;
break;
case TokenStream.NEW :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
count = getShort(iCode, pc + 3);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined && getShort(iCode, pc + 1) != -1)
{
// special code for better error message for call
// to undefined
lhs = strings[getShort(iCode, pc + 1)];
}
stack[stackTop] = ScriptRuntime.newObject(cx, lhs,
outArgs,
scope);
pc += 4; instructionCount = cx.instructionCount;
break;
case TokenStream.TYPEOF :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
case TokenStream.TYPEOFNAME :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop]
= ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
case TokenStream.STRING :
stack[++stackTop] = strings[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case TokenStream.INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case TokenStream.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = theData.
itsDoubleTable[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.NAME :
stack[++stackTop] = ScriptRuntime.name
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.NAMEINC :
stack[++stackTop] = ScriptRuntime.postIncrement
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.NAMEDEC :
stack[++stackTop] = ScriptRuntime.postDecrement
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.SETVAR :
slot = (iCode[++pc] & 0xFF);
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
break;
case TokenStream.GETVAR :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
break;
case TokenStream.VARINC :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot]
= stack_double(stack, sDbl, stackTop) + 1.0;
break;
case TokenStream.VARDEC :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot]
= stack_double(stack, sDbl, stackTop) - 1.0;
break;
case TokenStream.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case TokenStream.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case TokenStream.NULL :
stack[++stackTop] = null;
break;
case TokenStream.THIS :
stack[++stackTop] = thisObj;
break;
case TokenStream.THISFN :
stack[++stackTop] = fnOrScript;
break;
case TokenStream.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case TokenStream.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case TokenStream.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case TokenStream.THROW :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
throw new JavaScriptException(result);
case TokenStream.JTHROW :
result = stack[stackTop];
// No need to check for DBL_MRK: result is Exception
--stackTop;
if (result instanceof JavaScriptException)
throw (JavaScriptException)result;
else
throw (RuntimeException)result;
case TokenStream.ENTERWITH :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
break;
case TokenStream.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
break;
case TokenStream.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case TokenStream.ENUMINIT :
slot = (iCode[++pc] & 0xFF);
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot]
= ScriptRuntime.initEnum(lhs, scope);
break;
case TokenStream.ENUMNEXT :
slot = (iCode[++pc] & 0xFF);
val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.
nextEnum((Enumeration)val);
break;
case TokenStream.GETPROTO :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
case TokenStream.GETPARENT :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
case TokenStream.GETSCOPEPARENT :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
case TokenStream.SETPROTO :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setProto(lhs, rhs, scope);
break;
case TokenStream.SETPARENT :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setParent(lhs, rhs, scope);
break;
case TokenStream.SCOPE :
stack[++stackTop] = scope;
break;
case TokenStream.CLOSURE :
i = getShort(iCode, pc + 1);
stack[++stackTop]
= new InterpretedFunction(
theData.itsNestedFunctions[i],
scope, cx);
createFunctionObject(
(InterpretedFunction)stack[stackTop], scope);
pc += 2;
break;
case TokenStream.OBJECT :
i = getShort(iCode, pc + 1);
stack[++stackTop] = theData.itsRegExpLiterals[i];
pc += 2;
break;
case TokenStream.SOURCEFILE :
cx.interpreterSourceFile = theData.itsSourceFile;
break;
case TokenStream.LINE :
case TokenStream.BREAKPOINT :
i = getShort(iCode, pc + 1);
cx.interpreterLine = i;
if (frame != null)
frame.setLineNumber(i);
if ((iCode[pc] & 0xff) == TokenStream.BREAKPOINT ||
cx.inLineStepMode)
{
cx.getDebuggableEngine().
getDebugger().handleBreakpointHit(cx);
}
pc += 2;
break;
default :
dumpICode(theData);
throw new RuntimeException("Unknown icode : "
+ (iCode[pc] & 0xff) + " @ pc : " + pc);
}
pc++;
}
catch (Throwable ex) {
cx.interpreterSecurityDomain = null;
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
}
else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3;
int exType;
Object errObj; // Object seen by catch
if (ex instanceof JavaScriptException) {
errObj = ScriptRuntime.
unwrapJavaScriptException((JavaScriptException)ex);
exType = SCRIPT_THROW;
}
else if (ex instanceof EcmaError) {
// an offical ECMA error object,
errObj = ((EcmaError)ex).getErrorObject();
exType = ECMA;
}
else if (ex instanceof RuntimeException) {
errObj = ex;
exType = RUNTIME;
}
else {
errObj = ex; // Error instance
exType = OTHER;
}
if (exType != OTHER && cx.debugger != null) {
cx.debugger.handleExceptionThrown(cx, errObj);
}
boolean rethrow = true;
if (exType != OTHER && tryStackTop > 0) {
--tryStackTop;
if (exType == SCRIPT_THROW || exType == ECMA) {
// Check for catch only for
// JavaScriptException and EcmaError
pc = catchStack[tryStackTop * 2];
if (pc != 0) {
// Has catch block
rethrow = false;
}
}
if (rethrow) {
pc = catchStack[tryStackTop * 2 + 1];
if (pc != 0) {
// has finally block
rethrow = false;
errObj = ex;
}
}
}
if (rethrow) {
if (frame != null)
cx.popFrame();
if (exType == SCRIPT_THROW)
throw (JavaScriptException)ex;
if (exType == ECMA || exType == RUNTIME)
throw (RuntimeException)ex;
throw (Error)ex;
}
// We caught an exception,
// Notify instruction observer if necessary
// and point pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc;
// prepare stack and restore this function's security domain.
scope = (Scriptable)stack[TRY_SCOPE_SHFT + tryStackTop];
stackTop = 0;
stack[0] = errObj;
cx.interpreterSecurityDomain = theData.securityDomain;
}
}
cx.interpreterSecurityDomain = savedSecurityDomain;
if (frame != null)
cx.popFrame();
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
return result;
}
private static Object doubleWrap(double x) {
return new Double(x);
}
private static int stack_int32(Object[] stack, double[] stackDbl, int i) {
Object x = stack[i];
return (x != DBL_MRK)
? ScriptRuntime.toInt32(x)
: ScriptRuntime.toInt32(stackDbl[i]);
}
private static double stack_double(Object[] stack, double[] stackDbl,
int i)
{
Object x = stack[i];
return (x != DBL_MRK) ? ScriptRuntime.toNumber(x) : stackDbl[i];
}
private static void do_add(Object[] stack, double[] stackDbl, int stackTop)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
stackDbl[stackTop] += rDbl;
}
else {
do_add(lhs, rDbl, stack, stackDbl, stackTop, true);
}
}
else if (lhs == DBL_MRK) {
do_add(rhs, stackDbl[stackTop], stack, stackDbl, stackTop, false);
}
else {
if (lhs instanceof Scriptable)
lhs = ((Scriptable) lhs).getDefaultValue(null);
if (rhs instanceof Scriptable)
rhs = ((Scriptable) rhs).getDefaultValue(null);
if (lhs instanceof String || rhs instanceof String) {
stack[stackTop] = ScriptRuntime.toString(lhs)
+ ScriptRuntime.toString(rhs);
}
else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
double rDbl = (rhs instanceof Number)
? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
}
// x + y when x is Number, see
private static void do_add
(Object lhs, double rDbl,
Object[] stack, double[] stackDbl, int stackTop,
boolean left_right_order)
{
if (lhs instanceof Scriptable) {
if (lhs == Undefined.instance) {
lhs = ScriptRuntime.NaNobj;
} else {
lhs = ((Scriptable)lhs).getDefaultValue(null);
}
}
if (lhs instanceof String) {
if (left_right_order) {
stack[stackTop] = (String)lhs + ScriptRuntime.toString(rDbl);
}
else {
stack[stackTop] = ScriptRuntime.toString(rDbl) + (String)lhs;
}
}
else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
private static boolean do_eq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == stackDbl[stackTop + 1]);
}
else {
result = do_eq(stackDbl[stackTop + 1], lhs);
}
}
else {
if (lhs == DBL_MRK) {
result = do_eq(stackDbl[stackTop], rhs);
}
else {
result = ScriptRuntime.eq(lhs, rhs);
}
}
return result;
}
// Optimized version of ScriptRuntime.eq if x is a Number
private static boolean do_eq(double x, Object y) {
for (;;) {
if (y instanceof Number) {
return x == ((Number) y).doubleValue();
}
if (y instanceof String) {
return x == ScriptRuntime.toNumber((String)y);
}
if (y instanceof Boolean) {
return x == (((Boolean)y).booleanValue() ? 1 : 0);
}
if (y instanceof Scriptable) {
if (y == Undefined.instance) { return false; }
y = ScriptRuntime.toPrimitive(y);
continue;
}
return false;
}
}
private static boolean do_sheq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
}
else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
}
else if (rhs instanceof Number) {
double rDbl = ((Number)rhs).doubleValue();
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
}
else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
}
else {
result = ScriptRuntime.shallowEq(lhs, rhs);
}
return result;
}
private static void do_getElem(Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object lhs = stack[stackTop - 1];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 1]);
Object result;
Object id = stack[stackTop];
if (id != DBL_MRK) {
result = ScriptRuntime.getElem(lhs, id, scope);
}
else {
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(scope, lhs);
double val = stackDbl[stackTop];
int index = (int)val;
if (index == val) {
result = ScriptRuntime.getElem(obj, index);
}
else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.getStrIdElem(obj, s);
}
}
stack[stackTop - 1] = result;
}
private static void do_setElem(Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(stackDbl[stackTop]);
Object lhs = stack[stackTop - 2];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 2]);
Object result;
Object id = stack[stackTop - 1];
if (id != DBL_MRK) {
result = ScriptRuntime.setElem(lhs, id, rhs, scope);
}
else {
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(scope, lhs);
double val = stackDbl[stackTop - 1];
int index = (int)val;
if (index == val) {
result = ScriptRuntime.setElem(obj, index, rhs);
}
else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.setStrIdElem(obj, s, rhs, scope);
}
}
stack[stackTop - 2] = result;
}
private static Object[] getArgsArray(Object[] stack, double[] sDbl,
int stackTop, int count)
{
if (count == 0) {
return ScriptRuntime.emptyArgs;
}
Object[] args = new Object[count];
do {
Object val = stack[stackTop];
if (val == DBL_MRK)
val = doubleWrap(sDbl[stackTop]);
args[--count] = val;
--stackTop;
} while (count != 0);
return args;
}
private int version;
private boolean inLineStepMode;
private StringBuffer debugSource;
private static final Object DBL_MRK = new Object();
}
| true | true | public static Object interpret(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
NativeFunction fnOrScript,
InterpreterData theData)
throws JavaScriptException
{
int i;
Object lhs;
final int maxStack = theData.itsMaxStack;
final int maxVars = (fnOrScript.argNames == null)
? 0 : fnOrScript.argNames.length;
final int maxLocals = theData.itsMaxLocals;
final int maxTryDepth = theData.itsMaxTryDepth;
final int VAR_SHFT = maxStack;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int TRY_SCOPE_SHFT = LOCAL_SHFT + maxLocals;
// stack[0 <= i < VAR_SHFT]: stack data
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_SCOPE_SHFT]: used for newtemp/usetemp
// stack[TRY_SCOPE_SHFT <= i]: try scopes
// when 0 <= i < LOCAL_SHFT and stack[x] == DBL_MRK,
// sDbl[i] gives the number value
final Object DBL_MRK = Interpreter.DBL_MRK;
Object[] stack = new Object[TRY_SCOPE_SHFT + maxTryDepth];
double[] sDbl = new double[TRY_SCOPE_SHFT];
int stackTop = -1;
byte[] iCode = theData.itsICode;
String[] strings = theData.itsStringTable;
int pc = 0;
int iCodeLength = theData.itsICodeTop;
final Scriptable undefined = Undefined.instance;
if (maxVars != 0) {
int definedArgs = fnOrScript.argCount;
if (definedArgs != 0) {
if (definedArgs > args.length) { definedArgs = args.length; }
for (i = 0; i != definedArgs; ++i) {
stack[VAR_SHFT + i] = args[i];
}
}
for (i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
}
if (theData.itsNestedFunctions != null) {
for (i = 0; i < theData.itsNestedFunctions.length; i++)
createFunctionObject(theData.itsNestedFunctions[i], scope);
}
Object id;
Object rhs, val;
double valDbl;
boolean valBln;
int count;
int slot;
String name = null;
Object[] outArgs;
int lIntValue;
double lDbl;
int rIntValue;
double rDbl;
int[] catchStack = null;
int tryStackTop = 0;
InterpreterFrame frame = null;
if (cx.debugger != null) {
frame = new InterpreterFrame(scope, theData, fnOrScript);
cx.pushFrame(frame);
}
if (maxTryDepth != 0) {
// catchStack[2 * i]: starting pc of catch block
// catchStack[2 * i + 1]: starting pc of finally block
catchStack = new int[maxTryDepth * 2];
}
/* Save the security domain. Must restore upon normal exit.
* If we exit the interpreter loop by throwing an exception,
* set cx.interpreterSecurityDomain to null, and require the
* catching function to restore it.
*/
Object savedSecurityDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = theData.securityDomain;
Object result = undefined;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
while (pc < iCodeLength) {
try {
switch (iCode[pc] & 0xff) {
case TokenStream.ENDTRY :
tryStackTop--;
break;
case TokenStream.TRY :
i = getTarget(iCode, pc + 1);
if (i == pc) i = 0;
catchStack[tryStackTop * 2] = i;
i = getTarget(iCode, pc + 3);
if (i == (pc + 2)) i = 0;
catchStack[tryStackTop * 2 + 1] = i;
stack[TRY_SCOPE_SHFT + tryStackTop] = scope;
++tryStackTop;
pc += 4;
break;
case TokenStream.GE :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& rDbl <= lDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.LE :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& lDbl <= rDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.GT :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& rDbl < lDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.LT :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& lDbl < rDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.IN :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.INSTANCEOF :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
valBln = ScriptRuntime.instanceOf(scope, lhs, rhs);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.EQ :
--stackTop;
valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.NE :
--stackTop;
valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.SHEQ :
--stackTop;
valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.SHNE :
--stackTop;
valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.IFNE :
val = stack[stackTop];
if (val != DBL_MRK) {
valBln = !ScriptRuntime.toBoolean(val);
}
else {
valDbl = sDbl[stackTop];
valBln = !(valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount
(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
case TokenStream.IFEQ :
val = stack[stackTop];
if (val != DBL_MRK) {
valBln = ScriptRuntime.toBoolean(val);
}
else {
valDbl = sDbl[stackTop];
valBln = (valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount
(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
case TokenStream.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
case TokenStream.GOSUB :
sDbl[++stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue;
case TokenStream.RETSUB :
slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot];
continue;
case TokenStream.POP :
stackTop--;
break;
case TokenStream.DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case TokenStream.POPV :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
break;
case TokenStream.RETURN :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
pc = getTarget(iCode, pc + 1);
break;
case TokenStream.BITNOT :
rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
case TokenStream.BITAND :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
case TokenStream.BITOR :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
case TokenStream.BITXOR :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
case TokenStream.LSH :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
case TokenStream.RSH :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
case TokenStream.URSH :
rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl)
>>> rIntValue;
break;
case TokenStream.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case TokenStream.SUB :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
case TokenStream.NEG :
rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
case TokenStream.POS :
rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
case TokenStream.MUL :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
case TokenStream.DIV :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
case TokenStream.MOD :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
case TokenStream.BINDNAME :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
case TokenStream.GETBASE :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
case TokenStream.SETNAME :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
// what about class cast exception here for lhs?
stack[stackTop] = ScriptRuntime.setName
((Scriptable)lhs, rhs, scope,
strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.DELPROP :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs);
break;
case TokenStream.GETPROP :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.getProp(lhs, name, scope);
break;
case TokenStream.SETPROP :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
case TokenStream.GETELEM :
do_getElem(stack, sDbl, stackTop, scope);
--stackTop;
break;
case TokenStream.SETELEM :
do_setElem(stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case TokenStream.PROPINC :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postIncrement(lhs, name, scope);
break;
case TokenStream.PROPDEC :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postDecrement(lhs, name, scope);
break;
case TokenStream.ELEMINC :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
case TokenStream.ELEMDEC :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
case TokenStream.GETTHIS :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.getThis((Scriptable)lhs);
break;
case TokenStream.NEWTEMP :
slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
case TokenStream.USETEMP :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
case TokenStream.CALLSPECIAL :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int lineNum = getShort(iCode, pc + 1);
name = strings[getShort(iCode, pc + 3)];
count = getShort(iCode, pc + 5);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, lhs, rhs, outArgs,
thisObj, scope, name, lineNum);
pc += 6;
instructionCount = cx.instructionCount;
break;
case TokenStream.CALL :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
count = getShort(iCode, pc + 3);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined) {
lhs = strings[getShort(iCode, pc + 1)];
}
Scriptable calleeScope = scope;
if (theData.itsNeedsActivation) {
calleeScope = ScriptableObject.
getTopLevelScope(scope);
}
stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs,
outArgs,
calleeScope);
pc += 4; instructionCount = cx.instructionCount;
break;
case TokenStream.NEW :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
count = getShort(iCode, pc + 3);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined && getShort(iCode, pc + 1) != -1)
{
// special code for better error message for call
// to undefined
lhs = strings[getShort(iCode, pc + 1)];
}
stack[stackTop] = ScriptRuntime.newObject(cx, lhs,
outArgs,
scope);
pc += 4; instructionCount = cx.instructionCount;
break;
case TokenStream.TYPEOF :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
case TokenStream.TYPEOFNAME :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop]
= ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
case TokenStream.STRING :
stack[++stackTop] = strings[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case TokenStream.INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case TokenStream.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = theData.
itsDoubleTable[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.NAME :
stack[++stackTop] = ScriptRuntime.name
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.NAMEINC :
stack[++stackTop] = ScriptRuntime.postIncrement
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.NAMEDEC :
stack[++stackTop] = ScriptRuntime.postDecrement
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.SETVAR :
slot = (iCode[++pc] & 0xFF);
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
break;
case TokenStream.GETVAR :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
break;
case TokenStream.VARINC :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot]
= stack_double(stack, sDbl, stackTop) + 1.0;
break;
case TokenStream.VARDEC :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot]
= stack_double(stack, sDbl, stackTop) - 1.0;
break;
case TokenStream.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case TokenStream.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case TokenStream.NULL :
stack[++stackTop] = null;
break;
case TokenStream.THIS :
stack[++stackTop] = thisObj;
break;
case TokenStream.THISFN :
stack[++stackTop] = fnOrScript;
break;
case TokenStream.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case TokenStream.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case TokenStream.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case TokenStream.THROW :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
throw new JavaScriptException(result);
case TokenStream.JTHROW :
result = stack[stackTop];
// No need to check for DBL_MRK: result is Exception
--stackTop;
if (result instanceof JavaScriptException)
throw (JavaScriptException)result;
else
throw (RuntimeException)result;
case TokenStream.ENTERWITH :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
break;
case TokenStream.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
break;
case TokenStream.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case TokenStream.ENUMINIT :
slot = (iCode[++pc] & 0xFF);
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot]
= ScriptRuntime.initEnum(lhs, scope);
break;
case TokenStream.ENUMNEXT :
slot = (iCode[++pc] & 0xFF);
val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.
nextEnum((Enumeration)val);
break;
case TokenStream.GETPROTO :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
case TokenStream.GETPARENT :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
case TokenStream.GETSCOPEPARENT :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
case TokenStream.SETPROTO :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setProto(lhs, rhs, scope);
break;
case TokenStream.SETPARENT :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setParent(lhs, rhs, scope);
break;
case TokenStream.SCOPE :
stack[++stackTop] = scope;
break;
case TokenStream.CLOSURE :
i = getShort(iCode, pc + 1);
stack[++stackTop]
= new InterpretedFunction(
theData.itsNestedFunctions[i],
scope, cx);
createFunctionObject(
(InterpretedFunction)stack[stackTop], scope);
pc += 2;
break;
case TokenStream.OBJECT :
i = getShort(iCode, pc + 1);
stack[++stackTop] = theData.itsRegExpLiterals[i];
pc += 2;
break;
case TokenStream.SOURCEFILE :
cx.interpreterSourceFile = theData.itsSourceFile;
break;
case TokenStream.LINE :
case TokenStream.BREAKPOINT :
i = getShort(iCode, pc + 1);
cx.interpreterLine = i;
if (frame != null)
frame.setLineNumber(i);
if ((iCode[pc] & 0xff) == TokenStream.BREAKPOINT ||
cx.inLineStepMode)
{
cx.getDebuggableEngine().
getDebugger().handleBreakpointHit(cx);
}
pc += 2;
break;
default :
dumpICode(theData);
throw new RuntimeException("Unknown icode : "
+ (iCode[pc] & 0xff) + " @ pc : " + pc);
}
pc++;
}
catch (Throwable ex) {
cx.interpreterSecurityDomain = null;
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
}
else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3;
int exType;
Object errObj; // Object seen by catch
if (ex instanceof JavaScriptException) {
errObj = ScriptRuntime.
unwrapJavaScriptException((JavaScriptException)ex);
exType = SCRIPT_THROW;
}
else if (ex instanceof EcmaError) {
// an offical ECMA error object,
errObj = ((EcmaError)ex).getErrorObject();
exType = ECMA;
}
else if (ex instanceof RuntimeException) {
errObj = ex;
exType = RUNTIME;
}
else {
errObj = ex; // Error instance
exType = OTHER;
}
if (exType != OTHER && cx.debugger != null) {
cx.debugger.handleExceptionThrown(cx, errObj);
}
boolean rethrow = true;
if (exType != OTHER && tryStackTop > 0) {
--tryStackTop;
if (exType == SCRIPT_THROW || exType == ECMA) {
// Check for catch only for
// JavaScriptException and EcmaError
pc = catchStack[tryStackTop * 2];
if (pc != 0) {
// Has catch block
rethrow = false;
}
}
if (rethrow) {
pc = catchStack[tryStackTop * 2 + 1];
if (pc != 0) {
// has finally block
rethrow = false;
errObj = ex;
}
}
}
if (rethrow) {
if (frame != null)
cx.popFrame();
if (exType == SCRIPT_THROW)
throw (JavaScriptException)ex;
if (exType == ECMA || exType == RUNTIME)
throw (RuntimeException)ex;
throw (Error)ex;
}
// We caught an exception,
// Notify instruction observer if necessary
// and point pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc;
// prepare stack and restore this function's security domain.
scope = (Scriptable)stack[TRY_SCOPE_SHFT + tryStackTop];
stackTop = 0;
stack[0] = errObj;
cx.interpreterSecurityDomain = theData.securityDomain;
}
}
cx.interpreterSecurityDomain = savedSecurityDomain;
if (frame != null)
cx.popFrame();
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
return result;
}
| public static Object interpret(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
NativeFunction fnOrScript,
InterpreterData theData)
throws JavaScriptException
{
int i;
Object lhs;
final int maxStack = theData.itsMaxStack;
final int maxVars = (fnOrScript.argNames == null)
? 0 : fnOrScript.argNames.length;
final int maxLocals = theData.itsMaxLocals;
final int maxTryDepth = theData.itsMaxTryDepth;
final int VAR_SHFT = maxStack;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int TRY_SCOPE_SHFT = LOCAL_SHFT + maxLocals;
// stack[0 <= i < VAR_SHFT]: stack data
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_SCOPE_SHFT]: used for newtemp/usetemp
// stack[TRY_SCOPE_SHFT <= i]: try scopes
// when 0 <= i < LOCAL_SHFT and stack[x] == DBL_MRK,
// sDbl[i] gives the number value
final Object DBL_MRK = Interpreter.DBL_MRK;
Object[] stack = new Object[TRY_SCOPE_SHFT + maxTryDepth];
double[] sDbl = new double[TRY_SCOPE_SHFT];
int stackTop = -1;
byte[] iCode = theData.itsICode;
String[] strings = theData.itsStringTable;
int pc = 0;
int iCodeLength = theData.itsICodeTop;
final Scriptable undefined = Undefined.instance;
if (maxVars != 0) {
int definedArgs = fnOrScript.argCount;
if (definedArgs != 0) {
if (definedArgs > args.length) { definedArgs = args.length; }
for (i = 0; i != definedArgs; ++i) {
stack[VAR_SHFT + i] = args[i];
}
}
for (i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
}
if (theData.itsNestedFunctions != null) {
for (i = 0; i < theData.itsNestedFunctions.length; i++)
createFunctionObject(theData.itsNestedFunctions[i], scope);
}
Object id;
Object rhs, val;
double valDbl;
boolean valBln;
int count;
int slot;
String name = null;
Object[] outArgs;
int lIntValue;
double lDbl;
int rIntValue;
double rDbl;
int[] catchStack = null;
int tryStackTop = 0;
InterpreterFrame frame = null;
if (cx.debugger != null) {
frame = new InterpreterFrame(scope, theData, fnOrScript);
cx.pushFrame(frame);
}
if (maxTryDepth != 0) {
// catchStack[2 * i]: starting pc of catch block
// catchStack[2 * i + 1]: starting pc of finally block
catchStack = new int[maxTryDepth * 2];
}
/* Save the security domain. Must restore upon normal exit.
* If we exit the interpreter loop by throwing an exception,
* set cx.interpreterSecurityDomain to null, and require the
* catching function to restore it.
*/
Object savedSecurityDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = theData.securityDomain;
Object result = undefined;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
while (pc < iCodeLength) {
try {
switch (iCode[pc] & 0xff) {
case TokenStream.ENDTRY :
tryStackTop--;
break;
case TokenStream.TRY :
i = getTarget(iCode, pc + 1);
if (i == pc) i = 0;
catchStack[tryStackTop * 2] = i;
i = getTarget(iCode, pc + 3);
if (i == (pc + 2)) i = 0;
catchStack[tryStackTop * 2 + 1] = i;
stack[TRY_SCOPE_SHFT + tryStackTop] = scope;
++tryStackTop;
pc += 4;
break;
case TokenStream.GE :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& rDbl <= lDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.LE :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& lDbl <= rDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.GT :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& rDbl < lDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.LT :
--stackTop;
rhs = stack[stackTop + 1];
lhs = stack[stackTop];
if (rhs == DBL_MRK || lhs == DBL_MRK) {
rDbl = stack_double(stack, sDbl, stackTop + 1);
lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl
&& lDbl < rDbl);
}
else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.IN :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.INSTANCEOF :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
valBln = ScriptRuntime.instanceOf(scope, lhs, rhs);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.EQ :
--stackTop;
valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.NE :
--stackTop;
valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.SHEQ :
--stackTop;
valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.SHNE :
--stackTop;
valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
case TokenStream.IFNE :
val = stack[stackTop];
if (val != DBL_MRK) {
valBln = !ScriptRuntime.toBoolean(val);
}
else {
valDbl = sDbl[stackTop];
valBln = !(valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount
(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
case TokenStream.IFEQ :
val = stack[stackTop];
if (val != DBL_MRK) {
valBln = ScriptRuntime.toBoolean(val);
}
else {
valDbl = sDbl[stackTop];
valBln = (valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount
(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
case TokenStream.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
case TokenStream.GOSUB :
sDbl[++stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue;
case TokenStream.RETSUB :
slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot];
continue;
case TokenStream.POP :
stackTop--;
break;
case TokenStream.DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case TokenStream.POPV :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
break;
case TokenStream.RETURN :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
pc = getTarget(iCode, pc + 1);
break;
case TokenStream.BITNOT :
rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
case TokenStream.BITAND :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
case TokenStream.BITOR :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
case TokenStream.BITXOR :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
case TokenStream.LSH :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
case TokenStream.RSH :
rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
case TokenStream.URSH :
rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl)
>>> rIntValue;
break;
case TokenStream.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case TokenStream.SUB :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
case TokenStream.NEG :
rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
case TokenStream.POS :
rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
case TokenStream.MUL :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
case TokenStream.DIV :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
case TokenStream.MOD :
rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
case TokenStream.BINDNAME :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
case TokenStream.GETBASE :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
case TokenStream.SETNAME :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
// what about class cast exception here for lhs?
stack[stackTop] = ScriptRuntime.setName
((Scriptable)lhs, rhs, scope,
strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.DELPROP :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs);
break;
case TokenStream.GETPROP :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.getProp(lhs, name, scope);
break;
case TokenStream.SETPROP :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
case TokenStream.GETELEM :
do_getElem(stack, sDbl, stackTop, scope);
--stackTop;
break;
case TokenStream.SETELEM :
do_setElem(stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case TokenStream.PROPINC :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postIncrement(lhs, name, scope);
break;
case TokenStream.PROPDEC :
name = (String)stack[stackTop];
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postDecrement(lhs, name, scope);
break;
case TokenStream.ELEMINC :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
case TokenStream.ELEMDEC :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
case TokenStream.GETTHIS :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.getThis((Scriptable)lhs);
break;
case TokenStream.NEWTEMP :
slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
case TokenStream.USETEMP :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
case TokenStream.CALLSPECIAL :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int lineNum = getShort(iCode, pc + 1);
name = strings[getShort(iCode, pc + 3)];
count = getShort(iCode, pc + 5);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, lhs, rhs, outArgs,
thisObj, scope, name, lineNum);
pc += 6;
instructionCount = cx.instructionCount;
break;
case TokenStream.CALL :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
count = getShort(iCode, pc + 3);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined) {
i = getShort(iCode, pc + 1);
if (i != -1)
lhs = strings[i];
}
Scriptable calleeScope = scope;
if (theData.itsNeedsActivation) {
calleeScope = ScriptableObject.
getTopLevelScope(scope);
}
stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs,
outArgs,
calleeScope);
pc += 4; instructionCount = cx.instructionCount;
break;
case TokenStream.NEW :
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
count = getShort(iCode, pc + 3);
outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined && getShort(iCode, pc + 1) != -1)
{
// special code for better error message for call
// to undefined
lhs = strings[getShort(iCode, pc + 1)];
}
stack[stackTop] = ScriptRuntime.newObject(cx, lhs,
outArgs,
scope);
pc += 4; instructionCount = cx.instructionCount;
break;
case TokenStream.TYPEOF :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
case TokenStream.TYPEOFNAME :
name = strings[getShort(iCode, pc + 1)];
stack[++stackTop]
= ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
case TokenStream.STRING :
stack[++stackTop] = strings[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case TokenStream.INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case TokenStream.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = theData.
itsDoubleTable[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.NAME :
stack[++stackTop] = ScriptRuntime.name
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.NAMEINC :
stack[++stackTop] = ScriptRuntime.postIncrement
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.NAMEDEC :
stack[++stackTop] = ScriptRuntime.postDecrement
(scope, strings[getShort(iCode, pc + 1)]);
pc += 2;
break;
case TokenStream.SETVAR :
slot = (iCode[++pc] & 0xFF);
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
break;
case TokenStream.GETVAR :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
break;
case TokenStream.VARINC :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot]
= stack_double(stack, sDbl, stackTop) + 1.0;
break;
case TokenStream.VARDEC :
slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot]
= stack_double(stack, sDbl, stackTop) - 1.0;
break;
case TokenStream.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case TokenStream.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case TokenStream.NULL :
stack[++stackTop] = null;
break;
case TokenStream.THIS :
stack[++stackTop] = thisObj;
break;
case TokenStream.THISFN :
stack[++stackTop] = fnOrScript;
break;
case TokenStream.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case TokenStream.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case TokenStream.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case TokenStream.THROW :
result = stack[stackTop];
if (result == DBL_MRK)
result = doubleWrap(sDbl[stackTop]);
--stackTop;
throw new JavaScriptException(result);
case TokenStream.JTHROW :
result = stack[stackTop];
// No need to check for DBL_MRK: result is Exception
--stackTop;
if (result instanceof JavaScriptException)
throw (JavaScriptException)result;
else
throw (RuntimeException)result;
case TokenStream.ENTERWITH :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
break;
case TokenStream.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
break;
case TokenStream.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case TokenStream.ENUMINIT :
slot = (iCode[++pc] & 0xFF);
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot]
= ScriptRuntime.initEnum(lhs, scope);
break;
case TokenStream.ENUMNEXT :
slot = (iCode[++pc] & 0xFF);
val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.
nextEnum((Enumeration)val);
break;
case TokenStream.GETPROTO :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
case TokenStream.GETPARENT :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
case TokenStream.GETSCOPEPARENT :
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
case TokenStream.SETPROTO :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setProto(lhs, rhs, scope);
break;
case TokenStream.SETPARENT :
rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop]
= ScriptRuntime.setParent(lhs, rhs, scope);
break;
case TokenStream.SCOPE :
stack[++stackTop] = scope;
break;
case TokenStream.CLOSURE :
i = getShort(iCode, pc + 1);
stack[++stackTop]
= new InterpretedFunction(
theData.itsNestedFunctions[i],
scope, cx);
createFunctionObject(
(InterpretedFunction)stack[stackTop], scope);
pc += 2;
break;
case TokenStream.OBJECT :
i = getShort(iCode, pc + 1);
stack[++stackTop] = theData.itsRegExpLiterals[i];
pc += 2;
break;
case TokenStream.SOURCEFILE :
cx.interpreterSourceFile = theData.itsSourceFile;
break;
case TokenStream.LINE :
case TokenStream.BREAKPOINT :
i = getShort(iCode, pc + 1);
cx.interpreterLine = i;
if (frame != null)
frame.setLineNumber(i);
if ((iCode[pc] & 0xff) == TokenStream.BREAKPOINT ||
cx.inLineStepMode)
{
cx.getDebuggableEngine().
getDebugger().handleBreakpointHit(cx);
}
pc += 2;
break;
default :
dumpICode(theData);
throw new RuntimeException("Unknown icode : "
+ (iCode[pc] & 0xff) + " @ pc : " + pc);
}
pc++;
}
catch (Throwable ex) {
cx.interpreterSecurityDomain = null;
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
}
else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3;
int exType;
Object errObj; // Object seen by catch
if (ex instanceof JavaScriptException) {
errObj = ScriptRuntime.
unwrapJavaScriptException((JavaScriptException)ex);
exType = SCRIPT_THROW;
}
else if (ex instanceof EcmaError) {
// an offical ECMA error object,
errObj = ((EcmaError)ex).getErrorObject();
exType = ECMA;
}
else if (ex instanceof RuntimeException) {
errObj = ex;
exType = RUNTIME;
}
else {
errObj = ex; // Error instance
exType = OTHER;
}
if (exType != OTHER && cx.debugger != null) {
cx.debugger.handleExceptionThrown(cx, errObj);
}
boolean rethrow = true;
if (exType != OTHER && tryStackTop > 0) {
--tryStackTop;
if (exType == SCRIPT_THROW || exType == ECMA) {
// Check for catch only for
// JavaScriptException and EcmaError
pc = catchStack[tryStackTop * 2];
if (pc != 0) {
// Has catch block
rethrow = false;
}
}
if (rethrow) {
pc = catchStack[tryStackTop * 2 + 1];
if (pc != 0) {
// has finally block
rethrow = false;
errObj = ex;
}
}
}
if (rethrow) {
if (frame != null)
cx.popFrame();
if (exType == SCRIPT_THROW)
throw (JavaScriptException)ex;
if (exType == ECMA || exType == RUNTIME)
throw (RuntimeException)ex;
throw (Error)ex;
}
// We caught an exception,
// Notify instruction observer if necessary
// and point pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc;
// prepare stack and restore this function's security domain.
scope = (Scriptable)stack[TRY_SCOPE_SHFT + tryStackTop];
stackTop = 0;
stack[0] = errObj;
cx.interpreterSecurityDomain = theData.securityDomain;
}
}
cx.interpreterSecurityDomain = savedSecurityDomain;
if (frame != null)
cx.popFrame();
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
return result;
}
|
diff --git a/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java b/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java
index 97d39b2bf..65ecfd6fc 100644
--- a/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java
+++ b/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java
@@ -1,187 +1,185 @@
package biomesoplenty.integration;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import biomesoplenty.api.Blocks;
import biomesoplenty.api.Items;
import cpw.mods.fml.common.event.FMLInterModComms;
public class TreeCapitatorIntegration
{
public static void init()
{
int logs1 = Blocks.logs1.get().blockID;
int logs2 = Blocks.logs2.get().blockID;
int logs3 = Blocks.logs3.get().blockID;
int logs4 = Blocks.logs4.get().blockID;
int leavesColorized1 = Blocks.leavesColorized1.get().blockID;
int leavesColorized2 = Blocks.leavesColorized2.get().blockID;
- int leavesColorized3 = Blocks.leavesColorized3.get().blockID;
- int leavesColorized4 = Blocks.leavesColorized4.get().blockID;
int leaves1 = Blocks.leaves1.get().blockID;
int leaves2 = Blocks.leaves2.get().blockID;
int leaves3 = Blocks.leaves3.get().blockID;
int leaves4 = Blocks.leaves4.get().blockID;
NBTTagCompound tpModCfg = new NBTTagCompound();
tpModCfg.setString("modID", "BiomesOPlenty");
tpModCfg.setString("axeIDList", Items.axeAmethyst.get().itemID + "; " + Items.axeMud.get().itemID);
NBTTagList treeList = new NBTTagList();
/*
* NOTE: the vanilla trees (any tree that contains a vanilla log) are the only ones where treeName must be one of these values:
* vanilla_oak, vanilla_spruce, vanilla_birch, vanilla_jungle.
*/
// Vanilla Oak additions
NBTTagCompound tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_oak");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0; %d,3; %d; %d,0; %d,0; %d,2; 18,2; 18,10",
leaves2, leaves2, Blocks.leavesFruit.get().blockID, Blocks.leavesFruit2.get().blockID, leaves2, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Birch additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_birch");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Jungle additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_jungle");
tree.setString("logs", "");
tree.setString("leaves", "");
tree.setInteger("maxLeafIDDist", 3);
treeList.appendTag(tree);
/*
* logs1 trees
*/
// BoP acacia
tree = new NBTTagCompound();
tree.setString("treeName", "acacia");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP cherry
tree = new NBTTagCompound();
tree.setString("treeName", "cherry");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,1; %d,9; %d,3; %d,11", leaves3, leaves3, leaves3, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP darkwood
tree = new NBTTagCompound();
tree.setString("treeName", "darkwood");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,3; %d,11", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP fir
tree = new NBTTagCompound();
tree.setString("treeName", "fir");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs2 trees
*/
// BoP holy
tree = new NBTTagCompound();
tree.setString("treeName", "holy");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP magic
tree = new NBTTagCompound();
tree.setString("treeName", "magic");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP mangrove
tree = new NBTTagCompound();
tree.setString("treeName", "mangrove");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,1; %d,9", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP palm
tree = new NBTTagCompound();
tree.setString("treeName", "palm");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs3 trees
*/
// BoP redwood
tree = new NBTTagCompound();
tree.setString("treeName", "redwood");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,3; %d,11", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP willow
tree = new NBTTagCompound();
tree.setString("treeName", "willow");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized2, leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP dead
tree = new NBTTagCompound();
tree.setString("treeName", "dead");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs3, logs3, logs3));
tree.setString("leaves", "");
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP big_flower
tree = new NBTTagCompound();
tree.setString("treeName", "big_flower");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs3, logs3, logs3));
tree.setString("leaves", "" + Blocks.petals.get().blockID);
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs4 trees
*/
// BoP pine
tree = new NBTTagCompound();
tree.setString("treeName", "pine");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,2; %d,10", leavesColorized2, leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP hellbark
tree = new NBTTagCompound();
tree.setString("treeName", "hellbark");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,0; %d,8", leaves4, leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP jacaranda
tree = new NBTTagCompound();
tree.setString("treeName", "jacaranda");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,1; %d,9", leaves4, leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
tpModCfg.setTag("trees", treeList);
FMLInterModComms.sendMessage("TreeCapitator", "ThirdPartyModConfig", tpModCfg);
}
}
| true | true | public static void init()
{
int logs1 = Blocks.logs1.get().blockID;
int logs2 = Blocks.logs2.get().blockID;
int logs3 = Blocks.logs3.get().blockID;
int logs4 = Blocks.logs4.get().blockID;
int leavesColorized1 = Blocks.leavesColorized1.get().blockID;
int leavesColorized2 = Blocks.leavesColorized2.get().blockID;
int leavesColorized3 = Blocks.leavesColorized3.get().blockID;
int leavesColorized4 = Blocks.leavesColorized4.get().blockID;
int leaves1 = Blocks.leaves1.get().blockID;
int leaves2 = Blocks.leaves2.get().blockID;
int leaves3 = Blocks.leaves3.get().blockID;
int leaves4 = Blocks.leaves4.get().blockID;
NBTTagCompound tpModCfg = new NBTTagCompound();
tpModCfg.setString("modID", "BiomesOPlenty");
tpModCfg.setString("axeIDList", Items.axeAmethyst.get().itemID + "; " + Items.axeMud.get().itemID);
NBTTagList treeList = new NBTTagList();
/*
* NOTE: the vanilla trees (any tree that contains a vanilla log) are the only ones where treeName must be one of these values:
* vanilla_oak, vanilla_spruce, vanilla_birch, vanilla_jungle.
*/
// Vanilla Oak additions
NBTTagCompound tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_oak");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0; %d,3; %d; %d,0; %d,0; %d,2; 18,2; 18,10",
leaves2, leaves2, Blocks.leavesFruit.get().blockID, Blocks.leavesFruit2.get().blockID, leaves2, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Birch additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_birch");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Jungle additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_jungle");
tree.setString("logs", "");
tree.setString("leaves", "");
tree.setInteger("maxLeafIDDist", 3);
treeList.appendTag(tree);
/*
* logs1 trees
*/
// BoP acacia
tree = new NBTTagCompound();
tree.setString("treeName", "acacia");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP cherry
tree = new NBTTagCompound();
tree.setString("treeName", "cherry");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,1; %d,9; %d,3; %d,11", leaves3, leaves3, leaves3, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP darkwood
tree = new NBTTagCompound();
tree.setString("treeName", "darkwood");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,3; %d,11", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP fir
tree = new NBTTagCompound();
tree.setString("treeName", "fir");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs2 trees
*/
// BoP holy
tree = new NBTTagCompound();
tree.setString("treeName", "holy");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP magic
tree = new NBTTagCompound();
tree.setString("treeName", "magic");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP mangrove
tree = new NBTTagCompound();
tree.setString("treeName", "mangrove");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,1; %d,9", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP palm
tree = new NBTTagCompound();
tree.setString("treeName", "palm");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs3 trees
*/
// BoP redwood
tree = new NBTTagCompound();
tree.setString("treeName", "redwood");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,3; %d,11", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP willow
tree = new NBTTagCompound();
tree.setString("treeName", "willow");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized2, leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP dead
tree = new NBTTagCompound();
tree.setString("treeName", "dead");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs3, logs3, logs3));
tree.setString("leaves", "");
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP big_flower
tree = new NBTTagCompound();
tree.setString("treeName", "big_flower");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs3, logs3, logs3));
tree.setString("leaves", "" + Blocks.petals.get().blockID);
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs4 trees
*/
// BoP pine
tree = new NBTTagCompound();
tree.setString("treeName", "pine");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,2; %d,10", leavesColorized2, leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP hellbark
tree = new NBTTagCompound();
tree.setString("treeName", "hellbark");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,0; %d,8", leaves4, leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP jacaranda
tree = new NBTTagCompound();
tree.setString("treeName", "jacaranda");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,1; %d,9", leaves4, leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
tpModCfg.setTag("trees", treeList);
FMLInterModComms.sendMessage("TreeCapitator", "ThirdPartyModConfig", tpModCfg);
}
| public static void init()
{
int logs1 = Blocks.logs1.get().blockID;
int logs2 = Blocks.logs2.get().blockID;
int logs3 = Blocks.logs3.get().blockID;
int logs4 = Blocks.logs4.get().blockID;
int leavesColorized1 = Blocks.leavesColorized1.get().blockID;
int leavesColorized2 = Blocks.leavesColorized2.get().blockID;
int leaves1 = Blocks.leaves1.get().blockID;
int leaves2 = Blocks.leaves2.get().blockID;
int leaves3 = Blocks.leaves3.get().blockID;
int leaves4 = Blocks.leaves4.get().blockID;
NBTTagCompound tpModCfg = new NBTTagCompound();
tpModCfg.setString("modID", "BiomesOPlenty");
tpModCfg.setString("axeIDList", Items.axeAmethyst.get().itemID + "; " + Items.axeMud.get().itemID);
NBTTagList treeList = new NBTTagList();
/*
* NOTE: the vanilla trees (any tree that contains a vanilla log) are the only ones where treeName must be one of these values:
* vanilla_oak, vanilla_spruce, vanilla_birch, vanilla_jungle.
*/
// Vanilla Oak additions
NBTTagCompound tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_oak");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0; %d,3; %d; %d,0; %d,0; %d,2; 18,2; 18,10",
leaves2, leaves2, Blocks.leavesFruit.get().blockID, Blocks.leavesFruit2.get().blockID, leaves2, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Birch additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_birch");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Jungle additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_jungle");
tree.setString("logs", "");
tree.setString("leaves", "");
tree.setInteger("maxLeafIDDist", 3);
treeList.appendTag(tree);
/*
* logs1 trees
*/
// BoP acacia
tree = new NBTTagCompound();
tree.setString("treeName", "acacia");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP cherry
tree = new NBTTagCompound();
tree.setString("treeName", "cherry");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,1; %d,9; %d,3; %d,11", leaves3, leaves3, leaves3, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP darkwood
tree = new NBTTagCompound();
tree.setString("treeName", "darkwood");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,3; %d,11", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP fir
tree = new NBTTagCompound();
tree.setString("treeName", "fir");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs2 trees
*/
// BoP holy
tree = new NBTTagCompound();
tree.setString("treeName", "holy");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP magic
tree = new NBTTagCompound();
tree.setString("treeName", "magic");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP mangrove
tree = new NBTTagCompound();
tree.setString("treeName", "mangrove");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,1; %d,9", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP palm
tree = new NBTTagCompound();
tree.setString("treeName", "palm");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2; %d,10", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs3 trees
*/
// BoP redwood
tree = new NBTTagCompound();
tree.setString("treeName", "redwood");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,3; %d,11", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP willow
tree = new NBTTagCompound();
tree.setString("treeName", "willow");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized2, leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP dead
tree = new NBTTagCompound();
tree.setString("treeName", "dead");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs3, logs3, logs3));
tree.setString("leaves", "");
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP big_flower
tree = new NBTTagCompound();
tree.setString("treeName", "big_flower");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs3, logs3, logs3));
tree.setString("leaves", "" + Blocks.petals.get().blockID);
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs4 trees
*/
// BoP pine
tree = new NBTTagCompound();
tree.setString("treeName", "pine");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,2; %d,10", leavesColorized2, leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP hellbark
tree = new NBTTagCompound();
tree.setString("treeName", "hellbark");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,0; %d,8", leaves4, leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP jacaranda
tree = new NBTTagCompound();
tree.setString("treeName", "jacaranda");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,1; %d,9", leaves4, leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
tpModCfg.setTag("trees", treeList);
FMLInterModComms.sendMessage("TreeCapitator", "ThirdPartyModConfig", tpModCfg);
}
|
diff --git a/component/scripting/src/main/java/org/exoplatform/commons/utils/PortalPrinter.java b/component/scripting/src/main/java/org/exoplatform/commons/utils/PortalPrinter.java
index d79378575..6d28eb6c6 100755
--- a/component/scripting/src/main/java/org/exoplatform/commons/utils/PortalPrinter.java
+++ b/component/scripting/src/main/java/org/exoplatform/commons/utils/PortalPrinter.java
@@ -1,47 +1,49 @@
/*
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program 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.
*
* 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.exoplatform.commons.utils;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
* @version $Revision$
*/
public class PortalPrinter extends OutputStreamPrinter {
public PortalPrinter(TextEncoder encoder, OutputStream out) throws IllegalArgumentException {
super(encoder, out);
}
public void println() {
try {
write('\n');
} catch (IOException e) {}
}
public void print(Object o) {
try {
- if (o instanceof Text) {
+ if (o == null) {
+ write("null");
+ } else if (o instanceof Text) {
((Text)o).writeTo(this);
} else {
write(String.valueOf(o));
}
} catch (IOException e) {}
}
}
| true | true | public void print(Object o) {
try {
if (o instanceof Text) {
((Text)o).writeTo(this);
} else {
write(String.valueOf(o));
}
} catch (IOException e) {}
}
| public void print(Object o) {
try {
if (o == null) {
write("null");
} else if (o instanceof Text) {
((Text)o).writeTo(this);
} else {
write(String.valueOf(o));
}
} catch (IOException e) {}
}
|
diff --git a/src/com/android/providers/media/MediaUpgradeReceiver.java b/src/com/android/providers/media/MediaUpgradeReceiver.java
index f9eb5ba..eeba2e3 100644
--- a/src/com/android/providers/media/MediaUpgradeReceiver.java
+++ b/src/com/android/providers/media/MediaUpgradeReceiver.java
@@ -1,94 +1,95 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.providers.media;
import java.io.File;
import android.app.ActivityManagerNative;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.RemoteException;
import android.util.Log;
import android.util.Slog;
/**
* This will be launched during system boot, after the core system has
* been brought up but before any non-persistent processes have been
* started. It is launched in a special state, with no content provider
* or custom application class associated with the process running.
*
* It's job is to prime the contacts database. Either create it
* if it doesn't exist, or open it and force any necessary upgrades.
* All of this heavy lifting happens before the boot animation ends.
*/
public class MediaUpgradeReceiver extends BroadcastReceiver {
static final String TAG = "MediaUpgradeReceiver";
static final String PREF_DB_VERSION = "db_version";
@Override
public void onReceive(Context context, Intent intent) {
// We are now running with the system up, but no apps started,
// so can do whatever cleanup after an upgrade that we want.
// Lookup the last known database version
SharedPreferences prefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
int prefVersion = prefs.getInt(PREF_DB_VERSION, 0);
if (prefVersion == MediaProvider.DATABASE_VERSION) {
return;
}
prefs.edit().putInt(PREF_DB_VERSION, MediaProvider.DATABASE_VERSION).commit();
try {
File dbDir = context.getDatabasePath("foo").getParentFile();
String[] files = dbDir.list();
+ if (files == null) return;
for (int i=0; i<files.length; i++) {
String file = files[i];
if (MediaProvider.isMediaDatabaseName(file)) {
try {
ActivityManagerNative.getDefault().showBootMessage(
context.getText(R.string.upgrade_msg), true);
} catch (RemoteException e) {
}
long startTime = System.currentTimeMillis();
Slog.i(TAG, "---> Start upgrade of media database " + file);
SQLiteDatabase db = null;
try {
MediaProvider.DatabaseHelper helper = new MediaProvider.DatabaseHelper(
context, file, MediaProvider.isInternalMediaDatabaseName(file),
false, null);
db = helper.getWritableDatabase();
} catch (Throwable t) {
Log.wtf(TAG, "Error during upgrade of media db " + file, t);
} finally {
if (db != null) {
db.close();
}
}
Slog.i(TAG, "<--- Finished upgrade of media database " + file
+ " in " + (System.currentTimeMillis()-startTime) + "ms");
}
}
} catch (Throwable t) {
// Something has gone terribly wrong.
Log.wtf(TAG, "Error during upgrade attempt.", t);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
// We are now running with the system up, but no apps started,
// so can do whatever cleanup after an upgrade that we want.
// Lookup the last known database version
SharedPreferences prefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
int prefVersion = prefs.getInt(PREF_DB_VERSION, 0);
if (prefVersion == MediaProvider.DATABASE_VERSION) {
return;
}
prefs.edit().putInt(PREF_DB_VERSION, MediaProvider.DATABASE_VERSION).commit();
try {
File dbDir = context.getDatabasePath("foo").getParentFile();
String[] files = dbDir.list();
for (int i=0; i<files.length; i++) {
String file = files[i];
if (MediaProvider.isMediaDatabaseName(file)) {
try {
ActivityManagerNative.getDefault().showBootMessage(
context.getText(R.string.upgrade_msg), true);
} catch (RemoteException e) {
}
long startTime = System.currentTimeMillis();
Slog.i(TAG, "---> Start upgrade of media database " + file);
SQLiteDatabase db = null;
try {
MediaProvider.DatabaseHelper helper = new MediaProvider.DatabaseHelper(
context, file, MediaProvider.isInternalMediaDatabaseName(file),
false, null);
db = helper.getWritableDatabase();
} catch (Throwable t) {
Log.wtf(TAG, "Error during upgrade of media db " + file, t);
} finally {
if (db != null) {
db.close();
}
}
Slog.i(TAG, "<--- Finished upgrade of media database " + file
+ " in " + (System.currentTimeMillis()-startTime) + "ms");
}
}
} catch (Throwable t) {
// Something has gone terribly wrong.
Log.wtf(TAG, "Error during upgrade attempt.", t);
}
}
| public void onReceive(Context context, Intent intent) {
// We are now running with the system up, but no apps started,
// so can do whatever cleanup after an upgrade that we want.
// Lookup the last known database version
SharedPreferences prefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
int prefVersion = prefs.getInt(PREF_DB_VERSION, 0);
if (prefVersion == MediaProvider.DATABASE_VERSION) {
return;
}
prefs.edit().putInt(PREF_DB_VERSION, MediaProvider.DATABASE_VERSION).commit();
try {
File dbDir = context.getDatabasePath("foo").getParentFile();
String[] files = dbDir.list();
if (files == null) return;
for (int i=0; i<files.length; i++) {
String file = files[i];
if (MediaProvider.isMediaDatabaseName(file)) {
try {
ActivityManagerNative.getDefault().showBootMessage(
context.getText(R.string.upgrade_msg), true);
} catch (RemoteException e) {
}
long startTime = System.currentTimeMillis();
Slog.i(TAG, "---> Start upgrade of media database " + file);
SQLiteDatabase db = null;
try {
MediaProvider.DatabaseHelper helper = new MediaProvider.DatabaseHelper(
context, file, MediaProvider.isInternalMediaDatabaseName(file),
false, null);
db = helper.getWritableDatabase();
} catch (Throwable t) {
Log.wtf(TAG, "Error during upgrade of media db " + file, t);
} finally {
if (db != null) {
db.close();
}
}
Slog.i(TAG, "<--- Finished upgrade of media database " + file
+ " in " + (System.currentTimeMillis()-startTime) + "ms");
}
}
} catch (Throwable t) {
// Something has gone terribly wrong.
Log.wtf(TAG, "Error during upgrade attempt.", t);
}
}
|
diff --git a/src/ischemia/CompoundProcedure.java b/src/ischemia/CompoundProcedure.java
index 233bbc6..ecacf9e 100644
--- a/src/ischemia/CompoundProcedure.java
+++ b/src/ischemia/CompoundProcedure.java
@@ -1,28 +1,28 @@
package ischemia;
//A user-defined procedure
public class CompoundProcedure extends Procedure {
private SchemeObject body;
private SchemeObject unboundArgs;
public CompoundProcedure(SchemeObject args, SchemeObject body) {
//Use the begin form defined previously to make sure that
//the body of the lambda is one expression only and avoid repeating the code.
this.unboundArgs = args;
this.body = new Pair(new Pair(Symbol.beginSymbol, body), EmptyList.makeEmptyList());
}
//Evaluates the procedure in the given environment
public EvaluationResult evalProcedure(Environment environment,
SchemeObject args) throws EvalException {
//Extend the environment so that the arguments passed to the procedure are
//visible
Environment evalEnv = new Environment(environment, new Frame(unboundArgs, args));
//Since we wrapped the body of the procedure in a begin, we know there's only
//one element in the body.
- return EvaluationResult.makeFinished(((Pair)body).car().evaluate(evalEnv));
+ return EvaluationResult.makeUnfinished(((Pair)body).car(), evalEnv);
}
}
| true | true | public EvaluationResult evalProcedure(Environment environment,
SchemeObject args) throws EvalException {
//Extend the environment so that the arguments passed to the procedure are
//visible
Environment evalEnv = new Environment(environment, new Frame(unboundArgs, args));
//Since we wrapped the body of the procedure in a begin, we know there's only
//one element in the body.
return EvaluationResult.makeFinished(((Pair)body).car().evaluate(evalEnv));
}
| public EvaluationResult evalProcedure(Environment environment,
SchemeObject args) throws EvalException {
//Extend the environment so that the arguments passed to the procedure are
//visible
Environment evalEnv = new Environment(environment, new Frame(unboundArgs, args));
//Since we wrapped the body of the procedure in a begin, we know there's only
//one element in the body.
return EvaluationResult.makeUnfinished(((Pair)body).car(), evalEnv);
}
|
diff --git a/ide/eclipse/cep/org.wso2.developerstudio.eclipse.artifact.cep/src/org/wso2/developerstudio/eclipse/artifact/cep/ui/wizard/CEPProjectCreationWizard.java b/ide/eclipse/cep/org.wso2.developerstudio.eclipse.artifact.cep/src/org/wso2/developerstudio/eclipse/artifact/cep/ui/wizard/CEPProjectCreationWizard.java
index bc0b4786d..09dbf4e0a 100755
--- a/ide/eclipse/cep/org.wso2.developerstudio.eclipse.artifact.cep/src/org/wso2/developerstudio/eclipse/artifact/cep/ui/wizard/CEPProjectCreationWizard.java
+++ b/ide/eclipse/cep/org.wso2.developerstudio.eclipse.artifact.cep/src/org/wso2/developerstudio/eclipse/artifact/cep/ui/wizard/CEPProjectCreationWizard.java
@@ -1,151 +1,151 @@
/*
* Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.artifact.cep.ui.wizard;
import java.io.File;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.wso2.developerstudio.eclipse.artifact.cep.Activator;
import org.wso2.developerstudio.eclipse.artifact.cep.editor.CEPProjectEditorPage;
import org.wso2.developerstudio.eclipse.artifact.cep.model.CEPModel;
import org.wso2.developerstudio.eclipse.artifact.cep.utils.CEPImageUtils;
import org.wso2.developerstudio.eclipse.artifact.cep.utils.CEPTemplateUtils;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.platform.core.utils.XMLUtil;
import org.wso2.developerstudio.eclipse.platform.ui.wizard.AbstractWSO2ProjectCreationWizard;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
import org.wso2.developerstudio.eclipse.utils.project.ProjectUtils;
public class CEPProjectCreationWizard extends AbstractWSO2ProjectCreationWizard {
private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
private final CEPModel cepModel;
private static final String CEP_WIZARD_WINDOW_TITLE = "Create New CEP Project";
private IProject project;
private File openFile = null;
public static String pathfile;
public CEPProjectCreationWizard() {
this.cepModel = new CEPModel();
setModel(this.cepModel);
setWindowTitle(CEP_WIZARD_WINDOW_TITLE);
setDefaultPageImageDescriptor(CEPImageUtils.getInstance()
.getImageDescriptor("buket-64x64.png"));
}
public boolean performFinish() {
CEPProjectEditorPage.isCreatedProject = false;
boolean already = false;
try {
if (getModel().getSelectedOption().equals("import.cepproject")) {
File importFile = getModel().getImportFile();
CEPProjectEditorPage.initialFileLocation = importFile
.getAbsolutePath();
CEPProjectEditorPage.isNewProject = false;
IProject exproject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(cepModel.getProjectName());
if (exproject.exists()) {
MessageDialog.openError(getShell(), "ERROR",
"Project already exisits");
} else {
cepModel.setBucketName(cepModel.getProjectName());
project = createNewProject();
openFile = addCEPTemplate(project);
}
}
if (getModel().getSelectedOption().equals("new.cepproject")) {
project = createNewProject();
openFile = addCEPTemplate(project);
CEPProjectEditorPage.bucketProjectName = project.getName();
cepModel.setBucketName(project.getName());
}
if (!already) {
File pomfile = project.getFile("pom.xml").getLocation()
.toFile();
getModel().getMavenInfo().setPackageName(
- "cep" + File.separator + "bucket");
+ "cep/bucket");
createPOM(pomfile);
ProjectUtils.addNatureToProject(project, false,
"org.wso2.developerstudio.eclipse.cep.project.nature");
getModel().addToWorkingSet(project);
project.refreshLocal(IResource.DEPTH_INFINITE,
new NullProgressMonitor());
try {
refreshDistProjects();
IFile cepFile = ResourcesPlugin
.getWorkspace()
.getRoot()
.getFileForLocation(
Path.fromOSString(openFile
.getAbsolutePath()));
IDE.openEditor(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage(),
new FileEditorInput(cepFile),
"org.wso2.developerstudio.eclipse.artifact.cep.editor.CEPProjectEditor");
} catch (Exception e) {
log.error("Cannot open file in editor", e);
}
}
} catch (CoreException e) {
log.error("CoreException has occurred", e);
} catch (Exception e) {
log.error("An unexpected error has occurred", e);
}
return true;
}
private File addCEPTemplate(IProject project) throws Exception {
String eol = System.getProperty("line.separator");
File cepTemplateFile = new CEPTemplateUtils()
.getResourceFile("templates" + File.separator
+ "cepservice.xml");
String templateContent = FileUtils.getContentAsString(cepTemplateFile);
templateContent = templateContent.replaceAll("\\{", "<");
templateContent = templateContent.replaceAll("\\}", ">");
templateContent = templateContent.replaceAll("<service.name>",
cepModel.getBucketName());
IFolder cepfolder = project.getFolder("src" + File.separator + "main"
+ File.separator + "cepbucket");
File template = new File(cepfolder.getLocation().toFile(),
cepModel.getBucketName() + ".xml");
templateContent = XMLUtil.prettify(templateContent);
templateContent = templateContent.replaceAll("^" + eol, "");
FileUtils.createFile(template, templateContent);
return template;
}
public IResource getCreatedResource() {
return project;
}
}
| true | true | public boolean performFinish() {
CEPProjectEditorPage.isCreatedProject = false;
boolean already = false;
try {
if (getModel().getSelectedOption().equals("import.cepproject")) {
File importFile = getModel().getImportFile();
CEPProjectEditorPage.initialFileLocation = importFile
.getAbsolutePath();
CEPProjectEditorPage.isNewProject = false;
IProject exproject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(cepModel.getProjectName());
if (exproject.exists()) {
MessageDialog.openError(getShell(), "ERROR",
"Project already exisits");
} else {
cepModel.setBucketName(cepModel.getProjectName());
project = createNewProject();
openFile = addCEPTemplate(project);
}
}
if (getModel().getSelectedOption().equals("new.cepproject")) {
project = createNewProject();
openFile = addCEPTemplate(project);
CEPProjectEditorPage.bucketProjectName = project.getName();
cepModel.setBucketName(project.getName());
}
if (!already) {
File pomfile = project.getFile("pom.xml").getLocation()
.toFile();
getModel().getMavenInfo().setPackageName(
"cep" + File.separator + "bucket");
createPOM(pomfile);
ProjectUtils.addNatureToProject(project, false,
"org.wso2.developerstudio.eclipse.cep.project.nature");
getModel().addToWorkingSet(project);
project.refreshLocal(IResource.DEPTH_INFINITE,
new NullProgressMonitor());
try {
refreshDistProjects();
IFile cepFile = ResourcesPlugin
.getWorkspace()
.getRoot()
.getFileForLocation(
Path.fromOSString(openFile
.getAbsolutePath()));
IDE.openEditor(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage(),
new FileEditorInput(cepFile),
"org.wso2.developerstudio.eclipse.artifact.cep.editor.CEPProjectEditor");
} catch (Exception e) {
log.error("Cannot open file in editor", e);
}
}
} catch (CoreException e) {
log.error("CoreException has occurred", e);
} catch (Exception e) {
log.error("An unexpected error has occurred", e);
}
return true;
}
| public boolean performFinish() {
CEPProjectEditorPage.isCreatedProject = false;
boolean already = false;
try {
if (getModel().getSelectedOption().equals("import.cepproject")) {
File importFile = getModel().getImportFile();
CEPProjectEditorPage.initialFileLocation = importFile
.getAbsolutePath();
CEPProjectEditorPage.isNewProject = false;
IProject exproject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(cepModel.getProjectName());
if (exproject.exists()) {
MessageDialog.openError(getShell(), "ERROR",
"Project already exisits");
} else {
cepModel.setBucketName(cepModel.getProjectName());
project = createNewProject();
openFile = addCEPTemplate(project);
}
}
if (getModel().getSelectedOption().equals("new.cepproject")) {
project = createNewProject();
openFile = addCEPTemplate(project);
CEPProjectEditorPage.bucketProjectName = project.getName();
cepModel.setBucketName(project.getName());
}
if (!already) {
File pomfile = project.getFile("pom.xml").getLocation()
.toFile();
getModel().getMavenInfo().setPackageName(
"cep/bucket");
createPOM(pomfile);
ProjectUtils.addNatureToProject(project, false,
"org.wso2.developerstudio.eclipse.cep.project.nature");
getModel().addToWorkingSet(project);
project.refreshLocal(IResource.DEPTH_INFINITE,
new NullProgressMonitor());
try {
refreshDistProjects();
IFile cepFile = ResourcesPlugin
.getWorkspace()
.getRoot()
.getFileForLocation(
Path.fromOSString(openFile
.getAbsolutePath()));
IDE.openEditor(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage(),
new FileEditorInput(cepFile),
"org.wso2.developerstudio.eclipse.artifact.cep.editor.CEPProjectEditor");
} catch (Exception e) {
log.error("Cannot open file in editor", e);
}
}
} catch (CoreException e) {
log.error("CoreException has occurred", e);
} catch (Exception e) {
log.error("An unexpected error has occurred", e);
}
return true;
}
|
diff --git a/src/org/jsc/client/RegisterScreen.java b/src/org/jsc/client/RegisterScreen.java
index 31ff908..525c207 100644
--- a/src/org/jsc/client/RegisterScreen.java
+++ b/src/org/jsc/client/RegisterScreen.java
@@ -1,683 +1,683 @@
package org.jsc.client;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.TreeMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* A set of panels to allow users to register for a class. Collects the information
* needed for registration, and then redirects the user to PayPal for payment.
* @author Matt Jones
*/
public class RegisterScreen extends BaseScreen implements ValueChangeHandler {
private static final String MERCHANT_ID = "339U3JVK2X4E6"; // sandbox testing merchantid
// private static final String MERCHANT_ID = "4STDKBE3NBV64"; // real JSC account merchantid
private static final String PAYPAL_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
// private static final String PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr";
private static final String PAYPAL_HEADER_IMAGE = "http://juneauskatingclub.org/sites/all/themes/jsc/images/salamander1/jsc-header-bkg-paypal.png";
private static final String PAYPAL_RETURN_URL = "http://reg.juneauskatingclub.org";
private static final String PAYPAL_CANCEL_URL = "http://reg.juneauskatingclub.org";
private static final String PAYMENT_DATA_ID = "U7fGZVYSiD6KerUAg_PhVMlmWIkK1MM2WazdncZQz_v4Dx4HIpre8iyz92e";
private static final int EARLY_PRICE_GRACE_DAYS = 2;
private static final double MILLISECS_PER_DAY = 24*60*60*1000;
private static final double EARLY_PRICE = 70.00;
private static final double STANDARD_PRICE = 80.00;
private static final double FS_PRICE = 80.00;
private static final double MEMBERSHIP_PRICE = 60.00;
private static final double MEMBERSHIP_DISCOUNT = 5.00;
private static final String DISCOUNT_EXPLANATION = "<p class=\"jsc-text\">Because it helps with planning our class sizes, <b>we offer a discount for those who register early</b> (more than " + EARLY_PRICE_GRACE_DAYS + " days before the session starts).</p>";
private static final String PRICE_EXPLANATION = "<div id=\"explainstep\"><p class=\"jsc-text\">After you choose a class, you will be prompted to make payment through PayPal.</p>" + DISCOUNT_EXPLANATION + "</div>";
private static final String PAYPAL_EXPLANATION = "<div id=\"explainstep\"><p class=\"jsc-text\">You must make your payment using PayPal by clicking on the button below. <b>Your registration is <em>not complete</em></b> until after you have completed payment.</p><p class=\"jsc-text\">When you click \"Pay Now\" below, you will be taken to the PayPal site to make payment. PayPal will allow you to pay by credit card or using your bank account, among other options. Once the payment has been made, you will be returned to this site and your registration will be complete.</p></div>";
private static final String BS_EXPLANATION = "Basic Skills is our Learn to Skate program. These group lessons are based on the United States Figure Skating's (USFSA) Basic Skills Program. This is a nationwide, skills-based, graduated series of instruction for youth and adult skaters. This program is designed to teach all skaters the fundamentals of skating.";
private static final String FS_EXPLANATION = "Figure Skating is a one- to five-day-a-week program for skaters that have completed all of the Basic Skills Levels (8) or Adult Levels (4). Students work individually with their coach to develop their skills. Please only sign up for Figure Skating Classes if you have graduated from the Basic Skills program.";
private static final String STEP_1 = "Step 1: Choose a class";
private static final String STEP_2 = "Step 2: Process payment";
private ClassListModel sessionClassList;
// sessionClassLabels has the same data as sessionClassList but is keyed on
// the classid for ease of lookup of the label associated with a class
private TreeMap<String, String> sessionClassLabels;
private HorizontalPanel screen;
private VerticalPanel outerVerticalPanel;
private HorizontalPanel outerHorizPanel;
private RadioButton bsRadio;
private RadioButton fsRadio;
private VerticalPanel bsClassChoicePanel;
private VerticalPanel ppPaymentPanel;
private VerticalPanel bsPanel;
private VerticalPanel fsPanel;
private Label stepLabel;
private Grid basicSkillsGrid;
private Grid figureSkatingGrid;
private Label feeLabel;
private ListBox classField;
private Button registerButton;
private SkaterRegistrationServiceAsync regService;
private CheckBox memberCheckbox;
private Label memberDues;
private double totalFSCost;
private Label totalCostLabel;
private double total;
private Label memberCheckboxLabel;
private HashSet<String> fsClassesToRegister;
private Label discountLabel;
private NumberFormat numfmt;
private Label bsTotalLabel;
private Label bsDiscountLabel;
/**
* Construct the Registration view and controller used to display a form for
* registering for skating classes.
* @param loginSession the authenticated login session for submissions to the remote service
* @param sessionClassList the model of skating classes
*/
public RegisterScreen(LoginSession loginSession, HandlerManager eventBus, ClassListModel sessionClassList) {
super(loginSession, eventBus);
this.sessionClassList = sessionClassList;
sessionClassLabels = new TreeMap<String, String>();
numfmt = NumberFormat.getFormat("$#,##0.00");
fsClassesToRegister = new HashSet<String>();
totalFSCost = 0;
layoutScreen();
this.setContentPanel(screen);
regService = GWT.create(SkaterRegistrationService.class);
}
/**
* Lay out the user interface widgets on the screen.
*/
private void layoutScreen() {
this.setScreenTitle("Register");
this.setStyleName("jsc-onepanel-screen");
screen = new HorizontalPanel();
layoutBsPanel();
layoutFsPanel();
ppPaymentPanel = new VerticalPanel();
ppPaymentPanel.setVisible(false);
registerButton = new Button("Continue");
registerButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
register();
}
});
registerButton.addStyleName("jsc-button-right");
outerVerticalPanel = new VerticalPanel();
stepLabel = new Label(STEP_1);
stepLabel.addStyleName("jsc-step");
outerVerticalPanel.add(stepLabel);
bsRadio = new RadioButton("BSorFSGroup", "Basic Skills Classes");
bsRadio.addValueChangeHandler(this);
bsRadio.setValue(true);
fsRadio = new RadioButton("BSorFSGroup", "Figure Skating Classes");
fsRadio.addValueChangeHandler(this);
outerVerticalPanel.add(bsRadio);
outerVerticalPanel.add(fsRadio);
outerHorizPanel = new HorizontalPanel();
outerHorizPanel.add(bsPanel);
outerHorizPanel.add(fsPanel);
outerHorizPanel.add(ppPaymentPanel);
outerVerticalPanel.add(outerHorizPanel);
outerVerticalPanel.add(registerButton);
outerVerticalPanel.addStyleName("jsc-rightpanel");
screen.add(outerVerticalPanel);
}
/**
* Layout the user interface widgets for the basic skills screen.
*/
private void layoutBsPanel() {
bsPanel = new VerticalPanel();
Label bscTitle = new Label("Basic Skills Classes");
bscTitle.addStyleName("jsc-fieldlabel-left");
bsPanel.add(bscTitle);
Label bscDescription = new Label(BS_EXPLANATION);
bscDescription.addStyleName("jsc-text");
bsPanel.add(bscDescription);
basicSkillsGrid = new Grid(0, 4);
addToBSGrid(" ", new Label(" "));
classField = new ListBox();
classField.setVisibleItemCount(1);
addToBSGrid("Class:", classField);
int currentRow = basicSkillsGrid.getRowCount() - 1;
feeLabel = new Label("");
basicSkillsGrid.setWidget(currentRow, 2, new Label("Cost"));
basicSkillsGrid.setWidget(currentRow, 3, feeLabel);
HTMLTable.CellFormatter fmt = basicSkillsGrid.getCellFormatter();
fmt.addStyleName(currentRow, 2, "jsc-fieldlabel");
fmt.addStyleName(currentRow, 3, "jsc-currencyfield");
bsDiscountLabel = new Label();
int newRow = basicSkillsGrid.insertRow(basicSkillsGrid.getRowCount());
basicSkillsGrid.setWidget(newRow, 2, new Label("Discount"));
basicSkillsGrid.setWidget(newRow, 3, bsDiscountLabel);
fmt.addStyleName(newRow, 2, "jsc-fieldlabel");
fmt.addStyleName(newRow, 3, "jsc-currencyfield");
bsTotalLabel = new Label();
newRow = basicSkillsGrid.insertRow(basicSkillsGrid.getRowCount());
basicSkillsGrid.setWidget(newRow, 2, new Label("Total"));
basicSkillsGrid.setWidget(newRow, 3, bsTotalLabel);
fmt.addStyleName(newRow, 2, "jsc-fieldlabel");
fmt.addStyleName(newRow, 3, "jsc-currencyfield");
bsClassChoicePanel = new VerticalPanel();
bsClassChoicePanel.add(new HTMLPanel(PRICE_EXPLANATION));
bsClassChoicePanel.add(basicSkillsGrid);
bsPanel.add(bsClassChoicePanel);
}
/**
* Create the widgets needed to populate the figure skating registration panel.
*/
private void layoutFsPanel() {
// Create the panel, its labels, and the contained grid for layout
fsPanel = new VerticalPanel();
Label fscTitle = new Label("Figure Skating Classes");
fscTitle.addStyleName("jsc-fieldlabel-left");
fsPanel.add(fscTitle);
Label fscDescription = new Label(FS_EXPLANATION);
fscDescription.addStyleName("jsc-text");
fsPanel.add(fscDescription);
figureSkatingGrid = new Grid(0, 6);
// Insert the first row containing the membership fields
int newRow = figureSkatingGrid.insertRow(figureSkatingGrid.getRowCount());
memberCheckbox = new CheckBox();
memberCheckboxLabel = new Label("Pay membership dues");
memberDues = new Label();
double zero = 0;
memberDues.setText(numfmt.format(zero));
memberCheckbox.setValue(false, false);
memberCheckbox.addValueChangeHandler(this);
figureSkatingGrid.setWidget(newRow, 2, memberCheckbox);
figureSkatingGrid.setWidget(newRow, 3, memberCheckboxLabel);
figureSkatingGrid.setWidget(newRow, 4, new Label("Dues"));
figureSkatingGrid.setWidget(newRow, 5, memberDues);
HTMLTable.CellFormatter fmt = figureSkatingGrid.getCellFormatter();
fmt.addStyleName(newRow, 2, "jsc-fieldlabel");
fmt.addStyleName(newRow, 3, "jsc-field");
fmt.addStyleName(newRow, 4, "jsc-fieldlabel");
fmt.addStyleName(newRow, 5, "jsc-currencyfield");
// Insert the next to last row containing the discount amount
newRow = figureSkatingGrid.insertRow(figureSkatingGrid.getRowCount());
discountLabel = new Label();
discountLabel.setText(numfmt.format(zero));
figureSkatingGrid.setWidget(newRow, 4, new Label("Discount"));
figureSkatingGrid.setWidget(newRow, 5, discountLabel);
fmt.addStyleName(newRow, 4, "jsc-fieldlabel");
fmt.addStyleName(newRow, 5, "jsc-currencyfield");
// Insert the last row containing the payment total
newRow = figureSkatingGrid.insertRow(figureSkatingGrid.getRowCount());
totalCostLabel = new Label();
totalCostLabel.setText(numfmt.format(zero));
figureSkatingGrid.setWidget(newRow, 4, new Label("Total"));
figureSkatingGrid.setWidget(newRow, 5, totalCostLabel);
fmt.addStyleName(newRow, 4, "jsc-fieldlabel");
fmt.addStyleName(newRow, 5, "jsc-currencyfield");
fsPanel.add(figureSkatingGrid);
fsPanel.setVisible(false);
}
/**
* Add the given widget to the grid table along with a label. The Label is
* placed in column 1 of the grid, and the widget in column 2.
* @param label the label to display in column 1
* @param widget the widget to display in column 2
*/
private void addToBSGrid(String label, Widget widget) {
int newRow = basicSkillsGrid.insertRow(basicSkillsGrid.getRowCount());
basicSkillsGrid.setWidget(newRow, 0, new Label(label));
basicSkillsGrid.setWidget(newRow, 1, widget);
HTMLTable.CellFormatter fmt = basicSkillsGrid.getCellFormatter();
fmt.addStyleName(newRow, 0, "jsc-fieldlabel");
fmt.addStyleName(newRow, 1, "jsc-field");
}
/**
* Add the given FSClassCheckBox to the Figure Skating grid table along with a label.
* The Label is placed in column 2 of the grid, and the checkbox in column 1.
* FSClassCheckBox also contains a label that can be used to display the price
* of a figure skating class, and this label is placed in column 5.
*
* @param label the label to display in column 2
* @param widget the FSClassCheckBox to display in column 1
*/
private void addToFSGrid(String label, FSClassCheckBox widget) {
int newRow = figureSkatingGrid.insertRow(figureSkatingGrid.getRowCount()-2);
figureSkatingGrid.setWidget(newRow, 0, widget);
figureSkatingGrid.setWidget(newRow, 1, new Label(label));
figureSkatingGrid.setWidget(newRow, 5, widget.getClassPriceLabel());
HTMLTable.CellFormatter fmt = figureSkatingGrid.getCellFormatter();
fmt.addStyleName(newRow, 0, "jsc-fieldlabel");
fmt.addStyleName(newRow, 1, "jsc-field");
fmt.addStyleName(newRow, 5, "jsc-currencyfield");
}
/**
* Remove the current list of classes from the box and replace with the
* classes that are currently present in sessionClassList. Reset the
* registration form to the initial state of the application.
*/
protected void updateRegistrationScreenDetails() {
// Reset the form fields to begin registration
ppPaymentPanel.setVisible(false);
stepLabel.setText(STEP_1);
bsRadio.setVisible(true);
fsRadio.setVisible(true);
if (bsRadio.getValue()) {
bsPanel.setVisible(true);
fsPanel.setVisible(false);
} else {
bsPanel.setVisible(false);
fsPanel.setVisible(true);
}
registerButton.setVisible(true);
// Clear the list of basic skills classes to reflect the new data
classField.clear();
sessionClassLabels = new TreeMap<String, String>();
// Clear the set of fsClasses to be registered, and the form totals
fsClassesToRegister.clear();
totalFSCost = 0;
total = 0;
// Remove all of the rows from the FS grid table except the first and last two rows
int rows = figureSkatingGrid.getRowCount();
for (int i = rows-3; i > 0; i--) {
GWT.log("Removing FS table row: " + i, null);
figureSkatingGrid.removeRow(i);
}
// Iterate over the new list of classes, putting each class into either
// the dropdown for Basic Skills classes or the checkbox list for
// Figure Skating classes
ArrayList<SessionSkatingClass> list = sessionClassList.getClassList();
if (list != null) {
for (SessionSkatingClass curClass : list) {
GWT.log("SessionClass: " + (new Long(curClass.getClassId()).toString()) + " " + curClass.getClassType(), null);
String classLabel = curClass.formatClassLabel();
sessionClassLabels.put(new Long(curClass.getClassId()).toString(), classLabel);
// If it starts with "FS " it is a figure skating class
if (curClass.getClassType().startsWith("FS ")) {
FSClassCheckBox checkbox = new FSClassCheckBox();
checkbox.setValue(false, false);
checkbox.setName(Long.toString(curClass.getClassId()));
checkbox.addValueChangeHandler(this);
addToFSGrid(classLabel, checkbox);
// Otherwise it is a Basic Skills class
} else {
classField.addItem(classLabel, new Long(curClass.getClassId()).toString());
}
}
}
// Update the membership checkbox status based on the Person logged in
if (loginSession.getPerson().isMember()) {
memberCheckboxLabel.setText("Membership dues already paid. Discount applies.");
memberCheckbox.setEnabled(false);
double dues = 0;
String duesString = numfmt.format(dues);
memberDues.setText(duesString);
} else {
memberCheckboxLabel.setText("Pay membership dues");
memberCheckbox.setEnabled(true);
//String duesString = numfmt.format(MEMBERSHIP_PRICE);
//memberDues.setText(duesString);
}
recalculateAndDisplayBasicSkillsTotal();
recalculateAndDisplayTotals();
}
/**
* Set the price and discount for the Basic Skills form by recalculating the
* discount.
*/
private void recalculateAndDisplayBasicSkillsTotal() {
// Update the cost discount, and total fields on the BS Form
feeLabel.setText(numfmt.format(STANDARD_PRICE));
double bsDiscount = calculateDiscount();
bsDiscountLabel.setText(numfmt.format(bsDiscount));
double bsTotal = STANDARD_PRICE - bsDiscount;
bsTotalLabel.setText(numfmt.format(bsTotal));
}
/**
* Register for a class by creating a RosterEntry object from the form input
* and pass it to the remote registration service.
*/
private void register() {
GWT.log("Registering for a class...", null);
if (loginSession.isAuthenticated()) {
// This is the array of roster entries that should be created in the db
ArrayList<RosterEntry> entryList = new ArrayList<RosterEntry>();
boolean createMembership = false;
// Gather information from the Basic Skills form if it is selected
if (bsRadio.getValue()) {
String selectedClassId = classField.getValue(classField.getSelectedIndex());
Person registrant = loginSession.getPerson();
RosterEntry entry = new RosterEntry();
entry.setClassid(new Long(selectedClassId).longValue());
entry.setPid(registrant.getPid());
entry.setPayment_amount(STANDARD_PRICE);
entryList.add(entry);
// Otherwise gather information from the Figure Skating form if it is selected
} else if (fsRadio.getValue()) {
if (memberCheckbox.getValue() == true &! loginSession.getPerson().isMember()) {
createMembership = true;
}
// Loop through the checked classes, creating a RosterEntry for each
for (String selectedClassId : fsClassesToRegister) {
GWT.log("Need to register class: " + selectedClassId, null);
Person registrant = loginSession.getPerson();
RosterEntry entry = new RosterEntry();
entry.setClassid(new Long(selectedClassId).longValue());
entry.setPid(registrant.getPid());
entry.setPayment_amount(FS_PRICE);
entryList.add(entry);
}
} else {
GWT.log("Neither BS nor FS form is active. This shouldn't happen!", null);
return;
}
// Initialize the service proxy.
if (regService == null) {
regService = GWT.create(SkaterRegistrationService.class);
}
// Set up the callback object.
AsyncCallback<RegistrationResults> callback = new AsyncCallback<RegistrationResults>() {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
GWT.log("Failed to register the RosterEntry array.", caught);
}
public void onSuccess(RegistrationResults results) {
ArrayList<RosterEntry> newEntryList = results.getEntriesCreated();
if ((newEntryList == null || newEntryList.size() == 0) && !results.isMembershipAttempted()) {
// Failure on the remote end.
// Could simply be due to duplication errors
// TODO: Handle case where all duplication errors occur
// Could still have membership created in this case
- setMessage("Error registering for the class(es).");
+ setMessage("Error registering... Have you are already registered for these classes? Check 'My Classes'.");
return;
} else {
// TODO: Handle case where some duplication errors occur on insert but not all
// TODO: Post error messages about entries that were not created
StringBuffer ppCart = new StringBuffer();
ppCart.append("<form id=\"wizard\" action=\""+ PAYPAL_URL + "\" method=\"post\">");
ppCart.append("<input type=\"hidden\" name=\"cmd\" value=\"_cart\">");
ppCart.append("<input type=\"hidden\" name=\"upload\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"business\" value=\"" + MERCHANT_ID + "\">");
ppCart.append("<input type=\"hidden\" name=\"currency_code\" value=\"USD\">");
ppCart.append("<input type=\"hidden\" name=\"no_note\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"no_shipping\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"cpp_header_image\" value=\""+ PAYPAL_HEADER_IMAGE + "\">");
ppCart.append("<input type=\"hidden\" name=\"item_name\" value=\""+ "Registration Invoice" + "\">");
ppCart.append("<input type=\"hidden\" name=\"invoice\" value=\""+ results.getPaymentId() + "\">");
int i = 0;
for (RosterEntry newEntry : newEntryList) {
i++;
ppCart.append("<input type=\"hidden\" name=\"item_name_" + i + "\" value=\"" + sessionClassLabels.get(new Long(newEntry.getClassid()).toString()) + "\">");
ppCart.append("<input type=\"hidden\" name=\"item_number_" + i + "\" value=\""+ newEntry.getRosterid() +"\">");
ppCart.append("<input type=\"hidden\" name=\"amount_" + i + "\" value=\"" + STANDARD_PRICE + "\">");
}
// Handle membership payment by creating form items as needed
if (results.isMembershipCreated()) {
loginSession.getPerson().setMember(true);
loginSession.getPerson().setMembershipId(results.getMembershipId());
double dues = MEMBERSHIP_PRICE;
i++;
String season = SessionSkatingClass.calculateSeason();
ppCart.append("<input type=\"hidden\" name=\"item_name_" + i + "\" value=\"Membership dues for " + season + " season\">");
ppCart.append("<input type=\"hidden\" name=\"item_number_" + i + "\" value=\"" + results.getMembershipId() +"\">");
ppCart.append("<input type=\"hidden\" name=\"amount_" + i + "\" value=\"" + MEMBERSHIP_PRICE + "\">");
}
ppCart.append("<input type=\"hidden\" name=\"discount_amount_cart\" value=\"" + calculateDiscount() + "\">");
ppCart.append("<input type=\"hidden\" name=\"return\" value=\"" + PAYPAL_RETURN_URL + "\">");
ppCart.append("<input type=\"hidden\" name=\"cancel_return\" value=\"" + PAYPAL_CANCEL_URL + "\">");
ppCart.append("<input type=\"submit\" name=\"Pay Now\" value=\"Complete Payment Now\">");
//ppCart.append("<input type=\"image\" src=\"https://www.sandbox.paypal.com/en_US/i/btn/btn_paynow_LG.gif\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">");
//ppCart.append("<img alt=\"\" border=\"0\" src=\"https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">");
ppCart.append("</form>");
registerButton.setVisible(false);
ArrayList<Long> entriesFailed = results.getEntriesNotCreated();
if (entriesFailed.size() > 0) {
setMessage("You were already registered for " + entriesFailed.size() +
" classes, which were excluded.");
}
stepLabel.setText(STEP_2);
bsRadio.setVisible(false);
fsRadio.setVisible(false);
bsPanel.setVisible(false);
fsPanel.setVisible(false);
ppPaymentPanel.clear();
ppPaymentPanel.add(new HTMLPanel(PAYPAL_EXPLANATION));
ppPaymentPanel.add(new HTMLPanel(ppCart.toString()));
ppPaymentPanel.setVisible(true);
}
}
};
// Make the call to the registration service.
regService.register(loginSession, loginSession.getPerson(), entryList, createMembership, callback);
} else {
GWT.log("Error: Can not register without first signing in.", null);
}
}
/**
* Listen for change events when the radio buttons on the registration form
* are selected and deselected.
*/
public void onValueChange(ValueChangeEvent event) {
Widget sender = (Widget) event.getSource();
if (sender == bsRadio) {
GWT.log("bsRadio clicked", null);
recalculateAndDisplayBasicSkillsTotal();
bsPanel.setVisible(true);
fsPanel.setVisible(false);
} else if (sender == fsRadio) {
GWT.log("fsRadio clicked", null);
recalculateAndDisplayTotals();
bsPanel.setVisible(false);
fsPanel.setVisible(true);
} else if (sender == memberCheckbox) {
GWT.log("memberCheckbox clicked", null);
double dues = 0;
if (memberCheckbox.getValue() == true &! loginSession.getPerson().isMember()) {
dues = MEMBERSHIP_PRICE;
totalFSCost += MEMBERSHIP_PRICE;
} else {
dues = 0;
totalFSCost -= MEMBERSHIP_PRICE;
}
String duesString = numfmt.format(dues);
memberDues.setText(duesString);
recalculateAndDisplayTotals();
} else if (sender instanceof FSClassCheckBox) {
FSClassCheckBox sendercb = (FSClassCheckBox)sender;
GWT.log( "Checked class: " + sendercb.getName(), null);
if (sendercb.getValue() == true) {
totalFSCost += FS_PRICE;
fsClassesToRegister.add(sendercb.getName());
sendercb.setClassPrice(FS_PRICE);
} else {
totalFSCost -= FS_PRICE;
fsClassesToRegister.remove(sendercb.getName());
sendercb.setClassPrice(0);
}
recalculateAndDisplayTotals();
}
}
/**
* Recalculate the total amount of the registration charges, and update the
* screen to reflect the totals.
*/
private void recalculateAndDisplayTotals() {
double discount = calculateDiscount();
discountLabel.setText(numfmt.format(discount));
total = totalFSCost - discount;
totalCostLabel.setText(numfmt.format(total));
}
/**
* Calculate the registration discount based on the number of classes
* for which the user registers and whether or not they are a member of
* the club. Hard coding this algorithm is painful, but there are so many
* possible variants it seems that some aspect will be hardcoded.
* @return the amount of the discount
*/
private double calculateDiscount() {
double multiclassDiscount = 0;
// TODO: determine how to externalize this algorithm for discounting
if (fsClassesToRegister.size() == 3) {
multiclassDiscount = 10;
} else if (fsClassesToRegister.size() == 4) {
multiclassDiscount = 25;
} else if (fsClassesToRegister.size() >= 5) {
multiclassDiscount = 50;
}
// If the person is already a member, or if they have checked the
// membership box, then include the membership discount
double membershipDiscount = 0;
if (loginSession.getPerson().isMember() || memberCheckbox.getValue()) {
membershipDiscount = fsClassesToRegister.size()*MEMBERSHIP_DISCOUNT;
}
// Calculate the basic skills discount
ArrayList<SessionSkatingClass> list = sessionClassList.getClassList();
double bsDiscount = 0;
String sessionStart = list.get(0).getStartDate();
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd");
if (sessionStart != null) {
Date startDate = fmt.parse(sessionStart);
Date today = new Date(System.currentTimeMillis());
if (today.before(startDate) &&
(startDate.getTime() - today.getTime() > EARLY_PRICE_GRACE_DAYS*MILLISECS_PER_DAY)) {
bsDiscount = STANDARD_PRICE - EARLY_PRICE;
}
}
// If the Basic Skills screen is active, return the bsDiscount
// Otherwise, return the figure skating discount
if (bsRadio.getValue()) {
return bsDiscount;
} else {
return multiclassDiscount + membershipDiscount;
}
}
/**
* An extension of CheckBox that is used to display a figure skating class
* checkbox on the registration panel. Instances of FSClassCheckBox keep
* track of the current price of the class to be displayed, and contain a
* label that can be used to display the current price. Whenever the price
* of a class is updated, the label is also updated.
* @author Matt Jones
*
*/
private class FSClassCheckBox extends CheckBox {
private Label classPriceLabel;
private double classPrice;
private NumberFormat numfmt;
/**
* Construct the checkbox, initializing the internal label and price.
*/
public FSClassCheckBox() {
super();
numfmt = NumberFormat.getFormat("$#,##0.00");
classPriceLabel = new Label();
setClassPrice(0);
}
/**
* @return the classPrice
*/
public double getClassPrice() {
return classPrice;
}
/**
* @param classPrice the classPrice to set
*/
public void setClassPrice(double classPrice) {
this.classPrice = classPrice;
this.classPriceLabel.setText(numfmt.format(classPrice));
}
/**
* @return the classPriceLabel
*/
public Label getClassPriceLabel() {
return classPriceLabel;
}
}
}
| true | true | private void register() {
GWT.log("Registering for a class...", null);
if (loginSession.isAuthenticated()) {
// This is the array of roster entries that should be created in the db
ArrayList<RosterEntry> entryList = new ArrayList<RosterEntry>();
boolean createMembership = false;
// Gather information from the Basic Skills form if it is selected
if (bsRadio.getValue()) {
String selectedClassId = classField.getValue(classField.getSelectedIndex());
Person registrant = loginSession.getPerson();
RosterEntry entry = new RosterEntry();
entry.setClassid(new Long(selectedClassId).longValue());
entry.setPid(registrant.getPid());
entry.setPayment_amount(STANDARD_PRICE);
entryList.add(entry);
// Otherwise gather information from the Figure Skating form if it is selected
} else if (fsRadio.getValue()) {
if (memberCheckbox.getValue() == true &! loginSession.getPerson().isMember()) {
createMembership = true;
}
// Loop through the checked classes, creating a RosterEntry for each
for (String selectedClassId : fsClassesToRegister) {
GWT.log("Need to register class: " + selectedClassId, null);
Person registrant = loginSession.getPerson();
RosterEntry entry = new RosterEntry();
entry.setClassid(new Long(selectedClassId).longValue());
entry.setPid(registrant.getPid());
entry.setPayment_amount(FS_PRICE);
entryList.add(entry);
}
} else {
GWT.log("Neither BS nor FS form is active. This shouldn't happen!", null);
return;
}
// Initialize the service proxy.
if (regService == null) {
regService = GWT.create(SkaterRegistrationService.class);
}
// Set up the callback object.
AsyncCallback<RegistrationResults> callback = new AsyncCallback<RegistrationResults>() {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
GWT.log("Failed to register the RosterEntry array.", caught);
}
public void onSuccess(RegistrationResults results) {
ArrayList<RosterEntry> newEntryList = results.getEntriesCreated();
if ((newEntryList == null || newEntryList.size() == 0) && !results.isMembershipAttempted()) {
// Failure on the remote end.
// Could simply be due to duplication errors
// TODO: Handle case where all duplication errors occur
// Could still have membership created in this case
setMessage("Error registering for the class(es).");
return;
} else {
// TODO: Handle case where some duplication errors occur on insert but not all
// TODO: Post error messages about entries that were not created
StringBuffer ppCart = new StringBuffer();
ppCart.append("<form id=\"wizard\" action=\""+ PAYPAL_URL + "\" method=\"post\">");
ppCart.append("<input type=\"hidden\" name=\"cmd\" value=\"_cart\">");
ppCart.append("<input type=\"hidden\" name=\"upload\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"business\" value=\"" + MERCHANT_ID + "\">");
ppCart.append("<input type=\"hidden\" name=\"currency_code\" value=\"USD\">");
ppCart.append("<input type=\"hidden\" name=\"no_note\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"no_shipping\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"cpp_header_image\" value=\""+ PAYPAL_HEADER_IMAGE + "\">");
ppCart.append("<input type=\"hidden\" name=\"item_name\" value=\""+ "Registration Invoice" + "\">");
ppCart.append("<input type=\"hidden\" name=\"invoice\" value=\""+ results.getPaymentId() + "\">");
int i = 0;
for (RosterEntry newEntry : newEntryList) {
i++;
ppCart.append("<input type=\"hidden\" name=\"item_name_" + i + "\" value=\"" + sessionClassLabels.get(new Long(newEntry.getClassid()).toString()) + "\">");
ppCart.append("<input type=\"hidden\" name=\"item_number_" + i + "\" value=\""+ newEntry.getRosterid() +"\">");
ppCart.append("<input type=\"hidden\" name=\"amount_" + i + "\" value=\"" + STANDARD_PRICE + "\">");
}
// Handle membership payment by creating form items as needed
if (results.isMembershipCreated()) {
loginSession.getPerson().setMember(true);
loginSession.getPerson().setMembershipId(results.getMembershipId());
double dues = MEMBERSHIP_PRICE;
i++;
String season = SessionSkatingClass.calculateSeason();
ppCart.append("<input type=\"hidden\" name=\"item_name_" + i + "\" value=\"Membership dues for " + season + " season\">");
ppCart.append("<input type=\"hidden\" name=\"item_number_" + i + "\" value=\"" + results.getMembershipId() +"\">");
ppCart.append("<input type=\"hidden\" name=\"amount_" + i + "\" value=\"" + MEMBERSHIP_PRICE + "\">");
}
ppCart.append("<input type=\"hidden\" name=\"discount_amount_cart\" value=\"" + calculateDiscount() + "\">");
ppCart.append("<input type=\"hidden\" name=\"return\" value=\"" + PAYPAL_RETURN_URL + "\">");
ppCart.append("<input type=\"hidden\" name=\"cancel_return\" value=\"" + PAYPAL_CANCEL_URL + "\">");
ppCart.append("<input type=\"submit\" name=\"Pay Now\" value=\"Complete Payment Now\">");
//ppCart.append("<input type=\"image\" src=\"https://www.sandbox.paypal.com/en_US/i/btn/btn_paynow_LG.gif\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">");
//ppCart.append("<img alt=\"\" border=\"0\" src=\"https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">");
ppCart.append("</form>");
registerButton.setVisible(false);
ArrayList<Long> entriesFailed = results.getEntriesNotCreated();
if (entriesFailed.size() > 0) {
setMessage("You were already registered for " + entriesFailed.size() +
" classes, which were excluded.");
}
stepLabel.setText(STEP_2);
bsRadio.setVisible(false);
fsRadio.setVisible(false);
bsPanel.setVisible(false);
fsPanel.setVisible(false);
ppPaymentPanel.clear();
ppPaymentPanel.add(new HTMLPanel(PAYPAL_EXPLANATION));
ppPaymentPanel.add(new HTMLPanel(ppCart.toString()));
ppPaymentPanel.setVisible(true);
}
}
};
// Make the call to the registration service.
regService.register(loginSession, loginSession.getPerson(), entryList, createMembership, callback);
} else {
GWT.log("Error: Can not register without first signing in.", null);
}
}
| private void register() {
GWT.log("Registering for a class...", null);
if (loginSession.isAuthenticated()) {
// This is the array of roster entries that should be created in the db
ArrayList<RosterEntry> entryList = new ArrayList<RosterEntry>();
boolean createMembership = false;
// Gather information from the Basic Skills form if it is selected
if (bsRadio.getValue()) {
String selectedClassId = classField.getValue(classField.getSelectedIndex());
Person registrant = loginSession.getPerson();
RosterEntry entry = new RosterEntry();
entry.setClassid(new Long(selectedClassId).longValue());
entry.setPid(registrant.getPid());
entry.setPayment_amount(STANDARD_PRICE);
entryList.add(entry);
// Otherwise gather information from the Figure Skating form if it is selected
} else if (fsRadio.getValue()) {
if (memberCheckbox.getValue() == true &! loginSession.getPerson().isMember()) {
createMembership = true;
}
// Loop through the checked classes, creating a RosterEntry for each
for (String selectedClassId : fsClassesToRegister) {
GWT.log("Need to register class: " + selectedClassId, null);
Person registrant = loginSession.getPerson();
RosterEntry entry = new RosterEntry();
entry.setClassid(new Long(selectedClassId).longValue());
entry.setPid(registrant.getPid());
entry.setPayment_amount(FS_PRICE);
entryList.add(entry);
}
} else {
GWT.log("Neither BS nor FS form is active. This shouldn't happen!", null);
return;
}
// Initialize the service proxy.
if (regService == null) {
regService = GWT.create(SkaterRegistrationService.class);
}
// Set up the callback object.
AsyncCallback<RegistrationResults> callback = new AsyncCallback<RegistrationResults>() {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
GWT.log("Failed to register the RosterEntry array.", caught);
}
public void onSuccess(RegistrationResults results) {
ArrayList<RosterEntry> newEntryList = results.getEntriesCreated();
if ((newEntryList == null || newEntryList.size() == 0) && !results.isMembershipAttempted()) {
// Failure on the remote end.
// Could simply be due to duplication errors
// TODO: Handle case where all duplication errors occur
// Could still have membership created in this case
setMessage("Error registering... Have you are already registered for these classes? Check 'My Classes'.");
return;
} else {
// TODO: Handle case where some duplication errors occur on insert but not all
// TODO: Post error messages about entries that were not created
StringBuffer ppCart = new StringBuffer();
ppCart.append("<form id=\"wizard\" action=\""+ PAYPAL_URL + "\" method=\"post\">");
ppCart.append("<input type=\"hidden\" name=\"cmd\" value=\"_cart\">");
ppCart.append("<input type=\"hidden\" name=\"upload\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"business\" value=\"" + MERCHANT_ID + "\">");
ppCart.append("<input type=\"hidden\" name=\"currency_code\" value=\"USD\">");
ppCart.append("<input type=\"hidden\" name=\"no_note\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"no_shipping\" value=\"1\">");
ppCart.append("<input type=\"hidden\" name=\"cpp_header_image\" value=\""+ PAYPAL_HEADER_IMAGE + "\">");
ppCart.append("<input type=\"hidden\" name=\"item_name\" value=\""+ "Registration Invoice" + "\">");
ppCart.append("<input type=\"hidden\" name=\"invoice\" value=\""+ results.getPaymentId() + "\">");
int i = 0;
for (RosterEntry newEntry : newEntryList) {
i++;
ppCart.append("<input type=\"hidden\" name=\"item_name_" + i + "\" value=\"" + sessionClassLabels.get(new Long(newEntry.getClassid()).toString()) + "\">");
ppCart.append("<input type=\"hidden\" name=\"item_number_" + i + "\" value=\""+ newEntry.getRosterid() +"\">");
ppCart.append("<input type=\"hidden\" name=\"amount_" + i + "\" value=\"" + STANDARD_PRICE + "\">");
}
// Handle membership payment by creating form items as needed
if (results.isMembershipCreated()) {
loginSession.getPerson().setMember(true);
loginSession.getPerson().setMembershipId(results.getMembershipId());
double dues = MEMBERSHIP_PRICE;
i++;
String season = SessionSkatingClass.calculateSeason();
ppCart.append("<input type=\"hidden\" name=\"item_name_" + i + "\" value=\"Membership dues for " + season + " season\">");
ppCart.append("<input type=\"hidden\" name=\"item_number_" + i + "\" value=\"" + results.getMembershipId() +"\">");
ppCart.append("<input type=\"hidden\" name=\"amount_" + i + "\" value=\"" + MEMBERSHIP_PRICE + "\">");
}
ppCart.append("<input type=\"hidden\" name=\"discount_amount_cart\" value=\"" + calculateDiscount() + "\">");
ppCart.append("<input type=\"hidden\" name=\"return\" value=\"" + PAYPAL_RETURN_URL + "\">");
ppCart.append("<input type=\"hidden\" name=\"cancel_return\" value=\"" + PAYPAL_CANCEL_URL + "\">");
ppCart.append("<input type=\"submit\" name=\"Pay Now\" value=\"Complete Payment Now\">");
//ppCart.append("<input type=\"image\" src=\"https://www.sandbox.paypal.com/en_US/i/btn/btn_paynow_LG.gif\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">");
//ppCart.append("<img alt=\"\" border=\"0\" src=\"https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">");
ppCart.append("</form>");
registerButton.setVisible(false);
ArrayList<Long> entriesFailed = results.getEntriesNotCreated();
if (entriesFailed.size() > 0) {
setMessage("You were already registered for " + entriesFailed.size() +
" classes, which were excluded.");
}
stepLabel.setText(STEP_2);
bsRadio.setVisible(false);
fsRadio.setVisible(false);
bsPanel.setVisible(false);
fsPanel.setVisible(false);
ppPaymentPanel.clear();
ppPaymentPanel.add(new HTMLPanel(PAYPAL_EXPLANATION));
ppPaymentPanel.add(new HTMLPanel(ppCart.toString()));
ppPaymentPanel.setVisible(true);
}
}
};
// Make the call to the registration service.
regService.register(loginSession, loginSession.getPerson(), entryList, createMembership, callback);
} else {
GWT.log("Error: Can not register without first signing in.", null);
}
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
index 2d5bc00..92d1cc8 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
@@ -1,324 +1,327 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder.impl.osm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.common.geometry.PackedCoordinateSequence.Float;
import org.opentripplanner.graph_builder.model.osm.OSMNode;
import org.opentripplanner.graph_builder.model.osm.OSMRelation;
import org.opentripplanner.graph_builder.model.osm.OSMWay;
import org.opentripplanner.graph_builder.services.GraphBuilder;
import org.opentripplanner.graph_builder.services.osm.OpenStreetMapContentHandler;
import org.opentripplanner.graph_builder.services.osm.OpenStreetMapProvider;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.Intersection;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.Street;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
import org.opentripplanner.routing.edgetype.Turn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
public class OpenStreetMapGraphBuilderImpl implements GraphBuilder {
private static Logger _log = LoggerFactory.getLogger(OpenStreetMapGraphBuilderImpl.class);
private static final GeometryFactory _geometryFactory = new GeometryFactory();
private List<OpenStreetMapProvider> _providers = new ArrayList<OpenStreetMapProvider>();
private Map<Object, Object> _uniques = new HashMap<Object, Object>();
public void setProvider(OpenStreetMapProvider provider) {
_providers.add(provider);
}
public void setProviders(List<OpenStreetMapProvider> providers) {
_providers.addAll(providers);
}
@Override
public void buildGraph(Graph graph) {
Handler handler = new Handler();
for (OpenStreetMapProvider provider : _providers) {
_log.debug("gathering osm from provider: " + provider);
provider.readOSM(handler);
}
_log.debug("building osm street graph");
handler.buildGraph(graph);
}
@SuppressWarnings("unchecked")
private <T> T unique(T value) {
Object v = _uniques.get(value);
if (v == null) {
_uniques.put(value, value);
v = value;
}
return (T) v;
}
private class Handler implements OpenStreetMapContentHandler {
private Map<Integer, OSMNode> _nodes = new HashMap<Integer, OSMNode>();
private Map<Integer, OSMWay> _ways = new HashMap<Integer, OSMWay>();
public void buildGraph(Graph graph) {
// We want to prune nodes that don't have any edges
Set<Integer> nodesWithNeighbors = new HashSet<Integer>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
if (nodes.size() > 1)
nodesWithNeighbors.addAll(nodes);
}
// Remove all simple islands
_nodes.keySet().retainAll(nodesWithNeighbors);
pruneFloatingIslands();
HashMap<Coordinate, ArrayList<Edge>> edgesByLocation = new HashMap<Coordinate, ArrayList<Edge>>();
int wayIndex = 0;
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
StreetTraversalPermission permissions = getPermissionsForWay(way);
List<Integer> nodes = way.getNodeRefs();
for (int i = 0; i < nodes.size() - 1; i++) {
Integer startNode = nodes.get(i);
String vFromId = getVertexIdForNodeId(startNode) + "_" + i + "_" + way.getId();
Integer endNode = nodes.get(i + 1);
String vToId = getVertexIdForNodeId(endNode) + "_" + i + "_" + way.getId();
OSMNode osmStartNode = _nodes.get(startNode);
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
Vertex from = addVertex(graph, vFromId, osmStartNode);
Vertex to = addVertex(graph, vToId, osmEndNode);
double d = from.distance(to);
Street street = getEdgeForStreet(from, to, way, d, permissions);
graph.addEdge(street);
Street backStreet = getEdgeForStreet(to, from, way, d, permissions);
graph.addEdge(backStreet);
ArrayList<Edge> startEdges = edgesByLocation.get(from.getCoordinate());
if (startEdges == null) {
startEdges = new ArrayList<Edge>();
edgesByLocation.put(from.getCoordinate(), startEdges);
}
startEdges.add(street);
ArrayList<Edge> endEdges = edgesByLocation.get(to.getCoordinate());
if (endEdges == null) {
endEdges = new ArrayList<Edge>();
edgesByLocation.put(to.getCoordinate(), endEdges);
}
endEdges.add(backStreet);
}
}
// add turns
for (ArrayList<Edge> edges : edgesByLocation.values()) {
for (Edge in : edges) {
Vertex tov = in.getToVertex();
Coordinate c = tov.getCoordinate();
ArrayList<Edge> outEdges = edgesByLocation.get(c);
if (outEdges != null) {
/* If this is not an intersection or street name change, unify the vertices */
+ boolean unified = false;
if (outEdges.size() == 2) {
for (Edge out : outEdges) {
Vertex fromVertex = out.getFromVertex();
if (tov != fromVertex && out.getName() == in.getName()) {
Intersection v = (Intersection) tov;
v.mergeFrom(graph, (Intersection) fromVertex);
graph.removeVertex(fromVertex);
+ unified = true;
break;
}
}
- } else {
+ }
+ if (!unified) {
for (Edge out : outEdges) {
/*
* Only create a turn edge if: (a) the edge is not the one we are
* coming from (b) the edge is a Street (c) the edge is an outgoing
* edge from this location
*/
if (tov != out.getFromVertex() && out instanceof Street
&& out.getFromVertex().getCoordinate().equals(c)) {
graph.addEdge(new Turn(in, out));
}
}
}
}
}
}
}
private Vertex addVertex(Graph graph, String vertexId, OSMNode node) {
Intersection newVertex = new Intersection(vertexId, node.getLon(), node.getLat());
graph.addVertex(newVertex);
return newVertex;
}
private void pruneFloatingIslands() {
Map<Integer, HashSet<Integer>> subgraphs = new HashMap<Integer, HashSet<Integer>>();
Map<Integer, ArrayList<Integer>> neighborsForNode = new HashMap<Integer, ArrayList<Integer>>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
for (int node : nodes) {
ArrayList<Integer> nodelist = neighborsForNode.get(node);
if (nodelist == null) {
nodelist = new ArrayList<Integer>();
neighborsForNode.put(node, nodelist);
}
nodelist.addAll(nodes);
}
}
/* associate each node with a subgraph */
for (int node : _nodes.keySet()) {
if (subgraphs.containsKey(node)) {
continue;
}
HashSet<Integer> subgraph = computeConnectedSubgraph(neighborsForNode, node);
for (int subnode : subgraph) {
subgraphs.put(subnode, subgraph);
}
}
/* find the largest subgraph */
HashSet<Integer> largestSubgraph = null;
for (HashSet<Integer> subgraph : subgraphs.values()) {
if (largestSubgraph == null || largestSubgraph.size() < subgraph.size()) {
largestSubgraph = subgraph;
}
}
/* delete the rest */
_nodes.keySet().retainAll(largestSubgraph);
}
private HashSet<Integer> computeConnectedSubgraph(
Map<Integer, ArrayList<Integer>> neighborsForNode, int startNode) {
HashSet<Integer> subgraph = new HashSet<Integer>();
Queue<Integer> q = new LinkedList<Integer>();
q.add(startNode);
while (!q.isEmpty()) {
int node = q.poll();
for (int neighbor : neighborsForNode.get(node)) {
if (!subgraph.contains(neighbor)) {
subgraph.add(neighbor);
q.add(neighbor);
}
}
}
return subgraph;
}
public void addNode(OSMNode node) {
if (_nodes.containsKey(node.getId()))
return;
_nodes.put(node.getId(), node);
if (_nodes.size() % 1000 == 0)
_log.debug("nodes=" + _nodes.size());
}
public void addWay(OSMWay way) {
if (_ways.containsKey(way.getId()))
return;
if (!(way.getTags().containsKey("highway") || "platform".equals(way.getTags().get(
"railway")))) {
return;
}
_ways.put(way.getId(), way);
if (_ways.size() % 1000 == 0)
_log.debug("ways=" + _ways.size());
}
public void addRelation(OSMRelation relation) {
}
private String getVertexIdForNodeId(int nodeId) {
return "osm node " + nodeId;
}
private Street getEdgeForStreet(Vertex from, Vertex to, OSMWay way, double d,
StreetTraversalPermission permissions) {
String id = "way " + way.getId();
id = unique(id);
String name = way.getTags().get("name");
if (name == null) {
name = id;
}
Street street = new Street(from, to, id, name, d, permissions);
Coordinate[] coordinates = { from.getCoordinate(), to.getCoordinate() };
Float sequence = new PackedCoordinateSequence.Float(coordinates, 2);
LineString lineString = _geometryFactory.createLineString(sequence);
street.setGeometry(lineString);
return street;
}
private StreetTraversalPermission getPermissionsForWay(OSMWay way) {
// TODO : Better mapping between OSM tags and travel permissions
Map<String, String> tags = way.getTags();
String value = tags.get("highway");
if (value == null || value.equals("motorway") || value.equals("motorway_link"))
return StreetTraversalPermission.CAR_ONLY;
if ("platform".equals(way.getTags().get("railway"))) {
return StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY;
}
return StreetTraversalPermission.ALL;
}
}
}
| false | true | public void buildGraph(Graph graph) {
// We want to prune nodes that don't have any edges
Set<Integer> nodesWithNeighbors = new HashSet<Integer>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
if (nodes.size() > 1)
nodesWithNeighbors.addAll(nodes);
}
// Remove all simple islands
_nodes.keySet().retainAll(nodesWithNeighbors);
pruneFloatingIslands();
HashMap<Coordinate, ArrayList<Edge>> edgesByLocation = new HashMap<Coordinate, ArrayList<Edge>>();
int wayIndex = 0;
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
StreetTraversalPermission permissions = getPermissionsForWay(way);
List<Integer> nodes = way.getNodeRefs();
for (int i = 0; i < nodes.size() - 1; i++) {
Integer startNode = nodes.get(i);
String vFromId = getVertexIdForNodeId(startNode) + "_" + i + "_" + way.getId();
Integer endNode = nodes.get(i + 1);
String vToId = getVertexIdForNodeId(endNode) + "_" + i + "_" + way.getId();
OSMNode osmStartNode = _nodes.get(startNode);
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
Vertex from = addVertex(graph, vFromId, osmStartNode);
Vertex to = addVertex(graph, vToId, osmEndNode);
double d = from.distance(to);
Street street = getEdgeForStreet(from, to, way, d, permissions);
graph.addEdge(street);
Street backStreet = getEdgeForStreet(to, from, way, d, permissions);
graph.addEdge(backStreet);
ArrayList<Edge> startEdges = edgesByLocation.get(from.getCoordinate());
if (startEdges == null) {
startEdges = new ArrayList<Edge>();
edgesByLocation.put(from.getCoordinate(), startEdges);
}
startEdges.add(street);
ArrayList<Edge> endEdges = edgesByLocation.get(to.getCoordinate());
if (endEdges == null) {
endEdges = new ArrayList<Edge>();
edgesByLocation.put(to.getCoordinate(), endEdges);
}
endEdges.add(backStreet);
}
}
// add turns
for (ArrayList<Edge> edges : edgesByLocation.values()) {
for (Edge in : edges) {
Vertex tov = in.getToVertex();
Coordinate c = tov.getCoordinate();
ArrayList<Edge> outEdges = edgesByLocation.get(c);
if (outEdges != null) {
/* If this is not an intersection or street name change, unify the vertices */
if (outEdges.size() == 2) {
for (Edge out : outEdges) {
Vertex fromVertex = out.getFromVertex();
if (tov != fromVertex && out.getName() == in.getName()) {
Intersection v = (Intersection) tov;
v.mergeFrom(graph, (Intersection) fromVertex);
graph.removeVertex(fromVertex);
break;
}
}
} else {
for (Edge out : outEdges) {
/*
* Only create a turn edge if: (a) the edge is not the one we are
* coming from (b) the edge is a Street (c) the edge is an outgoing
* edge from this location
*/
if (tov != out.getFromVertex() && out instanceof Street
&& out.getFromVertex().getCoordinate().equals(c)) {
graph.addEdge(new Turn(in, out));
}
}
}
}
}
}
}
| public void buildGraph(Graph graph) {
// We want to prune nodes that don't have any edges
Set<Integer> nodesWithNeighbors = new HashSet<Integer>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
if (nodes.size() > 1)
nodesWithNeighbors.addAll(nodes);
}
// Remove all simple islands
_nodes.keySet().retainAll(nodesWithNeighbors);
pruneFloatingIslands();
HashMap<Coordinate, ArrayList<Edge>> edgesByLocation = new HashMap<Coordinate, ArrayList<Edge>>();
int wayIndex = 0;
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
StreetTraversalPermission permissions = getPermissionsForWay(way);
List<Integer> nodes = way.getNodeRefs();
for (int i = 0; i < nodes.size() - 1; i++) {
Integer startNode = nodes.get(i);
String vFromId = getVertexIdForNodeId(startNode) + "_" + i + "_" + way.getId();
Integer endNode = nodes.get(i + 1);
String vToId = getVertexIdForNodeId(endNode) + "_" + i + "_" + way.getId();
OSMNode osmStartNode = _nodes.get(startNode);
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
Vertex from = addVertex(graph, vFromId, osmStartNode);
Vertex to = addVertex(graph, vToId, osmEndNode);
double d = from.distance(to);
Street street = getEdgeForStreet(from, to, way, d, permissions);
graph.addEdge(street);
Street backStreet = getEdgeForStreet(to, from, way, d, permissions);
graph.addEdge(backStreet);
ArrayList<Edge> startEdges = edgesByLocation.get(from.getCoordinate());
if (startEdges == null) {
startEdges = new ArrayList<Edge>();
edgesByLocation.put(from.getCoordinate(), startEdges);
}
startEdges.add(street);
ArrayList<Edge> endEdges = edgesByLocation.get(to.getCoordinate());
if (endEdges == null) {
endEdges = new ArrayList<Edge>();
edgesByLocation.put(to.getCoordinate(), endEdges);
}
endEdges.add(backStreet);
}
}
// add turns
for (ArrayList<Edge> edges : edgesByLocation.values()) {
for (Edge in : edges) {
Vertex tov = in.getToVertex();
Coordinate c = tov.getCoordinate();
ArrayList<Edge> outEdges = edgesByLocation.get(c);
if (outEdges != null) {
/* If this is not an intersection or street name change, unify the vertices */
boolean unified = false;
if (outEdges.size() == 2) {
for (Edge out : outEdges) {
Vertex fromVertex = out.getFromVertex();
if (tov != fromVertex && out.getName() == in.getName()) {
Intersection v = (Intersection) tov;
v.mergeFrom(graph, (Intersection) fromVertex);
graph.removeVertex(fromVertex);
unified = true;
break;
}
}
}
if (!unified) {
for (Edge out : outEdges) {
/*
* Only create a turn edge if: (a) the edge is not the one we are
* coming from (b) the edge is a Street (c) the edge is an outgoing
* edge from this location
*/
if (tov != out.getFromVertex() && out instanceof Street
&& out.getFromVertex().getCoordinate().equals(c)) {
graph.addEdge(new Turn(in, out));
}
}
}
}
}
}
}
|
diff --git a/tz-commons/tz-commons-auth/src/main/java/com/thruzero/auth/realm/TzAuthorizingRealm.java b/tz-commons/tz-commons-auth/src/main/java/com/thruzero/auth/realm/TzAuthorizingRealm.java
index 416d7c0..006ec9b 100644
--- a/tz-commons/tz-commons-auth/src/main/java/com/thruzero/auth/realm/TzAuthorizingRealm.java
+++ b/tz-commons/tz-commons-auth/src/main/java/com/thruzero/auth/realm/TzAuthorizingRealm.java
@@ -1,114 +1,116 @@
/*
* Copyright 2012 George Norman
*
* 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.thruzero.auth.realm;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.thruzero.auth.exception.MessageIdAuthenticationException;
import com.thruzero.auth.model.User;
import com.thruzero.auth.model.UserPermission;
import com.thruzero.auth.service.UserService;
import com.thruzero.auth.utils.AuthenticationUtils;
import com.thruzero.common.core.locator.ServiceLocator;
/**
* Specialization of the Shiro AuthorizingRealm, that uses the tz-commons UserService to
* load User and UserPermission objects for authentication and authorization.
*
* @author George Norman
*/
public class TzAuthorizingRealm extends AuthorizingRealm {
private static final Logger logger = Logger.getLogger(TzAuthorizingRealm.class);
public static final String LOGIN_TOO_MANY_BAD_LOGIN_ATTEMPTS_ERROR = "login.tooManyBadLoginAttempts.error";
public static final String LOGIN_INVALID_LOGIN_ERROR = "login.invalidLogin.error";
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
User user = (User)principals.getPrimaryPrincipal();
for (UserPermission permission : user.getPermissions()) {
result.addObjectPermission(new WildcardPermission(permission.getDomain() + ":" + permission.getActions()));
}
return result;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
try {
AuthenticationInfo result;
String submittedLoginId = token.getPrincipal().toString();
char[] submittedOneTimePw = (char[])token.getCredentials();
String nonce = null;
if (token instanceof UsernamePasswordToken) { // TODO-p1(george) ugh - requires typecast to retrieve nonce
nonce = ((UsernamePasswordToken)token).getHost(); // TODO-p1(george) ugh - using host as nonce; maybe should create a new subclass (e.g., TzUsernamePasswordToken)
}
UserService userService = ServiceLocator.locate(UserService.class);
User user = userService.getUserByLoginId(submittedLoginId);
if (AuthenticationUtils.isTooManyBadLoginAttempts(user)) {
throw new MessageIdAuthenticationException(LOGIN_TOO_MANY_BAD_LOGIN_ATTEMPTS_ERROR);
}
if (AuthenticationUtils.isValidLogin(user, submittedLoginId, submittedOneTimePw, nonce)) {
Set<String> roleNames = new HashSet<String>();
Set<Permission> permissions = new HashSet<Permission>();
for (UserPermission permission : user.getPermissions()) {
permissions.add(new WildcardPermission(permission.getDomain() + ":" + permission.getActions()));
}
result = new SimpleAccount(user, token.getCredentials(), TzAuthorizingRealm.class.getSimpleName(), roleNames, permissions);
AuthenticationUtils.resetBadLoginAttemptTracker(user);
userService.saveUser(user);
} else {
- AuthenticationUtils.handleBadLoginAttempt(user); // update bad login attempts or reset if time threshold has been exceeded
- userService.saveUser(user);
+ if (user != null) {
+ AuthenticationUtils.handleBadLoginAttempt(user); // update bad login attempts or reset if time threshold has been exceeded
+ userService.saveUser(user);
+ }
throw new MessageIdAuthenticationException(LOGIN_INVALID_LOGIN_ERROR);
}
return result;
} catch (MessageIdAuthenticationException e) {
String err = "ERROR: failed to get authentication info.";
logger.error(err, e);
throw e; // rethrow, so it'll get caught and handled upstream
} catch (Exception e) {
String err = "ERROR: failed to get authentication info.";
logger.error(err, e);
throw new RuntimeException(err, e); // Something is seriously wrong; bail
}
}
}
| true | true | protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
try {
AuthenticationInfo result;
String submittedLoginId = token.getPrincipal().toString();
char[] submittedOneTimePw = (char[])token.getCredentials();
String nonce = null;
if (token instanceof UsernamePasswordToken) { // TODO-p1(george) ugh - requires typecast to retrieve nonce
nonce = ((UsernamePasswordToken)token).getHost(); // TODO-p1(george) ugh - using host as nonce; maybe should create a new subclass (e.g., TzUsernamePasswordToken)
}
UserService userService = ServiceLocator.locate(UserService.class);
User user = userService.getUserByLoginId(submittedLoginId);
if (AuthenticationUtils.isTooManyBadLoginAttempts(user)) {
throw new MessageIdAuthenticationException(LOGIN_TOO_MANY_BAD_LOGIN_ATTEMPTS_ERROR);
}
if (AuthenticationUtils.isValidLogin(user, submittedLoginId, submittedOneTimePw, nonce)) {
Set<String> roleNames = new HashSet<String>();
Set<Permission> permissions = new HashSet<Permission>();
for (UserPermission permission : user.getPermissions()) {
permissions.add(new WildcardPermission(permission.getDomain() + ":" + permission.getActions()));
}
result = new SimpleAccount(user, token.getCredentials(), TzAuthorizingRealm.class.getSimpleName(), roleNames, permissions);
AuthenticationUtils.resetBadLoginAttemptTracker(user);
userService.saveUser(user);
} else {
AuthenticationUtils.handleBadLoginAttempt(user); // update bad login attempts or reset if time threshold has been exceeded
userService.saveUser(user);
throw new MessageIdAuthenticationException(LOGIN_INVALID_LOGIN_ERROR);
}
return result;
} catch (MessageIdAuthenticationException e) {
String err = "ERROR: failed to get authentication info.";
logger.error(err, e);
throw e; // rethrow, so it'll get caught and handled upstream
} catch (Exception e) {
String err = "ERROR: failed to get authentication info.";
logger.error(err, e);
throw new RuntimeException(err, e); // Something is seriously wrong; bail
}
}
| protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
try {
AuthenticationInfo result;
String submittedLoginId = token.getPrincipal().toString();
char[] submittedOneTimePw = (char[])token.getCredentials();
String nonce = null;
if (token instanceof UsernamePasswordToken) { // TODO-p1(george) ugh - requires typecast to retrieve nonce
nonce = ((UsernamePasswordToken)token).getHost(); // TODO-p1(george) ugh - using host as nonce; maybe should create a new subclass (e.g., TzUsernamePasswordToken)
}
UserService userService = ServiceLocator.locate(UserService.class);
User user = userService.getUserByLoginId(submittedLoginId);
if (AuthenticationUtils.isTooManyBadLoginAttempts(user)) {
throw new MessageIdAuthenticationException(LOGIN_TOO_MANY_BAD_LOGIN_ATTEMPTS_ERROR);
}
if (AuthenticationUtils.isValidLogin(user, submittedLoginId, submittedOneTimePw, nonce)) {
Set<String> roleNames = new HashSet<String>();
Set<Permission> permissions = new HashSet<Permission>();
for (UserPermission permission : user.getPermissions()) {
permissions.add(new WildcardPermission(permission.getDomain() + ":" + permission.getActions()));
}
result = new SimpleAccount(user, token.getCredentials(), TzAuthorizingRealm.class.getSimpleName(), roleNames, permissions);
AuthenticationUtils.resetBadLoginAttemptTracker(user);
userService.saveUser(user);
} else {
if (user != null) {
AuthenticationUtils.handleBadLoginAttempt(user); // update bad login attempts or reset if time threshold has been exceeded
userService.saveUser(user);
}
throw new MessageIdAuthenticationException(LOGIN_INVALID_LOGIN_ERROR);
}
return result;
} catch (MessageIdAuthenticationException e) {
String err = "ERROR: failed to get authentication info.";
logger.error(err, e);
throw e; // rethrow, so it'll get caught and handled upstream
} catch (Exception e) {
String err = "ERROR: failed to get authentication info.";
logger.error(err, e);
throw new RuntimeException(err, e); // Something is seriously wrong; bail
}
}
|
diff --git a/srcj/com/sun/electric/tool/io/output/Spice.java b/srcj/com/sun/electric/tool/io/output/Spice.java
index 4affcd7c1..0c0e467ae 100755
--- a/srcj/com/sun/electric/tool/io/output/Spice.java
+++ b/srcj/com/sun/electric/tool/io/output/Spice.java
@@ -1,3314 +1,3314 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Spice.java
* Original C Code written by Steven M. Rubin and Sid Penstone
* Translated to Java by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.output;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.HierarchyEnumerator;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.network.Global;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.TransistorSize;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.generator.sclibrary.SCLibraryGen;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.input.spicenetlist.SpiceNetlistReader;
import com.sun.electric.tool.io.input.spicenetlist.SpiceSubckt;
import com.sun.electric.tool.logicaleffort.LENetlister;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations.NamePattern;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.Exec;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.ExecDialog;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import java.awt.geom.AffineTransform;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* This is the Simulation Interface tool.
*/
public class Spice extends Topology
{
/** key of Variable holding generic Spice templates. */ public static final Variable.Key SPICE_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template");
/** key of Variable holding Spice 2 templates. */ public static final Variable.Key SPICE_2_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice2");
/** key of Variable holding Spice 3 templates. */ public static final Variable.Key SPICE_3_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice3");
/** key of Variable holding HSpice templates. */ public static final Variable.Key SPICE_H_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_hspice");
/** key of Variable holding PSpice templates. */ public static final Variable.Key SPICE_P_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_pspice");
/** key of Variable holding GnuCap templates. */ public static final Variable.Key SPICE_GC_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_gnucap");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_SM_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_smartspice");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_A_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_assura");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_C_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_calibre");
/** key of Variable holding SPICE code. */ public static final Variable.Key SPICE_CARD_KEY = Variable.newKey("SIM_spice_card");
/** key of Variable holding SPICE declaration. */ public static final Variable.Key SPICE_DECLARATION_KEY = Variable.newKey("SIM_spice_declaration");
/** key of Variable holding SPICE model. */ public static final Variable.Key SPICE_MODEL_KEY = Variable.newKey("SIM_spice_model");
/** key of Variable holding SPICE flat code. */ public static final Variable.Key SPICE_CODE_FLAT_KEY = Variable.newKey("SIM_spice_code_flat");
/** key of wire capacitance. */ public static final Variable.Key ATTR_C = Variable.newKey("ATTR_C");
/** key of wire resistance. */ public static final Variable.Key ATTR_R = Variable.newKey("ATTR_R");
/** Prefix for spice extension. */ public static final String SPICE_EXTENSION_PREFIX = "Extension ";
/** key of Variable holding generic CDL templates. */ public static final Variable.Key CDL_TEMPLATE_KEY = Variable.newKey("ATTR_CDL_template");
/** maximum subcircuit name length */ private static final int SPICEMAXLENSUBCKTNAME = 70;
/** maximum subcircuit name length */ private static final int CDLMAXLENSUBCKTNAME = 40;
/** maximum subcircuit name length */ private static final int SPICEMAXLENLINE = 78;
/** legal characters in a spice deck */ private static final String SPICELEGALCHARS = "!#$%*+-/<>[]_@";
/** legal characters in a spice deck */ private static final String PSPICELEGALCHARS = "!#$%*+-/<>[]_";
/** legal characters in a CDL deck */ private static final String CDLNOBRACKETLEGALCHARS = "!#$%*+-/<>_";
/** if CDL writes out empty subckt definitions */ private static final boolean CDLWRITESEMPTYSUBCKTS = false;
/** if use spice globals */ private static final boolean USE_GLOBALS = true;
/** default Technology to use. */ private Technology layoutTechnology;
/** Mask shrink factor (default =1) */ private double maskScale;
/** True to write CDL format */ private boolean useCDL;
/** Legal characters */ private String legalSpiceChars;
/** Template Key for current spice engine */ private Variable.Key preferedEngineTemplateKey;
/** Special case for HSpice for Assura */ private boolean assuraHSpice = false;
/** Spice type: 2, 3, H, P, etc */ private Simulation.SpiceEngine spiceEngine;
/** those cells that have overridden models */ private HashMap<Cell,String> modelOverrides = new HashMap<Cell,String>();
/** List of segmented nets and parasitics */ private List<SegmentedNets> segmentedParasiticInfo = new ArrayList<SegmentedNets>();
/** Networks exempted during parasitic ext */ private ExemptedNets exemptedNets;
/** Whether or not to write empty subckts */ private boolean writeEmptySubckts = true;
/** max length per line */ private int spiceMaxLenLine = SPICEMAXLENLINE;
/** Flat measurements file */ private FlatSpiceCodeVisitor spiceCodeFlat = null;
/** map of "parameterized" cells that are not covered by Topology */ private Map<Cell,Cell> uniquifyCells;
/** uniqueID */ private int uniqueID;
/** map of shortened instance names */ private Map<String,Integer> uniqueNames;
private static final boolean useNewParasitics = true;
private static class SpiceNet
{
/** network object associated with this */ Network network;
/** merged geometry for this network */ PolyMerge merge;
/** area of diffusion */ double diffArea;
/** perimeter of diffusion */ double diffPerim;
/** amount of capacitance in non-diff */ float nonDiffCapacitance;
/** number of transistors on the net */ int transistorCount;
}
private static class SpiceFinishedListener implements Exec.FinishedListener {
private Cell cell;
private FileType type;
private String file;
private SpiceFinishedListener(Cell cell, FileType type, String file) {
this.cell = cell;
this.type = type;
this.file = file;
}
public void processFinished(Exec.FinishedEvent e) {
URL fileURL = TextUtils.makeURLToFile(file);
// create a new waveform window
WaveformWindow ww = WaveformWindow.findWaveformWindow(cell);
Simulate.plotSimulationResults(type, cell, fileURL, ww);
}
}
/**
* The main entry point for Spice deck writing.
* @param cell the top-level cell to write.
* @param context the hierarchical context to the cell.
* @param filePath the disk file to create.
* @param cdl true if this is CDL output (false for Spice).
*/
public static void writeSpiceFile(Cell cell, VarContext context, String filePath, boolean cdl)
{
Spice out = new Spice();
out.useCDL = cdl;
if (out.openTextOutputStream(filePath)) return;
if (out.writeCell(cell, context)) return;
if (out.closeTextOutputStream()) return;
System.out.println(filePath + " written");
// write CDL support file if requested
if (out.useCDL)
{
// write the control files
String deckFile = filePath;
String deckPath = "";
int lastDirSep = deckFile.lastIndexOf(File.separatorChar);
if (lastDirSep > 0)
{
deckPath = deckFile.substring(0, lastDirSep);
deckFile = deckFile.substring(lastDirSep+1);
}
String templateFile = deckPath + File.separator + cell.getName() + ".cdltemplate";
if (out.openTextOutputStream(templateFile)) return;
String libName = Simulation.getCDLLibName();
String libPath = Simulation.getCDLLibPath();
out.printWriter.print("cdlInKeys = list(nil\n");
out.printWriter.print(" 'searchPath \"" + deckFile + "");
if (libPath.length() > 0)
out.printWriter.print("\n " + libPath);
out.printWriter.print("\"\n");
out.printWriter.print(" 'cdlFile \"" + deckPath + File.separator + deckFile + "\"\n");
out.printWriter.print(" 'userSkillFile \"\"\n");
out.printWriter.print(" 'opusLib \"" + libName + "\"\n");
out.printWriter.print(" 'primaryCell \"" + cell.getName() + "\"\n");
out.printWriter.print(" 'caseSensitivity \"lower\"\n");
out.printWriter.print(" 'hierarchy \"flatten\"\n");
out.printWriter.print(" 'cellTable \"\"\n");
out.printWriter.print(" 'viewName \"netlist\"\n");
out.printWriter.print(" 'viewType \"\"\n");
out.printWriter.print(" 'pr nil\n");
out.printWriter.print(" 'skipDevice nil\n");
out.printWriter.print(" 'schemaLib \"sample\"\n");
out.printWriter.print(" 'refLib \"\"\n");
out.printWriter.print(" 'globalNodeExpand \"full\"\n");
out.printWriter.print(")\n");
if (out.closeTextOutputStream()) return;
System.out.println(templateFile + " written");
// ttyputmsg(x_("Now type: exec nino CDLIN %s &"), templatefile);
}
String runSpice = Simulation.getSpiceRunChoice();
if (!runSpice.equals(Simulation.spiceRunChoiceDontRun)) {
String command = Simulation.getSpiceRunProgram() + " " + Simulation.getSpiceRunProgramArgs();
// see if user specified custom dir to run process in
String workdir = User.getWorkingDirectory();
String rundir = workdir;
if (Simulation.getSpiceUseRunDir()) {
rundir = Simulation.getSpiceRunDir();
}
File dir = new File(rundir);
int start = filePath.lastIndexOf(File.separator);
if (start == -1) start = 0; else {
start++;
if (start > filePath.length()) start = filePath.length();
}
int end = filePath.lastIndexOf(".");
if (end == -1) end = filePath.length();
String filename_noext = filePath.substring(start, end);
String filename = filePath.substring(start, filePath.length());
// replace vars in command and args
command = command.replaceAll("\\$\\{WORKING_DIR}", workdir);
command = command.replaceAll("\\$\\{USE_DIR}", rundir);
command = command.replaceAll("\\$\\{FILENAME}", filename);
command = command.replaceAll("\\$\\{FILENAME_NO_EXT}", filename_noext);
// set up run probe
FileType type = Simulate.getCurrentSpiceOutputType();
String [] extensions = type.getExtensions();
String outFile = rundir + File.separator + filename_noext + "." + extensions[0];
Exec.FinishedListener l = new SpiceFinishedListener(cell, type, outFile);
if (runSpice.equals(Simulation.spiceRunChoiceRunIgnoreOutput)) {
Exec e = new Exec(command, null, dir, null, null);
if (Simulation.getSpiceRunProbe()) e.addFinishedListener(l);
e.start();
}
if (runSpice.equals(Simulation.spiceRunChoiceRunReportOutput)) {
ExecDialog dialog = new ExecDialog(TopLevel.getCurrentJFrame(), false);
if (Simulation.getSpiceRunProbe()) dialog.addFinishedListener(l);
dialog.startProcess(command, null, dir);
}
System.out.println("Running spice command: "+command);
}
if (Simulation.isParasiticsBackAnnotateLayout() && Simulation.isSpiceUseParasitics()) {
out.backAnnotateLayout();
}
// // run spice (if requested)
// var = getvalkey((INTBIG)sim_tool, VTOOL, VINTEGER, sim_dontrunkey);
// if (var != NOVARIABLE && var->addr != SIMRUNNO)
// {
// ttyputmsg(_("Running SPICE..."));
// var = getvalkey((INTBIG)sim_tool, VTOOL, VSTRING, sim_spice_listingfilekey);
// if (var == NOVARIABLE) sim_spice_execute(deckfile, x_(""), np); else
// sim_spice_execute(deckfile, (CHAR *)var->addr, np);
// }
}
/**
* Creates a new instance of Spice
*/
Spice()
{
}
protected void start()
{
// find the proper technology to use if this is schematics
if (topCell.getTechnology().isLayout())
layoutTechnology = topCell.getTechnology();
else
layoutTechnology = Schematics.getDefaultSchematicTechnology();
// make sure key is cached
spiceEngine = Simulation.getSpiceEngine();
preferedEngineTemplateKey = SPICE_TEMPLATE_KEY;
assuraHSpice = false;
switch (spiceEngine)
{
case SPICE_ENGINE_2: preferedEngineTemplateKey = SPICE_2_TEMPLATE_KEY; break;
case SPICE_ENGINE_3: preferedEngineTemplateKey = SPICE_3_TEMPLATE_KEY; break;
case SPICE_ENGINE_H: preferedEngineTemplateKey = SPICE_H_TEMPLATE_KEY; break;
case SPICE_ENGINE_P: preferedEngineTemplateKey = SPICE_P_TEMPLATE_KEY; break;
case SPICE_ENGINE_G: preferedEngineTemplateKey = SPICE_GC_TEMPLATE_KEY; break;
case SPICE_ENGINE_S: preferedEngineTemplateKey = SPICE_SM_TEMPLATE_KEY; break;
case SPICE_ENGINE_H_ASSURA: preferedEngineTemplateKey = SPICE_A_TEMPLATE_KEY; assuraHSpice = true; break;
case SPICE_ENGINE_H_CALIBRE: preferedEngineTemplateKey = SPICE_C_TEMPLATE_KEY; assuraHSpice = true; break;
}
if (assuraHSpice || (useCDL && !CDLWRITESEMPTYSUBCKTS) ||
(!useCDL && !Simulation.isSpiceWriteEmtpySubckts())) {
writeEmptySubckts = false;
}
// get the mask scale
maskScale = 1.0;
// Variable scaleVar = layoutTechnology.getVar("SIM_spice_mask_scale");
// if (scaleVar != null) maskScale = TextUtils.atof(scaleVar.getObject().toString());
// set up the parameterized cells
uniquifyCells = new HashMap<Cell,Cell>();
uniqueID = 0;
uniqueNames = new HashMap<String,Integer>();
checkIfParameterized(topCell);
// setup the legal characters
legalSpiceChars = SPICELEGALCHARS;
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) legalSpiceChars = PSPICELEGALCHARS;
// start writing the spice deck
if (useCDL)
{
// setup bracket conversion for CDL
if (Simulation.isCDLConvertBrackets())
legalSpiceChars = CDLNOBRACKETLEGALCHARS;
multiLinePrint(true, "* First line is ignored\n");
// see if include file specified
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
String filePart = Simulation.getCDLIncludeFile();
if (!filePart.equals("")) {
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Primitives described in this file:\n");
addIncludeFile(filePart);
} else {
System.out.println("Warning: CDL Include file not found: "+fileName);
}
}
} else
{
writeHeader(topCell);
spiceCodeFlat = new FlatSpiceCodeVisitor(filePath+".flatcode", this);
HierarchyEnumerator.enumerateCell(topCell, VarContext.globalContext, spiceCodeFlat, true);
spiceCodeFlat.close();
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
exemptedNets = new ExemptedNets(new File(headerPath + File.separator + "exemptedNets.txt"));
}
// gather all global signal names
/*
if (USE_GLOBALS)
{
Netlist netList = getNetlistForCell(topCell);
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
*/
}
protected void done()
{
if (!useCDL)
{
writeTrailer(topCell);
if (Simulation.isSpiceWriteFinalDotEnd())
multiLinePrint(false, ".END\n");
}
}
/**
* To write M factor information into given string buffer
* @param no Nodable representing the node
* @param infstr Buffer where to write to
*/
private void writeMFactor(VarContext context, Nodable no, StringBuffer infstr)
{
Variable mVar = no.getVar(Simulation.M_FACTOR_KEY);
if (mVar == null) return;
Object value = context.evalVar(mVar);
// check for M=@M, and warn user that this is a bad idea, and we will not write it out
if (mVar.getObject().toString().equals("@M") || (mVar.getObject().toString().equals("P(\"M\")"))) {
System.out.println("Warning: M=@M [eval="+value+"] on "+no.getName()+" is a bad idea, not writing it out: "+context.push(no).getInstPath("."));
return;
}
infstr.append(" M=" + formatParam(value.toString()));
}
/** Called at the end of the enter cell phase of hierarchy enumeration */
protected void enterCell(HierarchyEnumerator.CellInfo info) {
if (exemptedNets != null)
exemptedNets.setExemptedNets(info);
}
private Variable getEngineTemplate(Cell cell)
{
Variable varTemplate = null;
varTemplate = cell.getVar(preferedEngineTemplateKey);
if (!assuraHSpice) // null in case of NO_TEMPLATE_KEY
{
if (varTemplate == null)
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
}
return varTemplate;
}
/**
* Method to write cellGeom
*/
protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell && USE_GLOBALS) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics) {
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
boolean ignoreArc = false;
// figure out res and cap, see if we should ignore it
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
ignoreArc = true;
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaBaseWidth() * scale / 1000; // width in microns
// double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
double cap = 0;
double res = 0;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() > 0.0) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
res = length/width * layer.getResistance();
}
}
// add res if big enough
if (res <= cell.getTechnology().getMinResistance()) {
ignoreArc = true;
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
Network net = netList.getNetwork(ai, 0);
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
ignoreArc = true;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net)) && ignoreArc == false) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
}
} else {
ignoreArc = true;
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
if (ignoreArc)
arcPImodels = 1; // split cap to two pins if ignoring arc
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (ignoreArc) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = null;
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext();) {
PortInst p2 = pit.next();
if (p2 != gate0 && netList.getNetwork(gate0) == netList.getNetwork(p2))
gate1 = p2;
}
if (gate1 != null) {
segmentedNets.shortSegments(gate0, gate1);
}
}
} else {
//System.out.println("Shorting shorted exports");
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// // use ground net for substrate
// if (subnet == NOSPNET && sim_spice_gnd != NONETWORK)
// subnet = (SPNET *)sim_spice_gnd->temp1;
// if (bipolarTrans != 0 && subnet == NOSPNET)
// {
// infstr = initinfstr();
// formatinfstr(infstr, _("WARNING: no explicit connection to the substrate in cell %s"),
// describenodeproto(np));
// dumpErrorMessage(infstr);
// if (sim_spice_gnd != NONETWORK)
// {
// ttyputmsg(_(" A connection to ground will be used if necessary."));
// subnet = (SPNET *)sim_spice_gnd->temp1;
// }
// }
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (cs.isGlobal()) {
System.out.println("Warning: Explicit Global signal "+cs.getName()+" exported in "+cell.describe(false));
}
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
infstr.append(" " + cs.getName());
}
}
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
// write exports to this cell
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) continue;
if (cs.isGlobal()) continue;
//multiLinePrint(true, "** PORT " + cs.getName() + "\n");
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
if (useCDL)
{
varTemplate = subCell.getVar(CDL_TEMPLATE_KEY);
} else
{
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
}
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
// ignore networks that aren't exported
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (USE_GLOBALS)
{
if (pp == null) continue;
if (subCS.isGlobal() && subCS.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(subCS)) continue;
}
net = netList.getNetwork(no, pp, exportIndex);
} else
{
if (pp == null && !subCS.isGlobal()) continue;
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal()) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
Global.Set globals = subCni.getNetList().getGlobals();
int globalSize = globals.size();
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
infstr.append(" " + global.getName());
}
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj));
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
PrimitiveNode.Function fun = ni.getFunction();
// handle resistors, inductors, capacitors, and diodes
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor()) // == PrimitiveNode.Function.RESIST)
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
extra = " L='"+length+"*LAMBDA' W='"+width+"*LAMBDA'";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor()) // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC)
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth()));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
- infstr.append(" AREA=" + TextUtils.formatDouble(l*w, 2));
+ infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth()));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics) {
int capCount = 0;
int resCount = 0;
// write caps
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+TextUtils.formatDouble(segCap)+"fF\n");
capCount++;
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else {
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
// int i=0;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
// i++;
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
private void emitEmbeddedSpice(Variable cardVar, VarContext context, SegmentedNets segmentedNets, HierarchyEnumerator.CellInfo info, boolean flatNetNames)
{
Object obj = cardVar.getObject();
if (!(obj instanceof String) && !(obj instanceof String[])) return;
if (!cardVar.isDisplay()) return;
if (obj instanceof String)
{
StringBuffer buf = replacePortsAndVars((String)obj, context.getNodable(), context.pop(), null, segmentedNets, info, flatNetNames);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
} else
{
String [] strings = (String [])obj;
for(int i=0; i<strings.length; i++)
{
StringBuffer buf = replacePortsAndVars(strings[i], context.getNodable(), context.pop(), null, segmentedNets, info, flatNetNames);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
}
}
}
/**
* Check if the specified cell is parameterized. Note that this
* recursively checks all cells below this cell as well, and marks
* all cells that contain LE gates, or whose subcells contain LE gates,
* as parameterized.
* @return true if cell has been marked as parameterized
*/
private boolean checkIfParameterized(Cell cell) {
//System.out.println("Checking Cell "+cell.describe());
boolean mark = false;
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
if (!ni.isCellInstance()) continue;
if (ni.isIconOfParent()) continue;
if (ni.getVar(LENetlister.ATTR_LEGATE) != null) {
// make sure cell also has that var
Cell np = (Cell)ni.getProto();
if (np.contentsView() != null) np = np.contentsView();
if (np.getVar(LENetlister.ATTR_LEGATE) != null)
mark = true; continue;
}
if (ni.getVar(LENetlister.ATTR_LEKEEPER) != null) {
// make sure cell also has that var
Cell np = (Cell)ni.getProto();
if (np.contentsView() != null) np = np.contentsView();
if (np.getVar(LENetlister.ATTR_LEKEEPER) != null)
mark = true; continue;
}
Cell proto = ((Cell)ni.getProto()).contentsView();
if (proto == null) proto = (Cell)ni.getProto();
if (checkIfParameterized(proto)) { mark = true; }
}
if (mark)
uniquifyCells.put(cell, cell);
//System.out.println("---> "+cell.describe()+" is marked "+mark);
return mark;
}
/*
* Method to create a parameterized name for node instance "ni".
* If the node is not parameterized, returns zero.
* If it returns a name, that name must be deallocated when done.
*/
protected String parameterizedName(Nodable no, VarContext context)
{
Cell cell = (Cell)no.getProto();
StringBuffer uniqueCellName = new StringBuffer(getUniqueCellName(cell));
if (uniquifyCells.get(cell) != null) {
// if this cell is marked to be make unique, make a unique name out of the var context
VarContext vc = context.push(no);
uniqueCellName.append("_"+vc.getInstPath("."));
} else {
boolean useCellParams = !useCDL && Simulation.isSpiceUseCellParameters();
if (canParameterizeNames() && no.isCellInstance() && !SCLibraryGen.isStandardCell(cell))
{
// if there are parameters, append them to this name
List<Variable> paramValues = new ArrayList<Variable>();
for(Iterator<Variable> it = no.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (!no.getNodeInst().isParam(var.getKey())) continue;
// if (!var.isParam()) continue;
Variable cellvar = cell.getVar(var.getKey());
if (useCellParams && (cellvar.getCode() == TextDescriptor.Code.SPICE)) {
continue;
}
paramValues.add(var);
}
for(Variable var : paramValues)
{
String eval = var.describe(context, no);
//Object eval = context.evalVar(var, no);
if (eval == null) continue;
//uniqueCellName += "-" + var.getTrueName() + "-" + eval.toString();
uniqueCellName.append("-" + eval.toString());
}
}
}
// if it is over the length limit, truncate it
int limit = maxNameLength();
if (limit > 0 && uniqueCellName.length() > limit)
{
Integer i = uniqueNames.get(uniqueCellName.toString());
if (i == null) {
i = new Integer(uniqueID);
uniqueID++;
uniqueNames.put(uniqueCellName.toString(), i);
}
uniqueCellName = uniqueCellName.delete(limit-10, uniqueCellName.length());
uniqueCellName.append("-ID"+i);
}
// make it safe
return getSafeCellName(uniqueCellName.toString());
}
/**
* Replace ports and vars in 'line'. Ports and Vars should be
* referenced via $(name)
* @param line the string to search and replace within
* @param no the nodable up the hierarchy that has the parameters on it
* @param context the context of the nodable
* @param cni the cell net info of cell in which the nodable exists (if cni is
* null, no port name replacement will be done)
* @return the modified line
*/
private StringBuffer replacePortsAndVars(String line, Nodable no, VarContext context,
CellNetInfo cni, SegmentedNets segmentedNets,
HierarchyEnumerator.CellInfo info, boolean flatNetNames) {
StringBuffer infstr = new StringBuffer();
Cell subCell = null;
if (no != null)
{
subCell = (Cell)no.getProto();
}
for(int pt = 0; pt < line.length(); pt++)
{
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
infstr.append(chr);
continue;
}
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
if (subCell != null) {
pp = subCell.findPortProto(paramName);
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && no != null)
{
String nodeName = getSafeNetName(no.getName(), false);
// nodeName = nodeName.replaceAll("[\\[\\]]", "_");
infstr.append(nodeName);
} else if (cni != null && pp != null)
{
// port name found: use its spice node
Network net = cni.getNetList().getNetwork(no, pp, 0);
CellSignal cs = cni.getCellSignal(net);
String portName = cs.getName();
if (segmentedNets.getUseParasitics()) {
PortInst pi = no.getNodeInst().findPortInstFromProto(pp);
portName = segmentedNets.getNetName(pi);
}
if (flatNetNames) {
portName = info.getUniqueNetName(net, ".");
}
infstr.append(portName);
} else if (no != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null)
{
// no port name found, look for variable name
Variable attrVar = null;
//Variable.Key varKey = Variable.findKey("ATTR_" + paramName);
if (varKey != null) {
attrVar = no.getVar(varKey);
if (attrVar == null) attrVar = no.getParameter(varKey);
}
if (attrVar == null) infstr.append("??"); else
{
String pVal = "?";
Variable parentVar = attrVar;
if (subCell != null)
parentVar = subCell.getVar(attrVar.getKey());
if (!useCDL && Simulation.isSpiceUseCellParameters() &&
parentVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(attrVar, false);
if (obj != null)
pVal = obj.toString();
} else {
pVal = String.valueOf(context.evalVar(attrVar, no));
}
if (attrVar.getCode() != TextDescriptor.Code.NONE) pVal = trimSingleQuotes(pVal);
infstr.append(pVal);
//else
// infstr.append(trimSingleQuotes(attrVar.getPureValue(-1, -1)));
}
} else {
// look for the network name
boolean found = false;
String hierName = null;
String [] names = paramName.split("\\.");
if (names.length > 1 && flatNetNames) {
// hierarchical name, down hierarchy
Netlist thisNetlist = info.getNetlist();
VarContext thisContext = context;
if (no != null) {
// push it back on, it got popped off in "embedSpice..."
thisContext = thisContext.push(no);
}
for (int i=0; i<names.length-1; i++) {
boolean foundno = false;
for (Iterator<Nodable> it = thisNetlist.getNodables(); it.hasNext(); ) {
Nodable subno = it.next();
if (subno.getName().equals(names[i])) {
if (subno.getProto() instanceof Cell) {
thisNetlist = thisNetlist.getNetlist(subno);
thisContext = thisContext.push(subno);
}
foundno = true;
continue;
}
}
if (!foundno) {
System.out.println("Unable to find "+names[i]+" in "+paramName);
break;
}
}
Network net = findNet(thisNetlist, names[names.length-1]);
if (net != null) {
HierarchyEnumerator.NetNameProxy proxy = new HierarchyEnumerator.NetNameProxy(
thisContext, ".x", net);
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
}
} else {
// net may be exported and named at higher level, use getUniqueName
Network net = findNet(info.getNetlist(), paramName);
if (net != null) {
if (flatNetNames) {
HierarchyEnumerator.NetNameProxy proxy = info.getUniqueNetNameProxy(net, ".x");
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
} else {
hierName = cni.getCellSignal(net).getName();
}
}
}
// convert to spice format
if (hierName != null) {
if (flatNetNames) {
if (hierName.indexOf(".x") > 0) {
hierName = "x"+hierName;
}
// remove x in front of net name
int i = hierName.lastIndexOf(".x");
if (i > 0)
hierName = hierName.substring(0, i+1) + hierName.substring(i+2);
else {
i = hierName.lastIndexOf("."+paramName);
if (i > 0) {
hierName = hierName.substring(0, i) + "_" + hierName.substring(i+1);
}
}
}
infstr.append(hierName);
found = true;
}
if (!found) {
System.out.println("Unable to lookup key $("+paramName+") in cell "+context.getInstPath("."));
}
}
}
return infstr;
}
private Network findNet(Netlist netlist, String netName) {
Network foundnet = null;
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(netName)) {
foundnet = net;
break;
}
}
return foundnet;
}
/**
* Get the global associated with this net. Returns null if net is
* not a global.
* @param net
* @return global associated with this net, or null if not global
*/
private Global getGlobal(Network net) {
Netlist netlist = net.getNetlist();
for (int i=0; i<netlist.getGlobals().size(); i++) {
Global g = netlist.getGlobals().get(i);
if (netlist.getNetwork(g) == net)
return g;
}
return null;
}
/**
* Check if the global cell signal is exported as with a global name,
* rather than just being a global tied to some other export.
* I.e., returns true if global "gnd" has been exported using name "gnd".
* @param cs
* @return true if global signal exported with global name
*/
private boolean isGlobalExport(CellSignal cs) {
if (!cs.isGlobal() || !cs.isExported()) return false;
for (Iterator<Export> it = cs.getNetwork().getExports(); it.hasNext(); ) {
Export ex = it.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String name = ex.getNameKey().subname(i).canonicString();
if (cs.getName().equals(name)) {
return true;
}
}
}
return false;
}
private boolean ignoreSubcktPort(CellSignal cs) {
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (USE_GLOBALS)
{
if (pp == null) return true;
if (cs.isGlobal() && !cs.getNetwork().isExported()) return true;
if (cs.isGlobal() && cs.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(cs)) return true;
}
} else
{
if (pp == null && !cs.isGlobal()) return true;
}
if (useCDL)
{
// // if this is output and the last was input (or visa-versa), insert "/"
// if (i > 0 && netlist[i-1]->temp2 != net->temp2)
// infstr.append(" /");
}
return false;
}
/**
* Class to take care of added networks in cell due to
* extracting resistance of arcs. Takes care of naming,
* addings caps at portinst locations (due to PI model end caps),
* and storing resistance of arcs.
* <P>
* A network is broken into segments at all PortInsts along the network.
* Each PortInst is given a new net segment name. These names are used
* to write out caps and resistors. Each Arc writes out a PI model
* (a cap on each end and a resistor in the middle). Sometimes, an arc
* has very little or zero resistance, or we want to ignore it. Then
* we must short two portinsts together into the same net segment.
* However, we do not discard the capacitance, but continue to add it up.
*/
private static class SegmentedNets {
private static Comparator<PortInst> PORT_INST_COMPARATOR = new Comparator<PortInst>() {
public int compare(PortInst p1, PortInst p2) {
if (p1 == p2) return 0;
int cmp = p1.getNodeInst().compareTo(p2.getNodeInst());
if (cmp != 0) return cmp;
if (p1.getPortIndex() < p2.getPortIndex()) return -1;
return 1;
}
};
private static class NetInfo implements Comparable {
private String netName = "unassigned";
private double cap = 0;
private TreeSet<PortInst> joinedPorts = new TreeSet<PortInst>(PORT_INST_COMPARATOR); // list of portInsts on this new net
/**
* Compares NetInfos by thier first PortInst.
* @param obj the other NetInfo.
* @return a comparison between the NetInfos.
*/
public int compareTo(Object obj) {
NetInfo that = (NetInfo)obj;
if (this.joinedPorts.isEmpty()) return that.joinedPorts.isEmpty() ? 0 : -1;
if (that.joinedPorts.isEmpty()) return 1;
return PORT_INST_COMPARATOR.compare(this.joinedPorts.first(), that.joinedPorts.first());
}
}
private HashMap<PortInst,NetInfo> segmentedNets; // key: portinst, obj: PortInstInfo
private HashMap<ArcInst,Double> arcRes; // key: arcinst, obj: Double (arc resistance)
boolean verboseNames = false; // true to give renamed nets verbose names
private CellNetInfo cni; // the Cell's net info
boolean useParasitics = false; // disable or enable netname remapping
private HashMap<Network,Integer> netCounters; // key: net, obj: Integer - for naming segments
private Cell cell;
private List<List<String>> shortedExports; // list of lists of export names shorted together
private HashMap<ArcInst,Double> longArcCaps; // for arcs to be broken up into multiple PI models, need to record cap
private SegmentedNets(Cell cell, boolean verboseNames, CellNetInfo cni, boolean useParasitics) {
segmentedNets = new HashMap<PortInst,NetInfo>();
arcRes = new HashMap<ArcInst,Double>();
this.verboseNames = verboseNames;
this.cni = cni;
this.useParasitics = useParasitics;
netCounters = new HashMap<Network,Integer>();
this.cell = cell;
shortedExports = new ArrayList<List<String>>();
longArcCaps = new HashMap<ArcInst,Double>();
}
// don't call this method outside of SegmentedNets
// Add a new PortInst net segment
private NetInfo putSegment(PortInst pi, double cap) {
// create new info for PortInst
NetInfo info = segmentedNets.get(pi);
if (info == null) {
info = new NetInfo();
info.netName = getNewName(pi, info);
info.cap += cap;
if (isPowerGround(pi)) info.cap = 0; // note if you remove this line,
// you have to explicity short all
// power portinsts together, or you can get duplicate caps
info.joinedPorts.add(pi);
segmentedNets.put(pi, info);
} else {
info.cap += cap;
//assert(info.joinedPorts.contains(pi)); // should already contain pi if info already exists
}
return info;
}
// don't call this method outside of SegmentedNets
// Get a new name for the net segment associated with the portinst
private String getNewName(PortInst pi, NetInfo info) {
Network net = cni.getNetList().getNetwork(pi);
CellSignal cs = cni.getCellSignal(net);
if (!useParasitics || (!Simulation.isParasiticsExtractPowerGround() &&
isPowerGround(pi))) return cs.getName();
Integer i = netCounters.get(net);
if (i == null) {
i = new Integer(0);
netCounters.put(net, i);
}
// get new name
String name = info.netName;
Export ex = pi.getExports().hasNext() ? pi.getExports().next() : null;
//if (ex != null && ex.getName().equals(cs.getName())) {
if (ex != null) {
name = ex.getName();
} else {
if (i.intValue() == 0 && !cs.isExported()) // get rid of #0 if net not exported
name = cs.getName();
else {
if (verboseNames)
name = cs.getName() + "#" + i.intValue() + pi.getNodeInst().getName() + "_" + pi.getPortProto().getName();
else
name = cs.getName() + "#" + i.intValue();
}
i = new Integer(i.intValue() + 1);
netCounters.put(net, i);
}
return name;
}
// short two net segments together by their portinsts
private void shortSegments(PortInst p1, PortInst p2) {
if (!segmentedNets.containsKey(p1))
putSegment(p1, 0);
if (!segmentedNets.containsKey(p2));
putSegment(p2, 0);
NetInfo info1 = segmentedNets.get(p1);
NetInfo info2 = segmentedNets.get(p2);
if (info1 == info2) return; // already joined
// short
//System.out.println("Shorted together "+info1.netName+ " and "+info2.netName);
info1.joinedPorts.addAll(info2.joinedPorts);
info1.cap += info2.cap;
if (TextUtils.STRING_NUMBER_ORDER.compare(info2.netName, info1.netName) < 0) {
// if (info2.netName.compareTo(info1.netName) < 0) {
info1.netName = info2.netName;
}
//info1.netName += info2.netName;
// replace info2 with info1, info2 is no longer used
// need to do for every portinst in merged segment
for (PortInst pi : info1.joinedPorts)
segmentedNets.put(pi, info1);
}
// get the segment name for the portinst.
// if no parasitics, this is just the CellSignal name.
private String getNetName(PortInst pi) {
if (!useParasitics || (isPowerGround(pi) &&
!Simulation.isParasiticsExtractPowerGround())) {
CellSignal cs = cni.getCellSignal(cni.getNetList().getNetwork(pi));
//System.out.println("CellSignal name for "+pi.getNodeInst().getName()+"."+pi.getPortProto().getName()+" is "+cs.getName());
//System.out.println("NETWORK NAMED "+cs.getName());
return cs.getName();
}
NetInfo info = segmentedNets.get(pi);
if (info == null) {
info = putSegment(pi, 0);
}
//System.out.println("NETWORK INAMED "+info.netName);
return info.netName;
}
private void addArcRes(ArcInst ai, double res) {
// short out if both conns are power/ground
if (isPowerGround(ai.getHeadPortInst()) && isPowerGround(ai.getTailPortInst()) &&
!Simulation.isParasiticsExtractPowerGround()) {
shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
return;
}
arcRes.put(ai, new Double(res));
}
private boolean isPowerGround(PortInst pi) {
Network net = cni.getNetList().getNetwork(pi);
CellSignal cs = cni.getCellSignal(net);
if (cs.isPower() || cs.isGround()) return true;
if (cs.getName().startsWith("vdd")) return true;
if (cs.getName().startsWith("gnd")) return true;
return false;
}
/**
* Return list of NetInfos for unique segments
* @return a list of al NetInfos
*/
private TreeSet<NetInfo> getUniqueSegments() {
return new TreeSet<NetInfo>(segmentedNets.values());
}
private boolean getUseParasitics() {
return useParasitics;
}
// list of export names (Strings)
private void addShortedExports(List<String> exports) {
shortedExports.add(exports);
}
// list of lists of export names (Strings)
private Iterator<List<String>> getShortedExports() { return shortedExports.iterator(); }
public static int getNumPISegments(double res, double maxSeriesResistance) {
int arcPImodels = 1;
arcPImodels = (int)(res/maxSeriesResistance); // need preference here
if ((res % maxSeriesResistance) != 0) arcPImodels++;
return arcPImodels;
}
// for arcs of larger than max series resistance, we need to break it up into
// multiple PI models. So, we need to store the cap associated with the arc
private void addArcCap(ArcInst ai, double cap) {
longArcCaps.put(ai, new Double(cap));
}
private double getArcCap(ArcInst ai) {
Double d = longArcCaps.get(ai);
return d.doubleValue();
}
}
private SegmentedNets getSegmentedNets(Cell cell) {
for (SegmentedNets seg : segmentedParasiticInfo) {
if (seg.cell == cell) return seg;
}
return null;
}
private void backAnnotateLayout()
{
Set<Cell> cellsToClear = new HashSet<Cell>();
List<PortInst> capsOnPorts = new ArrayList<PortInst>();
List<String> valsOnPorts = new ArrayList<String>();
List<ArcInst> resOnArcs = new ArrayList<ArcInst>();
List<Double> valsOnArcs = new ArrayList<Double>();
for (SegmentedNets segmentedNets : segmentedParasiticInfo)
{
Cell cell = segmentedNets.cell;
if (cell.getView() != View.LAYOUT) continue;
// gather cells to clear capacitor values
cellsToClear.add(cell);
// gather capacitor updates
for (SegmentedNets.NetInfo info : segmentedNets.getUniqueSegments())
{
PortInst pi = info.joinedPorts.iterator().next();
if (info.cap > cell.getTechnology().getMinCapacitance())
{
capsOnPorts.add(pi);
valsOnPorts.add(TextUtils.formatDouble(info.cap, 2) + "fF");
}
}
// gather resistor updates
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
resOnArcs.add(ai);
valsOnArcs.add(res);
}
}
new BackAnnotateJob(cellsToClear, capsOnPorts, valsOnPorts, resOnArcs, valsOnArcs);
}
private static class BackAnnotateJob extends Job
{
private Set<Cell> cellsToClear;
private List<PortInst> capsOnPorts;
private List<String> valsOnPorts;
private List<ArcInst> resOnArcs;
private List<Double> valsOnArcs;
private BackAnnotateJob(Set<Cell> cellsToClear, List<PortInst> capsOnPorts, List<String> valsOnPorts,
List<ArcInst> resOnArcs, List<Double> valsOnArcs)
{
super("Spice Layout Back Annotate", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.capsOnPorts = capsOnPorts;
this.valsOnPorts = valsOnPorts;
this.resOnArcs = resOnArcs;
this.valsOnArcs = valsOnArcs;
this.cellsToClear = cellsToClear;
startJob();
}
public boolean doIt() throws JobException
{
TextDescriptor ctd = TextDescriptor.getPortInstTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE);
TextDescriptor rtd = TextDescriptor.getArcTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE);
int capCount = 0;
int resCount = 0;
// clear caps on layout
for(Cell cell : cellsToClear)
{
// delete all C's already on layout
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext(); )
{
PortInst pi = pit.next();
Variable var = pi.getVar(ATTR_C);
if (var != null) pi.delVar(var.getKey());
}
}
}
// add new C's
for(int i=0; i<capsOnPorts.size(); i++)
{
PortInst pi = capsOnPorts.get(i);
String str = valsOnPorts.get(i);
pi.newVar(ATTR_C, str, ctd);
resCount++;
}
// add new R's
for(int i=0; i<resOnArcs.size(); i++)
{
ArcInst ai = resOnArcs.get(i);
Double res = valsOnArcs.get(i);
// delete R if no new one
Variable var = ai.getVar(ATTR_R);
if (res == null && var != null)
ai.delVar(ATTR_R);
// change R if new one
if (res != null)
{
ai.newVar(ATTR_R, res, rtd);
resCount++;
}
}
System.out.println("Back-annotated "+resCount+" Resistors and "+capCount+" Capacitors");
return true;
}
}
/**
* These are nets that are either extracted when nothing else is extracted,
* or not extracted during extraction. They are specified via the top level
* net cell + name, any traversal of that net down the hierarchy is also not extracted.
*/
private static class ExemptedNets {
private HashMap<Cell,List<Net>> netsByCell; // key: cell, value: List of ExemptedNets.Net objects
private Set<Integer> exemptedNetIDs;
private static class Net {
private String name;
private double replacementCap;
}
private ExemptedNets(File file) {
netsByCell = new HashMap<Cell,List<Net>>();
exemptedNetIDs = new TreeSet<Integer>();
try {
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String line;
int lineno = 1;
System.out.println("Using exempted nets file "+file.getAbsolutePath());
while ((line = br.readLine()) != null) {
processLine(line, lineno);
lineno++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
return;
}
}
private void processLine(String line, int lineno) {
if (line == null) return;
if (line.trim().equals("")) return;
String parts[] = line.trim().split("\\s+");
if (parts.length < 3) {
System.out.println("Error on line "+lineno+": Expected 'LibraryName CellName NetName', but was "+line);
return;
}
Cell cell = getCell(parts[0], parts[1]);
if (cell == null) return;
double cap = 0;
if (parts.length > 3) {
try {
cap = Double.parseDouble(parts[3]);
} catch (NumberFormatException e) {
System.out.println("Error on line "+lineno+" "+e.getMessage());
}
}
List<Net> list = netsByCell.get(cell);
if (list == null) {
list = new ArrayList<Net>();
netsByCell.put(cell, list);
}
Net n = new Net();
n.name = parts[2];
n.replacementCap = cap;
list.add(n);
}
private Cell getCell(String library, String cell) {
Library lib = Library.findLibrary(library);
if (lib == null) {
System.out.println("Could not find library "+library);
return null;
}
Cell c = lib.findNodeProto(cell);
if (c == null) {
System.out.println("Could not find cell "+cell+" in library "+library);
return null;
}
return c;
}
/**
* Get the netIDs for all exempted nets in the cell specified by the CellInfo
* @param info
*/
private void setExemptedNets(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
List<Net> netNames = netsByCell.get(cell);
if (netNames == null) return; // nothing for this cell
for (Net n : netNames) {
String netName = n.name;
Network net = findNetwork(info, netName);
if (net == null) {
System.out.println("Cannot find network "+netName+" in cell "+cell.describe(true));
continue;
}
// get the global ID
System.out.println("Specified exemption of net "+cell.describe(false)+" "+netName);
int netID = info.getNetID(net);
exemptedNetIDs.add(new Integer(netID));
}
}
private Network findNetwork(HierarchyEnumerator.CellInfo info, String name) {
for (Iterator<Network> it = info.getNetlist().getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(name)) return net;
}
return null;
}
private boolean isExempted(int netID) {
return exemptedNetIDs.contains(new Integer(netID));
}
private double getReplacementCap(Cell cell, Network net) {
List<Net> netNames = netsByCell.get(cell);
if (netNames == null) return 0; // nothing for this cell
for (Net n : netNames) {
if (net.hasName(n.name)) {
return n.replacementCap;
}
}
return 0;
}
}
/****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/
/**
* Method to adjust a cell name to be safe for Spice output.
* @param name the cell name.
* @return the name, adjusted for Spice output.
*/
protected String getSafeCellName(String name)
{
return getSafeNetName(name, false);
}
/** Method to return the proper name of Power */
protected String getPowerName(Network net)
{
if (net != null)
{
// favor "vdd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("vdd")) return "vdd";
}
}
return null;
}
/** Method to return the proper name of Ground */
protected String getGroundName(Network net)
{
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) return "0";
if (net != null)
{
// favor "gnd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("gnd")) return "gnd";
}
}
return null;
}
/** Method to return the proper name of a Global signal */
protected String getGlobalName(Global glob) { return glob.getName(); }
/** Method to report that export names do NOT take precedence over
* arc names when determining the name of the network. */
protected boolean isNetworksUseExportedNames() { return false; }
/** Method to report that library names are NOT always prepended to cell names. */
protected boolean isLibraryNameAlwaysAddedToCellName() { return false; }
/** Method to report that aggregate names (busses) are not used. */
protected boolean isAggregateNamesSupported() { return false; }
/** Method to report that not to choose best export name among exports connected to signal. */
protected boolean isChooseBestExportName() { return false; }
/** Method to report whether input and output names are separated. */
protected boolean isSeparateInputAndOutput() { return false; }
/** If the netlister has requirments not to netlist certain cells and their
* subcells, override this method.
* If this cell has a spice template, skip it
*/
protected boolean skipCellAndSubcells(Cell cell)
{
if (useCDL) {
// check for CDL template: if exists, skip
Variable cdlTemplate = cell.getVar(CDL_TEMPLATE_KEY);
if (cdlTemplate != null) return true;
// no template, return false
return false;
}
// skip if there is a template
Variable varTemplate = null;
varTemplate = cell.getVar(preferedEngineTemplateKey);
if (varTemplate != null) return true;
if (!assuraHSpice)
{
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
}
if (varTemplate != null) return true;
// look for a model file on the current cell
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
String fileName = CellModelPrefs.spiceModelPrefs.getModelFile(cell);
if (!modelOverrides.containsKey(cell))
{
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
addIncludeFile(fileName);
if (!fileName.startsWith("/") && !fileName.startsWith("\\")) {
File spiceFile = new File(filePath);
fileName = (new File(spiceFile.getParent(), fileName)).getPath();
}
modelOverrides.put(cell, fileName);
}
return true;
}
return false;
}
protected void validateSkippedCell(HierarchyEnumerator.CellInfo info) {
String fileName = modelOverrides.get(info.getCell());
if (fileName != null) {
// validate included file
SpiceNetlistReader reader = new SpiceNetlistReader();
try {
reader.readFile(fileName, false);
HierarchyEnumerator.CellInfo parentInfo = info.getParentInfo();
Nodable no = info.getParentInst();
String parameterizedName = parameterizedName(no, parentInfo.getContext());
CellNetInfo cni = getCellNetInfo(parameterizedName);
SpiceSubckt subckt = reader.getSubckt(parameterizedName);
if (subckt == null) {
System.out.println("Error: No subckt for "+parameterizedName+" found in included file: "+fileName);
} else {
List<String> signals = new ArrayList<String>();
for (Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); ) {
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
signals.add(cs.getName());
}
List<String> subcktSignals = subckt.getPorts();
if (signals.size() != subcktSignals.size()) {
System.out.println("Warning: wrong number of ports for subckt "+
parameterizedName+": expected "+signals.size()+", but found "+
subcktSignals.size()+", in included file "+fileName);
}
int len = Math.min(signals.size(), subcktSignals.size());
for (int i=0; i<len; i++) {
String s1 = signals.get(i);
String s2 = subcktSignals.get(i);
if (!s1.equalsIgnoreCase(s2)) {
System.out.println("Warning: port "+i+" of subckt "+parameterizedName+
" is named "+s1+" in Electric, but "+s2+" in included file "+fileName);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Error validating included file: "+e.getMessage());
}
}
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
protected String getSafeNetName(String name, boolean bus)
{
return getSafeNetName(name, bus, legalSpiceChars, spiceEngine);
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
public static String getSafeNetName(String name)
{
String legalSpiceChars = SPICELEGALCHARS;
if (Simulation.getSpiceEngine() == Simulation.SpiceEngine.SPICE_ENGINE_P)
legalSpiceChars = PSPICELEGALCHARS;
return getSafeNetName(name, false, legalSpiceChars, Simulation.getSpiceEngine());
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
private static String getSafeNetName(String name, boolean bus, String legalSpiceChars, Simulation.SpiceEngine spiceEngine)
{
// simple names are trivially accepted as is
boolean allAlNum = true;
int len = name.length();
if (len <= 0) return name;
for(int i=0; i<len; i++)
{
boolean valid = TextUtils.isLetterOrDigit(name.charAt(i));
if (i == 0) valid = Character.isLetter(name.charAt(i));
if (!valid)
{
allAlNum = false;
break;
}
}
if (allAlNum) return name;
StringBuffer sb = new StringBuffer();
if (TextUtils.isDigit(name.charAt(0)) &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_G &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_P &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_2) sb.append('_');
for(int t=0; t<name.length(); t++)
{
char chr = name.charAt(t);
boolean legalChar = TextUtils.isLetterOrDigit(chr);
if (!legalChar)
{
for(int j=0; j<legalSpiceChars.length(); j++)
{
char legalChr = legalSpiceChars.charAt(j);
if (chr == legalChr) { legalChar = true; break; }
}
}
if (!legalChar) chr = '_';
sb.append(chr);
}
return sb.toString();
}
/** Tell the Hierarchy enumerator whether or not to short parasitic resistors */
protected boolean isShortResistors() {
if (useCDL && Simulation.getCDLIgnoreResistors())
return true;
return false;
}
/** Tell the Hierarchy enumerator whether or not to short explicit (poly) resistors */
protected boolean isShortExplicitResistors() {
// until netlister is changed
if (useCDL && Simulation.getCDLIgnoreResistors())
return false;
return false;
}
/**
* Method to tell whether the topological analysis should mangle cell names that are parameterized.
*/
protected boolean canParameterizeNames() { return true; } //return !useCDL; }
/**
* Method to tell set a limit on the number of characters in a name.
* @return the limit to name size (SPICE limits to 32 character names?????).
*/
protected int maxNameLength() { if (useCDL) return CDLMAXLENSUBCKTNAME; return SPICEMAXLENSUBCKTNAME; }
protected boolean enumerateLayoutView(Cell cell) {
return (CellModelPrefs.spiceModelPrefs.isUseLayoutView(cell));
}
/******************** DECK GENERATION SUPPORT ********************/
/**
* write a header for "cell" to spice deck "sim_spice_file"
* The model cards come from a file specified by tech:~.SIM_spice_model_file
* or else tech:~.SIM_spice_header_level%ld
* The spice model file can be located in el_libdir
*/
private void writeHeader(Cell cell)
{
// Print the header line for SPICE
multiLinePrint(true, "*** SPICE deck for cell " + cell.noLibDescribe() +
" from library " + cell.getLibrary().getName() + "\n");
emitCopyright("*** ", "");
if (User.isIncludeDateAndVersionInOutput())
{
multiLinePrint(true, "*** Created on " + TextUtils.formatDate(topCell.getCreationDate()) + "\n");
multiLinePrint(true, "*** Last revised on " + TextUtils.formatDate(topCell.getRevisionDate()) + "\n");
multiLinePrint(true, "*** Written on " + TextUtils.formatDate(new Date()) +
" by Electric VLSI Design System, version " + Version.getVersion() + "\n");
} else
{
multiLinePrint(true, "*** Written by Electric VLSI Design System\n");
}
String foundry = layoutTechnology.getSelectedFoundry() == null ? "" : (", foundry "+layoutTechnology.getSelectedFoundry().toString());
multiLinePrint(true, "*** Layout tech: "+layoutTechnology.getTechName()+foundry+"\n");
multiLinePrint(true, "*** UC SPICE *** , MIN_RESIST " + layoutTechnology.getMinResistance() +
", MIN_CAPAC " + layoutTechnology.getMinCapacitance() + "FF\n");
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
if (useParasitics) {
for (Layer layer : layoutTechnology.getLayersSortedByHeight()) {
if (layer.isPseudoLayer()) continue;
double edgecap = layer.getEdgeCapacitance();
double areacap = layer.getCapacitance();
double res = layer.getResistance();
if (edgecap != 0 || areacap != 0 || res != 0) {
multiLinePrint(true, "*** "+layer.getName()+":\tareacap="+areacap+"FF/um^2,\tedgecap="+edgecap+"FF/um,\tres="+res+"ohms/sq\n");
}
}
}
multiLinePrint(false, ".OPTIONS NOMOD NOPAGE\n");
// if sizes to be written in lambda, tell spice conversion factor
if (Simulation.isSpiceWriteTransSizeInLambda())
{
double scale = layoutTechnology.getScale();
multiLinePrint(true, "*** Lambda Conversion ***\n");
multiLinePrint(false, ".opt scale=" + TextUtils.formatDouble(scale / 1000.0, 3) + "U\n\n");
}
// see if spice model/option cards from file if specified
String headerFile = Simulation.getSpiceHeaderCardInfo();
if (headerFile.length() > 0)
{
if (headerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String headerPath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = headerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Header Card '" + fileName + "' is included");
return;
}
else
System.out.println("Spice Header Card '" + fileName + "' cannot be loaded");
} else
{
// normal header file specified
File test = new File(headerFile);
if (!test.exists())
System.out.println("Warning: cannot find model file '" + headerFile + "'");
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(headerFile);
return;
}
}
// no header files: write predefined header for this level and technology
int level = TextUtils.atoi(Simulation.getSpiceLevel());
String [] header = null;
switch (level)
{
case 1: header = layoutTechnology.getSpiceHeaderLevel1(); break;
case 2: header = layoutTechnology.getSpiceHeaderLevel2(); break;
case 3: header = layoutTechnology.getSpiceHeaderLevel3(); break;
}
if (header != null)
{
for(int i=0; i<header.length; i++)
multiLinePrint(false, header[i] + "\n");
return;
}
System.out.println("WARNING: no model cards for SPICE level " + level +
" in " + layoutTechnology.getTechName() + " technology");
}
/**
* Write a trailer from an external file, defined as a variable on
* the current technology in this library: tech:~.SIM_spice_trailer_file
* if it is available.
*/
private void writeTrailer(Cell cell)
{
// get spice trailer cards from file if specified
String trailerFile = Simulation.getSpiceTrailerCardInfo();
if (trailerFile.length() > 0)
{
if (trailerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String trailerpath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = trailerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = trailerpath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Trailer Card '" + fileName + "' is included");
}
else
System.out.println("Spice Trailer Card '" + fileName + "' cannot be loaded");
} else
{
// normal trailer file specified
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(trailerFile);
System.out.println("Spice Trailer Card '" + trailerFile + "' is included");
}
}
}
/**
* Function to write a two port device to the file. Complain about any missing connections.
* Determine the port connections from the portprotos in the instance
* prototype. Get the part number from the 'part' number value;
* increment it. The type of device is declared in type; extra is the string
* data acquired before calling here.
* If the device is connected to the same net at both ends, do not
* write it. Is this OK?
*/
private void writeTwoPort(NodeInst ni, String partName, String extra, CellNetInfo cni, Netlist netList, VarContext context, SegmentedNets segmentedNets)
{
PortInst port0 = ni.getPortInst(0);
PortInst port1 = ni.getPortInst(1);
Network net0 = netList.getNetwork(port0);
Network net1 = netList.getNetwork(port1);
CellSignal cs0 = cni.getCellSignal(net0);
CellSignal cs1 = cni.getCellSignal(net1);
// make sure the component is connected to nets
if (cs0 == null || cs1 == null)
{
String message = "WARNING: " + ni + " component not fully connected in " + ni.getParent();
dumpErrorMessage(message);
}
if (cs0 != null && cs1 != null && cs0 == cs1)
{
String message = "WARNING: " + ni + " component appears to be shorted on net " + net0.toString() +
" in " + ni.getParent();
dumpErrorMessage(message);
return;
}
if (ni.getName() != null) partName += getSafeNetName(ni.getName(), false);
// add Mfactor if there
StringBuffer sbExtra = new StringBuffer(extra);
writeMFactor(context, ni, sbExtra);
String name0 = cs0.getName();
String name1 = cs1.getName();
if (segmentedNets.getUseParasitics()) {
name0 = segmentedNets.getNetName(port0);
name1 = segmentedNets.getNetName(port1);
}
multiLinePrint(false, partName + " " + name1 + " " + name0 + " " + sbExtra.toString() + "\n");
}
/**
* This adds formatting to a Spice parameter value. It adds single quotes
* around the param string if they do not already exist.
* @param param the string param value (without the name= part).
* @return a param string with single quotes around it
*/
private static String formatParam(String param) {
String value = trimSingleQuotes(param);
try {
Double.valueOf(value);
return value;
} catch (NumberFormatException e) {
return ("'"+value+"'");
}
}
private static String trimSingleQuotes(String param) {
if (param.startsWith("'") && param.endsWith("'")) {
return param.substring(1, param.length()-1);
}
return param;
}
/******************** PARASITIC CALCULATIONS ********************/
/**
* Method to recursively determine the area of diffusion and capacitance
* associated with port "pp" of nodeinst "ni". If the node is mult_layer, then
* determine the dominant capacitance layer, and add its area; all other
* layers will be added as well to the extra_area total.
* Continue out of the ports on a complex cell
*/
private void addNodeInformation(Netlist netList, HashMap<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;
if (layer.getTechnology() != Technology.getCurrent()) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}
/**
* Method to recursively determine the area of diffusion, capacitance, (NOT
* resistance) on arc "ai". If the arc contains active device diffusion, then
* it will contribute to the area of sources and drains, and the other layers
* will be ignored. This is not quite the same as the rule used for
* contact (node) structures. Note: the earlier version of this
* function assumed that diffusion arcs would always have zero capacitance
* values for the other layers; this produces an error if any of these layers
* have non-zero values assigned for other reasons. So we will check for the
* function of the arc, and if it contains active device, we will ignore any
* other layers
*/
private void addArcInformation(PolyMerge merge, ArcInst ai)
{
boolean isDiffArc = ai.isDiffusionArc(); // check arc function
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
// if (layer.isPseudoLayer()) continue;
if (layer.isDiffusionLayer()||
(!isDiffArc && layer.getCapacitance() > 0.0))
merge.addPolygon(layer, poly);
}
}
/******************** TEXT METHODS ********************/
/**
* Method to insert an "include" of file "filename" into the stream "io".
*/
private void addIncludeFile(String fileName)
{
if (useCDL) {
multiLinePrint(false, ".include "+ fileName + "\n");
return;
}
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_S)
{
multiLinePrint(false, ".include " + fileName + "\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_CALIBRE)
{
multiLinePrint(false, ".include '" + fileName + "'\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P)
{
multiLinePrint(false, ".INC " + fileName + "\n");
}
}
// private void validateIncludeFile(String fileName, String subcktName) {
// }
/******************** SUPPORT ********************/
/**
* Method to return value if arc contains device active diffusion
*/
// private boolean arcIsDiff(ArcInst ai)
// {
// ArcProto.Function fun = ai.getProto().getFunction();
// boolean newV = ai.isDiffusionArc();
// boolean oldV = (fun == ArcProto.Function.DIFFP || fun == ArcProto.Function.DIFFN ||
// fun == ArcProto.Function.DIFF || fun == ArcProto.Function.DIFFS || fun == ArcProto.Function.DIFFW);
// if (newV != oldV)
// System.out.println("Difference in arcIsDiff");
// return oldV;
//// if (fun == ArcProto.Function.DIFFP || fun == ArcProto.Function.DIFFN || fun == ArcProto.Function.DIFF) return true;
//// if (fun == ArcProto.Function.DIFFS || fun == ArcProto.Function.DIFFW) return true;
//// return false;
// }
private static final boolean CELLISEMPTYDEBUG = false;
private HashMap<Cell,Boolean> checkedCells = new HashMap<Cell,Boolean>();
private boolean cellIsEmpty(Cell cell)
{
Boolean b = checkedCells.get(cell);
if (b != null) return b.booleanValue();
boolean empty = true;
List<Cell> emptyCells = new ArrayList<Cell>();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
// if node is a cell, check if subcell is empty
if (ni.isCellInstance()) {
// ignore own icon
if (ni.isIconOfParent()) {
continue;
}
Cell iconCell = (Cell)ni.getProto();
Cell schCell = iconCell.contentsView();
if (schCell == null) schCell = iconCell;
if (cellIsEmpty(schCell)) {
if (CELLISEMPTYDEBUG) emptyCells.add(schCell);
continue;
} else {
empty = false;
break;
}
}
// otherwise, this is a primitive
PrimitiveNode.Function fun = ni.getFunction();
// Passive devices used by spice/CDL
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
empty = false;
break;
}
// active devices used by Spice/CDL
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
empty = false;
break;
}
// check for spice code on pins
if (ni.getVar(SPICE_CARD_KEY) != null) {
empty = false;
break;
}
}
// look for a model file on the current cell
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
empty = false;
}
// check for spice template
if (getEngineTemplate(cell) != null) {
empty = false;
}
// empty
if (CELLISEMPTYDEBUG && empty) {
System.out.println(cell+" is empty and contains the following empty cells:");
for (Cell c : emptyCells)
System.out.println(" "+c.describe(true));
}
checkedCells.put(cell, new Boolean(empty));
return empty;
}
/******************** LOW-LEVEL OUTPUT METHODS ********************/
/**
* Method to report an error that is built in the infinite string.
* The error is sent to the messages window and also to the SPICE deck "f".
*/
private void dumpErrorMessage(String message)
{
multiLinePrint(true, "*** " + message + "\n");
System.out.println(message);
}
/**
* Formatted output to file "stream". All spice output is in upper case.
* The buffer can contain no more than 1024 chars including the newlinelastMoveTo
* and null characters.
* Doesn't return anything.
*/
private void multiLinePrint(boolean isComment, String str)
{
// put in line continuations, if over 78 chars long
char contChar = '+';
if (isComment) contChar = '*';
int lastSpace = -1;
int count = 0;
boolean insideQuotes = false;
int lineStart = 0;
for (int pt = 0; pt < str.length(); pt++)
{
char chr = str.charAt(pt);
// if (sim_spice_machine == SPICE2)
// {
// if (islower(*pt)) *pt = toupper(*pt);
// }
if (chr == '\n')
{
printWriter.print(str.substring(lineStart, pt+1));
count = 0;
lastSpace = -1;
lineStart = pt+1;
} else
{
if (chr == ' ' && !insideQuotes) lastSpace = pt;
if (chr == '\'') insideQuotes = !insideQuotes;
count++;
if (count >= spiceMaxLenLine && !insideQuotes && lastSpace > -1)
{
String partial = str.substring(lineStart, lastSpace+1);
printWriter.print(partial + "\n" + contChar);
count = count - partial.length();
lineStart = lastSpace+1;
lastSpace = -1;
}
}
}
if (lineStart < str.length())
{
String partial = str.substring(lineStart);
printWriter.print(partial);
}
}
public static class FlatSpiceCodeVisitor extends HierarchyEnumerator.Visitor {
private PrintWriter printWriter;
private PrintWriter spicePrintWriter;
private String filePath;
Spice spice; // just used for file writing and formatting
SegmentedNets segNets;
public FlatSpiceCodeVisitor(String filePath, Spice spice) {
this.spice = spice;
this.spicePrintWriter = spice.printWriter;
this.filePath = filePath;
spice.spiceMaxLenLine = 1000;
segNets = null;
}
public boolean enterCell(HierarchyEnumerator.CellInfo info) {
return true;
}
public void exitCell(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CODE_FLAT_KEY);
if (cardVar != null) {
if (printWriter == null) {
try {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath)));
} catch (IOException e) {
System.out.println("Unable to open "+filePath+" for write.");
return;
}
spice.printWriter = printWriter;
segNets = new SegmentedNets(null, false, null, false);
}
spice.emitEmbeddedSpice(cardVar, info.getContext(), segNets, info, true);
}
}
}
public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
return true;
}
public void close() {
if (printWriter != null) {
System.out.println(filePath+" written");
spice.printWriter = spicePrintWriter;
printWriter.close();
}
spice.spiceMaxLenLine = SPICEMAXLENLINE;
}
}
}
| true | true | protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell && USE_GLOBALS) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics) {
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
boolean ignoreArc = false;
// figure out res and cap, see if we should ignore it
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
ignoreArc = true;
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaBaseWidth() * scale / 1000; // width in microns
// double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
double cap = 0;
double res = 0;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() > 0.0) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
res = length/width * layer.getResistance();
}
}
// add res if big enough
if (res <= cell.getTechnology().getMinResistance()) {
ignoreArc = true;
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
Network net = netList.getNetwork(ai, 0);
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
ignoreArc = true;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net)) && ignoreArc == false) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
}
} else {
ignoreArc = true;
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
if (ignoreArc)
arcPImodels = 1; // split cap to two pins if ignoring arc
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (ignoreArc) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = null;
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext();) {
PortInst p2 = pit.next();
if (p2 != gate0 && netList.getNetwork(gate0) == netList.getNetwork(p2))
gate1 = p2;
}
if (gate1 != null) {
segmentedNets.shortSegments(gate0, gate1);
}
}
} else {
//System.out.println("Shorting shorted exports");
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// // use ground net for substrate
// if (subnet == NOSPNET && sim_spice_gnd != NONETWORK)
// subnet = (SPNET *)sim_spice_gnd->temp1;
// if (bipolarTrans != 0 && subnet == NOSPNET)
// {
// infstr = initinfstr();
// formatinfstr(infstr, _("WARNING: no explicit connection to the substrate in cell %s"),
// describenodeproto(np));
// dumpErrorMessage(infstr);
// if (sim_spice_gnd != NONETWORK)
// {
// ttyputmsg(_(" A connection to ground will be used if necessary."));
// subnet = (SPNET *)sim_spice_gnd->temp1;
// }
// }
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (cs.isGlobal()) {
System.out.println("Warning: Explicit Global signal "+cs.getName()+" exported in "+cell.describe(false));
}
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
infstr.append(" " + cs.getName());
}
}
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
// write exports to this cell
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) continue;
if (cs.isGlobal()) continue;
//multiLinePrint(true, "** PORT " + cs.getName() + "\n");
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
if (useCDL)
{
varTemplate = subCell.getVar(CDL_TEMPLATE_KEY);
} else
{
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
}
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
// ignore networks that aren't exported
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (USE_GLOBALS)
{
if (pp == null) continue;
if (subCS.isGlobal() && subCS.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(subCS)) continue;
}
net = netList.getNetwork(no, pp, exportIndex);
} else
{
if (pp == null && !subCS.isGlobal()) continue;
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal()) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
Global.Set globals = subCni.getNetList().getGlobals();
int globalSize = globals.size();
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
infstr.append(" " + global.getName());
}
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj));
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
PrimitiveNode.Function fun = ni.getFunction();
// handle resistors, inductors, capacitors, and diodes
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor()) // == PrimitiveNode.Function.RESIST)
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
extra = " L='"+length+"*LAMBDA' W='"+width+"*LAMBDA'";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor()) // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC)
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth()));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth()));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics) {
int capCount = 0;
int resCount = 0;
// write caps
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+TextUtils.formatDouble(segCap)+"fF\n");
capCount++;
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else {
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
// int i=0;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
// i++;
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
| protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell && USE_GLOBALS) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics) {
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
boolean ignoreArc = false;
// figure out res and cap, see if we should ignore it
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
ignoreArc = true;
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaBaseWidth() * scale / 1000; // width in microns
// double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
double cap = 0;
double res = 0;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() > 0.0) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
res = length/width * layer.getResistance();
}
}
// add res if big enough
if (res <= cell.getTechnology().getMinResistance()) {
ignoreArc = true;
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
Network net = netList.getNetwork(ai, 0);
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
ignoreArc = true;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net)) && ignoreArc == false) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
}
} else {
ignoreArc = true;
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
if (ignoreArc)
arcPImodels = 1; // split cap to two pins if ignoring arc
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (ignoreArc) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = null;
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext();) {
PortInst p2 = pit.next();
if (p2 != gate0 && netList.getNetwork(gate0) == netList.getNetwork(p2))
gate1 = p2;
}
if (gate1 != null) {
segmentedNets.shortSegments(gate0, gate1);
}
}
} else {
//System.out.println("Shorting shorted exports");
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// // use ground net for substrate
// if (subnet == NOSPNET && sim_spice_gnd != NONETWORK)
// subnet = (SPNET *)sim_spice_gnd->temp1;
// if (bipolarTrans != 0 && subnet == NOSPNET)
// {
// infstr = initinfstr();
// formatinfstr(infstr, _("WARNING: no explicit connection to the substrate in cell %s"),
// describenodeproto(np));
// dumpErrorMessage(infstr);
// if (sim_spice_gnd != NONETWORK)
// {
// ttyputmsg(_(" A connection to ground will be used if necessary."));
// subnet = (SPNET *)sim_spice_gnd->temp1;
// }
// }
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (cs.isGlobal()) {
System.out.println("Warning: Explicit Global signal "+cs.getName()+" exported in "+cell.describe(false));
}
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
infstr.append(" " + cs.getName());
}
}
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
// write exports to this cell
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) continue;
if (cs.isGlobal()) continue;
//multiLinePrint(true, "** PORT " + cs.getName() + "\n");
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
if (useCDL)
{
varTemplate = subCell.getVar(CDL_TEMPLATE_KEY);
} else
{
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
}
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
// ignore networks that aren't exported
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (USE_GLOBALS)
{
if (pp == null) continue;
if (subCS.isGlobal() && subCS.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(subCS)) continue;
}
net = netList.getNetwork(no, pp, exportIndex);
} else
{
if (pp == null && !subCS.isGlobal()) continue;
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal()) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
Global.Set globals = subCni.getNetList().getGlobals();
int globalSize = globals.size();
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
infstr.append(" " + global.getName());
}
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj));
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
PrimitiveNode.Function fun = ni.getFunction();
// handle resistors, inductors, capacitors, and diodes
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor()) // == PrimitiveNode.Function.RESIST)
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
extra = " L='"+length+"*LAMBDA' W='"+width+"*LAMBDA'";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor()) // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC)
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth()));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth()));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics) {
int capCount = 0;
int resCount = 0;
// write caps
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+TextUtils.formatDouble(segCap)+"fF\n");
capCount++;
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else {
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
// int i=0;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
// i++;
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
|
diff --git a/src/main/java/com/google/devtools/j2objc/util/UnicodeUtils.java b/src/main/java/com/google/devtools/j2objc/util/UnicodeUtils.java
index a273ece..54491ce 100644
--- a/src/main/java/com/google/devtools/j2objc/util/UnicodeUtils.java
+++ b/src/main/java/com/google/devtools/j2objc/util/UnicodeUtils.java
@@ -1,196 +1,196 @@
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.util;
import com.google.common.annotations.VisibleForTesting;
import com.google.devtools.j2objc.J2ObjC;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utility methods for translating Unicode strings to Objective-C.
*
* @author Tom Ball
*/
public final class UnicodeUtils {
private UnicodeUtils() {
// Don't instantiate.
}
public static String escapeStringLiteral(String s) {
return escapeOctalSequences(escapeUnicodeSequences(s));
}
/**
* Converts Unicode sequences that aren't all valid C++ universal
* characters, as defined by ISO 14882, section 2.2, to either
* characters or hexadecimal escape sequences.
*/
public static String escapeUnicodeSequences(String s) {
return escapeUnicodeSequences(s, true);
}
@VisibleForTesting
static String escapeUnicodeSequences(String s, boolean logErrorMessage) {
if (s.contains("\\u")) {
StringBuilder buffer = new StringBuilder();
int i, lastIndex = 0;
while ((i = s.indexOf("\\u", lastIndex)) != -1) {
String chunk = s.substring(lastIndex, i);
buffer.append(chunk);
// Convert hex Unicode number; format valid due to compiler check.
if (s.length() >= i + 6) {
char value = (char) Integer.parseInt(s.substring(i + 2, i + 6), 16);
String convertedChar = escapeCharacter(value);
if (convertedChar != null) {
buffer.append(convertedChar);
} else {
if (!isValidCppCharacter(value)) {
if (logErrorMessage) {
J2ObjC.error(String.format("Illegal C/C++ Unicode character \\u%4x in \"%s\"",
- value, s));
+ (int) value, s));
} else {
J2ObjC.error();
}
// Fall-through to print, so output is debug-able.
}
// Print Unicode sequence.
buffer.append(s.substring(i, i + 6));
}
lastIndex = i + 6;
} else {
buffer.append(s.substring(i));
lastIndex = s.length();
}
}
buffer.append(s.substring(lastIndex));
return buffer.toString();
} else {
return s;
}
}
private static final Pattern INVALID_OCTAL = Pattern.compile("\\\\([2-3][0-7][0-7])");
/**
* Replaces invalid octal escape sequences, from a C99 perspective.
*/
@VisibleForTesting
static String escapeOctalSequences(String s) {
Matcher matcher = INVALID_OCTAL.matcher(s);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "");
sb.append(escapeUtf8((char) Integer.parseInt(matcher.group(1), 8)));
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* Returns true if all characters in a string can be expressed as either
* C++ universal characters or valid hexadecimal escape sequences.
*/
public static boolean hasValidCppCharacters(String s) {
for (char c : s.toCharArray()) {
if (!isValidCppCharacter(c)) {
return false;
}
}
return true;
}
/**
* Converts a character into either a character or a hexadecimal sequence,
* depending on whether it is a valid C++ universal character, as defined
* by ISO 14882, section 2.2. Returns the converted character as a String,
* or null if the given value was not handled.
*/
public static String escapeCharacter(char value) {
if (value >= 0x20 && value <= 0x7E) {
// Printable ASCII character.
return Character.toString(value);
} else if (value < 0x20 || (value >= 0x7F && value < 0xA0)) {
// Invalid C++ Unicode number, convert to UTF-8 sequence.
return escapeUtf8(value);
} else {
return null;
}
}
private static String escapeUtf8(char value) {
StringBuilder buffer = new StringBuilder();
String charString = Character.toString(value);
try {
for (byte b : charString.getBytes("UTF-8")) {
int unsignedByte = b & 0xFF;
buffer.append("\\x");
if (unsignedByte < 16) {
buffer.append('0');
}
buffer.append(Integer.toHexString(unsignedByte));
}
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is an unsupported encoding");
}
return buffer.toString();
}
/**
* Returns true if the specified character can be represented in a C string
* or character literal declaration. Value ranges were determined from the
* <a href="http://www.unicode.org/charts/">Unicode 6.0 Character Code
* Charts</a>.
* <p>
* Note: these ranges include code points which Character.isDefined(ch)
* returns as false in Java 6. OpenJDK 7 lists an update to Unicode 6.0
* as one of its features, so when Java 7 is widely available this method
* can be removed.
*/
public static boolean isValidCppCharacter(char c) {
// This would be more efficiently implemented as a bitmap, but since it's
// not used in performance-critical code, this form is easier to inspect.
return c < 0xd800 ||
c >= 0xf900 && c <= 0xfad9 ||
c >= 0xfb50 && c <= 0xfbc1 ||
c >= 0xfbd3 && c <= 0xfd3f ||
c >= 0xfd5f && c <= 0xfd8f ||
c >= 0xfc92 && c <= 0xfdc7 ||
c >= 0xfdf0 && c <= 0xfdfd ||
c >= 0xfe10 && c <= 0xfe19 ||
c >= 0xfe20 && c <= 0xfe26 ||
c >= 0xfe30 && c <= 0xfe4f ||
c >= 0xfe50 && c <= 0xfe52 ||
c >= 0xfe54 && c <= 0xfe66 ||
c >= 0xfe68 && c <= 0xfe6b ||
c >= 0xfe70 && c <= 0xfe74 ||
c >= 0xfe76 && c <= 0xfefc ||
c == 0xfeff ||
c >= 0xff01 && c <= 0xffbe ||
c >= 0xffc2 && c <= 0xffc7 ||
c >= 0xffca && c <= 0xffcf ||
c >= 0xffd2 && c <= 0xffd7 ||
c >= 0xffda && c <= 0xffdc ||
c >= 0xffe0 && c <= 0xffe6 ||
c >= 0xffe8 && c <= 0xffee ||
c >= 0xfff9 && c <= 0xfffd;
}
}
| true | true | static String escapeUnicodeSequences(String s, boolean logErrorMessage) {
if (s.contains("\\u")) {
StringBuilder buffer = new StringBuilder();
int i, lastIndex = 0;
while ((i = s.indexOf("\\u", lastIndex)) != -1) {
String chunk = s.substring(lastIndex, i);
buffer.append(chunk);
// Convert hex Unicode number; format valid due to compiler check.
if (s.length() >= i + 6) {
char value = (char) Integer.parseInt(s.substring(i + 2, i + 6), 16);
String convertedChar = escapeCharacter(value);
if (convertedChar != null) {
buffer.append(convertedChar);
} else {
if (!isValidCppCharacter(value)) {
if (logErrorMessage) {
J2ObjC.error(String.format("Illegal C/C++ Unicode character \\u%4x in \"%s\"",
value, s));
} else {
J2ObjC.error();
}
// Fall-through to print, so output is debug-able.
}
// Print Unicode sequence.
buffer.append(s.substring(i, i + 6));
}
lastIndex = i + 6;
} else {
buffer.append(s.substring(i));
lastIndex = s.length();
}
}
buffer.append(s.substring(lastIndex));
return buffer.toString();
} else {
return s;
}
}
| static String escapeUnicodeSequences(String s, boolean logErrorMessage) {
if (s.contains("\\u")) {
StringBuilder buffer = new StringBuilder();
int i, lastIndex = 0;
while ((i = s.indexOf("\\u", lastIndex)) != -1) {
String chunk = s.substring(lastIndex, i);
buffer.append(chunk);
// Convert hex Unicode number; format valid due to compiler check.
if (s.length() >= i + 6) {
char value = (char) Integer.parseInt(s.substring(i + 2, i + 6), 16);
String convertedChar = escapeCharacter(value);
if (convertedChar != null) {
buffer.append(convertedChar);
} else {
if (!isValidCppCharacter(value)) {
if (logErrorMessage) {
J2ObjC.error(String.format("Illegal C/C++ Unicode character \\u%4x in \"%s\"",
(int) value, s));
} else {
J2ObjC.error();
}
// Fall-through to print, so output is debug-able.
}
// Print Unicode sequence.
buffer.append(s.substring(i, i + 6));
}
lastIndex = i + 6;
} else {
buffer.append(s.substring(i));
lastIndex = s.length();
}
}
buffer.append(s.substring(lastIndex));
return buffer.toString();
} else {
return s;
}
}
|
diff --git a/api/src/main/java/org/jboss/seam/solder/properties/query/PropertyQuery.java b/api/src/main/java/org/jboss/seam/solder/properties/query/PropertyQuery.java
index 0aa699b0..073d420a 100644
--- a/api/src/main/java/org/jboss/seam/solder/properties/query/PropertyQuery.java
+++ b/api/src/main/java/org/jboss/seam/solder/properties/query/PropertyQuery.java
@@ -1,229 +1,229 @@
package org.jboss.seam.solder.properties.query;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.jboss.seam.solder.properties.MethodProperty;
import org.jboss.seam.solder.properties.Properties;
import org.jboss.seam.solder.properties.Property;
/**
* <p>
* Queries a target class for properties that match certain criteria. A property
* may either be a private or public field, declared by the target class or
* inherited from a superclass, or a public method declared by the target class
* or inherited from any of its superclasses. For properties that are exposed
* via a method, the property must be a JavaBean style property, i.e. it must
* provide both an accessor and mutator method according to the JavaBean
* specification.
* </p>
*
* <p>
* This class is not thread-safe, however the result returned by the
* getResultList() method is.
* </p>
*
* @author Shane Bryzak
*
* @see PropertyQueries
* @see PropertyCriteria
*/
public class PropertyQuery<V>
{
private final Class<?> targetClass;
private final List<PropertyCriteria> criteria;
PropertyQuery(Class<?> targetClass)
{
if (targetClass == null)
{
throw new IllegalArgumentException("targetClass parameter may not be null");
}
this.targetClass = targetClass;
this.criteria = new ArrayList<PropertyCriteria>();
}
/**
* Add a criteria to query
*
* @param criteria the criteria to add
*/
public PropertyQuery<V> addCriteria(PropertyCriteria criteria)
{
this.criteria.add(criteria);
return this;
}
/**
* Get the first result from the query, causing the query to be run.
*
* @return the first result, or null if there are no results
*/
public Property<V> getFirstResult()
{
List<Property<V>> results = getResultList();
return results.isEmpty() ? null : results.get(0);
}
/**
* Get the first result from the query that is not marked as read only,
* causing the query to be run.
*
* @return the first writable result, or null if there are no results
*/
public Property<V> getFirstWritableResult()
{
List<Property<V>> results = getWritableResultList();
return results.isEmpty() ? null : results.get(0);
}
/**
* Get a single result from the query, causing the query to be run. An
* exception is thrown if the query does not return exactly one result.
*
* @throws RuntimeException if the query does not return exactly one result
* @return the single result
*/
public Property<V> getSingleResult()
{
List<Property<V>> results = getResultList();
if (results.size() == 1)
{
return results.get(0);
}
else if (results.isEmpty())
{
throw new RuntimeException("Expected one property match, but the criteria did not match any properties on " + targetClass.getName());
}
else
{
throw new RuntimeException("Expected one property match, but the criteria matched " + results.size() + " properties on " + targetClass.getName());
}
}
/**
* Get a single result from the query that is not marked as read only,
* causing the query to be run. An exception is thrown if the query does not
* return exactly one result.
*
* @throws RuntimeException if the query does not return exactly one result
* @return the single writable result
*/
public Property<V> getWritableSingleResult()
{
List<Property<V>> results = getWritableResultList();
if (results.size() == 1)
{
return results.get(0);
}
else if (results.isEmpty())
{
throw new RuntimeException("Expected one property match, but the criteria did not match any properties on " + targetClass.getName());
}
else
{
throw new RuntimeException("Expected one property match, but the criteria matched " + results.size() + " properties on " + targetClass.getName());
}
}
/**
* Get the result from the query, causing the query to be run.
*
* @return the results, or an empty list if there are no results
*/
public List<Property<V>> getResultList()
{
return getResultList(false);
}
/**
* Get the non read only results from the query, causing the query to be run.
*
* @return the results, or an empty list if there are no results
*/
public List<Property<V>> getWritableResultList()
{
return getResultList(true);
}
/**
* Get the result from the query, causing the query to be run.
*
* @param writable if this query should only return properties that are not
* read only
* @return the results, or an empty list if there are no results
*/
private List<Property<V>> getResultList(boolean writable)
{
List<Property<V>> results = new ArrayList<Property<V>>();
// First check public accessor methods (we ignore private methods)
for (Method method : targetClass.getMethods())
{
if (!(method.getName().startsWith("is") || method.getName().startsWith("get")))
continue;
boolean match = true;
for (PropertyCriteria c : criteria)
{
if (!c.methodMatches(method))
{
match = false;
break;
}
}
if (match)
{
MethodProperty<V> property = Properties.<V> createProperty(method);
if (!writable || !property.isReadOnly())
{
results.add(property);
}
}
}
Class<?> cls = targetClass;
- while (!cls.equals(Object.class))
+ while (cls != null && !cls.equals(Object.class))
{
// Now check declared fields
for (Field field : cls.getDeclaredFields())
{
boolean match = true;
for (PropertyCriteria c : criteria)
{
if (!c.fieldMatches(field))
{
match = false;
break;
}
}
Property<V> prop = Properties.<V> createProperty(field);
if (match && !resultsContainsProperty(results, prop.getName()))
{
if (!writable || !prop.isReadOnly())
{
results.add(prop);
}
}
}
cls = cls.getSuperclass();
}
return results;
}
private boolean resultsContainsProperty(List<Property<V>> results, String propertyName)
{
for (Property<V> p : results)
{
if (propertyName.equals(p.getName()))
return true;
}
return false;
}
}
| true | true | private List<Property<V>> getResultList(boolean writable)
{
List<Property<V>> results = new ArrayList<Property<V>>();
// First check public accessor methods (we ignore private methods)
for (Method method : targetClass.getMethods())
{
if (!(method.getName().startsWith("is") || method.getName().startsWith("get")))
continue;
boolean match = true;
for (PropertyCriteria c : criteria)
{
if (!c.methodMatches(method))
{
match = false;
break;
}
}
if (match)
{
MethodProperty<V> property = Properties.<V> createProperty(method);
if (!writable || !property.isReadOnly())
{
results.add(property);
}
}
}
Class<?> cls = targetClass;
while (!cls.equals(Object.class))
{
// Now check declared fields
for (Field field : cls.getDeclaredFields())
{
boolean match = true;
for (PropertyCriteria c : criteria)
{
if (!c.fieldMatches(field))
{
match = false;
break;
}
}
Property<V> prop = Properties.<V> createProperty(field);
if (match && !resultsContainsProperty(results, prop.getName()))
{
if (!writable || !prop.isReadOnly())
{
results.add(prop);
}
}
}
cls = cls.getSuperclass();
}
return results;
}
| private List<Property<V>> getResultList(boolean writable)
{
List<Property<V>> results = new ArrayList<Property<V>>();
// First check public accessor methods (we ignore private methods)
for (Method method : targetClass.getMethods())
{
if (!(method.getName().startsWith("is") || method.getName().startsWith("get")))
continue;
boolean match = true;
for (PropertyCriteria c : criteria)
{
if (!c.methodMatches(method))
{
match = false;
break;
}
}
if (match)
{
MethodProperty<V> property = Properties.<V> createProperty(method);
if (!writable || !property.isReadOnly())
{
results.add(property);
}
}
}
Class<?> cls = targetClass;
while (cls != null && !cls.equals(Object.class))
{
// Now check declared fields
for (Field field : cls.getDeclaredFields())
{
boolean match = true;
for (PropertyCriteria c : criteria)
{
if (!c.fieldMatches(field))
{
match = false;
break;
}
}
Property<V> prop = Properties.<V> createProperty(field);
if (match && !resultsContainsProperty(results, prop.getName()))
{
if (!writable || !prop.isReadOnly())
{
results.add(prop);
}
}
}
cls = cls.getSuperclass();
}
return results;
}
|
diff --git a/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java b/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java
index 628bb6d..663e7ea 100644
--- a/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java
+++ b/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java
@@ -1,40 +1,41 @@
package no.ovitas.compass2.config;
import org.apache.log4j.Logger;
/**
* @author csanyi
*
*/
public class KnowledgeBases extends BaseConfigContainer<KnowledgeBase> {
// Attributes
private Logger logger = Logger.getLogger(this.getClass());
// Constructors
public KnowledgeBases() {
super();
}
// Methods
public KnowledgeBase getKnowledgeBase(String name) {
- if (name != null && !name.isEmpty()) {
+ if (name != null && elements.containsKey(name)) {
return elements.get(name);
} else {
+ logger.error("The " + name + " KnowledgeBase is not exists!");
return null;
}
}
public String dumpOut(String indent) {
String ind = indent + " ";
String toDumpOut = ind + "KnowledgeBases\n";
toDumpOut += super.dumpOut(ind);
return toDumpOut;
}
}
| false | true | public KnowledgeBase getKnowledgeBase(String name) {
if (name != null && !name.isEmpty()) {
return elements.get(name);
} else {
return null;
}
}
| public KnowledgeBase getKnowledgeBase(String name) {
if (name != null && elements.containsKey(name)) {
return elements.get(name);
} else {
logger.error("The " + name + " KnowledgeBase is not exists!");
return null;
}
}
|
diff --git a/aggregator/src/main/java/org/demo/AggregatorRouterJava.java b/aggregator/src/main/java/org/demo/AggregatorRouterJava.java
index 83a6128..bbe197d 100644
--- a/aggregator/src/main/java/org/demo/AggregatorRouterJava.java
+++ b/aggregator/src/main/java/org/demo/AggregatorRouterJava.java
@@ -1,16 +1,16 @@
package org.demo;
import aggregator.BodyAppenderAggregator;
import org.apache.camel.builder.RouteBuilder;
/**
* todo
*/
public class AggregatorRouterJava extends RouteBuilder {
@Override
public void configure() throws Exception {
- from("file:./target/test-classes/camel/in").convertBodyTo( String.class ).
+ from("file:./target/scala-2.10/classes/camel/in").convertBodyTo( String.class ).
aggregate(new BodyAppenderAggregator()).xpath("/item/@id").completionTimeout(1000).completionSize(0).
- to("file:./target/test-classes/camel/out");
+ to("file:./target/scala-2.10/classes/camel/out");
}
}
| false | true | public void configure() throws Exception {
from("file:./target/test-classes/camel/in").convertBodyTo( String.class ).
aggregate(new BodyAppenderAggregator()).xpath("/item/@id").completionTimeout(1000).completionSize(0).
to("file:./target/test-classes/camel/out");
}
| public void configure() throws Exception {
from("file:./target/scala-2.10/classes/camel/in").convertBodyTo( String.class ).
aggregate(new BodyAppenderAggregator()).xpath("/item/@id").completionTimeout(1000).completionSize(0).
to("file:./target/scala-2.10/classes/camel/out");
}
|
diff --git a/eclipse_files/src/agent/GantryAgent.java b/eclipse_files/src/agent/GantryAgent.java
index a30dee6e..86c58bc5 100644
--- a/eclipse_files/src/agent/GantryAgent.java
+++ b/eclipse_files/src/agent/GantryAgent.java
@@ -1,228 +1,228 @@
package agent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import factory.PartType;
import DeviceGraphics.DeviceGraphics;
import GraphicsInterfaces.GantryGraphics;
import agent.data.Bin;
import agent.data.Bin.BinStatus;
import agent.interfaces.Gantry;
/**
* Gantry delivers parts to the feeder
* @author Arjun Bhargava
*/
public class GantryAgent extends Agent implements Gantry {
public List<Bin> binList = new ArrayList<Bin>();
public List<MyFeeder> feeders = new ArrayList<MyFeeder>();
// WAITING FOR GANTRYGRAPHICS
private GantryGraphics GUIGantry;
private final String name;
private boolean waitForDrop = false;
public class MyFeeder {
public FeederAgent feeder;
public PartType requestedType;
public MyFeeder(FeederAgent feeder) {
this.feeder = feeder;
}
public MyFeeder(FeederAgent feeder, PartType type) {
this.feeder = feeder;
this.requestedType = type;
}
public FeederAgent getFeeder() {
return feeder;
}
public PartType getRequestedType() {
return requestedType;
}
}
public Semaphore animation = new Semaphore(0, true);
public GantryAgent(String name) {
super();
this.name = name;
print("I'm working");
}
@Override
public void msgHereIsBin(Bin bin) {
print("Received msgHereIsBinConfig");
binList.add(bin);
stateChanged();
}
@Override
public void msgINeedParts(PartType type, FeederAgent feeder) {
print("Received msgINeedParts");
boolean temp = true;
for(MyFeeder currentFeeder : feeders) {
if(currentFeeder.getFeeder() == feeder) {
currentFeeder.requestedType = type;
temp = false;
break;
}
}
if(temp == true) {
feeders.add(new MyFeeder(feeder, type));
}
stateChanged();
}
@Override
public void msgReceiveBinDone(Bin bin) {
print("Received msgReceiveBinDone from graphics");
bin.binState = BinStatus.OVER_FEEDER;
animation.release();
stateChanged();
}
@Override
public void msgDropBinDone(Bin bin) {
print("Received msgdropBingDone from graphics");
bin.binState = BinStatus.EMPTY;
animation.release();
waitForDrop = false;
stateChanged();
}
@Override
public void msgRemoveBinDone(Bin bin) {
print("Received msgremoveBinDone from graphics");
binList.remove(bin);
animation.release();
stateChanged();
}
//SCHEDULER
@Override
public boolean pickAndExecuteAnAction() {
for(Bin bin:binList) {
if(bin.binState==BinStatus.PENDING){
addBinToGraphics(bin);
return true;
}
}
// TODO Auto-generated method stub
if(waitForDrop == false) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString()) && bin.binState == BinStatus.FULL) {
print("Moving to feeder");
moveToFeeder(bin, currentFeeder.getFeeder());
return true;
}
}
}
}
if(waitForDrop == true) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
- if (bin.part.type == currentFeeder.getRequestedType()
+ if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString())
&& bin.binState == BinStatus.OVER_FEEDER) {
fillFeeder(bin, currentFeeder.getFeeder());
return true;
}
}
}
}
if(waitForDrop == false) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
- if (bin.part.type == currentFeeder.getRequestedType()
+ if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString())
&& bin.binState == BinStatus.EMPTY) {
discardBin(bin);
return true;
}
}
}
}
print("I'm returning false");
return false;
}
//ACTIONS
@Override
public void moveToFeeder(Bin bin, FeederAgent feeder) {
print("Moving bin to over feeder");
bin.binState = BinStatus.MOVING;
GUIGantry.receiveBin(bin, feeder);
waitForDrop = true;
try {
animation.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stateChanged();
}
@Override
public void fillFeeder(Bin bin, FeederAgent feeder) {
print("Placing bin in feeder and filling feeder");
GUIGantry.dropBin(bin, feeder);
try {
animation.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
feeder.msgHereAreParts(bin.part.type, bin);
bin.binState = BinStatus.FILLING_FEEDER;
stateChanged();
}
@Override
public void discardBin(Bin bin) {
print("Discarding bin");
bin.binState = BinStatus.DISCARDING;
GUIGantry.removeBin(bin);
try {
animation.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stateChanged();
}
@Override
public String getName() {
return name;
}
@Override
public void setGraphicalRepresentation(DeviceGraphics dg) {
}
public void addBinToGraphics(Bin bin){
if(GUIGantry!=null){
GUIGantry.hereIsNewBin(bin);
}
bin.binState=BinStatus.FULL;
stateChanged();
}
}
| false | true | public boolean pickAndExecuteAnAction() {
for(Bin bin:binList) {
if(bin.binState==BinStatus.PENDING){
addBinToGraphics(bin);
return true;
}
}
// TODO Auto-generated method stub
if(waitForDrop == false) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString()) && bin.binState == BinStatus.FULL) {
print("Moving to feeder");
moveToFeeder(bin, currentFeeder.getFeeder());
return true;
}
}
}
}
if(waitForDrop == true) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type == currentFeeder.getRequestedType()
&& bin.binState == BinStatus.OVER_FEEDER) {
fillFeeder(bin, currentFeeder.getFeeder());
return true;
}
}
}
}
if(waitForDrop == false) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type == currentFeeder.getRequestedType()
&& bin.binState == BinStatus.EMPTY) {
discardBin(bin);
return true;
}
}
}
}
print("I'm returning false");
return false;
}
| public boolean pickAndExecuteAnAction() {
for(Bin bin:binList) {
if(bin.binState==BinStatus.PENDING){
addBinToGraphics(bin);
return true;
}
}
// TODO Auto-generated method stub
if(waitForDrop == false) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString()) && bin.binState == BinStatus.FULL) {
print("Moving to feeder");
moveToFeeder(bin, currentFeeder.getFeeder());
return true;
}
}
}
}
if(waitForDrop == true) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString())
&& bin.binState == BinStatus.OVER_FEEDER) {
fillFeeder(bin, currentFeeder.getFeeder());
return true;
}
}
}
}
if(waitForDrop == false) {
for (MyFeeder currentFeeder : feeders) {
for (Bin bin : binList) {
if (bin.part.type.toString().equals(currentFeeder.getRequestedType().toString())
&& bin.binState == BinStatus.EMPTY) {
discardBin(bin);
return true;
}
}
}
}
print("I'm returning false");
return false;
}
|
diff --git a/src/nz/gen/wellington/guardian/android/activities/ArticleListActivity.java b/src/nz/gen/wellington/guardian/android/activities/ArticleListActivity.java
index f5f44ef..5207dc5 100644
--- a/src/nz/gen/wellington/guardian/android/activities/ArticleListActivity.java
+++ b/src/nz/gen/wellington/guardian/android/activities/ArticleListActivity.java
@@ -1,579 +1,579 @@
package nz.gen.wellington.guardian.android.activities;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nz.gen.wellington.guardian.android.R;
import nz.gen.wellington.guardian.android.activities.ui.ArticleClicker;
import nz.gen.wellington.guardian.android.activities.ui.ClickerPopulatingService;
import nz.gen.wellington.guardian.android.activities.ui.TagListPopulatingService;
import nz.gen.wellington.guardian.android.api.ArticleDAO;
import nz.gen.wellington.guardian.android.api.ContentFetchType;
import nz.gen.wellington.guardian.android.api.ImageDAO;
import nz.gen.wellington.guardian.android.factories.ArticleSetFactory;
import nz.gen.wellington.guardian.android.factories.SingletonFactory;
import nz.gen.wellington.guardian.android.model.Article;
import nz.gen.wellington.guardian.android.model.ArticleBundle;
import nz.gen.wellington.guardian.android.model.ArticleSet;
import nz.gen.wellington.guardian.android.model.ColourScheme;
import nz.gen.wellington.guardian.android.model.Section;
import nz.gen.wellington.guardian.android.model.SectionColourMap;
import nz.gen.wellington.guardian.android.network.NetworkStatusService;
import nz.gen.wellington.guardian.android.usersettings.PreferencesDAO;
import nz.gen.wellington.guardian.android.utils.DateTimeHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public abstract class ArticleListActivity extends DownloadProgressAwareActivity implements FontResizingActivity {
private static final String TAG = "ArticleListActivity";
protected ArticleDAO articleDAO;
protected ImageDAO imageDAO;
private NetworkStatusService networkStatusService;
private PreferencesDAO preferencesDAO;
private UpdateArticlesHandler updateArticlesHandler;
private UpdateArticlesRunner updateArticlesRunner;
private ArticleBundle bundle;
private Map<String, View> viewsWaitingForTrailImages;
boolean showSeperators = false;
boolean showMainImage = true;
private Thread loader;
private Date loaded;
private int baseSize;
protected String[] permittedRefinements = {"keyword"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewsWaitingForTrailImages = new HashMap<String, View>();
articleDAO = SingletonFactory.getDao(this.getApplicationContext());
imageDAO = SingletonFactory.getImageDao(this.getApplicationContext());
networkStatusService = new NetworkStatusService(this);
preferencesDAO = SingletonFactory.getPreferencesDAO(this.getApplicationContext());
}
@Override
protected void onStart() {
super.onStart();
LinearLayout mainPane = (LinearLayout) findViewById(R.id.MainPane);
boolean mainPaneNeedsPopulating = shouldRefreshView(mainPane);
if (mainPaneNeedsPopulating) {
populateArticles(ContentFetchType.NORMAL, preferencesDAO.getBaseFontSize());
}
}
@Override
protected void onResume() {
super.onResume();
baseSize = preferencesDAO.getBaseFontSize();
setFontSize(baseSize);
View view = findViewById(R.id.Main);
if (view != null) {
view.setBackgroundColor(ColourScheme.BACKGROUND);
}
}
@Override
public void setFontSize(int baseSize) {
TextView description = (TextView) findViewById(R.id.Description);
if (description != null) {
description.setTextSize(TypedValue.COMPLEX_UNIT_PT, baseSize);
description.setTextColor(ColourScheme.BODYTEXT);
}
}
protected void refresh() {
populateArticles(ContentFetchType.CHECKSUM, preferencesDAO.getBaseFontSize());
}
protected int getPageSize() {
return preferencesDAO.getPageSizePreference();
}
private void populateArticles(ContentFetchType fetchType, int baseFontSize) {
Log.i(TAG, "Refresh requested");
if (!networkStatusService.isConnectionAvailable() && ContentFetchType.CHECKSUM.equals(fetchType)) { // TODO knowledge of connections requirements should be on the fetch type.
Log.i(TAG, "Not refreshing uncached as no connection is available");
return;
}
LinearLayout mainPane = (LinearLayout) findViewById(R.id.MainPane);
if (loader == null || !loader.isAlive()) {
mainPane.removeAllViews();
final ArticleSet articleSet = getArticleSet();
updateArticlesHandler = new UpdateArticlesHandler(this, articleSet, baseFontSize);
updateArticlesRunner = new UpdateArticlesRunner(articleDAO, imageDAO, networkStatusService, fetchType, articleSet);
updateArticlesHandler.init();
loader = new Thread(updateArticlesRunner);
loader.start();
}
}
@Override
protected void onPause() {
super.onPause();
if (updateArticlesHandler != null) {
updateArticlesRunner.stop();
}
}
private boolean shouldRefreshView(LinearLayout mainPane) {
if (loaded == null || mainPane.getChildCount() == 0) {
return true;
}
Date modtime = SingletonFactory.getDao(this.getApplicationContext()).getModificationTime(getArticleSet());
return modtime != null && modtime.after(loaded);
}
private ArticleBundle loadArticles(ContentFetchType fetchType, ArticleSet articleSet) {
if (articleSet != null) {
return articleDAO.getArticleSetArticles(articleSet, fetchType);
}
return null;
}
protected abstract ArticleSet getArticleSet();
protected abstract String getRefinementDescription(String refinementType);
class UpdateArticlesHandler extends Handler {
private static final int ARTICLE_READY = 1;
private static final int TRAIL_IMAGE_IS_AVAILABLE_FOR_ARTICLE = 3;
private static final int DESCRIPTION_TEXT_READY = 6;
private static final int DRAW_REFINEMENTS = 4;
private static final int SHOW_ARTICLE_SET_OUT_OF_DATE_WARNING = 5;
public static final int NO_ARTICLES = 2;
private Context context;
boolean first = true;
boolean isFirstOfSection;
Section currentSection;
private ArticleSet articleSet;
private boolean descriptionSet;
private int baseFontSize;
private ArticleSetFactory articleSetFactory;
public UpdateArticlesHandler(Context context, ArticleSet articleSet, int baseFontSize) {
super();
this.articleSetFactory = SingletonFactory.getArticleSetFactory(context);
this.context = context;
this.articleSet = articleSet;
this.descriptionSet = false;
this.baseFontSize = baseFontSize;
init();
}
public void init() {
first = true;
isFirstOfSection = false;
currentSection = null;
descriptionSet = false;
}
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ARTICLE_READY:
Article article = (Article) msg.getData().getSerializable("article");
LayoutInflater mInflater = LayoutInflater.from(context);
LinearLayout mainpane = (LinearLayout) findViewById(R.id.MainPane);
if (showSeperators) {
if (article.getSection() != null) {
if (currentSection == null || !currentSection.getId().equals(article.getSection().getId())) {
isFirstOfSection = true;
}
}
if (isFirstOfSection) {
addSeperator(mInflater, mainpane, article.getSection());
currentSection = article.getSection();
isFirstOfSection = false;
}
}
// TODO should base this decision on the articles set's tags
boolean isContributorArticleSet = false; // TODO articleSet.getApiUrl().startsWith("profile");
boolean shouldUseFeatureTrail = showMainImage && first && !isContributorArticleSet && article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl());
View articleTrailView = chooseTrailView(mInflater, shouldUseFeatureTrail);
populateArticleListView(article, articleTrailView, shouldUseFeatureTrail);
mainpane.addView(articleTrailView);
first = false;
return;
case TRAIL_IMAGE_IS_AVAILABLE_FOR_ARTICLE:
Bundle data = msg.getData();
if (data.containsKey("id")) {
final String id = data.getString("id");
final String url = data.getString("url");
if( viewsWaitingForTrailImages.containsKey(id)) {
View view = viewsWaitingForTrailImages.get(id);
populateTrailImage(url, view);
viewsWaitingForTrailImages.remove(id);
}
}
return;
case DESCRIPTION_TEXT_READY:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
Bundle descriptionData = msg.getData();
String descripton = descriptionData.getString("description");
if (descripton != null && !descriptionSet) {
populateTagDescription(mainpane, descripton, baseFontSize);
}
return;
case DRAW_REFINEMENTS:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
Map<String, List<ArticleSet>> refinements = bundle.getRefinements();
if (refinements != null && !refinements.isEmpty()) {
LayoutInflater inflater = LayoutInflater.from(context);
for (String refinementType : articleSet.getPermittedRefinements()) {
if (articleSet.getPermittedRefinements().contains(refinementType) && refinements.keySet().contains(refinementType)) {
String description = getRefinementDescription(refinementType);
populateRefinementType(mainpane, inflater, description, refinements.get(refinementType));
}
}
}
return;
case SHOW_ARTICLE_SET_OUT_OF_DATE_WARNING:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
TextView message = new TextView(context);
if (networkStatusService.isConnectionAvailable()) {
message.setText("This article set was last downloaded more than 2 hours ago. Refresh to check for updates.");
} else {
message.setText("This article set was last downloaded more than 2 hours ago and may be out of date.");
}
message.setTextColor(ColourScheme.STATUS);
message.setPadding(2, 3, 2, 3);
mainpane.addView(message, 0);
return;
case NO_ARTICLES:
Log.i(TAG, "Displaying no articles available message");
mainpane = (LinearLayout) findViewById(R.id.MainPane);
TextView noArticlesMessage = new TextView(context);
- noArticlesMessage.setTextSize(baseFontSize + 10, TypedValue.COMPLEX_UNIT_PT);
noArticlesMessage.setText("No articles available.");
+ noArticlesMessage.setTextSize(TypedValue.COMPLEX_UNIT_PT, baseFontSize);
noArticlesMessage.setTextColor(ColourScheme.HEADLINE);
noArticlesMessage.setPadding(2, 3, 2, 3);
mainpane.addView(noArticlesMessage, 0);
return;
}
}
private void populateTagDescription(LinearLayout mainpane, String descripton, int fontSize) {
// TODO move to the layout file
TextView descriptionView = new TextView(context);
descriptionView.setId(R.id.Description);
descriptionView.setText(descripton);
descriptionView.setPadding(2, 3, 2, 15);
mainpane.addView(descriptionView, 0);
descriptionView.setTextSize(TypedValue.COMPLEX_UNIT_PT, fontSize); // TODO duplicated setting code
descriptionView.setLineSpacing(new Float(0), new Float(1.1));
descriptionView.setTextColor(ColourScheme.BODYTEXT);
descriptionView.setPadding(2, 3, 2, 3);
descriptionSet = true;
}
private void populateRefinementType(LinearLayout mainpane, LayoutInflater inflater, String description, List<ArticleSet> typedRefinements) {
View refinementsHeadingView = inflater.inflate(R.layout.refinements, null);
TextView descriptionView = (TextView) refinementsHeadingView.findViewById(R.id.RefinementsDescription);
descriptionView.setText(description);
descriptionView.setTextColor(ColourScheme.BODYTEXT);
descriptionView.setPadding(2, 3, 2, 3);
mainpane.addView(refinementsHeadingView);
// TODO move to a layout
LinearLayout tagGroup = new LinearLayout(context);
tagGroup.setOrientation(LinearLayout.VERTICAL);
tagGroup.setPadding(2, 0, 2, 0);
TagListPopulatingService.populateTags(inflater, true, tagGroup, typedRefinements, context);
mainpane.addView(tagGroup);
}
private void populateTrailImage(final String url, View view) {
ImageView trialImage = (ImageView) view.findViewById(R.id.TrailImage);
Bitmap image = imageDAO.getImage(url);
trialImage.setImageBitmap(image);
trialImage.setVisibility(View.VISIBLE);
}
private void addSeperator(LayoutInflater mInflater, LinearLayout mainpane, Section section) {
View seperator = mInflater.inflate(R.layout.seperator, null);
final String colourForSection = SectionColourMap.getColourForSection(section.getId());
if (colourForSection != null) {
seperator.setBackgroundColor(Color.parseColor(colourForSection));
TextView heading = (TextView) seperator.findViewById(R.id.TagName);
heading.setText(section.getName());
ArticleSet articleSetForSection = articleSetFactory.getArticleSetForSection(section);
boolean contentIsAvailable = articleDAO.isAvailable(articleSetForSection);
ClickerPopulatingService.populateClicker(articleSetForSection, seperator, contentIsAvailable);
mainpane.addView(seperator);
} else {
Log.w(TAG, "Could not find section colour for section: " + section.getId());
}
}
private View chooseTrailView(LayoutInflater mInflater, boolean shouldUseFeatureTrail) {
View view;
if (shouldUseFeatureTrail) {
view = mInflater.inflate(R.layout.featurelist, null);
} else {
view = mInflater.inflate(R.layout.list, null);
}
return view;
}
private void populateArticleListView(Article article, View view, boolean shouldUseFeatureTrail) {
TextView titleText = (TextView) view.findViewById(R.id.Headline);
TextView pubDateText = (TextView) view.findViewById(R.id.Pubdate);
TextView standfirst = (TextView) view.findViewById(R.id.Standfirst);
TextView caption = (TextView) view.findViewById(R.id.Caption);
titleText.setTextColor(ColourScheme.HEADLINE);
pubDateText.setTextColor(ColourScheme.BODYTEXT);
standfirst.setTextColor(ColourScheme.BODYTEXT);
titleText.setTextSize(TypedValue.COMPLEX_UNIT_PT, baseSize);
pubDateText.setTextSize(TypedValue.COMPLEX_UNIT_PT, baseSize -2);
standfirst.setTextSize(TypedValue.COMPLEX_UNIT_PT, new Float(baseSize - 0.75));
if (caption != null) {
caption.setTextColor(ColourScheme.BODYTEXT);
}
titleText.setText(article.getTitle());
if (article.getPubDate() != null) {
pubDateText.setText(article.getPubDateString());
}
if (article.getStandfirst() != null) {
standfirst.setText(article.getStandfirst());
}
if (caption != null && article.getCaption() != null) {
caption.setText(article.getCaption());
caption.setVisibility(View.VISIBLE);
}
String trailImageUrl = article.getThumbnailUrl();
if (shouldUseFeatureTrail) {
trailImageUrl = article.getMainImageUrl();
}
if (trailImageUrl != null) {
if (imageDAO.isAvailableLocally(trailImageUrl)) {
populateTrailImage(trailImageUrl, view);
} else {
viewsWaitingForTrailImages.put(article.getId(), view);
}
}
ArticleClicker urlListener = new ArticleClicker(article);
view.setOnClickListener(urlListener);
}
}
private void sendArticleReadyMessage(Article article) {
Message m = new Message();
m.what = UpdateArticlesHandler.ARTICLE_READY;
Bundle bundle = new Bundle();
bundle.putSerializable("article", article);
m.setData(bundle);
updateArticlesHandler.sendMessage(m);
}
private void sendDescriptionReadyMessage(String description) {
Message m = new Message();
m.what = UpdateArticlesHandler.DESCRIPTION_TEXT_READY;
Bundle bundle = new Bundle();
bundle.putString("description", description);
m.setData(bundle);
updateArticlesHandler.sendMessage(m);
}
class UpdateArticlesRunner implements Runnable, ArticleCallback {
boolean running;
ArticleDAO articleDAO;
ImageDAO imageDAO;
NetworkStatusService networkStatusService;
ContentFetchType fetchType;
private ArticleSet articleSet;
public UpdateArticlesRunner(ArticleDAO articleDAO, ImageDAO imageDAO, NetworkStatusService networkStatusService, ContentFetchType fetchType, ArticleSet articleSet) {
this.articleDAO = articleDAO;
this.imageDAO = imageDAO;
this.running = true;
this.networkStatusService = networkStatusService;
articleDAO.setArticleReadyCallback(this);
this.fetchType = fetchType;
this.articleSet = articleSet;
}
public void run() {
if (running) {
bundle = loadArticles(fetchType, articleSet);
}
if (bundle == null) {
Log.i(TAG, "Article bundle was null");
Message m = new Message();
m.what = UpdateArticlesHandler.NO_ARTICLES;
updateArticlesHandler.sendMessage(m);
return;
}
if (bundle.getDescription() != null) {
sendDescriptionReadyMessage(bundle.getDescription());
}
Message m = new Message();
m.what = UpdateArticlesHandler.DRAW_REFINEMENTS;
updateArticlesHandler.sendMessage(m);
List<Article> downloadTrailImages = new LinkedList<Article>();
boolean first = true;
for (Article article : bundle.getArticles()) {
String imageUrl;
boolean mainImageIsAvailableLocally = article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl());
if (first && mainImageIsAvailableLocally) {
imageUrl = article.getMainImageUrl();
} else {
imageUrl = article.getThumbnailUrl();
}
if (imageUrl != null) {
if (imageDAO.isAvailableLocally(imageUrl)) {
m = new Message();
m.what = UpdateArticlesHandler.TRAIL_IMAGE_IS_AVAILABLE_FOR_ARTICLE;
Bundle bundle = new Bundle();
bundle.putString("id", article.getId());
bundle.putString("url", imageUrl);
m.setData(bundle);
updateArticlesHandler.sendMessage(m);
} else {
downloadTrailImages.add(article);
}
}
first = false;
}
if (running) {
for (Article article : downloadTrailImages) {
imageDAO.getImage(article.getThumbnailUrl());
m = new Message();
m.what = UpdateArticlesHandler.TRAIL_IMAGE_IS_AVAILABLE_FOR_ARTICLE;
Bundle bundle = new Bundle();
bundle.putString("id", article.getId());
bundle.putString("url", article.getThumbnailUrl());
m.setData(bundle);
updateArticlesHandler.sendMessage(m);
}
}
if (bundle != null) {
Date modificationTime = articleDAO.getModificationTime(articleSet);
if (modificationTime != null && DateTimeHelper.isMoreThanHoursOld(modificationTime, 2)) {
m = new Message();
m.what = UpdateArticlesHandler.SHOW_ARTICLE_SET_OUT_OF_DATE_WARNING;
Bundle bundle = new Bundle();
bundle.putString("modtime", modificationTime.toString());
m.setData(bundle);
updateArticlesHandler.sendMessage(m);
}
}
loaded = DateTimeHelper.now();
return;
}
public void stop() {
this.running = false;
articleDAO.stopLoading();
}
@Override
public void articleReady(Article article) {
sendArticleReadyMessage(article);
}
@Override
public void descriptionReady(String description) {
sendDescriptionReadyMessage(description);
}
}
}
| false | true | public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ARTICLE_READY:
Article article = (Article) msg.getData().getSerializable("article");
LayoutInflater mInflater = LayoutInflater.from(context);
LinearLayout mainpane = (LinearLayout) findViewById(R.id.MainPane);
if (showSeperators) {
if (article.getSection() != null) {
if (currentSection == null || !currentSection.getId().equals(article.getSection().getId())) {
isFirstOfSection = true;
}
}
if (isFirstOfSection) {
addSeperator(mInflater, mainpane, article.getSection());
currentSection = article.getSection();
isFirstOfSection = false;
}
}
// TODO should base this decision on the articles set's tags
boolean isContributorArticleSet = false; // TODO articleSet.getApiUrl().startsWith("profile");
boolean shouldUseFeatureTrail = showMainImage && first && !isContributorArticleSet && article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl());
View articleTrailView = chooseTrailView(mInflater, shouldUseFeatureTrail);
populateArticleListView(article, articleTrailView, shouldUseFeatureTrail);
mainpane.addView(articleTrailView);
first = false;
return;
case TRAIL_IMAGE_IS_AVAILABLE_FOR_ARTICLE:
Bundle data = msg.getData();
if (data.containsKey("id")) {
final String id = data.getString("id");
final String url = data.getString("url");
if( viewsWaitingForTrailImages.containsKey(id)) {
View view = viewsWaitingForTrailImages.get(id);
populateTrailImage(url, view);
viewsWaitingForTrailImages.remove(id);
}
}
return;
case DESCRIPTION_TEXT_READY:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
Bundle descriptionData = msg.getData();
String descripton = descriptionData.getString("description");
if (descripton != null && !descriptionSet) {
populateTagDescription(mainpane, descripton, baseFontSize);
}
return;
case DRAW_REFINEMENTS:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
Map<String, List<ArticleSet>> refinements = bundle.getRefinements();
if (refinements != null && !refinements.isEmpty()) {
LayoutInflater inflater = LayoutInflater.from(context);
for (String refinementType : articleSet.getPermittedRefinements()) {
if (articleSet.getPermittedRefinements().contains(refinementType) && refinements.keySet().contains(refinementType)) {
String description = getRefinementDescription(refinementType);
populateRefinementType(mainpane, inflater, description, refinements.get(refinementType));
}
}
}
return;
case SHOW_ARTICLE_SET_OUT_OF_DATE_WARNING:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
TextView message = new TextView(context);
if (networkStatusService.isConnectionAvailable()) {
message.setText("This article set was last downloaded more than 2 hours ago. Refresh to check for updates.");
} else {
message.setText("This article set was last downloaded more than 2 hours ago and may be out of date.");
}
message.setTextColor(ColourScheme.STATUS);
message.setPadding(2, 3, 2, 3);
mainpane.addView(message, 0);
return;
case NO_ARTICLES:
Log.i(TAG, "Displaying no articles available message");
mainpane = (LinearLayout) findViewById(R.id.MainPane);
TextView noArticlesMessage = new TextView(context);
noArticlesMessage.setTextSize(baseFontSize + 10, TypedValue.COMPLEX_UNIT_PT);
noArticlesMessage.setText("No articles available.");
noArticlesMessage.setTextColor(ColourScheme.HEADLINE);
noArticlesMessage.setPadding(2, 3, 2, 3);
mainpane.addView(noArticlesMessage, 0);
return;
}
}
| public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ARTICLE_READY:
Article article = (Article) msg.getData().getSerializable("article");
LayoutInflater mInflater = LayoutInflater.from(context);
LinearLayout mainpane = (LinearLayout) findViewById(R.id.MainPane);
if (showSeperators) {
if (article.getSection() != null) {
if (currentSection == null || !currentSection.getId().equals(article.getSection().getId())) {
isFirstOfSection = true;
}
}
if (isFirstOfSection) {
addSeperator(mInflater, mainpane, article.getSection());
currentSection = article.getSection();
isFirstOfSection = false;
}
}
// TODO should base this decision on the articles set's tags
boolean isContributorArticleSet = false; // TODO articleSet.getApiUrl().startsWith("profile");
boolean shouldUseFeatureTrail = showMainImage && first && !isContributorArticleSet && article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl());
View articleTrailView = chooseTrailView(mInflater, shouldUseFeatureTrail);
populateArticleListView(article, articleTrailView, shouldUseFeatureTrail);
mainpane.addView(articleTrailView);
first = false;
return;
case TRAIL_IMAGE_IS_AVAILABLE_FOR_ARTICLE:
Bundle data = msg.getData();
if (data.containsKey("id")) {
final String id = data.getString("id");
final String url = data.getString("url");
if( viewsWaitingForTrailImages.containsKey(id)) {
View view = viewsWaitingForTrailImages.get(id);
populateTrailImage(url, view);
viewsWaitingForTrailImages.remove(id);
}
}
return;
case DESCRIPTION_TEXT_READY:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
Bundle descriptionData = msg.getData();
String descripton = descriptionData.getString("description");
if (descripton != null && !descriptionSet) {
populateTagDescription(mainpane, descripton, baseFontSize);
}
return;
case DRAW_REFINEMENTS:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
Map<String, List<ArticleSet>> refinements = bundle.getRefinements();
if (refinements != null && !refinements.isEmpty()) {
LayoutInflater inflater = LayoutInflater.from(context);
for (String refinementType : articleSet.getPermittedRefinements()) {
if (articleSet.getPermittedRefinements().contains(refinementType) && refinements.keySet().contains(refinementType)) {
String description = getRefinementDescription(refinementType);
populateRefinementType(mainpane, inflater, description, refinements.get(refinementType));
}
}
}
return;
case SHOW_ARTICLE_SET_OUT_OF_DATE_WARNING:
mainpane = (LinearLayout) findViewById(R.id.MainPane);
TextView message = new TextView(context);
if (networkStatusService.isConnectionAvailable()) {
message.setText("This article set was last downloaded more than 2 hours ago. Refresh to check for updates.");
} else {
message.setText("This article set was last downloaded more than 2 hours ago and may be out of date.");
}
message.setTextColor(ColourScheme.STATUS);
message.setPadding(2, 3, 2, 3);
mainpane.addView(message, 0);
return;
case NO_ARTICLES:
Log.i(TAG, "Displaying no articles available message");
mainpane = (LinearLayout) findViewById(R.id.MainPane);
TextView noArticlesMessage = new TextView(context);
noArticlesMessage.setText("No articles available.");
noArticlesMessage.setTextSize(TypedValue.COMPLEX_UNIT_PT, baseFontSize);
noArticlesMessage.setTextColor(ColourScheme.HEADLINE);
noArticlesMessage.setPadding(2, 3, 2, 3);
mainpane.addView(noArticlesMessage, 0);
return;
}
}
|
diff --git a/JavaLib/src/com/punchline/javalib/entities/systems/physical/ParticleSystem.java b/JavaLib/src/com/punchline/javalib/entities/systems/physical/ParticleSystem.java
index ba7654f..7165800 100644
--- a/JavaLib/src/com/punchline/javalib/entities/systems/physical/ParticleSystem.java
+++ b/JavaLib/src/com/punchline/javalib/entities/systems/physical/ParticleSystem.java
@@ -1,83 +1,83 @@
/**
*
*/
package com.punchline.javalib.entities.systems.physical;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
import com.punchline.javalib.entities.Entity;
import com.punchline.javalib.entities.components.physical.Collidable;
import com.punchline.javalib.entities.components.physical.Particle;
import com.punchline.javalib.entities.systems.ComponentSystem;
/**
* The particle system which updates the position of particles
* @author William
* @created Jul 23, 2013
*/
public class ParticleSystem extends ComponentSystem {
/**
* Initializes the particle system for particle components.
*/
public ParticleSystem(){
super(Particle.class);
}
/** {@inheritDoc}
* @see com.badlogic.gdx.utils.Disposable#dispose()
*/
@Override
public void dispose() {
}
/** {@inheritDoc}
* @see com.punchline.javalib.entities.EntitySystem#process(com.punchline.javalib.entities.Entity)
*/
@Override
protected void process(Entity e) {
Particle p = e.getComponent();
//Move the particle
Vector2 pos = p.getPosition().cpy();
Vector2 deltaX = new Vector2(p.getLinearVelocity().x * deltaSeconds(), p.getLinearVelocity().y * deltaSeconds());
//DO RAY CASTING FOR COLLIDABLE CHECK
if(e.hasComponent(Collidable.class)){
com.badlogic.gdx.physics.box2d.World c = World.getPhysicsWorld();
- //Perform the raycast.
+ //Perform the raycast
c.rayCast(new RayCastCallback(){
Entity e;
public RayCastCallback init(Entity e){
this.e = e;
return this;
}
@Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
//If collision occurs
Collidable col = e.getComponent();
//Get the victim
Entity victim = (Entity)fixture.getBody().getUserData();
//Call the on collide event for the entity and terminate if appropriate.
return col.onCollide(e, victim);
}
}.init(e),
pos, pos.cpy().add(deltaX));
}
//Move and set the final position of the entity.
pos.add(deltaX);
p.setPosition(pos);
float angularVelocity = p.getAngularVelocity() * deltaSeconds();
p.setRotation(p.getRotation() + angularVelocity);
}
}
| true | true | protected void process(Entity e) {
Particle p = e.getComponent();
//Move the particle
Vector2 pos = p.getPosition().cpy();
Vector2 deltaX = new Vector2(p.getLinearVelocity().x * deltaSeconds(), p.getLinearVelocity().y * deltaSeconds());
//DO RAY CASTING FOR COLLIDABLE CHECK
if(e.hasComponent(Collidable.class)){
com.badlogic.gdx.physics.box2d.World c = World.getPhysicsWorld();
//Perform the raycast.
c.rayCast(new RayCastCallback(){
Entity e;
public RayCastCallback init(Entity e){
this.e = e;
return this;
}
@Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
//If collision occurs
Collidable col = e.getComponent();
//Get the victim
Entity victim = (Entity)fixture.getBody().getUserData();
//Call the on collide event for the entity and terminate if appropriate.
return col.onCollide(e, victim);
}
}.init(e),
pos, pos.cpy().add(deltaX));
}
//Move and set the final position of the entity.
pos.add(deltaX);
p.setPosition(pos);
float angularVelocity = p.getAngularVelocity() * deltaSeconds();
p.setRotation(p.getRotation() + angularVelocity);
}
| protected void process(Entity e) {
Particle p = e.getComponent();
//Move the particle
Vector2 pos = p.getPosition().cpy();
Vector2 deltaX = new Vector2(p.getLinearVelocity().x * deltaSeconds(), p.getLinearVelocity().y * deltaSeconds());
//DO RAY CASTING FOR COLLIDABLE CHECK
if(e.hasComponent(Collidable.class)){
com.badlogic.gdx.physics.box2d.World c = World.getPhysicsWorld();
//Perform the raycast
c.rayCast(new RayCastCallback(){
Entity e;
public RayCastCallback init(Entity e){
this.e = e;
return this;
}
@Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
//If collision occurs
Collidable col = e.getComponent();
//Get the victim
Entity victim = (Entity)fixture.getBody().getUserData();
//Call the on collide event for the entity and terminate if appropriate.
return col.onCollide(e, victim);
}
}.init(e),
pos, pos.cpy().add(deltaX));
}
//Move and set the final position of the entity.
pos.add(deltaX);
p.setPosition(pos);
float angularVelocity = p.getAngularVelocity() * deltaSeconds();
p.setRotation(p.getRotation() + angularVelocity);
}
|
diff --git a/core/src/main/java/net/tirasa/hct/repository/HCTQuery.java b/core/src/main/java/net/tirasa/hct/repository/HCTQuery.java
index 4b9654e..8be105c 100644
--- a/core/src/main/java/net/tirasa/hct/repository/HCTQuery.java
+++ b/core/src/main/java/net/tirasa/hct/repository/HCTQuery.java
@@ -1,395 +1,395 @@
/*
* 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 net.tirasa.hct.repository;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.Query;
import javax.jcr.query.RowIterator;
import net.tirasa.hct.cocoon.sax.Constants;
import net.tirasa.hct.cocoon.sax.Constants.Availability;
import org.apache.jackrabbit.JcrConstants;
import org.hippoecm.repository.HippoStdNodeType;
import org.hippoecm.repository.api.HippoNodeType;
import org.hippoecm.repository.translation.HippoTranslationNodeType;
import org.onehippo.taxonomy.api.TaxonomyNodeTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HCTQuery extends AbstractHCTEntity {
public enum Type {
DOCS,
FOLDERS,
TAXONOMY_DOCS,
TAXONOMIES
}
private static final Logger LOG = LoggerFactory.getLogger(HCTQuery.class);
private String base;
private transient String returnType;
private int depth;
private long page;
private long size;
private final transient Set<String> returnFields;
private boolean returnTags = false;
private boolean returnTaxonomies = false;
private boolean returnImages = false;
private boolean returnRelatedDocs = false;
private boolean includeFolders = false;
private final transient HCTQueryFilter filter;
private final transient StringBuilder orderBy;
private transient String sqlQuery;
private final transient Map<String, String> taxonomies;
private final transient Session session;
public HCTQuery(final Session session) {
super();
this.session = session;
returnFields = new HashSet<String>();
filter = new HCTQueryFilter();
orderBy = new StringBuilder();
taxonomies = new HashMap<String, String>();
}
public String getBase() {
return base;
}
public void setBase(final String base) {
this.base = base;
}
public int getDepth() {
return depth;
}
public void setDepth(final int depth) {
this.depth = depth;
}
public boolean isIncludeFolders() {
return includeFolders;
}
public void setIncludeFolders(final boolean includeFolders) {
this.includeFolders = includeFolders;
}
public long getPage() {
return page;
}
public void setPage(final long page) {
this.page = page;
}
public boolean isReturnTags() {
return returnTags;
}
public void setReturnTags(final boolean returnTags) {
this.returnTags = returnTags;
}
public boolean isReturnTaxonomies() {
return returnTaxonomies;
}
public void setReturnTaxonomies(final boolean returnTaxonomies) {
this.returnTaxonomies = returnTaxonomies;
}
public boolean isReturnImages() {
return returnImages;
}
public void setReturnImages(final boolean returnImages) {
this.returnImages = returnImages;
}
public boolean isReturnRelatedDocs() {
return returnRelatedDocs;
}
public void setReturnRelatedDocs(final boolean returnRelatedDocs) {
this.returnRelatedDocs = returnRelatedDocs;
}
public long getSize() {
return size;
}
public void setSize(final long size) {
this.size = size;
}
public String getReturnType() {
return returnType;
}
public void setReturnType(final String returnType) {
this.returnType = returnType;
}
public Set<String> getReturnFields() {
return returnFields;
}
public boolean addReturnField(final String returnField) {
return returnField != null && returnFields.add(returnField);
}
public boolean removeReturnField(final String returnField) {
return returnField != null && returnFields.remove(returnField);
}
public HCTQueryFilter getFilter() {
return filter;
}
public void addOrderByAscending(final String propertyName) {
orderBy.append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').append(propertyName).append(']').
append(" ASC, ");
}
public void addOrderByDescending(final String propertyName) {
orderBy.append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').append(propertyName).append(']').
append(" DESC, ");
}
public Type getType() {
return returnType == null || base == null
? null
: HippoStdNodeType.NT_FOLDER.equals(returnType)
? Type.FOLDERS
: TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY.equals(returnType)
? Type.TAXONOMIES
: base.startsWith("/content/taxonomies")
? Type.TAXONOMY_DOCS
: Type.DOCS;
}
public HCTQueryResult execute(final Locale locale, final Availability availability)
throws InvalidQueryException, RepositoryException {
buildSQLQuery(locale, availability);
LOG.debug("Elaborated JCR/SQL2 query: {}", getSqlQuery());
final Query query = session.getWorkspace().getQueryManager().createQuery(getSqlQuery(), Query.JCR_SQL2);
// first execute without boundaries (only to take total result size)
final long totalResultSize = page == 0 ? 0 : query.execute().getRows().getSize();
// then execute with page and offset, for actual result
query.setLimit(size);
if (page > 0) {
query.setOffset((page - 1) * size);
}
LOG.debug("About to execute {}", query.getStatement());
final RowIterator result = query.execute().getRows();
final long totalPages = page == 0 ? 1L : (totalResultSize % size == 0
? totalResultSize / size
: totalResultSize / size + 1);
return new HCTQueryResult(locale, page, totalPages, result);
}
public Map<String, String> getTaxonomies() {
return taxonomies;
}
private void findTaxonomies(final Node node, final int targetDepth)
throws RepositoryException {
if (targetDepth >= node.getDepth()) {
taxonomies.put(node.getProperty(TaxonomyNodeTypes.HIPPOTAXONOMY_KEY).getString(), node.getPath());
for (final NodeIterator nodes = node.getNodes(); nodes.hasNext();) {
final Node child = nodes.nextNode();
if (TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY.equals(child.getPrimaryNodeType().getName())) {
findTaxonomies(child, targetDepth);
}
}
}
}
private void findDepthFrontier(final Node node, final Set<String> frontier, final int targetDepth)
throws RepositoryException {
if (targetDepth == node.getDepth()) {
frontier.add(node.getPath());
} else {
for (final NodeIterator nodes = node.getNodes(); nodes.hasNext();) {
final Node child = nodes.nextNode();
if (HippoStdNodeType.NT_FOLDER.equals(child.getPrimaryNodeType().getName())
|| TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY.equals(
child.getPrimaryNodeType().getName())) {
findDepthFrontier(child, frontier, targetDepth);
}
}
}
}
private void addCondsToWhereClause(final List<String> conds, final StringBuilder clause, final String op) {
boolean firstItem = clause.length() == 0;
for (String cond : conds) {
clause.insert(0, '(');
if (!firstItem) {
clause.append(op).append(' ');
}
clause.append(cond).append(") ");
}
}
private void addJoinsAndCondsToQuery(final Map<HCTDocumentChildNode, HCTQueryFilter.ChildQueryFilter> children,
final StringBuilder query, final StringBuilder whereClause, final StringBuilder andCondClause,
final StringBuilder orCondClause) {
for (Map.Entry<HCTDocumentChildNode, HCTQueryFilter.ChildQueryFilter> entry : children.entrySet()) {
query.append("INNER JOIN [").append(entry.getKey().getType()).append("] AS ").
append(entry.getKey().getSelector()).append(" ON ISCHILDNODE(").append(entry.getKey().getSelector()).
append(", ").append(Constants.QUERY_DEFAULT_SELECTOR).append(") ");
whereClause.insert(0, '(');
whereClause.append("AND NAME(").append(entry.getKey().getSelector()).append(") = '").
append(entry.getKey().getName()).append("') ");
addCondsToWhereClause(entry.getValue().getAndConds(), andCondClause, "AND");
addCondsToWhereClause(entry.getValue().getOrConds(), orCondClause, "OR");
}
}
private void buildSQLQuery(final Locale locale, final Availability availability) throws RepositoryException {
LOG.debug("Query type: {}", getType());
final String actualBase = getType() == Type.TAXONOMY_DOCS ? "/content/documents" : base;
LOG.debug("Search base: {}", actualBase);
final StringBuilder whereClause =
new StringBuilder("ISDESCENDANTNODE(").append(Constants.QUERY_DEFAULT_SELECTOR).append(", '").
append(actualBase).append("') ");
final Node baseNode = session.getNode(actualBase);
if (getType() == Type.TAXONOMY_DOCS) {
final Node taxonomyBaseNode = session.getNode(base);
if (!TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY.equals(
taxonomyBaseNode.getPrimaryNodeType().getName())) {
throw new InvalidQueryException(base + " is not of type "
+ TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY);
}
taxonomies.clear();
findTaxonomies(taxonomyBaseNode, depth > 0 ? taxonomyBaseNode.getDepth() + depth - 1 : Integer.MAX_VALUE);
final StringBuilder taxonomySubclause = new StringBuilder();
for (String taxonomy : taxonomies.keySet()) {
if (taxonomySubclause.length() > 0) {
taxonomySubclause.append("OR ");
}
taxonomySubclause.insert(0, '(');
taxonomySubclause.append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(TaxonomyNodeTypes.HIPPOTAXONOMY_KEYS).append("] = '").append(taxonomy).append("') ");
}
whereClause.insert(0, '(');
whereClause.append("AND ").append(taxonomySubclause).append(") ");
LOG.debug("Searching with taxonomies: {}", taxonomies);
} else if (depth > 0) {
final Set<String> depthFrontier = new HashSet<String>();
findDepthFrontier(baseNode, depthFrontier, baseNode.getDepth() + depth);
for (String depthFrontierPath : depthFrontier) {
whereClause.insert(0, '(');
whereClause.append("AND NOT ISDESCENDANTNODE(").append(Constants.QUERY_DEFAULT_SELECTOR).append(",'").
append(depthFrontierPath).append("')) ");
}
}
- if (availability != null) {
+ if (getType() != Type.FOLDERS && availability != null) {
whereClause.insert(0, '(');
whereClause.append("AND ").append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(HippoNodeType.HIPPO_AVAILABILITY).append("] = '").append(availability.name()).append("') ");
}
if (getType() != Type.TAXONOMIES) {
whereClause.insert(0, '(');
whereClause.append("AND ").append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(HippoTranslationNodeType.LOCALE).append("] = '").append(locale).append("') ");
}
StringBuilder andCondClause = new StringBuilder();
StringBuilder orCondClause = new StringBuilder();
addCondsToWhereClause(filter.getAndConds(), andCondClause, "AND");
addCondsToWhereClause(filter.getOrConds(), orCondClause, "OR");
final StringBuilder query = new StringBuilder("SELECT ").append(Constants.QUERY_DEFAULT_SELECTOR).
append(".[").append(JcrConstants.JCR_UUID).append("] FROM [").append(returnType).append("] AS ").
append(Constants.QUERY_DEFAULT_SELECTOR).append(' ');
addJoinsAndCondsToQuery(filter.getChildConds(), query, whereClause, andCondClause, orCondClause);
query.append("WHERE ").append(whereClause);
if (andCondClause.length() > 0) {
query.append("AND ").append(andCondClause);
}
if (orCondClause.length() > 0) {
query.append("OR ").append(orCondClause);
}
if (orderBy.length() > 2) {
query.append("ORDER BY ").append(orderBy.toString().substring(0, orderBy.length() - 2));
}
sqlQuery = query.toString();
}
public String getSqlQuery() {
return sqlQuery;
}
}
| true | true | private void buildSQLQuery(final Locale locale, final Availability availability) throws RepositoryException {
LOG.debug("Query type: {}", getType());
final String actualBase = getType() == Type.TAXONOMY_DOCS ? "/content/documents" : base;
LOG.debug("Search base: {}", actualBase);
final StringBuilder whereClause =
new StringBuilder("ISDESCENDANTNODE(").append(Constants.QUERY_DEFAULT_SELECTOR).append(", '").
append(actualBase).append("') ");
final Node baseNode = session.getNode(actualBase);
if (getType() == Type.TAXONOMY_DOCS) {
final Node taxonomyBaseNode = session.getNode(base);
if (!TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY.equals(
taxonomyBaseNode.getPrimaryNodeType().getName())) {
throw new InvalidQueryException(base + " is not of type "
+ TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY);
}
taxonomies.clear();
findTaxonomies(taxonomyBaseNode, depth > 0 ? taxonomyBaseNode.getDepth() + depth - 1 : Integer.MAX_VALUE);
final StringBuilder taxonomySubclause = new StringBuilder();
for (String taxonomy : taxonomies.keySet()) {
if (taxonomySubclause.length() > 0) {
taxonomySubclause.append("OR ");
}
taxonomySubclause.insert(0, '(');
taxonomySubclause.append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(TaxonomyNodeTypes.HIPPOTAXONOMY_KEYS).append("] = '").append(taxonomy).append("') ");
}
whereClause.insert(0, '(');
whereClause.append("AND ").append(taxonomySubclause).append(") ");
LOG.debug("Searching with taxonomies: {}", taxonomies);
} else if (depth > 0) {
final Set<String> depthFrontier = new HashSet<String>();
findDepthFrontier(baseNode, depthFrontier, baseNode.getDepth() + depth);
for (String depthFrontierPath : depthFrontier) {
whereClause.insert(0, '(');
whereClause.append("AND NOT ISDESCENDANTNODE(").append(Constants.QUERY_DEFAULT_SELECTOR).append(",'").
append(depthFrontierPath).append("')) ");
}
}
if (availability != null) {
whereClause.insert(0, '(');
whereClause.append("AND ").append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(HippoNodeType.HIPPO_AVAILABILITY).append("] = '").append(availability.name()).append("') ");
}
if (getType() != Type.TAXONOMIES) {
whereClause.insert(0, '(');
whereClause.append("AND ").append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(HippoTranslationNodeType.LOCALE).append("] = '").append(locale).append("') ");
}
StringBuilder andCondClause = new StringBuilder();
StringBuilder orCondClause = new StringBuilder();
addCondsToWhereClause(filter.getAndConds(), andCondClause, "AND");
addCondsToWhereClause(filter.getOrConds(), orCondClause, "OR");
final StringBuilder query = new StringBuilder("SELECT ").append(Constants.QUERY_DEFAULT_SELECTOR).
append(".[").append(JcrConstants.JCR_UUID).append("] FROM [").append(returnType).append("] AS ").
append(Constants.QUERY_DEFAULT_SELECTOR).append(' ');
addJoinsAndCondsToQuery(filter.getChildConds(), query, whereClause, andCondClause, orCondClause);
query.append("WHERE ").append(whereClause);
if (andCondClause.length() > 0) {
query.append("AND ").append(andCondClause);
}
if (orCondClause.length() > 0) {
query.append("OR ").append(orCondClause);
}
if (orderBy.length() > 2) {
query.append("ORDER BY ").append(orderBy.toString().substring(0, orderBy.length() - 2));
}
sqlQuery = query.toString();
}
| private void buildSQLQuery(final Locale locale, final Availability availability) throws RepositoryException {
LOG.debug("Query type: {}", getType());
final String actualBase = getType() == Type.TAXONOMY_DOCS ? "/content/documents" : base;
LOG.debug("Search base: {}", actualBase);
final StringBuilder whereClause =
new StringBuilder("ISDESCENDANTNODE(").append(Constants.QUERY_DEFAULT_SELECTOR).append(", '").
append(actualBase).append("') ");
final Node baseNode = session.getNode(actualBase);
if (getType() == Type.TAXONOMY_DOCS) {
final Node taxonomyBaseNode = session.getNode(base);
if (!TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY.equals(
taxonomyBaseNode.getPrimaryNodeType().getName())) {
throw new InvalidQueryException(base + " is not of type "
+ TaxonomyNodeTypes.NODETYPE_HIPPOTAXONOMY_CATEGORY);
}
taxonomies.clear();
findTaxonomies(taxonomyBaseNode, depth > 0 ? taxonomyBaseNode.getDepth() + depth - 1 : Integer.MAX_VALUE);
final StringBuilder taxonomySubclause = new StringBuilder();
for (String taxonomy : taxonomies.keySet()) {
if (taxonomySubclause.length() > 0) {
taxonomySubclause.append("OR ");
}
taxonomySubclause.insert(0, '(');
taxonomySubclause.append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(TaxonomyNodeTypes.HIPPOTAXONOMY_KEYS).append("] = '").append(taxonomy).append("') ");
}
whereClause.insert(0, '(');
whereClause.append("AND ").append(taxonomySubclause).append(") ");
LOG.debug("Searching with taxonomies: {}", taxonomies);
} else if (depth > 0) {
final Set<String> depthFrontier = new HashSet<String>();
findDepthFrontier(baseNode, depthFrontier, baseNode.getDepth() + depth);
for (String depthFrontierPath : depthFrontier) {
whereClause.insert(0, '(');
whereClause.append("AND NOT ISDESCENDANTNODE(").append(Constants.QUERY_DEFAULT_SELECTOR).append(",'").
append(depthFrontierPath).append("')) ");
}
}
if (getType() != Type.FOLDERS && availability != null) {
whereClause.insert(0, '(');
whereClause.append("AND ").append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(HippoNodeType.HIPPO_AVAILABILITY).append("] = '").append(availability.name()).append("') ");
}
if (getType() != Type.TAXONOMIES) {
whereClause.insert(0, '(');
whereClause.append("AND ").append(Constants.QUERY_DEFAULT_SELECTOR).append('.').append('[').
append(HippoTranslationNodeType.LOCALE).append("] = '").append(locale).append("') ");
}
StringBuilder andCondClause = new StringBuilder();
StringBuilder orCondClause = new StringBuilder();
addCondsToWhereClause(filter.getAndConds(), andCondClause, "AND");
addCondsToWhereClause(filter.getOrConds(), orCondClause, "OR");
final StringBuilder query = new StringBuilder("SELECT ").append(Constants.QUERY_DEFAULT_SELECTOR).
append(".[").append(JcrConstants.JCR_UUID).append("] FROM [").append(returnType).append("] AS ").
append(Constants.QUERY_DEFAULT_SELECTOR).append(' ');
addJoinsAndCondsToQuery(filter.getChildConds(), query, whereClause, andCondClause, orCondClause);
query.append("WHERE ").append(whereClause);
if (andCondClause.length() > 0) {
query.append("AND ").append(andCondClause);
}
if (orCondClause.length() > 0) {
query.append("OR ").append(orCondClause);
}
if (orderBy.length() > 2) {
query.append("ORDER BY ").append(orderBy.toString().substring(0, orderBy.length() - 2));
}
sqlQuery = query.toString();
}
|
diff --git a/src/main/java/org/andidev/applicationname/config/SpringMvcConfig.java b/src/main/java/org/andidev/applicationname/config/SpringMvcConfig.java
index d9d2e09..8d44565 100644
--- a/src/main/java/org/andidev/applicationname/config/SpringMvcConfig.java
+++ b/src/main/java/org/andidev/applicationname/config/SpringMvcConfig.java
@@ -1,76 +1,76 @@
package org.andidev.applicationname.config;
import java.util.List;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.andidev.applicationname.config.format.UserDateTimeFormatAnnotationFormatterFactory;
import org.andidev.applicationname.config.interceptor.LocaleInterceptor;
import org.andidev.applicationname.config.interceptor.TimeZoneInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
@Configuration
@Slf4j
@Import({ThymeleafConfig.class})
public class SpringMvcConfig extends WebMvcConfigurationSupport {
@Inject
Environment environment;
@Bean
public LocaleInterceptor localeInterceptor() {
LocaleInterceptor localeInterceptor = new LocaleInterceptor();
return localeInterceptor;
}
@Bean
public TimeZoneInterceptor timeZoneInterceptor() {
TimeZoneInterceptor timeZoneInterceptor = new TimeZoneInterceptor();
return timeZoneInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeInterceptor());
registry.addInterceptor(timeZoneInterceptor());
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// Configure the list of HttpMessageConverters to use
}
@Override
protected void addFormatters(FormatterRegistry registry) {
// Configure the list of formatters to use
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
- if ("prod".equals(environment.getProperty("application.version"))) {
+ if ("prod".equals(environment.getProperty("application.environment"))) {
registry.addResourceHandler("/resources-" + environment.getProperty("application.version") + "/**")
.addResourceLocations("/resources/")
.setCachePeriod(365*24*60*60); // 365*24*60*60 equals one year
} else {
registry.addResourceHandler("/resources-" + environment.getProperty("application.version") + "/**")
.addResourceLocations("/resources/")
.setCachePeriod(0); // Don't chache
}
}
@Bean
@Override
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter();
adapter.setIgnoreDefaultModelOnRedirect(true); // Makes sure url parameters are removed on a redirect
return adapter;
}
}
| true | true | public void addResourceHandlers(ResourceHandlerRegistry registry) {
if ("prod".equals(environment.getProperty("application.version"))) {
registry.addResourceHandler("/resources-" + environment.getProperty("application.version") + "/**")
.addResourceLocations("/resources/")
.setCachePeriod(365*24*60*60); // 365*24*60*60 equals one year
} else {
registry.addResourceHandler("/resources-" + environment.getProperty("application.version") + "/**")
.addResourceLocations("/resources/")
.setCachePeriod(0); // Don't chache
}
}
| public void addResourceHandlers(ResourceHandlerRegistry registry) {
if ("prod".equals(environment.getProperty("application.environment"))) {
registry.addResourceHandler("/resources-" + environment.getProperty("application.version") + "/**")
.addResourceLocations("/resources/")
.setCachePeriod(365*24*60*60); // 365*24*60*60 equals one year
} else {
registry.addResourceHandler("/resources-" + environment.getProperty("application.version") + "/**")
.addResourceLocations("/resources/")
.setCachePeriod(0); // Don't chache
}
}
|
diff --git a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/UIFormColorPicker.java b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/UIFormColorPicker.java
index e1d5bdb8..6a09f877 100644
--- a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/UIFormColorPicker.java
+++ b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/UIFormColorPicker.java
@@ -1,480 +1,480 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.calendar.webui;
import org.exoplatform.commons.utils.HTMLEntityEncoder;
import org.exoplatform.web.application.JavascriptManager;
import org.exoplatform.web.application.RequireJS;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormInput;
import org.exoplatform.webui.form.UIFormInputBase;
import org.exoplatform.calendar.webui.UIFormColorPicker.Colors.Color;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
/**
* Created by The eXo Platform SAS
* Author : Pham Tuan
* [email protected]
* Feb 29, 2008
*/
public class UIFormColorPicker extends UIFormInputBase<String>
{
/**
* The size of the list (number of select options)
*/
private int items_ = 10;
/**
* The javascript expression executed when an onChange event fires
*/
private String onchange_;
/**
* The javascript expression executed when an client onChange event fires
*/
public static final String ON_CHANGE = "onchange".intern();
/**
* The javascript expression executed when an client event fires
*/
public static final String ON_BLUR = "onblur".intern();
/**
* The javascript expression executed when an client event fires
*/
public static final String ON_FOCUS = "onfocus".intern();
/**
* The javascript expression executed when an client event fires
*/
public static final String ON_KEYUP = "onkeyup".intern();
/**
* The javascript expression executed when an client event fires
*/
public static final String ON_KEYDOWN = "onkeydown".intern();
/**
* The javascript expression executed when an client event fires
*/
public static final String ON_CLICK = "onclick".intern();
private Map<String, String> jsActions_ = new HashMap<String, String>();
private Color[] colors_ = null;
public UIFormColorPicker(String name, String bindingExpression, String value)
{
super(name, bindingExpression, String.class);
this.value_ = value;
setColors(Colors.COLORS);
}
public UIFormColorPicker(String name, String bindingExpression, Color[] colors)
{
super(name, bindingExpression, null);
setColors(colors);
}
public void setJsActions(Map<String, String> jsActions)
{
if (jsActions != null)
jsActions_ = jsActions;
}
public Map<String, String> getJsActions()
{
return jsActions_;
}
public void addJsActions(String action, String javaScript)
{
jsActions_.put(action, javaScript);
}
public UIFormColorPicker(String name, String bindingExpression, Color[] colors, Map<String, String> jsActions)
{
super(name, bindingExpression, null);
setColors(colors);
setJsActions(jsActions);
}
public UIFormColorPicker(String name, String value)
{
this(name, null, value);
}
@SuppressWarnings("unused")
public void decode(Object input, WebuiRequestContext context)
{
value_ = (String)input;
if (value_ != null && value_.trim().length() == 0)
value_ = null;
}
public void setOnChange(String onchange)
{
onchange_ = onchange;
}
protected String renderOnChangeEvent(UIForm uiForm) throws Exception
{
return uiForm.event(onchange_, (String)null);
}
protected UIForm getUIform()
{
return getAncestorOfType(UIForm.class);
}
private String renderJsActions()
{
StringBuffer sb = new StringBuffer("");
for (String k : jsActions_.keySet())
{
if (sb != null && sb.length() > 0)
sb.append(" ");
if (jsActions_.get(k) != null)
{
sb.append(k).append("=\"").append(jsActions_.get(k)).append("\"");
}
}
return sb.toString();
}
private Color[] getColors()
{
return colors_;
}
private void setColors(Color[] colors)
{
colors_ = colors;
value_ = colors_[0].getName();
}
private int items()
{
return items_;
}
private int size()
{
return colors_.length;
}
public void setNumberItemsPerLine(int numberItems)
{
items_ = numberItems;
}
public void processRender(WebuiRequestContext context) throws Exception
{
JavascriptManager jsManager = context.getJavascriptManager();
RequireJS requireJS = jsManager.getRequireJS();
requireJS.require("SHARED/jquery","gj");
requireJS.require("SHARED/bts_dropdown","btsdropdown");
requireJS.require("PORTLET/calendar/CalendarPortlet","cal");
- requireJS.addScripts("gj('div.uiColorPickerInput').click(function(){ cal.UIColorPicker.adaptPopup(this); });");
+ requireJS.addScripts("gj(document).ready(function() { gj('div.uiColorPickerInput').click(function(){ cal.UIColorPicker.adaptPopup(this); }); });");
requireJS.addScripts("gj('a.colorCell').click(function(){ cal.UIColorPicker.setColor(this); });");
String value = getValue();
if (value != null)
{
value = HTMLEntityEncoder.getInstance().encode(value);
}
Writer w = context.getWriter();
w.write("<div class='uiFormColorPicker dropdown'>");
w.write("<div class=\"uiColorPickerInput dropdown-toggle\" data-toggle=\"dropdown\">");
w.write("<span class=\" displayValue " + value + "\"><span><b class=\"caret\"></b></span></span>");
w.write("</div>");
w.write("<ul class='calendarTableColor dropdown-menu' role=\"menu\" selectedColor=\"" + value + " \">");
int i = 0 ;
int items = 6 ;
int size = getColors().length ;
int rows = size/items ;
int count = 0 ;
while(i < rows) {
w.write("<li class=\"clearfix\">") ;
int j = 0 ;
while(j < items && count < size){
Color color = getColors()[count] ;
w.write("<a href=\"javascript:void(0);");
w.write("\" class=\"");
w.write(color.getName());
w.write(" colorCell \" onmousedown=\"event.cancelBubble=true\"><i class=\"");
if(color.getName().equals(value)){w.write("iconCheckBox");}
w.write("\"></i></a>");
count++;
j++;
}
w.write("</li>");
i++ ;
}
w.write("</ul>");
w.write("<input class='uiColorPickerValue' name='" + getId() + "' type='hidden'" + " id='" + getId() + "' "
+ renderJsActions());
if (value != null && value.trim().length() > 0)
{
w.write(" value='" + value + "'");
}
w.write(" />");
w.write("</div>");
}
@Override
public UIFormInput setValue(String arg0)
{
if (arg0 == null)
arg0 = colors_[0].getName();
return super.setValue(arg0);
}
public static class Colors
{
/* 1st line */
public static final String H_ASPARAGUS = "#909958";
public static final String N_ASPARAGUS = "asparagus";
public static final Color O_ASPARAGUS = new Color(H_ASPARAGUS, N_ASPARAGUS);
public static final String H_MUNSELL_BLUE = "#319AB3";
public static final String N_MUNSELL_BLUE = "munsell_blue";
public static final Color O_MUNSELL_BLUE = new Color(H_MUNSELL_BLUE, N_MUNSELL_BLUE);
public static final String H_NAVY_BLUE = "#4273C8";
public static final String N_NAVY_BLUE = "navy_blue";
public static final Color O_NAVY_BLUE = new Color(H_NAVY_BLUE, N_NAVY_BLUE);
public static final String H_PURPLE = "#774EA9";
public static final String N_PURPLE = "purple";
public static final Color O_PURPLE = new Color(H_PURPLE, N_PURPLE);
public static final String H_RED = "#FF5933";
public static final String N_RED = "red";
public static final Color O_RED = new Color(H_RED, N_RED);
public static final String H_BROWN = "#BB8E62";
public static final String N_BROWN = "brown";
public static final Color O_BROWN = new Color(H_BROWN, N_BROWN);
/* 2nd line */
public static final String H_LAUREL_GREEN = "#BED67E";
public static final String N_LAUREL_GREEN = "laurel_green";
public static final Color O_LAUREL_GREEN = new Color(H_LAUREL_GREEN, N_LAUREL_GREEN);
public static final String H_SKY_BLUE = "#4DBED9";
public static final String N_SKY_BLUE = "sky_blue";
public static final Color O_SKY_BLUE = new Color(H_SKY_BLUE, N_SKY_BLUE);
public static final String H_BLUE_GRAY = "#8EB0EA";
public static final String N_BLUE_GRAY = "blue_gray";
public static final Color O_BLUE_GRAY = new Color(H_BLUE_GRAY, N_BLUE_GRAY);
public static final String H_LIGHT_PURPLE = "#BC99E7";
public static final String N_LIGHT_PURPLE = "light_purple";
public static final Color O_LIGHT_PURPLE = new Color(H_LIGHT_PURPLE, N_LIGHT_PURPLE);
public static final String H_HOT_PINK = "#F97575";
public static final String N_HOT_PINK = "hot_pink";
public static final Color O_HOT_PINK = new Color(H_HOT_PINK, N_HOT_PINK);
public static final String H_LIGHT_BROWN = "#C5B294";
public static final String N_LIGHT_BROWN = "light_brown";
public static final Color O_LIGHT_BROWN = new Color(H_LIGHT_BROWN, N_LIGHT_BROWN);
/* 3rd line */
public static final String H_MOSS_GREEN = "#98CC81";
public static final String N_MOSS_GREEN = "moss_green";
public static final Color O_MOSS_GREEN = new Color(H_MOSS_GREEN, N_MOSS_GREEN);
public static final String H_POWDER_BLUE = "#9EE4F5";
public static final String N_POWDER_BLUE = "powder_blue";
public static final Color O_POWDER_BLUE = new Color(H_POWDER_BLUE, N_POWDER_BLUE);
public static final String H_LIGHT_BLUE = "#B3CFFF";
public static final String N_LIGHT_BLUE = "light_blue";
public static final Color O_LIGHT_BLUE = new Color(H_LIGHT_BLUE, N_LIGHT_BLUE);
public static final String H_PINK = "#FFC8F0";
public static final String N_PINK = "pink";
public static final Color O_PINK = new Color(H_PINK, N_PINK);
public static final String H_ORANGE = "#FDB519";
public static final String N_ORANGE = "orange";
public static final Color O_ORANGE = new Color(H_ORANGE, N_ORANGE);
public static final String H_GRAY = "#A39594";
public static final String N_GRAY = "gray";
public static final Color O_GRAY = new Color(H_GRAY, N_GRAY);
/* 4th line */
public static final String H_GREEN = "#89D4B3";
public static final String N_GREEN = "green";
public static final Color O_GREEN = new Color(H_GREEN, N_GREEN);
public static final String H_BABY_BLUE = "#B2E2FF";
public static final String N_BABY_BLUE = "baby_blue";
public static final Color O_BABY_BLUE = new Color(H_BABY_BLUE, N_BABY_BLUE);
public static final String H_LIGHT_GRAY = "#CDCDCD";
public static final String N_LIGHT_GRAY = "light_gray";
public static final Color O_LIGHT_GRAY = new Color(H_LIGHT_GRAY, N_LIGHT_GRAY);
public static final String H_BEIGE = "#FFE1BE";
public static final String N_BEIGE = "beige";
public static final Color O_BEIGE = new Color(H_BEIGE, N_BEIGE);
public static final String H_YELLOW = "#FFE347";
public static final String N_YELLOW = "yellow";
public static final Color O_YELLOW = new Color(H_YELLOW, N_YELLOW);
public static final String H_PLUM_PURPLE = "#CEA6AC";
public static final String N_PLUM_PURPLE = "plum";
public static final Color O_PLUM_PURPLE = new Color(H_PLUM_PURPLE, N_PLUM_PURPLE);
public static final Color[] COLORS =
{O_ASPARAGUS, O_MUNSELL_BLUE, O_NAVY_BLUE, O_PURPLE, O_RED, O_BROWN,
O_LAUREL_GREEN, O_SKY_BLUE, O_BLUE_GRAY, O_LIGHT_PURPLE, O_HOT_PINK, O_LIGHT_BROWN,
O_MOSS_GREEN, O_POWDER_BLUE, O_LIGHT_BLUE, O_PINK, O_ORANGE, O_GRAY,
O_GREEN, O_BABY_BLUE, O_LIGHT_GRAY, O_BEIGE, O_YELLOW, O_PLUM_PURPLE};
public static final String[] COLORNAMES =
{N_ASPARAGUS, N_MUNSELL_BLUE, N_NAVY_BLUE, N_PURPLE, N_RED, N_BROWN,
N_LAUREL_GREEN, N_SKY_BLUE, N_BLUE_GRAY, N_LIGHT_PURPLE, N_HOT_PINK, N_LIGHT_BROWN,
N_MOSS_GREEN, N_POWDER_BLUE, N_LIGHT_BLUE, N_PINK, N_ORANGE, N_GRAY,
N_GREEN, N_BABY_BLUE, N_LIGHT_GRAY, N_BEIGE, N_YELLOW, N_PLUM_PURPLE};
public static final String[] CODES =
{H_ASPARAGUS, H_MUNSELL_BLUE, H_NAVY_BLUE, H_PURPLE, H_RED, H_BROWN,
H_LAUREL_GREEN, H_SKY_BLUE, H_BLUE_GRAY, H_LIGHT_PURPLE, H_HOT_PINK, H_LIGHT_BROWN,
H_MOSS_GREEN, H_POWDER_BLUE, H_LIGHT_BLUE, H_PINK, H_ORANGE, H_GRAY,
H_GREEN, H_BABY_BLUE, H_LIGHT_GRAY, H_BEIGE, H_YELLOW, H_PLUM_PURPLE};
static public class Color
{
int R = 0;
int G = 0;
int B = 0;
String code_;
String name_;
public Color(String code)
{
setCode(code);
}
public Color(int r, int g, int b)
{
R = r;
G = g;
B = b;
}
public Color(String code, String name)
{
setCode(code);
setName(name);
}
public String getCode()
{
return code_;
}
public void setName(String name)
{
name_ = name;
}
public String getName()
{
return name_;
}
public void setCode(String code)
{
code_ = code;
}
}
}
}
| true | true | public void processRender(WebuiRequestContext context) throws Exception
{
JavascriptManager jsManager = context.getJavascriptManager();
RequireJS requireJS = jsManager.getRequireJS();
requireJS.require("SHARED/jquery","gj");
requireJS.require("SHARED/bts_dropdown","btsdropdown");
requireJS.require("PORTLET/calendar/CalendarPortlet","cal");
requireJS.addScripts("gj('div.uiColorPickerInput').click(function(){ cal.UIColorPicker.adaptPopup(this); });");
requireJS.addScripts("gj('a.colorCell').click(function(){ cal.UIColorPicker.setColor(this); });");
String value = getValue();
if (value != null)
{
value = HTMLEntityEncoder.getInstance().encode(value);
}
Writer w = context.getWriter();
w.write("<div class='uiFormColorPicker dropdown'>");
w.write("<div class=\"uiColorPickerInput dropdown-toggle\" data-toggle=\"dropdown\">");
w.write("<span class=\" displayValue " + value + "\"><span><b class=\"caret\"></b></span></span>");
w.write("</div>");
w.write("<ul class='calendarTableColor dropdown-menu' role=\"menu\" selectedColor=\"" + value + " \">");
int i = 0 ;
int items = 6 ;
int size = getColors().length ;
int rows = size/items ;
int count = 0 ;
while(i < rows) {
w.write("<li class=\"clearfix\">") ;
int j = 0 ;
while(j < items && count < size){
Color color = getColors()[count] ;
w.write("<a href=\"javascript:void(0);");
w.write("\" class=\"");
w.write(color.getName());
w.write(" colorCell \" onmousedown=\"event.cancelBubble=true\"><i class=\"");
if(color.getName().equals(value)){w.write("iconCheckBox");}
w.write("\"></i></a>");
count++;
j++;
}
w.write("</li>");
i++ ;
}
w.write("</ul>");
w.write("<input class='uiColorPickerValue' name='" + getId() + "' type='hidden'" + " id='" + getId() + "' "
+ renderJsActions());
if (value != null && value.trim().length() > 0)
{
w.write(" value='" + value + "'");
}
w.write(" />");
w.write("</div>");
}
| public void processRender(WebuiRequestContext context) throws Exception
{
JavascriptManager jsManager = context.getJavascriptManager();
RequireJS requireJS = jsManager.getRequireJS();
requireJS.require("SHARED/jquery","gj");
requireJS.require("SHARED/bts_dropdown","btsdropdown");
requireJS.require("PORTLET/calendar/CalendarPortlet","cal");
requireJS.addScripts("gj(document).ready(function() { gj('div.uiColorPickerInput').click(function(){ cal.UIColorPicker.adaptPopup(this); }); });");
requireJS.addScripts("gj('a.colorCell').click(function(){ cal.UIColorPicker.setColor(this); });");
String value = getValue();
if (value != null)
{
value = HTMLEntityEncoder.getInstance().encode(value);
}
Writer w = context.getWriter();
w.write("<div class='uiFormColorPicker dropdown'>");
w.write("<div class=\"uiColorPickerInput dropdown-toggle\" data-toggle=\"dropdown\">");
w.write("<span class=\" displayValue " + value + "\"><span><b class=\"caret\"></b></span></span>");
w.write("</div>");
w.write("<ul class='calendarTableColor dropdown-menu' role=\"menu\" selectedColor=\"" + value + " \">");
int i = 0 ;
int items = 6 ;
int size = getColors().length ;
int rows = size/items ;
int count = 0 ;
while(i < rows) {
w.write("<li class=\"clearfix\">") ;
int j = 0 ;
while(j < items && count < size){
Color color = getColors()[count] ;
w.write("<a href=\"javascript:void(0);");
w.write("\" class=\"");
w.write(color.getName());
w.write(" colorCell \" onmousedown=\"event.cancelBubble=true\"><i class=\"");
if(color.getName().equals(value)){w.write("iconCheckBox");}
w.write("\"></i></a>");
count++;
j++;
}
w.write("</li>");
i++ ;
}
w.write("</ul>");
w.write("<input class='uiColorPickerValue' name='" + getId() + "' type='hidden'" + " id='" + getId() + "' "
+ renderJsActions());
if (value != null && value.trim().length() > 0)
{
w.write(" value='" + value + "'");
}
w.write(" />");
w.write("</div>");
}
|
diff --git a/src/assignment7/Main.java b/src/assignment7/Main.java
index 92b2e12..b1e4413 100644
--- a/src/assignment7/Main.java
+++ b/src/assignment7/Main.java
@@ -1,39 +1,39 @@
package assignment7;
import java.util.ArrayList;
import java.util.List;
import assignment7.EpidemicSystem;
import assignment7.EpidemicSystem.Node;
public class Main {
final static List<Patient> list = new ArrayList<Patient>();
public static void main( String[] args ) {
list.add(new Patient(160, 72.7));
list.add(new Patient(178, 82.7));
list.add(new Patient(167, 76.9));
- list.add(new Patient(177, 802.0));
+ list.add(new Patient(177, 82.0));
list.add(new Patient(156, 79.3));
list.add(new Patient(180, 76.4));
list.add(new Patient(176, 78.9));
list.add(new Patient(187, 73.1));
list.add(new Patient(155, 76.7));
list.add(new Patient(190, 78.8));
EpidemicSystem es = new EpidemicSystem();
sendListToTree(list, es);
es.printInOrder(es.root);
}
public static void sendListToTree( List<Patient> list, EpidemicSystem es ) {
Node root = new Node(list.get(0).getWeight());
es.root = root;
for( Patient current : list ) {
es.insert(root, current.getWeight());
}
}
}
| true | true | public static void main( String[] args ) {
list.add(new Patient(160, 72.7));
list.add(new Patient(178, 82.7));
list.add(new Patient(167, 76.9));
list.add(new Patient(177, 802.0));
list.add(new Patient(156, 79.3));
list.add(new Patient(180, 76.4));
list.add(new Patient(176, 78.9));
list.add(new Patient(187, 73.1));
list.add(new Patient(155, 76.7));
list.add(new Patient(190, 78.8));
EpidemicSystem es = new EpidemicSystem();
sendListToTree(list, es);
es.printInOrder(es.root);
}
| public static void main( String[] args ) {
list.add(new Patient(160, 72.7));
list.add(new Patient(178, 82.7));
list.add(new Patient(167, 76.9));
list.add(new Patient(177, 82.0));
list.add(new Patient(156, 79.3));
list.add(new Patient(180, 76.4));
list.add(new Patient(176, 78.9));
list.add(new Patient(187, 73.1));
list.add(new Patient(155, 76.7));
list.add(new Patient(190, 78.8));
EpidemicSystem es = new EpidemicSystem();
sendListToTree(list, es);
es.printInOrder(es.root);
}
|
diff --git a/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/FancyCounter.java b/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/FancyCounter.java
index a920af1..3929c46 100644
--- a/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/FancyCounter.java
+++ b/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/FancyCounter.java
@@ -1,110 +1,110 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package robot.sensors;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.PIDSource;
/**
*
* @author Adambots 245
*/
public class FancyCounter extends Counter implements PIDSource {
// New constructor with radius option
// getDiameter();
// setDiameter();
// getDistance();
double diameter;
double lastRpm;
double distance;
int errorVal;
private int _ticksPerPeriod;
public FancyCounter(int channel) {
super(channel);
lastRpm = 0;
errorVal = 0;
diameter = 0;
_ticksPerPeriod = 1;
}
public FancyCounter(int slot, int channel) {
super(slot, channel);
lastRpm = 0;
errorVal = 0;
diameter = 0;
_ticksPerPeriod = 1;
}
public FancyCounter(int slot, int channel, int ticksPerPeriod) {
super(slot, channel);
lastRpm = 0;
errorVal = 0;
diameter = 0;
_ticksPerPeriod = ticksPerPeriod;
}
public FancyCounter(int slot, int channel, int ticksPerPeriod, double _diameter) {
super(slot, channel);
lastRpm = 0;
errorVal = 0;
diameter = _diameter;
_ticksPerPeriod = ticksPerPeriod;
}
public FancyCounter(int slot, int channel, double _diameter) {
super(slot, channel);
lastRpm = 0;
errorVal = 0;
diameter = _diameter;
_ticksPerPeriod = 1;
}
public int getError() {
return errorVal;
}
public void resetError() {
errorVal = 0;
}
public double getDiameter() {
return diameter;
}
public void setDiameter(double _diameter) {
diameter = _diameter;
}
// public double getDistance() {
// return get() * diameter * Math.PI / _ticksPerPeriod;
// }
public double pidGet() {
- double time = getPeriod() * _ticksPerPeriod;
- double rpm = 60 / time;
+ double time = getPeriod();
+ double rpm = (60 / time) / _ticksPerPeriod;
// if (rom > 5000) // was that before, but i thought i might need something different that wasn't 5000
if (rpm > 6000) {
errorVal++;
rpm = lastRpm;
} else if (rpm < 300) {
errorVal++;
rpm = lastRpm;
} else {
lastRpm = rpm;
}
return rpm;
}
public void setTicksPerPeriod(int t) {
_ticksPerPeriod = t;
}
}
| true | true | public double pidGet() {
double time = getPeriod() * _ticksPerPeriod;
double rpm = 60 / time;
// if (rom > 5000) // was that before, but i thought i might need something different that wasn't 5000
if (rpm > 6000) {
errorVal++;
rpm = lastRpm;
} else if (rpm < 300) {
errorVal++;
rpm = lastRpm;
} else {
lastRpm = rpm;
}
return rpm;
}
| public double pidGet() {
double time = getPeriod();
double rpm = (60 / time) / _ticksPerPeriod;
// if (rom > 5000) // was that before, but i thought i might need something different that wasn't 5000
if (rpm > 6000) {
errorVal++;
rpm = lastRpm;
} else if (rpm < 300) {
errorVal++;
rpm = lastRpm;
} else {
lastRpm = rpm;
}
return rpm;
}
|
diff --git a/src/main/java/de/lessvoid/nifty/examples/all/MenuController.java b/src/main/java/de/lessvoid/nifty/examples/all/MenuController.java
index 6aa6f939..467d6e00 100644
--- a/src/main/java/de/lessvoid/nifty/examples/all/MenuController.java
+++ b/src/main/java/de/lessvoid/nifty/examples/all/MenuController.java
@@ -1,121 +1,122 @@
package de.lessvoid.nifty.examples.all;
import de.lessvoid.nifty.EndNotify;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
/**
* Menu.
* @author void
*/
public class MenuController implements ScreenController {
/**
* the nifty instance.
*/
private Nifty nifty;
/**
* the screen this menu belongs to.
*/
private Screen screen;
/**
* bind.
* @param niftyParam niftyParam
* @param screenParam screenParam
*/
public void bind(final Nifty niftyParam, final Screen screenParam) {
this.nifty = niftyParam;
this.screen = screenParam;
hideIfThere("thumbHelloWorld");
hideIfThere("thumbHint");
+ hideIfThere("thumbMouse");
hideIfThere("thumbTextAlign");
hideIfThere("thumbTextField");
hideIfThere("thumbDropDownList");
hideIfThere("thumbScrollpanel");
hideIfThere("thumbMultiplayer");
hideIfThere("thumbConsole");
hideIfThere("thumbCredits");
hideIfThere("thumbExit");
}
private void hideIfThere(final String elementName) {
Element element = screen.findElementByName(elementName);
if (element != null) {
element.hide();
}
}
/**
* just goto the next screen.
*/
public final void onStartScreen() {
}
public final void onEndScreen() {
}
public void helloWorld() {
nifty.fromXml("helloworld/helloworld.xml", "start");
}
public void hint() {
nifty.fromXml("hint/hint.xml", "start");
}
public void mouse() {
nifty.fromXml("mouse/mouse.xml", "start");
}
public void textfield() {
nifty.fromXml("textfield/textfield.xml", "start");
}
public void textalign() {
nifty.fromXml("textalign/textalign.xml", "start");
}
public void multiplayer() {
nifty.fromXml("multiplayer/multiplayer.xml", "start");
}
public void console() {
nifty.fromXml("console/console.xml", "start");
}
public void dropDown() {
nifty.fromXml("controls/controls.xml", "start");
}
public void scrollpanel() {
nifty.fromXml("scroll/scroll.xml", "start");
}
public void credits() {
nifty.gotoScreen("outro");
}
public void exit() {
nifty.createPopupWithId("popupExit", "popupExit");
nifty.showPopup(screen, "popupExit", null);
}
/**
* popupExit.
* @param exit exit string
*/
public void popupExit(final String exit) {
nifty.closePopup("popupExit", new EndNotify() {
public void perform() {
if ("yes".equals(exit)) {
nifty.setAlternateKey("fade");
nifty.exit();
}
}
}
);
}
}
| true | true | public void bind(final Nifty niftyParam, final Screen screenParam) {
this.nifty = niftyParam;
this.screen = screenParam;
hideIfThere("thumbHelloWorld");
hideIfThere("thumbHint");
hideIfThere("thumbTextAlign");
hideIfThere("thumbTextField");
hideIfThere("thumbDropDownList");
hideIfThere("thumbScrollpanel");
hideIfThere("thumbMultiplayer");
hideIfThere("thumbConsole");
hideIfThere("thumbCredits");
hideIfThere("thumbExit");
}
| public void bind(final Nifty niftyParam, final Screen screenParam) {
this.nifty = niftyParam;
this.screen = screenParam;
hideIfThere("thumbHelloWorld");
hideIfThere("thumbHint");
hideIfThere("thumbMouse");
hideIfThere("thumbTextAlign");
hideIfThere("thumbTextField");
hideIfThere("thumbDropDownList");
hideIfThere("thumbScrollpanel");
hideIfThere("thumbMultiplayer");
hideIfThere("thumbConsole");
hideIfThere("thumbCredits");
hideIfThere("thumbExit");
}
|
diff --git a/src/main/java/org/terasology/launcher/gui/LauncherFrame.java b/src/main/java/org/terasology/launcher/gui/LauncherFrame.java
index c8d3f05..e419052 100644
--- a/src/main/java/org/terasology/launcher/gui/LauncherFrame.java
+++ b/src/main/java/org/terasology/launcher/gui/LauncherFrame.java
@@ -1,581 +1,584 @@
/*
* Copyright 2013 MovingBlocks
*
* 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.terasology.launcher.gui;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.launcher.LauncherSettings;
import org.terasology.launcher.util.BundleUtils;
import org.terasology.launcher.util.DirectoryUtils;
import org.terasology.launcher.util.FileUtils;
import org.terasology.launcher.util.GameStarter;
import org.terasology.launcher.version.TerasologyGameVersion;
import org.terasology.launcher.version.TerasologyGameVersions;
import org.terasology.launcher.version.TerasologyLauncherVersionInfo;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
public final class LauncherFrame extends JFrame implements ActionListener {
private static final Logger logger = LoggerFactory.getLogger(LauncherFrame.class);
private static final long serialVersionUID = 1L;
private static final int FRAME_WIDTH = 880;
private static final int FRAME_HEIGHT = 520;
private static final int INFO_PANEL_WIDTH = 600;
private static final int INFO_PANEL_HEIGHT = 300;
private static final String DOWNLOAD_ACTION = "download";
private static final String START_ACTION = "start";
private static final String DELETE_ACTION = "delete";
private static final String SETTINGS_ACTION = "settings";
private static final String EXIT_ACTION = "exit";
private JButton downloadButton;
private JButton startButton;
private JButton deleteButton;
private JButton settingsButton;
private JButton exitButton;
private JTextPane infoTextPane;
private LinkJLabel logo;
private LinkJLabel forums;
private LinkJLabel issues;
private LinkJLabel mods;
private JProgressBar progressBar;
private LinkJButton github;
private LinkJButton twitter;
private LinkJButton facebook;
private LinkJButton gplus;
private LinkJButton youtube;
private LinkJButton reddit;
private SettingsMenu settingsMenu;
private final GameStarter gameStarter;
private GameDownloader gameDownloader;
private final File launcherDirectory;
private final File tempDirectory;
private final LauncherSettings launcherSettings;
private final TerasologyGameVersions gameVersions;
public LauncherFrame(final File launcherDirectory, final File tempDirectory,
final LauncherSettings launcherSettings, final TerasologyGameVersions gameVersions) {
this.launcherDirectory = launcherDirectory;
this.tempDirectory = tempDirectory;
this.launcherSettings = launcherSettings;
this.gameVersions = gameVersions;
gameStarter = new GameStarter();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initComponents();
updateGui();
final Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((dim.width - FRAME_WIDTH) / 2, (dim.height - FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
getContentPane().add(new BackgroundImage(FRAME_WIDTH, FRAME_HEIGHT));
}
private void initComponents() {
final int xShift = 0;
int yShift = 0;
if (isUndecorated()) {
yShift += 30;
}
// Download button
downloadButton = new TSButton(BundleUtils.getLabel("launcher_download"));
downloadButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (4 * 40)) + yShift, 96, 32);
downloadButton.setActionCommand(DOWNLOAD_ACTION);
downloadButton.addActionListener(this);
// Start button
startButton = new TSButton(BundleUtils.getLabel("launcher_start"));
startButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (3 * 40)) + yShift, 96, 32);
startButton.setActionCommand(START_ACTION);
startButton.addActionListener(this);
// Delete button
deleteButton = new TSButton(BundleUtils.getLabel("launcher_delete"));
deleteButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (2 * 40)) + yShift, 96, 32);
deleteButton.setActionCommand(DELETE_ACTION);
deleteButton.addActionListener(this);
// Settings Button
settingsButton = new TSButton(BundleUtils.getLabel("launcher_settings"));
settingsButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (1 * 40)) + yShift, 96, 32);
settingsButton.setActionCommand(SETTINGS_ACTION);
settingsButton.addActionListener(this);
// Exit button
exitButton = new TSButton(BundleUtils.getLabel("launcher_exit"));
exitButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (0 * 40)) + yShift, 96, 32);
exitButton.setActionCommand(EXIT_ACTION);
exitButton.addActionListener(this);
// Transparent top panel and content/update panel
final TransparentPanel topPanel = new TransparentPanel(0.5f);
topPanel.setBounds(0, 0, FRAME_WIDTH, 96);
final TransparentPanel updatePanel = new TransparentPanel(0.5f);
updatePanel.setBounds(
(FRAME_WIDTH - INFO_PANEL_WIDTH) / 2,
(FRAME_HEIGHT - INFO_PANEL_HEIGHT) / 2,
INFO_PANEL_WIDTH,
INFO_PANEL_HEIGHT);
infoTextPane = new JTextPane();
infoTextPane.setFont(new Font("Arial", Font.PLAIN, 14));
infoTextPane.setEditable(false);
infoTextPane.setEnabled(false);
infoTextPane.setHighlighter(null);
infoTextPane.setOpaque(false);
infoTextPane.setContentType("text/html");
infoTextPane.setForeground(Color.WHITE);
//infoTextPane.setBounds(updatePanel.getX() + 8, updatePanel.getY() + 8, updatePanelWidth - 16,
// updatePanelHeight - 16);
final JScrollPane sp = new JScrollPane();
sp.getViewport().add(infoTextPane);
- sp.getVerticalScrollBar().setOpaque(false);
- sp.getVerticalScrollBar().setUI(new TSScrollBarUI());
sp.getViewport().setOpaque(false);
- sp.getVerticalScrollBar().setBorder(BorderFactory.createEmptyBorder());
sp.setBorder(BorderFactory.createEmptyBorder());
sp.setOpaque(false);
sp.setPreferredSize(new Dimension(INFO_PANEL_WIDTH - 16, INFO_PANEL_HEIGHT - 16));
sp.setBounds(updatePanel.getX() + 8, updatePanel.getY() + 8, INFO_PANEL_WIDTH - 16, INFO_PANEL_HEIGHT - 16);
+ sp.getHorizontalScrollBar().setUI(new TSScrollBarUI());
+ sp.getHorizontalScrollBar().setOpaque(false);
+ sp.getHorizontalScrollBar().setBorder(BorderFactory.createEmptyBorder());
+ sp.getVerticalScrollBar().setUI(new TSScrollBarUI());
+ sp.getVerticalScrollBar().setOpaque(false);
+ sp.getVerticalScrollBar().setBorder(BorderFactory.createEmptyBorder());
// Terasology logo
logo = new LinkJLabel();
logo.setBounds(8, 0, 400, 96);
// Launcher version info label
final JLabel version = new JLabel(TerasologyLauncherVersionInfo.getInstance().getDisplayVersion());
version.setFont(version.getFont().deriveFont(12f));
version.setForeground(Color.WHITE);
version.setBounds(FRAME_WIDTH - 400 - 16 - xShift, 0, 400, 32);
version.setHorizontalAlignment(JLabel.RIGHT);
// Forums link
forums = new LinkJLabel();
forums.setFont(forums.getFont().deriveFont(20f));
forums.setBounds(480, 36, 96, 32);
// Issues link
issues = new LinkJLabel();
issues.setFont(issues.getFont().deriveFont(20f));
issues.setBounds(616, 36, 128, 32);
// Mods
mods = new LinkJLabel();
mods.setFont(mods.getFont().deriveFont(20f));
mods.setBounds(FRAME_WIDTH - 96 - xShift, 36, 96, 32);
// Progress Bar
progressBar = new JProgressBar();
progressBar.setBounds((FRAME_WIDTH / 2) - 200, (FRAME_HEIGHT - 70) + yShift, 400, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
// Social media
github = new LinkJButton();
github.setBounds(8 + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
github.setBorder(null);
twitter = new LinkJButton();
twitter.setBounds(8 + (38 * 4) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
twitter.setBorder(null);
facebook = new LinkJButton();
facebook.setBounds(8 + (38 * 3) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
facebook.setBorder(null);
gplus = new LinkJButton();
gplus.setBounds(8 + (38 * 2) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
gplus.setBorder(null);
youtube = new LinkJButton();
youtube.setBounds(8 + 38 + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
youtube.setBorder(null);
reddit = new LinkJButton();
reddit.setBounds(8 + (38 * 5) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
reddit.setBorder(null);
final Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.add(logo);
contentPane.add(forums);
contentPane.add(issues);
contentPane.add(mods);
contentPane.add(version);
contentPane.add(downloadButton);
contentPane.add(startButton);
contentPane.add(deleteButton);
contentPane.add(settingsButton);
contentPane.add(exitButton);
contentPane.add(github);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(gplus);
contentPane.add(youtube);
contentPane.add(reddit);
contentPane.add(progressBar);
contentPane.add(sp);
contentPane.add(topPanel);
contentPane.add(updatePanel);
}
private TerasologyGameVersion getSelectedGameVersion() {
return gameVersions.getGameVersionForBuildVersion(launcherSettings.getJob(),
launcherSettings.getBuildVersion(launcherSettings.getJob()));
}
@Override
public void actionPerformed(final ActionEvent e) {
if (e.getSource() instanceof JComponent) {
action(e.getActionCommand());
}
}
private void action(final String command) {
if (command.equals(SETTINGS_ACTION)) {
if ((settingsMenu == null) || !settingsMenu.isVisible()) {
settingsMenu = new SettingsMenu(this, launcherDirectory, launcherSettings, gameVersions);
settingsMenu.setVisible(true);
settingsMenu.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(final WindowEvent e) {
updateGui();
}
});
}
} else if (command.equals(EXIT_ACTION)) {
dispose();
System.exit(0);
} else if (command.equals(START_ACTION)) {
final TerasologyGameVersion gameVersion = getSelectedGameVersion();
if ((gameVersion == null) || !gameVersion.isInstalled()) {
logger.warn("The selected game version can not be started! '{}'", gameVersion);
JOptionPane.showMessageDialog(this, BundleUtils.getLabel("message_error_gameStart"),
BundleUtils.getLabel("message_error_title"), JOptionPane.ERROR_MESSAGE);
updateGui();
} else if (gameStarter.isRunning()) {
logger.debug("The game can not be started because another game is already running!");
JOptionPane.showMessageDialog(this, BundleUtils.getLabel("message_information_gameRunning"),
BundleUtils.getLabel("message_information_title"), JOptionPane.INFORMATION_MESSAGE);
} else {
final boolean gameStarted = gameStarter.startGame(gameVersion, launcherSettings.getMaxHeapSize(),
launcherSettings.getInitialHeapSize());
if (!gameStarted) {
JOptionPane.showMessageDialog(this, BundleUtils.getLabel("message_error_gameStart"),
BundleUtils.getLabel("message_error_title"), JOptionPane.ERROR_MESSAGE);
} else if (launcherSettings.isCloseLauncherAfterGameStart()) {
logger.info("Close launcher after game start.");
dispose();
System.exit(0);
}
}
} else if (command.equals(DOWNLOAD_ACTION)) {
final TerasologyGameVersion gameVersion = getSelectedGameVersion();
if (gameDownloader != null) {
// Cancel download
logger.info("Cancel game download!");
gameDownloader.cancel(false);
} else if ((gameVersion == null) || gameVersion.isInstalled()
|| (gameVersion.getSuccessful() == null) || !gameVersion.getSuccessful()) {
logger.warn("The selected game version can not be downloaded! '{}'", gameVersion);
updateGui();
} else {
try {
gameDownloader = new GameDownloader(progressBar, this, tempDirectory,
launcherSettings.getGamesDirectory(), gameVersion, gameVersions);
} catch (IOException e) {
logger.error("The game download can not be started!", e);
finishedGameDownload(false);
return;
}
gameDownloader.execute();
updateGui();
}
} else if (command.equals(DELETE_ACTION)) {
final TerasologyGameVersion gameVersion = getSelectedGameVersion();
if ((gameVersion != null) && gameVersion.isInstalled()) {
final boolean containsGameData = DirectoryUtils.containsGameData(gameVersion.getInstallationPath());
final String msg;
if (containsGameData) {
msg = BundleUtils.getMessage("confirmDeleteGame_withData", gameVersion.getInstallationPath());
} else {
msg = BundleUtils.getMessage("confirmDeleteGame_withoutData", gameVersion.getInstallationPath());
}
final int option = JOptionPane.showConfirmDialog(this, msg,
BundleUtils.getLabel("message_deleteGame_title"),
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
logger.info("Delete installed game! '{}' '{}'", gameVersion, gameVersion.getInstallationPath());
FileUtils.delete(gameVersion.getInstallationPath());
gameVersions.removeInstallationInfo(gameVersion);
updateGui();
}
} else {
logger.warn("The selected game version can not be deleted! '{}'", gameVersion);
}
}
}
void updateGui() {
updateLocale();
updateButtons();
updateInfoTextPane();
}
private void updateLocale() {
setTitle(BundleUtils.getLabel("launcher_title"));
setIconImage(BundleUtils.getImage("icon"));
if (gameDownloader != null) {
downloadButton.setText(BundleUtils.getLabel("launcher_cancelDownload"));
downloadButton.setToolTipText(BundleUtils.getLabel("tooltip_cancelDownload"));
} else {
downloadButton.setText(BundleUtils.getLabel("launcher_download"));
downloadButton.setToolTipText(BundleUtils.getLabel("tooltip_download"));
}
startButton.setText(BundleUtils.getLabel("launcher_start"));
startButton.setToolTipText(BundleUtils.getLabel("tooltip_start"));
deleteButton.setText(BundleUtils.getLabel("launcher_delete"));
deleteButton.setToolTipText(BundleUtils.getLabel("tooltip_delete"));
settingsButton.setText(BundleUtils.getLabel("launcher_settings"));
settingsButton.setToolTipText(BundleUtils.getLabel("tooltip_settings"));
exitButton.setText(BundleUtils.getLabel("launcher_exit"));
exitButton.setToolTipText(BundleUtils.getLabel("tooltip_exit"));
logo.setToolTipText(BundleUtils.getLabel("tooltip_website") + " - "
+ BundleUtils.getURI("terasology_website"));
logo.setIcon(BundleUtils.getImageIcon("logo"));
logo.setUri(BundleUtils.getURI("terasology_website"));
forums.setText(BundleUtils.getLabel("launcher_forum"));
forums.setToolTipText(BundleUtils.getLabel("tooltip_forum") + " - "
+ BundleUtils.getURI("terasology_forum"));
forums.setUri(BundleUtils.getURI("terasology_forum"));
issues.setText(BundleUtils.getLabel("launcher_issues"));
issues.setToolTipText(BundleUtils.getLabel("tooltip_githubIssues") + " - "
+ BundleUtils.getURI("terasology_github_issues"));
issues.setUri(BundleUtils.getURI("terasology_github_issues"));
mods.setText(BundleUtils.getLabel("launcher_mods"));
mods.setToolTipText(BundleUtils.getLabel("tooltip_mods") + " - "
+ BundleUtils.getURI("terasology_mods"));
mods.setUri(BundleUtils.getURI("terasology_mods"));
github.setToolTipText(BundleUtils.getLabel("tooltip_github") + " - "
+ BundleUtils.getURI("terasology_github"));
github.setUri(BundleUtils.getURI("terasology_github"));
github.setIcon(BundleUtils.getImageIcon("github"));
github.setRolloverIcon(BundleUtils.getImageIcon("github_hover"));
twitter.setToolTipText(BundleUtils.getLabel("tooltip_twitter") + " - "
+ BundleUtils.getURI("terasology_twitter"));
twitter.setUri(BundleUtils.getURI("terasology_twitter"));
twitter.setIcon(BundleUtils.getImageIcon("twitter"));
twitter.setRolloverIcon(BundleUtils.getImageIcon("twitter_hover"));
facebook.setToolTipText(BundleUtils.getLabel("tooltip_facebook") + " - "
+ BundleUtils.getURI("terasology_facebook"));
facebook.setUri(BundleUtils.getURI("terasology_facebook"));
facebook.setIcon(BundleUtils.getImageIcon("facebook"));
facebook.setRolloverIcon(BundleUtils.getImageIcon("facebook_hover"));
gplus.setToolTipText(BundleUtils.getLabel("tooltip_gplus") + " - "
+ BundleUtils.getURI("terasology_gplus"));
gplus.setUri(BundleUtils.getURI("terasology_gplus"));
gplus.setIcon(BundleUtils.getImageIcon("gplus"));
gplus.setRolloverIcon(BundleUtils.getImageIcon("gplus_hover"));
youtube.setToolTipText(BundleUtils.getLabel("tooltip_youtube") + " - "
+ BundleUtils.getURI("terasology_youtube"));
youtube.setUri(BundleUtils.getURI("terasology_youtube"));
youtube.setIcon(BundleUtils.getImageIcon("youtube"));
youtube.setRolloverIcon(BundleUtils.getImageIcon("youtube_hover"));
reddit.setToolTipText(BundleUtils.getLabel("tooltip_reddit") + " - "
+ BundleUtils.getURI("terasology_reddit"));
reddit.setUri(BundleUtils.getURI("terasology_reddit"));
reddit.setIcon(BundleUtils.getImageIcon("reddit"));
reddit.setRolloverIcon(BundleUtils.getImageIcon("reddit_hover"));
}
private void updateButtons() {
final TerasologyGameVersion gameVersion = getSelectedGameVersion();
if (gameVersion == null) {
downloadButton.setEnabled(false);
startButton.setEnabled(false);
deleteButton.setEnabled(false);
} else if (gameVersion.isInstalled()) {
downloadButton.setEnabled(false);
startButton.setEnabled(true);
deleteButton.setEnabled(true);
} else if ((gameVersion.getSuccessful() != null) && gameVersion.getSuccessful()
&& (gameVersion.getBuildNumber() != null) && (gameDownloader == null)) {
downloadButton.setEnabled(true);
startButton.setEnabled(false);
deleteButton.setEnabled(false);
} else {
downloadButton.setEnabled(false);
startButton.setEnabled(false);
deleteButton.setEnabled(false);
}
// Cancel download
if (gameDownloader != null) {
downloadButton.setEnabled(true);
}
}
private String escapeHtml(final String text) {
return text.replace("&", "&").replace("<", "<").replace(">", ">")
.replace("\"", """).replace("'", "'").replace("/", "/");
}
private void updateInfoTextPane() {
final TerasologyGameVersion gameVersion = getSelectedGameVersion();
final String gameInfoText;
if ((gameVersion == null) || (gameVersion.getJob() == null) || (gameVersion.getBuildNumber() == null)) {
gameInfoText = "";
} else {
gameInfoText = getGameInfoText(gameVersion);
}
infoTextPane.setText(gameInfoText);
infoTextPane.setCaretPosition(0);
}
private String getGameInfoText(final TerasologyGameVersion gameVersion) {
final Object[] arguments = new Object[9];
arguments[0] = gameVersion.getJob().name();
if (gameVersion.getJob().isStable()) {
arguments[1] = 1;
} else {
arguments[1] = 0;
}
arguments[2] = gameVersion.getJob().getGitBranch();
arguments[3] = gameVersion.getBuildNumber();
if (gameVersion.isLatest()) {
arguments[4] = 1;
} else {
arguments[4] = 0;
}
if (gameVersion.isInstalled()) {
arguments[5] = 1;
} else {
arguments[5] = 0;
}
if ((gameVersion.getSuccessful() != null) && gameVersion.getSuccessful()) {
arguments[6] = 1;
} else {
arguments[6] = 0;
}
if ((gameVersion.getGameVersionInfo() != null)
&& (gameVersion.getGameVersionInfo().getDisplayVersion() != null)) {
arguments[7] = gameVersion.getGameVersionInfo().getDisplayVersion();
} else {
arguments[7] = "";
}
if ((gameVersion.getGameVersionInfo() != null)
&& (gameVersion.getGameVersionInfo().getDateTime() != null)) {
arguments[8] = gameVersion.getGameVersionInfo().getDateTime();
} else {
arguments[8] = "";
}
final String infoHeader1 = BundleUtils.getMessage(gameVersion.getJob().getInfoMessageKey(), arguments);
final String infoHeader2 = BundleUtils.getMessage("infoHeader2", arguments);
final StringBuilder b = new StringBuilder();
if ((infoHeader1 != null) && (infoHeader1.trim().length() > 0)) {
b.append("<h1>");
b.append(escapeHtml(infoHeader1));
b.append("</h1>\n");
}
if ((infoHeader2 != null) && (infoHeader2.trim().length() > 0)) {
b.append("<h2>");
b.append(escapeHtml(infoHeader2));
b.append("</h2>\n");
}
b.append("<strong>\n");
b.append(BundleUtils.getLabel("infoHeader3"));
b.append("</strong>\n");
if ((gameVersion.getChangeLog() != null) && !gameVersion.getChangeLog().isEmpty()) {
b.append("<p>\n");
b.append(BundleUtils.getLabel("infoHeader4"));
b.append("<ul>\n");
for (String msg : gameVersion.getChangeLog()) {
b.append("<li>");
b.append(escapeHtml(msg));
b.append("</li>\n");
}
b.append("</ul>\n");
b.append("</p>\n");
}
return b.toString();
}
void finishedGameDownload(final boolean successful) {
gameDownloader = null;
progressBar.setVisible(false);
updateGui();
if (!successful) {
JOptionPane.showMessageDialog(this, BundleUtils.getLabel("message_error_gameDownload"),
BundleUtils.getLabel("message_error_title"), JOptionPane.ERROR_MESSAGE);
}
}
}
| false | true | private void initComponents() {
final int xShift = 0;
int yShift = 0;
if (isUndecorated()) {
yShift += 30;
}
// Download button
downloadButton = new TSButton(BundleUtils.getLabel("launcher_download"));
downloadButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (4 * 40)) + yShift, 96, 32);
downloadButton.setActionCommand(DOWNLOAD_ACTION);
downloadButton.addActionListener(this);
// Start button
startButton = new TSButton(BundleUtils.getLabel("launcher_start"));
startButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (3 * 40)) + yShift, 96, 32);
startButton.setActionCommand(START_ACTION);
startButton.addActionListener(this);
// Delete button
deleteButton = new TSButton(BundleUtils.getLabel("launcher_delete"));
deleteButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (2 * 40)) + yShift, 96, 32);
deleteButton.setActionCommand(DELETE_ACTION);
deleteButton.addActionListener(this);
// Settings Button
settingsButton = new TSButton(BundleUtils.getLabel("launcher_settings"));
settingsButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (1 * 40)) + yShift, 96, 32);
settingsButton.setActionCommand(SETTINGS_ACTION);
settingsButton.addActionListener(this);
// Exit button
exitButton = new TSButton(BundleUtils.getLabel("launcher_exit"));
exitButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (0 * 40)) + yShift, 96, 32);
exitButton.setActionCommand(EXIT_ACTION);
exitButton.addActionListener(this);
// Transparent top panel and content/update panel
final TransparentPanel topPanel = new TransparentPanel(0.5f);
topPanel.setBounds(0, 0, FRAME_WIDTH, 96);
final TransparentPanel updatePanel = new TransparentPanel(0.5f);
updatePanel.setBounds(
(FRAME_WIDTH - INFO_PANEL_WIDTH) / 2,
(FRAME_HEIGHT - INFO_PANEL_HEIGHT) / 2,
INFO_PANEL_WIDTH,
INFO_PANEL_HEIGHT);
infoTextPane = new JTextPane();
infoTextPane.setFont(new Font("Arial", Font.PLAIN, 14));
infoTextPane.setEditable(false);
infoTextPane.setEnabled(false);
infoTextPane.setHighlighter(null);
infoTextPane.setOpaque(false);
infoTextPane.setContentType("text/html");
infoTextPane.setForeground(Color.WHITE);
//infoTextPane.setBounds(updatePanel.getX() + 8, updatePanel.getY() + 8, updatePanelWidth - 16,
// updatePanelHeight - 16);
final JScrollPane sp = new JScrollPane();
sp.getViewport().add(infoTextPane);
sp.getVerticalScrollBar().setOpaque(false);
sp.getVerticalScrollBar().setUI(new TSScrollBarUI());
sp.getViewport().setOpaque(false);
sp.getVerticalScrollBar().setBorder(BorderFactory.createEmptyBorder());
sp.setBorder(BorderFactory.createEmptyBorder());
sp.setOpaque(false);
sp.setPreferredSize(new Dimension(INFO_PANEL_WIDTH - 16, INFO_PANEL_HEIGHT - 16));
sp.setBounds(updatePanel.getX() + 8, updatePanel.getY() + 8, INFO_PANEL_WIDTH - 16, INFO_PANEL_HEIGHT - 16);
// Terasology logo
logo = new LinkJLabel();
logo.setBounds(8, 0, 400, 96);
// Launcher version info label
final JLabel version = new JLabel(TerasologyLauncherVersionInfo.getInstance().getDisplayVersion());
version.setFont(version.getFont().deriveFont(12f));
version.setForeground(Color.WHITE);
version.setBounds(FRAME_WIDTH - 400 - 16 - xShift, 0, 400, 32);
version.setHorizontalAlignment(JLabel.RIGHT);
// Forums link
forums = new LinkJLabel();
forums.setFont(forums.getFont().deriveFont(20f));
forums.setBounds(480, 36, 96, 32);
// Issues link
issues = new LinkJLabel();
issues.setFont(issues.getFont().deriveFont(20f));
issues.setBounds(616, 36, 128, 32);
// Mods
mods = new LinkJLabel();
mods.setFont(mods.getFont().deriveFont(20f));
mods.setBounds(FRAME_WIDTH - 96 - xShift, 36, 96, 32);
// Progress Bar
progressBar = new JProgressBar();
progressBar.setBounds((FRAME_WIDTH / 2) - 200, (FRAME_HEIGHT - 70) + yShift, 400, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
// Social media
github = new LinkJButton();
github.setBounds(8 + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
github.setBorder(null);
twitter = new LinkJButton();
twitter.setBounds(8 + (38 * 4) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
twitter.setBorder(null);
facebook = new LinkJButton();
facebook.setBounds(8 + (38 * 3) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
facebook.setBorder(null);
gplus = new LinkJButton();
gplus.setBounds(8 + (38 * 2) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
gplus.setBorder(null);
youtube = new LinkJButton();
youtube.setBounds(8 + 38 + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
youtube.setBorder(null);
reddit = new LinkJButton();
reddit.setBounds(8 + (38 * 5) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
reddit.setBorder(null);
final Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.add(logo);
contentPane.add(forums);
contentPane.add(issues);
contentPane.add(mods);
contentPane.add(version);
contentPane.add(downloadButton);
contentPane.add(startButton);
contentPane.add(deleteButton);
contentPane.add(settingsButton);
contentPane.add(exitButton);
contentPane.add(github);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(gplus);
contentPane.add(youtube);
contentPane.add(reddit);
contentPane.add(progressBar);
contentPane.add(sp);
contentPane.add(topPanel);
contentPane.add(updatePanel);
}
| private void initComponents() {
final int xShift = 0;
int yShift = 0;
if (isUndecorated()) {
yShift += 30;
}
// Download button
downloadButton = new TSButton(BundleUtils.getLabel("launcher_download"));
downloadButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (4 * 40)) + yShift, 96, 32);
downloadButton.setActionCommand(DOWNLOAD_ACTION);
downloadButton.addActionListener(this);
// Start button
startButton = new TSButton(BundleUtils.getLabel("launcher_start"));
startButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (3 * 40)) + yShift, 96, 32);
startButton.setActionCommand(START_ACTION);
startButton.addActionListener(this);
// Delete button
deleteButton = new TSButton(BundleUtils.getLabel("launcher_delete"));
deleteButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (2 * 40)) + yShift, 96, 32);
deleteButton.setActionCommand(DELETE_ACTION);
deleteButton.addActionListener(this);
// Settings Button
settingsButton = new TSButton(BundleUtils.getLabel("launcher_settings"));
settingsButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (1 * 40)) + yShift, 96, 32);
settingsButton.setActionCommand(SETTINGS_ACTION);
settingsButton.addActionListener(this);
// Exit button
exitButton = new TSButton(BundleUtils.getLabel("launcher_exit"));
exitButton.setBounds(FRAME_WIDTH - 96 - 16 - xShift, (FRAME_HEIGHT - 70 - (0 * 40)) + yShift, 96, 32);
exitButton.setActionCommand(EXIT_ACTION);
exitButton.addActionListener(this);
// Transparent top panel and content/update panel
final TransparentPanel topPanel = new TransparentPanel(0.5f);
topPanel.setBounds(0, 0, FRAME_WIDTH, 96);
final TransparentPanel updatePanel = new TransparentPanel(0.5f);
updatePanel.setBounds(
(FRAME_WIDTH - INFO_PANEL_WIDTH) / 2,
(FRAME_HEIGHT - INFO_PANEL_HEIGHT) / 2,
INFO_PANEL_WIDTH,
INFO_PANEL_HEIGHT);
infoTextPane = new JTextPane();
infoTextPane.setFont(new Font("Arial", Font.PLAIN, 14));
infoTextPane.setEditable(false);
infoTextPane.setEnabled(false);
infoTextPane.setHighlighter(null);
infoTextPane.setOpaque(false);
infoTextPane.setContentType("text/html");
infoTextPane.setForeground(Color.WHITE);
//infoTextPane.setBounds(updatePanel.getX() + 8, updatePanel.getY() + 8, updatePanelWidth - 16,
// updatePanelHeight - 16);
final JScrollPane sp = new JScrollPane();
sp.getViewport().add(infoTextPane);
sp.getViewport().setOpaque(false);
sp.setBorder(BorderFactory.createEmptyBorder());
sp.setOpaque(false);
sp.setPreferredSize(new Dimension(INFO_PANEL_WIDTH - 16, INFO_PANEL_HEIGHT - 16));
sp.setBounds(updatePanel.getX() + 8, updatePanel.getY() + 8, INFO_PANEL_WIDTH - 16, INFO_PANEL_HEIGHT - 16);
sp.getHorizontalScrollBar().setUI(new TSScrollBarUI());
sp.getHorizontalScrollBar().setOpaque(false);
sp.getHorizontalScrollBar().setBorder(BorderFactory.createEmptyBorder());
sp.getVerticalScrollBar().setUI(new TSScrollBarUI());
sp.getVerticalScrollBar().setOpaque(false);
sp.getVerticalScrollBar().setBorder(BorderFactory.createEmptyBorder());
// Terasology logo
logo = new LinkJLabel();
logo.setBounds(8, 0, 400, 96);
// Launcher version info label
final JLabel version = new JLabel(TerasologyLauncherVersionInfo.getInstance().getDisplayVersion());
version.setFont(version.getFont().deriveFont(12f));
version.setForeground(Color.WHITE);
version.setBounds(FRAME_WIDTH - 400 - 16 - xShift, 0, 400, 32);
version.setHorizontalAlignment(JLabel.RIGHT);
// Forums link
forums = new LinkJLabel();
forums.setFont(forums.getFont().deriveFont(20f));
forums.setBounds(480, 36, 96, 32);
// Issues link
issues = new LinkJLabel();
issues.setFont(issues.getFont().deriveFont(20f));
issues.setBounds(616, 36, 128, 32);
// Mods
mods = new LinkJLabel();
mods.setFont(mods.getFont().deriveFont(20f));
mods.setBounds(FRAME_WIDTH - 96 - xShift, 36, 96, 32);
// Progress Bar
progressBar = new JProgressBar();
progressBar.setBounds((FRAME_WIDTH / 2) - 200, (FRAME_HEIGHT - 70) + yShift, 400, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
// Social media
github = new LinkJButton();
github.setBounds(8 + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
github.setBorder(null);
twitter = new LinkJButton();
twitter.setBounds(8 + (38 * 4) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
twitter.setBorder(null);
facebook = new LinkJButton();
facebook.setBounds(8 + (38 * 3) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
facebook.setBorder(null);
gplus = new LinkJButton();
gplus.setBounds(8 + (38 * 2) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
gplus.setBorder(null);
youtube = new LinkJButton();
youtube.setBounds(8 + 38 + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
youtube.setBorder(null);
reddit = new LinkJButton();
reddit.setBounds(8 + (38 * 5) + xShift, (FRAME_HEIGHT - 70) + yShift, 32, 32);
reddit.setBorder(null);
final Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.add(logo);
contentPane.add(forums);
contentPane.add(issues);
contentPane.add(mods);
contentPane.add(version);
contentPane.add(downloadButton);
contentPane.add(startButton);
contentPane.add(deleteButton);
contentPane.add(settingsButton);
contentPane.add(exitButton);
contentPane.add(github);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(gplus);
contentPane.add(youtube);
contentPane.add(reddit);
contentPane.add(progressBar);
contentPane.add(sp);
contentPane.add(topPanel);
contentPane.add(updatePanel);
}
|
diff --git a/activemq-client/src/main/java/org/apache/activemq/command/NetworkBridgeFilter.java b/activemq-client/src/main/java/org/apache/activemq/command/NetworkBridgeFilter.java
index d08e2bb96..673497e05 100644
--- a/activemq-client/src/main/java/org/apache/activemq/command/NetworkBridgeFilter.java
+++ b/activemq-client/src/main/java/org/apache/activemq/command/NetworkBridgeFilter.java
@@ -1,157 +1,157 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.command;
import org.apache.activemq.filter.BooleanExpression;
import org.apache.activemq.filter.MessageEvaluationContext;
import org.apache.activemq.util.JMSExceptionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jms.JMSException;
import java.io.IOException;
import java.util.Arrays;
/**
* @openwire:marshaller code="91"
*
*/
public class NetworkBridgeFilter implements DataStructure, BooleanExpression {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.NETWORK_BRIDGE_FILTER;
static final Logger LOG = LoggerFactory.getLogger(NetworkBridgeFilter.class);
protected BrokerId networkBrokerId;
protected int networkTTL;
transient ConsumerInfo consumerInfo;
public NetworkBridgeFilter() {
}
public NetworkBridgeFilter(ConsumerInfo consumerInfo, BrokerId networkBrokerId, int networkTTL) {
this.networkBrokerId = networkBrokerId;
this.networkTTL = networkTTL;
this.consumerInfo = consumerInfo;
}
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
public boolean isMarshallAware() {
return false;
}
public boolean matches(MessageEvaluationContext mec) throws JMSException {
try {
// for Queues - the message can be acknowledged and dropped whilst
// still
// in the dispatch loop
// so need to get the reference to it
Message message = mec.getMessage();
return message != null && matchesForwardingFilter(message, mec);
} catch (IOException e) {
throw JMSExceptionSupport.create(e);
}
}
public Object evaluate(MessageEvaluationContext message) throws JMSException {
return matches(message) ? Boolean.TRUE : Boolean.FALSE;
}
protected boolean matchesForwardingFilter(Message message, MessageEvaluationContext mec) {
if (contains(message.getBrokerPath(), networkBrokerId)) {
if (LOG.isTraceEnabled()) {
LOG.trace("Message all ready routed once through target broker ("
+ networkBrokerId + "), path: "
+ Arrays.toString(message.getBrokerPath()) + " - ignoring: " + message);
}
return false;
}
int hops = message.getBrokerPath() == null ? 0 : message.getBrokerPath().length;
if (hops >= networkTTL) {
if (LOG.isTraceEnabled()) {
LOG.trace("Message restricted to " + networkTTL + " network hops ignoring: " + message);
}
return false;
}
if (message.isAdvisory()) {
if (consumerInfo != null && consumerInfo.isNetworkSubscription()) {
// they will be interpreted by the bridge leading to dup commands
- //if (LOG.isTraceEnabled()) {
- LOG.error("not propagating advisory to network sub: " + consumerInfo.getConsumerId() + ", message: "+ message);
- //}
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("not propagating advisory to network sub: " + consumerInfo.getConsumerId() + ", message: "+ message);
+ }
return false;
} else if ( message.getDataStructure() != null && message.getDataStructure().getDataStructureType() == CommandTypes.CONSUMER_INFO) {
ConsumerInfo info = (ConsumerInfo)message.getDataStructure();
hops = info.getBrokerPath() == null ? 0 : info.getBrokerPath().length;
if (hops >= networkTTL) {
if (LOG.isTraceEnabled()) {
LOG.trace("ConsumerInfo advisory restricted to " + networkTTL + " network hops ignoring: " + message);
}
return false;
}
if (contains(info.getBrokerPath(), networkBrokerId)) {
LOG.trace("ConsumerInfo advisory all ready routed once through target broker ("
+ networkBrokerId + "), path: "
+ Arrays.toString(info.getBrokerPath()) + " - ignoring: " + message);
return false;
}
}
}
return true;
}
public static boolean contains(BrokerId[] brokerPath, BrokerId brokerId) {
if (brokerPath != null && brokerId != null) {
for (int i = 0; i < brokerPath.length; i++) {
if (brokerId.equals(brokerPath[i])) {
return true;
}
}
}
return false;
}
/**
* @openwire:property version=1
*/
public int getNetworkTTL() {
return networkTTL;
}
public void setNetworkTTL(int networkTTL) {
this.networkTTL = networkTTL;
}
/**
* @openwire:property version=1 cache=true
*/
public BrokerId getNetworkBrokerId() {
return networkBrokerId;
}
public void setNetworkBrokerId(BrokerId remoteBrokerPath) {
this.networkBrokerId = remoteBrokerPath;
}
}
| true | true | protected boolean matchesForwardingFilter(Message message, MessageEvaluationContext mec) {
if (contains(message.getBrokerPath(), networkBrokerId)) {
if (LOG.isTraceEnabled()) {
LOG.trace("Message all ready routed once through target broker ("
+ networkBrokerId + "), path: "
+ Arrays.toString(message.getBrokerPath()) + " - ignoring: " + message);
}
return false;
}
int hops = message.getBrokerPath() == null ? 0 : message.getBrokerPath().length;
if (hops >= networkTTL) {
if (LOG.isTraceEnabled()) {
LOG.trace("Message restricted to " + networkTTL + " network hops ignoring: " + message);
}
return false;
}
if (message.isAdvisory()) {
if (consumerInfo != null && consumerInfo.isNetworkSubscription()) {
// they will be interpreted by the bridge leading to dup commands
//if (LOG.isTraceEnabled()) {
LOG.error("not propagating advisory to network sub: " + consumerInfo.getConsumerId() + ", message: "+ message);
//}
return false;
} else if ( message.getDataStructure() != null && message.getDataStructure().getDataStructureType() == CommandTypes.CONSUMER_INFO) {
ConsumerInfo info = (ConsumerInfo)message.getDataStructure();
hops = info.getBrokerPath() == null ? 0 : info.getBrokerPath().length;
if (hops >= networkTTL) {
if (LOG.isTraceEnabled()) {
LOG.trace("ConsumerInfo advisory restricted to " + networkTTL + " network hops ignoring: " + message);
}
return false;
}
if (contains(info.getBrokerPath(), networkBrokerId)) {
LOG.trace("ConsumerInfo advisory all ready routed once through target broker ("
+ networkBrokerId + "), path: "
+ Arrays.toString(info.getBrokerPath()) + " - ignoring: " + message);
return false;
}
}
}
return true;
}
| protected boolean matchesForwardingFilter(Message message, MessageEvaluationContext mec) {
if (contains(message.getBrokerPath(), networkBrokerId)) {
if (LOG.isTraceEnabled()) {
LOG.trace("Message all ready routed once through target broker ("
+ networkBrokerId + "), path: "
+ Arrays.toString(message.getBrokerPath()) + " - ignoring: " + message);
}
return false;
}
int hops = message.getBrokerPath() == null ? 0 : message.getBrokerPath().length;
if (hops >= networkTTL) {
if (LOG.isTraceEnabled()) {
LOG.trace("Message restricted to " + networkTTL + " network hops ignoring: " + message);
}
return false;
}
if (message.isAdvisory()) {
if (consumerInfo != null && consumerInfo.isNetworkSubscription()) {
// they will be interpreted by the bridge leading to dup commands
if (LOG.isTraceEnabled()) {
LOG.trace("not propagating advisory to network sub: " + consumerInfo.getConsumerId() + ", message: "+ message);
}
return false;
} else if ( message.getDataStructure() != null && message.getDataStructure().getDataStructureType() == CommandTypes.CONSUMER_INFO) {
ConsumerInfo info = (ConsumerInfo)message.getDataStructure();
hops = info.getBrokerPath() == null ? 0 : info.getBrokerPath().length;
if (hops >= networkTTL) {
if (LOG.isTraceEnabled()) {
LOG.trace("ConsumerInfo advisory restricted to " + networkTTL + " network hops ignoring: " + message);
}
return false;
}
if (contains(info.getBrokerPath(), networkBrokerId)) {
LOG.trace("ConsumerInfo advisory all ready routed once through target broker ("
+ networkBrokerId + "), path: "
+ Arrays.toString(info.getBrokerPath()) + " - ignoring: " + message);
return false;
}
}
}
return true;
}
|
diff --git a/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/preferences/REnvPreferencePage.java b/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/preferences/REnvPreferencePage.java
index 227f9809..b3c71e89 100644
--- a/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/preferences/REnvPreferencePage.java
+++ b/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/preferences/REnvPreferencePage.java
@@ -1,352 +1,353 @@
/*******************************************************************************
* Copyright (c) 2007-2010 WalWare/StatET-Project (www.walware.de/goto/statet).
* 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:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.internal.debug.ui.preferences;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IElementComparer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
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.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
import org.eclipse.ui.statushandlers.StatusManager;
import de.walware.ecommons.preferences.IPreferenceAccess;
import de.walware.ecommons.preferences.PreferencesUtil;
import de.walware.ecommons.preferences.ui.ConfigurationBlock;
import de.walware.ecommons.ui.SharedMessages;
import de.walware.ecommons.ui.components.ButtonGroup;
import de.walware.ecommons.ui.components.DropDownButton;
import de.walware.ecommons.ui.util.LayoutUtil;
import de.walware.ecommons.ui.util.ViewerUtil;
import de.walware.ecommons.ui.util.ViewerUtil.TableComposite;
import de.walware.statet.r.core.RCore;
import de.walware.statet.r.core.renv.IREnv;
import de.walware.statet.r.core.renv.IREnvConfiguration;
import de.walware.statet.r.core.renv.IREnvManager;
import de.walware.statet.r.ui.RUI;
/**
* Preference page for R (Environment) configuration of the workbench.
*/
public class REnvPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public static final String PREF_PAGE_ID = "de.walware.statet.r.preferencePages.REnvironmentPage"; //$NON-NLS-1$
private TableViewer fListViewer;
private ButtonGroup<IREnvConfiguration.WorkingCopy> fListButtons;
private IObservableList fList;
private IObservableValue fDefault;
public REnvPreferencePage() {
}
public void init(final IWorkbench workbench) {
fList = new WritableList();
fDefault = new WritableValue();
}
@Override
protected Control createContents(final Composite parent) {
final Composite pageComposite = new Composite(parent, SWT.NONE);
pageComposite.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 1));
final Label label = new Label(pageComposite, SWT.LEFT);
label.setText(Messages.REnv_REnvList_label);
label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
{ // Table area
final Composite composite = new Composite(pageComposite, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 2));
final Composite table = createTable(composite);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fListButtons = new ButtonGroup<IREnvConfiguration.WorkingCopy>(composite) {
@Override
protected IREnvConfiguration.WorkingCopy edit1(final IREnvConfiguration.WorkingCopy config, final boolean newConfig, final Object parent) {
IREnvConfiguration.WorkingCopy editConfig;
if (newConfig) {
if (config != null) {
editConfig = RCore.getREnvManager().newConfiguration(config.getType());
editConfig.load(config);
}
else {
return null;
}
}
else {
editConfig = config.createWorkingCopy();
}
if (edit(editConfig, newConfig)) {
if (newConfig) {
return editConfig;
}
else {
config.load(editConfig);
return config;
}
}
return null;
}
@Override
protected boolean isModifyAllowed(final Object element) {
final IREnvConfiguration config = (IREnvConfiguration) element;
return config.isEditable();
}
@Override
public void updateState() {
super.updateState();
REnvPreferencePage.this.updateStatus();
}
};
fListButtons.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, true));
final SelectionListener addDefaultListener = new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IREnvConfiguration.WorkingCopy config = RCore.getREnvManager()
.newConfiguration(IREnvConfiguration.USER_LOCAL_TYPE);
if (edit(config, true)) {
fList.add(config);
+ fListButtons.setDirty(true);
fListViewer.refresh();
}
}
};
final DropDownButton addButton = new DropDownButton(fListButtons) {
@Override
protected void fillDropDownMenu(final Menu menu) {
{ final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Add Local (default)...");
menuItem.addSelectionListener(addDefaultListener);
}
{ final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Add Remote...");
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IREnvConfiguration.WorkingCopy config = RCore.getREnvManager()
.newConfiguration(IREnvConfiguration.USER_REMOTE_TYPE);
if (edit(config, true)) {
fList.add(config);
fListButtons.setDirty(true);
fListViewer.refresh();
}
}
});
}
}
};
addButton.addSelectionListener(addDefaultListener);
addButton.setText(SharedMessages.CollectionEditing_AddItem_label);
addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fListButtons.addCopyButton();
fListButtons.addEditButton();
fListButtons.addDeleteButton();
fListButtons.addSeparator();
fListButtons.addDefaultButton();
fListButtons.connectTo(fListViewer, fList, fDefault);
fListViewer.setComparer(new IElementComparer() {
public int hashCode(final Object element) {
if (element instanceof IREnvConfiguration) {
return ((IREnvConfiguration) element).getReference().hashCode();
}
return element.hashCode();
}
public boolean equals(final Object a, final Object b) {
if (a instanceof IREnvConfiguration && b instanceof IREnvConfiguration) {
return ((IREnvConfiguration) a).getReference().equals(
((IREnvConfiguration) b).getReference());
}
return a.equals(b);
}
});
fListViewer.setInput(fList);
}
loadValues(PreferencesUtil.getInstancePrefs());
fListButtons.refresh();
applyDialogFont(pageComposite);
return pageComposite;
}
private boolean edit(final IREnvConfiguration.WorkingCopy config, final boolean newConfig) {
final List<IREnvConfiguration> existingConfigs = new ArrayList<IREnvConfiguration>(fList);
if (!newConfig) {
for (final Iterator<IREnvConfiguration> iter = existingConfigs.iterator(); iter.hasNext();) {
final IREnvConfiguration existing = iter.next();
if (existing.getReference() == config.getReference()) {
iter.remove();
break;
}
}
}
Dialog dialog;
if (config.getType() == IREnvConfiguration.USER_LOCAL_TYPE) {
dialog = new REnvLocalConfigDialog(getShell(),
config, newConfig, existingConfigs);
}
else if (config.getType() == IREnvConfiguration.USER_REMOTE_TYPE) {
dialog = new REnvRemoteConfigDialog(getShell(),
config, newConfig, existingConfigs);
}
else {
return false;
}
return (dialog.open() == Dialog.OK);
}
protected Composite createTable(final Composite parent) {
final TableComposite composite = new ViewerUtil.TableComposite(parent, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
fListViewer = composite.viewer;
composite.table.setHeaderVisible(true);
composite.table.setLinesVisible(true);
{ final TableViewerColumn column = new TableViewerColumn(composite.viewer, SWT.NONE);
composite.layout.setColumnData(column.getColumn(), new ColumnWeightData(1));
column.getColumn().setText(Messages.REnv_NameColumn_name);
column.setLabelProvider(new REnvLabelProvider(fDefault));
}
{ final TableViewerColumn column = new TableViewerColumn(composite.viewer, SWT.NONE);
composite.layout.setColumnData(column.getColumn(), new ColumnWeightData(1));
column.getColumn().setText(Messages.REnv_LocationColumn_name);
column.setLabelProvider(new ColumnLabelProvider() {
@Override
public Image getImage(final Object element) {
return super.getImage(element);
}
@Override
public String getText(final Object element) {
final IREnvConfiguration config = (IREnvConfiguration) element;
if (config.getType() == IREnvConfiguration.USER_LOCAL_TYPE) {
return config.getRHome();
}
return ""; //$NON-NLS-1$
}
});
}
composite.viewer.setContentProvider(new ArrayContentProvider());
// Sorter
composite.viewer.setComparator(new ViewerComparator() {
@SuppressWarnings("unchecked")
@Override
public int compare(final Viewer viewer, final Object e1, final Object e2) {
return getComparator().compare(((IREnvConfiguration.WorkingCopy) e1).getName(), ((IREnvConfiguration.WorkingCopy) e2).getName());
}
});
return composite;
}
@Override
protected void performDefaults() {
}
@Override
public boolean performOk() {
if (fListButtons.isDirty()) {
return saveValues(false);
}
return true;
}
@Override
protected void performApply() {
saveValues(true);
}
private void updateStatus() {
if (fDefault.getValue() == null) {
setMessage(Messages.REnv_warning_NoDefaultConfiguration_message, IStatus.WARNING);
return;
}
setMessage(null);
}
private boolean saveValues(final boolean saveStore) {
try {
final IREnvConfiguration.WorkingCopy defaultREnv = (IREnvConfiguration.WorkingCopy) fDefault.getValue();
final String[] groupIds = RCore.getREnvManager().set(
(IREnvConfiguration[]) fList.toArray(new IREnvConfiguration.WorkingCopy[fList.size()]),
(defaultREnv != null) ? defaultREnv.getReference().getId() : null);
if (groupIds != null) {
ConfigurationBlock.scheduleChangeNotification(
(IWorkbenchPreferenceContainer) getContainer(), groupIds, saveStore);
}
return true;
}
catch (final CoreException e) {
StatusManager.getManager().handle(new Status(IStatus.ERROR, RUI.PLUGIN_ID,
-1, Messages.REnv_error_Saving_message, e),
StatusManager.LOG | StatusManager.SHOW);
return false;
}
}
private void loadValues(final IPreferenceAccess prefs) {
fList.clear();
fDefault.setValue(null);
final IREnvManager manager = RCore.getREnvManager();
final IREnv defaultEnv = manager.getDefault().resolve();
final IREnvConfiguration[] configurations = manager.getConfigurations();
for (final IREnvConfiguration rEnvConfig : configurations) {
final IREnvConfiguration.WorkingCopy config = rEnvConfig.createWorkingCopy();
fList.add(config);
if (config.getReference() == defaultEnv) {
fDefault.setValue(config);
}
}
}
}
| true | true | protected Control createContents(final Composite parent) {
final Composite pageComposite = new Composite(parent, SWT.NONE);
pageComposite.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 1));
final Label label = new Label(pageComposite, SWT.LEFT);
label.setText(Messages.REnv_REnvList_label);
label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
{ // Table area
final Composite composite = new Composite(pageComposite, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 2));
final Composite table = createTable(composite);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fListButtons = new ButtonGroup<IREnvConfiguration.WorkingCopy>(composite) {
@Override
protected IREnvConfiguration.WorkingCopy edit1(final IREnvConfiguration.WorkingCopy config, final boolean newConfig, final Object parent) {
IREnvConfiguration.WorkingCopy editConfig;
if (newConfig) {
if (config != null) {
editConfig = RCore.getREnvManager().newConfiguration(config.getType());
editConfig.load(config);
}
else {
return null;
}
}
else {
editConfig = config.createWorkingCopy();
}
if (edit(editConfig, newConfig)) {
if (newConfig) {
return editConfig;
}
else {
config.load(editConfig);
return config;
}
}
return null;
}
@Override
protected boolean isModifyAllowed(final Object element) {
final IREnvConfiguration config = (IREnvConfiguration) element;
return config.isEditable();
}
@Override
public void updateState() {
super.updateState();
REnvPreferencePage.this.updateStatus();
}
};
fListButtons.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, true));
final SelectionListener addDefaultListener = new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IREnvConfiguration.WorkingCopy config = RCore.getREnvManager()
.newConfiguration(IREnvConfiguration.USER_LOCAL_TYPE);
if (edit(config, true)) {
fList.add(config);
fListViewer.refresh();
}
}
};
final DropDownButton addButton = new DropDownButton(fListButtons) {
@Override
protected void fillDropDownMenu(final Menu menu) {
{ final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Add Local (default)...");
menuItem.addSelectionListener(addDefaultListener);
}
{ final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Add Remote...");
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IREnvConfiguration.WorkingCopy config = RCore.getREnvManager()
.newConfiguration(IREnvConfiguration.USER_REMOTE_TYPE);
if (edit(config, true)) {
fList.add(config);
fListButtons.setDirty(true);
fListViewer.refresh();
}
}
});
}
}
};
addButton.addSelectionListener(addDefaultListener);
addButton.setText(SharedMessages.CollectionEditing_AddItem_label);
addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fListButtons.addCopyButton();
fListButtons.addEditButton();
fListButtons.addDeleteButton();
fListButtons.addSeparator();
fListButtons.addDefaultButton();
fListButtons.connectTo(fListViewer, fList, fDefault);
fListViewer.setComparer(new IElementComparer() {
public int hashCode(final Object element) {
if (element instanceof IREnvConfiguration) {
return ((IREnvConfiguration) element).getReference().hashCode();
}
return element.hashCode();
}
public boolean equals(final Object a, final Object b) {
if (a instanceof IREnvConfiguration && b instanceof IREnvConfiguration) {
return ((IREnvConfiguration) a).getReference().equals(
((IREnvConfiguration) b).getReference());
}
return a.equals(b);
}
});
fListViewer.setInput(fList);
}
loadValues(PreferencesUtil.getInstancePrefs());
fListButtons.refresh();
applyDialogFont(pageComposite);
return pageComposite;
}
| protected Control createContents(final Composite parent) {
final Composite pageComposite = new Composite(parent, SWT.NONE);
pageComposite.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 1));
final Label label = new Label(pageComposite, SWT.LEFT);
label.setText(Messages.REnv_REnvList_label);
label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
{ // Table area
final Composite composite = new Composite(pageComposite, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 2));
final Composite table = createTable(composite);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fListButtons = new ButtonGroup<IREnvConfiguration.WorkingCopy>(composite) {
@Override
protected IREnvConfiguration.WorkingCopy edit1(final IREnvConfiguration.WorkingCopy config, final boolean newConfig, final Object parent) {
IREnvConfiguration.WorkingCopy editConfig;
if (newConfig) {
if (config != null) {
editConfig = RCore.getREnvManager().newConfiguration(config.getType());
editConfig.load(config);
}
else {
return null;
}
}
else {
editConfig = config.createWorkingCopy();
}
if (edit(editConfig, newConfig)) {
if (newConfig) {
return editConfig;
}
else {
config.load(editConfig);
return config;
}
}
return null;
}
@Override
protected boolean isModifyAllowed(final Object element) {
final IREnvConfiguration config = (IREnvConfiguration) element;
return config.isEditable();
}
@Override
public void updateState() {
super.updateState();
REnvPreferencePage.this.updateStatus();
}
};
fListButtons.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, true));
final SelectionListener addDefaultListener = new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IREnvConfiguration.WorkingCopy config = RCore.getREnvManager()
.newConfiguration(IREnvConfiguration.USER_LOCAL_TYPE);
if (edit(config, true)) {
fList.add(config);
fListButtons.setDirty(true);
fListViewer.refresh();
}
}
};
final DropDownButton addButton = new DropDownButton(fListButtons) {
@Override
protected void fillDropDownMenu(final Menu menu) {
{ final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Add Local (default)...");
menuItem.addSelectionListener(addDefaultListener);
}
{ final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Add Remote...");
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final IREnvConfiguration.WorkingCopy config = RCore.getREnvManager()
.newConfiguration(IREnvConfiguration.USER_REMOTE_TYPE);
if (edit(config, true)) {
fList.add(config);
fListButtons.setDirty(true);
fListViewer.refresh();
}
}
});
}
}
};
addButton.addSelectionListener(addDefaultListener);
addButton.setText(SharedMessages.CollectionEditing_AddItem_label);
addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fListButtons.addCopyButton();
fListButtons.addEditButton();
fListButtons.addDeleteButton();
fListButtons.addSeparator();
fListButtons.addDefaultButton();
fListButtons.connectTo(fListViewer, fList, fDefault);
fListViewer.setComparer(new IElementComparer() {
public int hashCode(final Object element) {
if (element instanceof IREnvConfiguration) {
return ((IREnvConfiguration) element).getReference().hashCode();
}
return element.hashCode();
}
public boolean equals(final Object a, final Object b) {
if (a instanceof IREnvConfiguration && b instanceof IREnvConfiguration) {
return ((IREnvConfiguration) a).getReference().equals(
((IREnvConfiguration) b).getReference());
}
return a.equals(b);
}
});
fListViewer.setInput(fList);
}
loadValues(PreferencesUtil.getInstancePrefs());
fListButtons.refresh();
applyDialogFont(pageComposite);
return pageComposite;
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java b/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java
index e16f14963..a5d487a9d 100644
--- a/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java
+++ b/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java
@@ -1,110 +1,106 @@
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import org.restlet.Context;
// [excludes gwt]
/**
* Readable byte channel enforcing a maximum size.
*/
public class ReadableSizedChannel extends WrapperChannel<ReadableByteChannel>
implements ReadableByteChannel {
/** The total available size that should be read from the source channel. */
private volatile long availableSize;
/**
* Constructor.
*
* @param source
* The source channel.
* @param availableSize
* The total available size that can be read from the source
* channel.
*/
public ReadableSizedChannel(ReadableByteChannel source, long availableSize) {
super(source);
this.availableSize = availableSize;
}
/**
* Reads some bytes and put them into the destination buffer. The bytes come
* from the underlying channel.
*
* @param dst
* The destination buffer.
* @return The number of bytes read, or -1 if the end of the channel has
* been reached.
*/
public int read(ByteBuffer dst) throws IOException {
int result = -1;
if (this.availableSize > 0) {
if (this.availableSize < dst.remaining()) {
dst.limit((int) (this.availableSize + dst.position()));
}
result = getWrappedChannel().read(dst);
- } else {
- // Should be 0
- int finalRead = getWrappedChannel().read(dst);
- Context.getCurrentLogger().info("Final read : " + finalRead);
}
if (result > 0) {
this.availableSize -= result;
if (Context.getCurrentLogger().isLoggable(Level.FINE)) {
Context.getCurrentLogger().fine(
"Bytes read / available : " + result + " / "
+ this.availableSize);
}
if (this.availableSize == 0) {
if (Context.getCurrentLogger().isLoggable(Level.FINE)) {
Context.getCurrentLogger().fine("Channel fully read.");
}
}
}
if (getWrappedChannel() instanceof ReadableBufferedChannel) {
((ReadableBufferedChannel) getWrappedChannel()).postRead(result);
}
return result;
}
}
| true | true | public int read(ByteBuffer dst) throws IOException {
int result = -1;
if (this.availableSize > 0) {
if (this.availableSize < dst.remaining()) {
dst.limit((int) (this.availableSize + dst.position()));
}
result = getWrappedChannel().read(dst);
} else {
// Should be 0
int finalRead = getWrappedChannel().read(dst);
Context.getCurrentLogger().info("Final read : " + finalRead);
}
if (result > 0) {
this.availableSize -= result;
if (Context.getCurrentLogger().isLoggable(Level.FINE)) {
Context.getCurrentLogger().fine(
"Bytes read / available : " + result + " / "
+ this.availableSize);
}
if (this.availableSize == 0) {
if (Context.getCurrentLogger().isLoggable(Level.FINE)) {
Context.getCurrentLogger().fine("Channel fully read.");
}
}
}
if (getWrappedChannel() instanceof ReadableBufferedChannel) {
((ReadableBufferedChannel) getWrappedChannel()).postRead(result);
}
return result;
}
| public int read(ByteBuffer dst) throws IOException {
int result = -1;
if (this.availableSize > 0) {
if (this.availableSize < dst.remaining()) {
dst.limit((int) (this.availableSize + dst.position()));
}
result = getWrappedChannel().read(dst);
}
if (result > 0) {
this.availableSize -= result;
if (Context.getCurrentLogger().isLoggable(Level.FINE)) {
Context.getCurrentLogger().fine(
"Bytes read / available : " + result + " / "
+ this.availableSize);
}
if (this.availableSize == 0) {
if (Context.getCurrentLogger().isLoggable(Level.FINE)) {
Context.getCurrentLogger().fine("Channel fully read.");
}
}
}
if (getWrappedChannel() instanceof ReadableBufferedChannel) {
((ReadableBufferedChannel) getWrappedChannel()).postRead(result);
}
return result;
}
|
diff --git a/agile-apps/agile-app-dashboard/src/main/java/org/headsupdev/agile/app/dashboard/Account.java b/agile-apps/agile-app-dashboard/src/main/java/org/headsupdev/agile/app/dashboard/Account.java
index e07b8f1c..071bc1a7 100644
--- a/agile-apps/agile-app-dashboard/src/main/java/org/headsupdev/agile/app/dashboard/Account.java
+++ b/agile-apps/agile-app-dashboard/src/main/java/org/headsupdev/agile/app/dashboard/Account.java
@@ -1,290 +1,295 @@
/*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program 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.
*
* 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 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 org.headsupdev.agile.app.dashboard;
import org.headsupdev.agile.api.Event;
import org.headsupdev.agile.api.Manager;
import org.headsupdev.agile.api.Permission;
import org.headsupdev.agile.api.User;
import org.headsupdev.agile.app.dashboard.permission.MemberViewPermission;
import org.headsupdev.agile.security.permission.AdminPermission;
import org.headsupdev.agile.storage.HibernateStorage;
import org.headsupdev.agile.storage.StoredProject;
import org.headsupdev.agile.storage.issues.Duration;
import org.headsupdev.agile.storage.resource.DurationWorked;
import org.headsupdev.agile.storage.issues.Issue;
import org.headsupdev.agile.storage.resource.ResourceManagerImpl;
import org.headsupdev.agile.storage.resource.Velocity;
import org.headsupdev.agile.web.BookmarkableMenuLink;
import org.headsupdev.agile.web.HeadsUpPage;
import org.headsupdev.agile.web.HeadsUpSession;
import org.headsupdev.agile.web.MountPoint;
import org.headsupdev.agile.web.components.FormattedDateModel;
import org.headsupdev.agile.web.components.UserDetailsPanel;
import org.headsupdev.agile.web.components.history.HistoryPanel;
import org.headsupdev.agile.web.components.issues.IssueListPanel;
import org.headsupdev.agile.web.components.issues.IssueStatusModifier;
import org.headsupdev.agile.web.wicket.SortableEntityProvider;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.headsupdev.support.java.DateUtil;
import org.headsupdev.support.java.StringUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* The HeadsUp about page.
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
@MountPoint("account")
public class Account
extends HeadsUpPage
{
private String username;
public Permission getRequiredPermission()
{
return new MemberViewPermission();
}
public void layout()
{
super.layout();
add( CSSPackageResource.getHeaderContribution( getClass(), "account.css" ) );
org.headsupdev.agile.api.User user = getSession().getUser();
username = getPageParameters().getString( "username" );
if ( username != null )
{
user = getSecurityManager().getUserByUsername( username );
if ( user == null || user.equals( HeadsUpSession.ANONYMOUS_USER ) )
{
notFoundError();
return;
}
}
final org.headsupdev.agile.api.User finalUser = user;
boolean showTools = ( user.equals( getSession().getUser() ) && !user.equals( HeadsUpSession.ANONYMOUS_USER ) ) ||
getSecurityManager().userHasPermission( getSession().getUser(), new AdminPermission(), null );
final boolean timeEnabled = Boolean.parseBoolean( StoredProject.getDefault().getConfigurationValue(
StoredProject.CONFIGURATION_TIMETRACKING_ENABLED ) );
final boolean showVelocity = timeEnabled && showTools;
WebMarkupContainer velocityPanel = new WebMarkupContainer( "velocity" );
add( velocityPanel.setVisible( showVelocity ) );
if ( showVelocity )
{
Velocity velocity = getResourceManager().getUserVelocity( user );
String velocityStr = "-";
if ( !velocity.equals( Velocity.INVALID ) )
{
velocityStr = String.format( "%.1f", velocity.getVelocity() );
}
velocityPanel.add( new Label( "velocity", velocityStr ) );
Velocity currentVelocity = getResourceManager().getCurrentUserVelocity( user );
String currentVelocityStr = "-";
if ( !currentVelocity.equals( Velocity.INVALID ) )
{
currentVelocityStr = String.format( "%.1f", currentVelocity.getVelocity() );
}
velocityPanel.add( new Label( "currentvelocity", currentVelocityStr ) );
Velocity averageVelocity = getResourceManager().getAverageVelocity();
String averageVelocityStr = "-";
if ( !averageVelocity.equals( Velocity.INVALID ) )
{
averageVelocityStr = String.format( "%.1f", averageVelocity.getVelocity() );
}
velocityPanel.add( new Label( "averagevelocity", averageVelocityStr ) );
}
PageParameters params = new PageParameters();
params.add( "username", user.getUsername() );
params.add( "silent", "true" );
add( new Image( "account", new ResourceReference( "member.png" ), params ) );
add( new UserDetailsPanel( "details", user, getProject(), shouldShowFullDetails() ) );
if ( showTools )
{
params = getPageParameters();
addLink( new BookmarkableMenuLink( getPageClass( "editaccount" ), params, "edit" ) );
addLink( new BookmarkableMenuLink( getPageClass( "changepassword" ), params, "change-password" ) );
addLink( new BookmarkableMenuLink( getPageClass( "subscriptions" ), params, "subscriptions" ) );
}
add( new Label( "issues-name", user.getFullnameOrUsername() ) );
add( new IssueListPanel( "issues", getIssuesWatchedBy( finalUser ), this, false, false ) );
Calendar calendar = Calendar.getInstance();
Date startOfWeek = DateUtil.getStartOfWeekCurrent( calendar );
Date endOfWeek = DateUtil.getEndOfWeekCurrent( calendar );
Date startOfToday = DateUtil.getStartOfToday( calendar );
Date endOfToday = DateUtil.getEndOfToday( calendar );
Duration durationDay = getResourceManager().getLoggedTimeForUser( user, startOfToday, endOfToday );
add( new Label( "loggedtimeday", durationDay == null ? " - " : durationDay.toString() ) );
Duration durationWeek = getResourceManager().getLoggedTimeForUser( user, startOfWeek, endOfWeek );
add( new Label( "loggedtimeweek", durationWeek == null ? " - " : durationWeek.toString() ) );
add( new ListView<DurationWorked>( "comments", getRecentDurationWorked( user ) )
{
protected void populateItem( ListItem<DurationWorked> listItem )
{
DurationWorked worked = listItem.getModelObject();
+ if ( worked.getIssue() == null )
+ {
+ listItem.setVisible( false );
+ return;
+ }
WebMarkupContainer workedTitle = new WebMarkupContainer( "worked-title" );
listItem.add( new Image( "icon", new ResourceReference( HeadsUpPage.class, "images/worked.png" ) ) );
String time = "";
if ( worked.getWorked() != null )
{
time = worked.getWorked().toString();
}
workedTitle.add( new Label( "worked", time ) );
Issue related = worked.getIssue();
PageParameters params = new PageParameters();
params.put( "project", related.getProject() );
params.put( "id", related.getId() );
BookmarkablePageLink link = new BookmarkablePageLink( "issue-link", getPageClass( "issues/view" ), params );
String issueId = related.getProject().getId() + ":" + related.getId();
link.add( new Label( "issue", "issue:" + issueId ) );
workedTitle.add( link.add( new IssueStatusModifier( "relatedstatus", related ) ) );
workedTitle.add( new Label( "summary", related.getSummary() )
.add( new IssueStatusModifier( "relatedstatus", related ) ) );
workedTitle.add( new Label( "username", worked.getUser().getFullnameOrUsername() ) );
workedTitle.add( new Label( "created", new FormattedDateModel( worked.getDay(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
listItem.add( workedTitle );
}
}.setVisible( showTools && timeEnabled ) );
add( new Label( "history-name", user.getFullnameOrUsername() ) );
add( new HistoryPanel( "events", getEventsForUser( user ), true ) );
}
@Override
public String getPageTitle()
{
return super.getPageTitle() + " :: Account:" + username;
}
private boolean shouldShowFullDetails()
{
User currentUser = getSession().getUser();
return ( currentUser != null && !currentUser.equals( HeadsUpSession.ANONYMOUS_USER ) );
}
public SortableEntityProvider<Issue> getIssuesWatchedBy( final org.headsupdev.agile.api.User user )
{
return new SortableEntityProvider<Issue>()
{
@Override
protected Criteria createCriteria()
{
Session session = ( (HibernateStorage) Manager.getStorageInstance() ).getHibernateSession();
Criteria c = session.createCriteria( Issue.class );
c.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );
c.add( Restrictions.lt( "status", Issue.STATUS_RESOLVED ) );
c.createCriteria( "watchers" ).add( Restrictions.eq( "username", user.getUsername() ) );
return c;
}
@Override
protected List<Order> getDefaultOrder()
{
return Arrays.asList( Order.asc( "priority" ),
Order.asc( "status" ), Order.asc( "id.id" ) );
}
};
}
public List<DurationWorked> getRecentDurationWorked( org.headsupdev.agile.api.User user )
{
Session session = ( (HibernateStorage) getStorage() ).getHibernateSession();
Query q = session.createQuery( "from DurationWorked d where user = :user order by day desc" );
q.setEntity( "user", user );
q.setMaxResults( 10 );
return q.list();
}
public List<Event> getEventsForUser( org.headsupdev.agile.api.User user )
{
Session session = ( (HibernateStorage) getStorage() ).getHibernateSession();
Query q = session.createQuery( "from StoredEvent e where username = :username or " +
"username like :emailLike or username like :nameLike order by time desc" );
q.setString( "username", user.getUsername() );
if ( !StringUtil.isEmpty( user.getEmail() ) )
{
q.setString( "emailLike", "%<" + user.getEmail() + ">" );
}
else
{
// a silly fallback for now
q.setString( "emailLike", user.getUsername() );
}
if ( !StringUtil.isEmpty( user.getFullname() ) )
{
q.setString( "nameLike", user.getFullname() + " <%" );
}
else
{
// a silly fallback for now
q.setString( "nameLike", user.getUsername() );
}
q.setMaxResults( 10 );
return q.list();
}
public ResourceManagerImpl getResourceManager()
{
return ( (HibernateStorage) getStorage() ).getResourceManager();
}
}
| true | true | public void layout()
{
super.layout();
add( CSSPackageResource.getHeaderContribution( getClass(), "account.css" ) );
org.headsupdev.agile.api.User user = getSession().getUser();
username = getPageParameters().getString( "username" );
if ( username != null )
{
user = getSecurityManager().getUserByUsername( username );
if ( user == null || user.equals( HeadsUpSession.ANONYMOUS_USER ) )
{
notFoundError();
return;
}
}
final org.headsupdev.agile.api.User finalUser = user;
boolean showTools = ( user.equals( getSession().getUser() ) && !user.equals( HeadsUpSession.ANONYMOUS_USER ) ) ||
getSecurityManager().userHasPermission( getSession().getUser(), new AdminPermission(), null );
final boolean timeEnabled = Boolean.parseBoolean( StoredProject.getDefault().getConfigurationValue(
StoredProject.CONFIGURATION_TIMETRACKING_ENABLED ) );
final boolean showVelocity = timeEnabled && showTools;
WebMarkupContainer velocityPanel = new WebMarkupContainer( "velocity" );
add( velocityPanel.setVisible( showVelocity ) );
if ( showVelocity )
{
Velocity velocity = getResourceManager().getUserVelocity( user );
String velocityStr = "-";
if ( !velocity.equals( Velocity.INVALID ) )
{
velocityStr = String.format( "%.1f", velocity.getVelocity() );
}
velocityPanel.add( new Label( "velocity", velocityStr ) );
Velocity currentVelocity = getResourceManager().getCurrentUserVelocity( user );
String currentVelocityStr = "-";
if ( !currentVelocity.equals( Velocity.INVALID ) )
{
currentVelocityStr = String.format( "%.1f", currentVelocity.getVelocity() );
}
velocityPanel.add( new Label( "currentvelocity", currentVelocityStr ) );
Velocity averageVelocity = getResourceManager().getAverageVelocity();
String averageVelocityStr = "-";
if ( !averageVelocity.equals( Velocity.INVALID ) )
{
averageVelocityStr = String.format( "%.1f", averageVelocity.getVelocity() );
}
velocityPanel.add( new Label( "averagevelocity", averageVelocityStr ) );
}
PageParameters params = new PageParameters();
params.add( "username", user.getUsername() );
params.add( "silent", "true" );
add( new Image( "account", new ResourceReference( "member.png" ), params ) );
add( new UserDetailsPanel( "details", user, getProject(), shouldShowFullDetails() ) );
if ( showTools )
{
params = getPageParameters();
addLink( new BookmarkableMenuLink( getPageClass( "editaccount" ), params, "edit" ) );
addLink( new BookmarkableMenuLink( getPageClass( "changepassword" ), params, "change-password" ) );
addLink( new BookmarkableMenuLink( getPageClass( "subscriptions" ), params, "subscriptions" ) );
}
add( new Label( "issues-name", user.getFullnameOrUsername() ) );
add( new IssueListPanel( "issues", getIssuesWatchedBy( finalUser ), this, false, false ) );
Calendar calendar = Calendar.getInstance();
Date startOfWeek = DateUtil.getStartOfWeekCurrent( calendar );
Date endOfWeek = DateUtil.getEndOfWeekCurrent( calendar );
Date startOfToday = DateUtil.getStartOfToday( calendar );
Date endOfToday = DateUtil.getEndOfToday( calendar );
Duration durationDay = getResourceManager().getLoggedTimeForUser( user, startOfToday, endOfToday );
add( new Label( "loggedtimeday", durationDay == null ? " - " : durationDay.toString() ) );
Duration durationWeek = getResourceManager().getLoggedTimeForUser( user, startOfWeek, endOfWeek );
add( new Label( "loggedtimeweek", durationWeek == null ? " - " : durationWeek.toString() ) );
add( new ListView<DurationWorked>( "comments", getRecentDurationWorked( user ) )
{
protected void populateItem( ListItem<DurationWorked> listItem )
{
DurationWorked worked = listItem.getModelObject();
WebMarkupContainer workedTitle = new WebMarkupContainer( "worked-title" );
listItem.add( new Image( "icon", new ResourceReference( HeadsUpPage.class, "images/worked.png" ) ) );
String time = "";
if ( worked.getWorked() != null )
{
time = worked.getWorked().toString();
}
workedTitle.add( new Label( "worked", time ) );
Issue related = worked.getIssue();
PageParameters params = new PageParameters();
params.put( "project", related.getProject() );
params.put( "id", related.getId() );
BookmarkablePageLink link = new BookmarkablePageLink( "issue-link", getPageClass( "issues/view" ), params );
String issueId = related.getProject().getId() + ":" + related.getId();
link.add( new Label( "issue", "issue:" + issueId ) );
workedTitle.add( link.add( new IssueStatusModifier( "relatedstatus", related ) ) );
workedTitle.add( new Label( "summary", related.getSummary() )
.add( new IssueStatusModifier( "relatedstatus", related ) ) );
workedTitle.add( new Label( "username", worked.getUser().getFullnameOrUsername() ) );
workedTitle.add( new Label( "created", new FormattedDateModel( worked.getDay(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
listItem.add( workedTitle );
}
}.setVisible( showTools && timeEnabled ) );
add( new Label( "history-name", user.getFullnameOrUsername() ) );
add( new HistoryPanel( "events", getEventsForUser( user ), true ) );
}
| public void layout()
{
super.layout();
add( CSSPackageResource.getHeaderContribution( getClass(), "account.css" ) );
org.headsupdev.agile.api.User user = getSession().getUser();
username = getPageParameters().getString( "username" );
if ( username != null )
{
user = getSecurityManager().getUserByUsername( username );
if ( user == null || user.equals( HeadsUpSession.ANONYMOUS_USER ) )
{
notFoundError();
return;
}
}
final org.headsupdev.agile.api.User finalUser = user;
boolean showTools = ( user.equals( getSession().getUser() ) && !user.equals( HeadsUpSession.ANONYMOUS_USER ) ) ||
getSecurityManager().userHasPermission( getSession().getUser(), new AdminPermission(), null );
final boolean timeEnabled = Boolean.parseBoolean( StoredProject.getDefault().getConfigurationValue(
StoredProject.CONFIGURATION_TIMETRACKING_ENABLED ) );
final boolean showVelocity = timeEnabled && showTools;
WebMarkupContainer velocityPanel = new WebMarkupContainer( "velocity" );
add( velocityPanel.setVisible( showVelocity ) );
if ( showVelocity )
{
Velocity velocity = getResourceManager().getUserVelocity( user );
String velocityStr = "-";
if ( !velocity.equals( Velocity.INVALID ) )
{
velocityStr = String.format( "%.1f", velocity.getVelocity() );
}
velocityPanel.add( new Label( "velocity", velocityStr ) );
Velocity currentVelocity = getResourceManager().getCurrentUserVelocity( user );
String currentVelocityStr = "-";
if ( !currentVelocity.equals( Velocity.INVALID ) )
{
currentVelocityStr = String.format( "%.1f", currentVelocity.getVelocity() );
}
velocityPanel.add( new Label( "currentvelocity", currentVelocityStr ) );
Velocity averageVelocity = getResourceManager().getAverageVelocity();
String averageVelocityStr = "-";
if ( !averageVelocity.equals( Velocity.INVALID ) )
{
averageVelocityStr = String.format( "%.1f", averageVelocity.getVelocity() );
}
velocityPanel.add( new Label( "averagevelocity", averageVelocityStr ) );
}
PageParameters params = new PageParameters();
params.add( "username", user.getUsername() );
params.add( "silent", "true" );
add( new Image( "account", new ResourceReference( "member.png" ), params ) );
add( new UserDetailsPanel( "details", user, getProject(), shouldShowFullDetails() ) );
if ( showTools )
{
params = getPageParameters();
addLink( new BookmarkableMenuLink( getPageClass( "editaccount" ), params, "edit" ) );
addLink( new BookmarkableMenuLink( getPageClass( "changepassword" ), params, "change-password" ) );
addLink( new BookmarkableMenuLink( getPageClass( "subscriptions" ), params, "subscriptions" ) );
}
add( new Label( "issues-name", user.getFullnameOrUsername() ) );
add( new IssueListPanel( "issues", getIssuesWatchedBy( finalUser ), this, false, false ) );
Calendar calendar = Calendar.getInstance();
Date startOfWeek = DateUtil.getStartOfWeekCurrent( calendar );
Date endOfWeek = DateUtil.getEndOfWeekCurrent( calendar );
Date startOfToday = DateUtil.getStartOfToday( calendar );
Date endOfToday = DateUtil.getEndOfToday( calendar );
Duration durationDay = getResourceManager().getLoggedTimeForUser( user, startOfToday, endOfToday );
add( new Label( "loggedtimeday", durationDay == null ? " - " : durationDay.toString() ) );
Duration durationWeek = getResourceManager().getLoggedTimeForUser( user, startOfWeek, endOfWeek );
add( new Label( "loggedtimeweek", durationWeek == null ? " - " : durationWeek.toString() ) );
add( new ListView<DurationWorked>( "comments", getRecentDurationWorked( user ) )
{
protected void populateItem( ListItem<DurationWorked> listItem )
{
DurationWorked worked = listItem.getModelObject();
if ( worked.getIssue() == null )
{
listItem.setVisible( false );
return;
}
WebMarkupContainer workedTitle = new WebMarkupContainer( "worked-title" );
listItem.add( new Image( "icon", new ResourceReference( HeadsUpPage.class, "images/worked.png" ) ) );
String time = "";
if ( worked.getWorked() != null )
{
time = worked.getWorked().toString();
}
workedTitle.add( new Label( "worked", time ) );
Issue related = worked.getIssue();
PageParameters params = new PageParameters();
params.put( "project", related.getProject() );
params.put( "id", related.getId() );
BookmarkablePageLink link = new BookmarkablePageLink( "issue-link", getPageClass( "issues/view" ), params );
String issueId = related.getProject().getId() + ":" + related.getId();
link.add( new Label( "issue", "issue:" + issueId ) );
workedTitle.add( link.add( new IssueStatusModifier( "relatedstatus", related ) ) );
workedTitle.add( new Label( "summary", related.getSummary() )
.add( new IssueStatusModifier( "relatedstatus", related ) ) );
workedTitle.add( new Label( "username", worked.getUser().getFullnameOrUsername() ) );
workedTitle.add( new Label( "created", new FormattedDateModel( worked.getDay(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
listItem.add( workedTitle );
}
}.setVisible( showTools && timeEnabled ) );
add( new Label( "history-name", user.getFullnameOrUsername() ) );
add( new HistoryPanel( "events", getEventsForUser( user ), true ) );
}
|
diff --git a/src/main/java/com/salesforce/phoenix/schema/MetaDataClient.java b/src/main/java/com/salesforce/phoenix/schema/MetaDataClient.java
index 27e0a230..ff8c6a48 100644
--- a/src/main/java/com/salesforce/phoenix/schema/MetaDataClient.java
+++ b/src/main/java/com/salesforce/phoenix/schema/MetaDataClient.java
@@ -1,1174 +1,1173 @@
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, 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 Salesforce.com 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 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 com.salesforce.phoenix.schema;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_COUNT;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_MODIFIER;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_SIZE;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.DATA_TABLE_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.DATA_TYPE;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.DECIMAL_DIGITS;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.IMMUTABLE_ROWS;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.INDEX_STATE;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.NULLABLE;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.ORDINAL_POSITION;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.PK_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.SALT_BUCKETS;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_CAT_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_NAME_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_SCHEM_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_SEQ_NUM;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_TYPE_NAME;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SCHEMA;
import static com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_TABLE;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.salesforce.phoenix.compile.ColumnResolver;
import com.salesforce.phoenix.compile.FromCompiler;
import com.salesforce.phoenix.compile.MutationPlan;
import com.salesforce.phoenix.compile.PostDDLCompiler;
import com.salesforce.phoenix.compile.PostIndexDDLCompiler;
import com.salesforce.phoenix.coprocessor.MetaDataProtocol;
import com.salesforce.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult;
import com.salesforce.phoenix.coprocessor.MetaDataProtocol.MutationCode;
import com.salesforce.phoenix.exception.SQLExceptionCode;
import com.salesforce.phoenix.exception.SQLExceptionInfo;
import com.salesforce.phoenix.execute.MutationState;
import com.salesforce.phoenix.jdbc.PhoenixConnection;
import com.salesforce.phoenix.jdbc.PhoenixDatabaseMetaData;
import com.salesforce.phoenix.parse.AddColumnStatement;
import com.salesforce.phoenix.parse.AlterIndexStatement;
import com.salesforce.phoenix.parse.ColumnDef;
import com.salesforce.phoenix.parse.ColumnName;
import com.salesforce.phoenix.parse.CreateIndexStatement;
import com.salesforce.phoenix.parse.CreateTableStatement;
import com.salesforce.phoenix.parse.DropColumnStatement;
import com.salesforce.phoenix.parse.DropIndexStatement;
import com.salesforce.phoenix.parse.DropTableStatement;
import com.salesforce.phoenix.parse.ParseNodeFactory;
import com.salesforce.phoenix.parse.PrimaryKeyConstraint;
import com.salesforce.phoenix.parse.TableName;
import com.salesforce.phoenix.query.QueryConstants;
import com.salesforce.phoenix.query.QueryServices;
import com.salesforce.phoenix.query.QueryServicesOptions;
import com.salesforce.phoenix.util.IndexUtil;
import com.salesforce.phoenix.util.MetaDataUtil;
import com.salesforce.phoenix.util.PhoenixRuntime;
import com.salesforce.phoenix.util.SchemaUtil;
public class MetaDataClient {
private static final Logger logger = LoggerFactory.getLogger(MetaDataClient.class);
private static final ParseNodeFactory FACTORY = new ParseNodeFactory();
private static final String CREATE_TABLE =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
TABLE_TYPE_NAME + "," +
TABLE_SEQ_NUM + "," +
COLUMN_COUNT + "," +
SALT_BUCKETS + "," +
PK_NAME + "," +
DATA_TABLE_NAME + "," +
INDEX_STATE + "," +
IMMUTABLE_ROWS +
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String CREATE_INDEX_LINK =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
TABLE_CAT_NAME +
") VALUES (?, ?, ?)";
private static final String INCREMENT_SEQ_NUM =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
TABLE_SEQ_NUM +
") VALUES (?, ?, ?)";
private static final String MUTATE_TABLE =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
TABLE_TYPE_NAME + "," +
TABLE_SEQ_NUM + "," +
COLUMN_COUNT + "," +
IMMUTABLE_ROWS +
") VALUES (?, ?, ?, ?, ?, ?)";
// For system table, don't set IMMUTABLE_ROWS, since at upgrade time
// between 1.2 and 2.0, we'll add this column (and we don't yet have
// the column while upgrading).
private static final String MUTATE_SYSTEM_TABLE =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
TABLE_TYPE_NAME + "," +
TABLE_SEQ_NUM + "," +
COLUMN_COUNT +
") VALUES (?, ?, ?, ?, ?)";
private static final String UPDATE_INDEX_STATE =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
INDEX_STATE +
") VALUES (?, ?, ?)";
private static final String INSERT_COLUMN =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
COLUMN_NAME + "," +
TABLE_CAT_NAME + "," +
DATA_TYPE + "," +
NULLABLE + "," +
COLUMN_SIZE + "," +
DECIMAL_DIGITS + "," +
ORDINAL_POSITION + "," +
COLUMN_MODIFIER + "," +
DATA_TABLE_NAME + // write this both in the column and table rows for access by metadata APIs
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
// Don't write DATA_TABLE_NAME for system table since at upgrade time from 1.2 to 2.0, we won't have this column yet.
private static final String INSERT_SYSTEM_COLUMN =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\"( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
COLUMN_NAME + "," +
TABLE_CAT_NAME + "," +
DATA_TYPE + "," +
NULLABLE + "," +
COLUMN_SIZE + "," +
DECIMAL_DIGITS + "," +
ORDINAL_POSITION +
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String UPDATE_COLUMN_POSITION =
"UPSERT INTO " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\" ( " +
TABLE_SCHEM_NAME + "," +
TABLE_NAME_NAME + "," +
COLUMN_NAME + "," +
TABLE_CAT_NAME + "," +
ORDINAL_POSITION +
") VALUES (?, ?, ?, ?, ?)";
private final PhoenixConnection connection;
public MetaDataClient(PhoenixConnection connection) {
this.connection = connection;
}
/**
* Update the cache with the latest as of the connection scn.
* @param schemaName
* @param tableName
* @return the timestamp from the server, negative if the cache was updated and positive otherwise
* @throws SQLException
*/
public long updateCache(String schemaName, String tableName) throws SQLException {
Long scn = connection.getSCN();
long clientTimeStamp = scn == null ? HConstants.LATEST_TIMESTAMP : scn;
// TODO: better to check the type of the table
if (TYPE_SCHEMA.equals(schemaName) && TYPE_TABLE.equals(tableName)) {
return clientTimeStamp;
}
PTable table = null;
String fullTableName = SchemaUtil.getTableName(schemaName, tableName);
long tableTimestamp = HConstants.LATEST_TIMESTAMP;
try {
table = connection.getPMetaData().getTable(fullTableName);
tableTimestamp = table.getTimeStamp();
} catch (TableNotFoundException e) {
}
// Don't bother with server call: we can't possibly find a newer table
// TODO: review - this seems weird
if (tableTimestamp == clientTimeStamp - 1) {
return clientTimeStamp;
}
final byte[] schemaBytes = PDataType.VARCHAR.toBytes(schemaName);
final byte[] tableBytes = PDataType.VARCHAR.toBytes(tableName);
MetaDataMutationResult result = connection.getQueryServices().getTable(schemaBytes, tableBytes, tableTimestamp, clientTimeStamp);
MutationCode code = result.getMutationCode();
PTable resultTable = result.getTable();
// We found an updated table, so update our cache
if (resultTable != null) {
connection.addTable(resultTable);
return -result.getMutationTime();
} else {
// if (result.getMutationCode() == MutationCode.NEWER_TABLE_FOUND) {
// TODO: No table exists at the clientTimestamp, but a newer one exists.
// Since we disallow creation or modification of a table earlier than the latest
// timestamp, we can handle this such that we don't ask the
// server again.
// If table was not found at the current time stamp and we have one cached, remove it.
// Otherwise, we're up to date, so there's nothing to do.
if (code == MutationCode.TABLE_NOT_FOUND && table != null) {
connection.removeTable(fullTableName);
return -result.getMutationTime();
}
}
return result.getMutationTime();
}
private void addColumnMutation(String schemaName, String tableName, PColumn column, PreparedStatement colUpsert, String parentTableName, boolean isSalted) throws SQLException {
colUpsert.setString(1, schemaName);
colUpsert.setString(2, tableName);
colUpsert.setString(3, column.getName().getString());
colUpsert.setString(4, column.getFamilyName() == null ? null : column.getFamilyName().getString());
colUpsert.setInt(5, column.getDataType().getSqlType());
colUpsert.setInt(6, column.isNullable() ? ResultSetMetaData.columnNullable : ResultSetMetaData.columnNoNulls);
if (column.getMaxLength() == null) {
colUpsert.setNull(7, Types.INTEGER);
} else {
colUpsert.setInt(7, column.getMaxLength());
}
if (column.getScale() == null) {
colUpsert.setNull(8, Types.INTEGER);
} else {
colUpsert.setInt(8, column.getScale());
}
colUpsert.setInt(9, column.getPosition() + (isSalted ? 0 : 1));
if (colUpsert.getParameterMetaData().getParameterCount() > 9) {
colUpsert.setInt(10, ColumnModifier.toSystemValue(column.getColumnModifier()));
}
if (colUpsert.getParameterMetaData().getParameterCount() > 10) {
colUpsert.setString(11, parentTableName);
}
colUpsert.execute();
}
private PColumn newColumn(int position, ColumnDef def, PrimaryKeyConstraint pkConstraint) throws SQLException {
try {
ColumnName columnDefName = def.getColumnDefName();
ColumnModifier columnModifier = def.getColumnModifier();
boolean isPK = def.isPK();
if (pkConstraint != null) {
Pair<ColumnName,ColumnModifier> pkColumnModifier = pkConstraint.getColumn(columnDefName);
if (pkColumnModifier != null) {
isPK = true;
columnModifier = pkColumnModifier.getSecond();
}
}
String columnName = columnDefName.getColumnName();
PName familyName = null;
if (def.isPK() && !pkConstraint.getColumnNames().isEmpty() ) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_ALREADY_EXISTS)
.setColumnName(columnName).build().buildException();
}
if (def.getColumnDefName().getFamilyName() != null) {
String family = def.getColumnDefName().getFamilyName();
if (isPK) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_WITH_FAMILY_NAME)
.setColumnName(columnName).setFamilyName(family).build().buildException();
} else if (!def.isNull()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.KEY_VALUE_NOT_NULL)
.setColumnName(columnName).setFamilyName(family).build().buildException();
}
familyName = PNameFactory.newName(family);
} else if (!isPK) {
familyName = PNameFactory.newName(QueryConstants.DEFAULT_COLUMN_FAMILY);
}
PColumn column = new PColumnImpl(PNameFactory.newName(columnName), familyName, def.getDataType(),
def.getMaxLength(), def.getScale(), def.isNull(), position, columnModifier);
return column;
} catch (IllegalArgumentException e) { // Based on precondition check in constructor
throw new SQLException(e);
}
}
public MutationState createTable(CreateTableStatement statement, byte[][] splits) throws SQLException {
PTable table = createTable(statement, splits, null);
if (table == null || table.getType() == PTableType.VIEW) {
return new MutationState(0,connection);
}
// Hack to get around the case when an SCN is specified on the connection.
// In this case, we won't see the table we just created yet, so we hack
// around it by forcing the compiler to not resolve anything.
PostDDLCompiler compiler = new PostDDLCompiler(connection);
//connection.setAutoCommit(true);
// Execute any necessary data updates
Long scn = connection.getSCN();
long ts = (scn == null ? table.getTimeStamp() : scn);
// Getting the schema through the current connection doesn't work when the connection has an scn specified
// Since the table won't be added to the current connection.
TableRef tableRef = new TableRef(null, table, ts, false);
byte[] emptyCF = SchemaUtil.getEmptyColumnFamily(table.getColumnFamilies());
MutationPlan plan = compiler.compile(Collections.singletonList(tableRef), emptyCF, null, null, tableRef.getTimeStamp());
return connection.getQueryServices().updateData(plan);
}
/**
* Create an index table by morphing the CreateIndexStatement into a CreateTableStatement and calling
* MetaDataClient.createTable. In doing so, we perform the following translations:
* 1) Change the type of any columns being indexed to types that support null if the column is nullable.
* For example, a BIGINT type would be coerced to a DECIMAL type, since a DECIMAL type supports null
* when it's in the row key while a BIGINT does not.
* 2) Append any row key column from the data table that is not in the indexed column list. Our indexes
* rely on having a 1:1 correspondence between the index and data rows.
* 3) Change the name of the columns to include the column family. For example, if you have a column
* named "B" in a column family named "A", the indexed column name will be "A:B". This makes it easy
* to translate the column references in a query to the correct column references in an index table
* regardless of whether the column reference is prefixed with the column family name or not. It also
* has the side benefit of allowing the same named column in different column families to both be
* listed as an index column.
* @param statement
* @param splits
* @return MutationState from population of index table from data table
* @throws SQLException
*/
public MutationState createIndex(CreateIndexStatement statement, byte[][] splits) throws SQLException {
PrimaryKeyConstraint pk = statement.getIndexConstraint();
TableName indexTableName = statement.getIndexTableName();
String dataTableName = statement.getTable().getName().getTableName();
int hbaseVersion = connection.getQueryServices().getLowestClusterHBaseVersion();
if (hbaseVersion < PhoenixDatabaseMetaData.MUTABLE_SI_VERSION_THRESHOLD) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.NO_MUTABLE_INDEXES).setTableName(indexTableName.getTableName()).build().buildException();
}
List<Pair<ColumnName, ColumnModifier>> indexedPkColumns = pk.getColumnNames();
List<ColumnName> includedColumns = statement.getIncludeColumns();
TableRef tableRef = null;
PTable table = null;
boolean retry = true;
while (true) {
try {
ColumnResolver resolver = FromCompiler.getResolver(statement, connection);
tableRef = resolver.getTables().get(0);
PTable dataTable = tableRef.getTable();
Set<PColumn> unusedPkColumns;
if (dataTable.getBucketNum() != null) { // Ignore SALT column
unusedPkColumns = new LinkedHashSet<PColumn>(dataTable.getPKColumns().subList(1, dataTable.getPKColumns().size()));
} else {
unusedPkColumns = new LinkedHashSet<PColumn>(dataTable.getPKColumns());
}
List<Pair<ColumnName, ColumnModifier>> allPkColumns = Lists.newArrayListWithExpectedSize(unusedPkColumns.size());
List<ColumnDef> columnDefs = Lists.newArrayListWithExpectedSize(includedColumns.size() + indexedPkColumns.size());
// First columns are the indexed ones
for (Pair<ColumnName, ColumnModifier> pair : indexedPkColumns) {
ColumnName colName = pair.getFirst();
PColumn col = resolver.resolveColumn(null, colName.getFamilyName(), colName.getColumnName()).getColumn();
unusedPkColumns.remove(col);
PDataType dataType = IndexUtil.getIndexColumnDataType(col);
colName = ColumnName.caseSensitiveColumnName(IndexUtil.getIndexColumnName(col));
allPkColumns.add(new Pair<ColumnName, ColumnModifier>(colName, pair.getSecond()));
columnDefs.add(FACTORY.columnDef(colName, dataType.getSqlTypeName(), col.isNullable(), col.getMaxLength(), col.getScale(), false, null));
}
// Next all the PK columns from the data table that aren't indexed
if (!unusedPkColumns.isEmpty()) {
for (PColumn col : unusedPkColumns) {
ColumnName colName = ColumnName.caseSensitiveColumnName(IndexUtil.getIndexColumnName(col));
allPkColumns.add(new Pair<ColumnName, ColumnModifier>(colName, col.getColumnModifier()));
PDataType dataType = IndexUtil.getIndexColumnDataType(col);
columnDefs.add(FACTORY.columnDef(colName, dataType.getSqlTypeName(), col.isNullable(), col.getMaxLength(), col.getScale(), false, col.getColumnModifier()));
}
}
pk = FACTORY.primaryKey(null, allPkColumns);
// Last all the included columns (minus any PK columns)
for (ColumnName colName : includedColumns) {
PColumn col = resolver.resolveColumn(null, colName.getFamilyName(), colName.getColumnName()).getColumn();
if (SchemaUtil.isPKColumn(col)) {
if (!unusedPkColumns.contains(col)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.COLUMN_EXIST_IN_DEF).build().buildException();
}
} else {
colName = ColumnName.caseSensitiveColumnName(IndexUtil.getIndexColumnName(col));
// Check for duplicates between indexed and included columns
if (pk.contains(colName)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.COLUMN_EXIST_IN_DEF).build().buildException();
}
if (!SchemaUtil.isPKColumn(col)) {
// Need to re-create ColumnName, since the above one won't have the column family name
colName = ColumnName.caseSensitiveColumnName(col.getFamilyName().getString(), IndexUtil.getIndexColumnName(col));
columnDefs.add(FACTORY.columnDef(colName, col.getDataType().getSqlTypeName(), col.isNullable(), col.getMaxLength(), col.getScale(), false, col.getColumnModifier()));
}
}
}
CreateTableStatement tableStatement = FACTORY.createTable(indexTableName, statement.getProps(), columnDefs, pk, statement.getSplitNodes(), PTableType.INDEX, statement.ifNotExists(), statement.getBindCount());
table = createTable(tableStatement, splits, tableRef.getTable());
break;
} catch (ConcurrentTableMutationException e) { // Can happen if parent data table changes while above is in progress
if (retry) {
retry = false;
continue;
}
throw e;
}
}
if (table == null) {
return new MutationState(0,connection);
}
boolean success = false;
MetaDataClient client = this;
SQLException sqlException = null;
try {
// If our connection is at a fixed point-in-time, we need to open a new
// connection so that our new index table is visible.
if (connection.getSCN() != null) {
Properties props = new Properties(connection.getClientInfo());
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(connection.getSCN()+1));
client = new MetaDataClient(DriverManager.getConnection(connection.getURL(), props).unwrap(PhoenixConnection.class));
// Re-resolve the tableRef from the now newer connection
ColumnResolver resolver = FromCompiler.getResolver(statement, client.connection);
tableRef = resolver.getTables().get(0);
}
PostIndexDDLCompiler compiler = new PostIndexDDLCompiler(client.connection, tableRef);
MutationPlan plan = compiler.compile(table);
MutationState state = client.connection.getQueryServices().updateData(plan);
AlterIndexStatement indexStatement = FACTORY.alterIndex(FACTORY.namedTable(null, indexTableName), dataTableName, false, PIndexState.ACTIVE);
client.alterIndex(indexStatement);
success = true;
return state;
} catch (SQLException e) {
sqlException = e;
} finally {
// If we had to open another connection, then close it here
if (client != this) {
try {
client.connection.close();
} catch (SQLException e) {
if (sqlException == null) {
// If we're not in the middle of throwing another exception
// then throw the exception we got on close.
if (success) {
sqlException = e;
}
} else {
sqlException.setNextException(e);
}
}
}
if (sqlException != null) {
throw sqlException;
}
}
throw new IllegalStateException(); // impossible
}
private PTable createTable(CreateTableStatement statement, byte[][] splits, PTable parent) throws SQLException {
PTableType tableType = statement.getTableType();
boolean wasAutoCommit = connection.getAutoCommit();
connection.rollback();
try {
connection.setAutoCommit(false);
List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(statement.getColumnDefs().size() + 3);
TableName tableNameNode = statement.getTableName();
String schemaName = tableNameNode.getSchemaName();
String tableName = tableNameNode.getTableName();
String parentTableName = null;
if (parent != null) {
parentTableName = parent.getTableName().getString();
// Pass through data table sequence number so we can check it hasn't changed
PreparedStatement incrementStatement = connection.prepareStatement(INCREMENT_SEQ_NUM);
incrementStatement.setString(1, schemaName);
incrementStatement.setString(2, parentTableName);
incrementStatement.setLong(3, parent.getSequenceNumber());
incrementStatement.execute();
// Get list of mutations and add to table meta data that will be passed to server
// to guarantee order. This row will always end up last
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
// Add row linking from data table row to index table row
PreparedStatement linkStatement = connection.prepareStatement(CREATE_INDEX_LINK);
linkStatement.setString(1, schemaName);
linkStatement.setString(2, parentTableName);
linkStatement.setString(3, tableName);
linkStatement.execute();
}
PrimaryKeyConstraint pkConstraint = statement.getPrimaryKeyConstraint();
String pkName = null;
List<Pair<ColumnName,ColumnModifier>> pkColumnsNames = Collections.<Pair<ColumnName,ColumnModifier>>emptyList();
Iterator<Pair<ColumnName,ColumnModifier>> pkColumnsIterator = Iterators.emptyIterator();
if (pkConstraint != null) {
pkColumnsNames = pkConstraint.getColumnNames();
pkColumnsIterator = pkColumnsNames.iterator();
pkName = pkConstraint.getName();
}
List<ColumnDef> colDefs = statement.getColumnDefs();
List<PColumn> columns = Lists.newArrayListWithExpectedSize(colDefs.size());
List<PColumn> pkColumns = Lists.newArrayListWithExpectedSize(colDefs.size() + 1); // in case salted
PreparedStatement colUpsert = connection.prepareStatement(INSERT_COLUMN);
Map<String, PName> familyNames = Maps.newLinkedHashMap();
boolean isPK = false;
Map<String,Object> tableProps = Maps.newHashMapWithExpectedSize(statement.getProps().size());
Map<String,Object> commonFamilyProps = Collections.emptyMap();
// Somewhat hacky way of determining if property is for HColumnDescriptor or HTableDescriptor
HColumnDescriptor defaultDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES);
if (!statement.getProps().isEmpty()) {
commonFamilyProps = Maps.newHashMapWithExpectedSize(statement.getProps().size());
Collection<Pair<String,Object>> props = statement.getProps().get(QueryConstants.ALL_FAMILY_PROPERTIES_KEY);
for (Pair<String,Object> prop : props) {
- final String keyProperty = SchemaUtil.normalizeIdentifier( prop.getFirst() );
- if (defaultDescriptor.getValue(keyProperty) == null) {
- tableProps.put(keyProperty, prop.getSecond());
+ if (defaultDescriptor.getValue(prop.getFirst()) == null) {
+ tableProps.put(prop.getFirst(), prop.getSecond());
} else {
- commonFamilyProps.put(keyProperty, prop.getSecond());
+ commonFamilyProps.put(prop.getFirst(), prop.getSecond());
}
}
}
Integer saltBucketNum = (Integer) tableProps.remove(PhoenixDatabaseMetaData.SALT_BUCKETS);
if (saltBucketNum != null && (saltBucketNum <= 0 || saltBucketNum > SaltingUtil.MAX_BUCKET_NUM)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_BUCKET_NUM).build().buildException();
}
// Salt the index table if the data table is salted
if (saltBucketNum == null && parent != null) {
saltBucketNum = parent.getBucketNum();
}
boolean isSalted = (saltBucketNum != null);
boolean isImmutableRows;
Boolean isImmutableRowsProp = (Boolean) tableProps.remove(PTable.IS_IMMUTABLE_ROWS_PROP_NAME);
if (isImmutableRowsProp == null) {
isImmutableRows = connection.getQueryServices().getProps().getBoolean(QueryServices.IMMUTABLE_ROWS_ATTRIB, QueryServicesOptions.DEFAULT_IMMUTABLE_ROWS);
} else {
isImmutableRows = isImmutableRowsProp;
}
// Delay this check as it is supported to have IMMUTABLE_ROWS and SALT_BUCKETS defined on views
if (statement.getTableType() == PTableType.VIEW && !tableProps.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VIEW_WITH_PROPERTIES).build().buildException();
}
int position = 0;
if (isSalted) {
position = 1;
pkColumns.add(SaltingUtil.SALTING_COLUMN);
}
for (ColumnDef colDef : colDefs) {
if (colDef.isPK()) {
if (isPK) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_ALREADY_EXISTS)
.setColumnName(colDef.getColumnDefName().getColumnName()).build().buildException();
}
isPK = true;
}
PColumn column = newColumn(position++, colDef, pkConstraint);
if (SchemaUtil.isPKColumn(column)) {
// TODO: remove this constraint?
if (!pkColumnsNames.isEmpty() && !column.getName().getString().equals(pkColumnsIterator.next().getFirst().getColumnName())) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_OUT_OF_ORDER).setSchemaName(schemaName)
.setTableName(tableName).setColumnName(column.getName().getString()).build().buildException();
}
pkColumns.add(column);
}
columns.add(column);
if (colDef.getDataType() == PDataType.VARBINARY
&& SchemaUtil.isPKColumn(column)
&& pkColumnsNames.size() > 1
&& column.getPosition() < pkColumnsNames.size() - 1) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VARBINARY_IN_ROW_KEY).setSchemaName(schemaName)
.setTableName(tableName).setColumnName(column.getName().getString()).build().buildException();
}
if (column.getFamilyName() != null) {
familyNames.put(column.getFamilyName().getString(),column.getFamilyName());
}
}
if (!isPK && pkColumnsNames.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_MISSING)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
}
List<Pair<byte[],Map<String,Object>>> familyPropList = Lists.newArrayListWithExpectedSize(familyNames.size());
if (!statement.getProps().isEmpty()) {
for (String familyName : statement.getProps().keySet()) {
if (!familyName.equals(QueryConstants.ALL_FAMILY_PROPERTIES_KEY)) {
if (familyNames.get(familyName) == null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROPERTIES_FOR_FAMILY)
.setFamilyName(familyName).build().buildException();
} else if (statement.getTableType() == PTableType.VIEW) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VIEW_WITH_PROPERTIES).build().buildException();
}
}
}
}
for (PName familyName : familyNames.values()) {
Collection<Pair<String,Object>> props = statement.getProps().get(familyName.getString());
if (props.isEmpty()) {
familyPropList.add(new Pair<byte[],Map<String,Object>>(familyName.getBytes(),commonFamilyProps));
} else {
Map<String,Object> combinedFamilyProps = Maps.newHashMapWithExpectedSize(props.size() + commonFamilyProps.size());
combinedFamilyProps.putAll(commonFamilyProps);
for (Pair<String,Object> prop : props) {
combinedFamilyProps.put(prop.getFirst(), prop.getSecond());
}
familyPropList.add(new Pair<byte[],Map<String,Object>>(familyName.getBytes(),combinedFamilyProps));
}
}
// Bootstrapping for our SYSTEM.TABLE that creates itself before it exists
if (tableType == PTableType.SYSTEM) {
PTable table = PTableImpl.makePTable(PNameFactory.newName(schemaName),PNameFactory.newName(tableName), tableType, null, MetaDataProtocol.MIN_TABLE_TIMESTAMP, PTable.INITIAL_SEQ_NUM, PNameFactory.newName(QueryConstants.SYSTEM_TABLE_PK_NAME), null, columns, null, Collections.<PTable>emptyList(), isImmutableRows);
connection.addTable(table);
} else if (tableType == PTableType.INDEX) {
if (tableProps.get(HTableDescriptor.MAX_FILESIZE) == null) {
int nIndexRowKeyColumns = isPK ? 1 : pkColumnsNames.size();
int nIndexKeyValueColumns = columns.size() - nIndexRowKeyColumns;
int nBaseRowKeyColumns = parent.getPKColumns().size() - (parent.getBucketNum() == null ? 0 : 1);
int nBaseKeyValueColumns = parent.getColumns().size() - parent.getPKColumns().size();
/*
* Approximate ratio between index table size and data table size:
* More or less equal to the ratio between the number of key value columns in each. We add one to
* the key value column count to take into account our empty key value. We add 1/4 for any key
* value data table column that was moved into the index table row key.
*/
double ratio = (1+nIndexKeyValueColumns + (nIndexRowKeyColumns - nBaseRowKeyColumns)/4d)/(1+nBaseKeyValueColumns);
HTableDescriptor descriptor = connection.getQueryServices().getTableDescriptor(parent.getName().getBytes());
if (descriptor != null) { // Is null for connectionless
long maxFileSize = descriptor.getMaxFileSize();
if (maxFileSize == -1) { // If unset, use default
maxFileSize = HConstants.DEFAULT_MAX_FILE_SIZE;
}
tableProps.put(HTableDescriptor.MAX_FILESIZE, (long)(maxFileSize * ratio));
}
}
}
for (PColumn column : columns) {
addColumnMutation(schemaName, tableName, column, colUpsert, parentTableName, isSalted);
}
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
String dataTableName = parent == null ? null : parent.getTableName().getString();
PIndexState indexState = parent == null ? null : PIndexState.BUILDING;
PreparedStatement tableUpsert = connection.prepareStatement(CREATE_TABLE);
tableUpsert.setString(1, schemaName);
tableUpsert.setString(2, tableName);
tableUpsert.setString(3, tableType.getSerializedValue());
tableUpsert.setLong(4, PTable.INITIAL_SEQ_NUM);
tableUpsert.setInt(5, position);
if (saltBucketNum != null) {
tableUpsert.setInt(6, saltBucketNum);
} else {
tableUpsert.setNull(6, Types.INTEGER);
}
tableUpsert.setString(7, pkName);
tableUpsert.setString(8, dataTableName);
tableUpsert.setString(9, indexState == null ? null : indexState.getSerializedValue());
tableUpsert.setBoolean(10, isImmutableRows);
tableUpsert.execute();
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
/*
* The table metadata must be in the following order:
* 1) table header row
* 2) everything else
* 3) parent table header row
*/
Collections.reverse(tableMetaData);
splits = SchemaUtil.processSplits(splits, pkColumns, saltBucketNum, connection.getQueryServices().getProps().getBoolean(
QueryServices.ROW_KEY_ORDER_SALTED_TABLE_ATTRIB, QueryServicesOptions.DEFAULT_ROW_KEY_ORDER_SALTED_TABLE));
MetaDataMutationResult result = connection.getQueryServices().createTable(tableMetaData, tableType, tableProps, familyPropList, splits);
MutationCode code = result.getMutationCode();
switch(code) {
case TABLE_ALREADY_EXISTS:
connection.addTable(result.getTable());
if (!statement.ifNotExists()) {
throw new TableAlreadyExistsException(schemaName, tableName, result.getTable());
}
return null;
case PARENT_TABLE_NOT_FOUND:
throw new TableNotFoundException(schemaName, parent.getName().getString());
case NEWER_TABLE_FOUND:
throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable());
case UNALLOWED_TABLE_MUTATION:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
case CONCURRENT_TABLE_MUTATION:
connection.addTable(result.getTable());
throw new ConcurrentTableMutationException(schemaName, tableName);
default:
PTable table = PTableImpl.makePTable(
PNameFactory.newName(schemaName), PNameFactory.newName(tableName), tableType, indexState, result.getMutationTime(), PTable.INITIAL_SEQ_NUM,
pkName == null ? null : PNameFactory.newName(pkName), saltBucketNum, columns, dataTableName == null ? null : PNameFactory.newName(dataTableName), Collections.<PTable>emptyList(), isImmutableRows);
connection.addTable(table);
return table;
}
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
public MutationState dropTable(DropTableStatement statement) throws SQLException {
String schemaName = statement.getTableName().getSchemaName();
String tableName = statement.getTableName().getTableName();
return dropTable(schemaName, tableName, null, statement.getTableType(), statement.ifExists());
}
public MutationState dropIndex(DropIndexStatement statement) throws SQLException {
String schemaName = statement.getTableName().getSchemaName();
String tableName = statement.getIndexName().getName();
String parentTableName = statement.getTableName().getTableName();
return dropTable(schemaName, tableName, parentTableName, PTableType.INDEX, statement.ifExists());
}
private MutationState dropTable(String schemaName, String tableName, String parentTableName, PTableType tableType, boolean ifExists) throws SQLException {
connection.rollback();
boolean wasAutoCommit = connection.getAutoCommit();
try {
byte[] key = SchemaUtil.getTableKey(schemaName, tableName);
Long scn = connection.getSCN();
long clientTimeStamp = scn == null ? HConstants.LATEST_TIMESTAMP : scn;
List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(2);
@SuppressWarnings("deprecation") // FIXME: Remove when unintentionally deprecated method is fixed (HBASE-7870).
Delete tableDelete = new Delete(key, clientTimeStamp, null);
tableMetaData.add(tableDelete);
if (parentTableName != null) {
byte[] linkKey = MetaDataUtil.getParentLinkKey(schemaName, parentTableName, tableName);
@SuppressWarnings("deprecation") // FIXME: Remove when unintentionally deprecated method is fixed (HBASE-7870).
Delete linkDelete = new Delete(linkKey, clientTimeStamp, null);
tableMetaData.add(linkDelete);
}
MetaDataMutationResult result = connection.getQueryServices().dropTable(tableMetaData, tableType);
MutationCode code = result.getMutationCode();
switch(code) {
case TABLE_NOT_FOUND:
if (!ifExists) {
throw new TableNotFoundException(schemaName, tableName);
}
break;
case NEWER_TABLE_FOUND:
throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable());
case UNALLOWED_TABLE_MUTATION:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
default:
try {
// TODO: should we update the parent table by removing the index?
connection.removeTable(tableName);
} catch (TableNotFoundException e) { } // Ignore - just means wasn't cached
if (result.getTable() != null && tableType != PTableType.VIEW) {
connection.setAutoCommit(true);
// Delete everything in the column. You'll still be able to do queries at earlier timestamps
long ts = (scn == null ? result.getMutationTime() : scn);
// Create empty table and schema - they're only used to get the name from
// PName name, PTableType type, long timeStamp, long sequenceNumber, List<PColumn> columns
PTable table = result.getTable();
Map<String,PTable>tables = Maps.newHashMapWithExpectedSize(1 + table.getIndexes().size());
tables.put(table.getName().getString(), table);
for (PTable index : table.getIndexes()) {
tables.put(index.getName().getString(), index);
}
List<TableRef> tableRefs = Lists.newArrayListWithExpectedSize(1 + table.getIndexes().size());
tableRefs.add(new TableRef(null, table, ts, false));
for (PTable index: table.getIndexes()) {
tableRefs.add(new TableRef(null, index, ts, false));
}
MutationPlan plan = new PostDDLCompiler(connection).compile(tableRefs, null, null, Collections.<PColumn>emptyList(), ts);
return connection.getQueryServices().updateData(plan);
}
break;
}
return new MutationState(0,connection);
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
private MutationCode processMutationResult(String schemaName, String tableName, MetaDataMutationResult result) throws SQLException {
final MutationCode mutationCode = result.getMutationCode();
switch (mutationCode) {
case TABLE_NOT_FOUND:
connection.removeTable(tableName);
throw new TableNotFoundException(schemaName, tableName);
case UNALLOWED_TABLE_MUTATION:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
case COLUMN_ALREADY_EXISTS:
case COLUMN_NOT_FOUND:
break;
case CONCURRENT_TABLE_MUTATION:
connection.addTable(result.getTable());
if (logger.isDebugEnabled()) {
logger.debug("CONCURRENT_TABLE_MUTATION for table " + SchemaUtil.getTableName(schemaName, tableName));
}
throw new ConcurrentTableMutationException(schemaName, tableName);
case NEWER_TABLE_FOUND:
if (result.getTable() != null) {
connection.addTable(result.getTable());
}
throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable());
case NO_PK_COLUMNS:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_MISSING)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
case TABLE_ALREADY_EXISTS:
break;
default:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.UNEXPECTED_MUTATION_CODE).setSchemaName(schemaName)
.setTableName(tableName).setMessage("mutation code: " + mutationCode).build().buildException();
}
return mutationCode;
}
public MutationState addColumn(AddColumnStatement statement) throws SQLException {
connection.rollback();
boolean wasAutoCommit = connection.getAutoCommit();
try {
connection.setAutoCommit(false);
TableName tableNameNode = statement.getTable().getName();
String schemaName = tableNameNode.getSchemaName();
String tableName = tableNameNode.getTableName();
boolean retried = false;
while (true) {
List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(2);
ColumnResolver resolver = FromCompiler.getResolver(statement, connection);
PTable table = resolver.getTables().get(0).getTable();
if (logger.isDebugEnabled()) {
logger.debug("Resolved table to " + table.getName().getString() + " with seqNum " + table.getSequenceNumber() + " at timestamp " + table.getTimeStamp() + " with " + table.getColumns().size() + " columns: " + table.getColumns());
}
final int position = table.getColumns().size();
List<PColumn> currentPKs = table.getPKColumns();
PColumn lastPK = currentPKs.get(currentPKs.size()-1);
// Disallow adding columns if the last column is VARBIANRY.
if (lastPK.getDataType() == PDataType.VARBINARY) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VARBINARY_LAST_PK)
.setColumnName(lastPK.getName().getString()).build().buildException();
}
// Disallow adding columns if last column is fixed width and nullable.
if (lastPK.isNullable() && lastPK.getDataType().isFixedWidth()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.NULLABLE_FIXED_WIDTH_LAST_PK)
.setColumnName(lastPK.getName().getString()).build().buildException();
}
List<PColumn> columns = Lists.newArrayListWithExpectedSize(1);
ColumnDef colDef = statement.getColumnDef();
if (colDef != null && !colDef.isNull() && colDef.isPK()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.NOT_NULLABLE_COLUMN_IN_ROW_KEY)
.setColumnName(colDef.getColumnDefName().getColumnName()).build().buildException();
}
if (statement.getProps().remove(PhoenixDatabaseMetaData.SALT_BUCKETS) != null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.SALT_ONLY_ON_CREATE_TABLE)
.setTableName(table.getName().getString()).build().buildException();
}
boolean isImmutableRows = table.isImmutableRows();
Boolean isImmutableRowsProp = (Boolean)statement.getProps().remove(PTable.IS_IMMUTABLE_ROWS_PROP_NAME);
if (isImmutableRowsProp != null) {
isImmutableRows = isImmutableRowsProp;
}
boolean isSalted = table.getBucketNum() != null;
PreparedStatement colUpsert = connection.prepareStatement(SchemaUtil.isMetaTable(schemaName, tableName) ? INSERT_SYSTEM_COLUMN : INSERT_COLUMN);
Pair<byte[],Map<String,Object>> family = null;
if (colDef != null) {
PColumn column = newColumn(position, colDef, PrimaryKeyConstraint.EMPTY);
columns.add(column);
addColumnMutation(schemaName, tableName, column, colUpsert, null, isSalted);
// TODO: support setting properties on other families?
if (column.getFamilyName() != null) {
family = new Pair<byte[],Map<String,Object>>(column.getFamilyName().getBytes(),statement.getProps());
}
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
} else {
// Only support setting IMMUTABLE_ROWS=true on ALTER TABLE SET command
if (!statement.getProps().isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.SET_UNSUPPORTED_PROP_ON_ALTER_TABLE)
.setTableName(table.getName().getString()).build().buildException();
}
}
// Ordinal position is 1-based and we don't count SALT column in ordinal position
int totalColumnCount = position + (isSalted ? 0 : 1);
final long seqNum = table.getSequenceNumber() + 1;
PreparedStatement tableUpsert = connection.prepareStatement(SchemaUtil.isMetaTable(schemaName, tableName) ? MUTATE_SYSTEM_TABLE : MUTATE_TABLE);
tableUpsert.setString(1, schemaName);
tableUpsert.setString(2, tableName);
tableUpsert.setString(3, table.getType().getSerializedValue());
tableUpsert.setLong(4, seqNum);
tableUpsert.setInt(5, totalColumnCount);
if (tableUpsert.getParameterMetaData().getParameterCount() > 5) {
tableUpsert.setBoolean(6, isImmutableRows);
}
tableUpsert.execute();
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
// Force the table header row to be first
Collections.reverse(tableMetaData);
byte[] emptyCF = null;
byte[] projectCF = null;
if (table.getType() != PTableType.VIEW && family != null) {
if (table.getColumnFamilies().isEmpty()) {
emptyCF = family.getFirst();
} else {
try {
table.getColumnFamily(family.getFirst());
} catch (ColumnFamilyNotFoundException e) {
projectCF = family.getFirst();
emptyCF = SchemaUtil.getEmptyColumnFamily(table.getColumnFamilies());
}
}
}
MetaDataMutationResult result = connection.getQueryServices().addColumn(tableMetaData, table.getType(), family);
try {
MutationCode code = processMutationResult(schemaName, tableName, result);
if (code == MutationCode.COLUMN_ALREADY_EXISTS) {
connection.addTable(result.getTable());
if (!statement.ifNotExists()) {
throw new ColumnAlreadyExistsException(schemaName, tableName, SchemaUtil.findExistingColumn(result.getTable(), columns));
}
return new MutationState(0,connection);
}
connection.addColumn(SchemaUtil.getTableName(schemaName, tableName), columns, result.getMutationTime(), seqNum, isImmutableRows);
if (emptyCF != null) {
Long scn = connection.getSCN();
connection.setAutoCommit(true);
// Delete everything in the column. You'll still be able to do queries at earlier timestamps
long ts = (scn == null ? result.getMutationTime() : scn);
MutationPlan plan = new PostDDLCompiler(connection).compile(Collections.singletonList(new TableRef(null, table, ts, false)), emptyCF, projectCF, null, ts);
return connection.getQueryServices().updateData(plan);
}
return new MutationState(0,connection);
} catch (ConcurrentTableMutationException e) {
if (retried) {
throw e;
}
if (logger.isDebugEnabled()) {
logger.debug("Caught ConcurrentTableMutationException for table " + SchemaUtil.getTableName(schemaName, tableName) + ". Will try again...");
}
retried = true;
}
}
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
public MutationState dropColumn(DropColumnStatement statement) throws SQLException {
connection.rollback();
boolean wasAutoCommit = connection.getAutoCommit();
try {
connection.setAutoCommit(false);
TableName tableNameNode = statement.getTable().getName();
String schemaName = tableNameNode.getSchemaName();
String tableName = tableNameNode.getTableName();
String fullTableName = SchemaUtil.getTableName(schemaName, tableName);
boolean retried = false;
while (true) {
final ColumnResolver resolver = FromCompiler.getResolver(statement, connection);
PTable table = resolver.getTables().get(0).getTable();
ColumnRef columnRef = null;
try {
columnRef = resolver.resolveColumn(null, statement.getColumnRef().getFamilyName(), statement.getColumnRef().getColumnName());
} catch (ColumnNotFoundException e) {
if (statement.ifExists()) {
return new MutationState(0,connection);
}
throw e;
}
TableRef tableRef = columnRef.getTableRef();
PColumn columnToDrop = columnRef.getColumn();
if (SchemaUtil.isPKColumn(columnToDrop)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_DROP_PK)
.setColumnName(columnToDrop.getName().getString()).build().buildException();
}
int columnCount = table.getColumns().size() - 1;
List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(1 + table.getColumns().size() - columnToDrop.getPosition());
String familyName = null;
List<String> binds = Lists.newArrayListWithExpectedSize(4);
StringBuilder buf = new StringBuilder("DELETE FROM " + TYPE_SCHEMA + ".\"" + TYPE_TABLE + "\" WHERE " + TABLE_SCHEM_NAME);
if (schemaName == null || schemaName.length() == 0) {
buf.append(" IS NULL AND ");
} else {
buf.append(" = ? AND ");
binds.add(schemaName);
}
buf.append (TABLE_NAME_NAME + " = ? AND " + COLUMN_NAME + " = ? AND " + TABLE_CAT_NAME);
binds.add(tableName);
binds.add(columnToDrop.getName().getString());
if (columnToDrop.getFamilyName() == null) {
buf.append(" IS NULL");
} else {
buf.append(" = ?");
binds.add(familyName = columnToDrop.getFamilyName().getString());
}
PreparedStatement colDelete = connection.prepareStatement(buf.toString());
for (int i = 0; i < binds.size(); i++) {
colDelete.setString(i+1, binds.get(i));
}
colDelete.execute();
PreparedStatement colUpdate = connection.prepareStatement(UPDATE_COLUMN_POSITION);
colUpdate.setString(1, schemaName);
colUpdate.setString(2, tableName);
for (int i = columnToDrop.getPosition() + 1; i < table.getColumns().size(); i++) {
PColumn column = table.getColumns().get(i);
colUpdate.setString(3, column.getName().getString());
colUpdate.setString(4, column.getFamilyName() == null ? null : column.getFamilyName().getString());
colUpdate.setInt(5, i);
colUpdate.execute();
}
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
final long seqNum = table.getSequenceNumber() + 1;
PreparedStatement tableUpsert = connection.prepareStatement(MUTATE_TABLE);
tableUpsert.setString(1, schemaName);
tableUpsert.setString(2, tableName);
tableUpsert.setString(3, table.getType().getSerializedValue());
tableUpsert.setLong(4, seqNum);
tableUpsert.setInt(5, columnCount);
tableUpsert.setBoolean(6, table.isImmutableRows());
tableUpsert.execute();
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
// Force table header to be first in list
Collections.reverse(tableMetaData);
// If we're dropping the last KV colum, we have to pass an indication along to the dropColumn call
// to populate a new empty KV column
byte[] emptyCF = null;
if (table.getType() != PTableType.VIEW && !SchemaUtil.isPKColumn(columnToDrop) && table.getColumnFamilies().get(0).getName().equals(columnToDrop.getFamilyName()) && table.getColumnFamilies().get(0).getColumns().size() == 1) {
emptyCF = SchemaUtil.getEmptyColumnFamily(table.getColumnFamilies().subList(1, table.getColumnFamilies().size()));
}
MetaDataMutationResult result = connection.getQueryServices().dropColumn(tableMetaData, table.getType(), emptyCF != null && Bytes.compareTo(emptyCF, QueryConstants.EMPTY_COLUMN_BYTES)==0 ? emptyCF : null);
try {
MutationCode code = processMutationResult(schemaName, tableName, result);
if (code == MutationCode.COLUMN_NOT_FOUND) {
connection.addTable(result.getTable());
if (!statement.ifExists()) {
throw new ColumnNotFoundException(schemaName, tableName, familyName, columnToDrop.getName().getString());
}
return new MutationState(0, connection);
}
connection.removeColumn(SchemaUtil.getTableName(schemaName, tableName), familyName, columnToDrop.getName().getString(), result.getMutationTime(), seqNum);
// If we have a VIEW, then only delete the metadata, and leave the table data alone
if (table.getType() != PTableType.VIEW) {
connection.setAutoCommit(true);
Long scn = connection.getSCN();
// Delete everything in the column. You'll still be able to do queries at earlier timestamps
long ts = (scn == null ? result.getMutationTime() : scn);
MutationPlan plan = new PostDDLCompiler(connection).compile(Collections.singletonList(tableRef), emptyCF, null, Collections.singletonList(columnToDrop), ts);
return connection.getQueryServices().updateData(plan);
}
return new MutationState(0, connection);
} catch (ConcurrentTableMutationException e) {
if (retried) {
throw e;
}
table = connection.getPMetaData().getTable(fullTableName);
retried = true;
}
}
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
public MutationState alterIndex(AlterIndexStatement statement) throws SQLException {
connection.rollback();
boolean wasAutoCommit = connection.getAutoCommit();
try {
String dataTableName = statement.getTableName();
String schemaName = statement.getTable().getName().getSchemaName();
String indexName = statement.getTable().getName().getTableName();
connection.setAutoCommit(false);
// Confirm index table is valid and up-to-date
FromCompiler.getResolver(statement, connection);
PreparedStatement tableUpsert = connection.prepareStatement(UPDATE_INDEX_STATE);
tableUpsert.setString(1, schemaName);
tableUpsert.setString(2, indexName);
tableUpsert.setString(3, statement.getIndexState().getSerializedValue());
tableUpsert.execute();
List<Mutation> tableMetadata = connection.getMutationState().toMutations().next().getSecond();
connection.rollback();
MetaDataMutationResult result = connection.getQueryServices().updateIndexState(tableMetadata, dataTableName);
MutationCode code = result.getMutationCode();
if (code == MutationCode.TABLE_NOT_FOUND) {
throw new TableNotFoundException(schemaName,indexName);
}
if (code == MutationCode.TABLE_ALREADY_EXISTS) {
if (result.getTable() != null) { // To accommodate connection-less update of index state
connection.addTable(result.getTable());
}
}
return new MutationState(1, connection);
} catch (TableNotFoundException e) {
if (!statement.ifExists()) {
throw e;
}
return new MutationState(0, connection);
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
}
| false | true | private PTable createTable(CreateTableStatement statement, byte[][] splits, PTable parent) throws SQLException {
PTableType tableType = statement.getTableType();
boolean wasAutoCommit = connection.getAutoCommit();
connection.rollback();
try {
connection.setAutoCommit(false);
List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(statement.getColumnDefs().size() + 3);
TableName tableNameNode = statement.getTableName();
String schemaName = tableNameNode.getSchemaName();
String tableName = tableNameNode.getTableName();
String parentTableName = null;
if (parent != null) {
parentTableName = parent.getTableName().getString();
// Pass through data table sequence number so we can check it hasn't changed
PreparedStatement incrementStatement = connection.prepareStatement(INCREMENT_SEQ_NUM);
incrementStatement.setString(1, schemaName);
incrementStatement.setString(2, parentTableName);
incrementStatement.setLong(3, parent.getSequenceNumber());
incrementStatement.execute();
// Get list of mutations and add to table meta data that will be passed to server
// to guarantee order. This row will always end up last
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
// Add row linking from data table row to index table row
PreparedStatement linkStatement = connection.prepareStatement(CREATE_INDEX_LINK);
linkStatement.setString(1, schemaName);
linkStatement.setString(2, parentTableName);
linkStatement.setString(3, tableName);
linkStatement.execute();
}
PrimaryKeyConstraint pkConstraint = statement.getPrimaryKeyConstraint();
String pkName = null;
List<Pair<ColumnName,ColumnModifier>> pkColumnsNames = Collections.<Pair<ColumnName,ColumnModifier>>emptyList();
Iterator<Pair<ColumnName,ColumnModifier>> pkColumnsIterator = Iterators.emptyIterator();
if (pkConstraint != null) {
pkColumnsNames = pkConstraint.getColumnNames();
pkColumnsIterator = pkColumnsNames.iterator();
pkName = pkConstraint.getName();
}
List<ColumnDef> colDefs = statement.getColumnDefs();
List<PColumn> columns = Lists.newArrayListWithExpectedSize(colDefs.size());
List<PColumn> pkColumns = Lists.newArrayListWithExpectedSize(colDefs.size() + 1); // in case salted
PreparedStatement colUpsert = connection.prepareStatement(INSERT_COLUMN);
Map<String, PName> familyNames = Maps.newLinkedHashMap();
boolean isPK = false;
Map<String,Object> tableProps = Maps.newHashMapWithExpectedSize(statement.getProps().size());
Map<String,Object> commonFamilyProps = Collections.emptyMap();
// Somewhat hacky way of determining if property is for HColumnDescriptor or HTableDescriptor
HColumnDescriptor defaultDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES);
if (!statement.getProps().isEmpty()) {
commonFamilyProps = Maps.newHashMapWithExpectedSize(statement.getProps().size());
Collection<Pair<String,Object>> props = statement.getProps().get(QueryConstants.ALL_FAMILY_PROPERTIES_KEY);
for (Pair<String,Object> prop : props) {
final String keyProperty = SchemaUtil.normalizeIdentifier( prop.getFirst() );
if (defaultDescriptor.getValue(keyProperty) == null) {
tableProps.put(keyProperty, prop.getSecond());
} else {
commonFamilyProps.put(keyProperty, prop.getSecond());
}
}
}
Integer saltBucketNum = (Integer) tableProps.remove(PhoenixDatabaseMetaData.SALT_BUCKETS);
if (saltBucketNum != null && (saltBucketNum <= 0 || saltBucketNum > SaltingUtil.MAX_BUCKET_NUM)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_BUCKET_NUM).build().buildException();
}
// Salt the index table if the data table is salted
if (saltBucketNum == null && parent != null) {
saltBucketNum = parent.getBucketNum();
}
boolean isSalted = (saltBucketNum != null);
boolean isImmutableRows;
Boolean isImmutableRowsProp = (Boolean) tableProps.remove(PTable.IS_IMMUTABLE_ROWS_PROP_NAME);
if (isImmutableRowsProp == null) {
isImmutableRows = connection.getQueryServices().getProps().getBoolean(QueryServices.IMMUTABLE_ROWS_ATTRIB, QueryServicesOptions.DEFAULT_IMMUTABLE_ROWS);
} else {
isImmutableRows = isImmutableRowsProp;
}
// Delay this check as it is supported to have IMMUTABLE_ROWS and SALT_BUCKETS defined on views
if (statement.getTableType() == PTableType.VIEW && !tableProps.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VIEW_WITH_PROPERTIES).build().buildException();
}
int position = 0;
if (isSalted) {
position = 1;
pkColumns.add(SaltingUtil.SALTING_COLUMN);
}
for (ColumnDef colDef : colDefs) {
if (colDef.isPK()) {
if (isPK) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_ALREADY_EXISTS)
.setColumnName(colDef.getColumnDefName().getColumnName()).build().buildException();
}
isPK = true;
}
PColumn column = newColumn(position++, colDef, pkConstraint);
if (SchemaUtil.isPKColumn(column)) {
// TODO: remove this constraint?
if (!pkColumnsNames.isEmpty() && !column.getName().getString().equals(pkColumnsIterator.next().getFirst().getColumnName())) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_OUT_OF_ORDER).setSchemaName(schemaName)
.setTableName(tableName).setColumnName(column.getName().getString()).build().buildException();
}
pkColumns.add(column);
}
columns.add(column);
if (colDef.getDataType() == PDataType.VARBINARY
&& SchemaUtil.isPKColumn(column)
&& pkColumnsNames.size() > 1
&& column.getPosition() < pkColumnsNames.size() - 1) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VARBINARY_IN_ROW_KEY).setSchemaName(schemaName)
.setTableName(tableName).setColumnName(column.getName().getString()).build().buildException();
}
if (column.getFamilyName() != null) {
familyNames.put(column.getFamilyName().getString(),column.getFamilyName());
}
}
if (!isPK && pkColumnsNames.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_MISSING)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
}
List<Pair<byte[],Map<String,Object>>> familyPropList = Lists.newArrayListWithExpectedSize(familyNames.size());
if (!statement.getProps().isEmpty()) {
for (String familyName : statement.getProps().keySet()) {
if (!familyName.equals(QueryConstants.ALL_FAMILY_PROPERTIES_KEY)) {
if (familyNames.get(familyName) == null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROPERTIES_FOR_FAMILY)
.setFamilyName(familyName).build().buildException();
} else if (statement.getTableType() == PTableType.VIEW) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VIEW_WITH_PROPERTIES).build().buildException();
}
}
}
}
for (PName familyName : familyNames.values()) {
Collection<Pair<String,Object>> props = statement.getProps().get(familyName.getString());
if (props.isEmpty()) {
familyPropList.add(new Pair<byte[],Map<String,Object>>(familyName.getBytes(),commonFamilyProps));
} else {
Map<String,Object> combinedFamilyProps = Maps.newHashMapWithExpectedSize(props.size() + commonFamilyProps.size());
combinedFamilyProps.putAll(commonFamilyProps);
for (Pair<String,Object> prop : props) {
combinedFamilyProps.put(prop.getFirst(), prop.getSecond());
}
familyPropList.add(new Pair<byte[],Map<String,Object>>(familyName.getBytes(),combinedFamilyProps));
}
}
// Bootstrapping for our SYSTEM.TABLE that creates itself before it exists
if (tableType == PTableType.SYSTEM) {
PTable table = PTableImpl.makePTable(PNameFactory.newName(schemaName),PNameFactory.newName(tableName), tableType, null, MetaDataProtocol.MIN_TABLE_TIMESTAMP, PTable.INITIAL_SEQ_NUM, PNameFactory.newName(QueryConstants.SYSTEM_TABLE_PK_NAME), null, columns, null, Collections.<PTable>emptyList(), isImmutableRows);
connection.addTable(table);
} else if (tableType == PTableType.INDEX) {
if (tableProps.get(HTableDescriptor.MAX_FILESIZE) == null) {
int nIndexRowKeyColumns = isPK ? 1 : pkColumnsNames.size();
int nIndexKeyValueColumns = columns.size() - nIndexRowKeyColumns;
int nBaseRowKeyColumns = parent.getPKColumns().size() - (parent.getBucketNum() == null ? 0 : 1);
int nBaseKeyValueColumns = parent.getColumns().size() - parent.getPKColumns().size();
/*
* Approximate ratio between index table size and data table size:
* More or less equal to the ratio between the number of key value columns in each. We add one to
* the key value column count to take into account our empty key value. We add 1/4 for any key
* value data table column that was moved into the index table row key.
*/
double ratio = (1+nIndexKeyValueColumns + (nIndexRowKeyColumns - nBaseRowKeyColumns)/4d)/(1+nBaseKeyValueColumns);
HTableDescriptor descriptor = connection.getQueryServices().getTableDescriptor(parent.getName().getBytes());
if (descriptor != null) { // Is null for connectionless
long maxFileSize = descriptor.getMaxFileSize();
if (maxFileSize == -1) { // If unset, use default
maxFileSize = HConstants.DEFAULT_MAX_FILE_SIZE;
}
tableProps.put(HTableDescriptor.MAX_FILESIZE, (long)(maxFileSize * ratio));
}
}
}
for (PColumn column : columns) {
addColumnMutation(schemaName, tableName, column, colUpsert, parentTableName, isSalted);
}
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
String dataTableName = parent == null ? null : parent.getTableName().getString();
PIndexState indexState = parent == null ? null : PIndexState.BUILDING;
PreparedStatement tableUpsert = connection.prepareStatement(CREATE_TABLE);
tableUpsert.setString(1, schemaName);
tableUpsert.setString(2, tableName);
tableUpsert.setString(3, tableType.getSerializedValue());
tableUpsert.setLong(4, PTable.INITIAL_SEQ_NUM);
tableUpsert.setInt(5, position);
if (saltBucketNum != null) {
tableUpsert.setInt(6, saltBucketNum);
} else {
tableUpsert.setNull(6, Types.INTEGER);
}
tableUpsert.setString(7, pkName);
tableUpsert.setString(8, dataTableName);
tableUpsert.setString(9, indexState == null ? null : indexState.getSerializedValue());
tableUpsert.setBoolean(10, isImmutableRows);
tableUpsert.execute();
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
/*
* The table metadata must be in the following order:
* 1) table header row
* 2) everything else
* 3) parent table header row
*/
Collections.reverse(tableMetaData);
splits = SchemaUtil.processSplits(splits, pkColumns, saltBucketNum, connection.getQueryServices().getProps().getBoolean(
QueryServices.ROW_KEY_ORDER_SALTED_TABLE_ATTRIB, QueryServicesOptions.DEFAULT_ROW_KEY_ORDER_SALTED_TABLE));
MetaDataMutationResult result = connection.getQueryServices().createTable(tableMetaData, tableType, tableProps, familyPropList, splits);
MutationCode code = result.getMutationCode();
switch(code) {
case TABLE_ALREADY_EXISTS:
connection.addTable(result.getTable());
if (!statement.ifNotExists()) {
throw new TableAlreadyExistsException(schemaName, tableName, result.getTable());
}
return null;
case PARENT_TABLE_NOT_FOUND:
throw new TableNotFoundException(schemaName, parent.getName().getString());
case NEWER_TABLE_FOUND:
throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable());
case UNALLOWED_TABLE_MUTATION:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
case CONCURRENT_TABLE_MUTATION:
connection.addTable(result.getTable());
throw new ConcurrentTableMutationException(schemaName, tableName);
default:
PTable table = PTableImpl.makePTable(
PNameFactory.newName(schemaName), PNameFactory.newName(tableName), tableType, indexState, result.getMutationTime(), PTable.INITIAL_SEQ_NUM,
pkName == null ? null : PNameFactory.newName(pkName), saltBucketNum, columns, dataTableName == null ? null : PNameFactory.newName(dataTableName), Collections.<PTable>emptyList(), isImmutableRows);
connection.addTable(table);
return table;
}
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
| private PTable createTable(CreateTableStatement statement, byte[][] splits, PTable parent) throws SQLException {
PTableType tableType = statement.getTableType();
boolean wasAutoCommit = connection.getAutoCommit();
connection.rollback();
try {
connection.setAutoCommit(false);
List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(statement.getColumnDefs().size() + 3);
TableName tableNameNode = statement.getTableName();
String schemaName = tableNameNode.getSchemaName();
String tableName = tableNameNode.getTableName();
String parentTableName = null;
if (parent != null) {
parentTableName = parent.getTableName().getString();
// Pass through data table sequence number so we can check it hasn't changed
PreparedStatement incrementStatement = connection.prepareStatement(INCREMENT_SEQ_NUM);
incrementStatement.setString(1, schemaName);
incrementStatement.setString(2, parentTableName);
incrementStatement.setLong(3, parent.getSequenceNumber());
incrementStatement.execute();
// Get list of mutations and add to table meta data that will be passed to server
// to guarantee order. This row will always end up last
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
// Add row linking from data table row to index table row
PreparedStatement linkStatement = connection.prepareStatement(CREATE_INDEX_LINK);
linkStatement.setString(1, schemaName);
linkStatement.setString(2, parentTableName);
linkStatement.setString(3, tableName);
linkStatement.execute();
}
PrimaryKeyConstraint pkConstraint = statement.getPrimaryKeyConstraint();
String pkName = null;
List<Pair<ColumnName,ColumnModifier>> pkColumnsNames = Collections.<Pair<ColumnName,ColumnModifier>>emptyList();
Iterator<Pair<ColumnName,ColumnModifier>> pkColumnsIterator = Iterators.emptyIterator();
if (pkConstraint != null) {
pkColumnsNames = pkConstraint.getColumnNames();
pkColumnsIterator = pkColumnsNames.iterator();
pkName = pkConstraint.getName();
}
List<ColumnDef> colDefs = statement.getColumnDefs();
List<PColumn> columns = Lists.newArrayListWithExpectedSize(colDefs.size());
List<PColumn> pkColumns = Lists.newArrayListWithExpectedSize(colDefs.size() + 1); // in case salted
PreparedStatement colUpsert = connection.prepareStatement(INSERT_COLUMN);
Map<String, PName> familyNames = Maps.newLinkedHashMap();
boolean isPK = false;
Map<String,Object> tableProps = Maps.newHashMapWithExpectedSize(statement.getProps().size());
Map<String,Object> commonFamilyProps = Collections.emptyMap();
// Somewhat hacky way of determining if property is for HColumnDescriptor or HTableDescriptor
HColumnDescriptor defaultDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES);
if (!statement.getProps().isEmpty()) {
commonFamilyProps = Maps.newHashMapWithExpectedSize(statement.getProps().size());
Collection<Pair<String,Object>> props = statement.getProps().get(QueryConstants.ALL_FAMILY_PROPERTIES_KEY);
for (Pair<String,Object> prop : props) {
if (defaultDescriptor.getValue(prop.getFirst()) == null) {
tableProps.put(prop.getFirst(), prop.getSecond());
} else {
commonFamilyProps.put(prop.getFirst(), prop.getSecond());
}
}
}
Integer saltBucketNum = (Integer) tableProps.remove(PhoenixDatabaseMetaData.SALT_BUCKETS);
if (saltBucketNum != null && (saltBucketNum <= 0 || saltBucketNum > SaltingUtil.MAX_BUCKET_NUM)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_BUCKET_NUM).build().buildException();
}
// Salt the index table if the data table is salted
if (saltBucketNum == null && parent != null) {
saltBucketNum = parent.getBucketNum();
}
boolean isSalted = (saltBucketNum != null);
boolean isImmutableRows;
Boolean isImmutableRowsProp = (Boolean) tableProps.remove(PTable.IS_IMMUTABLE_ROWS_PROP_NAME);
if (isImmutableRowsProp == null) {
isImmutableRows = connection.getQueryServices().getProps().getBoolean(QueryServices.IMMUTABLE_ROWS_ATTRIB, QueryServicesOptions.DEFAULT_IMMUTABLE_ROWS);
} else {
isImmutableRows = isImmutableRowsProp;
}
// Delay this check as it is supported to have IMMUTABLE_ROWS and SALT_BUCKETS defined on views
if (statement.getTableType() == PTableType.VIEW && !tableProps.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VIEW_WITH_PROPERTIES).build().buildException();
}
int position = 0;
if (isSalted) {
position = 1;
pkColumns.add(SaltingUtil.SALTING_COLUMN);
}
for (ColumnDef colDef : colDefs) {
if (colDef.isPK()) {
if (isPK) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_ALREADY_EXISTS)
.setColumnName(colDef.getColumnDefName().getColumnName()).build().buildException();
}
isPK = true;
}
PColumn column = newColumn(position++, colDef, pkConstraint);
if (SchemaUtil.isPKColumn(column)) {
// TODO: remove this constraint?
if (!pkColumnsNames.isEmpty() && !column.getName().getString().equals(pkColumnsIterator.next().getFirst().getColumnName())) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_OUT_OF_ORDER).setSchemaName(schemaName)
.setTableName(tableName).setColumnName(column.getName().getString()).build().buildException();
}
pkColumns.add(column);
}
columns.add(column);
if (colDef.getDataType() == PDataType.VARBINARY
&& SchemaUtil.isPKColumn(column)
&& pkColumnsNames.size() > 1
&& column.getPosition() < pkColumnsNames.size() - 1) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VARBINARY_IN_ROW_KEY).setSchemaName(schemaName)
.setTableName(tableName).setColumnName(column.getName().getString()).build().buildException();
}
if (column.getFamilyName() != null) {
familyNames.put(column.getFamilyName().getString(),column.getFamilyName());
}
}
if (!isPK && pkColumnsNames.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_MISSING)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
}
List<Pair<byte[],Map<String,Object>>> familyPropList = Lists.newArrayListWithExpectedSize(familyNames.size());
if (!statement.getProps().isEmpty()) {
for (String familyName : statement.getProps().keySet()) {
if (!familyName.equals(QueryConstants.ALL_FAMILY_PROPERTIES_KEY)) {
if (familyNames.get(familyName) == null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.PROPERTIES_FOR_FAMILY)
.setFamilyName(familyName).build().buildException();
} else if (statement.getTableType() == PTableType.VIEW) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.VIEW_WITH_PROPERTIES).build().buildException();
}
}
}
}
for (PName familyName : familyNames.values()) {
Collection<Pair<String,Object>> props = statement.getProps().get(familyName.getString());
if (props.isEmpty()) {
familyPropList.add(new Pair<byte[],Map<String,Object>>(familyName.getBytes(),commonFamilyProps));
} else {
Map<String,Object> combinedFamilyProps = Maps.newHashMapWithExpectedSize(props.size() + commonFamilyProps.size());
combinedFamilyProps.putAll(commonFamilyProps);
for (Pair<String,Object> prop : props) {
combinedFamilyProps.put(prop.getFirst(), prop.getSecond());
}
familyPropList.add(new Pair<byte[],Map<String,Object>>(familyName.getBytes(),combinedFamilyProps));
}
}
// Bootstrapping for our SYSTEM.TABLE that creates itself before it exists
if (tableType == PTableType.SYSTEM) {
PTable table = PTableImpl.makePTable(PNameFactory.newName(schemaName),PNameFactory.newName(tableName), tableType, null, MetaDataProtocol.MIN_TABLE_TIMESTAMP, PTable.INITIAL_SEQ_NUM, PNameFactory.newName(QueryConstants.SYSTEM_TABLE_PK_NAME), null, columns, null, Collections.<PTable>emptyList(), isImmutableRows);
connection.addTable(table);
} else if (tableType == PTableType.INDEX) {
if (tableProps.get(HTableDescriptor.MAX_FILESIZE) == null) {
int nIndexRowKeyColumns = isPK ? 1 : pkColumnsNames.size();
int nIndexKeyValueColumns = columns.size() - nIndexRowKeyColumns;
int nBaseRowKeyColumns = parent.getPKColumns().size() - (parent.getBucketNum() == null ? 0 : 1);
int nBaseKeyValueColumns = parent.getColumns().size() - parent.getPKColumns().size();
/*
* Approximate ratio between index table size and data table size:
* More or less equal to the ratio between the number of key value columns in each. We add one to
* the key value column count to take into account our empty key value. We add 1/4 for any key
* value data table column that was moved into the index table row key.
*/
double ratio = (1+nIndexKeyValueColumns + (nIndexRowKeyColumns - nBaseRowKeyColumns)/4d)/(1+nBaseKeyValueColumns);
HTableDescriptor descriptor = connection.getQueryServices().getTableDescriptor(parent.getName().getBytes());
if (descriptor != null) { // Is null for connectionless
long maxFileSize = descriptor.getMaxFileSize();
if (maxFileSize == -1) { // If unset, use default
maxFileSize = HConstants.DEFAULT_MAX_FILE_SIZE;
}
tableProps.put(HTableDescriptor.MAX_FILESIZE, (long)(maxFileSize * ratio));
}
}
}
for (PColumn column : columns) {
addColumnMutation(schemaName, tableName, column, colUpsert, parentTableName, isSalted);
}
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
String dataTableName = parent == null ? null : parent.getTableName().getString();
PIndexState indexState = parent == null ? null : PIndexState.BUILDING;
PreparedStatement tableUpsert = connection.prepareStatement(CREATE_TABLE);
tableUpsert.setString(1, schemaName);
tableUpsert.setString(2, tableName);
tableUpsert.setString(3, tableType.getSerializedValue());
tableUpsert.setLong(4, PTable.INITIAL_SEQ_NUM);
tableUpsert.setInt(5, position);
if (saltBucketNum != null) {
tableUpsert.setInt(6, saltBucketNum);
} else {
tableUpsert.setNull(6, Types.INTEGER);
}
tableUpsert.setString(7, pkName);
tableUpsert.setString(8, dataTableName);
tableUpsert.setString(9, indexState == null ? null : indexState.getSerializedValue());
tableUpsert.setBoolean(10, isImmutableRows);
tableUpsert.execute();
tableMetaData.addAll(connection.getMutationState().toMutations().next().getSecond());
connection.rollback();
/*
* The table metadata must be in the following order:
* 1) table header row
* 2) everything else
* 3) parent table header row
*/
Collections.reverse(tableMetaData);
splits = SchemaUtil.processSplits(splits, pkColumns, saltBucketNum, connection.getQueryServices().getProps().getBoolean(
QueryServices.ROW_KEY_ORDER_SALTED_TABLE_ATTRIB, QueryServicesOptions.DEFAULT_ROW_KEY_ORDER_SALTED_TABLE));
MetaDataMutationResult result = connection.getQueryServices().createTable(tableMetaData, tableType, tableProps, familyPropList, splits);
MutationCode code = result.getMutationCode();
switch(code) {
case TABLE_ALREADY_EXISTS:
connection.addTable(result.getTable());
if (!statement.ifNotExists()) {
throw new TableAlreadyExistsException(schemaName, tableName, result.getTable());
}
return null;
case PARENT_TABLE_NOT_FOUND:
throw new TableNotFoundException(schemaName, parent.getName().getString());
case NEWER_TABLE_FOUND:
throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable());
case UNALLOWED_TABLE_MUTATION:
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE)
.setSchemaName(schemaName).setTableName(tableName).build().buildException();
case CONCURRENT_TABLE_MUTATION:
connection.addTable(result.getTable());
throw new ConcurrentTableMutationException(schemaName, tableName);
default:
PTable table = PTableImpl.makePTable(
PNameFactory.newName(schemaName), PNameFactory.newName(tableName), tableType, indexState, result.getMutationTime(), PTable.INITIAL_SEQ_NUM,
pkName == null ? null : PNameFactory.newName(pkName), saltBucketNum, columns, dataTableName == null ? null : PNameFactory.newName(dataTableName), Collections.<PTable>emptyList(), isImmutableRows);
connection.addTable(table);
return table;
}
} finally {
connection.setAutoCommit(wasAutoCommit);
}
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java
index db878419..f1c12465 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java
@@ -1,98 +1,112 @@
package devopsdistilled.operp.client.items.panes.details;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.inject.Inject;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import devopsdistilled.operp.client.abstracts.AbstractEntityDetailsPane;
import devopsdistilled.operp.client.items.controllers.ProductController;
import devopsdistilled.operp.server.data.entity.items.Category;
import devopsdistilled.operp.server.data.entity.items.Product;
public class ProductDetailsPane extends AbstractEntityDetailsPane<Product> {
@Inject
private ProductController productController;
private Product product;
private final JPanel pane;
private final JTextField productIdField;
private final JTextField productNameField;
private final JList<Category> productCategoryList;
public ProductDetailsPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]"));
JLabel lblProductId = new JLabel("Product ID");
pane.add(lblProductId, "cell 0 0,alignx trailing");
productIdField = new JTextField();
productIdField.setEditable(false);
pane.add(productIdField, "cell 1 0,growx");
productIdField.setColumns(10);
JLabel lblProductName = new JLabel("Product Name");
pane.add(lblProductName, "cell 0 1,alignx trailing");
productNameField = new JTextField();
productNameField.setEditable(false);
pane.add(productNameField, "cell 1 1,growx");
productNameField.setColumns(10);
JLabel lblProductCategory = new JLabel("Product Category");
pane.add(lblProductCategory, "cell 0 2");
productCategoryList = new JList();
pane.add(productCategoryList, "cell 1 2,grow");
JButton btnDelete = new JButton("Delete");
+ btnDelete.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ getDialog().dispose();
+ productController.delete(product);
+ }
+ });
pane.add(btnDelete, "flowx,cell 1 3");
JButton btnEdit = new JButton("Edit");
+ btnEdit.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ getDialog().dispose();
+ productController.edit(product);
+ }
+ });
pane.add(btnEdit, "cell 1 3");
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
}
});
btnOk.setSelected(true);
pane.add(btnOk, "cell 1 3");
}
@Override
public JComponent getPane() {
return pane;
}
@Override
public void show(Product product) {
this.product = product;
if (product != null) {
productIdField.setText(product.getProductId().toString());
productNameField.setText(product.getProductName());
productCategoryList.setListData((Category[]) product
.getCategories().toArray());
getDialog().setVisible(true);
}
}
@Override
public String getTitle() {
return "Product Details";
}
}
| false | true | public ProductDetailsPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]"));
JLabel lblProductId = new JLabel("Product ID");
pane.add(lblProductId, "cell 0 0,alignx trailing");
productIdField = new JTextField();
productIdField.setEditable(false);
pane.add(productIdField, "cell 1 0,growx");
productIdField.setColumns(10);
JLabel lblProductName = new JLabel("Product Name");
pane.add(lblProductName, "cell 0 1,alignx trailing");
productNameField = new JTextField();
productNameField.setEditable(false);
pane.add(productNameField, "cell 1 1,growx");
productNameField.setColumns(10);
JLabel lblProductCategory = new JLabel("Product Category");
pane.add(lblProductCategory, "cell 0 2");
productCategoryList = new JList();
pane.add(productCategoryList, "cell 1 2,grow");
JButton btnDelete = new JButton("Delete");
pane.add(btnDelete, "flowx,cell 1 3");
JButton btnEdit = new JButton("Edit");
pane.add(btnEdit, "cell 1 3");
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
}
});
btnOk.setSelected(true);
pane.add(btnOk, "cell 1 3");
}
| public ProductDetailsPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]"));
JLabel lblProductId = new JLabel("Product ID");
pane.add(lblProductId, "cell 0 0,alignx trailing");
productIdField = new JTextField();
productIdField.setEditable(false);
pane.add(productIdField, "cell 1 0,growx");
productIdField.setColumns(10);
JLabel lblProductName = new JLabel("Product Name");
pane.add(lblProductName, "cell 0 1,alignx trailing");
productNameField = new JTextField();
productNameField.setEditable(false);
pane.add(productNameField, "cell 1 1,growx");
productNameField.setColumns(10);
JLabel lblProductCategory = new JLabel("Product Category");
pane.add(lblProductCategory, "cell 0 2");
productCategoryList = new JList();
pane.add(productCategoryList, "cell 1 2,grow");
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
productController.delete(product);
}
});
pane.add(btnDelete, "flowx,cell 1 3");
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
productController.edit(product);
}
});
pane.add(btnEdit, "cell 1 3");
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
}
});
btnOk.setSelected(true);
pane.add(btnOk, "cell 1 3");
}
|
diff --git a/src/main/java/com/mmounirou/spotirss/provider/Apple.java b/src/main/java/com/mmounirou/spotirss/provider/Apple.java
index 9312155..ebd5282 100644
--- a/src/main/java/com/mmounirou/spotirss/provider/Apple.java
+++ b/src/main/java/com/mmounirou/spotirss/provider/Apple.java
@@ -1,72 +1,72 @@
/*
* Copyright (C) 2011 Mohamed MOUNIROU
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.mmounirou.spotirss.provider;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import com.mmounirou.spotirss.rss.Track;
import com.mmounirou.spotirss.tools.StringTools;
public class Apple implements EntryToTrackConverter
{
@Override
@Nullable
public Track apply(@Nullable String strTitle)
{
int rankPos = strTitle.indexOf(".");
String strRank = strTitle.substring(0, rankPos);
String strArtistAndSong = strTitle.substring(rankPos + 1);
- String strTempSong = strArtistAndSong.substring(0, strArtistAndSong.lastIndexOf("-"));
- String strTempArtist = strArtistAndSong.substring(strArtistAndSong.lastIndexOf("-") + 1);
+ String strTempSong = strArtistAndSong.substring(0, strArtistAndSong.lastIndexOf(" - "));
+ String strTempArtist = strArtistAndSong.substring(strArtistAndSong.lastIndexOf(" - ") + 2);
String strSong = strTempSong;
strSong = StringUtils.remove(strSong, String.format("(%s)", StringUtils.substringBetween(strSong, "(", ")")));
strSong = StringUtils.remove(strSong, String.format("[%s]", StringUtils.substringBetween(strSong, "[", "]")));
String strArtist = strTempArtist;
String strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "(", ")"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "[", "]"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
final Set<String> artistNames =StringTools.split(strArtist, new String[] { "Featuring", "Feat\\.","feat\\.", "&",","});
return new Track(Integer.parseInt(strRank), artistNames, strSong);
}
public static void main(String[] args)
{
System.out.println(new Apple().apply("74. Hands in the Air (feat. Ne-Yo) [From \"Step Up Revolution\"] - Timbaland"));
}
}
| true | true | public Track apply(@Nullable String strTitle)
{
int rankPos = strTitle.indexOf(".");
String strRank = strTitle.substring(0, rankPos);
String strArtistAndSong = strTitle.substring(rankPos + 1);
String strTempSong = strArtistAndSong.substring(0, strArtistAndSong.lastIndexOf("-"));
String strTempArtist = strArtistAndSong.substring(strArtistAndSong.lastIndexOf("-") + 1);
String strSong = strTempSong;
strSong = StringUtils.remove(strSong, String.format("(%s)", StringUtils.substringBetween(strSong, "(", ")")));
strSong = StringUtils.remove(strSong, String.format("[%s]", StringUtils.substringBetween(strSong, "[", "]")));
String strArtist = strTempArtist;
String strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "(", ")"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "[", "]"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
final Set<String> artistNames =StringTools.split(strArtist, new String[] { "Featuring", "Feat\\.","feat\\.", "&",","});
return new Track(Integer.parseInt(strRank), artistNames, strSong);
}
| public Track apply(@Nullable String strTitle)
{
int rankPos = strTitle.indexOf(".");
String strRank = strTitle.substring(0, rankPos);
String strArtistAndSong = strTitle.substring(rankPos + 1);
String strTempSong = strArtistAndSong.substring(0, strArtistAndSong.lastIndexOf(" - "));
String strTempArtist = strArtistAndSong.substring(strArtistAndSong.lastIndexOf(" - ") + 2);
String strSong = strTempSong;
strSong = StringUtils.remove(strSong, String.format("(%s)", StringUtils.substringBetween(strSong, "(", ")")));
strSong = StringUtils.remove(strSong, String.format("[%s]", StringUtils.substringBetween(strSong, "[", "]")));
String strArtist = strTempArtist;
String strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "(", ")"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
strfeaturing = StringUtils.trimToEmpty(StringUtils.substringBetween(strTempSong, "[", "]"));
if (strfeaturing.contains("feat."))
{
strArtist = strArtist + " " + strfeaturing;
}
final Set<String> artistNames =StringTools.split(strArtist, new String[] { "Featuring", "Feat\\.","feat\\.", "&",","});
return new Track(Integer.parseInt(strRank), artistNames, strSong);
}
|
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardView.java b/java/src/com/android/inputmethod/keyboard/KeyboardView.java
index 7dbc7901..4086a8e7 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardView.java
@@ -1,890 +1,890 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.keyboard;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.inputmethod.compat.FrameLayoutCompatUtils;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
import java.util.HashMap;
/**
* A view that renders a virtual {@link Keyboard}.
*
* @attr ref R.styleable#KeyboardView_backgroundDimAmount
* @attr ref R.styleable#KeyboardView_keyBackground
* @attr ref R.styleable#KeyboardView_keyLetterRatio
* @attr ref R.styleable#KeyboardView_keyLargeLetterRatio
* @attr ref R.styleable#KeyboardView_keyLabelRatio
* @attr ref R.styleable#KeyboardView_keyHintLetterRatio
* @attr ref R.styleable#KeyboardView_keyUppercaseLetterRatio
* @attr ref R.styleable#KeyboardView_keyHintLabelRatio
* @attr ref R.styleable#KeyboardView_keyLabelHorizontalPadding
* @attr ref R.styleable#KeyboardView_keyHintLetterPadding
* @attr ref R.styleable#KeyboardView_keyUppercaseLetterPadding
* @attr ref R.styleable#KeyboardView_keyTextStyle
* @attr ref R.styleable#KeyboardView_keyPreviewLayout
* @attr ref R.styleable#KeyboardView_keyPreviewTextRatio
* @attr ref R.styleable#KeyboardView_keyPreviewOffset
* @attr ref R.styleable#KeyboardView_keyPreviewHeight
* @attr ref R.styleable#KeyboardView_keyTextColor
* @attr ref R.styleable#KeyboardView_keyTextColorDisabled
* @attr ref R.styleable#KeyboardView_keyHintLetterColor
* @attr ref R.styleable#KeyboardView_keyHintLabelColor
* @attr ref R.styleable#KeyboardView_keyUppercaseLetterInactivatedColor
* @attr ref R.styleable#KeyboardView_keyUppercaseLetterActivatedColor
* @attr ref R.styleable#KeyboardView_shadowColor
* @attr ref R.styleable#KeyboardView_shadowRadius
*/
public class KeyboardView extends View implements PointerTracker.DrawingProxy {
// Miscellaneous constants
private static final int[] LONG_PRESSABLE_STATE_SET = { android.R.attr.state_long_pressable };
// XML attribute
private final float mBackgroundDimAmount;
// HORIZONTAL ELLIPSIS "...", character for popup hint.
private static final String POPUP_HINT_CHAR = "\u2026";
// Main keyboard
private Keyboard mKeyboard;
private final KeyDrawParams mKeyDrawParams;
// Key preview
private final int mKeyPreviewLayoutId;
private final KeyPreviewDrawParams mKeyPreviewDrawParams;
private boolean mShowKeyPreviewPopup = true;
private final int mDelayBeforePreview;
private int mDelayAfterPreview;
private ViewGroup mPreviewPlacer;
// Drawing
/** Whether the keyboard bitmap buffer needs to be redrawn before it's blitted. **/
private boolean mBufferNeedsUpdate;
/** The dirty region in the keyboard bitmap */
private final Rect mDirtyRect = new Rect();
/** The key to invalidate. */
private Key mInvalidatedKey;
/** The dirty region for single key drawing */
private final Rect mInvalidatedKeyRect = new Rect();
/** The keyboard bitmap buffer for faster updates */
private Bitmap mBuffer;
/** The canvas for the above mutable keyboard bitmap */
private Canvas mCanvas;
private final Paint mPaint = new Paint();
// This map caches key label text height in pixel as value and key label text size as map key.
private static final HashMap<Integer, Float> sTextHeightCache =
new HashMap<Integer, Float>();
// This map caches key label text width in pixel as value and key label text size as map key.
private static final HashMap<Integer, Float> sTextWidthCache =
new HashMap<Integer, Float>();
private static final String KEY_LABEL_REFERENCE_CHAR = "M";
private static final int MEASURESPEC_UNSPECIFIED = MeasureSpec.makeMeasureSpec(
0, MeasureSpec.UNSPECIFIED);
private final DrawingHandler mDrawingHandler = new DrawingHandler(this);
public static class DrawingHandler extends StaticInnerHandlerWrapper<KeyboardView> {
private static final int MSG_SHOW_KEY_PREVIEW = 1;
private static final int MSG_DISMISS_KEY_PREVIEW = 2;
public DrawingHandler(KeyboardView outerInstance) {
super(outerInstance);
}
@Override
public void handleMessage(Message msg) {
final KeyboardView keyboardView = getOuterInstance();
if (keyboardView == null) return;
final PointerTracker tracker = (PointerTracker) msg.obj;
switch (msg.what) {
case MSG_SHOW_KEY_PREVIEW:
keyboardView.showKey(msg.arg1, tracker);
break;
case MSG_DISMISS_KEY_PREVIEW:
tracker.getKeyPreviewText().setVisibility(View.INVISIBLE);
break;
}
}
public void showKeyPreview(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_SHOW_KEY_PREVIEW);
final KeyboardView keyboardView = getOuterInstance();
if (keyboardView == null) return;
if (tracker.getKeyPreviewText().getVisibility() == VISIBLE || delay == 0) {
// Show right away, if it's already visible and finger is moving around
keyboardView.showKey(keyIndex, tracker);
} else {
sendMessageDelayed(
obtainMessage(MSG_SHOW_KEY_PREVIEW, keyIndex, 0, tracker), delay);
}
}
public void cancelShowKeyPreview(PointerTracker tracker) {
removeMessages(MSG_SHOW_KEY_PREVIEW, tracker);
}
public void cancelAllShowKeyPreviews() {
removeMessages(MSG_SHOW_KEY_PREVIEW);
}
public void dismissKeyPreview(long delay, PointerTracker tracker) {
sendMessageDelayed(obtainMessage(MSG_DISMISS_KEY_PREVIEW, tracker), delay);
}
public void cancelDismissKeyPreview(PointerTracker tracker) {
removeMessages(MSG_DISMISS_KEY_PREVIEW, tracker);
}
public void cancelAllDismissKeyPreviews() {
removeMessages(MSG_DISMISS_KEY_PREVIEW);
}
public void cancelAllMessages() {
cancelAllShowKeyPreviews();
cancelAllDismissKeyPreviews();
}
}
private static class KeyDrawParams {
// XML attributes
public final int mKeyTextColor;
public final int mKeyTextInactivatedColor;
public final Typeface mKeyTextStyle;
public final float mKeyLabelHorizontalPadding;
public final float mKeyHintLetterPadding;
public final float mKeyUppercaseLetterPadding;
public final int mShadowColor;
public final float mShadowRadius;
public final Drawable mKeyBackground;
public final int mKeyHintLetterColor;
public final int mKeyHintLabelColor;
public final int mKeyUppercaseLetterInactivatedColor;
public final int mKeyUppercaseLetterActivatedColor;
private final float mKeyLetterRatio;
private final float mKeyLargeLetterRatio;
private final float mKeyLabelRatio;
private final float mKeyHintLetterRatio;
private final float mKeyUppercaseLetterRatio;
private final float mKeyHintLabelRatio;
public final Rect mPadding = new Rect();
public int mKeyLetterSize;
public int mKeyLargeLetterSize;
public int mKeyLabelSize;
public int mKeyHintLetterSize;
public int mKeyUppercaseLetterSize;
public int mKeyHintLabelSize;
public KeyDrawParams(TypedArray a) {
mKeyBackground = a.getDrawable(R.styleable.KeyboardView_keyBackground);
mKeyLetterRatio = getRatio(a, R.styleable.KeyboardView_keyLetterRatio);
mKeyLargeLetterRatio = getRatio(a, R.styleable.KeyboardView_keyLargeLetterRatio);
mKeyLabelRatio = getRatio(a, R.styleable.KeyboardView_keyLabelRatio);
mKeyHintLetterRatio = getRatio(a, R.styleable.KeyboardView_keyHintLetterRatio);
mKeyUppercaseLetterRatio = getRatio(a,
R.styleable.KeyboardView_keyUppercaseLetterRatio);
mKeyHintLabelRatio = getRatio(a, R.styleable.KeyboardView_keyHintLabelRatio);
mKeyLabelHorizontalPadding = a.getDimension(
R.styleable.KeyboardView_keyLabelHorizontalPadding, 0);
mKeyHintLetterPadding = a.getDimension(
R.styleable.KeyboardView_keyHintLetterPadding, 0);
mKeyUppercaseLetterPadding = a.getDimension(
R.styleable.KeyboardView_keyUppercaseLetterPadding, 0);
mKeyTextColor = a.getColor(R.styleable.KeyboardView_keyTextColor, 0xFF000000);
mKeyTextInactivatedColor = a.getColor(
R.styleable.KeyboardView_keyTextInactivatedColor, 0xFF000000);
mKeyHintLetterColor = a.getColor(R.styleable.KeyboardView_keyHintLetterColor, 0);
mKeyHintLabelColor = a.getColor(R.styleable.KeyboardView_keyHintLabelColor, 0);
mKeyUppercaseLetterInactivatedColor = a.getColor(
R.styleable.KeyboardView_keyUppercaseLetterInactivatedColor, 0);
mKeyUppercaseLetterActivatedColor = a.getColor(
R.styleable.KeyboardView_keyUppercaseLetterActivatedColor, 0);
mKeyTextStyle = Typeface.defaultFromStyle(
a.getInt(R.styleable.KeyboardView_keyTextStyle, Typeface.NORMAL));
mShadowColor = a.getColor(R.styleable.KeyboardView_shadowColor, 0);
mShadowRadius = a.getFloat(R.styleable.KeyboardView_shadowRadius, 0f);
mKeyBackground.getPadding(mPadding);
}
public void updateKeyHeight(int keyHeight) {
mKeyLetterSize = (int)(keyHeight * mKeyLetterRatio);
mKeyLargeLetterSize = (int)(keyHeight * mKeyLargeLetterRatio);
mKeyLabelSize = (int)(keyHeight * mKeyLabelRatio);
mKeyHintLetterSize = (int)(keyHeight * mKeyHintLetterRatio);
mKeyUppercaseLetterSize = (int)(keyHeight * mKeyUppercaseLetterRatio);
mKeyHintLabelSize = (int)(keyHeight * mKeyHintLabelRatio);
}
}
private static class KeyPreviewDrawParams {
// XML attributes.
public final Drawable mPreviewBackground;
public final Drawable mPreviewLeftBackground;
public final Drawable mPreviewRightBackground;
public final int mPreviewTextColor;
public final int mPreviewOffset;
public final int mPreviewHeight;
public final Typeface mKeyTextStyle;
private final float mPreviewTextRatio;
private final float mKeyLetterRatio;
public int mPreviewTextSize;
public int mKeyLetterSize;
public final int[] mCoordinates = new int[2];
private static final int PREVIEW_ALPHA = 240;
public KeyPreviewDrawParams(TypedArray a, KeyDrawParams keyDrawParams) {
mPreviewBackground = a.getDrawable(R.styleable.KeyboardView_keyPreviewBackground);
mPreviewLeftBackground = a.getDrawable(
R.styleable.KeyboardView_keyPreviewLeftBackground);
mPreviewRightBackground = a.getDrawable(
R.styleable.KeyboardView_keyPreviewRightBackground);
setAlpha(mPreviewBackground, PREVIEW_ALPHA);
setAlpha(mPreviewLeftBackground, PREVIEW_ALPHA);
setAlpha(mPreviewRightBackground, PREVIEW_ALPHA);
mPreviewOffset = a.getDimensionPixelOffset(
R.styleable.KeyboardView_keyPreviewOffset, 0);
mPreviewHeight = a.getDimensionPixelSize(
R.styleable.KeyboardView_keyPreviewHeight, 80);
mPreviewTextRatio = getRatio(a, R.styleable.KeyboardView_keyPreviewTextRatio);
mPreviewTextColor = a.getColor(R.styleable.KeyboardView_keyPreviewTextColor, 0);
mKeyLetterRatio = keyDrawParams.mKeyLetterRatio;
mKeyTextStyle = keyDrawParams.mKeyTextStyle;
}
public void updateKeyHeight(int keyHeight) {
mPreviewTextSize = (int)(keyHeight * mPreviewTextRatio);
mKeyLetterSize = (int)(keyHeight * mKeyLetterRatio);
}
private static void setAlpha(Drawable drawable, int alpha) {
if (drawable == null)
return;
drawable.setAlpha(alpha);
}
}
public KeyboardView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.keyboardViewStyle);
}
public KeyboardView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.KeyboardView, defStyle, R.style.KeyboardView);
mKeyDrawParams = new KeyDrawParams(a);
mKeyPreviewDrawParams = new KeyPreviewDrawParams(a, mKeyDrawParams);
mKeyPreviewLayoutId = a.getResourceId(R.styleable.KeyboardView_keyPreviewLayout, 0);
if (mKeyPreviewLayoutId == 0) {
mShowKeyPreviewPopup = false;
}
mBackgroundDimAmount = a.getFloat(R.styleable.KeyboardView_backgroundDimAmount, 0.5f);
a.recycle();
final Resources res = getResources();
mDelayBeforePreview = res.getInteger(R.integer.config_delay_before_preview);
mDelayAfterPreview = res.getInteger(R.integer.config_delay_after_preview);
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Align.CENTER);
mPaint.setAlpha(255);
}
// Read fraction value in TypedArray as float.
private static float getRatio(TypedArray a, int index) {
return a.getFraction(index, 1000, 1000, 1) / 1000.0f;
}
/**
* Attaches a keyboard to this view. The keyboard can be switched at any time and the
* view will re-layout itself to accommodate the keyboard.
* @see Keyboard
* @see #getKeyboard()
* @param keyboard the keyboard to display in this view
*/
public void setKeyboard(Keyboard keyboard) {
// Remove any pending messages, except dismissing preview
mDrawingHandler.cancelAllShowKeyPreviews();
mKeyboard = keyboard;
LatinImeLogger.onSetKeyboard(keyboard);
requestLayout();
mDirtyRect.set(0, 0, getWidth(), getHeight());
mBufferNeedsUpdate = true;
invalidateAllKeys();
final int keyHeight = keyboard.getRowHeight() - keyboard.getVerticalGap();
mKeyDrawParams.updateKeyHeight(keyHeight);
mKeyPreviewDrawParams.updateKeyHeight(keyHeight);
}
/**
* Returns the current keyboard being displayed by this view.
* @return the currently attached keyboard
* @see #setKeyboard(Keyboard)
*/
public Keyboard getKeyboard() {
return mKeyboard;
}
/**
* Enables or disables the key feedback popup. This is a popup that shows a magnified
* version of the depressed key. By default the preview is enabled.
* @param previewEnabled whether or not to enable the key feedback preview
* @param delay the delay after which the preview is dismissed
* @see #isKeyPreviewPopupEnabled()
*/
public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) {
mShowKeyPreviewPopup = previewEnabled;
mDelayAfterPreview = delay;
}
/**
* Returns the enabled state of the key feedback preview
* @return whether or not the key feedback preview is enabled
* @see #setKeyPreviewPopupEnabled(boolean, int)
*/
public boolean isKeyPreviewPopupEnabled() {
return mShowKeyPreviewPopup;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mKeyboard != null) {
// The main keyboard expands to the display width.
final int height = mKeyboard.getKeyboardHeight() + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(widthMeasureSpec, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBufferNeedsUpdate || mBuffer == null) {
mBufferNeedsUpdate = false;
onBufferDraw();
}
canvas.drawBitmap(mBuffer, 0, 0, null);
}
private void onBufferDraw() {
final int width = getWidth();
final int height = getHeight();
if (width == 0 || height == 0)
return;
if (mBuffer == null || mBuffer.getWidth() != width || mBuffer.getHeight() != height) {
if (mBuffer != null)
mBuffer.recycle();
mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mDirtyRect.union(0, 0, width, height);
if (mCanvas != null) {
mCanvas.setBitmap(mBuffer);
} else {
mCanvas = new Canvas(mBuffer);
}
}
final Canvas canvas = mCanvas;
canvas.clipRect(mDirtyRect, Op.REPLACE);
canvas.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR);
if (mKeyboard == null) return;
final boolean isManualTemporaryUpperCase = mKeyboard.isManualTemporaryUpperCase();
final KeyDrawParams params = mKeyDrawParams;
if (mInvalidatedKey != null && mInvalidatedKeyRect.contains(mDirtyRect)) {
// Draw a single key.
final int keyDrawX = mInvalidatedKey.mX + mInvalidatedKey.mVisualInsetsLeft
+ getPaddingLeft();
final int keyDrawY = mInvalidatedKey.mY + getPaddingTop();
canvas.translate(keyDrawX, keyDrawY);
onBufferDrawKey(mInvalidatedKey, canvas, mPaint, params, isManualTemporaryUpperCase);
canvas.translate(-keyDrawX, -keyDrawY);
} else {
// Draw all keys.
for (final Key key : mKeyboard.getKeys()) {
final int keyDrawX = key.mX + key.mVisualInsetsLeft + getPaddingLeft();
final int keyDrawY = key.mY + getPaddingTop();
canvas.translate(keyDrawX, keyDrawY);
onBufferDrawKey(key, canvas, mPaint, params, isManualTemporaryUpperCase);
canvas.translate(-keyDrawX, -keyDrawY);
}
}
// Overlay a dark rectangle to dim the keyboard
if (needsToDimKeyboard()) {
mPaint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
canvas.drawRect(0, 0, width, height, mPaint);
}
mInvalidatedKey = null;
mDirtyRect.setEmpty();
}
protected boolean needsToDimKeyboard() {
return false;
}
private static void onBufferDrawKey(final Key key, final Canvas canvas, Paint paint,
KeyDrawParams params, boolean isManualTemporaryUpperCase) {
final boolean debugShowAlign = LatinImeLogger.sVISUALDEBUG;
// Draw key background.
final int bgWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight
+ params.mPadding.left + params.mPadding.right;
final int bgHeight = key.mHeight + params.mPadding.top + params.mPadding.bottom;
final int bgX = -params.mPadding.left;
final int bgY = -params.mPadding.top;
final int[] drawableState = key.getCurrentDrawableState();
final Drawable background = params.mKeyBackground;
background.setState(drawableState);
final Rect bounds = background.getBounds();
if (bgWidth != bounds.right || bgHeight != bounds.bottom) {
background.setBounds(0, 0, bgWidth, bgHeight);
}
canvas.translate(bgX, bgY);
background.draw(canvas);
if (debugShowAlign) {
drawRectangle(canvas, 0, 0, bgWidth, bgHeight, 0x80c00000, new Paint());
}
canvas.translate(-bgX, -bgY);
// Draw key top visuals.
final int keyWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight;
final int keyHeight = key.mHeight;
final float centerX = keyWidth * 0.5f;
final float centerY = keyHeight * 0.5f;
if (debugShowAlign) {
drawRectangle(canvas, 0, 0, keyWidth, keyHeight, 0x800000c0, new Paint());
}
// Draw key label.
float positionX = centerX;
if (key.mLabel != null) {
// Switch the character to uppercase if shift is pressed
final CharSequence label = key.getCaseAdjustedLabel();
// For characters, use large font. For labels like "Done", use smaller font.
paint.setTypeface(key.selectTypeface(params.mKeyTextStyle));
final int labelSize = key.selectTextSize(params.mKeyLetterSize,
params.mKeyLargeLetterSize, params.mKeyLabelSize, params.mKeyHintLabelSize);
paint.setTextSize(labelSize);
final float labelCharHeight = getCharHeight(paint);
final float labelCharWidth = getCharWidth(paint);
// Vertical label text alignment.
final float baseline = centerY + labelCharHeight / 2;
// Horizontal label text alignment
if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT) != 0) {
positionX = (int)params.mKeyLabelHorizontalPadding;
paint.setTextAlign(Align.LEFT);
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_RIGHT) != 0) {
positionX = keyWidth - (int)params.mKeyLabelHorizontalPadding;
paint.setTextAlign(Align.RIGHT);
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT_OF_CENTER) != 0) {
// TODO: Parameterise this?
positionX = centerX - labelCharWidth * 7 / 4;
paint.setTextAlign(Align.LEFT);
} else {
positionX = centerX;
paint.setTextAlign(Align.CENTER);
}
if (key.hasUppercaseLetter() && isManualTemporaryUpperCase) {
paint.setColor(params.mKeyTextInactivatedColor);
} else {
paint.setColor(params.mKeyTextColor);
}
if (key.isEnabled()) {
// Set a drop shadow for the text
paint.setShadowLayer(params.mShadowRadius, 0, 0, params.mShadowColor);
} else {
// Make label invisible
paint.setColor(Color.TRANSPARENT);
}
canvas.drawText(label, 0, label.length(), positionX, baseline, paint);
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, baseline, keyWidth, 0xc0008000, line);
drawVerticalLine(canvas, positionX, keyHeight, 0xc0800080, line);
}
}
// Draw hint label.
if (key.mHintLabel != null) {
final CharSequence hint = key.mHintLabel;
final int hintColor;
final int hintSize;
if (key.hasHintLabel()) {
hintColor = params.mKeyHintLabelColor;
hintSize = params.mKeyHintLabelSize;
paint.setTypeface(Typeface.DEFAULT);
} else if (key.hasUppercaseLetter()) {
hintColor = isManualTemporaryUpperCase
? params.mKeyUppercaseLetterActivatedColor
: params.mKeyUppercaseLetterInactivatedColor;
hintSize = params.mKeyUppercaseLetterSize;
} else { // key.hasHintLetter()
hintColor = params.mKeyHintLetterColor;
hintSize = params.mKeyHintLetterSize;
}
paint.setColor(hintColor);
paint.setTextSize(hintSize);
final float hintCharWidth = getCharWidth(paint);
final float hintX, hintY;
if (key.hasHintLabel()) {
// TODO: Generalize the following calculations.
hintX = positionX + hintCharWidth * 2;
hintY = centerY + getCharHeight(paint) / 2;
paint.setTextAlign(Align.LEFT);
} else if (key.hasUppercaseLetter()) {
hintX = keyWidth - params.mKeyUppercaseLetterPadding - hintCharWidth / 2;
hintY = -paint.ascent() + params.mKeyUppercaseLetterPadding;
paint.setTextAlign(Align.CENTER);
} else { // key.hasHintLetter()
hintX = keyWidth - params.mKeyHintLetterPadding - hintCharWidth / 2;
hintY = -paint.ascent() + params.mKeyHintLetterPadding;
paint.setTextAlign(Align.CENTER);
}
canvas.drawText(hint, 0, hint.length(), hintX, hintY, paint);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, (int)hintY, keyWidth, 0xc0808000, line);
drawVerticalLine(canvas, (int)hintX, keyHeight, 0xc0808000, line);
}
}
// Draw key icon.
final Drawable icon = key.getIcon();
if (key.mLabel == null && icon != null) {
final int iconWidth = icon.getIntrinsicWidth();
final int iconHeight = icon.getIntrinsicHeight();
final int iconX, alignX;
final int iconY = (keyHeight - iconHeight) / 2;
if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT) != 0) {
iconX = (int)params.mKeyLabelHorizontalPadding;
alignX = iconX;
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_RIGHT) != 0) {
iconX = keyWidth - (int)params.mKeyLabelHorizontalPadding - iconWidth;
alignX = iconX + iconWidth;
} else { // Align center
iconX = (keyWidth - iconWidth) / 2;
alignX = iconX + iconWidth / 2;
}
drawIcon(canvas, icon, iconX, iconY, iconWidth, iconHeight);
if (debugShowAlign) {
final Paint line = new Paint();
drawVerticalLine(canvas, alignX, keyHeight, 0xc0800080, line);
drawRectangle(canvas, iconX, iconY, iconWidth, iconHeight, 0x80c00000, line);
}
}
// Draw popup hint "..." at the bottom right corner of the key.
- if (key.hasPopupHint()) {
+ if (key.hasPopupHint() && key.mPopupCharacters != null && key.mPopupCharacters.length > 0) {
paint.setTextSize(params.mKeyHintLetterSize);
paint.setColor(params.mKeyHintLabelColor);
paint.setTextAlign(Align.CENTER);
final float hintX = keyWidth - params.mKeyHintLetterPadding - getCharWidth(paint) / 2;
final float hintY = keyHeight - params.mKeyHintLetterPadding;
canvas.drawText(POPUP_HINT_CHAR, hintX, hintY, paint);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, (int)hintY, keyWidth, 0xc0808000, line);
drawVerticalLine(canvas, (int)hintX, keyHeight, 0xc0808000, line);
}
}
}
// This method is currently being used only by MiniKeyboardBuilder
public int getDefaultLabelSizeAndSetPaint(Paint paint) {
// For characters, use large font. For labels like "Done", use small font.
final int labelSize = mKeyDrawParams.mKeyLabelSize;
paint.setTextSize(labelSize);
paint.setTypeface(mKeyDrawParams.mKeyTextStyle);
return labelSize;
}
private static final Rect sTextBounds = new Rect();
private static float getCharHeight(Paint paint) {
final int labelSize = (int)paint.getTextSize();
final Float cachedValue = sTextHeightCache.get(labelSize);
if (cachedValue != null)
return cachedValue;
paint.getTextBounds(KEY_LABEL_REFERENCE_CHAR, 0, 1, sTextBounds);
final float height = sTextBounds.height();
sTextHeightCache.put(labelSize, height);
return height;
}
private static float getCharWidth(Paint paint) {
final int labelSize = (int)paint.getTextSize();
final Typeface face = paint.getTypeface();
final Integer key;
if (face == Typeface.DEFAULT) {
key = labelSize;
} else if (face == Typeface.DEFAULT_BOLD) {
key = labelSize + 1000;
} else if (face == Typeface.MONOSPACE) {
key = labelSize + 2000;
} else {
key = labelSize;
}
final Float cached = sTextWidthCache.get(key);
if (cached != null)
return cached;
paint.getTextBounds(KEY_LABEL_REFERENCE_CHAR, 0, 1, sTextBounds);
final float width = sTextBounds.width();
sTextWidthCache.put(key, width);
return width;
}
private static void drawIcon(Canvas canvas, Drawable icon, int x, int y, int width,
int height) {
canvas.translate(x, y);
icon.setBounds(0, 0, width, height);
icon.draw(canvas);
canvas.translate(-x, -y);
}
private static void drawHorizontalLine(Canvas canvas, float y, float w, int color, Paint paint) {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1.0f);
paint.setColor(color);
canvas.drawLine(0, y, w, y, paint);
}
private static void drawVerticalLine(Canvas canvas, float x, float h, int color, Paint paint) {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1.0f);
paint.setColor(color);
canvas.drawLine(x, 0, x, h, paint);
}
private static void drawRectangle(Canvas canvas, float x, float y, float w, float h, int color,
Paint paint) {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1.0f);
paint.setColor(color);
canvas.translate(x, y);
canvas.drawRect(0, 0, w, h, paint);
canvas.translate(-x, -y);
}
public void cancelAllMessages() {
mDrawingHandler.cancelAllMessages();
}
// Called by {@link PointerTracker} constructor to create a TextView.
@Override
public TextView inflateKeyPreviewText() {
final Context context = getContext();
if (mKeyPreviewLayoutId != 0) {
return (TextView)LayoutInflater.from(context).inflate(mKeyPreviewLayoutId, null);
} else {
return new TextView(context);
}
}
@Override
public void showKeyPreview(int keyIndex, PointerTracker tracker) {
if (mShowKeyPreviewPopup) {
mDrawingHandler.showKeyPreview(mDelayBeforePreview, keyIndex, tracker);
}
}
@Override
public void cancelShowKeyPreview(PointerTracker tracker) {
mDrawingHandler.cancelShowKeyPreview(tracker);
}
@Override
public void dismissKeyPreview(PointerTracker tracker) {
mDrawingHandler.cancelShowKeyPreview(tracker);
mDrawingHandler.dismissKeyPreview(mDelayAfterPreview, tracker);
}
private void addKeyPreview(TextView keyPreview) {
if (mPreviewPlacer == null) {
mPreviewPlacer = FrameLayoutCompatUtils.getPlacer(
(ViewGroup)getRootView().findViewById(android.R.id.content));
}
final ViewGroup placer = mPreviewPlacer;
placer.addView(keyPreview, FrameLayoutCompatUtils.newLayoutParam(placer, 0, 0));
}
// TODO: Introduce minimum duration for displaying key previews
private void showKey(final int keyIndex, PointerTracker tracker) {
final TextView previewText = tracker.getKeyPreviewText();
// If the key preview has no parent view yet, add it to the ViewGroup which can place
// key preview absolutely in SoftInputWindow.
if (previewText.getParent() == null) {
addKeyPreview(previewText);
}
mDrawingHandler.cancelDismissKeyPreview(tracker);
final Key key = tracker.getKey(keyIndex);
// If keyIndex is invalid or IME is already closed, we must not show key preview.
// Trying to show key preview while root window is closed causes
// WindowManager.BadTokenException.
if (key == null)
return;
final KeyPreviewDrawParams params = mKeyPreviewDrawParams;
final int keyDrawX = key.mX + key.mVisualInsetsLeft;
final int keyDrawWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight;
// What we show as preview should match what we show on key top in onBufferDraw().
if (key.mLabel != null) {
// TODO Should take care of temporaryShiftLabel here.
previewText.setCompoundDrawables(null, null, null, null);
if (key.mLabel.length() > 1) {
previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, params.mKeyLetterSize);
previewText.setTypeface(Typeface.DEFAULT_BOLD);
} else {
previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, params.mPreviewTextSize);
previewText.setTypeface(params.mKeyTextStyle);
}
previewText.setText(key.getCaseAdjustedLabel());
} else {
final Drawable previewIcon = key.getPreviewIcon();
previewText.setCompoundDrawables(null, null, null,
previewIcon != null ? previewIcon : key.getIcon());
previewText.setText(null);
}
previewText.setBackgroundDrawable(params.mPreviewBackground);
previewText.measure(MEASURESPEC_UNSPECIFIED, MEASURESPEC_UNSPECIFIED);
final int previewWidth = Math.max(previewText.getMeasuredWidth(), keyDrawWidth
+ previewText.getPaddingLeft() + previewText.getPaddingRight());
final int previewHeight = params.mPreviewHeight;
getLocationInWindow(params.mCoordinates);
int previewX = keyDrawX - (previewWidth - keyDrawWidth) / 2 + params.mCoordinates[0];
final int previewY = key.mY - previewHeight
+ params.mCoordinates[1] + params.mPreviewOffset;
if (previewX < 0 && params.mPreviewLeftBackground != null) {
previewText.setBackgroundDrawable(params.mPreviewLeftBackground);
previewX = 0;
} else if (previewX + previewWidth > getWidth() && params.mPreviewRightBackground != null) {
previewText.setBackgroundDrawable(params.mPreviewRightBackground);
previewX = getWidth() - previewWidth;
}
// Set the preview background state
previewText.getBackground().setState(
key.mPopupCharacters != null ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET);
previewText.setTextColor(params.mPreviewTextColor);
FrameLayoutCompatUtils.placeViewAt(
previewText, previewX, previewY, previewWidth, previewHeight);
previewText.setVisibility(VISIBLE);
}
/**
* Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient
* because the keyboard renders the keys to an off-screen buffer and an invalidate() only
* draws the cached buffer.
* @see #invalidateKey(Key)
*/
public void invalidateAllKeys() {
mDirtyRect.union(0, 0, getWidth(), getHeight());
mBufferNeedsUpdate = true;
invalidate();
}
/**
* Invalidates a key so that it will be redrawn on the next repaint. Use this method if only
* one key is changing it's content. Any changes that affect the position or size of the key
* may not be honored.
* @param key key in the attached {@link Keyboard}.
* @see #invalidateAllKeys
*/
@Override
public void invalidateKey(Key key) {
if (key == null)
return;
mInvalidatedKey = key;
final int x = key.mX + getPaddingLeft();
final int y = key.mY + getPaddingTop();
mInvalidatedKeyRect.set(x, y, x + key.mWidth, y + key.mHeight);
mDirtyRect.union(mInvalidatedKeyRect);
mBufferNeedsUpdate = true;
invalidate(mInvalidatedKeyRect);
}
public void closing() {
PointerTracker.dismissAllKeyPreviews();
cancelAllMessages();
mDirtyRect.union(0, 0, getWidth(), getHeight());
requestLayout();
}
@Override
public boolean dismissPopupPanel() {
return false;
}
public void purgeKeyboardAndClosing() {
mKeyboard = null;
closing();
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
closing();
}
}
| true | true | private static void onBufferDrawKey(final Key key, final Canvas canvas, Paint paint,
KeyDrawParams params, boolean isManualTemporaryUpperCase) {
final boolean debugShowAlign = LatinImeLogger.sVISUALDEBUG;
// Draw key background.
final int bgWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight
+ params.mPadding.left + params.mPadding.right;
final int bgHeight = key.mHeight + params.mPadding.top + params.mPadding.bottom;
final int bgX = -params.mPadding.left;
final int bgY = -params.mPadding.top;
final int[] drawableState = key.getCurrentDrawableState();
final Drawable background = params.mKeyBackground;
background.setState(drawableState);
final Rect bounds = background.getBounds();
if (bgWidth != bounds.right || bgHeight != bounds.bottom) {
background.setBounds(0, 0, bgWidth, bgHeight);
}
canvas.translate(bgX, bgY);
background.draw(canvas);
if (debugShowAlign) {
drawRectangle(canvas, 0, 0, bgWidth, bgHeight, 0x80c00000, new Paint());
}
canvas.translate(-bgX, -bgY);
// Draw key top visuals.
final int keyWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight;
final int keyHeight = key.mHeight;
final float centerX = keyWidth * 0.5f;
final float centerY = keyHeight * 0.5f;
if (debugShowAlign) {
drawRectangle(canvas, 0, 0, keyWidth, keyHeight, 0x800000c0, new Paint());
}
// Draw key label.
float positionX = centerX;
if (key.mLabel != null) {
// Switch the character to uppercase if shift is pressed
final CharSequence label = key.getCaseAdjustedLabel();
// For characters, use large font. For labels like "Done", use smaller font.
paint.setTypeface(key.selectTypeface(params.mKeyTextStyle));
final int labelSize = key.selectTextSize(params.mKeyLetterSize,
params.mKeyLargeLetterSize, params.mKeyLabelSize, params.mKeyHintLabelSize);
paint.setTextSize(labelSize);
final float labelCharHeight = getCharHeight(paint);
final float labelCharWidth = getCharWidth(paint);
// Vertical label text alignment.
final float baseline = centerY + labelCharHeight / 2;
// Horizontal label text alignment
if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT) != 0) {
positionX = (int)params.mKeyLabelHorizontalPadding;
paint.setTextAlign(Align.LEFT);
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_RIGHT) != 0) {
positionX = keyWidth - (int)params.mKeyLabelHorizontalPadding;
paint.setTextAlign(Align.RIGHT);
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT_OF_CENTER) != 0) {
// TODO: Parameterise this?
positionX = centerX - labelCharWidth * 7 / 4;
paint.setTextAlign(Align.LEFT);
} else {
positionX = centerX;
paint.setTextAlign(Align.CENTER);
}
if (key.hasUppercaseLetter() && isManualTemporaryUpperCase) {
paint.setColor(params.mKeyTextInactivatedColor);
} else {
paint.setColor(params.mKeyTextColor);
}
if (key.isEnabled()) {
// Set a drop shadow for the text
paint.setShadowLayer(params.mShadowRadius, 0, 0, params.mShadowColor);
} else {
// Make label invisible
paint.setColor(Color.TRANSPARENT);
}
canvas.drawText(label, 0, label.length(), positionX, baseline, paint);
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, baseline, keyWidth, 0xc0008000, line);
drawVerticalLine(canvas, positionX, keyHeight, 0xc0800080, line);
}
}
// Draw hint label.
if (key.mHintLabel != null) {
final CharSequence hint = key.mHintLabel;
final int hintColor;
final int hintSize;
if (key.hasHintLabel()) {
hintColor = params.mKeyHintLabelColor;
hintSize = params.mKeyHintLabelSize;
paint.setTypeface(Typeface.DEFAULT);
} else if (key.hasUppercaseLetter()) {
hintColor = isManualTemporaryUpperCase
? params.mKeyUppercaseLetterActivatedColor
: params.mKeyUppercaseLetterInactivatedColor;
hintSize = params.mKeyUppercaseLetterSize;
} else { // key.hasHintLetter()
hintColor = params.mKeyHintLetterColor;
hintSize = params.mKeyHintLetterSize;
}
paint.setColor(hintColor);
paint.setTextSize(hintSize);
final float hintCharWidth = getCharWidth(paint);
final float hintX, hintY;
if (key.hasHintLabel()) {
// TODO: Generalize the following calculations.
hintX = positionX + hintCharWidth * 2;
hintY = centerY + getCharHeight(paint) / 2;
paint.setTextAlign(Align.LEFT);
} else if (key.hasUppercaseLetter()) {
hintX = keyWidth - params.mKeyUppercaseLetterPadding - hintCharWidth / 2;
hintY = -paint.ascent() + params.mKeyUppercaseLetterPadding;
paint.setTextAlign(Align.CENTER);
} else { // key.hasHintLetter()
hintX = keyWidth - params.mKeyHintLetterPadding - hintCharWidth / 2;
hintY = -paint.ascent() + params.mKeyHintLetterPadding;
paint.setTextAlign(Align.CENTER);
}
canvas.drawText(hint, 0, hint.length(), hintX, hintY, paint);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, (int)hintY, keyWidth, 0xc0808000, line);
drawVerticalLine(canvas, (int)hintX, keyHeight, 0xc0808000, line);
}
}
// Draw key icon.
final Drawable icon = key.getIcon();
if (key.mLabel == null && icon != null) {
final int iconWidth = icon.getIntrinsicWidth();
final int iconHeight = icon.getIntrinsicHeight();
final int iconX, alignX;
final int iconY = (keyHeight - iconHeight) / 2;
if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT) != 0) {
iconX = (int)params.mKeyLabelHorizontalPadding;
alignX = iconX;
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_RIGHT) != 0) {
iconX = keyWidth - (int)params.mKeyLabelHorizontalPadding - iconWidth;
alignX = iconX + iconWidth;
} else { // Align center
iconX = (keyWidth - iconWidth) / 2;
alignX = iconX + iconWidth / 2;
}
drawIcon(canvas, icon, iconX, iconY, iconWidth, iconHeight);
if (debugShowAlign) {
final Paint line = new Paint();
drawVerticalLine(canvas, alignX, keyHeight, 0xc0800080, line);
drawRectangle(canvas, iconX, iconY, iconWidth, iconHeight, 0x80c00000, line);
}
}
// Draw popup hint "..." at the bottom right corner of the key.
if (key.hasPopupHint()) {
paint.setTextSize(params.mKeyHintLetterSize);
paint.setColor(params.mKeyHintLabelColor);
paint.setTextAlign(Align.CENTER);
final float hintX = keyWidth - params.mKeyHintLetterPadding - getCharWidth(paint) / 2;
final float hintY = keyHeight - params.mKeyHintLetterPadding;
canvas.drawText(POPUP_HINT_CHAR, hintX, hintY, paint);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, (int)hintY, keyWidth, 0xc0808000, line);
drawVerticalLine(canvas, (int)hintX, keyHeight, 0xc0808000, line);
}
}
}
| private static void onBufferDrawKey(final Key key, final Canvas canvas, Paint paint,
KeyDrawParams params, boolean isManualTemporaryUpperCase) {
final boolean debugShowAlign = LatinImeLogger.sVISUALDEBUG;
// Draw key background.
final int bgWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight
+ params.mPadding.left + params.mPadding.right;
final int bgHeight = key.mHeight + params.mPadding.top + params.mPadding.bottom;
final int bgX = -params.mPadding.left;
final int bgY = -params.mPadding.top;
final int[] drawableState = key.getCurrentDrawableState();
final Drawable background = params.mKeyBackground;
background.setState(drawableState);
final Rect bounds = background.getBounds();
if (bgWidth != bounds.right || bgHeight != bounds.bottom) {
background.setBounds(0, 0, bgWidth, bgHeight);
}
canvas.translate(bgX, bgY);
background.draw(canvas);
if (debugShowAlign) {
drawRectangle(canvas, 0, 0, bgWidth, bgHeight, 0x80c00000, new Paint());
}
canvas.translate(-bgX, -bgY);
// Draw key top visuals.
final int keyWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight;
final int keyHeight = key.mHeight;
final float centerX = keyWidth * 0.5f;
final float centerY = keyHeight * 0.5f;
if (debugShowAlign) {
drawRectangle(canvas, 0, 0, keyWidth, keyHeight, 0x800000c0, new Paint());
}
// Draw key label.
float positionX = centerX;
if (key.mLabel != null) {
// Switch the character to uppercase if shift is pressed
final CharSequence label = key.getCaseAdjustedLabel();
// For characters, use large font. For labels like "Done", use smaller font.
paint.setTypeface(key.selectTypeface(params.mKeyTextStyle));
final int labelSize = key.selectTextSize(params.mKeyLetterSize,
params.mKeyLargeLetterSize, params.mKeyLabelSize, params.mKeyHintLabelSize);
paint.setTextSize(labelSize);
final float labelCharHeight = getCharHeight(paint);
final float labelCharWidth = getCharWidth(paint);
// Vertical label text alignment.
final float baseline = centerY + labelCharHeight / 2;
// Horizontal label text alignment
if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT) != 0) {
positionX = (int)params.mKeyLabelHorizontalPadding;
paint.setTextAlign(Align.LEFT);
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_RIGHT) != 0) {
positionX = keyWidth - (int)params.mKeyLabelHorizontalPadding;
paint.setTextAlign(Align.RIGHT);
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT_OF_CENTER) != 0) {
// TODO: Parameterise this?
positionX = centerX - labelCharWidth * 7 / 4;
paint.setTextAlign(Align.LEFT);
} else {
positionX = centerX;
paint.setTextAlign(Align.CENTER);
}
if (key.hasUppercaseLetter() && isManualTemporaryUpperCase) {
paint.setColor(params.mKeyTextInactivatedColor);
} else {
paint.setColor(params.mKeyTextColor);
}
if (key.isEnabled()) {
// Set a drop shadow for the text
paint.setShadowLayer(params.mShadowRadius, 0, 0, params.mShadowColor);
} else {
// Make label invisible
paint.setColor(Color.TRANSPARENT);
}
canvas.drawText(label, 0, label.length(), positionX, baseline, paint);
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, baseline, keyWidth, 0xc0008000, line);
drawVerticalLine(canvas, positionX, keyHeight, 0xc0800080, line);
}
}
// Draw hint label.
if (key.mHintLabel != null) {
final CharSequence hint = key.mHintLabel;
final int hintColor;
final int hintSize;
if (key.hasHintLabel()) {
hintColor = params.mKeyHintLabelColor;
hintSize = params.mKeyHintLabelSize;
paint.setTypeface(Typeface.DEFAULT);
} else if (key.hasUppercaseLetter()) {
hintColor = isManualTemporaryUpperCase
? params.mKeyUppercaseLetterActivatedColor
: params.mKeyUppercaseLetterInactivatedColor;
hintSize = params.mKeyUppercaseLetterSize;
} else { // key.hasHintLetter()
hintColor = params.mKeyHintLetterColor;
hintSize = params.mKeyHintLetterSize;
}
paint.setColor(hintColor);
paint.setTextSize(hintSize);
final float hintCharWidth = getCharWidth(paint);
final float hintX, hintY;
if (key.hasHintLabel()) {
// TODO: Generalize the following calculations.
hintX = positionX + hintCharWidth * 2;
hintY = centerY + getCharHeight(paint) / 2;
paint.setTextAlign(Align.LEFT);
} else if (key.hasUppercaseLetter()) {
hintX = keyWidth - params.mKeyUppercaseLetterPadding - hintCharWidth / 2;
hintY = -paint.ascent() + params.mKeyUppercaseLetterPadding;
paint.setTextAlign(Align.CENTER);
} else { // key.hasHintLetter()
hintX = keyWidth - params.mKeyHintLetterPadding - hintCharWidth / 2;
hintY = -paint.ascent() + params.mKeyHintLetterPadding;
paint.setTextAlign(Align.CENTER);
}
canvas.drawText(hint, 0, hint.length(), hintX, hintY, paint);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, (int)hintY, keyWidth, 0xc0808000, line);
drawVerticalLine(canvas, (int)hintX, keyHeight, 0xc0808000, line);
}
}
// Draw key icon.
final Drawable icon = key.getIcon();
if (key.mLabel == null && icon != null) {
final int iconWidth = icon.getIntrinsicWidth();
final int iconHeight = icon.getIntrinsicHeight();
final int iconX, alignX;
final int iconY = (keyHeight - iconHeight) / 2;
if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_LEFT) != 0) {
iconX = (int)params.mKeyLabelHorizontalPadding;
alignX = iconX;
} else if ((key.mLabelOption & Key.LABEL_OPTION_ALIGN_RIGHT) != 0) {
iconX = keyWidth - (int)params.mKeyLabelHorizontalPadding - iconWidth;
alignX = iconX + iconWidth;
} else { // Align center
iconX = (keyWidth - iconWidth) / 2;
alignX = iconX + iconWidth / 2;
}
drawIcon(canvas, icon, iconX, iconY, iconWidth, iconHeight);
if (debugShowAlign) {
final Paint line = new Paint();
drawVerticalLine(canvas, alignX, keyHeight, 0xc0800080, line);
drawRectangle(canvas, iconX, iconY, iconWidth, iconHeight, 0x80c00000, line);
}
}
// Draw popup hint "..." at the bottom right corner of the key.
if (key.hasPopupHint() && key.mPopupCharacters != null && key.mPopupCharacters.length > 0) {
paint.setTextSize(params.mKeyHintLetterSize);
paint.setColor(params.mKeyHintLabelColor);
paint.setTextAlign(Align.CENTER);
final float hintX = keyWidth - params.mKeyHintLetterPadding - getCharWidth(paint) / 2;
final float hintY = keyHeight - params.mKeyHintLetterPadding;
canvas.drawText(POPUP_HINT_CHAR, hintX, hintY, paint);
if (debugShowAlign) {
final Paint line = new Paint();
drawHorizontalLine(canvas, (int)hintY, keyWidth, 0xc0808000, line);
drawVerticalLine(canvas, (int)hintX, keyHeight, 0xc0808000, line);
}
}
}
|
diff --git a/extrabiomes/src/extrabiomes/module/fabrica/recipe/WoodCookBook.java b/extrabiomes/src/extrabiomes/module/fabrica/recipe/WoodCookBook.java
index 03b2f4d3..84d57cd0 100644
--- a/extrabiomes/src/extrabiomes/module/fabrica/recipe/WoodCookBook.java
+++ b/extrabiomes/src/extrabiomes/module/fabrica/recipe/WoodCookBook.java
@@ -1,198 +1,200 @@
/**
* This work is licensed under the Creative Commons
* Attribution-ShareAlike 3.0 Unported License. To view a copy of this
* license, visit http://creativecommons.org/licenses/by-sa/3.0/.
*/
package extrabiomes.module.fabrica.recipe;
import net.minecraft.src.Block;
import net.minecraft.src.IRecipe;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import com.google.common.base.Optional;
import extrabiomes.Extrabiomes;
import extrabiomes.module.fabrica.block.BlockCustomWood;
import extrabiomes.module.fabrica.block.BlockCustomWoodSlab;
import extrabiomes.module.fabrica.block.BlockManager;
public class WoodCookBook {
private static void addLogRecipes() {
final Optional<? extends Block> planks = BlockManager.PLANKS
.getBlock();
if (planks.isPresent()) {
IRecipe recipe = new ShapelessOreRecipe(new ItemStack(
planks.get(), 4,
BlockCustomWood.BlockType.FIR.metadata()), "logFir");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapelessOreRecipe(new ItemStack(planks.get(),
4, BlockCustomWood.BlockType.ACACIA.metadata()),
"logAcacia");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapelessOreRecipe(new ItemStack(planks.get(),
4, BlockCustomWood.BlockType.REDWOOD.metadata()),
"logRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
}
private static void addPlankCustomRecipes() {
Optional<? extends Block> stairs = BlockManager.ACACIASTAIRS
.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankAcacia");
Extrabiomes.proxy.addRecipe(recipe);
}
stairs = BlockManager.FIRSTAIRS.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankFir");
Extrabiomes.proxy.addRecipe(recipe);
}
stairs = BlockManager.REDWOODSTAIRS.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
final Optional<? extends Block> slab = BlockManager.WOODSLAB
.getBlock();
if (slab.isPresent()) {
IRecipe recipe = new ShapedOreRecipe(new ItemStack(
slab.get(), 6,
BlockCustomWoodSlab.BlockType.ACACIA.metadata()),
new String[] { "ppp" }, 'p', "plankAcacia");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(slab.get(), 6,
BlockCustomWoodSlab.BlockType.FIR.metadata()),
new String[] { "ppp" }, 'p', "plankFir");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(slab.get(), 6,
BlockCustomWoodSlab.BlockType.REDWOOD.metadata()),
new String[] { "ppp" }, 'p', "plankRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
}
private static void addPlankVanillaRecipes() {
IRecipe recipe = new ShapedOreRecipe(Block.chest, new String[] {
"ppp", "p p", "ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.workbench, new String[] {
"pp", "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.pickaxeWood, new String[] {
"ppp", " s ", " s " }, 'p', "plankWood", 's',
Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.shovelWood, new String[] {
"p", "s", "s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.axeWood, new String[] { "pp",
"ps", " s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.hoeWood, new String[] { "pp",
" s", " s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.swordWood, new String[] {
"p", "p", "s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.fenceGate, new String[] {
"sps", "sps" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.jukebox, new String[] {
"ppp", "pdp", "ppp" }, 'p', "plankWood", 'r',
Item.diamond);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.music, new String[] { "ppp",
"prp", "ppp" }, 'p', "plankWood", 'r', Item.redstone);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.bookShelf, new String[] {
"ppp", "bbb", "ppp" }, 'p', "plankWood", 'b', Item.book);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.doorWood, new String[] {
"pp", "pp", "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(Block.trapdoor, 2),
new String[] { "ppp", "ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.sign, new String[] { "ppp",
"ppp", " s " }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapelessOreRecipe(new ItemStack(Item.stick, 4),
"plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(Item.bowlEmpty, 4),
new String[] { "p p", " p " }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.boat, new String[] { "p p",
"ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.pressurePlatePlanks,
new String[] { "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.pistonBase, new String[] {
"ppp", "cic", "crc" }, 'p', "plankWood", 'c',
Block.cobblestone, 'i', Item.ingotIron, 'r',
Item.redstone);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.bed, new String[] { "ppp",
"ccc", "ppp" }, 'p', "plankWood", 'c', Block.cloth);
Extrabiomes.proxy.addRecipe(recipe);
- recipe = new ShapedOreRecipe(Block.tripWireSource, new String[] { "i",
- "s", "p" }, 'p', "plankWood", 'i', Item.ingotIron, 's', Item.stick);
+ recipe = new ShapedOreRecipe(new ItemStack(
+ Block.tripWireSource, 2),
+ new String[] { "i", "s", "p" }, 'p', "plankWood", 'i',
+ Item.ingotIron, 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
}
public static void init() {
addPlankVanillaRecipes();
addPlankCustomRecipes();
addLogRecipes();
}
}
| true | true | private static void addPlankCustomRecipes() {
Optional<? extends Block> stairs = BlockManager.ACACIASTAIRS
.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankAcacia");
Extrabiomes.proxy.addRecipe(recipe);
}
stairs = BlockManager.FIRSTAIRS.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankFir");
Extrabiomes.proxy.addRecipe(recipe);
}
stairs = BlockManager.REDWOODSTAIRS.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
final Optional<? extends Block> slab = BlockManager.WOODSLAB
.getBlock();
if (slab.isPresent()) {
IRecipe recipe = new ShapedOreRecipe(new ItemStack(
slab.get(), 6,
BlockCustomWoodSlab.BlockType.ACACIA.metadata()),
new String[] { "ppp" }, 'p', "plankAcacia");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(slab.get(), 6,
BlockCustomWoodSlab.BlockType.FIR.metadata()),
new String[] { "ppp" }, 'p', "plankFir");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(slab.get(), 6,
BlockCustomWoodSlab.BlockType.REDWOOD.metadata()),
new String[] { "ppp" }, 'p', "plankRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
}
private static void addPlankVanillaRecipes() {
IRecipe recipe = new ShapedOreRecipe(Block.chest, new String[] {
"ppp", "p p", "ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.workbench, new String[] {
"pp", "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.pickaxeWood, new String[] {
"ppp", " s ", " s " }, 'p', "plankWood", 's',
Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.shovelWood, new String[] {
"p", "s", "s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.axeWood, new String[] { "pp",
"ps", " s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.hoeWood, new String[] { "pp",
" s", " s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.swordWood, new String[] {
"p", "p", "s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.fenceGate, new String[] {
"sps", "sps" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.jukebox, new String[] {
"ppp", "pdp", "ppp" }, 'p', "plankWood", 'r',
Item.diamond);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.music, new String[] { "ppp",
"prp", "ppp" }, 'p', "plankWood", 'r', Item.redstone);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.bookShelf, new String[] {
"ppp", "bbb", "ppp" }, 'p', "plankWood", 'b', Item.book);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.doorWood, new String[] {
"pp", "pp", "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(Block.trapdoor, 2),
new String[] { "ppp", "ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.sign, new String[] { "ppp",
"ppp", " s " }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapelessOreRecipe(new ItemStack(Item.stick, 4),
"plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(Item.bowlEmpty, 4),
new String[] { "p p", " p " }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.boat, new String[] { "p p",
"ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.pressurePlatePlanks,
new String[] { "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.pistonBase, new String[] {
"ppp", "cic", "crc" }, 'p', "plankWood", 'c',
Block.cobblestone, 'i', Item.ingotIron, 'r',
Item.redstone);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.bed, new String[] { "ppp",
"ccc", "ppp" }, 'p', "plankWood", 'c', Block.cloth);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.tripWireSource, new String[] { "i",
"s", "p" }, 'p', "plankWood", 'i', Item.ingotIron, 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
}
public static void init() {
addPlankVanillaRecipes();
addPlankCustomRecipes();
addLogRecipes();
}
}
| private static void addPlankCustomRecipes() {
Optional<? extends Block> stairs = BlockManager.ACACIASTAIRS
.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankAcacia");
Extrabiomes.proxy.addRecipe(recipe);
}
stairs = BlockManager.FIRSTAIRS.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankFir");
Extrabiomes.proxy.addRecipe(recipe);
}
stairs = BlockManager.REDWOODSTAIRS.getBlock();
if (stairs.isPresent()) {
final IRecipe recipe = new ShapedOreRecipe(new ItemStack(
stairs.get(), 4), new String[] { "p ", "pp ",
"ppp" }, 'p', "plankRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
final Optional<? extends Block> slab = BlockManager.WOODSLAB
.getBlock();
if (slab.isPresent()) {
IRecipe recipe = new ShapedOreRecipe(new ItemStack(
slab.get(), 6,
BlockCustomWoodSlab.BlockType.ACACIA.metadata()),
new String[] { "ppp" }, 'p', "plankAcacia");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(slab.get(), 6,
BlockCustomWoodSlab.BlockType.FIR.metadata()),
new String[] { "ppp" }, 'p', "plankFir");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(slab.get(), 6,
BlockCustomWoodSlab.BlockType.REDWOOD.metadata()),
new String[] { "ppp" }, 'p', "plankRedwood");
Extrabiomes.proxy.addRecipe(recipe);
}
}
private static void addPlankVanillaRecipes() {
IRecipe recipe = new ShapedOreRecipe(Block.chest, new String[] {
"ppp", "p p", "ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.workbench, new String[] {
"pp", "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.pickaxeWood, new String[] {
"ppp", " s ", " s " }, 'p', "plankWood", 's',
Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.shovelWood, new String[] {
"p", "s", "s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.axeWood, new String[] { "pp",
"ps", " s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.hoeWood, new String[] { "pp",
" s", " s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.swordWood, new String[] {
"p", "p", "s" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.fenceGate, new String[] {
"sps", "sps" }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.jukebox, new String[] {
"ppp", "pdp", "ppp" }, 'p', "plankWood", 'r',
Item.diamond);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.music, new String[] { "ppp",
"prp", "ppp" }, 'p', "plankWood", 'r', Item.redstone);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.bookShelf, new String[] {
"ppp", "bbb", "ppp" }, 'p', "plankWood", 'b', Item.book);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.doorWood, new String[] {
"pp", "pp", "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(Block.trapdoor, 2),
new String[] { "ppp", "ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.sign, new String[] { "ppp",
"ppp", " s " }, 'p', "plankWood", 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapelessOreRecipe(new ItemStack(Item.stick, 4),
"plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(Item.bowlEmpty, 4),
new String[] { "p p", " p " }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.boat, new String[] { "p p",
"ppp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.pressurePlatePlanks,
new String[] { "pp" }, 'p', "plankWood");
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Block.pistonBase, new String[] {
"ppp", "cic", "crc" }, 'p', "plankWood", 'c',
Block.cobblestone, 'i', Item.ingotIron, 'r',
Item.redstone);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(Item.bed, new String[] { "ppp",
"ccc", "ppp" }, 'p', "plankWood", 'c', Block.cloth);
Extrabiomes.proxy.addRecipe(recipe);
recipe = new ShapedOreRecipe(new ItemStack(
Block.tripWireSource, 2),
new String[] { "i", "s", "p" }, 'p', "plankWood", 'i',
Item.ingotIron, 's', Item.stick);
Extrabiomes.proxy.addRecipe(recipe);
}
public static void init() {
addPlankVanillaRecipes();
addPlankCustomRecipes();
addLogRecipes();
}
}
|
diff --git a/src/main/java/org/crosswire/jsword/book/study/StrongsNumber.java b/src/main/java/org/crosswire/jsword/book/study/StrongsNumber.java
index ffcf7268..858b3905 100644
--- a/src/main/java/org/crosswire/jsword/book/study/StrongsNumber.java
+++ b/src/main/java/org/crosswire/jsword/book/study/StrongsNumber.java
@@ -1,284 +1,284 @@
/**
* Distribution License:
* JSword is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License, version 2.1 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.
*
* The License is available on the internet at:
* http://www.gnu.org/copyleft/lgpl.html
* or by writing to:
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Copyright: 2007
* The copyright to this program is held by it's authors.
*
* ID: $Id$
*/
package org.crosswire.jsword.book.study;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.crosswire.jsword.book.BookException;
/**
* A Strong's Number is either Greek or Hebrew, where the actual numbers for
* each start at 1. This class can parse Strong's Numbers that begin with G, g,
* H or h and are immediately followed by a number. That number can have leading
* 0's. It can be followed by an OSISref extension of !a, !b, which is ignored.
*
* <p>
* The canonical representation of the number is a G or H followed by 4 digits,
* with leading 0's as needed.
* </p>
*
* <p>
* Numbers that exist:
* <ul>
* <li>Hebrew: 1-8674
* <li>Greek: 1-5624 (but not 1418, 2717, 3203-3302, 4452)
* </ul>
* </p>
*
* @see gnu.lgpl.License for license details.<br>
* The copyright to this program is held by it's authors.
* @author DM Smith [dmsmith555 at yahoo dot com]
*/
public class StrongsNumber {
/**
* Build an immutable Strong's Number. Anything that does not match causes a
* BookException.
*
* @param input
* a string that needs to be parsed.
* @throws BookException
*/
public StrongsNumber(String input) {
valid = parse(input);
}
/**
* Build an immutable Strong's Number.
*
* @param language
* @param strongsNumber
*/
public StrongsNumber(char language, short strongsNumber) {
this(language, strongsNumber, null);
}
/**
* Build an immutable Strong's Number.
*
* @param language
* @param strongsNumber * @throws BookException
*/
public StrongsNumber(char language, short strongsNumber, String part) {
this.language = language;
this.strongsNumber = strongsNumber;
this.part = part;
valid = isValid();
}
/**
* Return the canonical form of a Strong's Number, without the part.
*
* @return the strongsNumber
*/
public String getStrongsNumber() {
StringBuilder buf = new StringBuilder(5);
buf.append(language);
buf.append(ZERO_PAD.format(strongsNumber));
return buf.toString();
}
/**
* Return the canonical form of a Strong's Number, with the part, if any
*
* @return the strongsNumber
*/
public String getFullStrongsNumber() {
StringBuilder buf = new StringBuilder(5);
buf.append(language);
buf.append(ZERO_PAD.format(strongsNumber));
if (part != null) {
buf.append(part);
}
return buf.toString();
}
/**
* @return true if the Strong's number is for Greek
*/
public boolean isGreek() {
return language == 'G';
}
/**
* @return true if the Strong's number is for Hebrew
*/
public boolean isHebrew() {
return language == 'H';
}
/**
* @return true if this Strong's number is identified by a sub part
*/
public boolean isPart() {
return part != null;
}
/**
* Validates the number portion of this StrongsNumber.
* <ul>
* <li>Hebrew Strong's numbers are in the range of: 1-8674.</li>
* <li>Greek Strong's numbers in the range of: 1-5624
* (but not 1418, 2717, 3203-3302, 4452).</li>
* </ul>
*
* @return true if the Strong's number is in range.
*/
public boolean isValid() {
if (!valid) {
return false;
}
// Dig deeper.
// The valid flag when set by parse indicates whether it had problems.
if (language == 'H'
&& strongsNumber >= 1
&& strongsNumber <= 8674)
{
return true;
}
if (language == 'G'
&& ((strongsNumber >= 1 && strongsNumber < 1418)
|| (strongsNumber > 1418 && strongsNumber < 2717)
|| (strongsNumber > 2717 && strongsNumber < 3203)
|| (strongsNumber > 3302 && strongsNumber <= 5624)))
{
return true;
}
valid = false;
return false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = 31 + language;
return 31 * result + strongsNumber;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final StrongsNumber other = (StrongsNumber) obj;
return language == other.language && strongsNumber == other.strongsNumber;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getStrongsNumber();
}
/**
* Do the actual parsing.
*
* @param input
* @return true when the input looks like a Strong's Number
*/
private boolean parse(String input) {
String text = input;
language = 'U';
strongsNumber = 9999;
part = "";
// Does it match
Matcher m = STRONGS_PATTERN.matcher(text);
if (!m.lookingAt()) {
return false;
}
String lang = m.group(1);
language = lang.charAt(0);
switch (language) {
case 'g':
language = 'G';
break;
case 'h':
language = 'H';
break;
default:
- return false;
+ // pass through
}
// Get the number after the G or H
try {
strongsNumber = Short.parseShort(m.group(2));
} catch(NumberFormatException e) {
strongsNumber = 0; // An invalid Strong's Number
return false;
}
// FYI: OSIS refers to what follows a ! as a grain
part = m.group(3);
return true;
}
/**
* Whether it is Greek (G) or Hebrew (H).
*/
private char language;
/**
* The Strong's Number.
*/
private short strongsNumber;
/**
* The part if any.
*/
private String part;
/*
* The value is valid.
*/
private boolean valid;
/**
* The pattern of an acceptable Strong's number.
*/
private static final Pattern STRONGS_PATTERN = Pattern.compile("([GgHh])([0-9]*)!?([A-Za-z]+)?");
private static final DecimalFormat ZERO_PAD = new DecimalFormat("0000");
}
| true | true | private boolean parse(String input) {
String text = input;
language = 'U';
strongsNumber = 9999;
part = "";
// Does it match
Matcher m = STRONGS_PATTERN.matcher(text);
if (!m.lookingAt()) {
return false;
}
String lang = m.group(1);
language = lang.charAt(0);
switch (language) {
case 'g':
language = 'G';
break;
case 'h':
language = 'H';
break;
default:
return false;
}
// Get the number after the G or H
try {
strongsNumber = Short.parseShort(m.group(2));
} catch(NumberFormatException e) {
strongsNumber = 0; // An invalid Strong's Number
return false;
}
// FYI: OSIS refers to what follows a ! as a grain
part = m.group(3);
return true;
}
| private boolean parse(String input) {
String text = input;
language = 'U';
strongsNumber = 9999;
part = "";
// Does it match
Matcher m = STRONGS_PATTERN.matcher(text);
if (!m.lookingAt()) {
return false;
}
String lang = m.group(1);
language = lang.charAt(0);
switch (language) {
case 'g':
language = 'G';
break;
case 'h':
language = 'H';
break;
default:
// pass through
}
// Get the number after the G or H
try {
strongsNumber = Short.parseShort(m.group(2));
} catch(NumberFormatException e) {
strongsNumber = 0; // An invalid Strong's Number
return false;
}
// FYI: OSIS refers to what follows a ! as a grain
part = m.group(3);
return true;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/util/Localization.java b/src/FE_SRC_COMMON/com/ForgeEssentials/util/Localization.java
index c38900151..145a4d634 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/util/Localization.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/util/Localization.java
@@ -1,197 +1,197 @@
package com.ForgeEssentials.util;
import cpw.mods.fml.common.registry.LanguageRegistry;
public class Localization
{
private String[] langFiles = { "en_US.xml", "en_UK.xml" };
/*
* Command stuff
*/
public static final String BUTCHERED = "message.butchered";
public static final String REMOVED = "message.removed";
public static final String KILLED = "message.killed";
public static final String SMITE_SELF = "message.smite.self";
public static final String SMITE_PLAYER = "message.smite.player";
public static final String SMITE_GROUND = "message.smite.ground";
public static final String BURN_SELF = "message.burn.self";
public static final String BURN_PLAYER = "message.burn.player";
public static final String HEALED = "message.healed";
public static final String SPAWNED = "message.spawned";
public static final String POTIONEFFECTNOTFOUND = "command.potion.effectnotfound";
/*
* Kit command & tickHandler
*/
public static final String KIT_LIST = "command.kit.list";
public static final String KIT_NOTEXISTS = "command.kit.noExists";
public static final String KIT_MADE = "command.kit.made";
public static final String KIT_ALREADYEXISTS = "command.kit.alreadyExists";
public static final String KIT_REMOVED = "command.kit.removed";
public static final String KIT_STILLINCOOLDOWN = "command.kit.stillInCooldown";
public static final String KIT_DONE = "command.kit.done";
/*
* Ego boosts
*/
public static final String CREDITS_ABRARSYED = "message.credits.AbrarSyed";
public static final String CREDITS_BOBAREDDINO = "message.credits.Bob_A_Red_Dino";
public static final String CREDITS_BSPKRS = "message.credits.bspkrs";
public static final String CREDITS_MYSTERIOUSAGES = "message.credits.MysteriousAges";
public static final String CREDITS_LUACS1998 = "message.credits.luacs1998";
public static final String CREDITS_DRIES007 = "message.credits.Dries007";
/*
* Errors & general messages
*/
public static final String ERROR_NOPLAYER = "message.error.noPlayerX";
public static final String ERROR_BADSYNTAX = "message.error.badsyntax";
public static final String ERROR_NAN = "message.error.nan";
public static final String ERROR_NODEATHPOINT = "message.error.nodeathpoint";
public static final String ERROR_NOHOME = "message.error.nohome";
public static final String ERROR_NOSELECTION = "message.error.noselection";
public static final String ERROR_TARGET = "message.error.target";
public static final String ERROR_NOPAGE = "message.error.nopage";
public static final String ERROR_PERMDENIED = "message.error.permdenied";
public static final String ERROR_NOITEMPLAYER = "message.error.noItemPlayer";
public static final String ERROR_NOITEMTARGET = "message.error.noItemTarget";
public static final String ERROR_NOMOB = "message.error.noMobX";
public static final String DONE = "message.done";
/*
* Permissions stuff
*/
public static final String ERROR_ZONE_NOZONE = "message.error.nozone";
public static final String ERROR_ZONE_YESZONE = "message.error.yeszone";
public static final String CONFIRM_ZONE_REMOVE = "message.confirm.zone.remove";
public static final String CONFIRM_ZONE_DEFINE = "message.confirm.zone.define";
public static final String CONFIRM_ZONE_REDEFINE = "message.confirm.zone.redefine";
public static final String CONFIRM_ZONE_SETPARENT = "message.confirm.zone.setparent";
public static final String ERROR_ILLEGAL_STATE = "message.error.illegalState";
public static final String ERROR_ILLEGAL_ENTITY = "message.error.illegalState";
/*
* WorldControl
*/
public static final String WC_SETCONFIRMBLOCKSCHANGED = "message.wc.setConfirmBlocksChanged";
public static final String WC_REPLACECONFIRMBLOCKSCHANGED = "message.wc.replaceConfirmBlocksChanged";
public static final String WC_THAWCONFIRM = "message.wc.thawConfirm";
public static final String WC_FREEZECONFIRM = "message.wc.freezeConfirm";
public static final String WC_SNOWCONFIRM = "message.wc.snowConfirm";
public static final String WC_TILLCONFIRM = "message.wc.tillConfirm";
public static final String WC_UNTILLCONFIRM = "message.wc.untillConfirm";
public static final String WC_INVALIDBLOCKID = "message.wc.invalidBlockId";
public static final String WC_BLOCKIDOUTOFRANGE = "message.wc.blockIdOutOfRange";
public static final String WC_NOUNDO = "message.wc.noUndo";
public static final String WC_NOREDO = "message.wc.noRedo";
/*
* TeleportCenter
*/
public static final String TC_COOLDOWN = "message.tc.cooldown";
public static final String TC_WARMUP = "message.tc.warmup";
public static final String TC_ABORTED = "message.tc.aborted";
public static final String TC_DONE = "message.tc.done";
/*
* WorldBorder
*/
public static final String WB_HITBORDER = "message.wb.hitborder";
public static final String WB_STATUS_HEADER = "message.wb.status.header";
public static final String WB_STATUS_BORDERSET = "message.wb.status.borderset";
public static final String WB_STATUS_BORDERNOTSET = "message.wb.status.bordernotset";
public static final String WB_LAGWARING = "message.wb.lagwarning";
public static final String WB_FILL_INFO = "message.wb.fill.info";
public static final String WB_FILL_CONFIRM = "message.wb.fill.confirm";
public static final String WB_FILL_ONLYONCE = "message.wb.fill.onlyonce";
public static final String WB_FILL_CONSOLENEEDSDIM = "message.wb.fill.consoleneedsdim";
public static final String WB_FILL_START = "message.wb.fill.start";
public static final String WB_FILL_STILLGOING = "message.wb.fill.stillgoing";
public static final String WB_FILL_DONE = "message.wb.fill.done";
public static final String WB_FILL_ETA = "message.wb.fill.eta";
public static final String WB_FILL_ABORTED = "message.wb.fill.aborted";
public static final String WB_FILL_FINISHED = "message.wb.fill.finished";
public static final String WB_SAVING_FAILED = "message.wb.saving.failed";
public static final String WB_TURBO_INFO = "message.wb.turbo.info";
public static final String WB_TURBO_CONFIRM = "message.wb.turbo.confirm";
public static final String WB_TURBO_NOTHINGTODO = "message.wb.turbo.nothingtodo";
public static final String WB_TURBO_ON = "message.wb.turbo.on";
public static final String WB_TURBO_OFF = "message.wb.turbo.off";
public static final String WB_SET = "message.wb.set";
public static final String UNIT_SECONDS = "unit.seconds";
/*
* Wallet
*/
public static final String WALLET = "message.wallet.walletname";
public static final String WALLET_CURRENCY_SINGULAR = "message.wallet.currencysingular";
public static final String WALLET_CURRENCY_PLURAL = "message.wallet.currencyplural";
public static final String WALLET_SET = "message.wallet.walletset";
public static final String WALLET_SET_SELF = "message.wallet.walletsetself";
public static final String WALLET_SET_TARGET = "message.wallet.walletsettarget";
public static final String WALLET_ADD = "message.wallet.walletadd";
public static final String WALLET_ADD_SELF = "message.wallet.walletaddself";
public static final String WALLET_ADD_TARGET = "message.wallet.walletaddtarget";
public static final String WALLET_REMOVE = "message.wallet.walletremove";
public static final String WALLET_REMOVE_SELF = "message.wallet.walletremoveself";
public static final String WALLET_REMOVE_TARGET = "message.wallet.walletremovetarget";
public static final String WALLET_GET = "message.wallet.walletget";
public static final String WALLET_GET_SELF = "message.wallet.walletgetself";
public static final String WALLET_GET_TARGET = "message.wallet.walletgettarget";
public static final String COMMAND_DESELECT = "message.wc.deselection";
public void load()
{
OutputHandler.SOP("Loading languages");
- String langDir = "com/ForgeEssentials/util/lang/";
+ String langDir = "/com/ForgeEssentials/util/lang/";
for (String langFile : langFiles)
try
{
- LanguageRegistry.instance().loadLocalization(ClassLoader.getSystemResource(langDir + langFile), langFile.substring(langFile.lastIndexOf('/') + 1, langFile.lastIndexOf('.')), true);
+ LanguageRegistry.instance().loadLocalization(langDir + langFile, langFile.substring(langFile.lastIndexOf('/') + 1, langFile.lastIndexOf('.')), true);
OutputHandler.SOP("Loaded language file " + langFile);
}
catch (Exception e)
{
OutputHandler.SOP("Could not load language file " + langFile);
}
}
public static String get(String key)
{
return LanguageRegistry.instance().getStringLocalization(key);
}
/**
* Fetches a localized format string, and inserts any provided arguments into it. A wrapper for all the "String.format(Localization.get(key), ...)" calls in commands.
*
* @param localizationKey
* Key to get the appropriate entry in the current localization file.
* @param args
* Arguments required to populate the localized string
* @return String String containing the localized, formatted string.
*/
public static String format(String localizationKey, Object... args)
{
return String.format(get(localizationKey), args);
}
}
| false | true | public void load()
{
OutputHandler.SOP("Loading languages");
String langDir = "com/ForgeEssentials/util/lang/";
for (String langFile : langFiles)
try
{
LanguageRegistry.instance().loadLocalization(ClassLoader.getSystemResource(langDir + langFile), langFile.substring(langFile.lastIndexOf('/') + 1, langFile.lastIndexOf('.')), true);
OutputHandler.SOP("Loaded language file " + langFile);
}
catch (Exception e)
{
OutputHandler.SOP("Could not load language file " + langFile);
}
}
| public void load()
{
OutputHandler.SOP("Loading languages");
String langDir = "/com/ForgeEssentials/util/lang/";
for (String langFile : langFiles)
try
{
LanguageRegistry.instance().loadLocalization(langDir + langFile, langFile.substring(langFile.lastIndexOf('/') + 1, langFile.lastIndexOf('.')), true);
OutputHandler.SOP("Loaded language file " + langFile);
}
catch (Exception e)
{
OutputHandler.SOP("Could not load language file " + langFile);
}
}
|
diff --git a/samigo-qti/src/java/org/sakaiproject/tool/assessment/qti/helper/item/ItemTypeExtractionStrategy.java b/samigo-qti/src/java/org/sakaiproject/tool/assessment/qti/helper/item/ItemTypeExtractionStrategy.java
index 14f4dd794..cc09412a3 100755
--- a/samigo-qti/src/java/org/sakaiproject/tool/assessment/qti/helper/item/ItemTypeExtractionStrategy.java
+++ b/samigo-qti/src/java/org/sakaiproject/tool/assessment/qti/helper/item/ItemTypeExtractionStrategy.java
@@ -1,334 +1,333 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.qti.helper.item;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.facade.ItemFacade;
import org.sakaiproject.tool.assessment.qti.constants.AuthoringConstantStrings;
/**
* Encapsulates the work of figuring out what type the item is.
* Right now, uses static methods, later, we might want to change, add to factory.
*
* We use the QTI qmd_itemtype in itemmetadata as the preferred way to ascertain type.
* We fall back on title and then item structure, also attempring keyword matching.
* Note, this may be deprecated in favor of a vocabulary based approach.
* Need to investigate. Anyway, this is the form that is backwardly compatible.
*
* @author Ed Smiley
*/
public class ItemTypeExtractionStrategy
{
private static Log log = LogFactory.getLog(ItemTypeExtractionStrategy.class);
private static final Long DEFAULT_TYPE = Long.valueOf(2);
/**
* Obtain Long item type id from strings extracted from item.
* @param title the item title
* @param itemIntrospect hte structure based guess from XSL
* @param qmdItemtype hte item type meta information
* @return Long item type id
*/
public static Long calculate(String title, String itemIntrospect, String qmdItemtype)
{
String itemType = obtainTypeString(title, itemIntrospect, qmdItemtype);
Long typeId = getType(itemType);
return typeId;
}
public static Long calculate(Map itemMap)
{
String itemType = null;
if (itemMap.get("type") != null && !itemMap.get("type").equals("")) {
if (itemMap.get("type").equals("FIB")) {
itemType = AuthoringConstantStrings.FIB;
}
else if (itemMap.get("type").equals("Matching"))
itemType = AuthoringConstantStrings.MATCHING;
}
else if (itemMap.get("itemRcardinality") != null && !itemMap.get("itemRcardinality").equals("")) {
String itemRcardinality = (String) itemMap.get("itemRcardinality");
if ("Single".equalsIgnoreCase(itemRcardinality)) {
List answerList = (List) itemMap.get("itemAnswer");
if (answerList.size() == 2) {
String firstAnswer = ((String) answerList.get(0)).split(":::")[1];
String secondAnswer = ((String) answerList.get(1)).split(":::")[1];
if ((firstAnswer.equalsIgnoreCase("true") && secondAnswer.equalsIgnoreCase("false"))
|| (firstAnswer.equalsIgnoreCase("false") && secondAnswer.equalsIgnoreCase("true"))) {
itemType = AuthoringConstantStrings.TF;
}
else {
itemType = AuthoringConstantStrings.MCSC;
}
}
else {
itemType = AuthoringConstantStrings.MCSC;
}
}
else {
itemType = AuthoringConstantStrings.MCMC;
}
}
else {
itemType = AuthoringConstantStrings.ESSAY;
}
Long typeId = getType(itemType);
return typeId;
}
/**
* simple unit test
*
* @param args not used
*/
public static void main(String[] args)
{
// ItemFacade item = new ItemFacade();
String title;
String intro;
String qmd;
String[] typeArray = AuthoringConstantStrings.itemTypes;
for (int i = 0; i < typeArray.length; i++)
{
qmd = typeArray[i];
title = "title";
intro = "introspect";
Long typeId = calculate(title, intro, qmd);
}
for (int i = 0; i < typeArray.length; i++)
{
title = typeArray[i];
intro = "introspect";
qmd = "qmd";
Long typeId = calculate(title, intro, qmd);
}
for (int i = 0; i < typeArray.length; i++)
{
title = "title";
intro = typeArray[i];
qmd = "qmd";
Long typeId = calculate(title, intro, qmd);
}
}
/**
* Figure out the best string describing type to use.
* @param titleItemType the item's title
* @param itemIntrospectItemType best guess based on structure
* @param qmdItemType the type declared in metadata, if any
* @return the string describing the item.
*/
private static String obtainTypeString( String titleItemType,
String itemIntrospectItemType,
String qmdItemType)
{
log.debug("qmdItemType: " + qmdItemType);
log.debug("titleItemType: " + titleItemType);
log.debug("itemIntrospectItemType: " + itemIntrospectItemType);
// if we can't find any other approach
String itemType = itemIntrospectItemType;
// start with item title
if (titleItemType != null)
{
if (isExactType(titleItemType)) itemType = titleItemType;
titleItemType = guessType(titleItemType);
if (titleItemType != null) itemType = titleItemType;
}
// next try to figure out from qmd_itemtype metadata
if (qmdItemType != null)
{
if (isExactType(qmdItemType)) itemType = qmdItemType;
qmdItemType = guessType(qmdItemType);
if (qmdItemType != null) itemType = qmdItemType;
}
log.debug("returning itemType: " + itemType);
return itemType;
}
/**
* Try to infer the type of imported question from string, such as title.
* @param candidate string to guess type from
* @return AuthoringConstantStrings.{type}
*/
private static String guessType(String candidate)
{
String itemType;
String lower = candidate.toLowerCase();
itemType = matchGuess(lower);
return itemType;
}
/**
* helper method for guessType() with its type guess strategy.
* @param toGuess string to test
* @return the guessed canonical type
*/
private static String matchGuess(String toGuess)
{
// not sure how well this works for i18n.
String itemType = null;
if (toGuess.indexOf("multiple") != -1 &&
toGuess.indexOf("response") != -1)
{
itemType = AuthoringConstantStrings.MCMC;
}
else if (toGuess.indexOf("true") != -1 ||
toGuess.indexOf("tf") != -1)
{
itemType = AuthoringConstantStrings.TF;
}
else if (toGuess.indexOf("matrix") != -1)
{
itemType = AuthoringConstantStrings.MATRIX;
}
else if (toGuess.indexOf("survey") != -1)
{
itemType = AuthoringConstantStrings.SURVEY;
}
else if (toGuess.indexOf("single") != -1 &&
toGuess.indexOf("correct") != -1)
{
if (toGuess.indexOf("selection") != -1) {
itemType = AuthoringConstantStrings.MCMCSS;
}
else {
itemType = AuthoringConstantStrings.MCSC;
}
}
else if (toGuess.indexOf("multiple") != -1 &&
toGuess.indexOf("correct") != -1)
{
itemType = AuthoringConstantStrings.MCMC;
}
else if (toGuess.indexOf("audio") != -1 ||
toGuess.indexOf("recording") != -1)
{
itemType = AuthoringConstantStrings.AUDIO;
}
else if (toGuess.indexOf("file") != -1 ||
toGuess.indexOf("upload") != -1)
{
itemType = AuthoringConstantStrings.FILE;
}
else if (toGuess.indexOf("match") != -1)
{
itemType = AuthoringConstantStrings.MATCHING;
}
else if (toGuess.indexOf("fib") != -1 ||
toGuess.indexOf("fill") != -1 ||
toGuess.indexOf("f.i.b.") != -1
)
{
itemType = AuthoringConstantStrings.FIB;
}
// place holder for numerical responses questions
else if (toGuess.indexOf("numerical") != -1 ||
toGuess.indexOf("calculate") != -1 ||
toGuess.indexOf("math") != -1
)
{
itemType = AuthoringConstantStrings.FIN;
}
// CALCULATED_QUESTION
else if (toGuess.indexOf("calcq") != -1 ||
- toGuess.indexOf("calculated_question") != -1 ||
toGuess.indexOf("c.q.") != -1 ||
toGuess.indexOf("cq") != -1
)
{
itemType = AuthoringConstantStrings.CALCQ;
}
else if (toGuess.indexOf("essay") != -1 ||
toGuess.indexOf("short") != -1)
{
itemType = AuthoringConstantStrings.ESSAY;
}
return itemType;
}
/**
*
* @param typeString get type string
* @return Long item type
*/
private static Long getType(String typeString)
{
Long type = getValidType(typeString);
if (type==null)
{
log.warn("Unable to set item type: '" + typeString + "'.");
log.warn("guessing item type: '" + DEFAULT_TYPE + "'.");
type = DEFAULT_TYPE;
}
return type;
}
/**
* Is this one of our exact type strings, or not?
* Ignores case and extra space.
* @param typeString the string
* @return true if it is
*/
private static boolean isExactType(String typeString)
{
return getValidType(typeString)!=null;
}
/**
* Get valid type as Long matching typeString
* Ignores case and extra space.
* @param typeString the candidate string
* @return valid type as Long matching typeString, or null, if no match.
*/
private static Long getValidType(String typeString)
{
Long type = null;
String[] typeArray = AuthoringConstantStrings.itemTypes;
for (int i = 0; i < typeArray.length; i++)
{
if (typeString.trim().equalsIgnoreCase(typeArray[i]))
{
type = Long.valueOf(i);
break;
}
}
return type;
}
}
| true | true | private static String matchGuess(String toGuess)
{
// not sure how well this works for i18n.
String itemType = null;
if (toGuess.indexOf("multiple") != -1 &&
toGuess.indexOf("response") != -1)
{
itemType = AuthoringConstantStrings.MCMC;
}
else if (toGuess.indexOf("true") != -1 ||
toGuess.indexOf("tf") != -1)
{
itemType = AuthoringConstantStrings.TF;
}
else if (toGuess.indexOf("matrix") != -1)
{
itemType = AuthoringConstantStrings.MATRIX;
}
else if (toGuess.indexOf("survey") != -1)
{
itemType = AuthoringConstantStrings.SURVEY;
}
else if (toGuess.indexOf("single") != -1 &&
toGuess.indexOf("correct") != -1)
{
if (toGuess.indexOf("selection") != -1) {
itemType = AuthoringConstantStrings.MCMCSS;
}
else {
itemType = AuthoringConstantStrings.MCSC;
}
}
else if (toGuess.indexOf("multiple") != -1 &&
toGuess.indexOf("correct") != -1)
{
itemType = AuthoringConstantStrings.MCMC;
}
else if (toGuess.indexOf("audio") != -1 ||
toGuess.indexOf("recording") != -1)
{
itemType = AuthoringConstantStrings.AUDIO;
}
else if (toGuess.indexOf("file") != -1 ||
toGuess.indexOf("upload") != -1)
{
itemType = AuthoringConstantStrings.FILE;
}
else if (toGuess.indexOf("match") != -1)
{
itemType = AuthoringConstantStrings.MATCHING;
}
else if (toGuess.indexOf("fib") != -1 ||
toGuess.indexOf("fill") != -1 ||
toGuess.indexOf("f.i.b.") != -1
)
{
itemType = AuthoringConstantStrings.FIB;
}
// place holder for numerical responses questions
else if (toGuess.indexOf("numerical") != -1 ||
toGuess.indexOf("calculate") != -1 ||
toGuess.indexOf("math") != -1
)
{
itemType = AuthoringConstantStrings.FIN;
}
// CALCULATED_QUESTION
else if (toGuess.indexOf("calcq") != -1 ||
toGuess.indexOf("calculated_question") != -1 ||
toGuess.indexOf("c.q.") != -1 ||
toGuess.indexOf("cq") != -1
)
{
itemType = AuthoringConstantStrings.CALCQ;
}
else if (toGuess.indexOf("essay") != -1 ||
toGuess.indexOf("short") != -1)
{
itemType = AuthoringConstantStrings.ESSAY;
}
return itemType;
}
| private static String matchGuess(String toGuess)
{
// not sure how well this works for i18n.
String itemType = null;
if (toGuess.indexOf("multiple") != -1 &&
toGuess.indexOf("response") != -1)
{
itemType = AuthoringConstantStrings.MCMC;
}
else if (toGuess.indexOf("true") != -1 ||
toGuess.indexOf("tf") != -1)
{
itemType = AuthoringConstantStrings.TF;
}
else if (toGuess.indexOf("matrix") != -1)
{
itemType = AuthoringConstantStrings.MATRIX;
}
else if (toGuess.indexOf("survey") != -1)
{
itemType = AuthoringConstantStrings.SURVEY;
}
else if (toGuess.indexOf("single") != -1 &&
toGuess.indexOf("correct") != -1)
{
if (toGuess.indexOf("selection") != -1) {
itemType = AuthoringConstantStrings.MCMCSS;
}
else {
itemType = AuthoringConstantStrings.MCSC;
}
}
else if (toGuess.indexOf("multiple") != -1 &&
toGuess.indexOf("correct") != -1)
{
itemType = AuthoringConstantStrings.MCMC;
}
else if (toGuess.indexOf("audio") != -1 ||
toGuess.indexOf("recording") != -1)
{
itemType = AuthoringConstantStrings.AUDIO;
}
else if (toGuess.indexOf("file") != -1 ||
toGuess.indexOf("upload") != -1)
{
itemType = AuthoringConstantStrings.FILE;
}
else if (toGuess.indexOf("match") != -1)
{
itemType = AuthoringConstantStrings.MATCHING;
}
else if (toGuess.indexOf("fib") != -1 ||
toGuess.indexOf("fill") != -1 ||
toGuess.indexOf("f.i.b.") != -1
)
{
itemType = AuthoringConstantStrings.FIB;
}
// place holder for numerical responses questions
else if (toGuess.indexOf("numerical") != -1 ||
toGuess.indexOf("calculate") != -1 ||
toGuess.indexOf("math") != -1
)
{
itemType = AuthoringConstantStrings.FIN;
}
// CALCULATED_QUESTION
else if (toGuess.indexOf("calcq") != -1 ||
toGuess.indexOf("c.q.") != -1 ||
toGuess.indexOf("cq") != -1
)
{
itemType = AuthoringConstantStrings.CALCQ;
}
else if (toGuess.indexOf("essay") != -1 ||
toGuess.indexOf("short") != -1)
{
itemType = AuthoringConstantStrings.ESSAY;
}
return itemType;
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
index c8643eca..8fe0e69a 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
@@ -1,440 +1,441 @@
/*
* Copyright 2010-2011 The myBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring;
import java.io.IOException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* {@code FactoryBean} that creates an MyBatis {@code SqlSessionFactory}.
* This is the usual way to set up a shared MyBatis {@code SqlSessionFactory} in a Spring application context;
* the SqlSessionFactory can then be passed to MyBatis-based DAOs via dependency injection.
*
* Either {@code DataSourceTransactionManager} or {@code JtaTransactionManager} can be used for transaction
* demarcation in combination with a {@code SqlSessionFactory}. JTA should be used for transactions
* which span multiple databases or when container managed transactions (CMT) are being used.
*
* @see #setConfigLocation
* @see #setDataSource
* @version $Id$
*/
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
private final Log logger = LogFactory.getLog(getClass());
private Resource configLocation;
private Resource[] mapperLocations;
private DataSource dataSource;
private TransactionFactory transactionFactory;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private boolean failFast;
private Interceptor[] plugins;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
/**
* Mybatis plugin list.
*
* @since 1.0.1
*
* @param plugins list of plugins
*
*/
public void setPlugins(Interceptor[] plugins) {
this.plugins = plugins;
}
/**
* Packages to search for type aliases.
*
* @since 1.0.1
*
* @param typeAliasesPackage package to scan for domain objects
*
*/
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}
/**
* Packages to search for type handlers.
*
* @since 1.0.1
*
* @param typeHandlersPackage package to scan for type handlers
*
*/
public void setTypeHandlersPackage(String typeHandlersPackage) {
this.typeHandlersPackage = typeHandlersPackage;
}
/**
* Set type handlers. They must be annotated with {@code MappedTypes} and optionally with {@code MappedJdbcTypes}
*
* @since 1.0.1
*
* @param typeHandlers Type handler list
*/
public void setTypeHandlers(TypeHandler<?>[] typeHandlers) {
this.typeHandlers = typeHandlers;
}
/**
* List of type aliases to register. They can be annotated with {@code Alias}
*
* @since 1.0.1
*
* @param typeAliases Type aliases list
*/
public void setTypeAliases(Class<?>[] typeAliases) {
this.typeAliases = typeAliases;
}
/**
* If true, a final check is done on Configuration to assure that all mapped
* statements are fully loaded and there is no one still pending to resolve
* includes. Defaults to false.
*
* @since 1.0.1
*
* @param failFast enable failFast
*/
public void setFailFast(boolean failFast) {
this.failFast = failFast;
}
/**
* Set the location of the MyBatis {@code SqlSessionFactory} config file. A typical value is
* "WEB-INF/mybatis-configuration.xml".
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set locations of MyBatis mapper files that are going to be merged into the {@code SqlSessionFactory}
* configuration at runtime.
*
* This is an alternative to specifying "<sqlmapper>" entries in an MyBatis config file.
* This property being based on Spring's resource abstraction also allows for specifying
* resource patterns here: e.g. "classpath*:sqlmap/*-mapper.xml".
*/
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
/**
* Set optional properties to be passed into the SqlSession configuration, as alternative to a
* {@code <properties>} tag in the configuration xml file. This will be used to
* resolve placeholders in the config file.
*/
public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
this.configurationProperties = sqlSessionFactoryProperties;
}
/**
* Set the JDBC {@code DataSource} that this instance should manage transactions for. The {@code DataSource}
* should match the one used by the {@code SqlSessionFactory}: for example, you could specify the same
* JNDI DataSource for both.
*
* A transactional JDBC {@code Connection} for this {@code DataSource} will be provided to application code
* accessing this {@code DataSource} directly via {@code DataSourceUtils} or {@code DataSourceTransactionManager}.
*
* The {@code DataSource} specified here should be the target {@code DataSource} to manage transactions for, not
* a {@code TransactionAwareDataSourceProxy}. Only data access code may work with
* {@code TransactionAwareDataSourceProxy}, while the transaction manager needs to work on the
* underlying target {@code DataSource}. If there's nevertheless a {@code TransactionAwareDataSourceProxy}
* passed in, it will be unwrapped to extract its target {@code DataSource}.
*
*/
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
// If we got a TransactionAwareDataSourceProxy, we need to perform
// transactions for its underlying target DataSource, else data
// access code won't see properly exposed transactions (i.e.
// transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
/**
* Sets the {@code SqlSessionFactoryBuilder} to use when creating the {@code SqlSessionFactory}.
*
* This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By
* default, {@code SqlSessionFactoryBuilder} creates {@code DefaultSqlSessionFactory} instances.
*
*/
public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}
/**
* Set the MyBatis TransactionFactory to use. Default is {@code SpringManagedTransactionFactory}
*
* The default {@code SpringManagedTransactionFactory} should be appropriate for all cases:
* be it Spring transaction management, EJB CMT or plain JTA. If there is no active transaction,
* SqlSession operations will execute SQL statements non-transactionally.
*
* <b>It is strongly recommended to use the default {@code TransactionFactory}.</b> If not used, any
* attempt at getting an SqlSession through Spring's MyBatis framework will throw an exception if
* a transaction is active.
*
* @see SpringManagedTransactionFactory
* @param transactionFactory the MyBatis TransactionFactory
*/
public void setTransactionFactory(TransactionFactory transactionFactory) {
this.transactionFactory = transactionFactory;
}
/**
* <b>NOTE:</b> This class <em>overrides</em> any {@code Environment} you have set in the MyBatis
* config file. This is used only as a placeholder name. The default value is
* {@code SqlSessionFactoryBean.class.getSimpleName()}.
*
* @param environment the environment name
*/
public void setEnvironment(String environment) {
this.environment = environment;
}
/**
* {@inheritDoc}
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSource, "Property 'dataSource' is required");
Assert.notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
this.sqlSessionFactory = buildSqlSessionFactory();
}
/**
* Build a {@code SqlSessionFactory} instance.
*
* The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
* {@code SqlSessionFactory} instance based on an Reader.
*
* @return SqlSessionFactory
* @throws IOException if loading the config file failed
*/
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
+ configuration.setVariables(this.configurationProperties);
}
if (StringUtils.hasLength(this.typeAliasesPackage)) {
String[] typeAliasPackageArray = StringUtils.tokenizeToStringArray(this.typeAliasesPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeAliasPackageArray) {
configuration.getTypeAliasRegistry().registerAliases(packageToScan);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Scanned package: '" + packageToScan + "' for aliases");
}
}
}
if (!ObjectUtils.isEmpty(this.typeAliases)) {
for (Class<?> typeAlias : this.typeAliases) {
configuration.getTypeAliasRegistry().registerAlias(typeAlias);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered type alias: '" + typeAlias + "'");
}
}
}
if (!ObjectUtils.isEmpty(this.plugins)) {
for (Interceptor plugin : this.plugins) {
configuration.addInterceptor(plugin);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered plugin: '" + plugin + "'");
}
}
}
if (StringUtils.hasLength(this.typeHandlersPackage)) {
String[] typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeHandlersPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeHandlersPackageArray ) {
configuration.getTypeHandlerRegistry().register(packageToScan);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
}
}
}
if (!ObjectUtils.isEmpty(this.typeHandlers)) {
for (TypeHandler<?> typeHandler : this.typeHandlers) {
configuration.getTypeHandlerRegistry().register(typeHandler);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered type handler: '" + typeHandler + "'");
}
}
}
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Parsed configuration file: '" + this.configLocation + "'");
}
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
if (this.transactionFactory == null) {
this.transactionFactory = new SpringManagedTransactionFactory(this.dataSource);
}
Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
// this block is a workaround for issue http://code.google.com/p/mybatis/issues/detail?id=235
// when running MyBatis 3.0.4. But not always works.
// Not needed in 3.0.5 and above.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ((ClassPathResource) mapperLocation).getPath();
} else {
path = mapperLocation.toString();
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
configuration, path, configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
/**
* {@inheritDoc}
*/
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
/**
* {@inheritDoc}
*/
public Class<? extends SqlSessionFactory> getObjectType() {
return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
}
/**
* {@inheritDoc}
*/
public boolean isSingleton() {
return true;
}
/**
* {@inheritDoc}
*/
public void onApplicationEvent(ApplicationEvent event) {
if (failFast && event instanceof ContextRefreshedEvent) {
// fail-fast -> check all statements are completed
this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
}
}
}
| true | true | protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
if (StringUtils.hasLength(this.typeAliasesPackage)) {
String[] typeAliasPackageArray = StringUtils.tokenizeToStringArray(this.typeAliasesPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeAliasPackageArray) {
configuration.getTypeAliasRegistry().registerAliases(packageToScan);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Scanned package: '" + packageToScan + "' for aliases");
}
}
}
if (!ObjectUtils.isEmpty(this.typeAliases)) {
for (Class<?> typeAlias : this.typeAliases) {
configuration.getTypeAliasRegistry().registerAlias(typeAlias);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered type alias: '" + typeAlias + "'");
}
}
}
if (!ObjectUtils.isEmpty(this.plugins)) {
for (Interceptor plugin : this.plugins) {
configuration.addInterceptor(plugin);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered plugin: '" + plugin + "'");
}
}
}
if (StringUtils.hasLength(this.typeHandlersPackage)) {
String[] typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeHandlersPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeHandlersPackageArray ) {
configuration.getTypeHandlerRegistry().register(packageToScan);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
}
}
}
if (!ObjectUtils.isEmpty(this.typeHandlers)) {
for (TypeHandler<?> typeHandler : this.typeHandlers) {
configuration.getTypeHandlerRegistry().register(typeHandler);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered type handler: '" + typeHandler + "'");
}
}
}
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Parsed configuration file: '" + this.configLocation + "'");
}
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
if (this.transactionFactory == null) {
this.transactionFactory = new SpringManagedTransactionFactory(this.dataSource);
}
Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
// this block is a workaround for issue http://code.google.com/p/mybatis/issues/detail?id=235
// when running MyBatis 3.0.4. But not always works.
// Not needed in 3.0.5 and above.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ((ClassPathResource) mapperLocation).getPath();
} else {
path = mapperLocation.toString();
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
configuration, path, configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
| protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
configuration.setVariables(this.configurationProperties);
}
if (StringUtils.hasLength(this.typeAliasesPackage)) {
String[] typeAliasPackageArray = StringUtils.tokenizeToStringArray(this.typeAliasesPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeAliasPackageArray) {
configuration.getTypeAliasRegistry().registerAliases(packageToScan);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Scanned package: '" + packageToScan + "' for aliases");
}
}
}
if (!ObjectUtils.isEmpty(this.typeAliases)) {
for (Class<?> typeAlias : this.typeAliases) {
configuration.getTypeAliasRegistry().registerAlias(typeAlias);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered type alias: '" + typeAlias + "'");
}
}
}
if (!ObjectUtils.isEmpty(this.plugins)) {
for (Interceptor plugin : this.plugins) {
configuration.addInterceptor(plugin);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered plugin: '" + plugin + "'");
}
}
}
if (StringUtils.hasLength(this.typeHandlersPackage)) {
String[] typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeHandlersPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeHandlersPackageArray ) {
configuration.getTypeHandlerRegistry().register(packageToScan);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
}
}
}
if (!ObjectUtils.isEmpty(this.typeHandlers)) {
for (TypeHandler<?> typeHandler : this.typeHandlers) {
configuration.getTypeHandlerRegistry().register(typeHandler);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Registered type handler: '" + typeHandler + "'");
}
}
}
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Parsed configuration file: '" + this.configLocation + "'");
}
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
if (this.transactionFactory == null) {
this.transactionFactory = new SpringManagedTransactionFactory(this.dataSource);
}
Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
// this block is a workaround for issue http://code.google.com/p/mybatis/issues/detail?id=235
// when running MyBatis 3.0.4. But not always works.
// Not needed in 3.0.5 and above.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ((ClassPathResource) mapperLocation).getPath();
} else {
path = mapperLocation.toString();
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
configuration, path, configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
|
diff --git a/src/tools/hb/HappensBeforeTool.java b/src/tools/hb/HappensBeforeTool.java
index bcffb7e..411c085 100644
--- a/src/tools/hb/HappensBeforeTool.java
+++ b/src/tools/hb/HappensBeforeTool.java
@@ -1,400 +1,400 @@
/******************************************************************************
Copyright (c) 2010, Cormac Flanagan (University of California, Santa Cruz)
and Stephen Freund (Williams College)
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 names of the University of California, Santa Cruz
and Williams College 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
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 tools.hb;
import java.util.Vector;
import rr.annotations.Abbrev;
import rr.barrier.BarrierEvent;
import rr.barrier.BarrierListener;
import rr.barrier.BarrierMonitor;
import rr.error.ErrorMessage;
import rr.error.ErrorMessages;
import rr.event.AccessEvent;
import rr.event.AcquireEvent;
import rr.event.ArrayAccessEvent;
import rr.event.FieldAccessEvent;
import rr.event.InterruptEvent;
import rr.event.InterruptedEvent;
import rr.event.JoinEvent;
import rr.event.NewThreadEvent;
import rr.event.NotifyEvent;
import rr.event.ReleaseEvent;
import rr.event.StartEvent;
import rr.event.VolatileAccessEvent;
import rr.event.WaitEvent;
import rr.event.AccessEvent.Kind;
import rr.meta.ArrayAccessInfo;
import rr.meta.FieldInfo;
import rr.state.ShadowLock;
import rr.state.ShadowThread;
import rr.state.ShadowVar;
import rr.tool.Tool;
import tools.util.CV;
import tools.util.CVPair;
import acme.util.Assert;
import acme.util.Util;
import acme.util.decorations.Decoration;
import acme.util.decorations.DecorationFactory;
import acme.util.decorations.DefaultValue;
import acme.util.decorations.NullDefault;
import acme.util.option.CommandLine;
/**
* VC-based HappensBefore Race Detector.
*
*/
@Abbrev("HB")
public final class HappensBeforeTool extends Tool implements BarrierListener<HBBarrierState> {
/* Reporters for field/array errors */
public final ErrorMessage<FieldInfo> errors = ErrorMessages.makeFieldErrorMessage("HappensBefore");
public final ErrorMessage<ArrayAccessInfo> arrayErrors = ErrorMessages.makeArrayErrorMessage("HappensBefore");
public HappensBeforeTool(String name, Tool next, CommandLine commandLine) {
super(name, next, commandLine);
/*
* Create a barrier monitor that will notify this tool when barrier ops happen.
* The get(k) method returns the initial state to associate with each barrier
* when the barrier is created.
*/
new BarrierMonitor<HBBarrierState>(this, new DefaultValue<Object,HBBarrierState>() {
public HBBarrierState get(Object k) {
return new HBBarrierState(ShadowLock.get(k));
}
});
}
/*
* Special methods that tells the instrumentor to create a field in ShadowThread
* named "hb" of type "CV". This is for performance only -- you could do the same
* thing using a decoration on ThreadStates.
*/
static CV ts_get_cv_hb(ShadowThread ts) { Assert.panic("Bad"); return null; }
static void ts_set_cv_hb(ShadowThread ts, CV cv) { Assert.panic("Bad"); }
private CV get(ShadowThread td) {
return ts_get_cv_hb(td);
}
/*
* Attach a VectorClock to each object used as a lock.
*/
Decoration<ShadowLock,CV> shadowLock = ShadowLock.decoratorFactory.make("HB:lock", DecorationFactory.Type.MULTIPLE,
new DefaultValue<ShadowLock,CV>() { public CV get(ShadowLock ld) { return new CV(1); }});
private CV get(ShadowLock td) {
return shadowLock.get(td);
}
@Override
public void create(NewThreadEvent e) {
ShadowThread td = e.getThread();
CV cv = new CV(td.getTid() + 1);
ts_set_cv_hb(td, cv);
super.create(e);
}
/*
* increment the time of the current thread.
*/
public void tick(ShadowThread currentThread) {
get(currentThread).inc(currentThread.getTid());
}
@Override
public void acquire(AcquireEvent ae) {
final ShadowThread currentThread = ae.getThread();
final ShadowLock shadowLock = ae.getLock();
tick(currentThread);
synchronized(shadowLock) {
get(currentThread).max(get(shadowLock));
}
super.acquire(ae);
}
@Override
public void release(ReleaseEvent re) {
final ShadowThread currentThread = re.getThread();
final ShadowLock shadowLock = re.getLock();
synchronized(shadowLock) {
get(shadowLock).max(get(currentThread));
}
tick(currentThread);
super.release(re);
}
@Override
public void volatileAccess(VolatileAccessEvent fae) {
ShadowVar g = fae.getOriginalShadow();
final ShadowThread currentThread = fae.getThread();
if (g instanceof CVPair) {
final ShadowVar orig = fae.getOriginalShadow();
final ShadowThread td = fae.getThread();
CVPair p = (CVPair)g;
final CV cv = ts_get_cv_hb(td);
if (fae.isWrite()) {
p.rd.max(get(currentThread));
tick(td);
} else {
synchronized(p.rd) {
get(currentThread).max(p.rd);
}
}
}
super.volatileAccess(fae);
}
// FIXME: syncrhonize-me because we have destructive races on clock-vectors, and
// we have no "right-mover" argument
@Override
public void access(AccessEvent fae) {
ShadowVar g = fae.getOriginalShadow();
final ShadowThread currentThread = fae.getThread();
if (g instanceof CVPair) {
boolean passAlong = false;
CVPair p = (CVPair)g;
boolean isWrite = fae.isWrite();
CV cv = get(currentThread);
// Util.log("p=" + p);
// Util.log("t=" + cv);
final int tid = currentThread.getTid();
if (isWrite) {
// check after prev read
passAlong |= checkAfter(p.rd, "read", currentThread, "write", fae, true, p);
// check after prev write
passAlong |= checkAfter(p.wr, "write", currentThread, "write", fae, true, p);
p.wr.set(tid, cv.get(tid));
} else {
// check after prev write
passAlong |= checkAfter(p.wr, "write", currentThread, "read", fae, true, p);
p.rd.set(tid, cv.get(tid));
// p.rd.max(cv);
}
if (passAlong) {
advance(fae);
}
// Util.log("p=" + p);
// Util.log("t=" + cv);
} else {
super.access(fae);
}
}
private boolean checkAfter(CV prev, String prevOp, ShadowThread currentThread, String curOp,
AccessEvent fad, boolean isWrite, ShadowVar p) {
CV cv = get(currentThread);
if(prev.anyGt(cv)) {
int start=0;
while(true) {
start=prev.nextGt(cv, start);
if (start==-1) {
break;
}
Object target = fad.getTarget();
if (fad.getKind() == Kind.ARRAY) {
ArrayAccessEvent aae = (ArrayAccessEvent)fad;
final ArrayAccessInfo arrayAccessInfo = aae.getInfo();
arrayErrors.error(currentThread, arrayAccessInfo,
"Guard State", prev,
- "Array", Util.objectToIdentityString(target) + "[]", "" + aae.getIndex(),
+ "Array", Util.objectToIdentityString(target) + "[" + aae.getIndex() +"]",
"Locks", currentThread.getLocksHeld(),
"Prev Op", prevOp+"-by-thread-"+start,
"Prev Op CV", prev,
"Cur Op", curOp,
"Cur Op CV", cv,
"Stack", ShadowThread.stackDumpForErrorMessage(currentThread));
start++;
return !arrayErrors.stillLooking(arrayAccessInfo);
} else {
FieldInfo fd = ((FieldAccessEvent)fad).getInfo().getField();
errors.error(currentThread, fd,
- "Guard State", prev,
- "Class", target==null?fd.getOwner():target.getClass(),
+ "Guard State", prev,
+ "Class", target==null?fd.getOwner():target.getClass(),
"Field", Util.objectToIdentityString(target) + "." + fd,
"Locks", currentThread.getLocksHeld(),
"Prev Op", prevOp+"-by-thread-"+start,
"Prev Op CV", prev,
"Cur Op", curOp,
"Cur Op CV", cv,
"Stack", ShadowThread.stackDumpForErrorMessage(currentThread));
start++;
return !errors.stillLooking(fd);
}
}
return false;
} else {
return false;
}
}
@Override
public ShadowVar makeShadowVar(AccessEvent fae) {
return new CVPair();
}
@Override
public void preStart(final StartEvent se) {
final ShadowThread td = se.getThread();
final ShadowThread forked = se.getNewThread();
ts_set_cv_hb(forked, new CV(ts_get_cv_hb(td)));
this.tick(forked);
this.tick(td);
super.preStart(se);
}
@Override
public void preNotify(NotifyEvent we) {
tick(we.getThread());
synchronized(we.getLock()) {
get(we.getLock()).max(get(we.getThread()));
}
tick(we.getThread());
super.preNotify(we);
}
@Override
public void preWait(WaitEvent we) {
tick(we.getThread());
synchronized(we.getLock()) {
get(we.getLock()).max(get(we.getThread()));
}
tick(we.getThread());
super.preWait(we);
}
@Override
public void postWait(WaitEvent we) {
tick(we.getThread());
synchronized(we.getLock()) {
get(we.getThread()).max(get(we.getLock()));
}
tick(we.getThread());
super.postWait(we);
}
@Override
public void postJoin(JoinEvent je) {
final ShadowThread currentThread = je.getThread();
final ShadowThread joinedThread = je.getJoiningThread();
tick(currentThread);
get(currentThread).max(get(joinedThread));
tick(currentThread);
super.postJoin(je);
}
private final Decoration<ShadowThread, CV> cvForExit =
ShadowThread.makeDecoration("HB:sbarrier", DecorationFactory.Type.MULTIPLE, new NullDefault<ShadowThread, CV>());
public void postDoBarrier(BarrierEvent<HBBarrierState> be) {
ShadowThread currentThread = be.getThread();
CV old = cvForExit.get(currentThread);
be.getBarrier().reset(old);
get(currentThread).max(old);
this.tick(currentThread);
}
public void preDoBarrier(BarrierEvent<HBBarrierState> be) {
ShadowThread td = be.getThread();
CV entering = be.getBarrier().entering;
entering.max(get(td));
cvForExit.set(td, entering);
}
@Override
public ShadowVar cloneState(ShadowVar shadowVar) {
return null;
}
protected static Decoration<ShadowThread,Vector<CV>> interruptions =
ShadowThread.makeDecoration("interruptions", DecorationFactory.Type.MULTIPLE,
new DefaultValue<ShadowThread, Vector<CV>>() { public Vector<CV> get(ShadowThread ld) { return new Vector<CV>(); }} );
@Override
public synchronized void preInterrupt(InterruptEvent me) {
final ShadowThread td = me.getThread();
final ShadowThread joining = me.getInterruptedThread();
CV cv = new CV(get(td));
interruptions.get(joining).add(cv);
tick(td);
}
@Override
public synchronized void interrupted(InterruptedEvent e) {
final ShadowThread current = e.getThread();
Vector<CV> v = interruptions.get(current);
for (CV cv : v) {
get(current).max(cv);
}
v.clear();
super.interrupted(e);
}
}
| false | true | private boolean checkAfter(CV prev, String prevOp, ShadowThread currentThread, String curOp,
AccessEvent fad, boolean isWrite, ShadowVar p) {
CV cv = get(currentThread);
if(prev.anyGt(cv)) {
int start=0;
while(true) {
start=prev.nextGt(cv, start);
if (start==-1) {
break;
}
Object target = fad.getTarget();
if (fad.getKind() == Kind.ARRAY) {
ArrayAccessEvent aae = (ArrayAccessEvent)fad;
final ArrayAccessInfo arrayAccessInfo = aae.getInfo();
arrayErrors.error(currentThread, arrayAccessInfo,
"Guard State", prev,
"Array", Util.objectToIdentityString(target) + "[]", "" + aae.getIndex(),
"Locks", currentThread.getLocksHeld(),
"Prev Op", prevOp+"-by-thread-"+start,
"Prev Op CV", prev,
"Cur Op", curOp,
"Cur Op CV", cv,
"Stack", ShadowThread.stackDumpForErrorMessage(currentThread));
start++;
return !arrayErrors.stillLooking(arrayAccessInfo);
} else {
FieldInfo fd = ((FieldAccessEvent)fad).getInfo().getField();
errors.error(currentThread, fd,
"Guard State", prev,
"Class", target==null?fd.getOwner():target.getClass(),
"Field", Util.objectToIdentityString(target) + "." + fd,
"Locks", currentThread.getLocksHeld(),
"Prev Op", prevOp+"-by-thread-"+start,
"Prev Op CV", prev,
"Cur Op", curOp,
"Cur Op CV", cv,
"Stack", ShadowThread.stackDumpForErrorMessage(currentThread));
start++;
return !errors.stillLooking(fd);
}
}
return false;
} else {
return false;
}
}
| private boolean checkAfter(CV prev, String prevOp, ShadowThread currentThread, String curOp,
AccessEvent fad, boolean isWrite, ShadowVar p) {
CV cv = get(currentThread);
if(prev.anyGt(cv)) {
int start=0;
while(true) {
start=prev.nextGt(cv, start);
if (start==-1) {
break;
}
Object target = fad.getTarget();
if (fad.getKind() == Kind.ARRAY) {
ArrayAccessEvent aae = (ArrayAccessEvent)fad;
final ArrayAccessInfo arrayAccessInfo = aae.getInfo();
arrayErrors.error(currentThread, arrayAccessInfo,
"Guard State", prev,
"Array", Util.objectToIdentityString(target) + "[" + aae.getIndex() +"]",
"Locks", currentThread.getLocksHeld(),
"Prev Op", prevOp+"-by-thread-"+start,
"Prev Op CV", prev,
"Cur Op", curOp,
"Cur Op CV", cv,
"Stack", ShadowThread.stackDumpForErrorMessage(currentThread));
start++;
return !arrayErrors.stillLooking(arrayAccessInfo);
} else {
FieldInfo fd = ((FieldAccessEvent)fad).getInfo().getField();
errors.error(currentThread, fd,
"Guard State", prev,
"Class", target==null?fd.getOwner():target.getClass(),
"Field", Util.objectToIdentityString(target) + "." + fd,
"Locks", currentThread.getLocksHeld(),
"Prev Op", prevOp+"-by-thread-"+start,
"Prev Op CV", prev,
"Cur Op", curOp,
"Cur Op CV", cv,
"Stack", ShadowThread.stackDumpForErrorMessage(currentThread));
start++;
return !errors.stillLooking(fd);
}
}
return false;
} else {
return false;
}
}
|
diff --git a/Slick/src/org/newdawn/slick/SpriteSheet.java b/Slick/src/org/newdawn/slick/SpriteSheet.java
index 603722c..ad6418a 100644
--- a/Slick/src/org/newdawn/slick/SpriteSheet.java
+++ b/Slick/src/org/newdawn/slick/SpriteSheet.java
@@ -1,201 +1,204 @@
package org.newdawn.slick;
import java.io.InputStream;
/**
* A sheet of sprites that can be drawn individually
*
* @author Kevin Glass
*/
public class SpriteSheet extends Image {
/** The width of a single element in pixels */
private int tw;
/** The height of a single element in pixels */
private int th;
/** Subimages */
private Image[][] subImages;
/** The spacing between tiles */
private int spacing;
/** The target image for this sheet */
private Image target;
/**
* Create a new sprite sheet based on a image location
*
* @param image The image to based the sheet of
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
*/
public SpriteSheet(Image image,int tw,int th) {
super(image);
this.target = image;
this.tw = tw;
this.th = th;
// call init manually since constructing from an image will have previously initialised
// from incorrect values
initImpl();
}
/**
* Create a new sprite sheet based on a image location
*
* @param image The image to based the sheet of
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @param spacing The spacing between tiles
*/
public SpriteSheet(Image image,int tw,int th,int spacing) {
super(image);
this.target = image;
this.tw = tw;
this.th = th;
this.spacing = spacing;
// call init manually since constructing from an image will have previously initialised
// from incorrect values
initImpl();
}
/**
* Create a new sprite sheet based on a image location
*
* @param ref The location of the sprite sheet to load
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String ref,int tw,int th) throws SlickException {
this(ref,tw,th,null);
}
/**
* Create a new sprite sheet based on a image location
*
* @param ref The location of the sprite sheet to load
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @param col The colour to treat as transparent
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String ref,int tw,int th, Color col) throws SlickException {
super(ref, false, FILTER_NEAREST, col);
this.target = this;
this.tw = tw;
this.th = th;
}
/**
* Create a new sprite sheet based on a image location
*
* @param name The name to give to the image in the image cache
* @param ref The stream from which we can load the image
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String name, InputStream ref,int tw,int th) throws SlickException {
super(ref,name,false);
this.target = this;
this.tw = tw;
this.th = th;
}
/**
* @see org.newdawn.slick.Image#initImpl()
*/
protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth() - tw) / (tw + spacing)) + 1;
- int tilesDown = ((getHeight() - th) / (th + spacing)) + 2;
+ int tilesDown = ((getHeight() - th) / (th + spacing)) + 1;
+ if (getHeight() - th % (th+spacing) != 0) {
+ tilesDown++;
+ }
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
/**
* Get a sprite at a particular cell on the sprite sheet
*
* @param x The x position of the cell on the sprite sheet
* @param y The y position of the cell on the sprite sheet
* @return The single image from the sprite sheet
*/
public Image getSprite(int x, int y) {
target.init();
initImpl();
return target.getSubImage(x*(tw+spacing),y*(th+spacing),tw,th);
}
/**
* Get the number of sprites across the sheet
*
* @return The number of sprites across the sheet
*/
public int getHorizontalCount() {
target.init();
initImpl();
return subImages.length;
}
/**
* Get the number of sprites down the sheet
*
* @return The number of sprite down the sheet
*/
public int getVerticalCount() {
target.init();
initImpl();
return subImages[0].length;
}
/**
* Render a sprite when this sprite sheet is in use.
*
* @see #startUse()
* @see #endUse()
*
* @param x The x position to render the sprite at
* @param y The y position to render the sprite at
* @param sx The x location of the cell to render
* @param sy The y location of the cell to render
*/
public void renderInUse(int x,int y,int sx,int sy) {
subImages[sx][sy].drawEmbedded(x, y, tw, th);
}
/**
* @see org.newdawn.slick.Image#endUse()
*/
public void endUse() {
if (target == this) {
super.endUse();
return;
}
target.endUse();
}
/**
* @see org.newdawn.slick.Image#startUse()
*/
public void startUse() {
if (target == this) {
super.startUse();
return;
}
target.startUse();
}
}
| true | true | protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth() - tw) / (tw + spacing)) + 1;
int tilesDown = ((getHeight() - th) / (th + spacing)) + 2;
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
| protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth() - tw) / (tw + spacing)) + 1;
int tilesDown = ((getHeight() - th) / (th + spacing)) + 1;
if (getHeight() - th % (th+spacing) != 0) {
tilesDown++;
}
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
|
diff --git a/src/com/wehuibao/DocListFragment.java b/src/com/wehuibao/DocListFragment.java
index b08d3c3..77be235 100644
--- a/src/com/wehuibao/DocListFragment.java
+++ b/src/com/wehuibao/DocListFragment.java
@@ -1,465 +1,466 @@
package com.wehuibao;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.gson.Gson;
import com.wehuibao.json.Doc;
import com.wehuibao.json.DocList;
public class DocListFragment extends SherlockListFragment implements
OnClickListener {
private final static String DOC_LIST_SUFFIX = "_DOC_LIST";
private List<Doc> docs = null;
private DocAdapter adapter;
private int start = 0;
private Boolean hasMore = true;
private TextView loadMore;
private ProgressBar loadMorePB;
private MenuItem refresh = null;
private View footer;
private String listUrl;
private DocList docList;
private boolean isRefresh = false;
private String maxId = null;
private ListType lt = null;
private boolean needFetch = true;
private boolean isStart() {
return getArguments().getBoolean(DocListActivity.IS_START);
}
private String getCookie() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity()
.getApplicationContext());
return prefs.getString("cookie", null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity()
.getApplicationContext());
listUrl = getArguments().getString(DocListActivity.LIST_URL);
if (lt == null) {
lt = getListType();
}
if (docs == null) {
docs = new ArrayList<Doc>();
if (isStart() && (lt == ListType.ME || lt == ListType.HOT)) {
String docListStr = prefs.getString(lt.toString()
+ DOC_LIST_SUFFIX, null);
if (docListStr != null) {
Gson gson = new Gson();
docList = gson.fromJson(docListStr, DocList.class);
if (docList.items.size() > 0) {
docs = docList.items;
needFetch = false;
if (refresh != null) {
refresh.setActionView(null);
}
}
}
}
if (needFetch) {
isRefresh = true;
new DocFetchTask().execute(listUrl);
}
} else {
+ needFetch = false;
if (refresh != null) {
refresh.setActionView(null);
}
}
adapter = new DocAdapter();
footer = this.getActivity().getLayoutInflater()
.inflate(R.layout.load_more, null);
if (hasMore) {
if (getListView().getFooterViewsCount() == 0) {
getListView().addFooterView(footer);
}
} else {
if (getListView().getFooterViewsCount() > 0) {
getListView().removeFooterView(footer);
}
}
loadMore = (TextView) footer.findViewById(R.id.load_more);
loadMorePB = (ProgressBar) footer.findViewById(R.id.load_more_pb);
loadMore.setOnClickListener(this);
this.setListAdapter(adapter);
}
private ListType getListType() {
String listType = getArguments().getString(DocListActivity.LIST_TYPE);
return ListType.getListType(listType);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (lt == null) {
lt = getListType();
}
switch (lt) {
case ME:
inflater.inflate(R.menu.me, menu);
break;
case HOT:
inflater.inflate(R.menu.hot, menu);
break;
default:
inflater.inflate(R.menu.doc_list, menu);
}
refresh = menu.findItem(R.id.menu_refresh);
if (needFetch) {
refresh.setActionView(R.layout.refresh);
}
super.onCreateOptionsMenu(menu, inflater);
}
private void loadMore() {
loadMore.setVisibility(View.GONE);
loadMorePB.setVisibility(View.VISIBLE);
new DocFetchTask().execute(listUrl);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_refresh) {
isRefresh = true;
start = 0;
maxId = null;
refresh.setActionView(R.layout.refresh);
new DocFetchTask().execute(listUrl);
}
if (item.getItemId() == R.id.menu_home) {
String cookie = getCookie();
if (cookie != null) {
Intent homeIntent = new Intent(getActivity(),
DocListActivity.class);
homeIntent.putExtra(DocListActivity.LIST_TYPE,
ListType.ME.toString());
startActivity(homeIntent);
} else {
Intent profileIntent = new Intent(getActivity(),
ProfileActivity.class);
startActivity(profileIntent);
}
}
if (item.getItemId() == R.id.menu_hot) {
Intent hotIntent = new Intent(getActivity(), DocListActivity.class);
hotIntent.putExtra(DocListActivity.LIST_TYPE,
ListType.HOT.toString());
startActivity(hotIntent);
}
if (item.getItemId() == R.id.menu_profile) {
Intent profileIntent = new Intent(getActivity(),
ProfileActivity.class);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity()
.getApplicationContext());
String userId = prefs.getString("userId", "");
String userName = prefs.getString("userName", "");
profileIntent.putExtra(ProfileActivity.USERID, userId);
profileIntent.putExtra(ProfileActivity.USER_NAME, userName);
startActivity(profileIntent);
}
return super.onOptionsItemSelected(item);
}
class DocAdapter extends ArrayAdapter<Doc> {
public DocAdapter() {
super(DocListFragment.this.getActivity(), R.layout.doc_row,
R.id.doc_title, docs);
}
@Override
public int getCount() {
return docs.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
Doc doc = docs.get(position);
TextView title = (TextView) row.findViewById(R.id.doc_title);
title.setText(doc.major_title);
TextView abbrev = (TextView) row.findViewById(R.id.doc_abbrev);
abbrev.setText(doc.abbrev_text);
ImageView thumb = (ImageView) row.findViewById(R.id.doc_thumb);
if (doc.thumb != null && doc.thumb.image_path != null) {
Bitmap bm = BitmapFactory.decodeFile(doc.thumb.image_path);
thumb.setImageBitmap(bm);
thumb.setVisibility(View.VISIBLE);
} else {
thumb.setVisibility(View.GONE);
}
return row;
}
}
class DocFetchTask extends AsyncTask<String, Doc, DocList> {
private List<Doc> fetchedDocs = new ArrayList<Doc>();
@Override
protected DocList doInBackground(String... urls) {
try {
String urlStr = urls[0];
switch (lt) {
case HOT:
if (start != 0) {
urlStr += "?start=" + String.valueOf(start);
}
break;
default:
if (maxId != null) {
urlStr += "?max_id=" + maxId;
}
}
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
String cookie = getCookie();
if (cookie != null) {
connection.setRequestProperty("Cookie", cookie);
}
connection.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
Gson gson = new Gson();
docList = gson.fromJson(reader, DocList.class);
reader.close();
for (Doc doc : docList.items) {
if (doc.title == null || doc.title.length() == 0) {
continue;
}
if (doc.thumb != null && doc.thumb.image_src != null) {
doc.thumb.image_path = downloadDocThumbnail(
doc.thumb.image_src, doc.docId);
}
maxId = doc.docId;
publishProgress(doc);
}
hasMore = docList.has_more;
if (docList.has_more) {
if (isRefresh) {
start = 20;
} else {
start += 20;
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return docList;
}
@Override
protected void onProgressUpdate(Doc... docs) {
for (Doc doc : docs) {
if (DocListFragment.this.docs.indexOf(doc) == -1) {
fetchedDocs.add(doc);
}
}
}
@Override
protected void onPostExecute(DocList docList) {
if (docList == null) {
if (isAdded()) {
Toast.makeText(getActivity(),
getString(R.string.err_msg_cannot_connet),
Toast.LENGTH_SHORT).show();
}
return;
}
if (loadMorePB.getVisibility() == View.VISIBLE) {
loadMorePB.setVisibility(View.GONE);
loadMore.setVisibility(View.VISIBLE);
}
if (!hasMore) {
DocListFragment.this.getListView().removeFooterView(footer);
} else {
if (DocListFragment.this.getListView().getFooterViewsCount() == 0) {
DocListFragment.this.getListView().addFooterView(footer);
}
}
if (isRefresh) {
adapter.clear();
for (Doc doc : docList.items) {
adapter.add(doc);
}
} else {
for (Doc doc : fetchedDocs) {
adapter.add(doc);
}
}
if (fetchedDocs.size() > 0) {
adapter.notifyDataSetChanged();
if (isAdded()) {
Toast.makeText(
getActivity(),
String.valueOf(fetchedDocs.size())
+ getString(R.string.number_of_new_docs),
Toast.LENGTH_SHORT).show();
}
}
if (isRefresh) {
if (refresh != null) {
refresh.setActionView(null);
}
DocListFragment.this.getListView()
.setSelectionAfterHeaderView();
isRefresh = false;
}
}
private String downloadDocThumbnail(String image_url, String doc_id) {
String root = DocListFragment.this.getActivity()
.getExternalFilesDir(null).toString();
File avatarDir = new File(root + "/docs/" + doc_id);
String image_name = image_url
.substring(image_url.lastIndexOf('/') + 1);
if (image_name.indexOf('?') != -1) {
image_name = image_name.substring(0,
image_name.lastIndexOf('?'));
}
File avatar = new File(avatarDir.toString() + '/' + image_name);
if (avatar.exists()) {
return avatar.getAbsolutePath();
}
if (!avatarDir.exists()) {
avatarDir.mkdirs();
}
try {
URL url = new URL(image_url);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(50000);
connection.connect();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(avatar.getPath());
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int len = 0;
try {
while ((len = in.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
bos.flush();
} finally {
fos.getFD().sync();
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
return "";
}
return avatar.getAbsolutePath();
}
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.load_more) {
loadMore();
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (position == docs.size()) {
loadMore();
} else {
Doc doc = docs.get(position);
Intent intent = new Intent(this.getActivity(),
DocDetailActivity.class);
intent.putExtra(DocDetailActivity.DOC_ID, doc.docId);
this.startActivity(intent);
}
}
@Override
public void onPause() {
if (docList != null) {
docList.items = docs;
if (lt != null) {
if (lt == ListType.ME || lt == ListType.HOT) {
Gson gson = new Gson();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity()
.getApplicationContext());
prefs.edit()
.putString(lt.toString() + "_DOC_LIST",
gson.toJson(docList)).commit();
}
}
}
super.onPause();
}
@Override
public void onResume() {
super.onResume();
if (lt == ListType.ME && getCookie() == null) {
Intent hotIntent = new Intent(getActivity(), DocListActivity.class);
hotIntent.putExtra(DocListActivity.LIST_TYPE,
ListType.HOT.toString());
startActivity(hotIntent);
getActivity().finish();
}
}
}
| true | true | public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity()
.getApplicationContext());
listUrl = getArguments().getString(DocListActivity.LIST_URL);
if (lt == null) {
lt = getListType();
}
if (docs == null) {
docs = new ArrayList<Doc>();
if (isStart() && (lt == ListType.ME || lt == ListType.HOT)) {
String docListStr = prefs.getString(lt.toString()
+ DOC_LIST_SUFFIX, null);
if (docListStr != null) {
Gson gson = new Gson();
docList = gson.fromJson(docListStr, DocList.class);
if (docList.items.size() > 0) {
docs = docList.items;
needFetch = false;
if (refresh != null) {
refresh.setActionView(null);
}
}
}
}
if (needFetch) {
isRefresh = true;
new DocFetchTask().execute(listUrl);
}
} else {
if (refresh != null) {
refresh.setActionView(null);
}
}
adapter = new DocAdapter();
footer = this.getActivity().getLayoutInflater()
.inflate(R.layout.load_more, null);
if (hasMore) {
if (getListView().getFooterViewsCount() == 0) {
getListView().addFooterView(footer);
}
} else {
if (getListView().getFooterViewsCount() > 0) {
getListView().removeFooterView(footer);
}
}
loadMore = (TextView) footer.findViewById(R.id.load_more);
loadMorePB = (ProgressBar) footer.findViewById(R.id.load_more_pb);
loadMore.setOnClickListener(this);
this.setListAdapter(adapter);
}
| public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getActivity()
.getApplicationContext());
listUrl = getArguments().getString(DocListActivity.LIST_URL);
if (lt == null) {
lt = getListType();
}
if (docs == null) {
docs = new ArrayList<Doc>();
if (isStart() && (lt == ListType.ME || lt == ListType.HOT)) {
String docListStr = prefs.getString(lt.toString()
+ DOC_LIST_SUFFIX, null);
if (docListStr != null) {
Gson gson = new Gson();
docList = gson.fromJson(docListStr, DocList.class);
if (docList.items.size() > 0) {
docs = docList.items;
needFetch = false;
if (refresh != null) {
refresh.setActionView(null);
}
}
}
}
if (needFetch) {
isRefresh = true;
new DocFetchTask().execute(listUrl);
}
} else {
needFetch = false;
if (refresh != null) {
refresh.setActionView(null);
}
}
adapter = new DocAdapter();
footer = this.getActivity().getLayoutInflater()
.inflate(R.layout.load_more, null);
if (hasMore) {
if (getListView().getFooterViewsCount() == 0) {
getListView().addFooterView(footer);
}
} else {
if (getListView().getFooterViewsCount() > 0) {
getListView().removeFooterView(footer);
}
}
loadMore = (TextView) footer.findViewById(R.id.load_more);
loadMorePB = (ProgressBar) footer.findViewById(R.id.load_more_pb);
loadMore.setOnClickListener(this);
this.setListAdapter(adapter);
}
|
diff --git a/src/com/btmura/android/reddit/app/LinkFragment.java b/src/com/btmura/android/reddit/app/LinkFragment.java
index 313285e7..e3521afd 100644
--- a/src/com/btmura/android/reddit/app/LinkFragment.java
+++ b/src/com/btmura/android/reddit/app/LinkFragment.java
@@ -1,133 +1,134 @@
/*
* Copyright (C) 2012 Brian Muramatsu
*
* 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.btmura.android.reddit.app;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.btmura.android.reddit.R;
import com.btmura.android.reddit.util.Strings;
public class LinkFragment extends Fragment {
public static final String TAG = "LinkFragment";
private static final String ARG_URL = "url";
private WebView webView;
private ProgressBar progress;
public static LinkFragment newInstance(CharSequence url) {
Bundle b = new Bundle(1);
b.putCharSequence(ARG_URL, url);
LinkFragment frag = new LinkFragment();
frag.setArguments(b);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.link, container, false);
webView = (WebView) view.findViewById(R.id.link);
progress = (ProgressBar) view.findViewById(R.id.progress);
setupWebView(webView);
return view;
}
@SuppressLint("SetJavaScriptEnabled")
private void setupWebView(WebView webView) {
WebSettings settings = webView.getSettings();
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
+ settings.setDomStorageEnabled(true);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setSupportZoom(true);
settings.setPluginState(PluginState.ON_DEMAND);
settings.setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
progress.setProgress(newProgress);
}
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.loadUrl(getUrl());
}
}
private String getUrl() {
return Strings.toString(getArguments().getCharSequence(ARG_URL));
}
@Override
public void onResume() {
super.onResume();
webView.onResume();
}
@Override
public void onPause() {
webView.onPause();
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
@Override
public void onDetach() {
webView.destroy();
webView = null;
progress = null;
super.onDetach();
}
}
| true | true | private void setupWebView(WebView webView) {
WebSettings settings = webView.getSettings();
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setSupportZoom(true);
settings.setPluginState(PluginState.ON_DEMAND);
settings.setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
progress.setProgress(newProgress);
}
});
}
| private void setupWebView(WebView webView) {
WebSettings settings = webView.getSettings();
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setDomStorageEnabled(true);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setSupportZoom(true);
settings.setPluginState(PluginState.ON_DEMAND);
settings.setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
progress.setProgress(newProgress);
}
});
}
|
diff --git a/utils/org/eclipse/cdt/utils/Platform.java b/utils/org/eclipse/cdt/utils/Platform.java
index 2eb67ebbd..a99aab2b1 100644
--- a/utils/org/eclipse/cdt/utils/Platform.java
+++ b/utils/org/eclipse/cdt/utils/Platform.java
@@ -1,93 +1,102 @@
/*******************************************************************************
* Copyright (c) 2006, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - Initial API and implementation (Corey Ashford)
* Anton Leherbauer (Wind River Systems)
* Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.osgi.framework.Bundle;
public final class Platform {
// This class duplicates all of the methods in org.eclipse.core.runtime.Platform
// that are used by the CDT. getOSArch() needs a few tweaks because the value returned
// by org.eclipse.core.runtime.Platform.getOSArch represents what the JVM thinks the
// architecture is. In some cases, we may actually be running on a 64-bit machine,
// but the JVM thinks it's running on a 32-bit machine. Without this change, the CDT
// will not handle 64-bit executables on some ppc64. This method could easily be
// extended to handle other platforms with similar issues.
//
// Unfortunately, the org.eclipse.core.runtime.Platform is final, so we cannot just
// extend it and and then override the getOSArch method, so getBundle and getOS just
// encapsulate calls to the same methods in org.eclipse.core.runtime.Platform.
public static final String OS_LINUX = org.eclipse.core.runtime.Platform.OS_LINUX;
private static String cachedArch = null;
public static Bundle getBundle(String symbolicName) {
return org.eclipse.core.runtime.Platform.getBundle(symbolicName);
}
public static String getOS() {
return org.eclipse.core.runtime.Platform.getOS();
}
public static String getOSArch() {
if (cachedArch == null) {
String arch = org.eclipse.core.runtime.Platform.getOSArch();
if (arch.equals(org.eclipse.core.runtime.Platform.ARCH_PPC)) {
// Determine if the platform is actually a ppc64 machine
Process unameProcess;
String cmd[] = {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
try {
unameProcess = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(unameProcess.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String unameOutput= bufferedReader.readLine();
if (unameOutput != null) {
arch= unameOutput;
}
+ bufferedReader.close();
unameProcess.waitFor(); // otherwise the process becomes a zombie
} catch (IOException e) {
} catch (InterruptedException exc) {
- Thread.currentThread().interrupt();
+ // clear interrupted state
+ Thread.interrupted();
}
} else if (arch.equals(org.eclipse.core.runtime.Platform.ARCH_X86)) {
// Determine if the platform is actually a x86_64 machine
Process unameProcess;
- String cmd[] = {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
+ String cmd[];
+ if (org.eclipse.core.runtime.Platform.OS_WIN32.equals(getOS())) {
+ cmd = new String[] {"cmd", "/c", "set", "PROCESSOR_ARCHITECTURE"}; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ } else {
+ cmd = new String[] {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
+ }
try {
unameProcess = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(unameProcess.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String unameOutput = bufferedReader.readLine();
if (unameOutput != null && unameOutput.endsWith("64")) { //$NON-NLS-1$
arch= org.eclipse.core.runtime.Platform.ARCH_X86_64;
}
+ bufferedReader.close();
unameProcess.waitFor(); // otherwise the process becomes a zombie
} catch (IOException e) {
} catch (InterruptedException exc) {
- Thread.currentThread().interrupt();
+ // clear interrupted state
+ Thread.interrupted();
}
}
cachedArch= arch;
}
return cachedArch;
}
}
| false | true | public static String getOSArch() {
if (cachedArch == null) {
String arch = org.eclipse.core.runtime.Platform.getOSArch();
if (arch.equals(org.eclipse.core.runtime.Platform.ARCH_PPC)) {
// Determine if the platform is actually a ppc64 machine
Process unameProcess;
String cmd[] = {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
try {
unameProcess = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(unameProcess.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String unameOutput= bufferedReader.readLine();
if (unameOutput != null) {
arch= unameOutput;
}
unameProcess.waitFor(); // otherwise the process becomes a zombie
} catch (IOException e) {
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
}
} else if (arch.equals(org.eclipse.core.runtime.Platform.ARCH_X86)) {
// Determine if the platform is actually a x86_64 machine
Process unameProcess;
String cmd[] = {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
try {
unameProcess = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(unameProcess.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String unameOutput = bufferedReader.readLine();
if (unameOutput != null && unameOutput.endsWith("64")) { //$NON-NLS-1$
arch= org.eclipse.core.runtime.Platform.ARCH_X86_64;
}
unameProcess.waitFor(); // otherwise the process becomes a zombie
} catch (IOException e) {
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
}
}
cachedArch= arch;
}
return cachedArch;
}
| public static String getOSArch() {
if (cachedArch == null) {
String arch = org.eclipse.core.runtime.Platform.getOSArch();
if (arch.equals(org.eclipse.core.runtime.Platform.ARCH_PPC)) {
// Determine if the platform is actually a ppc64 machine
Process unameProcess;
String cmd[] = {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
try {
unameProcess = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(unameProcess.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String unameOutput= bufferedReader.readLine();
if (unameOutput != null) {
arch= unameOutput;
}
bufferedReader.close();
unameProcess.waitFor(); // otherwise the process becomes a zombie
} catch (IOException e) {
} catch (InterruptedException exc) {
// clear interrupted state
Thread.interrupted();
}
} else if (arch.equals(org.eclipse.core.runtime.Platform.ARCH_X86)) {
// Determine if the platform is actually a x86_64 machine
Process unameProcess;
String cmd[];
if (org.eclipse.core.runtime.Platform.OS_WIN32.equals(getOS())) {
cmd = new String[] {"cmd", "/c", "set", "PROCESSOR_ARCHITECTURE"}; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
} else {
cmd = new String[] {"uname", "-p"}; //$NON-NLS-1$//$NON-NLS-2$
}
try {
unameProcess = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(unameProcess.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String unameOutput = bufferedReader.readLine();
if (unameOutput != null && unameOutput.endsWith("64")) { //$NON-NLS-1$
arch= org.eclipse.core.runtime.Platform.ARCH_X86_64;
}
bufferedReader.close();
unameProcess.waitFor(); // otherwise the process becomes a zombie
} catch (IOException e) {
} catch (InterruptedException exc) {
// clear interrupted state
Thread.interrupted();
}
}
cachedArch= arch;
}
return cachedArch;
}
|
diff --git a/src/main/java/com/sohu/jafka/console/Dumper.java b/src/main/java/com/sohu/jafka/console/Dumper.java
index 1fea0e4..baefed7 100644
--- a/src/main/java/com/sohu/jafka/console/Dumper.java
+++ b/src/main/java/com/sohu/jafka/console/Dumper.java
@@ -1,99 +1,100 @@
/**
* 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 com.sohu.jafka.console;
import static java.lang.String.format;
import java.io.File;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import com.sohu.jafka.message.FileMessageSet;
import com.sohu.jafka.message.Message;
import com.sohu.jafka.message.MessageAndOffset;
import com.sohu.jafka.utils.Utils;
/**
* String message dumper
* @author adyliu ([email protected])
* @since 1.1
*/
public class Dumper {
public static void main(String[] args) throws Exception {
OptionParser parser = new OptionParser();
parser.accepts("no-message", "do not decode message(utf-8 strings)");
parser.accepts("no-offset", "do not print message offset");
parser.accepts("no-size", "do not print message size");
ArgumentAcceptingOptionSpec<Integer> countOpt = parser.accepts("c", "max count mesages.")//
.withRequiredArg().describedAs("count")//
.ofType(Integer.class).defaultsTo(-1);
ArgumentAcceptingOptionSpec<String> fileOpt = parser.accepts("file", "decode file list")//
.withRequiredArg().ofType(String.class).describedAs("filepath");
OptionSet options = parser.parse(args);
if (!options.has(fileOpt)) {
System.err.println("Usage: [options] --file <file>...");
parser.printHelpOn(System.err);
System.exit(1);
}
final boolean decode = !options.has("no-message");
final boolean withOffset = !options.has("no-offset");
final boolean withSize = !options.has("no-size");
int count = countOpt.value(options);
count = count <= 0 ? Integer.MAX_VALUE : count;
int index = 0;
final String logformat = "%s|%s|%s";
for (String filepath : fileOpt.values(options)) {
if (index >= count) break;
File file = new File(filepath);
String filename = file.getName();
final long startOffset = Long.parseLong(filename.substring(0, filename.lastIndexOf('.')));
FileMessageSet messageSet = new FileMessageSet(file, false);
long offset = 0L;
long totalSize = 0L;
try {
int messageCount = 0;
for (MessageAndOffset mao : messageSet) {
final Message msg = mao.message;
if (index >= count) {
break;
}
if (decode || withOffset || withSize) {
System.out.println(format(logformat,//
withOffset ? "" + (startOffset + offset) : "",//
withSize ? "" + msg.payloadSize() : "",//
decode ? Utils.toString(msg.payload(), "UTF-8") : ""));
}
offset = mao.offset;
totalSize += msg.payloadSize();
messageCount++;
+ index++;
}
System.out.println("-----------------------------------------------------------------------------");
System.out.println(filepath);
System.out.println("total message count: " + messageCount);
System.out.println("total message size: " + totalSize);
System.out.println("=============================================");
} finally {
messageSet.close();
}
}
}
}
| true | true | public static void main(String[] args) throws Exception {
OptionParser parser = new OptionParser();
parser.accepts("no-message", "do not decode message(utf-8 strings)");
parser.accepts("no-offset", "do not print message offset");
parser.accepts("no-size", "do not print message size");
ArgumentAcceptingOptionSpec<Integer> countOpt = parser.accepts("c", "max count mesages.")//
.withRequiredArg().describedAs("count")//
.ofType(Integer.class).defaultsTo(-1);
ArgumentAcceptingOptionSpec<String> fileOpt = parser.accepts("file", "decode file list")//
.withRequiredArg().ofType(String.class).describedAs("filepath");
OptionSet options = parser.parse(args);
if (!options.has(fileOpt)) {
System.err.println("Usage: [options] --file <file>...");
parser.printHelpOn(System.err);
System.exit(1);
}
final boolean decode = !options.has("no-message");
final boolean withOffset = !options.has("no-offset");
final boolean withSize = !options.has("no-size");
int count = countOpt.value(options);
count = count <= 0 ? Integer.MAX_VALUE : count;
int index = 0;
final String logformat = "%s|%s|%s";
for (String filepath : fileOpt.values(options)) {
if (index >= count) break;
File file = new File(filepath);
String filename = file.getName();
final long startOffset = Long.parseLong(filename.substring(0, filename.lastIndexOf('.')));
FileMessageSet messageSet = new FileMessageSet(file, false);
long offset = 0L;
long totalSize = 0L;
try {
int messageCount = 0;
for (MessageAndOffset mao : messageSet) {
final Message msg = mao.message;
if (index >= count) {
break;
}
if (decode || withOffset || withSize) {
System.out.println(format(logformat,//
withOffset ? "" + (startOffset + offset) : "",//
withSize ? "" + msg.payloadSize() : "",//
decode ? Utils.toString(msg.payload(), "UTF-8") : ""));
}
offset = mao.offset;
totalSize += msg.payloadSize();
messageCount++;
}
System.out.println("-----------------------------------------------------------------------------");
System.out.println(filepath);
System.out.println("total message count: " + messageCount);
System.out.println("total message size: " + totalSize);
System.out.println("=============================================");
} finally {
messageSet.close();
}
}
}
| public static void main(String[] args) throws Exception {
OptionParser parser = new OptionParser();
parser.accepts("no-message", "do not decode message(utf-8 strings)");
parser.accepts("no-offset", "do not print message offset");
parser.accepts("no-size", "do not print message size");
ArgumentAcceptingOptionSpec<Integer> countOpt = parser.accepts("c", "max count mesages.")//
.withRequiredArg().describedAs("count")//
.ofType(Integer.class).defaultsTo(-1);
ArgumentAcceptingOptionSpec<String> fileOpt = parser.accepts("file", "decode file list")//
.withRequiredArg().ofType(String.class).describedAs("filepath");
OptionSet options = parser.parse(args);
if (!options.has(fileOpt)) {
System.err.println("Usage: [options] --file <file>...");
parser.printHelpOn(System.err);
System.exit(1);
}
final boolean decode = !options.has("no-message");
final boolean withOffset = !options.has("no-offset");
final boolean withSize = !options.has("no-size");
int count = countOpt.value(options);
count = count <= 0 ? Integer.MAX_VALUE : count;
int index = 0;
final String logformat = "%s|%s|%s";
for (String filepath : fileOpt.values(options)) {
if (index >= count) break;
File file = new File(filepath);
String filename = file.getName();
final long startOffset = Long.parseLong(filename.substring(0, filename.lastIndexOf('.')));
FileMessageSet messageSet = new FileMessageSet(file, false);
long offset = 0L;
long totalSize = 0L;
try {
int messageCount = 0;
for (MessageAndOffset mao : messageSet) {
final Message msg = mao.message;
if (index >= count) {
break;
}
if (decode || withOffset || withSize) {
System.out.println(format(logformat,//
withOffset ? "" + (startOffset + offset) : "",//
withSize ? "" + msg.payloadSize() : "",//
decode ? Utils.toString(msg.payload(), "UTF-8") : ""));
}
offset = mao.offset;
totalSize += msg.payloadSize();
messageCount++;
index++;
}
System.out.println("-----------------------------------------------------------------------------");
System.out.println(filepath);
System.out.println("total message count: " + messageCount);
System.out.println("total message size: " + totalSize);
System.out.println("=============================================");
} finally {
messageSet.close();
}
}
}
|
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 0f505316..9a524234 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -1,1859 +1,1865 @@
/**
* Copyright 2007 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.regionserver;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Constructor;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HMsg;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.HServerInfo;
import org.apache.hadoop.hbase.HServerLoad;
import org.apache.hadoop.hbase.HStoreKey;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.LeaseListener;
import org.apache.hadoop.hbase.Leases;
import org.apache.hadoop.hbase.LocalHBaseCluster;
import org.apache.hadoop.hbase.NotServingRegionException;
import org.apache.hadoop.hbase.RegionHistorian;
import org.apache.hadoop.hbase.RemoteExceptionHandler;
import org.apache.hadoop.hbase.UnknownScannerException;
import org.apache.hadoop.hbase.UnknownRowLockException;
import org.apache.hadoop.hbase.ValueOverMaxLengthException;
import org.apache.hadoop.hbase.Leases.LeaseStillHeldException;
import org.apache.hadoop.hbase.client.ServerConnection;
import org.apache.hadoop.hbase.client.ServerConnectionManager;
import org.apache.hadoop.hbase.filter.RowFilterInterface;
import org.apache.hadoop.hbase.io.BatchOperation;
import org.apache.hadoop.hbase.io.BatchUpdate;
import org.apache.hadoop.hbase.io.Cell;
import org.apache.hadoop.hbase.io.HbaseMapWritable;
import org.apache.hadoop.hbase.io.RowResult;
import org.apache.hadoop.hbase.ipc.HMasterRegionInterface;
import org.apache.hadoop.hbase.ipc.HRegionInterface;
import org.apache.hadoop.hbase.ipc.HbaseRPC;
import org.apache.hadoop.hbase.regionserver.metrics.RegionServerMetrics;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.util.InfoServer;
import org.apache.hadoop.hbase.util.Sleeper;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.StringUtils;
/**
* HRegionServer makes a set of HRegions available to clients. It checks in with
* the HMaster. There are many HRegionServers in a single HBase deployment.
*/
public class HRegionServer implements HConstants, HRegionInterface, Runnable {
static final Log LOG = LogFactory.getLog(HRegionServer.class);
// Set when a report to the master comes back with a message asking us to
// shutdown. Also set by call to stop when debugging or running unit tests
// of HRegionServer in isolation. We use AtomicBoolean rather than
// plain boolean so we can pass a reference to Chore threads. Otherwise,
// Chore threads need to know about the hosting class.
protected final AtomicBoolean stopRequested = new AtomicBoolean(false);
protected final AtomicBoolean quiesced = new AtomicBoolean(false);
// Go down hard. Used if file system becomes unavailable and also in
// debugging and unit tests.
protected volatile boolean abortRequested;
// If false, the file system has become unavailable
protected volatile boolean fsOk;
protected final HServerInfo serverInfo;
protected final HBaseConfiguration conf;
private final ServerConnection connection;
private final AtomicBoolean haveRootRegion = new AtomicBoolean(false);
private FileSystem fs;
private Path rootDir;
private final Random rand = new Random();
// Key is Bytes.hashCode of region name byte array and the value is HRegion
// in both of the maps below. Use Bytes.mapKey(byte []) generating key for
// below maps.
protected final Map<Integer, HRegion> onlineRegions =
new ConcurrentHashMap<Integer, HRegion>();
protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final List<HMsg> outboundMsgs =
Collections.synchronizedList(new ArrayList<HMsg>());
final int numRetries;
protected final int threadWakeFrequency;
private final int msgInterval;
private final int serverLeaseTimeout;
protected final int numRegionsToReport;
// Remote HMaster
private HMasterRegionInterface hbaseMaster;
// Server to handle client requests. Default access so can be accessed by
// unit tests.
final Server server;
// Leases
private final Leases leases;
// Request counter
private volatile AtomicInteger requestCount = new AtomicInteger();
// Info server. Default access so can be used by unit tests. REGIONSERVER
// is name of the webapp and the attribute name used stuffing this instance
// into web context.
InfoServer infoServer;
/** region server process name */
public static final String REGIONSERVER = "regionserver";
/**
* Space is reserved in HRS constructor and then released when aborting
* to recover from an OOME. See HBASE-706.
*/
private final LinkedList<byte[]> reservedSpace = new LinkedList<byte []>();
private RegionServerMetrics metrics;
/**
* Thread to shutdown the region server in an orderly manner. This thread
* is registered as a shutdown hook in the HRegionServer constructor and is
* only called when the HRegionServer receives a kill signal.
*/
class ShutdownThread extends Thread {
private final HRegionServer instance;
/**
* @param instance
*/
public ShutdownThread(HRegionServer instance) {
this.instance = instance;
}
@Override
public void run() {
LOG.info("Starting shutdown thread.");
// tell the region server to stop and wait for it to complete
instance.stop();
instance.join();
LOG.info("Shutdown thread complete");
}
}
// Compactions
final CompactSplitThread compactSplitThread;
// Cache flushing
final MemcacheFlusher cacheFlusher;
// HLog and HLog roller. log is protected rather than private to avoid
// eclipse warning when accessed by inner classes
protected volatile HLog log;
final LogRoller logRoller;
final LogFlusher logFlusher;
// flag set after we're done setting up server threads (used for testing)
protected volatile boolean isOnline;
/**
* Starts a HRegionServer at the default location
* @param conf
* @throws IOException
*/
public HRegionServer(HBaseConfiguration conf) throws IOException {
this(new HServerAddress(conf.get(REGIONSERVER_ADDRESS,
DEFAULT_REGIONSERVER_ADDRESS)), conf);
}
/**
* Starts a HRegionServer at the specified location
* @param address
* @param conf
* @throws IOException
*/
public HRegionServer(HServerAddress address, HBaseConfiguration conf)
throws IOException {
this.abortRequested = false;
this.fsOk = true;
this.conf = conf;
this.connection = ServerConnectionManager.getConnection(conf);
this.isOnline = false;
// Config'ed params
this.numRetries = conf.getInt("hbase.client.retries.number", 2);
this.threadWakeFrequency = conf.getInt(THREAD_WAKE_FREQUENCY, 10 * 1000);
this.msgInterval = conf.getInt("hbase.regionserver.msginterval", 3 * 1000);
this.serverLeaseTimeout =
conf.getInt("hbase.master.lease.period", 120 * 1000);
// Cache flushing thread.
this.cacheFlusher = new MemcacheFlusher(conf, this);
// Compaction thread
this.compactSplitThread = new CompactSplitThread(this);
// Log rolling thread
this.logRoller = new LogRoller(this);
// Log flushing thread
this.logFlusher =
new LogFlusher(this.threadWakeFrequency, this.stopRequested);
// Task thread to process requests from Master
this.worker = new Worker();
this.workerThread = new Thread(worker);
// Server to handle client requests
this.server = HbaseRPC.getServer(this, address.getBindAddress(),
address.getPort(), conf.getInt("hbase.regionserver.handler.count", 10),
false, conf);
// Address is givin a default IP for the moment. Will be changed after
// calling the master.
this.serverInfo = new HServerInfo(new HServerAddress(
new InetSocketAddress(DEFAULT_HOST,
this.server.getListenerAddress().getPort())), System.currentTimeMillis(),
this.conf.getInt("hbase.regionserver.info.port", 60030));
if (this.serverInfo.getServerAddress() == null) {
throw new NullPointerException("Server address cannot be null; " +
"hbase-958 debugging");
}
this.numRegionsToReport =
conf.getInt("hbase.regionserver.numregionstoreport", 10);
this.leases = new Leases(
conf.getInt("hbase.regionserver.lease.period", 60 * 1000),
this.threadWakeFrequency);
int nbBlocks = conf.getInt("hbase.regionserver.nbreservationblocks", 4);
for(int i = 0; i < nbBlocks; i++) {
reservedSpace.add(new byte[DEFAULT_SIZE_RESERVATION_BLOCK]);
}
// Register shutdown hook for HRegionServer, runs an orderly shutdown
// when a kill signal is recieved
Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));
}
/**
* The HRegionServer sticks in this loop until closed. It repeatedly checks
* in with the HMaster, sending heartbeats & reports, and receiving HRegion
* load/unload instructions.
*/
public void run() {
boolean quiesceRequested = false;
// A sleeper that sleeps for msgInterval.
Sleeper sleeper = new Sleeper(this.msgInterval, this.stopRequested);
try {
init(reportForDuty(sleeper));
long lastMsg = 0;
// Now ask master what it wants us to do and tell it what we have done
for (int tries = 0; !stopRequested.get() && isHealthy();) {
long now = System.currentTimeMillis();
if (lastMsg != 0 && (now - lastMsg) >= serverLeaseTimeout) {
// It has been way too long since we last reported to the master.
LOG.warn("unable to report to master for " + (now - lastMsg) +
" milliseconds - retrying");
}
if ((now - lastMsg) >= msgInterval) {
HMsg outboundArray[] = null;
synchronized(this.outboundMsgs) {
outboundArray =
this.outboundMsgs.toArray(new HMsg[outboundMsgs.size()]);
this.outboundMsgs.clear();
}
try {
doMetrics();
this.serverInfo.setLoad(new HServerLoad(requestCount.get(),
onlineRegions.size(), this.metrics.storefiles.get(),
this.metrics.memcacheSizeMB.get()));
this.requestCount.set(0);
HMsg msgs[] = hbaseMaster.regionServerReport(
serverInfo, outboundArray, getMostLoadedRegions());
lastMsg = System.currentTimeMillis();
if (this.quiesced.get() && onlineRegions.size() == 0) {
// We've just told the master we're exiting because we aren't
// serving any regions. So set the stop bit and exit.
LOG.info("Server quiesced and not serving any regions. " +
"Starting shutdown");
stopRequested.set(true);
this.outboundMsgs.clear();
continue;
}
// Queue up the HMaster's instruction stream for processing
boolean restart = false;
for(int i = 0;
!restart && !stopRequested.get() && i < msgs.length;
i++) {
LOG.info(msgs[i].toString());
switch(msgs[i].getType()) {
case MSG_CALL_SERVER_STARTUP:
// We the MSG_CALL_SERVER_STARTUP on startup but we can also
// get it when the master is panicing because for instance
// the HDFS has been yanked out from under it. Be wary of
// this message.
if (checkFileSystem()) {
closeAllRegions();
try {
log.closeAndDelete();
} catch (Exception e) {
LOG.error("error closing and deleting HLog", e);
}
try {
serverInfo.setStartCode(System.currentTimeMillis());
log = setupHLog();
this.logFlusher.setHLog(log);
} catch (IOException e) {
this.abortRequested = true;
this.stopRequested.set(true);
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("error restarting server", e);
break;
}
reportForDuty(sleeper);
restart = true;
} else {
LOG.fatal("file system available check failed. " +
"Shutting down server.");
}
break;
case MSG_REGIONSERVER_STOP:
stopRequested.set(true);
break;
case MSG_REGIONSERVER_QUIESCE:
if (!quiesceRequested) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
quiesceRequested = true;
}
break;
default:
if (fsOk) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
}
}
}
// Reset tries count if we had a successful transaction.
tries = 0;
if (restart || this.stopRequested.get()) {
toDo.clear();
continue;
}
} catch (Exception e) {
if (e instanceof IOException) {
e = RemoteExceptionHandler.checkIOException((IOException) e);
}
if (tries < this.numRetries) {
LOG.warn("Processing message (Retry: " + tries + ")", e);
tries++;
} else {
LOG.error("Exceeded max retries: " + this.numRetries, e);
checkFileSystem();
}
+ if (this.stopRequested.get()) {
+ LOG.info("Stop was requested, clearing the toDo " +
+ "despite of the exception");
+ toDo.clear();
+ continue;
+ }
}
}
// Do some housekeeping before going to sleep
housekeeping();
sleeper.sleep(lastMsg);
} // for
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (Throwable t) {
LOG.fatal("Unhandled exception. Aborting...", t);
abort();
}
RegionHistorian.getInstance().offline();
this.leases.closeAfterLeasesExpire();
this.worker.stop();
this.server.stop();
if (this.infoServer != null) {
LOG.info("Stopping infoServer");
try {
this.infoServer.stop();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Send interrupts to wake up threads if sleeping so they notice shutdown.
// TODO: Should we check they are alive? If OOME could have exited already
cacheFlusher.interruptIfNecessary();
logFlusher.interrupt();
compactSplitThread.interruptIfNecessary();
logRoller.interruptIfNecessary();
if (abortRequested) {
if (this.fsOk) {
// Only try to clean up if the file system is available
try {
if (this.log != null) {
this.log.close();
LOG.info("On abort, closed hlog");
}
} catch (IOException e) {
LOG.error("Unable to close log in abort",
RemoteExceptionHandler.checkIOException(e));
}
closeAllRegions(); // Don't leave any open file handles
}
LOG.info("aborting server at: " +
serverInfo.getServerAddress().toString());
} else {
ArrayList<HRegion> closedRegions = closeAllRegions();
try {
log.closeAndDelete();
} catch (IOException e) {
LOG.error("Close and delete failed",
RemoteExceptionHandler.checkIOException(e));
}
try {
HMsg[] exitMsg = new HMsg[closedRegions.size() + 1];
exitMsg[0] = HMsg.REPORT_EXITING;
// Tell the master what regions we are/were serving
int i = 1;
for (HRegion region: closedRegions) {
exitMsg[i++] = new HMsg(HMsg.Type.MSG_REPORT_CLOSE,
region.getRegionInfo());
}
LOG.info("telling master that region server is shutting down at: " +
serverInfo.getServerAddress().toString());
hbaseMaster.regionServerReport(serverInfo, exitMsg, (HRegionInfo[])null);
} catch (IOException e) {
LOG.warn("Failed to send exiting message to master: ",
RemoteExceptionHandler.checkIOException(e));
}
LOG.info("stopping server at: " +
serverInfo.getServerAddress().toString());
}
if (this.hbaseMaster != null) {
HbaseRPC.stopProxy(this.hbaseMaster);
this.hbaseMaster = null;
}
join();
LOG.info(Thread.currentThread().getName() + " exiting");
}
/*
* Run init. Sets up hlog and starts up all server threads.
* @param c Extra configuration.
*/
protected void init(final MapWritable c) throws IOException {
try {
for (Map.Entry<Writable, Writable> e: c.entrySet()) {
String key = e.getKey().toString();
String value = e.getValue().toString();
if (LOG.isDebugEnabled()) {
LOG.debug("Config from master: " + key + "=" + value);
}
this.conf.set(key, value);
}
// Master may have sent us a new address with the other configs.
// Update our address in this case. See HBASE-719
if(conf.get("hbase.regionserver.address") != null)
serverInfo.setServerAddress(new HServerAddress
(conf.get("hbase.regionserver.address"),
serverInfo.getServerAddress().getPort()));
// Master sent us hbase.rootdir to use. Should be fully qualified
// path with file system specification included. Set 'fs.default.name'
// to match the filesystem on hbase.rootdir else underlying hadoop hdfs
// accessors will be going against wrong filesystem (unless all is set
// to defaults).
this.conf.set("fs.default.name", this.conf.get("hbase.rootdir"));
this.fs = FileSystem.get(this.conf);
this.rootDir = new Path(this.conf.get(HConstants.HBASE_DIR));
this.log = setupHLog();
this.logFlusher.setHLog(log);
// Init in here rather than in constructor after thread name has been set
this.metrics = new RegionServerMetrics();
startServiceThreads();
isOnline = true;
} catch (IOException e) {
this.stopRequested.set(true);
isOnline = false;
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("Failed init", e);
IOException ex = new IOException("region server startup failed");
ex.initCause(e);
throw ex;
}
}
/**
* Report the status of the server. A server is online once all the startup
* is completed (setting up filesystem, starting service threads, etc.). This
* method is designed mostly to be useful in tests.
* @return true if online, false if not.
*/
public boolean isOnline() {
return isOnline;
}
private HLog setupHLog() throws RegionServerRunningException,
IOException {
Path logdir = new Path(rootDir, "log" + "_" +
serverInfo.getServerAddress().getBindAddress() + "_" +
this.serverInfo.getStartCode() + "_" +
this.serverInfo.getServerAddress().getPort());
if (LOG.isDebugEnabled()) {
LOG.debug("Log dir " + logdir);
}
if (fs.exists(logdir)) {
throw new RegionServerRunningException("region server already " +
"running at " + this.serverInfo.getServerAddress().toString() +
" because logdir " + logdir.toString() + " exists");
}
HLog newlog = new HLog(fs, logdir, conf, logRoller);
return newlog;
}
/*
* @param interval Interval since last time metrics were called.
*/
protected void doMetrics() {
this.metrics.regions.set(this.onlineRegions.size());
this.metrics.incrementRequests(this.requestCount.get());
// Is this too expensive every three seconds getting a lock on onlineRegions
// and then per store carried? Can I make metrics be sloppier and avoid
// the synchronizations?
int storefiles = 0;
long memcacheSize = 0;
synchronized (this.onlineRegions) {
for (Map.Entry<Integer, HRegion> e: this.onlineRegions.entrySet()) {
HRegion r = e.getValue();
memcacheSize += r.memcacheSize.get();
synchronized(r.stores) {
for(Map.Entry<Integer, HStore> ee: r.stores.entrySet()) {
storefiles += ee.getValue().getStorefilesCount();
}
}
}
}
this.metrics.storefiles.set(storefiles);
this.metrics.memcacheSizeMB.set((int)(memcacheSize/(1024*1024)));
}
/**
* @return Region server metrics instance.
*/
public RegionServerMetrics getMetrics() {
return this.metrics;
}
/*
* Start maintanence Threads, Server, Worker and lease checker threads.
* Install an UncaughtExceptionHandler that calls abort of RegionServer if we
* get an unhandled exception. We cannot set the handler on all threads.
* Server's internal Listener thread is off limits. For Server, if an OOME,
* it waits a while then retries. Meantime, a flush or a compaction that
* tries to run should trigger same critical condition and the shutdown will
* run. On its way out, this server will shut down Server. Leases are sort
* of inbetween. It has an internal thread that while it inherits from
* Chore, it keeps its own internal stop mechanism so needs to be stopped
* by this hosting server. Worker logs the exception and exits.
*/
private void startServiceThreads() throws IOException {
String n = Thread.currentThread().getName();
UncaughtExceptionHandler handler = new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
abort();
LOG.fatal("Set stop flag in " + t.getName(), e);
}
};
Threads.setDaemonThreadRunning(this.logRoller, n + ".logRoller",
handler);
Threads.setDaemonThreadRunning(this.logFlusher, n + ".logFlusher",
handler);
Threads.setDaemonThreadRunning(this.cacheFlusher, n + ".cacheFlusher",
handler);
Threads.setDaemonThreadRunning(this.compactSplitThread, n + ".compactor",
handler);
Threads.setDaemonThreadRunning(this.workerThread, n + ".worker", handler);
// Leases is not a Thread. Internally it runs a daemon thread. If it gets
// an unhandled exception, it will just exit.
this.leases.setName(n + ".leaseChecker");
this.leases.start();
// Put up info server.
int port = this.conf.getInt("hbase.regionserver.info.port", 60030);
if (port >= 0) {
String a = this.conf.get("hbase.master.info.bindAddress", "0.0.0.0");
this.infoServer = new InfoServer("regionserver", a, port, false);
this.infoServer.setAttribute("regionserver", this);
this.infoServer.start();
}
// Start Server. This service is like leases in that it internally runs
// a thread.
this.server.start();
LOG.info("HRegionServer started at: " +
serverInfo.getServerAddress().toString());
}
/*
* Verify that server is healthy
*/
private boolean isHealthy() {
if (!fsOk) {
// File system problem
return false;
}
// Verify that all threads are alive
if (!(leases.isAlive() && compactSplitThread.isAlive() &&
cacheFlusher.isAlive() && logRoller.isAlive() &&
workerThread.isAlive())) {
// One or more threads are no longer alive - shut down
stop();
return false;
}
return true;
}
/*
* Run some housekeeping tasks before we go into 'hibernation' sleeping at
* the end of the main HRegionServer run loop.
*/
private void housekeeping() {
// Try to get the root region location from the master.
if (!haveRootRegion.get()) {
HServerAddress rootServer = hbaseMaster.getRootRegionLocation();
if (rootServer != null) {
// By setting the root region location, we bypass the wait imposed on
// HTable for all regions being assigned.
this.connection.setRootRegionLocation(
new HRegionLocation(HRegionInfo.ROOT_REGIONINFO, rootServer));
haveRootRegion.set(true);
}
}
// If the todo list has > 0 messages, iterate looking for open region
// messages. Send the master a message that we're working on its
// processing so it doesn't assign the region elsewhere.
if (this.toDo.size() <= 0) {
return;
}
// This iterator is 'safe'. We are guaranteed a view on state of the
// queue at time iterator was taken out. Apparently goes from oldest.
for (ToDoEntry e: this.toDo) {
if (e.msg.isType(HMsg.Type.MSG_REGION_OPEN)) {
addProcessingMessage(e.msg.getRegionInfo());
}
}
}
/** @return the HLog */
HLog getLog() {
return this.log;
}
/**
* Sets a flag that will cause all the HRegionServer threads to shut down
* in an orderly fashion. Used by unit tests.
*/
public void stop() {
this.stopRequested.set(true);
synchronized(this) {
notifyAll(); // Wakes run() if it is sleeping
}
}
/**
* Cause the server to exit without closing the regions it is serving, the
* log it is using and without notifying the master.
* Used unit testing and on catastrophic events such as HDFS is yanked out
* from under hbase or we OOME.
*/
public void abort() {
reservedSpace.clear();
this.abortRequested = true;
stop();
}
/**
* Wait on all threads to finish.
* Presumption is that all closes and stops have already been called.
*/
void join() {
join(this.workerThread);
join(this.cacheFlusher);
join(this.compactSplitThread);
join(this.logRoller);
}
private void join(final Thread t) {
while (t.isAlive()) {
try {
t.join();
} catch (InterruptedException e) {
// continue
}
}
}
/*
* Let the master know we're here
* Run initialization using parameters passed us by the master.
*/
private MapWritable reportForDuty(final Sleeper sleeper) {
if (LOG.isDebugEnabled()) {
LOG.debug("Telling master at " +
conf.get(MASTER_ADDRESS) + " that we are up");
}
HMasterRegionInterface master = null;
while (!stopRequested.get() && master == null) {
try {
// Do initial RPC setup. The final argument indicates that the RPC
// should retry indefinitely.
master = (HMasterRegionInterface)HbaseRPC.waitForProxy(
HMasterRegionInterface.class, HMasterRegionInterface.versionID,
new HServerAddress(conf.get(MASTER_ADDRESS)).getInetSocketAddress(),
this.conf, -1);
} catch (IOException e) {
LOG.warn("Unable to connect to master. Retrying. Error was:", e);
sleeper.sleep();
}
}
this.hbaseMaster = master;
MapWritable result = null;
long lastMsg = 0;
while(!stopRequested.get()) {
try {
this.requestCount.set(0);
this.serverInfo.setLoad(new HServerLoad(0, onlineRegions.size(), 0, 0));
lastMsg = System.currentTimeMillis();
result = this.hbaseMaster.regionServerStartup(serverInfo);
break;
} catch (Leases.LeaseStillHeldException e) {
LOG.info("Lease " + e.getName() + " already held on master. Check " +
"DNS configuration so that all region servers are" +
"reporting their true IPs and not 127.0.0.1. Otherwise, this" +
"problem should resolve itself after the lease period of " +
this.conf.get("hbase.master.lease.period")
+ " seconds expires over on the master");
} catch (IOException e) {
LOG.warn("error telling master we are up", e);
}
sleeper.sleep(lastMsg);
}
return result;
}
/* Add to the outbound message buffer */
private void reportOpen(HRegionInfo region) {
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_OPEN, region));
}
/* Add to the outbound message buffer */
private void reportClose(HRegionInfo region) {
reportClose(region, null);
}
/* Add to the outbound message buffer */
private void reportClose(final HRegionInfo region, final byte[] message) {
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_CLOSE, region, message));
}
/**
* Add to the outbound message buffer
*
* When a region splits, we need to tell the master that there are two new
* regions that need to be assigned.
*
* We do not need to inform the master about the old region, because we've
* updated the meta or root regions, and the master will pick that up on its
* next rescan of the root or meta tables.
*/
void reportSplit(HRegionInfo oldRegion, HRegionInfo newRegionA,
HRegionInfo newRegionB) {
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_SPLIT, oldRegion,
(oldRegion.getRegionNameAsString() + " split; daughters: " +
newRegionA.getRegionNameAsString() + ", " +
newRegionB.getRegionNameAsString()).getBytes()));
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_OPEN, newRegionA));
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_OPEN, newRegionB));
}
//////////////////////////////////////////////////////////////////////////////
// HMaster-given operations
//////////////////////////////////////////////////////////////////////////////
/*
* Data structure to hold a HMsg and retries count.
*/
private static class ToDoEntry {
private int tries;
private final HMsg msg;
ToDoEntry(HMsg msg) {
this.tries = 0;
this.msg = msg;
}
}
final BlockingQueue<ToDoEntry> toDo = new LinkedBlockingQueue<ToDoEntry>();
private Worker worker;
private Thread workerThread;
/** Thread that performs long running requests from the master */
class Worker implements Runnable {
void stop() {
synchronized(toDo) {
toDo.notifyAll();
}
}
public void run() {
try {
while(!stopRequested.get()) {
ToDoEntry e = null;
try {
e = toDo.poll(threadWakeFrequency, TimeUnit.MILLISECONDS);
if(e == null || stopRequested.get()) {
continue;
}
LOG.info(e.msg);
switch(e.msg.getType()) {
case MSG_REGIONSERVER_QUIESCE:
closeUserRegions();
break;
case MSG_REGION_OPEN:
// Open a region
openRegion(e.msg.getRegionInfo());
break;
case MSG_REGION_CLOSE:
// Close a region
closeRegion(e.msg.getRegionInfo(), true);
break;
case MSG_REGION_CLOSE_WITHOUT_REPORT:
// Close a region, don't reply
closeRegion(e.msg.getRegionInfo(), false);
break;
case MSG_REGION_SPLIT: {
HRegionInfo info = e.msg.getRegionInfo();
// Force split a region
HRegion region = getRegion(info.getRegionName());
region.regionInfo.shouldSplit(true);
compactSplitThread.compactionRequested(region);
} break;
case MSG_REGION_COMPACT: {
// Compact a region
HRegionInfo info = e.msg.getRegionInfo();
HRegion region = getRegion(info.getRegionName());
compactSplitThread.compactionRequested(region);
} break;
default:
throw new AssertionError(
"Impossible state during msg processing. Instruction: "
+ e.msg.toString());
}
} catch (InterruptedException ex) {
// continue
} catch (Exception ex) {
if (ex instanceof IOException) {
ex = RemoteExceptionHandler.checkIOException((IOException) ex);
}
if(e != null && e.tries < numRetries) {
LOG.warn(ex);
e.tries++;
try {
toDo.put(e);
} catch (InterruptedException ie) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", ex);
}
} else {
LOG.error("unable to process message" +
(e != null ? (": " + e.msg.toString()) : ""), ex);
if (!checkFileSystem()) {
break;
}
}
}
}
} catch(Throwable t) {
LOG.fatal("Unhandled exception", t);
} finally {
LOG.info("worker thread exiting");
}
}
}
void openRegion(final HRegionInfo regionInfo) {
// If historian is not online and this is not a meta region, online it.
if (!regionInfo.isMetaRegion() &&
!RegionHistorian.getInstance().isOnline()) {
RegionHistorian.getInstance().online(this.conf);
}
Integer mapKey = Bytes.mapKey(regionInfo.getRegionName());
HRegion region = this.onlineRegions.get(mapKey);
if (region == null) {
try {
region = instantiateRegion(regionInfo);
// Startup a compaction early if one is needed.
this.compactSplitThread.compactionRequested(region);
} catch (IOException e) {
LOG.error("error opening region " + regionInfo.getRegionNameAsString(), e);
// TODO: add an extra field in HRegionInfo to indicate that there is
// an error. We can't do that now because that would be an incompatible
// change that would require a migration
reportClose(regionInfo, StringUtils.stringifyException(e).getBytes());
return;
}
this.lock.writeLock().lock();
try {
this.log.setSequenceNumber(region.getMinSequenceId());
this.onlineRegions.put(mapKey, region);
} finally {
this.lock.writeLock().unlock();
}
}
reportOpen(regionInfo);
}
protected HRegion instantiateRegion(final HRegionInfo regionInfo)
throws IOException {
HRegion r = new HRegion(HTableDescriptor.getTableDir(rootDir, regionInfo
.getTableDesc().getName()), this.log, this.fs, conf, regionInfo,
this.cacheFlusher);
r.initialize(null, new Progressable() {
public void progress() {
addProcessingMessage(regionInfo);
}
});
return r;
}
/*
* Add a MSG_REPORT_PROCESS_OPEN to the outbound queue.
* This method is called while region is in the queue of regions to process
* and then while the region is being opened, it is called from the Worker
* thread that is running the region open.
* @param hri Region to add the message for
*/
protected void addProcessingMessage(final HRegionInfo hri) {
getOutboundMsgs().add(new HMsg(HMsg.Type.MSG_REPORT_PROCESS_OPEN, hri));
}
void closeRegion(final HRegionInfo hri, final boolean reportWhenCompleted)
throws IOException {
HRegion region = this.removeFromOnlineRegions(hri);
if (region != null) {
region.close();
if(reportWhenCompleted) {
reportClose(hri);
}
}
}
/** Called either when the master tells us to restart or from stop() */
ArrayList<HRegion> closeAllRegions() {
ArrayList<HRegion> regionsToClose = new ArrayList<HRegion>();
this.lock.writeLock().lock();
try {
regionsToClose.addAll(onlineRegions.values());
onlineRegions.clear();
} finally {
this.lock.writeLock().unlock();
}
for(HRegion region: regionsToClose) {
if (LOG.isDebugEnabled()) {
LOG.debug("closing region " + Bytes.toString(region.getRegionName()));
}
try {
region.close(abortRequested);
} catch (IOException e) {
LOG.error("error closing region " +
Bytes.toString(region.getRegionName()),
RemoteExceptionHandler.checkIOException(e));
}
}
return regionsToClose;
}
/** Called as the first stage of cluster shutdown. */
void closeUserRegions() {
ArrayList<HRegion> regionsToClose = new ArrayList<HRegion>();
this.lock.writeLock().lock();
try {
synchronized (onlineRegions) {
for (Iterator<Map.Entry<Integer, HRegion>> i =
onlineRegions.entrySet().iterator(); i.hasNext();) {
Map.Entry<Integer, HRegion> e = i.next();
HRegion r = e.getValue();
if (!r.getRegionInfo().isMetaRegion()) {
regionsToClose.add(r);
i.remove();
}
}
}
} finally {
this.lock.writeLock().unlock();
}
for(HRegion region: regionsToClose) {
if (LOG.isDebugEnabled()) {
LOG.debug("closing region " + Bytes.toString(region.getRegionName()));
}
try {
region.close();
} catch (IOException e) {
LOG.error("error closing region " + region.getRegionName(),
RemoteExceptionHandler.checkIOException(e));
}
}
this.quiesced.set(true);
if (onlineRegions.size() == 0) {
outboundMsgs.add(HMsg.REPORT_EXITING);
} else {
outboundMsgs.add(HMsg.REPORT_QUIESCED);
}
}
//
// HRegionInterface
//
public HRegionInfo getRegionInfo(final byte [] regionName)
throws NotServingRegionException {
requestCount.incrementAndGet();
return getRegion(regionName).getRegionInfo();
}
public Cell[] get(final byte [] regionName, final byte [] row,
final byte [] column, final long timestamp, final int numVersions)
throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
return getRegion(regionName).get(row, column, timestamp, numVersions);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public RowResult getRow(final byte [] regionName, final byte [] row,
final byte [][] columns, final long ts, final long lockId)
throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
// convert the columns array into a set so it's easy to check later.
Set<byte []> columnSet = null;
if (columns != null) {
columnSet = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
columnSet.addAll(Arrays.asList(columns));
}
HRegion region = getRegion(regionName);
Map<byte [], Cell> map = region.getFull(row, columnSet, ts,
getLockFromId(lockId));
HbaseMapWritable<byte [], Cell> result =
new HbaseMapWritable<byte [], Cell>();
result.putAll(map);
return new RowResult(row, result);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public RowResult getClosestRowBefore(final byte [] regionName,
final byte [] row)
throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
// locate the region we're operating on
HRegion region = getRegion(regionName);
// ask the region for all the data
RowResult rr = region.getClosestRowBefore(row);
return rr;
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public RowResult next(final long scannerId) throws IOException {
RowResult[] rrs = next(scannerId, 1);
return rrs.length == 0 ? null : rrs[0];
}
public RowResult[] next(final long scannerId, int nbRows) throws IOException {
checkOpen();
requestCount.incrementAndGet();
ArrayList<RowResult> resultSets = new ArrayList<RowResult>();
try {
String scannerName = String.valueOf(scannerId);
InternalScanner s = scanners.get(scannerName);
if (s == null) {
throw new UnknownScannerException("Name: " + scannerName);
}
this.leases.renewLease(scannerName);
for(int i = 0; i < nbRows; i++) {
// Collect values to be returned here
HbaseMapWritable<byte [], Cell> values
= new HbaseMapWritable<byte [], Cell>();
HStoreKey key = new HStoreKey();
while (s.next(key, values)) {
if (values.size() > 0) {
// Row has something in it. Return the value.
resultSets.add(new RowResult(key.getRow(), values));
break;
}
}
}
return resultSets.toArray(new RowResult[resultSets.size()]);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public void batchUpdate(final byte [] regionName, BatchUpdate b,
@SuppressWarnings("unused") long lockId)
throws IOException {
if (b.getRow() == null)
throw new IllegalArgumentException("update has null row");
checkOpen();
this.requestCount.incrementAndGet();
HRegion region = getRegion(regionName);
validateValuesLength(b, region);
try {
cacheFlusher.reclaimMemcacheMemory();
region.batchUpdate(b, getLockFromId(b.getRowLock()));
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public int batchUpdates(final byte[] regionName, final BatchUpdate[] b)
throws IOException {
int i = 0;
checkOpen();
try {
HRegion region = getRegion(regionName);
this.cacheFlusher.reclaimMemcacheMemory();
Integer[] locks = new Integer[b.length];
for (i = 0; i < b.length; i++) {
this.requestCount.incrementAndGet();
validateValuesLength(b[i], region);
locks[i] = getLockFromId(b[i].getRowLock());
region.batchUpdate(b[i], locks[i]);
}
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch(WrongRegionException ex) {
return i;
} catch (NotServingRegionException ex) {
return i;
} catch (IOException e) {
checkFileSystem();
throw e;
}
return -1;
}
/**
* Utility method to verify values length
* @param batchUpdate The update to verify
* @throws IOException Thrown if a value is too long
*/
private void validateValuesLength(BatchUpdate batchUpdate,
HRegion region) throws IOException {
HTableDescriptor desc = region.getTableDesc();
for (Iterator<BatchOperation> iter =
batchUpdate.iterator(); iter.hasNext();) {
BatchOperation operation = iter.next();
if (operation.getValue() != null) {
HColumnDescriptor fam =
desc.getFamily(HStoreKey.getFamily(operation.getColumn()));
if (fam != null) {
int maxLength = fam.getMaxValueLength();
if (operation.getValue().length > maxLength) {
throw new ValueOverMaxLengthException("Value in column "
+ Bytes.toString(operation.getColumn()) + " is too long. "
+ operation.getValue().length + " instead of " + maxLength);
}
}
}
}
}
//
// remote scanner interface
//
public long openScanner(byte [] regionName, byte [][] cols, byte [] firstRow,
final long timestamp, final RowFilterInterface filter)
throws IOException {
checkOpen();
NullPointerException npe = null;
if (regionName == null) {
npe = new NullPointerException("regionName is null");
} else if (cols == null) {
npe = new NullPointerException("columns to scan is null");
} else if (firstRow == null) {
npe = new NullPointerException("firstRow for scanner is null");
}
if (npe != null) {
IOException io = new IOException("Invalid arguments to openScanner");
io.initCause(npe);
throw io;
}
requestCount.incrementAndGet();
try {
HRegion r = getRegion(regionName);
InternalScanner s =
r.getScanner(cols, firstRow, timestamp, filter);
long scannerId = addScanner(s);
return scannerId;
} catch (IOException e) {
LOG.error("Error opening scanner (fsOk: " + this.fsOk + ")",
RemoteExceptionHandler.checkIOException(e));
checkFileSystem();
throw e;
}
}
protected long addScanner(InternalScanner s) throws LeaseStillHeldException {
long scannerId = -1L;
scannerId = rand.nextLong();
String scannerName = String.valueOf(scannerId);
synchronized(scanners) {
scanners.put(scannerName, s);
}
this.leases.
createLease(scannerName, new ScannerListener(scannerName));
return scannerId;
}
public void close(final long scannerId) throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
String scannerName = String.valueOf(scannerId);
InternalScanner s = null;
synchronized(scanners) {
s = scanners.remove(scannerName);
}
if(s == null) {
throw new UnknownScannerException(scannerName);
}
s.close();
this.leases.cancelLease(scannerName);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
Map<String, InternalScanner> scanners =
new ConcurrentHashMap<String, InternalScanner>();
/**
* Instantiated as a scanner lease.
* If the lease times out, the scanner is closed
*/
private class ScannerListener implements LeaseListener {
private final String scannerName;
ScannerListener(final String n) {
this.scannerName = n;
}
public void leaseExpired() {
LOG.info("Scanner " + this.scannerName + " lease expired");
InternalScanner s = null;
synchronized(scanners) {
s = scanners.remove(this.scannerName);
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
LOG.error("Closing scanner", e);
}
}
}
}
//
// Methods that do the actual work for the remote API
//
public void deleteAll(final byte [] regionName, final byte [] row,
final byte [] column, final long timestamp, final long lockId)
throws IOException {
HRegion region = getRegion(regionName);
region.deleteAll(row, column, timestamp, getLockFromId(lockId));
}
public void deleteAll(final byte [] regionName, final byte [] row,
final long timestamp, final long lockId)
throws IOException {
HRegion region = getRegion(regionName);
region.deleteAll(row, timestamp, getLockFromId(lockId));
}
public void deleteFamily(byte [] regionName, byte [] row, byte [] family,
long timestamp, final long lockId)
throws IOException{
getRegion(regionName).deleteFamily(row, family, timestamp,
getLockFromId(lockId));
}
public long lockRow(byte [] regionName, byte [] row)
throws IOException {
checkOpen();
NullPointerException npe = null;
if(regionName == null) {
npe = new NullPointerException("regionName is null");
} else if(row == null) {
npe = new NullPointerException("row to lock is null");
}
if(npe != null) {
IOException io = new IOException("Invalid arguments to lockRow");
io.initCause(npe);
throw io;
}
requestCount.incrementAndGet();
try {
HRegion region = getRegion(regionName);
Integer r = region.obtainRowLock(row);
long lockId = addRowLock(r,region);
LOG.debug("Row lock " + lockId + " explicitly acquired by client");
return lockId;
} catch (IOException e) {
LOG.error("Error obtaining row lock (fsOk: " + this.fsOk + ")",
RemoteExceptionHandler.checkIOException(e));
checkFileSystem();
throw e;
}
}
protected long addRowLock(Integer r, HRegion region) throws LeaseStillHeldException {
long lockId = -1L;
lockId = rand.nextLong();
String lockName = String.valueOf(lockId);
synchronized(rowlocks) {
rowlocks.put(lockName, r);
}
this.leases.
createLease(lockName, new RowLockListener(lockName, region));
return lockId;
}
/**
* Method to get the Integer lock identifier used internally
* from the long lock identifier used by the client.
* @param lockId long row lock identifier from client
* @return intId Integer row lock used internally in HRegion
* @throws IOException Thrown if this is not a valid client lock id.
*/
private Integer getLockFromId(long lockId)
throws IOException {
if(lockId == -1L) {
return null;
}
String lockName = String.valueOf(lockId);
Integer rl = null;
synchronized(rowlocks) {
rl = rowlocks.get(lockName);
}
if(rl == null) {
throw new IOException("Invalid row lock");
}
this.leases.renewLease(lockName);
return rl;
}
public void unlockRow(byte [] regionName, long lockId)
throws IOException {
checkOpen();
NullPointerException npe = null;
if(regionName == null) {
npe = new NullPointerException("regionName is null");
} else if(lockId == -1L) {
npe = new NullPointerException("lockId is null");
}
if(npe != null) {
IOException io = new IOException("Invalid arguments to unlockRow");
io.initCause(npe);
throw io;
}
requestCount.incrementAndGet();
try {
HRegion region = getRegion(regionName);
String lockName = String.valueOf(lockId);
Integer r = null;
synchronized(rowlocks) {
r = rowlocks.remove(lockName);
}
if(r == null) {
throw new UnknownRowLockException(lockName);
}
region.releaseRowLock(r);
this.leases.cancelLease(lockName);
LOG.debug("Row lock " + lockId + " has been explicitly released by client");
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
Map<String, Integer> rowlocks =
new ConcurrentHashMap<String, Integer>();
/**
* Instantiated as a row lock lease.
* If the lease times out, the row lock is released
*/
private class RowLockListener implements LeaseListener {
private final String lockName;
private final HRegion region;
RowLockListener(final String lockName, final HRegion region) {
this.lockName = lockName;
this.region = region;
}
public void leaseExpired() {
LOG.info("Row Lock " + this.lockName + " lease expired");
Integer r = null;
synchronized(rowlocks) {
r = rowlocks.remove(this.lockName);
}
if(r != null) {
region.releaseRowLock(r);
}
}
}
/**
* @return Info on this server.
*/
public HServerInfo getServerInfo() {
return this.serverInfo;
}
/** @return the info server */
public InfoServer getInfoServer() {
return infoServer;
}
/**
* @return true if a stop has been requested.
*/
public boolean isStopRequested() {
return stopRequested.get();
}
/**
*
* @return the configuration
*/
public HBaseConfiguration getConfiguration() {
return conf;
}
/** @return the write lock for the server */
ReentrantReadWriteLock.WriteLock getWriteLock() {
return lock.writeLock();
}
/**
* @return Immutable list of this servers regions.
*/
public Collection<HRegion> getOnlineRegions() {
return Collections.unmodifiableCollection(onlineRegions.values());
}
/**
* @return The HRegionInfos from online regions sorted
*/
public SortedSet<HRegionInfo> getSortedOnlineRegionInfos() {
SortedSet<HRegionInfo> result = new TreeSet<HRegionInfo>();
synchronized(this.onlineRegions) {
for (HRegion r: this.onlineRegions.values()) {
result.add(r.getRegionInfo());
}
}
return result;
}
/**
* This method removes HRegion corresponding to hri from the Map of onlineRegions.
*
* @param hri the HRegionInfo corresponding to the HRegion to-be-removed.
* @return the removed HRegion, or null if the HRegion was not in onlineRegions.
*/
HRegion removeFromOnlineRegions(HRegionInfo hri) {
this.lock.writeLock().lock();
HRegion toReturn = null;
try {
toReturn = onlineRegions.remove(Bytes.mapKey(hri.getRegionName()));
} finally {
this.lock.writeLock().unlock();
}
return toReturn;
}
/**
* @return A new Map of online regions sorted by region size with the first
* entry being the biggest.
*/
public SortedMap<Long, HRegion> getCopyOfOnlineRegionsSortedBySize() {
// we'll sort the regions in reverse
SortedMap<Long, HRegion> sortedRegions = new TreeMap<Long, HRegion>(
new Comparator<Long>() {
public int compare(Long a, Long b) {
return -1 * a.compareTo(b);
}
});
// Copy over all regions. Regions are sorted by size with biggest first.
synchronized (this.onlineRegions) {
for (HRegion region : this.onlineRegions.values()) {
sortedRegions.put(region.memcacheSize.get(), region);
}
}
return sortedRegions;
}
/**
* @param regionName
* @return HRegion for the passed <code>regionName</code> or null if named
* region is not member of the online regions.
*/
public HRegion getOnlineRegion(final byte [] regionName) {
return onlineRegions.get(Bytes.mapKey(regionName));
}
/** @return the request count */
public AtomicInteger getRequestCount() {
return this.requestCount;
}
/** @return reference to FlushRequester */
public FlushRequester getFlushRequester() {
return this.cacheFlusher;
}
/**
* Protected utility method for safely obtaining an HRegion handle.
* @param regionName Name of online {@link HRegion} to return
* @return {@link HRegion} for <code>regionName</code>
* @throws NotServingRegionException
*/
protected HRegion getRegion(final byte [] regionName)
throws NotServingRegionException {
HRegion region = null;
this.lock.readLock().lock();
try {
Integer key = Integer.valueOf(Bytes.hashCode(regionName));
region = onlineRegions.get(key);
if (region == null) {
throw new NotServingRegionException(regionName);
}
return region;
} finally {
this.lock.readLock().unlock();
}
}
/**
* Get the top N most loaded regions this server is serving so we can
* tell the master which regions it can reallocate if we're overloaded.
* TODO: actually calculate which regions are most loaded. (Right now, we're
* just grabbing the first N regions being served regardless of load.)
*/
protected HRegionInfo[] getMostLoadedRegions() {
ArrayList<HRegionInfo> regions = new ArrayList<HRegionInfo>();
synchronized (onlineRegions) {
for (HRegion r : onlineRegions.values()) {
if (regions.size() < numRegionsToReport) {
regions.add(r.getRegionInfo());
} else {
break;
}
}
}
return regions.toArray(new HRegionInfo[regions.size()]);
}
/**
* Called to verify that this server is up and running.
*
* @throws IOException
*/
protected void checkOpen() throws IOException {
if (this.stopRequested.get() || this.abortRequested) {
throw new IOException("Server not running");
}
if (!fsOk) {
throw new IOException("File system not available");
}
}
/**
* Checks to see if the file system is still accessible.
* If not, sets abortRequested and stopRequested
*
* @return false if file system is not available
*/
protected boolean checkFileSystem() {
if (this.fsOk && fs != null) {
try {
FSUtils.checkFileSystemAvailable(fs);
} catch (IOException e) {
LOG.fatal("Shutting down HRegionServer: file system not available", e);
abort();
fsOk = false;
}
}
return this.fsOk;
}
/**
* @return Returns list of non-closed regions hosted on this server. If no
* regions to check, returns an empty list.
*/
protected Set<HRegion> getRegionsToCheck() {
HashSet<HRegion> regionsToCheck = new HashSet<HRegion>();
//TODO: is this locking necessary?
lock.readLock().lock();
try {
regionsToCheck.addAll(this.onlineRegions.values());
} finally {
lock.readLock().unlock();
}
// Purge closed regions.
for (final Iterator<HRegion> i = regionsToCheck.iterator(); i.hasNext();) {
HRegion r = i.next();
if (r.isClosed()) {
i.remove();
}
}
return regionsToCheck;
}
public long getProtocolVersion(final String protocol,
@SuppressWarnings("unused") final long clientVersion)
throws IOException {
if (protocol.equals(HRegionInterface.class.getName())) {
return HRegionInterface.versionID;
}
throw new IOException("Unknown protocol to name node: " + protocol);
}
/**
* @return Queue to which you can add outbound messages.
*/
protected List<HMsg> getOutboundMsgs() {
return this.outboundMsgs;
}
/**
* Return the total size of all memcaches in every region.
* @return memcache size in bytes
*/
public long getGlobalMemcacheSize() {
long total = 0;
synchronized (onlineRegions) {
for (HRegion region : onlineRegions.values()) {
total += region.memcacheSize.get();
}
}
return total;
}
/**
* @return Return the leases.
*/
protected Leases getLeases() {
return leases;
}
/**
* @return Return the rootDir.
*/
protected Path getRootDir() {
return rootDir;
}
/**
* @return Return the fs.
*/
protected FileSystem getFileSystem() {
return fs;
}
//
// Main program and support routines
//
private static void printUsageAndExit() {
printUsageAndExit(null);
}
private static void printUsageAndExit(final String message) {
if (message != null) {
System.err.println(message);
}
System.err.println("Usage: java " +
"org.apache.hbase.HRegionServer [--bind=hostname:port] start");
System.exit(0);
}
/**
* Do class main.
* @param args
* @param regionServerClass HRegionServer to instantiate.
*/
protected static void doMain(final String [] args,
final Class<? extends HRegionServer> regionServerClass) {
if (args.length < 1) {
printUsageAndExit();
}
Configuration conf = new HBaseConfiguration();
// Process command-line args. TODO: Better cmd-line processing
// (but hopefully something not as painful as cli options).
final String addressArgKey = "--bind=";
for (String cmd: args) {
if (cmd.startsWith(addressArgKey)) {
conf.set(REGIONSERVER_ADDRESS, cmd.substring(addressArgKey.length()));
continue;
}
if (cmd.equals("start")) {
try {
// If 'local', don't start a region server here. Defer to
// LocalHBaseCluster. It manages 'local' clusters.
if (LocalHBaseCluster.isLocal(conf)) {
LOG.warn("Not starting a distinct region server because " +
"hbase.master is set to 'local' mode");
} else {
Constructor<? extends HRegionServer> c =
regionServerClass.getConstructor(HBaseConfiguration.class);
HRegionServer hrs = c.newInstance(conf);
Thread t = new Thread(hrs);
t.setName("regionserver" + hrs.server.getListenerAddress());
t.start();
}
} catch (Throwable t) {
LOG.error( "Can not start region server because "+
StringUtils.stringifyException(t) );
System.exit(-1);
}
break;
}
if (cmd.equals("stop")) {
printUsageAndExit("To shutdown the regionserver run " +
"bin/hbase-daemon.sh stop regionserver or send a kill signal to" +
"the regionserver pid");
}
// Print out usage if we get to here.
printUsageAndExit();
}
}
/**
* @param args
*/
public static void main(String [] args) {
Configuration conf = new HBaseConfiguration();
@SuppressWarnings("unchecked")
Class<? extends HRegionServer> regionServerClass = (Class<? extends HRegionServer>) conf
.getClass(HConstants.REGION_SERVER_IMPL, HRegionServer.class);
doMain(args, regionServerClass);
}
}
| true | true | public void run() {
boolean quiesceRequested = false;
// A sleeper that sleeps for msgInterval.
Sleeper sleeper = new Sleeper(this.msgInterval, this.stopRequested);
try {
init(reportForDuty(sleeper));
long lastMsg = 0;
// Now ask master what it wants us to do and tell it what we have done
for (int tries = 0; !stopRequested.get() && isHealthy();) {
long now = System.currentTimeMillis();
if (lastMsg != 0 && (now - lastMsg) >= serverLeaseTimeout) {
// It has been way too long since we last reported to the master.
LOG.warn("unable to report to master for " + (now - lastMsg) +
" milliseconds - retrying");
}
if ((now - lastMsg) >= msgInterval) {
HMsg outboundArray[] = null;
synchronized(this.outboundMsgs) {
outboundArray =
this.outboundMsgs.toArray(new HMsg[outboundMsgs.size()]);
this.outboundMsgs.clear();
}
try {
doMetrics();
this.serverInfo.setLoad(new HServerLoad(requestCount.get(),
onlineRegions.size(), this.metrics.storefiles.get(),
this.metrics.memcacheSizeMB.get()));
this.requestCount.set(0);
HMsg msgs[] = hbaseMaster.regionServerReport(
serverInfo, outboundArray, getMostLoadedRegions());
lastMsg = System.currentTimeMillis();
if (this.quiesced.get() && onlineRegions.size() == 0) {
// We've just told the master we're exiting because we aren't
// serving any regions. So set the stop bit and exit.
LOG.info("Server quiesced and not serving any regions. " +
"Starting shutdown");
stopRequested.set(true);
this.outboundMsgs.clear();
continue;
}
// Queue up the HMaster's instruction stream for processing
boolean restart = false;
for(int i = 0;
!restart && !stopRequested.get() && i < msgs.length;
i++) {
LOG.info(msgs[i].toString());
switch(msgs[i].getType()) {
case MSG_CALL_SERVER_STARTUP:
// We the MSG_CALL_SERVER_STARTUP on startup but we can also
// get it when the master is panicing because for instance
// the HDFS has been yanked out from under it. Be wary of
// this message.
if (checkFileSystem()) {
closeAllRegions();
try {
log.closeAndDelete();
} catch (Exception e) {
LOG.error("error closing and deleting HLog", e);
}
try {
serverInfo.setStartCode(System.currentTimeMillis());
log = setupHLog();
this.logFlusher.setHLog(log);
} catch (IOException e) {
this.abortRequested = true;
this.stopRequested.set(true);
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("error restarting server", e);
break;
}
reportForDuty(sleeper);
restart = true;
} else {
LOG.fatal("file system available check failed. " +
"Shutting down server.");
}
break;
case MSG_REGIONSERVER_STOP:
stopRequested.set(true);
break;
case MSG_REGIONSERVER_QUIESCE:
if (!quiesceRequested) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
quiesceRequested = true;
}
break;
default:
if (fsOk) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
}
}
}
// Reset tries count if we had a successful transaction.
tries = 0;
if (restart || this.stopRequested.get()) {
toDo.clear();
continue;
}
} catch (Exception e) {
if (e instanceof IOException) {
e = RemoteExceptionHandler.checkIOException((IOException) e);
}
if (tries < this.numRetries) {
LOG.warn("Processing message (Retry: " + tries + ")", e);
tries++;
} else {
LOG.error("Exceeded max retries: " + this.numRetries, e);
checkFileSystem();
}
}
}
// Do some housekeeping before going to sleep
housekeeping();
sleeper.sleep(lastMsg);
} // for
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (Throwable t) {
LOG.fatal("Unhandled exception. Aborting...", t);
abort();
}
RegionHistorian.getInstance().offline();
this.leases.closeAfterLeasesExpire();
this.worker.stop();
this.server.stop();
if (this.infoServer != null) {
LOG.info("Stopping infoServer");
try {
this.infoServer.stop();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Send interrupts to wake up threads if sleeping so they notice shutdown.
// TODO: Should we check they are alive? If OOME could have exited already
cacheFlusher.interruptIfNecessary();
logFlusher.interrupt();
compactSplitThread.interruptIfNecessary();
logRoller.interruptIfNecessary();
if (abortRequested) {
if (this.fsOk) {
// Only try to clean up if the file system is available
try {
if (this.log != null) {
this.log.close();
LOG.info("On abort, closed hlog");
}
} catch (IOException e) {
LOG.error("Unable to close log in abort",
RemoteExceptionHandler.checkIOException(e));
}
closeAllRegions(); // Don't leave any open file handles
}
LOG.info("aborting server at: " +
serverInfo.getServerAddress().toString());
} else {
ArrayList<HRegion> closedRegions = closeAllRegions();
try {
log.closeAndDelete();
} catch (IOException e) {
LOG.error("Close and delete failed",
RemoteExceptionHandler.checkIOException(e));
}
try {
HMsg[] exitMsg = new HMsg[closedRegions.size() + 1];
exitMsg[0] = HMsg.REPORT_EXITING;
// Tell the master what regions we are/were serving
int i = 1;
for (HRegion region: closedRegions) {
exitMsg[i++] = new HMsg(HMsg.Type.MSG_REPORT_CLOSE,
region.getRegionInfo());
}
LOG.info("telling master that region server is shutting down at: " +
serverInfo.getServerAddress().toString());
hbaseMaster.regionServerReport(serverInfo, exitMsg, (HRegionInfo[])null);
} catch (IOException e) {
LOG.warn("Failed to send exiting message to master: ",
RemoteExceptionHandler.checkIOException(e));
}
LOG.info("stopping server at: " +
serverInfo.getServerAddress().toString());
}
if (this.hbaseMaster != null) {
HbaseRPC.stopProxy(this.hbaseMaster);
this.hbaseMaster = null;
}
join();
LOG.info(Thread.currentThread().getName() + " exiting");
}
| public void run() {
boolean quiesceRequested = false;
// A sleeper that sleeps for msgInterval.
Sleeper sleeper = new Sleeper(this.msgInterval, this.stopRequested);
try {
init(reportForDuty(sleeper));
long lastMsg = 0;
// Now ask master what it wants us to do and tell it what we have done
for (int tries = 0; !stopRequested.get() && isHealthy();) {
long now = System.currentTimeMillis();
if (lastMsg != 0 && (now - lastMsg) >= serverLeaseTimeout) {
// It has been way too long since we last reported to the master.
LOG.warn("unable to report to master for " + (now - lastMsg) +
" milliseconds - retrying");
}
if ((now - lastMsg) >= msgInterval) {
HMsg outboundArray[] = null;
synchronized(this.outboundMsgs) {
outboundArray =
this.outboundMsgs.toArray(new HMsg[outboundMsgs.size()]);
this.outboundMsgs.clear();
}
try {
doMetrics();
this.serverInfo.setLoad(new HServerLoad(requestCount.get(),
onlineRegions.size(), this.metrics.storefiles.get(),
this.metrics.memcacheSizeMB.get()));
this.requestCount.set(0);
HMsg msgs[] = hbaseMaster.regionServerReport(
serverInfo, outboundArray, getMostLoadedRegions());
lastMsg = System.currentTimeMillis();
if (this.quiesced.get() && onlineRegions.size() == 0) {
// We've just told the master we're exiting because we aren't
// serving any regions. So set the stop bit and exit.
LOG.info("Server quiesced and not serving any regions. " +
"Starting shutdown");
stopRequested.set(true);
this.outboundMsgs.clear();
continue;
}
// Queue up the HMaster's instruction stream for processing
boolean restart = false;
for(int i = 0;
!restart && !stopRequested.get() && i < msgs.length;
i++) {
LOG.info(msgs[i].toString());
switch(msgs[i].getType()) {
case MSG_CALL_SERVER_STARTUP:
// We the MSG_CALL_SERVER_STARTUP on startup but we can also
// get it when the master is panicing because for instance
// the HDFS has been yanked out from under it. Be wary of
// this message.
if (checkFileSystem()) {
closeAllRegions();
try {
log.closeAndDelete();
} catch (Exception e) {
LOG.error("error closing and deleting HLog", e);
}
try {
serverInfo.setStartCode(System.currentTimeMillis());
log = setupHLog();
this.logFlusher.setHLog(log);
} catch (IOException e) {
this.abortRequested = true;
this.stopRequested.set(true);
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("error restarting server", e);
break;
}
reportForDuty(sleeper);
restart = true;
} else {
LOG.fatal("file system available check failed. " +
"Shutting down server.");
}
break;
case MSG_REGIONSERVER_STOP:
stopRequested.set(true);
break;
case MSG_REGIONSERVER_QUIESCE:
if (!quiesceRequested) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
quiesceRequested = true;
}
break;
default:
if (fsOk) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
}
}
}
// Reset tries count if we had a successful transaction.
tries = 0;
if (restart || this.stopRequested.get()) {
toDo.clear();
continue;
}
} catch (Exception e) {
if (e instanceof IOException) {
e = RemoteExceptionHandler.checkIOException((IOException) e);
}
if (tries < this.numRetries) {
LOG.warn("Processing message (Retry: " + tries + ")", e);
tries++;
} else {
LOG.error("Exceeded max retries: " + this.numRetries, e);
checkFileSystem();
}
if (this.stopRequested.get()) {
LOG.info("Stop was requested, clearing the toDo " +
"despite of the exception");
toDo.clear();
continue;
}
}
}
// Do some housekeeping before going to sleep
housekeeping();
sleeper.sleep(lastMsg);
} // for
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (Throwable t) {
LOG.fatal("Unhandled exception. Aborting...", t);
abort();
}
RegionHistorian.getInstance().offline();
this.leases.closeAfterLeasesExpire();
this.worker.stop();
this.server.stop();
if (this.infoServer != null) {
LOG.info("Stopping infoServer");
try {
this.infoServer.stop();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Send interrupts to wake up threads if sleeping so they notice shutdown.
// TODO: Should we check they are alive? If OOME could have exited already
cacheFlusher.interruptIfNecessary();
logFlusher.interrupt();
compactSplitThread.interruptIfNecessary();
logRoller.interruptIfNecessary();
if (abortRequested) {
if (this.fsOk) {
// Only try to clean up if the file system is available
try {
if (this.log != null) {
this.log.close();
LOG.info("On abort, closed hlog");
}
} catch (IOException e) {
LOG.error("Unable to close log in abort",
RemoteExceptionHandler.checkIOException(e));
}
closeAllRegions(); // Don't leave any open file handles
}
LOG.info("aborting server at: " +
serverInfo.getServerAddress().toString());
} else {
ArrayList<HRegion> closedRegions = closeAllRegions();
try {
log.closeAndDelete();
} catch (IOException e) {
LOG.error("Close and delete failed",
RemoteExceptionHandler.checkIOException(e));
}
try {
HMsg[] exitMsg = new HMsg[closedRegions.size() + 1];
exitMsg[0] = HMsg.REPORT_EXITING;
// Tell the master what regions we are/were serving
int i = 1;
for (HRegion region: closedRegions) {
exitMsg[i++] = new HMsg(HMsg.Type.MSG_REPORT_CLOSE,
region.getRegionInfo());
}
LOG.info("telling master that region server is shutting down at: " +
serverInfo.getServerAddress().toString());
hbaseMaster.regionServerReport(serverInfo, exitMsg, (HRegionInfo[])null);
} catch (IOException e) {
LOG.warn("Failed to send exiting message to master: ",
RemoteExceptionHandler.checkIOException(e));
}
LOG.info("stopping server at: " +
serverInfo.getServerAddress().toString());
}
if (this.hbaseMaster != null) {
HbaseRPC.stopProxy(this.hbaseMaster);
this.hbaseMaster = null;
}
join();
LOG.info(Thread.currentThread().getName() + " exiting");
}
|
diff --git a/org.eclipse.text/src/org/eclipse/jface/text/link/InclusivePositionUpdater.java b/org.eclipse.text/src/org/eclipse/jface/text/link/InclusivePositionUpdater.java
index 6075d39ac..35dc529d5 100644
--- a/org.eclipse.text/src/org/eclipse/jface/text/link/InclusivePositionUpdater.java
+++ b/org.eclipse.text/src/org/eclipse/jface/text/link/InclusivePositionUpdater.java
@@ -1,104 +1,104 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.text.link;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.Position;
/**
* Position updater that takes any change in [position.offset, position.offset + position.length] as
* belonging to the position.
*
* @since 3.0
*/
public class InclusivePositionUpdater implements IPositionUpdater {
/** The position category. */
private final String fCategory;
/**
* Creates a new updater for the given <code>category</code>.
*
* @param category the new category.
*/
public InclusivePositionUpdater(String category) {
fCategory= category;
}
/*
* @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
*/
public void update(DocumentEvent event) {
int eventOffset= event.getOffset();
int eventOldLength= event.getLength();
int eventNewLength= event.getText() == null ? 0 : event.getText().length();
int deltaLength= eventNewLength - eventOldLength;
try {
Position[] positions= event.getDocument().getPositions(fCategory);
for (int i= 0; i != positions.length; i++) {
Position position= positions[i];
if (position.isDeleted())
continue;
int offset= position.getOffset();
int length= position.getLength();
int end= offset + length;
if (offset > eventOffset + eventOldLength)
// position comes way
// after change - shift
position.setOffset(offset + deltaLength);
else if (end < eventOffset)
// position comes way before change -
// leave alone
;
else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
// event completely internal to the position - adjust length
position.setLength(length + deltaLength);
} else if (offset < eventOffset) {
// event extends over end of position - adjust length
int newEnd= eventOffset + eventNewLength;
position.setLength(newEnd - offset);
} else if (end > eventOffset + eventOldLength) {
// event extends from before position into it - adjust offset
// and length
// offset becomes end of event, length ajusted acordingly
// we want to recycle the overlapping part
- int newOffset= eventOffset + eventNewLength;
- position.setOffset(newOffset);
- position.setLength(length + deltaLength);
+ position.setOffset(eventOffset);
+ int deleted= eventOffset + eventOldLength - offset;
+ position.setLength(length - deleted + eventNewLength);
} else {
// event consumes the position - delete it
position.delete();
}
}
} catch (BadPositionCategoryException e) {
// ignore and return
}
}
/**
* Returns the position category.
*
* @return the position category
*/
public String getCategory() {
return fCategory;
}
}
| true | true | public void update(DocumentEvent event) {
int eventOffset= event.getOffset();
int eventOldLength= event.getLength();
int eventNewLength= event.getText() == null ? 0 : event.getText().length();
int deltaLength= eventNewLength - eventOldLength;
try {
Position[] positions= event.getDocument().getPositions(fCategory);
for (int i= 0; i != positions.length; i++) {
Position position= positions[i];
if (position.isDeleted())
continue;
int offset= position.getOffset();
int length= position.getLength();
int end= offset + length;
if (offset > eventOffset + eventOldLength)
// position comes way
// after change - shift
position.setOffset(offset + deltaLength);
else if (end < eventOffset)
// position comes way before change -
// leave alone
;
else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
// event completely internal to the position - adjust length
position.setLength(length + deltaLength);
} else if (offset < eventOffset) {
// event extends over end of position - adjust length
int newEnd= eventOffset + eventNewLength;
position.setLength(newEnd - offset);
} else if (end > eventOffset + eventOldLength) {
// event extends from before position into it - adjust offset
// and length
// offset becomes end of event, length ajusted acordingly
// we want to recycle the overlapping part
int newOffset= eventOffset + eventNewLength;
position.setOffset(newOffset);
position.setLength(length + deltaLength);
} else {
// event consumes the position - delete it
position.delete();
}
}
} catch (BadPositionCategoryException e) {
// ignore and return
}
}
| public void update(DocumentEvent event) {
int eventOffset= event.getOffset();
int eventOldLength= event.getLength();
int eventNewLength= event.getText() == null ? 0 : event.getText().length();
int deltaLength= eventNewLength - eventOldLength;
try {
Position[] positions= event.getDocument().getPositions(fCategory);
for (int i= 0; i != positions.length; i++) {
Position position= positions[i];
if (position.isDeleted())
continue;
int offset= position.getOffset();
int length= position.getLength();
int end= offset + length;
if (offset > eventOffset + eventOldLength)
// position comes way
// after change - shift
position.setOffset(offset + deltaLength);
else if (end < eventOffset)
// position comes way before change -
// leave alone
;
else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
// event completely internal to the position - adjust length
position.setLength(length + deltaLength);
} else if (offset < eventOffset) {
// event extends over end of position - adjust length
int newEnd= eventOffset + eventNewLength;
position.setLength(newEnd - offset);
} else if (end > eventOffset + eventOldLength) {
// event extends from before position into it - adjust offset
// and length
// offset becomes end of event, length ajusted acordingly
// we want to recycle the overlapping part
position.setOffset(eventOffset);
int deleted= eventOffset + eventOldLength - offset;
position.setLength(length - deleted + eventNewLength);
} else {
// event consumes the position - delete it
position.delete();
}
}
} catch (BadPositionCategoryException e) {
// ignore and return
}
}
|
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelAutomationHelper.java b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelAutomationHelper.java
index 0579f4d3..eaea6e3e 100644
--- a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelAutomationHelper.java
+++ b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelAutomationHelper.java
@@ -1,205 +1,205 @@
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2003 Jonathan Halliday
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.panels;
import com.izforge.izpack.Pack;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.PanelAutomation;
import com.izforge.izpack.adaptator.IXMLElement;
import com.izforge.izpack.adaptator.impl.XMLElementImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* Functions to support automated usage of the PacksPanel
*
* @author Jonathan Halliday
* @author Julien Ponge
*/
public class PacksPanelAutomationHelper implements PanelAutomation
{
/**
* Asks to make the XML panel data.
*
* @param idata The installation data.
* @param panelRoot The XML tree to write the data in.
*/
public void makeXMLData(AutomatedInstallData idata, IXMLElement panelRoot)
{
// We add each pack to the panelRoot element
for (int i = 0; i < idata.availablePacks.size(); i++)
{
Pack pack = idata.availablePacks.get(i);
IXMLElement el = new XMLElementImpl("pack", panelRoot);
el.setAttribute("index", Integer.toString(i));
el.setAttribute("name", pack.name);
Boolean selected = Boolean.valueOf(idata.selectedPacks.contains(pack));
el.setAttribute("selected", selected.toString());
panelRoot.addChild(el);
}
}
/**
* Asks to run in the automated mode.
*
* @param idata The installation data.
* @param panelRoot The root of the panel data.
*/
public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot)
{
final class PInfo
{
private boolean _selected;
private int _index;
private String _name = "";
PInfo(boolean selected, String index, String name)
{
_selected = selected;
try
{
_index = Integer.valueOf(index).intValue();
}
catch (NumberFormatException e)
{
_index = -100;
}
if (name != null)
{
_name = name;
}
}
public boolean isSelected()
{
return _selected;
}
public boolean equals(int index)
{
return _index == index && _name.equals("");
}
public boolean equals(String name)
{
return _name.equals(name);
}
@Override
public String toString()
{
String retVal = "";
if (!_name.equals(""))
{
retVal = "Name: " + _name + " and ";
}
retVal += "Index: " + String.valueOf(_index);
return retVal;
}
}
List<PInfo> autoinstallPackInfoList = new ArrayList<PInfo>();
// We get the packs markups
Vector<IXMLElement> packList = panelRoot.getChildrenNamed("pack");
// Read all packs from the xml and remember them to merge it with the selected packs from
// install data
System.out.println("Read pack list from xml definition.");
int numberOfPacks = packList.size();
for (int packIndex = 0; packIndex < numberOfPacks; packIndex++)
{
IXMLElement pack = packList.get(packIndex);
String index = pack.getAttribute("index");
String name = pack.getAttribute("name");
final String selectedString = pack.getAttribute("selected");
boolean selected = selectedString.equalsIgnoreCase("true")
|| selectedString.equalsIgnoreCase("on");
final PInfo packInfo = new PInfo(selected, index, name);
autoinstallPackInfoList.add(packInfo);
System.out.println("Try to " + (selected ? "add to" : "remove from") + " selection ["
+ packInfo.toString() + "]");
}
// Now merge the selected pack from automated install data with the selected packs form
// autoinstall.xml
System.out.println("Modify pack selection.");
for (Pack pack : idata.availablePacks)
{
// Check if the pack is in the List of autoinstall.xml (search by name and index)
final int indexOfAvailablePack = idata.availablePacks.indexOf(pack);
for (PInfo packInfo : autoinstallPackInfoList)
{
// Check if we have a pack available that is referenced in autoinstall.xml
if ((packInfo.equals(pack.name)) || (packInfo.equals(indexOfAvailablePack)))
{
if (pack.required)
{
// Do not modify required packs
if (!packInfo.isSelected())
{
System.out.println("Pack [" + packInfo.toString()
+ "] must be installed because it is required!");
}
}
else
{
if (packInfo.isSelected())
{
// Check if the conditions allow to select the pack
if ((idata.selectedPacks.indexOf(pack) < 0)
&& (pack.id != null)
&& (!idata.getRules().canInstallPack(pack.id,
idata.getVariables())))
{
idata.selectedPacks.add(pack);
System.out.println("Pack [" + packInfo.toString()
+ "] added to selection.");
}
}
else
{
// Pack can be removed from selection because it is not required
idata.selectedPacks.remove(pack);
System.out.println("Pack [" + packInfo.toString()
+ "] removed from selection.");
}
}
break;
}
}
}
// Update panelRoot to reflect the changes made by the automation helper, panel validate or panel action
- for (int childIndex = panelRoot.getChildrenCount(); childIndex > 0; childIndex--)
+ for (int counter = panelRoot.getChildrenCount(); counter > 0; counter--)
{
- panelRoot.removeChild(panelRoot.getChildAtIndex(childIndex));
+ panelRoot.removeChild(panelRoot.getChildAtIndex(0));
}
makeXMLData(idata, panelRoot);
}
}
| false | true | public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot)
{
final class PInfo
{
private boolean _selected;
private int _index;
private String _name = "";
PInfo(boolean selected, String index, String name)
{
_selected = selected;
try
{
_index = Integer.valueOf(index).intValue();
}
catch (NumberFormatException e)
{
_index = -100;
}
if (name != null)
{
_name = name;
}
}
public boolean isSelected()
{
return _selected;
}
public boolean equals(int index)
{
return _index == index && _name.equals("");
}
public boolean equals(String name)
{
return _name.equals(name);
}
@Override
public String toString()
{
String retVal = "";
if (!_name.equals(""))
{
retVal = "Name: " + _name + " and ";
}
retVal += "Index: " + String.valueOf(_index);
return retVal;
}
}
List<PInfo> autoinstallPackInfoList = new ArrayList<PInfo>();
// We get the packs markups
Vector<IXMLElement> packList = panelRoot.getChildrenNamed("pack");
// Read all packs from the xml and remember them to merge it with the selected packs from
// install data
System.out.println("Read pack list from xml definition.");
int numberOfPacks = packList.size();
for (int packIndex = 0; packIndex < numberOfPacks; packIndex++)
{
IXMLElement pack = packList.get(packIndex);
String index = pack.getAttribute("index");
String name = pack.getAttribute("name");
final String selectedString = pack.getAttribute("selected");
boolean selected = selectedString.equalsIgnoreCase("true")
|| selectedString.equalsIgnoreCase("on");
final PInfo packInfo = new PInfo(selected, index, name);
autoinstallPackInfoList.add(packInfo);
System.out.println("Try to " + (selected ? "add to" : "remove from") + " selection ["
+ packInfo.toString() + "]");
}
// Now merge the selected pack from automated install data with the selected packs form
// autoinstall.xml
System.out.println("Modify pack selection.");
for (Pack pack : idata.availablePacks)
{
// Check if the pack is in the List of autoinstall.xml (search by name and index)
final int indexOfAvailablePack = idata.availablePacks.indexOf(pack);
for (PInfo packInfo : autoinstallPackInfoList)
{
// Check if we have a pack available that is referenced in autoinstall.xml
if ((packInfo.equals(pack.name)) || (packInfo.equals(indexOfAvailablePack)))
{
if (pack.required)
{
// Do not modify required packs
if (!packInfo.isSelected())
{
System.out.println("Pack [" + packInfo.toString()
+ "] must be installed because it is required!");
}
}
else
{
if (packInfo.isSelected())
{
// Check if the conditions allow to select the pack
if ((idata.selectedPacks.indexOf(pack) < 0)
&& (pack.id != null)
&& (!idata.getRules().canInstallPack(pack.id,
idata.getVariables())))
{
idata.selectedPacks.add(pack);
System.out.println("Pack [" + packInfo.toString()
+ "] added to selection.");
}
}
else
{
// Pack can be removed from selection because it is not required
idata.selectedPacks.remove(pack);
System.out.println("Pack [" + packInfo.toString()
+ "] removed from selection.");
}
}
break;
}
}
}
// Update panelRoot to reflect the changes made by the automation helper, panel validate or panel action
for (int childIndex = panelRoot.getChildrenCount(); childIndex > 0; childIndex--)
{
panelRoot.removeChild(panelRoot.getChildAtIndex(childIndex));
}
makeXMLData(idata, panelRoot);
}
| public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot)
{
final class PInfo
{
private boolean _selected;
private int _index;
private String _name = "";
PInfo(boolean selected, String index, String name)
{
_selected = selected;
try
{
_index = Integer.valueOf(index).intValue();
}
catch (NumberFormatException e)
{
_index = -100;
}
if (name != null)
{
_name = name;
}
}
public boolean isSelected()
{
return _selected;
}
public boolean equals(int index)
{
return _index == index && _name.equals("");
}
public boolean equals(String name)
{
return _name.equals(name);
}
@Override
public String toString()
{
String retVal = "";
if (!_name.equals(""))
{
retVal = "Name: " + _name + " and ";
}
retVal += "Index: " + String.valueOf(_index);
return retVal;
}
}
List<PInfo> autoinstallPackInfoList = new ArrayList<PInfo>();
// We get the packs markups
Vector<IXMLElement> packList = panelRoot.getChildrenNamed("pack");
// Read all packs from the xml and remember them to merge it with the selected packs from
// install data
System.out.println("Read pack list from xml definition.");
int numberOfPacks = packList.size();
for (int packIndex = 0; packIndex < numberOfPacks; packIndex++)
{
IXMLElement pack = packList.get(packIndex);
String index = pack.getAttribute("index");
String name = pack.getAttribute("name");
final String selectedString = pack.getAttribute("selected");
boolean selected = selectedString.equalsIgnoreCase("true")
|| selectedString.equalsIgnoreCase("on");
final PInfo packInfo = new PInfo(selected, index, name);
autoinstallPackInfoList.add(packInfo);
System.out.println("Try to " + (selected ? "add to" : "remove from") + " selection ["
+ packInfo.toString() + "]");
}
// Now merge the selected pack from automated install data with the selected packs form
// autoinstall.xml
System.out.println("Modify pack selection.");
for (Pack pack : idata.availablePacks)
{
// Check if the pack is in the List of autoinstall.xml (search by name and index)
final int indexOfAvailablePack = idata.availablePacks.indexOf(pack);
for (PInfo packInfo : autoinstallPackInfoList)
{
// Check if we have a pack available that is referenced in autoinstall.xml
if ((packInfo.equals(pack.name)) || (packInfo.equals(indexOfAvailablePack)))
{
if (pack.required)
{
// Do not modify required packs
if (!packInfo.isSelected())
{
System.out.println("Pack [" + packInfo.toString()
+ "] must be installed because it is required!");
}
}
else
{
if (packInfo.isSelected())
{
// Check if the conditions allow to select the pack
if ((idata.selectedPacks.indexOf(pack) < 0)
&& (pack.id != null)
&& (!idata.getRules().canInstallPack(pack.id,
idata.getVariables())))
{
idata.selectedPacks.add(pack);
System.out.println("Pack [" + packInfo.toString()
+ "] added to selection.");
}
}
else
{
// Pack can be removed from selection because it is not required
idata.selectedPacks.remove(pack);
System.out.println("Pack [" + packInfo.toString()
+ "] removed from selection.");
}
}
break;
}
}
}
// Update panelRoot to reflect the changes made by the automation helper, panel validate or panel action
for (int counter = panelRoot.getChildrenCount(); counter > 0; counter--)
{
panelRoot.removeChild(panelRoot.getChildAtIndex(0));
}
makeXMLData(idata, panelRoot);
}
|
diff --git a/WEB-INF/src/org/cdlib/xtf/textIndexer/TextIndexer.java b/WEB-INF/src/org/cdlib/xtf/textIndexer/TextIndexer.java
index ddf7d149..eae6507f 100644
--- a/WEB-INF/src/org/cdlib/xtf/textIndexer/TextIndexer.java
+++ b/WEB-INF/src/org/cdlib/xtf/textIndexer/TextIndexer.java
@@ -1,440 +1,442 @@
package org.cdlib.xtf.textIndexer;
/**
* Copyright (c) 2004, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of California 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.
*/
import java.io.*;
import org.cdlib.xtf.util.*;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* This class is the main class for the TextIndexer program. <br><br>
*
* Internally, this class retrieves command line arguments, and processes them
* in order to index source XML files into one or more Lucene databases. The
* command line arguments required by the TextIndexer program are as follows:
*
* <blockquote dir=ltr style="MARGIN-RIGHT: 0px"><code>
* <b>TextIndexer -config</b> <font color=#0000ff><i>CfgFilePath</i></font>
* { {<b>-clean</b>|<b>-incremental</b>}?
* {<b>-trace errors</b>|<b>warnings</b>|<b>info</b>|<b>debug</b>}?
* <b>-index</b> <font color=#0000ff><i>IndexName</i></font> }+
* </b></code></blockquote>
*
* The <code>-config</code> argument identifies an XML configuration file that
* defines one or more indices to be created, updated, or deleted. This argument
* must be the first argument passed, and it must be passed only once. For a
* complete description of the contents of the configuration file, see the
* {@link XMLConfigParser} class.<br><br>
*
* The <code>-clean</code> / <code>-incremental</code> argument is an optional
* argument that specifies whether Lucene indices should be rebuilt from scratch
* (<code>-clean</code>) or should be updated (<code>-incremental</code>). If
* this argument is not specified, the default behavior is incremental. <br><br>
*
* The <code>-buildlazy</code> / <code>-nobuildlazy</code> argument is an
* optional argument that specifies whether the indexer should build a
* persistent ("lazy") version of each document during the indexing process.
* The lazy files are stored in the index directory, and they speed dynaXML
* access later. If this argument is not specified, the default behavior is
* to build lazy versions of the documents. <br><br>
*
* The <code>-optimize</code> / <code>-nooptimize</code> argument is an optional
* argument that specifies whether the indexer should optimize the indexes after
* they are built. Optimization improves query speed, but can take a very long
* time to complete depending on the index size. If this argument is not
* specified, the default behavior is to optimize. <br><br>
*
* The <code>-trace</code> argument is an optional argument that sets the level
* of output displayed by the text indexer. The output levels are defined as
* follows:
*
* <blockquote dir=ltr style="MARGIN-RIGHT: 0px">
* <code>errors</code> - Only error messages are displayed. <br>
* <code>warnings</code> - Both error and warning messages are displayed. <br>
* <code>info</code> - Error, warning, and informational messages are displayed. <br>
* <code>debug</code> - Low level debug output is displayed in addition to
* error, warning and informational messages.<br><br>
* </blockquote>
*
* If this argument is not specified, the TextIndexer defaults to displaying
* informational (<code>info</code>) level messages.<br><br>
*
* The <code>-index</code> argument identifies the name of the index to be
* created/updated. The name must be one of the index names contained in the
* configuration file specified as the first parameter. As is mentioned above,
* the <code>-config</code> parameter must be specified first. After that,
* the remaining arguments may be used one or more times to update a single
* index or multiple indices. <br><br><br>
*
* A simple example of a command line parameters for the TextIndexer might
* look like this:
* <br><br>
*
* <code><blockquote dir=ltr style="MARGIN-RIGHT: 0px"><b>
* TextIndexer -config IdxConfig.xml -clean -index AllText
* </b></blockquote></code>
*
* This example assumes that the config file is called <code>IdxConfig.xml</code>,
* that the config file contains an entry for an index called <b>AllText</b>, and
* that the user wants the index to be rebuilt from scratch (because of the
* <code>-clean</code> argument. <br><br>
*
*/
public class TextIndexer
{
//////////////////////////////////////////////////////////////////////////////
/** Main entry-point for the Text Indexer. <br><br>
*
* This function takes the command line arguments passed and uses them to
* create or update the specified indices with the specified source text.
* <br><br>
*
* @param args Command line arguments to process. The command line
* arguments required by the TextIndexer program are as follows:
*
* <blockquote dir=ltr style="MARGIN-RIGHT: 0px"><code>
* <b>TextIndexer -config</b> <font color=#0000ff><i>CfgFilePath</i></font>
* { {<b>-clean</b>|<b>-incremental</b>}?
* {<b>-trace errors</b>|<b>warnings</b>|<b>info</b>|<b>debug</b>}?
* <b>-index</b> <font color=#0000ff><i>IndexName</i></font> }+
* </b></code></blockquote>
*
* For a complete description of each command line argument, see the
* {@link TextIndexer} class description.
* <br><br>
*
*/
public static void main( String[] args )
{
try {
IndexerConfig cfgInfo = new IndexerConfig();
XMLConfigParser cfgParser = new XMLConfigParser();
SrcTreeProcessor srcTreeProcessor = new SrcTreeProcessor();
IdxTreeCleaner indexCleaner = new IdxTreeCleaner();
int startArg = 0;
boolean showUsage = false;
boolean firstIndex = true;
long startTime = System.currentTimeMillis();
// Regardless of whether we succeed or fail, say our name.
Trace.info( "TextIndexer v" + 1.7 );
Trace.info( "" );
Trace.tab();
// Make sure the XTF_HOME environment variable is specified.
cfgInfo.xtfHomePath = System.getProperty( "xtf.home" );
if( cfgInfo.xtfHomePath == null || cfgInfo.xtfHomePath.length() == 0 ) {
Trace.error( "Error: xtf.home property not found" );
System.exit( 1 );
}
cfgInfo.xtfHomePath = Path.normalizePath( cfgInfo.xtfHomePath );
if( !new File(cfgInfo.xtfHomePath).isDirectory() ) {
Trace.error( "Error: xtf.home directory \"" + cfgInfo.xtfHomePath +
"\" does not exist or cannot be read." );
System.exit( 1 );
}
// Perform indexing for each index specified.
for(;;) {
// The minimum set of arguments consists of the name of an index
// to update. If we don't get at least that two, we will show the
// usage text and bail.
//
if( args.length < 2 )
showUsage = true;
// We have enough arguments, so...
else {
// Read the command line arguments until we find what we
// need to do some work, or until we run out.
//
int ret = cfgInfo.readCmdLine( args, startArg );
// If we didn't find enough command line arguments...
if( ret == -1 ) {
// And this is the first time we've visited the command
// line arguments, avoid trying to doing work and just
// display the usage text. Otherwise, we're done.
//
if( startArg == 0 ) showUsage = true;
else break;
} // if( ret == -1 )
// We did find enough command line arguments, so...
//
else {
// Make sure the configuration path is absolute
if( !(new File(cfgInfo.cfgFilePath).isAbsolute()) ) {
cfgInfo.cfgFilePath = Path.resolveRelOrAbs(
cfgInfo.xtfHomePath, cfgInfo.cfgFilePath);
}
// Get the configuration for the index specified by the
// current command line arguments.
//
if( cfgParser.configure(cfgInfo) < 0 ) {
Trace.error( "Error: index '" +
cfgInfo.indexInfo.indexName +
"' not found\n" );
System.exit( 1 );
}
// Since we're starting a new index, reset the 'must
// clean' flag so that the index will get cleaned if
// requested.
//
cfgInfo.mustClean = cfgInfo.clean;
// Set the tracing level specified by the user.
Trace.setOutputLevel( cfgInfo.traceLevel );
} // else( ret != -1 )
// Save the new start argument for the next time.
startArg = ret;
} // else( args.length >= 4 )
// If the config file was not okay, print a message and bail out.
if( showUsage ) {
// Do so...
Trace.error( "Usage: textIndexer {options} -index indexname" );
Trace.error( "Available options:" );
Trace.tab();
Trace.error( "-config <configfile> Default: -config textIndexer.conf" );
Trace.error( "-incremental|-clean Default: -incremental" );
Trace.error( "-optimize|-nooptimize Default: -optimize" );
Trace.error( "-trace errors|warnings|info|debug Default: -trace info" );
Trace.error( "-dir <subdir> Default: (all data directories)" );
Trace.error( "-buildlazy|-nobuildlazy Default: -buildlazy" );
Trace.error( "-updatespell|-noupdatespell Default: -updatespell" );
Trace.error( "\n" );
Trace.untab();
// And then bail.
System.exit( 1 );
} // if( showUsage )
// Begin processing.
File xtfHomeFile = new File( cfgInfo.xtfHomePath );
// If this is our first time through, purge any incomplete
// documents from the indices, and tell the user what
// we're doing.
//
if( firstIndex ) {
if( !cfgInfo.mustClean ) {
// Clean all indices below the root index directory.
File idxRootDir = new File(Path.resolveRelOrAbs(
xtfHomeFile,
cfgInfo.indexInfo.indexPath) );
Trace.info("");
Trace.info( "Purging Incomplete Documents From Indexes:" );
Trace.tab();
indexCleaner.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
Trace.info("");
Trace.info( "Indexing New/Updated Documents:" );
Trace.tab();
// Indicate that the next pass through this loop is not
// the first one.
//
firstIndex = false;
}
// Say what index we're working on.
Trace.info( "Index: \"" + cfgInfo.indexInfo.indexName +"\"" );
// And if we're debugging, say some more about the index.
if( Trace.getOutputLevel() == Trace.debug )
Trace.more( " [ Chunk Size = " +
cfgInfo.indexInfo.getChunkSize() +
", Overlap = " +
cfgInfo.indexInfo.getChunkOvlp() +
" ]" );
Trace.tab();
// Start at the root directory specified by the config file.
String srcRootDir = Path.resolveRelOrAbs( xtfHomeFile,
cfgInfo.indexInfo.sourcePath );
// If a sub-directory was specified, limit to just that.
if( cfgInfo.indexInfo.subDir != null ) {
srcRootDir = Path.resolveRelOrAbs(
srcRootDir,
Path.normalizePath(cfgInfo.indexInfo.subDir) );
}
// Process everything below it.
srcTreeProcessor.open( cfgInfo );
srcTreeProcessor.processDir( new File(srcRootDir), 0 );
srcTreeProcessor.close();
// Cull files which are present in the index but missing
// from the filesystem.
//
IdxTreeCuller culler = new IdxTreeCuller();
Trace.info( "Removing Missing Documents From Index:" );
Trace.tab();
culler.cullIndex( new File(cfgInfo.xtfHomePath),
cfgInfo.indexInfo );
Trace.untab();
Trace.info( "Done." );
Trace.untab();
Trace.info( "Done." );
} // for(;;)
Trace.untab();
Trace.info( "Done." );
// Optimize the indices, now that we're all done processing them.
if( cfgInfo.optimize ) {
// Create a tree culler.
IdxTreeOptimizer optimizer = new IdxTreeOptimizer();
Trace.info("");
Trace.info( "Optimizing Index:" );
Trace.tab();
- File idxRootDir = new File( cfgInfo.indexInfo.indexPath );
+ File idxRootDir = new File( Path.resolveRelOrAbs(
+ cfgInfo.xtfHomePath, cfgInfo.indexInfo.indexPath) );
optimizer.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
else {
Trace.info("");
Trace.info( "Skipping Optimization Pass." );
}
// Create spelling dictionaries, now that we're done indexing.
if( cfgInfo.updateSpellDict ) {
// Create a tree culler.
IdxTreeDictMaker dictMaker = new IdxTreeDictMaker();
Trace.info("");
Trace.info( "Updating Spellcheck Dictionary:" );
Trace.tab();
- File idxRootDir = new File( cfgInfo.indexInfo.indexPath );
+ File idxRootDir = new File( Path.resolveRelOrAbs(
+ cfgInfo.xtfHomePath, cfgInfo.indexInfo.indexPath) );
dictMaker.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
else {
Trace.info("");
Trace.info( "Skipping Spellcheck Dictionary Pass." );
}
Trace.untab();
Trace.info("");
long timeMsec = System.currentTimeMillis() - startTime;
long timeSec = timeMsec / 1000;
long timeMin = timeSec / 60;
long timeHour = timeMin / 60;
Trace.info( "Total time: " );
if( timeHour > 0 ) {
String ending = (timeHour == 1) ? "" : "s";
Trace.more( Trace.info, timeHour + " hour" + ending + ", " );
}
if( timeMin > 0 ) {
String ending = ((timeMin % 60) == 1) ? "" : "s";
Trace.more( Trace.info, (timeMin % 60) + " minute" + ending + ", " );
}
String ending = ((timeSec % 60) == 1) ? "" : "s";
Trace.more( Trace.info, (timeSec % 60) + " second" + ending + "." );
Trace.info( "Indexing complete." );
Trace.info("");
} // try
// Log any unhandled exceptions.
catch( Throwable t ) {
Trace.clearTabs();
Trace.error( "*** Error: " + t.getClass() );
Trace.error( "" );
t.printStackTrace( System.out );
Trace.error( "Indexing Process Aborted." );
System.exit( 1 );
}
// Exit successfully.
return;
} // main()
} // class textIndexer
| false | true | public static void main( String[] args )
{
try {
IndexerConfig cfgInfo = new IndexerConfig();
XMLConfigParser cfgParser = new XMLConfigParser();
SrcTreeProcessor srcTreeProcessor = new SrcTreeProcessor();
IdxTreeCleaner indexCleaner = new IdxTreeCleaner();
int startArg = 0;
boolean showUsage = false;
boolean firstIndex = true;
long startTime = System.currentTimeMillis();
// Regardless of whether we succeed or fail, say our name.
Trace.info( "TextIndexer v" + 1.7 );
Trace.info( "" );
Trace.tab();
// Make sure the XTF_HOME environment variable is specified.
cfgInfo.xtfHomePath = System.getProperty( "xtf.home" );
if( cfgInfo.xtfHomePath == null || cfgInfo.xtfHomePath.length() == 0 ) {
Trace.error( "Error: xtf.home property not found" );
System.exit( 1 );
}
cfgInfo.xtfHomePath = Path.normalizePath( cfgInfo.xtfHomePath );
if( !new File(cfgInfo.xtfHomePath).isDirectory() ) {
Trace.error( "Error: xtf.home directory \"" + cfgInfo.xtfHomePath +
"\" does not exist or cannot be read." );
System.exit( 1 );
}
// Perform indexing for each index specified.
for(;;) {
// The minimum set of arguments consists of the name of an index
// to update. If we don't get at least that two, we will show the
// usage text and bail.
//
if( args.length < 2 )
showUsage = true;
// We have enough arguments, so...
else {
// Read the command line arguments until we find what we
// need to do some work, or until we run out.
//
int ret = cfgInfo.readCmdLine( args, startArg );
// If we didn't find enough command line arguments...
if( ret == -1 ) {
// And this is the first time we've visited the command
// line arguments, avoid trying to doing work and just
// display the usage text. Otherwise, we're done.
//
if( startArg == 0 ) showUsage = true;
else break;
} // if( ret == -1 )
// We did find enough command line arguments, so...
//
else {
// Make sure the configuration path is absolute
if( !(new File(cfgInfo.cfgFilePath).isAbsolute()) ) {
cfgInfo.cfgFilePath = Path.resolveRelOrAbs(
cfgInfo.xtfHomePath, cfgInfo.cfgFilePath);
}
// Get the configuration for the index specified by the
// current command line arguments.
//
if( cfgParser.configure(cfgInfo) < 0 ) {
Trace.error( "Error: index '" +
cfgInfo.indexInfo.indexName +
"' not found\n" );
System.exit( 1 );
}
// Since we're starting a new index, reset the 'must
// clean' flag so that the index will get cleaned if
// requested.
//
cfgInfo.mustClean = cfgInfo.clean;
// Set the tracing level specified by the user.
Trace.setOutputLevel( cfgInfo.traceLevel );
} // else( ret != -1 )
// Save the new start argument for the next time.
startArg = ret;
} // else( args.length >= 4 )
// If the config file was not okay, print a message and bail out.
if( showUsage ) {
// Do so...
Trace.error( "Usage: textIndexer {options} -index indexname" );
Trace.error( "Available options:" );
Trace.tab();
Trace.error( "-config <configfile> Default: -config textIndexer.conf" );
Trace.error( "-incremental|-clean Default: -incremental" );
Trace.error( "-optimize|-nooptimize Default: -optimize" );
Trace.error( "-trace errors|warnings|info|debug Default: -trace info" );
Trace.error( "-dir <subdir> Default: (all data directories)" );
Trace.error( "-buildlazy|-nobuildlazy Default: -buildlazy" );
Trace.error( "-updatespell|-noupdatespell Default: -updatespell" );
Trace.error( "\n" );
Trace.untab();
// And then bail.
System.exit( 1 );
} // if( showUsage )
// Begin processing.
File xtfHomeFile = new File( cfgInfo.xtfHomePath );
// If this is our first time through, purge any incomplete
// documents from the indices, and tell the user what
// we're doing.
//
if( firstIndex ) {
if( !cfgInfo.mustClean ) {
// Clean all indices below the root index directory.
File idxRootDir = new File(Path.resolveRelOrAbs(
xtfHomeFile,
cfgInfo.indexInfo.indexPath) );
Trace.info("");
Trace.info( "Purging Incomplete Documents From Indexes:" );
Trace.tab();
indexCleaner.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
Trace.info("");
Trace.info( "Indexing New/Updated Documents:" );
Trace.tab();
// Indicate that the next pass through this loop is not
// the first one.
//
firstIndex = false;
}
// Say what index we're working on.
Trace.info( "Index: \"" + cfgInfo.indexInfo.indexName +"\"" );
// And if we're debugging, say some more about the index.
if( Trace.getOutputLevel() == Trace.debug )
Trace.more( " [ Chunk Size = " +
cfgInfo.indexInfo.getChunkSize() +
", Overlap = " +
cfgInfo.indexInfo.getChunkOvlp() +
" ]" );
Trace.tab();
// Start at the root directory specified by the config file.
String srcRootDir = Path.resolveRelOrAbs( xtfHomeFile,
cfgInfo.indexInfo.sourcePath );
// If a sub-directory was specified, limit to just that.
if( cfgInfo.indexInfo.subDir != null ) {
srcRootDir = Path.resolveRelOrAbs(
srcRootDir,
Path.normalizePath(cfgInfo.indexInfo.subDir) );
}
// Process everything below it.
srcTreeProcessor.open( cfgInfo );
srcTreeProcessor.processDir( new File(srcRootDir), 0 );
srcTreeProcessor.close();
// Cull files which are present in the index but missing
// from the filesystem.
//
IdxTreeCuller culler = new IdxTreeCuller();
Trace.info( "Removing Missing Documents From Index:" );
Trace.tab();
culler.cullIndex( new File(cfgInfo.xtfHomePath),
cfgInfo.indexInfo );
Trace.untab();
Trace.info( "Done." );
Trace.untab();
Trace.info( "Done." );
} // for(;;)
Trace.untab();
Trace.info( "Done." );
// Optimize the indices, now that we're all done processing them.
if( cfgInfo.optimize ) {
// Create a tree culler.
IdxTreeOptimizer optimizer = new IdxTreeOptimizer();
Trace.info("");
Trace.info( "Optimizing Index:" );
Trace.tab();
File idxRootDir = new File( cfgInfo.indexInfo.indexPath );
optimizer.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
else {
Trace.info("");
Trace.info( "Skipping Optimization Pass." );
}
// Create spelling dictionaries, now that we're done indexing.
if( cfgInfo.updateSpellDict ) {
// Create a tree culler.
IdxTreeDictMaker dictMaker = new IdxTreeDictMaker();
Trace.info("");
Trace.info( "Updating Spellcheck Dictionary:" );
Trace.tab();
File idxRootDir = new File( cfgInfo.indexInfo.indexPath );
dictMaker.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
else {
Trace.info("");
Trace.info( "Skipping Spellcheck Dictionary Pass." );
}
Trace.untab();
Trace.info("");
long timeMsec = System.currentTimeMillis() - startTime;
long timeSec = timeMsec / 1000;
long timeMin = timeSec / 60;
long timeHour = timeMin / 60;
Trace.info( "Total time: " );
if( timeHour > 0 ) {
String ending = (timeHour == 1) ? "" : "s";
Trace.more( Trace.info, timeHour + " hour" + ending + ", " );
}
if( timeMin > 0 ) {
String ending = ((timeMin % 60) == 1) ? "" : "s";
Trace.more( Trace.info, (timeMin % 60) + " minute" + ending + ", " );
}
String ending = ((timeSec % 60) == 1) ? "" : "s";
Trace.more( Trace.info, (timeSec % 60) + " second" + ending + "." );
Trace.info( "Indexing complete." );
Trace.info("");
} // try
// Log any unhandled exceptions.
catch( Throwable t ) {
Trace.clearTabs();
Trace.error( "*** Error: " + t.getClass() );
Trace.error( "" );
t.printStackTrace( System.out );
Trace.error( "Indexing Process Aborted." );
System.exit( 1 );
}
// Exit successfully.
return;
} // main()
| public static void main( String[] args )
{
try {
IndexerConfig cfgInfo = new IndexerConfig();
XMLConfigParser cfgParser = new XMLConfigParser();
SrcTreeProcessor srcTreeProcessor = new SrcTreeProcessor();
IdxTreeCleaner indexCleaner = new IdxTreeCleaner();
int startArg = 0;
boolean showUsage = false;
boolean firstIndex = true;
long startTime = System.currentTimeMillis();
// Regardless of whether we succeed or fail, say our name.
Trace.info( "TextIndexer v" + 1.7 );
Trace.info( "" );
Trace.tab();
// Make sure the XTF_HOME environment variable is specified.
cfgInfo.xtfHomePath = System.getProperty( "xtf.home" );
if( cfgInfo.xtfHomePath == null || cfgInfo.xtfHomePath.length() == 0 ) {
Trace.error( "Error: xtf.home property not found" );
System.exit( 1 );
}
cfgInfo.xtfHomePath = Path.normalizePath( cfgInfo.xtfHomePath );
if( !new File(cfgInfo.xtfHomePath).isDirectory() ) {
Trace.error( "Error: xtf.home directory \"" + cfgInfo.xtfHomePath +
"\" does not exist or cannot be read." );
System.exit( 1 );
}
// Perform indexing for each index specified.
for(;;) {
// The minimum set of arguments consists of the name of an index
// to update. If we don't get at least that two, we will show the
// usage text and bail.
//
if( args.length < 2 )
showUsage = true;
// We have enough arguments, so...
else {
// Read the command line arguments until we find what we
// need to do some work, or until we run out.
//
int ret = cfgInfo.readCmdLine( args, startArg );
// If we didn't find enough command line arguments...
if( ret == -1 ) {
// And this is the first time we've visited the command
// line arguments, avoid trying to doing work and just
// display the usage text. Otherwise, we're done.
//
if( startArg == 0 ) showUsage = true;
else break;
} // if( ret == -1 )
// We did find enough command line arguments, so...
//
else {
// Make sure the configuration path is absolute
if( !(new File(cfgInfo.cfgFilePath).isAbsolute()) ) {
cfgInfo.cfgFilePath = Path.resolveRelOrAbs(
cfgInfo.xtfHomePath, cfgInfo.cfgFilePath);
}
// Get the configuration for the index specified by the
// current command line arguments.
//
if( cfgParser.configure(cfgInfo) < 0 ) {
Trace.error( "Error: index '" +
cfgInfo.indexInfo.indexName +
"' not found\n" );
System.exit( 1 );
}
// Since we're starting a new index, reset the 'must
// clean' flag so that the index will get cleaned if
// requested.
//
cfgInfo.mustClean = cfgInfo.clean;
// Set the tracing level specified by the user.
Trace.setOutputLevel( cfgInfo.traceLevel );
} // else( ret != -1 )
// Save the new start argument for the next time.
startArg = ret;
} // else( args.length >= 4 )
// If the config file was not okay, print a message and bail out.
if( showUsage ) {
// Do so...
Trace.error( "Usage: textIndexer {options} -index indexname" );
Trace.error( "Available options:" );
Trace.tab();
Trace.error( "-config <configfile> Default: -config textIndexer.conf" );
Trace.error( "-incremental|-clean Default: -incremental" );
Trace.error( "-optimize|-nooptimize Default: -optimize" );
Trace.error( "-trace errors|warnings|info|debug Default: -trace info" );
Trace.error( "-dir <subdir> Default: (all data directories)" );
Trace.error( "-buildlazy|-nobuildlazy Default: -buildlazy" );
Trace.error( "-updatespell|-noupdatespell Default: -updatespell" );
Trace.error( "\n" );
Trace.untab();
// And then bail.
System.exit( 1 );
} // if( showUsage )
// Begin processing.
File xtfHomeFile = new File( cfgInfo.xtfHomePath );
// If this is our first time through, purge any incomplete
// documents from the indices, and tell the user what
// we're doing.
//
if( firstIndex ) {
if( !cfgInfo.mustClean ) {
// Clean all indices below the root index directory.
File idxRootDir = new File(Path.resolveRelOrAbs(
xtfHomeFile,
cfgInfo.indexInfo.indexPath) );
Trace.info("");
Trace.info( "Purging Incomplete Documents From Indexes:" );
Trace.tab();
indexCleaner.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
Trace.info("");
Trace.info( "Indexing New/Updated Documents:" );
Trace.tab();
// Indicate that the next pass through this loop is not
// the first one.
//
firstIndex = false;
}
// Say what index we're working on.
Trace.info( "Index: \"" + cfgInfo.indexInfo.indexName +"\"" );
// And if we're debugging, say some more about the index.
if( Trace.getOutputLevel() == Trace.debug )
Trace.more( " [ Chunk Size = " +
cfgInfo.indexInfo.getChunkSize() +
", Overlap = " +
cfgInfo.indexInfo.getChunkOvlp() +
" ]" );
Trace.tab();
// Start at the root directory specified by the config file.
String srcRootDir = Path.resolveRelOrAbs( xtfHomeFile,
cfgInfo.indexInfo.sourcePath );
// If a sub-directory was specified, limit to just that.
if( cfgInfo.indexInfo.subDir != null ) {
srcRootDir = Path.resolveRelOrAbs(
srcRootDir,
Path.normalizePath(cfgInfo.indexInfo.subDir) );
}
// Process everything below it.
srcTreeProcessor.open( cfgInfo );
srcTreeProcessor.processDir( new File(srcRootDir), 0 );
srcTreeProcessor.close();
// Cull files which are present in the index but missing
// from the filesystem.
//
IdxTreeCuller culler = new IdxTreeCuller();
Trace.info( "Removing Missing Documents From Index:" );
Trace.tab();
culler.cullIndex( new File(cfgInfo.xtfHomePath),
cfgInfo.indexInfo );
Trace.untab();
Trace.info( "Done." );
Trace.untab();
Trace.info( "Done." );
} // for(;;)
Trace.untab();
Trace.info( "Done." );
// Optimize the indices, now that we're all done processing them.
if( cfgInfo.optimize ) {
// Create a tree culler.
IdxTreeOptimizer optimizer = new IdxTreeOptimizer();
Trace.info("");
Trace.info( "Optimizing Index:" );
Trace.tab();
File idxRootDir = new File( Path.resolveRelOrAbs(
cfgInfo.xtfHomePath, cfgInfo.indexInfo.indexPath) );
optimizer.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
else {
Trace.info("");
Trace.info( "Skipping Optimization Pass." );
}
// Create spelling dictionaries, now that we're done indexing.
if( cfgInfo.updateSpellDict ) {
// Create a tree culler.
IdxTreeDictMaker dictMaker = new IdxTreeDictMaker();
Trace.info("");
Trace.info( "Updating Spellcheck Dictionary:" );
Trace.tab();
File idxRootDir = new File( Path.resolveRelOrAbs(
cfgInfo.xtfHomePath, cfgInfo.indexInfo.indexPath) );
dictMaker.processDir( idxRootDir );
Trace.untab();
Trace.info( "Done." );
}
else {
Trace.info("");
Trace.info( "Skipping Spellcheck Dictionary Pass." );
}
Trace.untab();
Trace.info("");
long timeMsec = System.currentTimeMillis() - startTime;
long timeSec = timeMsec / 1000;
long timeMin = timeSec / 60;
long timeHour = timeMin / 60;
Trace.info( "Total time: " );
if( timeHour > 0 ) {
String ending = (timeHour == 1) ? "" : "s";
Trace.more( Trace.info, timeHour + " hour" + ending + ", " );
}
if( timeMin > 0 ) {
String ending = ((timeMin % 60) == 1) ? "" : "s";
Trace.more( Trace.info, (timeMin % 60) + " minute" + ending + ", " );
}
String ending = ((timeSec % 60) == 1) ? "" : "s";
Trace.more( Trace.info, (timeSec % 60) + " second" + ending + "." );
Trace.info( "Indexing complete." );
Trace.info("");
} // try
// Log any unhandled exceptions.
catch( Throwable t ) {
Trace.clearTabs();
Trace.error( "*** Error: " + t.getClass() );
Trace.error( "" );
t.printStackTrace( System.out );
Trace.error( "Indexing Process Aborted." );
System.exit( 1 );
}
// Exit successfully.
return;
} // main()
|
diff --git a/src/main/java/com/philihp/weblabora/model/CommandUse.java b/src/main/java/com/philihp/weblabora/model/CommandUse.java
index d25c631..1abe5f1 100644
--- a/src/main/java/com/philihp/weblabora/model/CommandUse.java
+++ b/src/main/java/com/philihp/weblabora/model/CommandUse.java
@@ -1,60 +1,68 @@
package com.philihp.weblabora.model;
import static com.philihp.weblabora.model.TerrainTypeEnum.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.philihp.weblabora.model.building.*;
public class CommandUse implements MoveCommand, InvalidDuringSettlement {
@Override
public void execute(Board board, CommandParameters params)
throws WeblaboraException {
String buildingId = params.get(0);
UsageParam usageParam = null;
boolean usingPrior = params.getSuffix().contains("*");
switch (params.size()) {
case 1:
usageParam = new UsageParam("");
break;
case 2:
usageParam = new UsageParam(params.get(1));
break;
default:
usageParam = new UsageParam("");
- for (int i = 0; params.get(i * 2 + 1) != null
- && params.get(i * 2 + 2) != null; i++) {
- usageParam.pushCoordinate(
- Integer.parseInt(params.get(i * 2 + 1)),
- Integer.parseInt(params.get(i * 2 + 2)));
+ Integer x = null;
+ for (int i = 1; i < params.size(); i++) {
+ if(x == null) {
+ x = Integer.parseInt(params.get(i));
+ }
+ else {
+ usageParam.pushCoordinate(
+ x, Integer.parseInt(params.get(i)));
+ x = null;
+ }
+ }
+ if(x != null) {
+ throw new WeblaboraException("Coordinate building usage parameters must come in pairs. Parsed "+x+" for the x, but no y number.");
}
break;
}
execute(board, BuildingEnum.valueOf(buildingId), usageParam, usingPrior, params.getPlaceClergyman());
System.out.println("Using " + buildingId + " with " + usageParam);
}
public static void execute(Board board, BuildingEnum buildingId,
UsageParam param, boolean usingPrior, boolean placeClergyman) throws WeblaboraException {
Building building = board.findBuildingInstance(buildingId);
Player buildingOwner = building.getLocation().getLandscape().getPlayer();
Terrain location = building.getLocation();
if (placeClergyman) {
if (usingPrior) {
buildingOwner.placePrior(location);
} else {
buildingOwner.placeClergyman(location);
}
}
building.use(board, param);
}
}
| true | true | public void execute(Board board, CommandParameters params)
throws WeblaboraException {
String buildingId = params.get(0);
UsageParam usageParam = null;
boolean usingPrior = params.getSuffix().contains("*");
switch (params.size()) {
case 1:
usageParam = new UsageParam("");
break;
case 2:
usageParam = new UsageParam(params.get(1));
break;
default:
usageParam = new UsageParam("");
for (int i = 0; params.get(i * 2 + 1) != null
&& params.get(i * 2 + 2) != null; i++) {
usageParam.pushCoordinate(
Integer.parseInt(params.get(i * 2 + 1)),
Integer.parseInt(params.get(i * 2 + 2)));
}
break;
}
execute(board, BuildingEnum.valueOf(buildingId), usageParam, usingPrior, params.getPlaceClergyman());
System.out.println("Using " + buildingId + " with " + usageParam);
}
| public void execute(Board board, CommandParameters params)
throws WeblaboraException {
String buildingId = params.get(0);
UsageParam usageParam = null;
boolean usingPrior = params.getSuffix().contains("*");
switch (params.size()) {
case 1:
usageParam = new UsageParam("");
break;
case 2:
usageParam = new UsageParam(params.get(1));
break;
default:
usageParam = new UsageParam("");
Integer x = null;
for (int i = 1; i < params.size(); i++) {
if(x == null) {
x = Integer.parseInt(params.get(i));
}
else {
usageParam.pushCoordinate(
x, Integer.parseInt(params.get(i)));
x = null;
}
}
if(x != null) {
throw new WeblaboraException("Coordinate building usage parameters must come in pairs. Parsed "+x+" for the x, but no y number.");
}
break;
}
execute(board, BuildingEnum.valueOf(buildingId), usageParam, usingPrior, params.getPlaceClergyman());
System.out.println("Using " + buildingId + " with " + usageParam);
}
|
diff --git a/src/main/java/br/org/indt/ndg/mobile/settings/SettingsStructure.java b/src/main/java/br/org/indt/ndg/mobile/settings/SettingsStructure.java
index 384b404..611e03e 100644
--- a/src/main/java/br/org/indt/ndg/mobile/settings/SettingsStructure.java
+++ b/src/main/java/br/org/indt/ndg/mobile/settings/SettingsStructure.java
@@ -1,425 +1,424 @@
package br.org.indt.ndg.mobile.settings;
import br.org.indt.ndg.lwuit.extended.DateField;
import br.org.indt.ndg.mobile.AppMIDlet;
import java.io.PrintStream;
import br.org.indt.ndg.mobile.Utils;
import br.org.indt.ndg.mobile.settings.PhotoSettings.PhotoResolution;
import br.org.indt.ndg.mobile.structures.Language;
import java.util.Vector;
/**
* READ FIRST!
* To add a new setting You need to perform 5 steps:
* 1) Implement Setter and Getter for new setting
* 2) Add default setting value constant
* 3) Apply the constant to initial value of new setting
* 4) Add setting default value to createDefaultSettings method
* 5) Update SettingsHandler
* @author tomasz.baniak
*/
public class SettingsStructure {
public static final int NOT_REGISTERED = 0;
public static final int REGISTERED = 1;
/* Default values */
private static final boolean DEFAULT_USE_COMPRESSION = true;
private static final int DEFAULT_SPLASH_TIME = 8000;
private static final int DEFAULT_IS_REGISTERED = NOT_REGISTERED;
private static final boolean DEFAULT_GPS = true;
private static final boolean DEFAULT_GEO_TAGGING = true;
private static final int DEFAULT_PHOTO_RESULUTION_ID = 0;
private static final int DEFAULT_STYLE_ID = 0;
private static final boolean DEFAULT_LOG_SUPPORT = false;
private static final int DEFAULT_DATE_FORMAT_ID = DateField.DDMMYYYY;
private static final boolean DEFAULT_ENCRYPTION = false;
private static final int DEFAULT_ENCRIPTION_CONFIGURED = 0;
private static final String DEFAULT_LANGUAGE_NAME = "Default (English)";
private static final String DEFAULT_LANGUAGE_LOCALE = "en-GB";
private String server_normal_url;
private String server_compress_url;
private String localization_serving_url;
private String server_results_openrosa_url;
private String receive_survey_url;
private String update_check_url;
private String register_imei_url;
private String language_list_url;
private boolean compress_state = DEFAULT_USE_COMPRESSION;
private int splash_time = DEFAULT_SPLASH_TIME;
private int isRegistered_flag = DEFAULT_IS_REGISTERED;
private boolean gps_configured = DEFAULT_GPS;
private boolean geoTagging_configured = DEFAULT_GEO_TAGGING;
private int selectedResolution = DEFAULT_PHOTO_RESULUTION_ID;
private int selectedStyle = DEFAULT_STYLE_ID;
private boolean logSupport = DEFAULT_LOG_SUPPORT;
private int dateFormatId = DEFAULT_DATE_FORMAT_ID;
private int encryptionConfigured = DEFAULT_ENCRIPTION_CONFIGURED;
private boolean encryption = DEFAULT_ENCRYPTION;
private String language = DEFAULT_LANGUAGE_NAME;
private String appVersion;
private Language defaultLanguage = new Language(DEFAULT_LANGUAGE_NAME, DEFAULT_LANGUAGE_LOCALE);
private Vector languages = new Vector();
public SettingsStructure() {
initializeDefaultRuntimeSettings();
}
private void initializeDefaultRuntimeSettings() {
String defaultServerUrl = AppMIDlet.getInstance().getDefaultServerUrl();
String[] defaultServlets = AppMIDlet.getInstance().getDefaultServlets();
server_normal_url = defaultServerUrl + defaultServlets[0] + defaultServlets[1];
server_compress_url = defaultServerUrl + defaultServlets[0] + defaultServlets[1];
localization_serving_url = defaultServerUrl + defaultServlets[0] + defaultServlets[6];
language_list_url = defaultServerUrl + defaultServlets[0] + defaultServlets[7];
server_results_openrosa_url = defaultServerUrl + defaultServlets[0] + defaultServlets[5];
receive_survey_url = defaultServerUrl + defaultServlets[0] + defaultServlets[2];
update_check_url = defaultServerUrl + defaultServlets[0] + defaultServlets[3];
register_imei_url = defaultServerUrl + defaultServlets[0] + defaultServlets[4];
appVersion = AppMIDlet.getInstance().getAppVersion();
languages.addElement(defaultLanguage);
}
public void createDefaultSettings(PrintStream _out) {
String defaultServerUrl = AppMIDlet.getInstance().getDefaultServerUrl();
String[] defaultServlets = AppMIDlet.getInstance().getDefaultServlets();
// Reset to default values
setLanguage(defaultLanguage.getLocale());
setRegisteredFlag(DEFAULT_IS_REGISTERED);
setSplashTime(DEFAULT_SPLASH_TIME);
setGpsConfigured(DEFAULT_GPS);
setGeoTaggingConfigured(DEFAULT_GEO_TAGGING);
setPhotoResolutionId(DEFAULT_PHOTO_RESULUTION_ID);
setStyleId(DEFAULT_STYLE_ID);
setLogSupport(DEFAULT_LOG_SUPPORT);
setServerCompression(DEFAULT_USE_COMPRESSION);
setDateFormatId(DEFAULT_DATE_FORMAT_ID);
setEncryptionConfigured(DEFAULT_ENCRIPTION_CONFIGURED);
setEncryption(DEFAULT_ENCRYPTION);
setServerUrl_Compress(defaultServerUrl + defaultServlets[0] + defaultServlets[1]);
setServerUrl_Normal(defaultServerUrl + defaultServlets[0] + defaultServlets[1]);
setServerUrl_ResultsOpenRosa(defaultServerUrl + defaultServlets[0] + defaultServlets[5]);
setReceiveSurveyURL(defaultServerUrl + defaultServlets[0] + defaultServlets[2]);
setUpdateCheckURL(defaultServerUrl + defaultServlets[0] + defaultServlets[3]);
setRegisterIMEIUrl(defaultServerUrl + defaultServlets[0] + defaultServlets[4]);
setLocalizationServingURL(defaultServerUrl + defaultServlets[0] + defaultServlets[6]);
setLanguageListURL(defaultServerUrl + defaultServlets[0] + defaultServlets[7]);
setAppVersion(AppMIDlet.getInstance().getAppVersion());
- languages.addElement(defaultLanguage);
saveSettings(_out);
}
public void saveSettings(PrintStream _out) {
_out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
_out.print("<settings");
_out.print(" registered=\"" + getRegisteredFlag() + "\"");
_out.print(" splash=\"" + getSplashTime() + "\"");
_out.print(" language=\"" + getLanguage() + "\"");
_out.println(" showEncryptionScreen=\""+ (isEncryptionConfigured() ? "1" : "0") + "\">");
writeGpsSettings(_out);
writeGeoTaggingSettings(_out);
writePhotoResolutionSettings(_out);
writeStyleSettings(_out);
writeLogSettings(_out);
writeServerSettings(_out);
writeLanguageSettings(_out);
writeVersionSettings(_out);
writeDateFormatSettings(_out);
writeEncryption(_out);
_out.println("</settings>");
}
public void writeServerSettings(PrintStream _out) {
_out.print("<server compression=\"");
if (compress_state) _out.println("on\">");
else _out.println("off\">");
_out.println("<url_compress>" + server_compress_url + "</url_compress>");
_out.println("<url_normal>" + server_normal_url + "</url_normal>");
_out.println("<url_results_openrosa>" + server_results_openrosa_url + "</url_results_openrosa>");
_out.println("<url_receive_survey>" + receive_survey_url + "</url_receive_survey>");
_out.println("<url_update_check>" + update_check_url + "</url_update_check>");
_out.println("<url_register_imei>" + register_imei_url + "</url_register_imei>");
_out.println("<url_localization_serving>" + localization_serving_url + "</url_localization_serving>");
_out.println("<url_language_list>" + language_list_url + "</url_language_list>");
_out.println("</server>");
}
private void writeLanguageSettings(PrintStream _out) {
if(languages != null)
{
_out.println("<languages>");
StringBuffer languageString = null;
for(int i = 0 ; i < languages.size(); i++)
{
languageString = new StringBuffer();
languageString.append("<language name=\"").append( ((Language)languages.elementAt(i)).getLangName());
languageString.append("\" locale= \"").append(((Language)languages.elementAt(i)).getLocale()).append("\"/>");
_out.println(languageString);
}
_out.println("</languages>");
}
}
public void writeGpsSettings(PrintStream _out) {
_out.print("<gps configured=\"");
if (gps_configured) _out.println("yes\"/>");
else _out.println("no\"/>");
}
public void writeGeoTaggingSettings(PrintStream _out) {
_out.print("<geotagging configured=\"");
if (geoTagging_configured) _out.println("yes\"/>");
else _out.println("no\"/>");
}
void writeLogSettings(PrintStream _out) {
String strLogSupport = logSupport ? "yes" : "no";
_out.println("<log active=\"" + strLogSupport + "\"" + "/>");
}
void writeVersionSettings(PrintStream _out) {
_out.println("<version application=\"" + appVersion + "\"/>");
}
void writePhotoResolutionSettings(PrintStream output) {
output.print("<photoResolution configId=\"");
output.print( String.valueOf(selectedResolution) );
output.println( "\"/>" );
}
void writeStyleSettings(PrintStream output) {
output.print("<style id=\"");
output.print( String.valueOf(selectedStyle) );
output.println( "\"/>" );
}
void writeDateFormatSettings(PrintStream output){
output.print("<dateFormat id=\"");
output.print( String.valueOf(dateFormatId) );
output.println( "\"/>" );
}
public void writeEncryption(PrintStream _out) {
_out.print("<encryption enabled=\"");
if (encryption) _out.println("yes\"/>");
else _out.println("no\"/>");
}
void setLogSupport(boolean _logSupport) {
logSupport = _logSupport;
}
public boolean getLogSupport(){
return logSupport;
}
public void setLanguage(String _lang) {
language = _lang;
}
public String getLanguage() {
if(language == null || language.equals("")){
language = defaultLanguage.getLocale();
}
return language;
}
void setAppVersion(String _ver) {
appVersion = _ver;
}
public String getAppVersion() {
return appVersion;
}
void setUpdateCheckURL(String _url) {
update_check_url = _url;
}
public String getUpdateCheckURL() {
return update_check_url;
}
public void setServerCompression(boolean _state) {
compress_state = _state;
}
public boolean getServerCompression() {
return compress_state;
}
public void setServerUrl_Compress(String _url) {
server_compress_url = _url;
}
public void setServerUrl_Normal(String _url) {
server_normal_url = _url;
}
public void setServerUrl_ResultsOpenRosa(String _url) {
server_results_openrosa_url = _url;
}
public String getDateFormatString(){
//TODO format to string;
return "0";
}
public int getDateFormatId(){
return dateFormatId;
}
public void setDateFormatId(int _id){
dateFormatId = _id;
}
public String getServerUrl( int surveyFormat ) {
String result = null;
switch (surveyFormat) {
case Utils.NDG_FORMAT:
if ( compress_state )
result = server_compress_url;
else
result = server_normal_url;
break;
case Utils.OPEN_ROSA_FORMAT:
result = server_results_openrosa_url;
break;
default:
throw new RuntimeException("Unsupported Survey Format");
}
return result;
}
public void setReceiveSurveyURL(String url){
receive_survey_url = url;
}
public String getReceiveSurveyURL(){
return receive_survey_url;
}
public String getLocalizationServingURL()
{
return localization_serving_url;
}
public void setLocalizationServingURL(String url){
localization_serving_url = url;
}
public String getLanguageListURL()
{
return language_list_url;
}
public void setLanguageListURL(String url)
{
language_list_url = url;
}
public String getRegisterIMEIUrl() {
return register_imei_url;
}
public void setRegisterIMEIUrl(String url) {
this.register_imei_url = url;
}
public void setRegisteredFlag(int _flag) {
isRegistered_flag = _flag;
}
public int getRegisteredFlag() {
return isRegistered_flag;
}
public void setSplashTime(int _time) {
splash_time = _time;
}
public int getSplashTime() {
return splash_time;
}
public void setGpsConfigured(boolean _state) {
gps_configured = _state;
}
public boolean getGpsConfigured() {
return gps_configured;
}
public void setGeoTaggingConfigured(boolean _state) {
geoTagging_configured = _state;
}
public boolean getGeoTaggingConfigured() {
return geoTagging_configured;
}
public void setPhotoResolutionId(int _resConf ) {
selectedResolution = _resConf;
}
public int getPhotoResolutionId() {
return selectedResolution;
}
public void setStyleId(int styleId ) {
selectedStyle = styleId;
}
public int getStyleId() {
return selectedStyle;
}
public PhotoResolution getPhotoResolution() {
return PhotoSettings.getInstance().getPhotoResolution( selectedResolution );
}
public String[] getResolutionList() {
return PhotoSettings.getInstance().getResolutionList();
}
public boolean isEncryptionConfigured() {
return encryptionConfigured== 1 ? true : false;
}
public void setEncryptionConfigured(int encryption) {
encryptionConfigured = encryption;
}
public boolean getEncryption() {
return encryption;
}
public void setEncryption(boolean encrypt) {
encryption = encrypt;
}
public Vector getLanguages() {
return languages;
}
public void setLanguages(Vector languages) {
this.languages = languages;
}
public Language getDefaultLanguage(){
return defaultLanguage;
}
}
| true | true | public void createDefaultSettings(PrintStream _out) {
String defaultServerUrl = AppMIDlet.getInstance().getDefaultServerUrl();
String[] defaultServlets = AppMIDlet.getInstance().getDefaultServlets();
// Reset to default values
setLanguage(defaultLanguage.getLocale());
setRegisteredFlag(DEFAULT_IS_REGISTERED);
setSplashTime(DEFAULT_SPLASH_TIME);
setGpsConfigured(DEFAULT_GPS);
setGeoTaggingConfigured(DEFAULT_GEO_TAGGING);
setPhotoResolutionId(DEFAULT_PHOTO_RESULUTION_ID);
setStyleId(DEFAULT_STYLE_ID);
setLogSupport(DEFAULT_LOG_SUPPORT);
setServerCompression(DEFAULT_USE_COMPRESSION);
setDateFormatId(DEFAULT_DATE_FORMAT_ID);
setEncryptionConfigured(DEFAULT_ENCRIPTION_CONFIGURED);
setEncryption(DEFAULT_ENCRYPTION);
setServerUrl_Compress(defaultServerUrl + defaultServlets[0] + defaultServlets[1]);
setServerUrl_Normal(defaultServerUrl + defaultServlets[0] + defaultServlets[1]);
setServerUrl_ResultsOpenRosa(defaultServerUrl + defaultServlets[0] + defaultServlets[5]);
setReceiveSurveyURL(defaultServerUrl + defaultServlets[0] + defaultServlets[2]);
setUpdateCheckURL(defaultServerUrl + defaultServlets[0] + defaultServlets[3]);
setRegisterIMEIUrl(defaultServerUrl + defaultServlets[0] + defaultServlets[4]);
setLocalizationServingURL(defaultServerUrl + defaultServlets[0] + defaultServlets[6]);
setLanguageListURL(defaultServerUrl + defaultServlets[0] + defaultServlets[7]);
setAppVersion(AppMIDlet.getInstance().getAppVersion());
languages.addElement(defaultLanguage);
saveSettings(_out);
}
| public void createDefaultSettings(PrintStream _out) {
String defaultServerUrl = AppMIDlet.getInstance().getDefaultServerUrl();
String[] defaultServlets = AppMIDlet.getInstance().getDefaultServlets();
// Reset to default values
setLanguage(defaultLanguage.getLocale());
setRegisteredFlag(DEFAULT_IS_REGISTERED);
setSplashTime(DEFAULT_SPLASH_TIME);
setGpsConfigured(DEFAULT_GPS);
setGeoTaggingConfigured(DEFAULT_GEO_TAGGING);
setPhotoResolutionId(DEFAULT_PHOTO_RESULUTION_ID);
setStyleId(DEFAULT_STYLE_ID);
setLogSupport(DEFAULT_LOG_SUPPORT);
setServerCompression(DEFAULT_USE_COMPRESSION);
setDateFormatId(DEFAULT_DATE_FORMAT_ID);
setEncryptionConfigured(DEFAULT_ENCRIPTION_CONFIGURED);
setEncryption(DEFAULT_ENCRYPTION);
setServerUrl_Compress(defaultServerUrl + defaultServlets[0] + defaultServlets[1]);
setServerUrl_Normal(defaultServerUrl + defaultServlets[0] + defaultServlets[1]);
setServerUrl_ResultsOpenRosa(defaultServerUrl + defaultServlets[0] + defaultServlets[5]);
setReceiveSurveyURL(defaultServerUrl + defaultServlets[0] + defaultServlets[2]);
setUpdateCheckURL(defaultServerUrl + defaultServlets[0] + defaultServlets[3]);
setRegisterIMEIUrl(defaultServerUrl + defaultServlets[0] + defaultServlets[4]);
setLocalizationServingURL(defaultServerUrl + defaultServlets[0] + defaultServlets[6]);
setLanguageListURL(defaultServerUrl + defaultServlets[0] + defaultServlets[7]);
setAppVersion(AppMIDlet.getInstance().getAppVersion());
saveSettings(_out);
}
|
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java
index 79d65476..742ea9c3 100644
--- a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java
+++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java
@@ -1,527 +1,528 @@
package ch.cern.atlas.apvs.client.ui;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.cern.atlas.apvs.client.ClientFactory;
import ch.cern.atlas.apvs.client.domain.Ternary;
import ch.cern.atlas.apvs.client.event.ConnectionStatusChangedRemoteEvent;
import ch.cern.atlas.apvs.client.event.SelectPtuEvent;
import ch.cern.atlas.apvs.client.event.SelectTabEvent;
import ch.cern.atlas.apvs.client.service.SortOrder;
import ch.cern.atlas.apvs.client.widget.ActionHeader;
import ch.cern.atlas.apvs.client.widget.ClickableHtmlColumn;
import ch.cern.atlas.apvs.client.widget.ClickableTextColumn;
import ch.cern.atlas.apvs.client.widget.CompositeHeader;
import ch.cern.atlas.apvs.client.widget.GlassPanel;
import ch.cern.atlas.apvs.client.widget.PagerHeader;
import ch.cern.atlas.apvs.client.widget.PagerHeader.TextLocation;
import ch.cern.atlas.apvs.client.widget.ScrolledDataGrid;
import ch.cern.atlas.apvs.client.widget.UpdateScheduler;
import ch.cern.atlas.apvs.domain.Event;
import ch.cern.atlas.apvs.ptu.shared.EventChangedEvent;
import ch.cern.atlas.apvs.ptu.shared.PtuClientConstants;
import com.google.gwt.cell.client.ActionCell.Delegate;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo;
import com.google.gwt.user.cellview.client.TextHeader;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.web.bindery.event.shared.EventBus;
public class EventView extends GlassPanel implements Module {
private Logger log = LoggerFactory.getLogger(getClass().getName());
private EventBus cmdBus;
private String ptuId;
private String measurementName;
private ScrolledDataGrid<Event> table = new ScrolledDataGrid<Event>();
private ScrollPanel scrollPanel;
private PagerHeader pager;
private ActionHeader update;
private boolean showUpdate;
private ClickableTextColumn<Event> date;
private String ptuHeader;
private CompositeHeader compositeFooter;
private ClickableTextColumn<Event> ptu;
private String nameHeader;
private ClickableHtmlColumn<Event> name;
private boolean selectable = false;
private boolean sortable = true;
private UpdateScheduler scheduler = new UpdateScheduler(this);
protected Ternary daqOk = Ternary.Unknown;
protected Ternary databaseOk = Ternary.Unknown;
public EventView() {
}
@SuppressWarnings("unchecked")
@Override
public boolean configure(Element element,
final ClientFactory clientFactory, Arguments args) {
String height = args.getArg(0);
if (args.size() > 1) {
cmdBus = clientFactory.getEventBus(args.getArg(1));
}
table.setSize("100%", height);
table.setEmptyTableWidget(new Label("No Events"));
pager = new PagerHeader(TextLocation.LEFT);
pager.setDisplay(table);
pager.setNextPageButtonsDisabled(true);
update = new ActionHeader("Update", new Delegate<String>() {
@Override
public void execute(String object) {
pager.setPage(0);
scrollPanel.setVerticalScrollPosition(scrollPanel
.getMinimumHorizontalScrollPosition());
+ table.getColumnSortList().clear();
table.getColumnSortList().push(new ColumnSortInfo(date, false));
scheduler.update();
}
});
update.setVisible(false);
compositeFooter = new CompositeHeader(
pager.getHeader(), update);
final TextArea msg = new TextArea();
// FIXME, not sure how to handle scroll bar and paging
// add(msg, NORTH);
setWidth("100%");
add(table, CENTER);
scrollPanel = table.getScrollPanel();
scrollPanel.addScrollHandler(new ScrollHandler() {
int line = 0;
@Override
public void onScroll(ScrollEvent event) {
msg.setText(msg.getText() + "\n" + line + " "
+ event.toDebugString() + " "
+ scrollPanel.getVerticalScrollPosition() + " "
+ scrollPanel.getMinimumVerticalScrollPosition() + " "
+ scrollPanel.getMaximumVerticalScrollPosition());
msg.getElement().setScrollTop(
msg.getElement().getScrollHeight());
line++;
if (scrollPanel.getVerticalScrollPosition() == scrollPanel
.getMinimumVerticalScrollPosition()) {
scheduler.update();
}
}
});
AsyncDataProvider<Event> dataProvider = new AsyncDataProvider<Event>() {
@Override
protected void onRangeChanged(HasData<Event> display) {
clientFactory.getEventService().getRowCount(ptuId,
measurementName, new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
table.setRowCount(result);
}
@Override
public void onFailure(Throwable caught) {
table.setRowCount(0);
}
});
final Range range = display.getVisibleRange();
final ColumnSortList sortList = table.getColumnSortList();
SortOrder[] order = new SortOrder[sortList.size()];
for (int i = 0; i < sortList.size(); i++) {
ColumnSortInfo info = sortList.get(i);
order[i] = new SortOrder(info.getColumn()
.getDataStoreName(), info.isAscending());
}
if (order.length == 0) {
order = new SortOrder[1];
order[0] = new SortOrder("tbl_events.datetime", false);
}
clientFactory.getEventService().getTableData(range, order,
ptuId, measurementName,
new AsyncCallback<List<Event>>() {
@Override
public void onSuccess(List<Event> result) {
table.setRowData(range.getStart(), result);
}
@Override
public void onFailure(Throwable caught) {
log.warn("RPC DB FAILED " + caught);
table.setRowCount(0);
}
});
}
};
// Table
dataProvider.addDataDisplay(table);
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
// Subscriptions
ConnectionStatusChangedRemoteEvent.subscribe(
clientFactory.getRemoteEventBus(),
new ConnectionStatusChangedRemoteEvent.Handler() {
@Override
public void onConnectionStatusChanged(
ConnectionStatusChangedRemoteEvent event) {
switch (event.getConnection()) {
case daq:
daqOk = event.getStatus();
break;
case database:
databaseOk = event.getStatus();
break;
default:
break;
}
showGlass(daqOk.not().or(databaseOk.not()).isTrue());
}
});
EventChangedEvent.register(clientFactory.getRemoteEventBus(),
new EventChangedEvent.Handler() {
@Override
public void onEventChanged(EventChangedEvent e) {
Event event = e.getEvent();
if (event == null)
return;
if (((ptuId == null) || event.getPtuId().equals(ptuId))
&& ((measurementName == null) || event
.getName().equals(measurementName))) {
showUpdate = true;
scheduler.update();
}
}
});
if (cmdBus != null) {
SelectPtuEvent.subscribe(cmdBus, new SelectPtuEvent.Handler() {
@Override
public void onPtuSelected(SelectPtuEvent event) {
ptuId = event.getPtuId();
showUpdate = true;
scheduler.update();
}
});
SelectMeasurementEvent.subscribe(cmdBus,
new SelectMeasurementEvent.Handler() {
@Override
public void onSelection(SelectMeasurementEvent event) {
measurementName = event.getName();
showUpdate = true;
scheduler.update();
}
});
// FIXME #189
SelectTabEvent.subscribe(cmdBus, new SelectTabEvent.Handler() {
@Override
public void onTabSelected(SelectTabEvent event) {
if (event.getTab().equals("Summary")) {
showUpdate = true;
scheduler.update();
}
}
});
}
// DATE and TIME (1)
date = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return PtuClientConstants.dateFormat.format(object.getDate());
}
@Override
public String getDataStoreName() {
return "tbl_events.datetime";
}
};
date.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
date.setSortable(sortable);
if (selectable) {
date.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(date, new TextHeader("Date / Time"), compositeFooter);
table.getColumnSortList().push(new ColumnSortInfo(date, false));
// PtuID (2)
ptu = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getPtuId();
}
@Override
public String getDataStoreName() {
return "tbl_devices.name";
}
};
ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptu.setSortable(sortable);
if (selectable) {
ptu.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
ptuHeader = "PTU ID";
table.addColumn(ptu, new TextHeader(ptuHeader), compositeFooter);
// Name (3)
name = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getName();
}
@Override
public String getDataStoreName() {
return "tbl_events.sensor";
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
nameHeader = "Name";
table.addColumn(name, new TextHeader(nameHeader), compositeFooter);
// EventType
ClickableTextColumn<Event> eventType = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getEventType();
}
@Override
public String getDataStoreName() {
return "tbl_events.event_type";
}
};
eventType.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
eventType.setSortable(sortable);
if (selectable) {
eventType.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(eventType, "EventType");
// Value
ClickableTextColumn<Event> value = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getValue() != null ? object.getValue().toString() : "";
}
@Override
public String getDataStoreName() {
return "tbl_events.value";
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(value, new TextHeader("Value"));
// Threshold
ClickableTextColumn<Event> threshold = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getTheshold() != null ? object.getTheshold().toString() : "";
}
@Override
public String getDataStoreName() {
return "tbl_events.threshold";
}
};
threshold.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
threshold.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(threshold, "Threshold");
// Unit
ClickableHtmlColumn<Event> unit = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getUnit();
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(unit, "Unit");
// Selection
if (selectable) {
final SingleSelectionModel<Event> selectionModel = new SingleSelectionModel<Event>();
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Event m = selectionModel.getSelectedObject();
log.info(m + " " + event.getSource());
}
});
}
return true;
}
private boolean needsUpdate() {
if (showUpdate) {
ColumnSortList sortList = table.getColumnSortList();
ColumnSortInfo sortInfo = sortList.size() > 0 ? sortList.get(0)
: null;
if (sortInfo == null) {
return true;
}
if (!sortInfo.getColumn().equals(date)) {
return true;
}
if (sortInfo.isAscending()) {
return true;
}
showUpdate = (scrollPanel.getVerticalScrollPosition() != scrollPanel
.getMinimumVerticalScrollPosition())
|| (pager.getPage() != pager.getPageStart());
return showUpdate;
}
return false;
}
private void selectEvent(Event event) {
}
@Override
public boolean update() {
// enable / disable columns
if (table.getColumnIndex(ptu) >= 0) {
if (ptuId != null) {
table.removeColumn(ptu);
}
} else {
if (ptuId == null) {
// add Ptu Column
table.insertColumn(1, ptu, new TextHeader(ptuHeader), compositeFooter);
}
}
if (table.getColumnIndex(name) >= 0) {
if (measurementName != null) {
table.removeColumn(name);
}
} else {
if (measurementName == null) {
// add Name column
table.insertColumn(2, name, nameHeader);
}
}
// show or hide update button
update.setVisible(needsUpdate());
// Re-sort the table
// RangeChangeEvent.fire(table, table.getVisibleRange());
table.redraw();
return false;
}
}
| true | true | public boolean configure(Element element,
final ClientFactory clientFactory, Arguments args) {
String height = args.getArg(0);
if (args.size() > 1) {
cmdBus = clientFactory.getEventBus(args.getArg(1));
}
table.setSize("100%", height);
table.setEmptyTableWidget(new Label("No Events"));
pager = new PagerHeader(TextLocation.LEFT);
pager.setDisplay(table);
pager.setNextPageButtonsDisabled(true);
update = new ActionHeader("Update", new Delegate<String>() {
@Override
public void execute(String object) {
pager.setPage(0);
scrollPanel.setVerticalScrollPosition(scrollPanel
.getMinimumHorizontalScrollPosition());
table.getColumnSortList().push(new ColumnSortInfo(date, false));
scheduler.update();
}
});
update.setVisible(false);
compositeFooter = new CompositeHeader(
pager.getHeader(), update);
final TextArea msg = new TextArea();
// FIXME, not sure how to handle scroll bar and paging
// add(msg, NORTH);
setWidth("100%");
add(table, CENTER);
scrollPanel = table.getScrollPanel();
scrollPanel.addScrollHandler(new ScrollHandler() {
int line = 0;
@Override
public void onScroll(ScrollEvent event) {
msg.setText(msg.getText() + "\n" + line + " "
+ event.toDebugString() + " "
+ scrollPanel.getVerticalScrollPosition() + " "
+ scrollPanel.getMinimumVerticalScrollPosition() + " "
+ scrollPanel.getMaximumVerticalScrollPosition());
msg.getElement().setScrollTop(
msg.getElement().getScrollHeight());
line++;
if (scrollPanel.getVerticalScrollPosition() == scrollPanel
.getMinimumVerticalScrollPosition()) {
scheduler.update();
}
}
});
AsyncDataProvider<Event> dataProvider = new AsyncDataProvider<Event>() {
@Override
protected void onRangeChanged(HasData<Event> display) {
clientFactory.getEventService().getRowCount(ptuId,
measurementName, new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
table.setRowCount(result);
}
@Override
public void onFailure(Throwable caught) {
table.setRowCount(0);
}
});
final Range range = display.getVisibleRange();
final ColumnSortList sortList = table.getColumnSortList();
SortOrder[] order = new SortOrder[sortList.size()];
for (int i = 0; i < sortList.size(); i++) {
ColumnSortInfo info = sortList.get(i);
order[i] = new SortOrder(info.getColumn()
.getDataStoreName(), info.isAscending());
}
if (order.length == 0) {
order = new SortOrder[1];
order[0] = new SortOrder("tbl_events.datetime", false);
}
clientFactory.getEventService().getTableData(range, order,
ptuId, measurementName,
new AsyncCallback<List<Event>>() {
@Override
public void onSuccess(List<Event> result) {
table.setRowData(range.getStart(), result);
}
@Override
public void onFailure(Throwable caught) {
log.warn("RPC DB FAILED " + caught);
table.setRowCount(0);
}
});
}
};
// Table
dataProvider.addDataDisplay(table);
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
// Subscriptions
ConnectionStatusChangedRemoteEvent.subscribe(
clientFactory.getRemoteEventBus(),
new ConnectionStatusChangedRemoteEvent.Handler() {
@Override
public void onConnectionStatusChanged(
ConnectionStatusChangedRemoteEvent event) {
switch (event.getConnection()) {
case daq:
daqOk = event.getStatus();
break;
case database:
databaseOk = event.getStatus();
break;
default:
break;
}
showGlass(daqOk.not().or(databaseOk.not()).isTrue());
}
});
EventChangedEvent.register(clientFactory.getRemoteEventBus(),
new EventChangedEvent.Handler() {
@Override
public void onEventChanged(EventChangedEvent e) {
Event event = e.getEvent();
if (event == null)
return;
if (((ptuId == null) || event.getPtuId().equals(ptuId))
&& ((measurementName == null) || event
.getName().equals(measurementName))) {
showUpdate = true;
scheduler.update();
}
}
});
if (cmdBus != null) {
SelectPtuEvent.subscribe(cmdBus, new SelectPtuEvent.Handler() {
@Override
public void onPtuSelected(SelectPtuEvent event) {
ptuId = event.getPtuId();
showUpdate = true;
scheduler.update();
}
});
SelectMeasurementEvent.subscribe(cmdBus,
new SelectMeasurementEvent.Handler() {
@Override
public void onSelection(SelectMeasurementEvent event) {
measurementName = event.getName();
showUpdate = true;
scheduler.update();
}
});
// FIXME #189
SelectTabEvent.subscribe(cmdBus, new SelectTabEvent.Handler() {
@Override
public void onTabSelected(SelectTabEvent event) {
if (event.getTab().equals("Summary")) {
showUpdate = true;
scheduler.update();
}
}
});
}
// DATE and TIME (1)
date = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return PtuClientConstants.dateFormat.format(object.getDate());
}
@Override
public String getDataStoreName() {
return "tbl_events.datetime";
}
};
date.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
date.setSortable(sortable);
if (selectable) {
date.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(date, new TextHeader("Date / Time"), compositeFooter);
table.getColumnSortList().push(new ColumnSortInfo(date, false));
// PtuID (2)
ptu = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getPtuId();
}
@Override
public String getDataStoreName() {
return "tbl_devices.name";
}
};
ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptu.setSortable(sortable);
if (selectable) {
ptu.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
ptuHeader = "PTU ID";
table.addColumn(ptu, new TextHeader(ptuHeader), compositeFooter);
// Name (3)
name = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getName();
}
@Override
public String getDataStoreName() {
return "tbl_events.sensor";
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
nameHeader = "Name";
table.addColumn(name, new TextHeader(nameHeader), compositeFooter);
// EventType
ClickableTextColumn<Event> eventType = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getEventType();
}
@Override
public String getDataStoreName() {
return "tbl_events.event_type";
}
};
eventType.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
eventType.setSortable(sortable);
if (selectable) {
eventType.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(eventType, "EventType");
// Value
ClickableTextColumn<Event> value = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getValue() != null ? object.getValue().toString() : "";
}
@Override
public String getDataStoreName() {
return "tbl_events.value";
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(value, new TextHeader("Value"));
// Threshold
ClickableTextColumn<Event> threshold = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getTheshold() != null ? object.getTheshold().toString() : "";
}
@Override
public String getDataStoreName() {
return "tbl_events.threshold";
}
};
threshold.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
threshold.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(threshold, "Threshold");
// Unit
ClickableHtmlColumn<Event> unit = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getUnit();
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(unit, "Unit");
// Selection
if (selectable) {
final SingleSelectionModel<Event> selectionModel = new SingleSelectionModel<Event>();
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Event m = selectionModel.getSelectedObject();
log.info(m + " " + event.getSource());
}
});
}
return true;
}
| public boolean configure(Element element,
final ClientFactory clientFactory, Arguments args) {
String height = args.getArg(0);
if (args.size() > 1) {
cmdBus = clientFactory.getEventBus(args.getArg(1));
}
table.setSize("100%", height);
table.setEmptyTableWidget(new Label("No Events"));
pager = new PagerHeader(TextLocation.LEFT);
pager.setDisplay(table);
pager.setNextPageButtonsDisabled(true);
update = new ActionHeader("Update", new Delegate<String>() {
@Override
public void execute(String object) {
pager.setPage(0);
scrollPanel.setVerticalScrollPosition(scrollPanel
.getMinimumHorizontalScrollPosition());
table.getColumnSortList().clear();
table.getColumnSortList().push(new ColumnSortInfo(date, false));
scheduler.update();
}
});
update.setVisible(false);
compositeFooter = new CompositeHeader(
pager.getHeader(), update);
final TextArea msg = new TextArea();
// FIXME, not sure how to handle scroll bar and paging
// add(msg, NORTH);
setWidth("100%");
add(table, CENTER);
scrollPanel = table.getScrollPanel();
scrollPanel.addScrollHandler(new ScrollHandler() {
int line = 0;
@Override
public void onScroll(ScrollEvent event) {
msg.setText(msg.getText() + "\n" + line + " "
+ event.toDebugString() + " "
+ scrollPanel.getVerticalScrollPosition() + " "
+ scrollPanel.getMinimumVerticalScrollPosition() + " "
+ scrollPanel.getMaximumVerticalScrollPosition());
msg.getElement().setScrollTop(
msg.getElement().getScrollHeight());
line++;
if (scrollPanel.getVerticalScrollPosition() == scrollPanel
.getMinimumVerticalScrollPosition()) {
scheduler.update();
}
}
});
AsyncDataProvider<Event> dataProvider = new AsyncDataProvider<Event>() {
@Override
protected void onRangeChanged(HasData<Event> display) {
clientFactory.getEventService().getRowCount(ptuId,
measurementName, new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
table.setRowCount(result);
}
@Override
public void onFailure(Throwable caught) {
table.setRowCount(0);
}
});
final Range range = display.getVisibleRange();
final ColumnSortList sortList = table.getColumnSortList();
SortOrder[] order = new SortOrder[sortList.size()];
for (int i = 0; i < sortList.size(); i++) {
ColumnSortInfo info = sortList.get(i);
order[i] = new SortOrder(info.getColumn()
.getDataStoreName(), info.isAscending());
}
if (order.length == 0) {
order = new SortOrder[1];
order[0] = new SortOrder("tbl_events.datetime", false);
}
clientFactory.getEventService().getTableData(range, order,
ptuId, measurementName,
new AsyncCallback<List<Event>>() {
@Override
public void onSuccess(List<Event> result) {
table.setRowData(range.getStart(), result);
}
@Override
public void onFailure(Throwable caught) {
log.warn("RPC DB FAILED " + caught);
table.setRowCount(0);
}
});
}
};
// Table
dataProvider.addDataDisplay(table);
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
// Subscriptions
ConnectionStatusChangedRemoteEvent.subscribe(
clientFactory.getRemoteEventBus(),
new ConnectionStatusChangedRemoteEvent.Handler() {
@Override
public void onConnectionStatusChanged(
ConnectionStatusChangedRemoteEvent event) {
switch (event.getConnection()) {
case daq:
daqOk = event.getStatus();
break;
case database:
databaseOk = event.getStatus();
break;
default:
break;
}
showGlass(daqOk.not().or(databaseOk.not()).isTrue());
}
});
EventChangedEvent.register(clientFactory.getRemoteEventBus(),
new EventChangedEvent.Handler() {
@Override
public void onEventChanged(EventChangedEvent e) {
Event event = e.getEvent();
if (event == null)
return;
if (((ptuId == null) || event.getPtuId().equals(ptuId))
&& ((measurementName == null) || event
.getName().equals(measurementName))) {
showUpdate = true;
scheduler.update();
}
}
});
if (cmdBus != null) {
SelectPtuEvent.subscribe(cmdBus, new SelectPtuEvent.Handler() {
@Override
public void onPtuSelected(SelectPtuEvent event) {
ptuId = event.getPtuId();
showUpdate = true;
scheduler.update();
}
});
SelectMeasurementEvent.subscribe(cmdBus,
new SelectMeasurementEvent.Handler() {
@Override
public void onSelection(SelectMeasurementEvent event) {
measurementName = event.getName();
showUpdate = true;
scheduler.update();
}
});
// FIXME #189
SelectTabEvent.subscribe(cmdBus, new SelectTabEvent.Handler() {
@Override
public void onTabSelected(SelectTabEvent event) {
if (event.getTab().equals("Summary")) {
showUpdate = true;
scheduler.update();
}
}
});
}
// DATE and TIME (1)
date = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return PtuClientConstants.dateFormat.format(object.getDate());
}
@Override
public String getDataStoreName() {
return "tbl_events.datetime";
}
};
date.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
date.setSortable(sortable);
if (selectable) {
date.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(date, new TextHeader("Date / Time"), compositeFooter);
table.getColumnSortList().push(new ColumnSortInfo(date, false));
// PtuID (2)
ptu = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getPtuId();
}
@Override
public String getDataStoreName() {
return "tbl_devices.name";
}
};
ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptu.setSortable(sortable);
if (selectable) {
ptu.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
ptuHeader = "PTU ID";
table.addColumn(ptu, new TextHeader(ptuHeader), compositeFooter);
// Name (3)
name = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getName();
}
@Override
public String getDataStoreName() {
return "tbl_events.sensor";
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
nameHeader = "Name";
table.addColumn(name, new TextHeader(nameHeader), compositeFooter);
// EventType
ClickableTextColumn<Event> eventType = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getEventType();
}
@Override
public String getDataStoreName() {
return "tbl_events.event_type";
}
};
eventType.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
eventType.setSortable(sortable);
if (selectable) {
eventType.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(eventType, "EventType");
// Value
ClickableTextColumn<Event> value = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getValue() != null ? object.getValue().toString() : "";
}
@Override
public String getDataStoreName() {
return "tbl_events.value";
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(value, new TextHeader("Value"));
// Threshold
ClickableTextColumn<Event> threshold = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getTheshold() != null ? object.getTheshold().toString() : "";
}
@Override
public String getDataStoreName() {
return "tbl_events.threshold";
}
};
threshold.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
threshold.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(threshold, "Threshold");
// Unit
ClickableHtmlColumn<Event> unit = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getUnit();
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(unit, "Unit");
// Selection
if (selectable) {
final SingleSelectionModel<Event> selectionModel = new SingleSelectionModel<Event>();
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Event m = selectionModel.getSelectedObject();
log.info(m + " " + event.getSource());
}
});
}
return true;
}
|
diff --git a/src/main/java/org/instructionexecutor/InstructionCompiledExecutor.java b/src/main/java/org/instructionexecutor/InstructionCompiledExecutor.java
index bf69f8236..26ed424f5 100644
--- a/src/main/java/org/instructionexecutor/InstructionCompiledExecutor.java
+++ b/src/main/java/org/instructionexecutor/InstructionCompiledExecutor.java
@@ -1,391 +1,391 @@
package org.instructionexecutor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.instructionexecutor.InstructionUtil.Closure;
import org.instructionexecutor.InstructionUtil.Insn;
import org.instructionexecutor.InstructionUtil.Instruction;
import org.suite.Suite;
import org.suite.doer.Formatter;
import org.suite.node.Atom;
import org.suite.node.Int;
import org.suite.node.Node;
import org.suite.node.Reference;
import org.suite.node.Tree;
import org.util.IoUtil;
import org.util.LogUtil;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* TODO variant type for closure invocation return value
*
* TODO variant type for stack-popped/-topped value
*
* TODO unknown register for passing return value
*
* Possible types: closure, int, node (atom/reference/tree)
*/
public class InstructionCompiledExecutor {
protected BiMap<Integer, Node> constantPool = HashBiMap.create();
private AtomicInteger counter = new AtomicInteger();
private StringBuilder clazzsec = new StringBuilder();
private StringBuilder methodsec = new StringBuilder();
private StringBuilder swsec = new StringBuilder();
private int ip;
private Deque<Integer> lastEnterIps = new ArrayDeque<>();
private Class<?> registerTypes[];
private String compare = "comparer.compare(#{reg-node}, #{reg-node})";
private Atom COMPARE = Atom.create("COMPARE");
public InstructionCompiledExecutor(Node node) {
InstructionExtractor extractor = new InstructionExtractor(constantPool);
List<Instruction> instructions = extractor.extractInstructions(node);
// Find out the parent of closures.
// Assumes every ENTER has a ASSIGN-CLOSURE referencing it.
Map<Integer, Integer> parentFrames = new HashMap<>();
for (int ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
if (insn.insn == Insn.ASSIGNCLOSURE_)
parentFrames.put(insn.op2, lastEnterIps.peek());
else if (insn.insn == Insn.ENTER_________)
lastEnterIps.push(ip);
else if (insn.insn == Insn.LEAVE_________)
lastEnterIps.pop();
}
Node constant;
String var0, s;
for (ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
int op0 = insn.op0, op1 = insn.op1, op2 = insn.op2;
app("case #{num}: ", ip);
switch (insn.insn) {
case ASSIGNCLOSURE_:
registerTypes[op0] = Closure.class;
app("#{reg} = new Closure(#{fr}, #{num})", op0, op1);
break;
case ASSIGNFRAMEREG:
s = "";
for (int i = 0; i < op1; i++)
s += ".previous";
app("#{reg} = #{fr}#{str}.r#{num}", op0, s, op2);
break;
case ASSIGNCONST___:
registerTypes[op0] = Node.class;
constant = constantPool.get(op1);
app("#{reg} = #{str}", op0, defineConstant(constant));
break;
case ASSIGNINT_____:
registerTypes[op0] = int.class;
app("#{reg} = #{num}", op0, op1);
break;
case CALL__________:
pushCallee();
app("ip = #{reg-num}", op0);
app("continue");
break;
case CALLCONST_____:
pushCallee();
app("#{jump}", op0);
break;
case CALLCLOSURE___:
registerTypes[op0] = Node.class;
app("if(#{reg-clos}.result == null) {", op1);
pushCallee();
app("ip = #{reg-clos}.ip", op1);
app("#{fr} = #{reg-clos}.frame", op1);
app("continue");
app("} else #{reg} = #{reg-clos}.result", op0, op1);
break;
case ENTER_________:
lastEnterIps.push(ip);
registerTypes = new Class<?>[op0];
var0 = "oldFrame" + counter.getAndIncrement();
app("#{fr-class} #{str} = #{fr}", parentFrames.get(ip), var0);
app("#{fr} = new #{fr-class}(#{fr})", ip);
break;
case EVALADD_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} + #{reg-num}", op0, op1, op2);
break;
case EVALDIV_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} / #{reg-num}", op0, op1, op2);
break;
case EVALEQ________:
registerTypes[op0] = int.class;
app("#{reg} = " + compare + " == 0", op0, op1, op2);
break;
case EVALGE________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " >= 0", op0, op1, op2);
break;
case EVALGT________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " > 0", op0, op1, op2);
break;
case EVALLE________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " <= 0", op0, op1, op2);
break;
case EVALLT________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " < 0", op0, op1, op2);
break;
case EVALNE________:
registerTypes[op0] = int.class;
app("#{reg} = " + compare + " != 0", op0, op1, op2);
break;
case EVALMOD_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} %% #{reg-num}", op0, op1, op2);
break;
case EVALMUL_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} * #{reg-num}", op0, op1, op2);
break;
case EVALSUB_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} - #{reg-num}", op0, op1, op2);
break;
case EXIT__________:
app("return #{reg}", op0);
break;
case FORMTREE0_____:
registerTypes[op0] = Tree.class;
insn = instructions.get(ip++);
app("#{reg} = Tree.create(TermOp.#{str}, #{reg-node}, #{reg-node})", insn.op2,
((Atom) constantPool.get(op0)).getName(), op0, op1);
break;
case IFFALSE_______:
app("if (!#{reg-bool}) #{jump}", op1, op0);
break;
case IFNOTEQUALS___:
app("if (#{reg} != #{reg}) #{jump}", op1, op2, op0);
break;
case JUMP__________:
app("#{jump}", op0);
break;
case LABEL_________:
break;
case LEAVE_________:
app(clazzsec, "private static class #{fr-class} {", lastEnterIps.pop());
for (int r = 0; r < registerTypes.length; r++) {
String typeName = registerTypes[r].getSimpleName();
app(clazzsec, "private #{str} r#{num}", typeName, r);
}
app(clazzsec, "}");
app(methodsec, "#{fr-class} #{fr}");
break;
case LOG___________:
constant = constantPool.get(op0);
app("LogUtil.info(#{str}.toString())", defineConstant(constant));
break;
case NEWNODE_______:
registerTypes[op0] = Reference.class;
app("#{reg} = new Reference()", op0);
break;
case PUSH__________:
app("ds[dsp++] = #{reg-node}", op0);
break;
case PUSHCONST_____:
app("ds[dsp++] = Int.create(#{num})", op0);
break;
case POP___________:
registerTypes[op0] = Node.class;
app("#{reg} = ds[--dsp]", op0);
break;
case REMARK________:
break;
case RETURN________:
popCaller();
app("continue");
break;
case RETURNVALUE___:
s = registerTypes[op0].getSimpleName(); // Return value type
var0 = "returnValue" + counter.getAndIncrement();
app("#{str} #{str} = #{reg}", s, var0, op0);
popCaller();
app("returnValue = #{str}", var0);
break;
case SERVICE_______:
app("dsp -= #{num}", op2);
node = constantPool.get(op1);
// TODO FunInstructionExecutor.sys()
if (node == COMPARE) {
registerTypes[op0] = int.class;
app("Node left = (Node) ds[dsp + 1]");
app("Node right = (Node) ds[dsp]");
app("#{reg} = comparer.compare(left, right)", op0);
}
break;
case SETRESULT_____:
registerTypes[op0] = Node.class;
app("#{reg} = returnValue", op0);
break;
case SETCLOSURERES_:
registerTypes[op0] = Node.class;
app("#{reg} = returnValue", op0);
app("#{reg-clos}.result = #{reg}", op1, op0);
break;
case TOP___________:
registerTypes[op0] = Node.class;
app("#{reg} = ds[dsp + #{num}]", op0, op1);
break;
default:
throw new RuntimeException("Unknown instruction " + insn);
// TODO LogicInstructionExecutor.execute()
}
}
String className = "CompiledRun" + counter.getAndIncrement();
String java = String.format("" //
+ "package org.compiled; \n" //
+ "import org.suite.node.*; \n" //
+ "import " + Closure.class.getCanonicalName() + "; \n" //
+ "import " + Int.class.getCanonicalName() + "; \n" //
+ "import " + LogUtil.class.getCanonicalName() + "; \n" //
+ "import " + Node.class.getCanonicalName() + "; \n" //
+ "import " + Suite.class.getCanonicalName() + "; \n" //
+ "public class %s { \n" //
+ "%s" //
+ "public static void exec() { \n" //
+ "int ip = 0; \n" //
+ "Node returnValue = null; \n" //
+ "%s \n" //
+ "while(true) switch(ip) { \n" //
+ "%s \n" //
+ "default: \n" //
+ "} \n" //
+ "} \n" //
+ "} \n" //
, className, clazzsec, methodsec, swsec);
- String filename = "src/main/java/org/instructionexecutor/Output.java";
+ String filename = "src/main/java/org/instructionexecutor/" + className + ".java";
try (OutputStream os = new FileOutputStream(filename)) {
os.write(java.getBytes(IoUtil.charset));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void pushCallee() {
app("cs[csp] = ip");
app("fs[csp] = #{fr}");
app("csp++");
}
private void popCaller() {
app("--csp");
app("ip = cs[csp]");
app("#{fr} = fs[csp]");
}
private String defineConstant(Node node) {
node = node.finalNode();
String result = "const" + counter.getAndIncrement();
String decl = "private static final Node #{str} = Suite.parse(\"#{str}\")";
app(clazzsec, decl, result, Formatter.dump(node));
return result;
}
private void app(String fmt, Object... ps) {
app(swsec, fmt, ps);
}
private void app(StringBuilder section, String fmt, Object... ps) {
List<Object> list = Arrays.asList(ps);
Iterator<Object> iter = list.iterator();
while (!fmt.isEmpty()) {
int pos0 = fmt.indexOf("#{");
int pos1 = fmt.indexOf("}", pos0);
String s0, s1, s2;
if (pos0 > 0 && pos1 > 0) {
s0 = fmt.substring(0, pos0);
s1 = fmt.substring(pos0 + 2, pos1);
s2 = fmt.substring(pos1 + 1);
} else {
s0 = fmt;
s1 = s2 = "";
}
int reg;
switch (s1) {
case "fr":
s1 = String.format("f%d", lastEnterIps.peek());
break;
case "fr-class":
s1 = String.format("Frame%d", iter.next());
break;
case "jump":
s1 = String.format("{ ip = %d; continue; }", iter.next());
break;
case "num":
s1 = String.format("%d", iter.next());
break;
case "reg":
s1 = reg((int) iter.next());
break;
case "reg-clos":
reg = (int) iter.next();
s1 = reg(reg);
if (registerTypes[reg] == Node.class)
s1 = "((Closure) " + s1 + ")";
break;
case "reg-node":
reg = (int) iter.next();
s1 = reg(reg);
if (registerTypes[reg] == int.class)
s1 = "Int.create(" + s1 + ")";
break;
case "reg-num":
reg = (int) iter.next();
s1 = reg(reg);
if (registerTypes[reg] == Node.class)
s1 = "((Int) " + s1 + ").getValue()";
break;
case "str":
s1 = String.format("%s", iter.next());
}
section.append(s0);
section.append(s1);
fmt = s2;
}
section.append(";\n");
}
private String reg(int reg) {
String s1;
s1 = String.format("f%d.r%d", lastEnterIps.peek(), reg);
return s1;
}
}
| true | true | public InstructionCompiledExecutor(Node node) {
InstructionExtractor extractor = new InstructionExtractor(constantPool);
List<Instruction> instructions = extractor.extractInstructions(node);
// Find out the parent of closures.
// Assumes every ENTER has a ASSIGN-CLOSURE referencing it.
Map<Integer, Integer> parentFrames = new HashMap<>();
for (int ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
if (insn.insn == Insn.ASSIGNCLOSURE_)
parentFrames.put(insn.op2, lastEnterIps.peek());
else if (insn.insn == Insn.ENTER_________)
lastEnterIps.push(ip);
else if (insn.insn == Insn.LEAVE_________)
lastEnterIps.pop();
}
Node constant;
String var0, s;
for (ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
int op0 = insn.op0, op1 = insn.op1, op2 = insn.op2;
app("case #{num}: ", ip);
switch (insn.insn) {
case ASSIGNCLOSURE_:
registerTypes[op0] = Closure.class;
app("#{reg} = new Closure(#{fr}, #{num})", op0, op1);
break;
case ASSIGNFRAMEREG:
s = "";
for (int i = 0; i < op1; i++)
s += ".previous";
app("#{reg} = #{fr}#{str}.r#{num}", op0, s, op2);
break;
case ASSIGNCONST___:
registerTypes[op0] = Node.class;
constant = constantPool.get(op1);
app("#{reg} = #{str}", op0, defineConstant(constant));
break;
case ASSIGNINT_____:
registerTypes[op0] = int.class;
app("#{reg} = #{num}", op0, op1);
break;
case CALL__________:
pushCallee();
app("ip = #{reg-num}", op0);
app("continue");
break;
case CALLCONST_____:
pushCallee();
app("#{jump}", op0);
break;
case CALLCLOSURE___:
registerTypes[op0] = Node.class;
app("if(#{reg-clos}.result == null) {", op1);
pushCallee();
app("ip = #{reg-clos}.ip", op1);
app("#{fr} = #{reg-clos}.frame", op1);
app("continue");
app("} else #{reg} = #{reg-clos}.result", op0, op1);
break;
case ENTER_________:
lastEnterIps.push(ip);
registerTypes = new Class<?>[op0];
var0 = "oldFrame" + counter.getAndIncrement();
app("#{fr-class} #{str} = #{fr}", parentFrames.get(ip), var0);
app("#{fr} = new #{fr-class}(#{fr})", ip);
break;
case EVALADD_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} + #{reg-num}", op0, op1, op2);
break;
case EVALDIV_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} / #{reg-num}", op0, op1, op2);
break;
case EVALEQ________:
registerTypes[op0] = int.class;
app("#{reg} = " + compare + " == 0", op0, op1, op2);
break;
case EVALGE________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " >= 0", op0, op1, op2);
break;
case EVALGT________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " > 0", op0, op1, op2);
break;
case EVALLE________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " <= 0", op0, op1, op2);
break;
case EVALLT________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " < 0", op0, op1, op2);
break;
case EVALNE________:
registerTypes[op0] = int.class;
app("#{reg} = " + compare + " != 0", op0, op1, op2);
break;
case EVALMOD_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} %% #{reg-num}", op0, op1, op2);
break;
case EVALMUL_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} * #{reg-num}", op0, op1, op2);
break;
case EVALSUB_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} - #{reg-num}", op0, op1, op2);
break;
case EXIT__________:
app("return #{reg}", op0);
break;
case FORMTREE0_____:
registerTypes[op0] = Tree.class;
insn = instructions.get(ip++);
app("#{reg} = Tree.create(TermOp.#{str}, #{reg-node}, #{reg-node})", insn.op2,
((Atom) constantPool.get(op0)).getName(), op0, op1);
break;
case IFFALSE_______:
app("if (!#{reg-bool}) #{jump}", op1, op0);
break;
case IFNOTEQUALS___:
app("if (#{reg} != #{reg}) #{jump}", op1, op2, op0);
break;
case JUMP__________:
app("#{jump}", op0);
break;
case LABEL_________:
break;
case LEAVE_________:
app(clazzsec, "private static class #{fr-class} {", lastEnterIps.pop());
for (int r = 0; r < registerTypes.length; r++) {
String typeName = registerTypes[r].getSimpleName();
app(clazzsec, "private #{str} r#{num}", typeName, r);
}
app(clazzsec, "}");
app(methodsec, "#{fr-class} #{fr}");
break;
case LOG___________:
constant = constantPool.get(op0);
app("LogUtil.info(#{str}.toString())", defineConstant(constant));
break;
case NEWNODE_______:
registerTypes[op0] = Reference.class;
app("#{reg} = new Reference()", op0);
break;
case PUSH__________:
app("ds[dsp++] = #{reg-node}", op0);
break;
case PUSHCONST_____:
app("ds[dsp++] = Int.create(#{num})", op0);
break;
case POP___________:
registerTypes[op0] = Node.class;
app("#{reg} = ds[--dsp]", op0);
break;
case REMARK________:
break;
case RETURN________:
popCaller();
app("continue");
break;
case RETURNVALUE___:
s = registerTypes[op0].getSimpleName(); // Return value type
var0 = "returnValue" + counter.getAndIncrement();
app("#{str} #{str} = #{reg}", s, var0, op0);
popCaller();
app("returnValue = #{str}", var0);
break;
case SERVICE_______:
app("dsp -= #{num}", op2);
node = constantPool.get(op1);
// TODO FunInstructionExecutor.sys()
if (node == COMPARE) {
registerTypes[op0] = int.class;
app("Node left = (Node) ds[dsp + 1]");
app("Node right = (Node) ds[dsp]");
app("#{reg} = comparer.compare(left, right)", op0);
}
break;
case SETRESULT_____:
registerTypes[op0] = Node.class;
app("#{reg} = returnValue", op0);
break;
case SETCLOSURERES_:
registerTypes[op0] = Node.class;
app("#{reg} = returnValue", op0);
app("#{reg-clos}.result = #{reg}", op1, op0);
break;
case TOP___________:
registerTypes[op0] = Node.class;
app("#{reg} = ds[dsp + #{num}]", op0, op1);
break;
default:
throw new RuntimeException("Unknown instruction " + insn);
// TODO LogicInstructionExecutor.execute()
}
}
String className = "CompiledRun" + counter.getAndIncrement();
String java = String.format("" //
+ "package org.compiled; \n" //
+ "import org.suite.node.*; \n" //
+ "import " + Closure.class.getCanonicalName() + "; \n" //
+ "import " + Int.class.getCanonicalName() + "; \n" //
+ "import " + LogUtil.class.getCanonicalName() + "; \n" //
+ "import " + Node.class.getCanonicalName() + "; \n" //
+ "import " + Suite.class.getCanonicalName() + "; \n" //
+ "public class %s { \n" //
+ "%s" //
+ "public static void exec() { \n" //
+ "int ip = 0; \n" //
+ "Node returnValue = null; \n" //
+ "%s \n" //
+ "while(true) switch(ip) { \n" //
+ "%s \n" //
+ "default: \n" //
+ "} \n" //
+ "} \n" //
+ "} \n" //
, className, clazzsec, methodsec, swsec);
String filename = "src/main/java/org/instructionexecutor/Output.java";
try (OutputStream os = new FileOutputStream(filename)) {
os.write(java.getBytes(IoUtil.charset));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
| public InstructionCompiledExecutor(Node node) {
InstructionExtractor extractor = new InstructionExtractor(constantPool);
List<Instruction> instructions = extractor.extractInstructions(node);
// Find out the parent of closures.
// Assumes every ENTER has a ASSIGN-CLOSURE referencing it.
Map<Integer, Integer> parentFrames = new HashMap<>();
for (int ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
if (insn.insn == Insn.ASSIGNCLOSURE_)
parentFrames.put(insn.op2, lastEnterIps.peek());
else if (insn.insn == Insn.ENTER_________)
lastEnterIps.push(ip);
else if (insn.insn == Insn.LEAVE_________)
lastEnterIps.pop();
}
Node constant;
String var0, s;
for (ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
int op0 = insn.op0, op1 = insn.op1, op2 = insn.op2;
app("case #{num}: ", ip);
switch (insn.insn) {
case ASSIGNCLOSURE_:
registerTypes[op0] = Closure.class;
app("#{reg} = new Closure(#{fr}, #{num})", op0, op1);
break;
case ASSIGNFRAMEREG:
s = "";
for (int i = 0; i < op1; i++)
s += ".previous";
app("#{reg} = #{fr}#{str}.r#{num}", op0, s, op2);
break;
case ASSIGNCONST___:
registerTypes[op0] = Node.class;
constant = constantPool.get(op1);
app("#{reg} = #{str}", op0, defineConstant(constant));
break;
case ASSIGNINT_____:
registerTypes[op0] = int.class;
app("#{reg} = #{num}", op0, op1);
break;
case CALL__________:
pushCallee();
app("ip = #{reg-num}", op0);
app("continue");
break;
case CALLCONST_____:
pushCallee();
app("#{jump}", op0);
break;
case CALLCLOSURE___:
registerTypes[op0] = Node.class;
app("if(#{reg-clos}.result == null) {", op1);
pushCallee();
app("ip = #{reg-clos}.ip", op1);
app("#{fr} = #{reg-clos}.frame", op1);
app("continue");
app("} else #{reg} = #{reg-clos}.result", op0, op1);
break;
case ENTER_________:
lastEnterIps.push(ip);
registerTypes = new Class<?>[op0];
var0 = "oldFrame" + counter.getAndIncrement();
app("#{fr-class} #{str} = #{fr}", parentFrames.get(ip), var0);
app("#{fr} = new #{fr-class}(#{fr})", ip);
break;
case EVALADD_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} + #{reg-num}", op0, op1, op2);
break;
case EVALDIV_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} / #{reg-num}", op0, op1, op2);
break;
case EVALEQ________:
registerTypes[op0] = int.class;
app("#{reg} = " + compare + " == 0", op0, op1, op2);
break;
case EVALGE________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " >= 0", op0, op1, op2);
break;
case EVALGT________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " > 0", op0, op1, op2);
break;
case EVALLE________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " <= 0", op0, op1, op2);
break;
case EVALLT________:
registerTypes[op0] = Node.class;
app("#{reg} = " + compare + " < 0", op0, op1, op2);
break;
case EVALNE________:
registerTypes[op0] = int.class;
app("#{reg} = " + compare + " != 0", op0, op1, op2);
break;
case EVALMOD_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} %% #{reg-num}", op0, op1, op2);
break;
case EVALMUL_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} * #{reg-num}", op0, op1, op2);
break;
case EVALSUB_______:
registerTypes[op0] = int.class;
app("#{reg} = #{reg-num} - #{reg-num}", op0, op1, op2);
break;
case EXIT__________:
app("return #{reg}", op0);
break;
case FORMTREE0_____:
registerTypes[op0] = Tree.class;
insn = instructions.get(ip++);
app("#{reg} = Tree.create(TermOp.#{str}, #{reg-node}, #{reg-node})", insn.op2,
((Atom) constantPool.get(op0)).getName(), op0, op1);
break;
case IFFALSE_______:
app("if (!#{reg-bool}) #{jump}", op1, op0);
break;
case IFNOTEQUALS___:
app("if (#{reg} != #{reg}) #{jump}", op1, op2, op0);
break;
case JUMP__________:
app("#{jump}", op0);
break;
case LABEL_________:
break;
case LEAVE_________:
app(clazzsec, "private static class #{fr-class} {", lastEnterIps.pop());
for (int r = 0; r < registerTypes.length; r++) {
String typeName = registerTypes[r].getSimpleName();
app(clazzsec, "private #{str} r#{num}", typeName, r);
}
app(clazzsec, "}");
app(methodsec, "#{fr-class} #{fr}");
break;
case LOG___________:
constant = constantPool.get(op0);
app("LogUtil.info(#{str}.toString())", defineConstant(constant));
break;
case NEWNODE_______:
registerTypes[op0] = Reference.class;
app("#{reg} = new Reference()", op0);
break;
case PUSH__________:
app("ds[dsp++] = #{reg-node}", op0);
break;
case PUSHCONST_____:
app("ds[dsp++] = Int.create(#{num})", op0);
break;
case POP___________:
registerTypes[op0] = Node.class;
app("#{reg} = ds[--dsp]", op0);
break;
case REMARK________:
break;
case RETURN________:
popCaller();
app("continue");
break;
case RETURNVALUE___:
s = registerTypes[op0].getSimpleName(); // Return value type
var0 = "returnValue" + counter.getAndIncrement();
app("#{str} #{str} = #{reg}", s, var0, op0);
popCaller();
app("returnValue = #{str}", var0);
break;
case SERVICE_______:
app("dsp -= #{num}", op2);
node = constantPool.get(op1);
// TODO FunInstructionExecutor.sys()
if (node == COMPARE) {
registerTypes[op0] = int.class;
app("Node left = (Node) ds[dsp + 1]");
app("Node right = (Node) ds[dsp]");
app("#{reg} = comparer.compare(left, right)", op0);
}
break;
case SETRESULT_____:
registerTypes[op0] = Node.class;
app("#{reg} = returnValue", op0);
break;
case SETCLOSURERES_:
registerTypes[op0] = Node.class;
app("#{reg} = returnValue", op0);
app("#{reg-clos}.result = #{reg}", op1, op0);
break;
case TOP___________:
registerTypes[op0] = Node.class;
app("#{reg} = ds[dsp + #{num}]", op0, op1);
break;
default:
throw new RuntimeException("Unknown instruction " + insn);
// TODO LogicInstructionExecutor.execute()
}
}
String className = "CompiledRun" + counter.getAndIncrement();
String java = String.format("" //
+ "package org.compiled; \n" //
+ "import org.suite.node.*; \n" //
+ "import " + Closure.class.getCanonicalName() + "; \n" //
+ "import " + Int.class.getCanonicalName() + "; \n" //
+ "import " + LogUtil.class.getCanonicalName() + "; \n" //
+ "import " + Node.class.getCanonicalName() + "; \n" //
+ "import " + Suite.class.getCanonicalName() + "; \n" //
+ "public class %s { \n" //
+ "%s" //
+ "public static void exec() { \n" //
+ "int ip = 0; \n" //
+ "Node returnValue = null; \n" //
+ "%s \n" //
+ "while(true) switch(ip) { \n" //
+ "%s \n" //
+ "default: \n" //
+ "} \n" //
+ "} \n" //
+ "} \n" //
, className, clazzsec, methodsec, swsec);
String filename = "src/main/java/org/instructionexecutor/" + className + ".java";
try (OutputStream os = new FileOutputStream(filename)) {
os.write(java.getBytes(IoUtil.charset));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
|
diff --git a/XMLSpider.java b/XMLSpider.java
index 482d2d0..8c63d37 100644
--- a/XMLSpider.java
+++ b/XMLSpider.java
@@ -1,1043 +1,1044 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.XMLSpider;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.Configuration;
import com.db4o.config.QueryEvaluationMode;
import com.db4o.diagnostic.DiagnosticToConsole;
import com.db4o.query.Query;
import com.db4o.reflect.jdk.JdkReflector;
import freenet.client.ClientMetadata;
import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.InsertException;
import freenet.client.async.BaseClientPutter;
import freenet.client.async.ClientCallback;
import freenet.client.async.ClientGetter;
import freenet.client.async.USKCallback;
import freenet.clients.http.PageMaker;
import freenet.clients.http.filter.ContentFilter;
import freenet.clients.http.filter.FoundURICallback;
import freenet.clients.http.filter.UnsafeContentTypeException;
import freenet.keys.FreenetURI;
import freenet.keys.USK;
import freenet.l10n.L10n.LANGUAGE;
import freenet.node.NodeClientCore;
import freenet.node.RequestStarter;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginHTTP;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginHTTPException;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.Bucket;
import freenet.support.api.HTTPRequest;
import freenet.support.io.NativeThread;
import freenet.support.io.NullBucketFactory;
/**
* XMLSpider. Produces xml index for searching words.
* In case the size of the index grows up a specific threshold the index is split into several subindices.
* The indexing key is the md5 hash of the word.
*
* @author swati goyal
*
*/
public class XMLSpider implements FredPlugin, FredPluginHTTP, FredPluginThreadless, FredPluginVersioned, FredPluginL10n, USKCallback {
public synchronized long getNextPageId() {
long x = maxPageId.incrementAndGet();
db.store(maxPageId);
return x;
}
/** Document ID of fetching documents */
protected Map<Page, ClientGetter> runningFetch = Collections.synchronizedMap(new HashMap<Page, ClientGetter>());
protected MaxPageId maxPageId;
/**
* directory where the generated indices are stored.
* Needs to be created before it can be used
*/
public static final String DEFAULT_INDEX_DIR = "myindex7/";
/**
* Lists the allowed mime types of the fetched page.
*/
public Set<String> allowedMIMETypes;
static final int MAX_ENTRIES = 800;
static final long MAX_SUBINDEX_UNCOMPRESSED_SIZE = 4 * 1024 * 1024;
private static int version = 33;
private static final String pluginName = "XML spider " + version;
public String getVersion() {
return version + " r" + Version.getSvnRevision();
}
/**
* Gives the allowed fraction of total time spent on generating indices with
* maximum value = 1; minimum value = 0.
*/
public static final double MAX_TIME_SPENT_INDEXING = 0.5;
static final String indexTitle = "XMLSpider index";
static final String indexOwner = "Freenet";
static final String indexOwnerEmail = null;
// Can have many; this limit only exists to save memory.
private static final int maxParallelRequests = 100;
private int maxShownURIs = 15;
private NodeClientCore core;
private FetchContext ctx;
// Equal to Frost, ARK fetches etc. One step down from Fproxy.
// Any lower makes it very difficult to debug. Maybe reduce for production - after solving the ARK bugs.
private final short PRIORITY_CLASS = RequestStarter.IMMEDIATE_SPLITFILE_PRIORITY_CLASS;
private boolean stopped = true;
private PageMaker pageMaker;
private final static String[] BADLIST_EXTENSTION = new String[] {
".ico", ".bmp", ".png", ".jpg", ".gif", // image
".zip", ".jar", ".gz" , ".bz2", ".rar", // archive
".7z" , ".rar", ".arj", ".rpm", ".deb",
".xpi", ".ace", ".cab", ".lza", ".lzh",
".ace",
".exe", ".iso", // binary
".mpg", ".ogg", ".mp3", ".avi", // media
".css", ".sig" // other
};
/**
* Adds the found uri to the list of to-be-retrieved uris. <p>Every usk uri added as ssk.
* @param uri the new uri that needs to be fetched for further indexing
*/
public void queueURI(FreenetURI uri, String comment, boolean force) {
String sURI = uri.toString();
for (String ext : BADLIST_EXTENSTION)
if (sURI.endsWith(ext))
return; // be smart
if (uri.isUSK()) {
if(uri.getSuggestedEdition() < 0)
uri = uri.setSuggestedEdition((-1)* uri.getSuggestedEdition());
try{
uri = ((USK.create(uri)).getSSK()).getURI();
(ctx.uskManager).subscribe(USK.create(uri),this, false, this);
}
catch(Exception e){}
}
synchronized (this) {
Page page = getPageByURI(uri);
if (page == null) {
page = new Page(getNextPageId(), uri.toString(), comment);
db.store(page);
} else if (force) {
synchronized (page) {
page.status = Status.QUEUED;
page.lastChange = System.currentTimeMillis();
db.store(page);
}
}
}
}
protected List<Page> queuedRequestCache = new ArrayList<Page>();
private void startSomeRequests() {
FreenetURI[] initialURIs = core.getBookmarkURIs();
for (int i = 0; i < initialURIs.length; i++)
queueURI(initialURIs[i], "bookmark", false);
ArrayList<ClientGetter> toStart = null;
synchronized (this) {
if (stopped)
return;
synchronized (runningFetch) {
int running = runningFetch.size();
if (running >= maxParallelRequests) return;
if (queuedRequestCache.isEmpty()) {
Query query = db.query();
query.constrain(Page.class);
query.descend("status").constrain(Status.QUEUED);
query.descend("lastChange").orderAscending();
@SuppressWarnings("unchecked")
ObjectSet<Page> queuedSet = query.execute();
for (int i = 0 ;
i < maxParallelRequests * 2 && queuedSet.hasNext();
i++) { // cache 2 * maxParallelRequests
queuedRequestCache.add(queuedSet.next());
}
}
queuedRequestCache.removeAll(runningFetch.keySet());
toStart = new ArrayList<ClientGetter>(maxParallelRequests - running);
Iterator<Page> it = queuedRequestCache.iterator();
while (running + toStart.size() < maxParallelRequests && it.hasNext()) {
Page page = it.next();
+ it.remove();
try {
ClientGetter getter = makeGetter(page);
Logger.minor(this, "Starting " + getter + " " + page);
toStart.add(getter);
runningFetch.put(page, getter);
} catch (MalformedURLException e) {
Logger.error(this, "IMPOSSIBLE-Malformed URI: " + page, e);
page.status = Status.FAILED;
page.lastChange = System.currentTimeMillis();
db.store(page);
}
}
}
}
for (ClientGetter g : toStart) {
try {
g.start();
Logger.minor(this, g + " started");
} catch (FetchException e) {
Logger.minor(this, "Fetch Exception: " + g, e);
g.getClientCallback().onFailure(e, g);
}
}
}
private class MyClientCallback implements ClientCallback {
final Page page;
public MyClientCallback(Page page) {
this.page = page;
}
public void onFailure(FetchException e, ClientGetter state) {
callbackExecutor.execute(new OnFailureCallback(e, state, page));
}
public void onFailure(InsertException e, BaseClientPutter state) {
// Ignore
}
public void onFetchable(BaseClientPutter state) {
// Ignore
}
public void onGeneratedURI(FreenetURI uri, BaseClientPutter state) {
// Ignore
}
public void onMajorProgress() {
// Ignore
}
public void onSuccess(final FetchResult result, final ClientGetter state) {
callbackExecutor.execute(new OnSuccessCallback(result, state, page));
}
public void onSuccess(BaseClientPutter state) {
// Ignore
}
public String toString() {
return super.toString() + ":" + page;
}
}
private ClientGetter makeGetter(Page page) throws MalformedURLException {
ClientGetter getter = new ClientGetter(new MyClientCallback(page),
core.requestStarters.chkFetchScheduler,
core.requestStarters.sskFetchScheduler, new FreenetURI(page.uri), ctx, PRIORITY_CLASS, this, null, null);
return getter;
}
protected class OnFailureCallback implements Runnable {
private FetchException e;
private ClientGetter state;
private Page page;
OnFailureCallback(FetchException e, ClientGetter state, Page page) {
this.e = e;
this.state = state;
this.page = page;
}
public void run() {
onFailure(e, state, page);
}
}
protected class OnSuccessCallback implements Runnable {
private FetchResult result;
private ClientGetter state;
private Page page;
OnSuccessCallback(FetchResult result, ClientGetter state, Page page) {
this.result = result;
this.state = state;
this.page = page;
}
public void run() {
onSuccess(result, state, page);
}
}
private synchronized void scheduleMakeIndex() {
if (writeIndexScheduled || writingIndex)
return;
callbackExecutor.execute(new MakeIndexCallback());
writeIndexScheduled = true;
}
protected class MakeIndexCallback implements Runnable {
public void run() {
try {
synchronized (this) {
writingIndex = true;
}
indexWriter.makeIndex();
synchronized (this) {
writingIndex = false;
writeIndexScheduled = false;
}
} catch (Exception e) {
Logger.error(this, "Could not generate index: "+e, e);
} finally {
synchronized (this) {
writingIndex = false;
notifyAll();
}
}
}
}
protected static class CallbackPrioritizer implements Comparator<Runnable> {
public int compare(Runnable o1, Runnable o2) {
if (o1.getClass() == o2.getClass())
return 0;
return getPriority(o1) - getPriority(o2);
}
private int getPriority(Runnable r) {
if (r instanceof MakeIndexCallback)
return 0;
else if (r instanceof OnFailureCallback)
return 1;
else if (r instanceof OnSuccessCallback)
return 2;
return -1;
}
}
// this is java.util.concurrent.Executor, not freenet.support.Executor
// always run with one thread --> more thread cause contention and slower!
protected ThreadPoolExecutor callbackExecutor = new ThreadPoolExecutor( //
1, 1, 600, TimeUnit.SECONDS, //
new PriorityBlockingQueue<Runnable>(5, new CallbackPrioritizer()), //
new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new NativeThread(r, "XMLSpider", NativeThread.NORM_PRIORITY - 1, true);
t.setDaemon(true);
return t;
}
});
/**
* Processes the successfully fetched uri for further outlinks.
*
* @param result
* @param state
* @param page
*/
// single threaded
protected void onSuccess(FetchResult result, ClientGetter state, Page page) {
synchronized (this) {
if (stopped)
return;
}
FreenetURI uri = state.getURI();
page.status = Status.SUCCEEDED; // Content filter may throw, but we mark it as success anyway
try {
// Page may be refetched if added manually
// Delete existing TermPosition
Query query = db.query();
query.constrain(TermPosition.class);
query.descend("pageId").constrain(page.id);
@SuppressWarnings("unchecked")
ObjectSet<TermPosition> set = query.execute();
for (TermPosition tp : set)
db.delete(tp);
ClientMetadata cm = result.getMetadata();
Bucket data = result.asBucket();
String mimeType = cm.getMIMEType();
/*
* instead of passing the current object, the pagecallback object for every page is
* passed to the content filter this has many benefits to efficiency, and allows us
* to identify trivially which page is being indexed. (we CANNOT rely on the base
* href provided).
*/
PageCallBack pageCallBack = new PageCallBack(page);
Logger.minor(this, "Successful: " + uri + " : " + page.id);
try {
ContentFilter.filter(data, new NullBucketFactory(), mimeType, uri.toURI("http://127.0.0.1:8888/"),
pageCallBack);
pageCallBack.store();
Logger.minor(this, "Filtered " + uri + " : " + page.id);
} catch (UnsafeContentTypeException e) {
return; // Ignore
} catch (IOException e) {
Logger.error(this, "Bucket error?: " + e, e);
} catch (URISyntaxException e) {
Logger.error(this, "Internal error: " + e, e);
} finally {
data.free();
}
} finally {
synchronized (this) {
runningFetch.remove(page);
page.lastChange = System.currentTimeMillis();
db.store(page);
}
db.commit();
startSomeRequests();
}
}
protected void onFailure(FetchException fe, ClientGetter state, Page page) {
Logger.minor(this, "Failed: " + page + " : " + state, fe);
synchronized (this) {
if (stopped)
return;
synchronized (page) {
if (fe.newURI != null) {
// redirect, mark as succeeded
queueURI(fe.newURI, "redirect from " + state.getURI(), false);
page.status = Status.SUCCEEDED;
page.lastChange = System.currentTimeMillis();
db.store(page);
} else if (fe.isFatal()) {
// too many tries or fatal, mark as failed
page.status = Status.FAILED;
page.lastChange = System.currentTimeMillis();
db.store(page);
} else {
// requeue at back
page.status = Status.QUEUED;
page.lastChange = System.currentTimeMillis();
db.store(page);
}
}
db.commit();
runningFetch.remove(page);
}
startSomeRequests();
}
private boolean writingIndex;
private boolean writeIndexScheduled;
protected IndexWriter indexWriter;
public void terminate(){
synchronized (this) {
stopped = true;
for (Map.Entry<Page, ClientGetter> me : runningFetch.entrySet()) {
me.getValue().cancel();
}
runningFetch.clear();
callbackExecutor.shutdownNow();
}
try { callbackExecutor.awaitTermination(15, TimeUnit.SECONDS); } catch (InterruptedException e) {}
try { db.close(); } catch (Exception e) {}
}
public synchronized void runPlugin(PluginRespirator pr) {
this.core = pr.getNode().clientCore;
this.pageMaker = pr.getPageMaker();
pageMaker.addNavigationLink("/plugins/plugins.XMLSpider.XMLSpider", "Home", "Home page", false, null);
pageMaker.addNavigationLink("/plugins/", "Plugins page", "Back to Plugins page", false, null);
/* Initialize Fetch Context */
this.ctx = pr.getHLSimpleClient().getFetchContext();
ctx.maxSplitfileBlockRetries = 2;
ctx.maxNonSplitfileRetries = 2;
ctx.maxTempLength = 2 * 1024 * 1024;
ctx.maxOutputLength = 2 * 1024 * 1024;
allowedMIMETypes = new HashSet<String>();
allowedMIMETypes.add("text/html");
allowedMIMETypes.add("text/plain");
allowedMIMETypes.add("application/xhtml+xml");
ctx.allowedMIMETypes = new HashSet<String>(allowedMIMETypes);
stopped = false;
if (!new File(DEFAULT_INDEX_DIR).mkdirs()) {
Logger.error(this, "Could not create default index directory ");
}
// Initial DB4O
db = initDB4O();
// Find max Page ID
{
Query query = db.query();
query.constrain(MaxPageId.class);
@SuppressWarnings("unchecked")
ObjectSet<MaxPageId> set = query.execute();
if (set.hasNext())
maxPageId = set.next();
else {
query = db.query();
query.constrain(Page.class);
query.descend("id").orderDescending();
@SuppressWarnings("unchecked")
ObjectSet<Page> set2 = query.execute();
if (set2.hasNext())
maxPageId = new MaxPageId(set2.next().id);
else
maxPageId = new MaxPageId(0);
}
}
indexWriter = new IndexWriter(this);
pr.getNode().executor.execute(new Runnable() {
public void run() {
try{
Thread.sleep(30 * 1000); // Let the node start up
} catch (InterruptedException e){}
startSomeRequests();
}
}, "Spider Plugin Starter");
}
static class PageStatus {
long count;
List<Page> pages;
PageStatus(long count, List<Page> pages) {
this.count = count;
this.pages = pages;
}
}
private PageStatus getPageStatus(Status status) {
Query query = db.query();
query.constrain(Page.class);
query.descend("status").constrain(status);
query.descend("lastChange").orderDescending();
@SuppressWarnings("unchecked")
ObjectSet<Page> set = query.execute();
List<Page> pages = new ArrayList<Page>();
while (set.hasNext() && pages.size() < maxShownURIs) {
pages.add(set.next());
}
return new PageStatus(set.size(), pages);
}
private void listPages(PageStatus pageStatus, HTMLNode parent) {
if (pageStatus.pages.isEmpty()) {
HTMLNode list = parent.addChild("#", "NO URI");
} else {
HTMLNode list = parent.addChild("ol", "style", "overflow: auto; white-space: nowrap;");
for (Page page : pageStatus.pages) {
HTMLNode litem = list.addChild("li", "title", page.comment);
litem.addChild("a", "href", "/freenet:" + page.uri, page.uri);
}
}
}
/**
* Interface to the Spider data
*/
public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
HTMLNode pageNode = pageMaker.getPageNode(pluginName, null);
HTMLNode contentNode = pageMaker.getContentNode(pageNode);
return generateHTML(request, pageNode, contentNode);
}
public String handleHTTPPost(HTTPRequest request) throws PluginHTTPException {
HTMLNode pageNode = pageMaker.getPageNode(pluginName, null);
HTMLNode contentNode = pageMaker.getContentNode(pageNode);
if (request.isPartSet("createIndex")) {
synchronized (this) {
scheduleMakeIndex();
HTMLNode infobox = pageMaker.getInfobox("infobox infobox-success", "Scheduled Creating Index");
infobox.addChild("#", "Index will start create soon.");
contentNode.addChild(infobox);
}
}
String addURI = request.getPartAsString("addURI", 512);
if (addURI != null && addURI.length() != 0) {
try {
FreenetURI uri = new FreenetURI(addURI);
queueURI(uri, "manually", true);
HTMLNode infobox = pageMaker.getInfobox("infobox infobox-success", "URI Added");
infobox.addChild("#", "Added " + uri);
contentNode.addChild(infobox);
} catch (Exception e) {
HTMLNode infobox = pageMaker.getInfobox("infobox infobox-error", "Error adding URI");
infobox.addChild("#", e.getMessage());
contentNode.addChild(infobox);
Logger.normal(this, "Manual added URI cause exception", e);
}
startSomeRequests();
}
return generateHTML(request, pageNode, contentNode);
}
private String generateHTML(HTTPRequest request, HTMLNode pageNode, HTMLNode contentNode) {
HTMLNode overviewTable = contentNode.addChild("table", "class", "column");
HTMLNode overviewTableRow = overviewTable.addChild("tr");
PageStatus queuedStatus = getPageStatus(Status.QUEUED);
PageStatus succeededStatus = getPageStatus(Status.SUCCEEDED);
PageStatus failedStatus = getPageStatus(Status.FAILED);
// Column 1
HTMLNode nextTableCell = overviewTableRow.addChild("td", "class", "first");
HTMLNode statusBox = pageMaker.getInfobox("Spider Status");
HTMLNode statusContent = pageMaker.getContentNode(statusBox);
statusContent.addChild("#", "Running Request: " + runningFetch.size() + "/" + maxParallelRequests);
statusContent.addChild("br");
statusContent.addChild("#", "Queued: " + queuedStatus.count);
statusContent.addChild("br");
statusContent.addChild("#", "Succeeded: " + succeededStatus.count);
statusContent.addChild("br");
statusContent.addChild("#", "Failed: " + failedStatus.count);
statusContent.addChild("br");
statusContent.addChild("br");
statusContent.addChild("#", "Queued Event: " + callbackExecutor.getQueue().size());
statusContent.addChild("br");
statusContent.addChild("#", "Index Writer: ");
synchronized (this) {
if (writingIndex)
statusContent.addChild("span", "style", "color: red; font-weight: bold;", "RUNNING");
else if (writeIndexScheduled)
statusContent.addChild("span", "style", "color: blue; font-weight: bold;", "SCHEDULED");
else
statusContent.addChild("span", "style", "color: green; font-weight: bold;", "IDLE");
}
statusContent.addChild("br");
statusContent.addChild("#", "Last Written: "
+ (indexWriter.tProducedIndex == 0 ? "NEVER" : new Date(indexWriter.tProducedIndex).toString()));
nextTableCell.addChild(statusBox);
// Column 2
nextTableCell = overviewTableRow.addChild("td", "class", "second");
HTMLNode mainBox = pageMaker.getInfobox("Main");
HTMLNode mainContent = pageMaker.getContentNode(mainBox);
HTMLNode addForm = mainContent.addChild("form", //
new String[] { "action", "method" }, //
new String[] { "plugins.XMLSpider.XMLSpider", "post" });
addForm.addChild("label", "for", "addURI", "Add URI:");
addForm.addChild("input", new String[] { "name", "style" }, new String[] { "addURI", "width: 20em;" });
addForm.addChild("input", //
new String[] { "name", "type", "value" },//
new String[] { "formPassword", "hidden", core.formPassword });
addForm.addChild("input", "type", "submit");
nextTableCell.addChild(mainBox);
HTMLNode indexBox = pageMaker.getInfobox("Create Index");
HTMLNode indexContent = pageMaker.getContentNode(indexBox);
HTMLNode indexForm = indexContent.addChild("form", //
new String[] { "action", "method" }, //
new String[] { "plugins.XMLSpider.XMLSpider", "post" });
indexForm.addChild("input", //
new String[] { "name", "type", "value" },//
new String[] { "formPassword", "hidden", core.formPassword });
indexForm.addChild("input", //
new String[] { "name", "type", "value" },//
new String[] { "createIndex", "hidden", "createIndex" });
indexForm.addChild("input", //
new String[] { "type", "value" }, //
new String[] { "submit", "Create Index Now" });
nextTableCell.addChild(indexBox);
HTMLNode runningBox = pageMaker.getInfobox("Running URI");
runningBox.addAttribute("style", "right: 0;");
HTMLNode runningContent = pageMaker.getContentNode(runningBox);
synchronized (runningFetch) {
if (runningFetch.isEmpty()) {
HTMLNode list = runningContent.addChild("#", "NO URI");
} else {
HTMLNode list = runningContent.addChild("ol", "style", "overflow: auto; white-space: nowrap;");
Iterator<Page> pi = runningFetch.keySet().iterator();
for (int i = 0; i < maxShownURIs && pi.hasNext(); i++) {
Page page = pi.next();
HTMLNode litem = list.addChild("li", "title", page.comment);
litem.addChild("a", "href", "/freenet:" + page.uri, page.uri);
}
}
}
contentNode.addChild(runningBox);
HTMLNode queuedBox = pageMaker.getInfobox("Queued URI");
queuedBox.addAttribute("style", "right: 0; overflow: auto;");
HTMLNode queuedContent = pageMaker.getContentNode(queuedBox);
listPages(queuedStatus, queuedContent);
contentNode.addChild(queuedBox);
HTMLNode succeededBox = pageMaker.getInfobox("Succeeded URI");
succeededBox.addAttribute("style", "right: 0;");
HTMLNode succeededContent = pageMaker.getContentNode(succeededBox);
listPages(succeededStatus, succeededContent);
contentNode.addChild(succeededBox);
HTMLNode failedBox = pageMaker.getInfobox("Failed URI");
failedBox.addAttribute("style", "right: 0;");
HTMLNode failedContent = pageMaker.getContentNode(failedBox);
listPages(failedStatus, failedContent);
contentNode.addChild(failedBox);
return pageNode.generate();
}
/**
* creates the callback object for each page.
*<p>Used to create inlinks and outlinks for each page separately.
* @author swati
*
*/
public class PageCallBack implements FoundURICallback{
final Page page;
PageCallBack(Page page) {
this.page = page;
}
public void foundURI(FreenetURI uri){
// Ignore
}
public void foundURI(FreenetURI uri, boolean inline){
Logger.debug(this, "foundURI " + uri + " on " + page);
queueURI(uri, "Added from " + page.uri, false);
}
Integer lastPosition = null;
public void onText(String s, String type, URI baseURI){
Logger.debug(this, "onText on " + page.id + " (" + baseURI + ")");
if ("title".equalsIgnoreCase(type) && (s != null) && (s.length() != 0) && (s.indexOf('\n') < 0)) {
/*
* title of the page
*/
page.pageTitle = s;
type = "title";
}
else type = null;
/*
* determine the position of the word in the retrieved page
* FIXME - replace with a real tokenizor
*/
String[] words = s.split("[^\\p{L}\\{N}]+");
if(lastPosition == null)
lastPosition = 1;
for (int i = 0; i < words.length; i++) {
String word = words[i];
if ((word == null) || (word.length() == 0))
continue;
word = word.toLowerCase();
word = word.intern();
try{
if(type == null)
addWord(word, lastPosition.intValue() + i);
else
addWord(word, -1 * (i + 1));
}
catch (Exception e){}
}
if(type == null) {
lastPosition = lastPosition + words.length;
}
}
private void addWord(String word, int position) throws Exception {
if (word.length() < 3)
return;
Term term = getTermByWord(word, true);
TermPosition termPos = getTermPosition(term, true);
synchronized (termPos) {
int[] newPositions = new int[termPos.positions.length + 1];
System.arraycopy(termPos.positions, 0, newPositions, 0, termPos.positions.length);
newPositions[termPos.positions.length] = position;
termPos.positions = newPositions;
}
}
@SuppressWarnings("serial")
protected Map<Term, TermPosition> termPosCache = new LinkedHashMap<Term, TermPosition>() {
protected boolean removeEldestEntry(Map.Entry<Term, TermPosition> eldest) {
if (size() < 1024) return false;
db.store(eldest.getValue());
return true;
}
};
public void store() {
for (TermPosition tp : termPosCache.values())
db.store(tp);
termPosCache.clear();
}
protected TermPosition getTermPosition(Term term, boolean create) {
synchronized (term) {
TermPosition cachedTermPos = termPosCache.get(term);
if (cachedTermPos != null)
return cachedTermPos;
synchronized (page) {
Query query = db.query();
query.constrain(TermPosition.class);
query.descend("word").constrain(term.word);
query.descend("pageId").constrain(page.id);
@SuppressWarnings("unchecked")
ObjectSet<TermPosition> set = query.execute();
if (set.hasNext()) {
cachedTermPos = set.next();
termPosCache.put(term, cachedTermPos);
return cachedTermPos;
} else if (create) {
cachedTermPos = new TermPosition();
cachedTermPos.word = term.word;
cachedTermPos.pageId = page.id;
cachedTermPos.positions = new int[0];
termPosCache.put(term, cachedTermPos);
db.store(cachedTermPos);
return cachedTermPos;
} else {
return null;
}
}
}
}
}
public void onFoundEdition(long l, USK key){
FreenetURI uri = key.getURI();
/*-
* FIXME this code don't make sense
* (1) runningFetchesByURI contain SSK, not USK
* (2) onFoundEdition always have the edition set
*
if(runningFetchesByURI.containsKey(uri)) runningFetchesByURI.remove(uri);
uri = key.getURI().setSuggestedEdition(l);
*/
queueURI(uri, "USK found edition", true);
startSomeRequests();
}
public short getPollingPriorityNormal() {
return (short) Math.min(RequestStarter.MINIMUM_PRIORITY_CLASS, PRIORITY_CLASS + 1);
}
public short getPollingPriorityProgress() {
return PRIORITY_CLASS;
}
protected ObjectContainer db;
/**
* Initializes DB4O.
*
* @return db4o's connector
*/
private ObjectContainer initDB4O() {
Configuration cfg = Db4o.newConfiguration();
cfg.reflectWith(new JdkReflector(getClass().getClassLoader()));
//- Page
cfg.objectClass(Page.class).objectField("id").indexed(true);
cfg.objectClass(Page.class).objectField("uri").indexed(true);
cfg.objectClass(Page.class).objectField("status").indexed(true);
cfg.objectClass(Page.class).objectField("lastChange").indexed(true);
cfg.objectClass(Page.class).callConstructor(true);
//- Term
cfg.objectClass(Term.class).objectField("md5").indexed(true);
cfg.objectClass(Term.class).objectField("word").indexed(true);
cfg.objectClass(Term.class).callConstructor(true);
//- TermPosition
cfg.objectClass(TermPosition.class).objectField("pageId").indexed(true);
cfg.objectClass(TermPosition.class).objectField("word").indexed(true);
cfg.objectClass(TermPosition.class).callConstructor(true);
//- Other
cfg.activationDepth(1);
cfg.updateDepth(1);
// cfg.automaticShutDown(false);
cfg.queries().evaluationMode(QueryEvaluationMode.LAZY);
cfg.diagnostic().addListener(new DiagnosticToConsole());
ObjectContainer oc = Db4o.openFile(cfg, "XMLSpider-" + version + ".db4o");
return oc;
}
protected Page getPageByURI(FreenetURI uri) {
Query query = db.query();
query.constrain(Page.class);
query.descend("uri").constrain(uri.toString());
@SuppressWarnings("unchecked")
ObjectSet<Page> set = query.execute();
if (set.hasNext())
return set.next();
else
return null;
}
protected Page getPageById(long id) {
Query query = db.query();
query.constrain(Page.class);
query.descend("id").constrain(id);
@SuppressWarnings("unchecked")
ObjectSet<Page> set = query.execute();
if (set.hasNext())
return set.next();
else
return null;
}
protected Term getTermByMd5(String md5) {
Query query = db.query();
query.constrain(Term.class);
query.descend("md5").constrain(md5);
@SuppressWarnings("unchecked")
ObjectSet<Term> set = query.execute();
if (set.hasNext())
return set.next();
else
return null;
}
@SuppressWarnings("serial")
protected Map<String, Term> termCache = new LinkedHashMap<String, Term>() {
protected boolean removeEldestEntry(Map.Entry<String, Term> eldest) {
return size() > 1024;
}
};
// language for I10N
private LANGUAGE language;
protected Term getTermByWord(String word, boolean create) {
synchronized (this) {
Term cachedTerm = termCache.get(word);
if (cachedTerm != null)
return cachedTerm;
Query query = db.query();
query.constrain(Term.class);
query.descend("word").constrain(word);
@SuppressWarnings("unchecked")
ObjectSet<Term> set = query.execute();
if (set.hasNext()) {
cachedTerm = set.next();
termCache.put(word, cachedTerm);
return cachedTerm;
} else if (create) {
cachedTerm = new Term(word);
termCache.put(word, cachedTerm);
db.store(cachedTerm);
return cachedTerm;
} else
return null;
}
}
public String getString(String key) {
// TODO return a translated string
return key;
}
public void setLanguage(LANGUAGE newLanguage) {
language = newLanguage;
}
}
| true | true | private void startSomeRequests() {
FreenetURI[] initialURIs = core.getBookmarkURIs();
for (int i = 0; i < initialURIs.length; i++)
queueURI(initialURIs[i], "bookmark", false);
ArrayList<ClientGetter> toStart = null;
synchronized (this) {
if (stopped)
return;
synchronized (runningFetch) {
int running = runningFetch.size();
if (running >= maxParallelRequests) return;
if (queuedRequestCache.isEmpty()) {
Query query = db.query();
query.constrain(Page.class);
query.descend("status").constrain(Status.QUEUED);
query.descend("lastChange").orderAscending();
@SuppressWarnings("unchecked")
ObjectSet<Page> queuedSet = query.execute();
for (int i = 0 ;
i < maxParallelRequests * 2 && queuedSet.hasNext();
i++) { // cache 2 * maxParallelRequests
queuedRequestCache.add(queuedSet.next());
}
}
queuedRequestCache.removeAll(runningFetch.keySet());
toStart = new ArrayList<ClientGetter>(maxParallelRequests - running);
Iterator<Page> it = queuedRequestCache.iterator();
while (running + toStart.size() < maxParallelRequests && it.hasNext()) {
Page page = it.next();
try {
ClientGetter getter = makeGetter(page);
Logger.minor(this, "Starting " + getter + " " + page);
toStart.add(getter);
runningFetch.put(page, getter);
} catch (MalformedURLException e) {
Logger.error(this, "IMPOSSIBLE-Malformed URI: " + page, e);
page.status = Status.FAILED;
page.lastChange = System.currentTimeMillis();
db.store(page);
}
}
}
}
for (ClientGetter g : toStart) {
try {
g.start();
Logger.minor(this, g + " started");
} catch (FetchException e) {
Logger.minor(this, "Fetch Exception: " + g, e);
g.getClientCallback().onFailure(e, g);
}
}
}
| private void startSomeRequests() {
FreenetURI[] initialURIs = core.getBookmarkURIs();
for (int i = 0; i < initialURIs.length; i++)
queueURI(initialURIs[i], "bookmark", false);
ArrayList<ClientGetter> toStart = null;
synchronized (this) {
if (stopped)
return;
synchronized (runningFetch) {
int running = runningFetch.size();
if (running >= maxParallelRequests) return;
if (queuedRequestCache.isEmpty()) {
Query query = db.query();
query.constrain(Page.class);
query.descend("status").constrain(Status.QUEUED);
query.descend("lastChange").orderAscending();
@SuppressWarnings("unchecked")
ObjectSet<Page> queuedSet = query.execute();
for (int i = 0 ;
i < maxParallelRequests * 2 && queuedSet.hasNext();
i++) { // cache 2 * maxParallelRequests
queuedRequestCache.add(queuedSet.next());
}
}
queuedRequestCache.removeAll(runningFetch.keySet());
toStart = new ArrayList<ClientGetter>(maxParallelRequests - running);
Iterator<Page> it = queuedRequestCache.iterator();
while (running + toStart.size() < maxParallelRequests && it.hasNext()) {
Page page = it.next();
it.remove();
try {
ClientGetter getter = makeGetter(page);
Logger.minor(this, "Starting " + getter + " " + page);
toStart.add(getter);
runningFetch.put(page, getter);
} catch (MalformedURLException e) {
Logger.error(this, "IMPOSSIBLE-Malformed URI: " + page, e);
page.status = Status.FAILED;
page.lastChange = System.currentTimeMillis();
db.store(page);
}
}
}
}
for (ClientGetter g : toStart) {
try {
g.start();
Logger.minor(this, g + " started");
} catch (FetchException e) {
Logger.minor(this, "Fetch Exception: " + g, e);
g.getClientCallback().onFailure(e, g);
}
}
}
|
diff --git a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/viewport/event/ViewportEventHandler.java b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/viewport/event/ViewportEventHandler.java
index f6eb0c5f..272b1be9 100644
--- a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/viewport/event/ViewportEventHandler.java
+++ b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/viewport/event/ViewportEventHandler.java
@@ -1,93 +1,93 @@
/*******************************************************************************
* Copyright (c) 2012 Original authors and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Original authors and others - initial API and implementation
******************************************************************************/
package org.eclipse.nebula.widgets.nattable.viewport.event;
import java.util.Collection;
import org.eclipse.nebula.widgets.nattable.coordinate.Range;
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEventHandler;
import org.eclipse.nebula.widgets.nattable.layer.event.IStructuralChangeEvent;
import org.eclipse.nebula.widgets.nattable.layer.event.StructuralDiff;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
public class ViewportEventHandler implements ILayerEventHandler<IStructuralChangeEvent> {
private final ViewportLayer viewportLayer;
public ViewportEventHandler(ViewportLayer viewportLayer) {
this.viewportLayer = viewportLayer;
}
public Class<IStructuralChangeEvent> getLayerEventClass() {
return IStructuralChangeEvent.class;
}
public void handleLayerEvent(IStructuralChangeEvent event) {
if (event.isHorizontalStructureChanged()) {
viewportLayer.invalidateHorizontalStructure();
}
if (event.isVerticalStructureChanged()) {
viewportLayer.invalidateVerticalStructure();
}
Collection<StructuralDiff> columnDiffs = event.getColumnDiffs();
if (columnDiffs != null) {
int columnOffset = 0;
int minimumOriginColumnPosition = viewportLayer.getMinimumOriginColumnPosition();
for (StructuralDiff columnDiff : columnDiffs) {
switch (columnDiff.getDiffType()) {
case ADD:
Range afterPositionRange = columnDiff.getAfterPositionRange();
if (afterPositionRange.start < minimumOriginColumnPosition) {
columnOffset += afterPositionRange.size();
}
break;
case DELETE:
Range beforePositionRange = columnDiff.getBeforePositionRange();
if (beforePositionRange.start < minimumOriginColumnPosition) {
columnOffset -= Math.min(beforePositionRange.end, minimumOriginColumnPosition + 1) - beforePositionRange.start;
}
break;
}
}
- viewportLayer.setMinimumOriginX(viewportLayer.getStartXOfColumnPosition(minimumOriginColumnPosition + columnOffset));
+ viewportLayer.setMinimumOriginX(viewportLayer.getScrollableLayer().getStartXOfColumnPosition(minimumOriginColumnPosition + columnOffset));
}
Collection<StructuralDiff> rowDiffs = event.getRowDiffs();
if (rowDiffs != null) {
int rowOffset = 0;
int minimumOriginRowPosition = viewportLayer.getMinimumOriginRowPosition();
for (StructuralDiff rowDiff : rowDiffs) {
switch (rowDiff.getDiffType()) {
case ADD:
Range afterPositionRange = rowDiff.getAfterPositionRange();
if (afterPositionRange.start < minimumOriginRowPosition) {
rowOffset += afterPositionRange.size();
}
break;
case DELETE:
Range beforePositionRange = rowDiff.getBeforePositionRange();
if (beforePositionRange.start < minimumOriginRowPosition) {
rowOffset -= Math.min(beforePositionRange.end, minimumOriginRowPosition + 1) - beforePositionRange.start;
}
break;
}
}
- viewportLayer.setMinimumOriginY(viewportLayer.getStartYOfRowPosition(minimumOriginRowPosition + rowOffset));
+ viewportLayer.setMinimumOriginY(viewportLayer.getScrollableLayer().getStartYOfRowPosition(minimumOriginRowPosition + rowOffset));
}
}
}
| false | true | public void handleLayerEvent(IStructuralChangeEvent event) {
if (event.isHorizontalStructureChanged()) {
viewportLayer.invalidateHorizontalStructure();
}
if (event.isVerticalStructureChanged()) {
viewportLayer.invalidateVerticalStructure();
}
Collection<StructuralDiff> columnDiffs = event.getColumnDiffs();
if (columnDiffs != null) {
int columnOffset = 0;
int minimumOriginColumnPosition = viewportLayer.getMinimumOriginColumnPosition();
for (StructuralDiff columnDiff : columnDiffs) {
switch (columnDiff.getDiffType()) {
case ADD:
Range afterPositionRange = columnDiff.getAfterPositionRange();
if (afterPositionRange.start < minimumOriginColumnPosition) {
columnOffset += afterPositionRange.size();
}
break;
case DELETE:
Range beforePositionRange = columnDiff.getBeforePositionRange();
if (beforePositionRange.start < minimumOriginColumnPosition) {
columnOffset -= Math.min(beforePositionRange.end, minimumOriginColumnPosition + 1) - beforePositionRange.start;
}
break;
}
}
viewportLayer.setMinimumOriginX(viewportLayer.getStartXOfColumnPosition(minimumOriginColumnPosition + columnOffset));
}
Collection<StructuralDiff> rowDiffs = event.getRowDiffs();
if (rowDiffs != null) {
int rowOffset = 0;
int minimumOriginRowPosition = viewportLayer.getMinimumOriginRowPosition();
for (StructuralDiff rowDiff : rowDiffs) {
switch (rowDiff.getDiffType()) {
case ADD:
Range afterPositionRange = rowDiff.getAfterPositionRange();
if (afterPositionRange.start < minimumOriginRowPosition) {
rowOffset += afterPositionRange.size();
}
break;
case DELETE:
Range beforePositionRange = rowDiff.getBeforePositionRange();
if (beforePositionRange.start < minimumOriginRowPosition) {
rowOffset -= Math.min(beforePositionRange.end, minimumOriginRowPosition + 1) - beforePositionRange.start;
}
break;
}
}
viewportLayer.setMinimumOriginY(viewportLayer.getStartYOfRowPosition(minimumOriginRowPosition + rowOffset));
}
}
| public void handleLayerEvent(IStructuralChangeEvent event) {
if (event.isHorizontalStructureChanged()) {
viewportLayer.invalidateHorizontalStructure();
}
if (event.isVerticalStructureChanged()) {
viewportLayer.invalidateVerticalStructure();
}
Collection<StructuralDiff> columnDiffs = event.getColumnDiffs();
if (columnDiffs != null) {
int columnOffset = 0;
int minimumOriginColumnPosition = viewportLayer.getMinimumOriginColumnPosition();
for (StructuralDiff columnDiff : columnDiffs) {
switch (columnDiff.getDiffType()) {
case ADD:
Range afterPositionRange = columnDiff.getAfterPositionRange();
if (afterPositionRange.start < minimumOriginColumnPosition) {
columnOffset += afterPositionRange.size();
}
break;
case DELETE:
Range beforePositionRange = columnDiff.getBeforePositionRange();
if (beforePositionRange.start < minimumOriginColumnPosition) {
columnOffset -= Math.min(beforePositionRange.end, minimumOriginColumnPosition + 1) - beforePositionRange.start;
}
break;
}
}
viewportLayer.setMinimumOriginX(viewportLayer.getScrollableLayer().getStartXOfColumnPosition(minimumOriginColumnPosition + columnOffset));
}
Collection<StructuralDiff> rowDiffs = event.getRowDiffs();
if (rowDiffs != null) {
int rowOffset = 0;
int minimumOriginRowPosition = viewportLayer.getMinimumOriginRowPosition();
for (StructuralDiff rowDiff : rowDiffs) {
switch (rowDiff.getDiffType()) {
case ADD:
Range afterPositionRange = rowDiff.getAfterPositionRange();
if (afterPositionRange.start < minimumOriginRowPosition) {
rowOffset += afterPositionRange.size();
}
break;
case DELETE:
Range beforePositionRange = rowDiff.getBeforePositionRange();
if (beforePositionRange.start < minimumOriginRowPosition) {
rowOffset -= Math.min(beforePositionRange.end, minimumOriginRowPosition + 1) - beforePositionRange.start;
}
break;
}
}
viewportLayer.setMinimumOriginY(viewportLayer.getScrollableLayer().getStartYOfRowPosition(minimumOriginRowPosition + rowOffset));
}
}
|
diff --git a/plugins/org.eclipse.emf.eef.runtime.extended/src/org/eclipse/emf/eef/runtime/ui/editors/pages/EEFDetailsPage.java b/plugins/org.eclipse.emf.eef.runtime.extended/src/org/eclipse/emf/eef/runtime/ui/editors/pages/EEFDetailsPage.java
index 35d676fbe..3fd7d7120 100644
--- a/plugins/org.eclipse.emf.eef.runtime.extended/src/org/eclipse/emf/eef/runtime/ui/editors/pages/EEFDetailsPage.java
+++ b/plugins/org.eclipse.emf.eef.runtime.extended/src/org/eclipse/emf/eef/runtime/ui/editors/pages/EEFDetailsPage.java
@@ -1,166 +1,166 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.emf.eef.runtime.ui.editors.pages;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener;
import org.eclipse.emf.eef.runtime.context.impl.DomainPropertiesEditionContext;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.ui.editor.InteractiveEEFEditor;
import org.eclipse.emf.eef.runtime.ui.layout.EEFFormLayoutFactory;
import org.eclipse.emf.eef.runtime.ui.viewers.PropertiesEditionContentProvider;
import org.eclipse.emf.eef.runtime.ui.viewers.PropertiesEditionMessageManager;
import org.eclipse.emf.eef.runtime.ui.viewers.PropertiesEditionViewer;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.AbstractFormPart;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.widgets.FormToolkit;
/**
* @author <a href="mailto:[email protected]">Goulwen Le Fur</a>
*/
public class EEFDetailsPage extends AbstractFormPart implements IDetailsPage, IPropertiesEditionListener {
private FormToolkit toolkit;
private EditingDomain editingDomain;
protected EObject eObject;
protected IPropertiesEditionComponent propertiesEditionComponent;
/**
* Manager for error message
*/
private PropertiesEditionMessageManager messageManager;
protected PropertiesEditionViewer viewer;
private AdapterFactory adapterFactory;
public EEFDetailsPage(FormToolkit toolkit, EditingDomain editingDomain, AdapterFactory adapterFactory) {
super();
this.toolkit = toolkit;
this.editingDomain = editingDomain;
this.adapterFactory = adapterFactory;
}
public void createContents(Composite parent) {
toolkit = getManagedForm().getToolkit();
parent.setLayout(EEFFormLayoutFactory.createDetailsGridLayout(false, 1));
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite container = toolkit.createComposite(parent, SWT.FLAT);
GridLayout containerLayout = new GridLayout();
container.setLayout(containerLayout);
container.setLayoutData(new GridData(GridData.FILL_BOTH));
messageManager = new PropertiesEditionMessageManager() {
@Override
protected void updateStatus(String message) {
- if (message != null)
+ if (message != null && !"".equals(message))
getManagedForm().getForm().setMessage(message, IMessageProvider.ERROR);
else
getManagedForm().getForm().setMessage(null, IMessageProvider.NONE);
}
};
this.viewer = new PropertiesEditionViewer(container, null, SWT.NONE, 1);
viewer.setDynamicTabHeader(true);
viewer.setToolkit(getManagedForm().getToolkit());
viewer.setContentProvider(new PropertiesEditionContentProvider(adapterFactory,
IPropertiesEditionComponent.LIVE_MODE, editingDomain));
viewer.addPropertiesListener(this);
}
public void selectionChanged(IFormPart part, ISelection selection) {
if (!(selection instanceof IStructuredSelection)) {
return;
}
EObject newEObject = getEObjectFromSelection(selection);
if (newEObject != null && newEObject != eObject) {
eObject = newEObject;
if (eObject != null) {
if (viewer.getToolkit() == null)
viewer.setToolkit(toolkit);
viewer.setInput(new DomainPropertiesEditionContext(null, null, editingDomain, adapterFactory,
eObject));
viewer.addPropertiesListener(this);
}
}
}
private EObject getEObjectFromSelection(ISelection selection) {
if (selection instanceof StructuredSelection
&& (((StructuredSelection)selection).getFirstElement() instanceof EObject))
return (EObject)((StructuredSelection)selection).getFirstElement();
if (selection instanceof EObject)
return (EObject)selection;
if (selection instanceof IAdaptable && ((IAdaptable)selection).getAdapter(EObject.class) != null)
return (EObject)((IAdaptable)selection).getAdapter(EObject.class);
return null;
}
/**
* @return the viewer
*/
public PropertiesEditionViewer getViewer() {
return viewer;
}
public void firePropertiesChanged(IPropertiesEditionEvent event) {
handleChange(event);
if (event.getState() == PropertiesEditionEvent.FOCUS_CHANGED
&& event.getKind() == PropertiesEditionEvent.FOCUS_GAINED) {
// de-activate global actions
if (getEditor() instanceof InteractiveEEFEditor) {
((InteractiveEEFEditor)getEditor()).deactivateCCPActions();
}
} else if (event.getState() == PropertiesEditionEvent.FOCUS_CHANGED
&& event.getKind() == PropertiesEditionEvent.FOCUS_LOST) {
// re-activate global actions
if (getEditor() instanceof InteractiveEEFEditor) {
((InteractiveEEFEditor)getEditor()).activateCCPActions();
}
}
}
private void handleChange(IPropertiesEditionEvent event) {
// do not handle changes if you are in initialization.
if (viewer.isInitializing())
return;
messageManager.processMessage(event);
}
/**
* Retrieve the Editor from the form.
*
* @return The eef editor used to display this page.
*/
private Object getEditor() {
if (getManagedForm().getContainer() instanceof AbstractEEFMDFormPage)
return ((AbstractEEFMDFormPage)getManagedForm().getContainer()).getEditor();
return null;
}
}
| true | true | public void createContents(Composite parent) {
toolkit = getManagedForm().getToolkit();
parent.setLayout(EEFFormLayoutFactory.createDetailsGridLayout(false, 1));
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite container = toolkit.createComposite(parent, SWT.FLAT);
GridLayout containerLayout = new GridLayout();
container.setLayout(containerLayout);
container.setLayoutData(new GridData(GridData.FILL_BOTH));
messageManager = new PropertiesEditionMessageManager() {
@Override
protected void updateStatus(String message) {
if (message != null)
getManagedForm().getForm().setMessage(message, IMessageProvider.ERROR);
else
getManagedForm().getForm().setMessage(null, IMessageProvider.NONE);
}
};
this.viewer = new PropertiesEditionViewer(container, null, SWT.NONE, 1);
viewer.setDynamicTabHeader(true);
viewer.setToolkit(getManagedForm().getToolkit());
viewer.setContentProvider(new PropertiesEditionContentProvider(adapterFactory,
IPropertiesEditionComponent.LIVE_MODE, editingDomain));
viewer.addPropertiesListener(this);
}
| public void createContents(Composite parent) {
toolkit = getManagedForm().getToolkit();
parent.setLayout(EEFFormLayoutFactory.createDetailsGridLayout(false, 1));
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite container = toolkit.createComposite(parent, SWT.FLAT);
GridLayout containerLayout = new GridLayout();
container.setLayout(containerLayout);
container.setLayoutData(new GridData(GridData.FILL_BOTH));
messageManager = new PropertiesEditionMessageManager() {
@Override
protected void updateStatus(String message) {
if (message != null && !"".equals(message))
getManagedForm().getForm().setMessage(message, IMessageProvider.ERROR);
else
getManagedForm().getForm().setMessage(null, IMessageProvider.NONE);
}
};
this.viewer = new PropertiesEditionViewer(container, null, SWT.NONE, 1);
viewer.setDynamicTabHeader(true);
viewer.setToolkit(getManagedForm().getToolkit());
viewer.setContentProvider(new PropertiesEditionContentProvider(adapterFactory,
IPropertiesEditionComponent.LIVE_MODE, editingDomain));
viewer.addPropertiesListener(this);
}
|
diff --git a/Workspace/iMapDBApp/src/org/ltc/imapdbapp/iMapDBApp.java b/Workspace/iMapDBApp/src/org/ltc/imapdbapp/iMapDBApp.java
index c5eb3f8..1bb301c 100644
--- a/Workspace/iMapDBApp/src/org/ltc/imapdbapp/iMapDBApp.java
+++ b/Workspace/iMapDBApp/src/org/ltc/imapdbapp/iMapDBApp.java
@@ -1,37 +1,37 @@
/*
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.ltc.imapdbapp;
import android.os.Bundle;
import org.apache.cordova.*;
public class iMapDBApp extends DroidGap
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
super.setIntegerProperty("splashscreen", R.drawable.imap);
- super.loadUrl("file:///android_asset/www/index.html", 5000);
+ super.loadUrl("file:///android_asset/www/indexDebug.html", 5000);
//super.loadUrl("file:///android_asset/www/index.html")
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
super.setIntegerProperty("splashscreen", R.drawable.imap);
super.loadUrl("file:///android_asset/www/index.html", 5000);
//super.loadUrl("file:///android_asset/www/index.html")
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
super.setIntegerProperty("splashscreen", R.drawable.imap);
super.loadUrl("file:///android_asset/www/indexDebug.html", 5000);
//super.loadUrl("file:///android_asset/www/index.html")
}
|
diff --git a/src/main/java/com/modelmetrics/Order.java b/src/main/java/com/modelmetrics/Order.java
index 872c309..31aa0f8 100644
--- a/src/main/java/com/modelmetrics/Order.java
+++ b/src/main/java/com/modelmetrics/Order.java
@@ -1,79 +1,79 @@
package com.modelmetrics;
public class Order {
public final static int MSRP = 360400;
public final static int Option1Price = 3299;
public final static int Option2Price = 4000;
public final static int Option3Price = 400;
private String _vehicleImage;
private String _leatherType;
private String _optionOne;
private String _optionTwo;
private String _optionThree;
public Order() {
reset();
}
public String getVehicleImage() {
return _vehicleImage;
}
public void setVehicleImage(String vehicleImage) {
_vehicleImage = vehicleImage;
}
public String getLeatherType() {
return _leatherType;
}
public void setLeatherType(String leatherType) {
_leatherType = leatherType;
}
public String getOptionOne() {
return _optionOne;
}
public void setOptionOne(String optionOne) {
_optionOne = optionOne;
}
public String getOptionTwo() {
return _optionTwo;
}
public void setOptionTwo(String optionTwo) {
_optionTwo = optionTwo;
}
public String getOptionThree() {
return _optionThree;
}
public void setOptionThree(String optionThree) {
_optionThree = optionThree;
}
public void reset() {
_vehicleImage = null;
_leatherType = null;
_optionOne = null;
_optionTwo = null;
_optionThree = null;
}
public int getTotal() {
- int totalPrice = 0;
+ int totalPrice = Order.MSRP;
String[] options = {_optionOne, _optionTwo, _optionThree};
int[] price = {Option1Price, Option2Price, Option3Price};
for(int i=0; i < options.length; i++) {
if(options[i] != null && options[i].length() > 0) {
totalPrice += price[i];
}
}
return totalPrice;
}
}
| true | true | public int getTotal() {
int totalPrice = 0;
String[] options = {_optionOne, _optionTwo, _optionThree};
int[] price = {Option1Price, Option2Price, Option3Price};
for(int i=0; i < options.length; i++) {
if(options[i] != null && options[i].length() > 0) {
totalPrice += price[i];
}
}
return totalPrice;
}
| public int getTotal() {
int totalPrice = Order.MSRP;
String[] options = {_optionOne, _optionTwo, _optionThree};
int[] price = {Option1Price, Option2Price, Option3Price};
for(int i=0; i < options.length; i++) {
if(options[i] != null && options[i].length() > 0) {
totalPrice += price[i];
}
}
return totalPrice;
}
|
diff --git a/src/ZoneDessin.java b/src/ZoneDessin.java
index 6c7d5ad..b08aa86 100755
--- a/src/ZoneDessin.java
+++ b/src/ZoneDessin.java
@@ -1,232 +1,232 @@
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class ZoneDessin extends JPanel {
int largeurDessin; //La largeur de la zone de dessin
int hauteurDessin; //La longueur de la zone de dessin
Color background;
Curseur curseur;
//Les bords de la zones de dessin
int ecartHorizontal;
int ecartVertical;
private Controleur controleur;
/**
* Constructeur de la zone de dessin
*/
ZoneDessin(int largeurDessin, int hauteurDessin, Color background, Curseur curseur){
this.largeurDessin = largeurDessin;
this.hauteurDessin = hauteurDessin;
this.background = background;
this.curseur = curseur;
}
/**
* Methode dessinant la zone de dessin puis le curseur
*/
public void paintComponent(Graphics gd){
Graphics2D g = (Graphics2D)gd;
//ETAPE 1 : Afficher toutes les anciennes actions
//Background
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, this.getWidth(), this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
//Calcul de l'ecart de la zone de dessin pour centrer le dessin
ecartHorizontal = (this.getWidth() - largeurDessin)/2;
ecartVertical = (this.getHeight() - hauteurDessin)/2;
//Ombre de l'image
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + 5, ecartVertical + 5, this.largeurDessin, this.hauteurDessin);
//Image
g.setColor(background);//Couleur de fond du dessin
g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin);
//ETAPE 2 : Afficher les traceurs
Traceur t;
for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){
t = StockageDonnee.liste_dessin.get(i);
//Initialisons les propriétés de l'objet graphics
g.setColor(t.getColor());
g.setStroke(new BasicStroke(t.getEpaisseur(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine()));
System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine()));
System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee()));
System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee()));
System.out.println("Couleur Curseur : " + t.getColor());
System.out.println("Epaisseur : " + t.getEpaisseur());
//Si le t est une droite/point
if (t.getType() == 1 || t.getType() == 0){
g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee()));
}
//Si le t est un Rectangle
else if (t.getType() == 2){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur());
}
}
//Si le t est un triangle
else if (t.getType() == 3){
int[] x = {posXAbsolue(t.getXOrigine()),
posXAbsolue(t.getXArrivee()),
posXAbsolue(t.getX3())};
int[] y = {posYAbsolue(t.getYOrigine()),
posYAbsolue(t.getYArrivee()),
posYAbsolue(t.getY3())};
if(!t.estRempli()){
g.fillPolygon(x, y, 3);
}
else{
g.drawPolygon(x, y, 3);
}
}
//Si le t est un Cercle
else if (t.getType() == 4){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
}
}
//DESSINONS LE FOND
g.setStroke(new BasicStroke());
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, ecartHorizontal - 1, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight());
- g.fillRect(ecartHorizontal, 0, largeurDessin, ecartVertical);
- g.fillRect(ecartHorizontal, largeurDessin + ecartVertical, largeurDessin, ecartVertical);
+ g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical);
+ g.fillRect(ecartHorizontal - 1, largeurDessin + ecartVertical, largeurDessin + 1, ecartVertical);
//Ombre du dessin
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin);
g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5);
//ETAPE 3 : Afficher le curseur
//Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal
//Initialisons la couleur négative
/*int negRed = 255 - curseur.getCouleur().getRed();
int negGreen = 255 - curseur.getCouleur().getGreen();
int negBlue = 255 - curseur.getCouleur().getBlue();
Color neg = new Color(negRed, negGreen, negBlue);
*/
//Forme du curseur en fonction de l'outil
BasicStroke forme;
if(curseur.getType() == 0){
forme = new BasicStroke(0);
}
else{
float[] dashArray = {2, 2};
forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0);
}
g.setStroke(forme);
//AFFICHAGE DE LA BASE DU CURSEUR
//Calcul du rayon de la base
int rayonBase;
if (curseur.getEpaisseur() > 10)
rayonBase = curseur.getEpaisseur() / 2;
else rayonBase = 5;
//Dessin de la base
//Sous curseur negatif
g.setColor(Color.white);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1);
g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2);
}
//Curseur de la bonne couleur
g.setColor(Color.black);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY());
g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2);
}
//Affichage de la fleche d'orientation
//Determinons le point d'arrivée du trait symbolisant l'orientation
int tailleTrait;
if (curseur.getEpaisseur() > 40)
tailleTrait = curseur.getEpaisseur();
else tailleTrait = 40;
double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180);
//Dessinons le trait
g.setStroke(new BasicStroke(0));
g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2);
g.setColor(Color.white);
g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1);
}
/*///
* ACCESSEURS
//*/
public int posXAbsolue(int x){
return x + ecartHorizontal;
}
public int posYAbsolue(int y){
return y + ecartVertical;
}
/*///
* ACCESSEURS
//*/
public int getPosX(){
return curseur.getPosX() + ecartHorizontal;
}
public int getPosY(){
return curseur.getPosY() + ecartVertical;
}
public int getEcartHorizontal(){
return ecartHorizontal;
}
public int getEcartVertical(){
return ecartVertical;
}
public int getLargeurDessin(){
return largeurDessin;
}
public int getHauteurDessin(){
return largeurDessin;
}
public Color getBackground(){
return background;
}
/**
* Modifie le controleur
* @param c nouveau controleur
*/
public void setControleur(Controleur c)
{
this.controleur = c;
}
}
| true | true | public void paintComponent(Graphics gd){
Graphics2D g = (Graphics2D)gd;
//ETAPE 1 : Afficher toutes les anciennes actions
//Background
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, this.getWidth(), this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
//Calcul de l'ecart de la zone de dessin pour centrer le dessin
ecartHorizontal = (this.getWidth() - largeurDessin)/2;
ecartVertical = (this.getHeight() - hauteurDessin)/2;
//Ombre de l'image
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + 5, ecartVertical + 5, this.largeurDessin, this.hauteurDessin);
//Image
g.setColor(background);//Couleur de fond du dessin
g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin);
//ETAPE 2 : Afficher les traceurs
Traceur t;
for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){
t = StockageDonnee.liste_dessin.get(i);
//Initialisons les propriétés de l'objet graphics
g.setColor(t.getColor());
g.setStroke(new BasicStroke(t.getEpaisseur(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine()));
System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine()));
System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee()));
System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee()));
System.out.println("Couleur Curseur : " + t.getColor());
System.out.println("Epaisseur : " + t.getEpaisseur());
//Si le t est une droite/point
if (t.getType() == 1 || t.getType() == 0){
g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee()));
}
//Si le t est un Rectangle
else if (t.getType() == 2){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur());
}
}
//Si le t est un triangle
else if (t.getType() == 3){
int[] x = {posXAbsolue(t.getXOrigine()),
posXAbsolue(t.getXArrivee()),
posXAbsolue(t.getX3())};
int[] y = {posYAbsolue(t.getYOrigine()),
posYAbsolue(t.getYArrivee()),
posYAbsolue(t.getY3())};
if(!t.estRempli()){
g.fillPolygon(x, y, 3);
}
else{
g.drawPolygon(x, y, 3);
}
}
//Si le t est un Cercle
else if (t.getType() == 4){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
}
}
//DESSINONS LE FOND
g.setStroke(new BasicStroke());
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, ecartHorizontal - 1, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight());
g.fillRect(ecartHorizontal, 0, largeurDessin, ecartVertical);
g.fillRect(ecartHorizontal, largeurDessin + ecartVertical, largeurDessin, ecartVertical);
//Ombre du dessin
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin);
g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5);
//ETAPE 3 : Afficher le curseur
//Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal
//Initialisons la couleur négative
/*int negRed = 255 - curseur.getCouleur().getRed();
int negGreen = 255 - curseur.getCouleur().getGreen();
int negBlue = 255 - curseur.getCouleur().getBlue();
Color neg = new Color(negRed, negGreen, negBlue);
*/
//Forme du curseur en fonction de l'outil
BasicStroke forme;
if(curseur.getType() == 0){
forme = new BasicStroke(0);
}
else{
float[] dashArray = {2, 2};
forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0);
}
g.setStroke(forme);
//AFFICHAGE DE LA BASE DU CURSEUR
//Calcul du rayon de la base
int rayonBase;
if (curseur.getEpaisseur() > 10)
rayonBase = curseur.getEpaisseur() / 2;
else rayonBase = 5;
//Dessin de la base
//Sous curseur negatif
g.setColor(Color.white);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1);
g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2);
}
//Curseur de la bonne couleur
g.setColor(Color.black);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY());
g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2);
}
//Affichage de la fleche d'orientation
//Determinons le point d'arrivée du trait symbolisant l'orientation
int tailleTrait;
if (curseur.getEpaisseur() > 40)
tailleTrait = curseur.getEpaisseur();
else tailleTrait = 40;
double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180);
//Dessinons le trait
g.setStroke(new BasicStroke(0));
g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2);
g.setColor(Color.white);
g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1);
}
| public void paintComponent(Graphics gd){
Graphics2D g = (Graphics2D)gd;
//ETAPE 1 : Afficher toutes les anciennes actions
//Background
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, this.getWidth(), this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
//Calcul de l'ecart de la zone de dessin pour centrer le dessin
ecartHorizontal = (this.getWidth() - largeurDessin)/2;
ecartVertical = (this.getHeight() - hauteurDessin)/2;
//Ombre de l'image
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + 5, ecartVertical + 5, this.largeurDessin, this.hauteurDessin);
//Image
g.setColor(background);//Couleur de fond du dessin
g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin);
//ETAPE 2 : Afficher les traceurs
Traceur t;
for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){
t = StockageDonnee.liste_dessin.get(i);
//Initialisons les propriétés de l'objet graphics
g.setColor(t.getColor());
g.setStroke(new BasicStroke(t.getEpaisseur(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine()));
System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine()));
System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee()));
System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee()));
System.out.println("Couleur Curseur : " + t.getColor());
System.out.println("Epaisseur : " + t.getEpaisseur());
//Si le t est une droite/point
if (t.getType() == 1 || t.getType() == 0){
g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee()));
}
//Si le t est un Rectangle
else if (t.getType() == 2){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur());
}
}
//Si le t est un triangle
else if (t.getType() == 3){
int[] x = {posXAbsolue(t.getXOrigine()),
posXAbsolue(t.getXArrivee()),
posXAbsolue(t.getX3())};
int[] y = {posYAbsolue(t.getYOrigine()),
posYAbsolue(t.getYArrivee()),
posYAbsolue(t.getY3())};
if(!t.estRempli()){
g.fillPolygon(x, y, 3);
}
else{
g.drawPolygon(x, y, 3);
}
}
//Si le t est un Cercle
else if (t.getType() == 4){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
}
}
//DESSINONS LE FOND
g.setStroke(new BasicStroke());
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, ecartHorizontal - 1, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight());
g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical);
g.fillRect(ecartHorizontal - 1, largeurDessin + ecartVertical, largeurDessin + 1, ecartVertical);
//Ombre du dessin
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin);
g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5);
//ETAPE 3 : Afficher le curseur
//Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal
//Initialisons la couleur négative
/*int negRed = 255 - curseur.getCouleur().getRed();
int negGreen = 255 - curseur.getCouleur().getGreen();
int negBlue = 255 - curseur.getCouleur().getBlue();
Color neg = new Color(negRed, negGreen, negBlue);
*/
//Forme du curseur en fonction de l'outil
BasicStroke forme;
if(curseur.getType() == 0){
forme = new BasicStroke(0);
}
else{
float[] dashArray = {2, 2};
forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0);
}
g.setStroke(forme);
//AFFICHAGE DE LA BASE DU CURSEUR
//Calcul du rayon de la base
int rayonBase;
if (curseur.getEpaisseur() > 10)
rayonBase = curseur.getEpaisseur() / 2;
else rayonBase = 5;
//Dessin de la base
//Sous curseur negatif
g.setColor(Color.white);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1);
g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2);
}
//Curseur de la bonne couleur
g.setColor(Color.black);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY());
g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2);
}
//Affichage de la fleche d'orientation
//Determinons le point d'arrivée du trait symbolisant l'orientation
int tailleTrait;
if (curseur.getEpaisseur() > 40)
tailleTrait = curseur.getEpaisseur();
else tailleTrait = 40;
double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180);
//Dessinons le trait
g.setStroke(new BasicStroke(0));
g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2);
g.setColor(Color.white);
g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1);
}
|
diff --git a/contrib/Quote.java b/contrib/Quote.java
index fa5989c..1806e9f 100644
--- a/contrib/Quote.java
+++ b/contrib/Quote.java
@@ -1,1510 +1,1513 @@
import uk.co.uwcs.choob.*;
import uk.co.uwcs.choob.modules.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.util.*;
import java.util.regex.*;
import java.text.*;
public class QuoteObject
{
public int id;
public String quoter;
public String hostmask;
public int lines;
public int score;
public int up;
public int down;
public long time;
}
public class QuoteLine
{
public int id;
public int quoteID;
public int lineNumber;
public String nick;
public String message;
public boolean isAction;
}
public class RecentQuote
{
public QuoteObject quote;
// No sense in caching the lines here.
public long time;
/*
* 0 = displayed
* 1 = quoted
*/
public int type;
}
public class Quote
{
private static int MINLENGTH = 7; // Minimum length of a line to be quotable using simple syntax.
private static int MINWORDS = 2; // Minimum words in a line to be quotable using simple syntax.
private static int HISTORY = 100; // Lines of history to search.
private static int EXCERPT = 40; // Maximum length of excerpt text in replies to create.
private static int MAXLINES = 10; // Maximum allowed lines in a quote.
private static int MAXCLAUSES = 20; // Maximum allowed lines in a quote.
private static int MAXJOINS = 6; // Maximum allowed lines in a quote.
private static int RECENTLENGTH = 20; // Maximum length of "recent quotes" list for a context.
private static String IGNORE = "quoteme|quote|quoten|quote.create"; // Ignore these when searching for regex quotes.
private static int THRESHOLD = -3; // Lowest karma of displayed quote.
private HashMap<String,List<RecentQuote>> recentQuotes;
private Modules mods;
private IRCInterface irc;
final private Pattern ignorePattern;
public Quote( Modules mods, IRCInterface irc )
{
this.mods = mods;
this.irc = irc;
this.ignorePattern = Pattern.compile(
"^(?:" + irc.getTriggerRegex() + ")" +
"(?:" + IGNORE + ")", Pattern.CASE_INSENSITIVE);
recentQuotes = new HashMap<String,List<RecentQuote>>();
}
public String[] info()
{
return new String[] {
"Plugin to allow users to create a database of infamous quotes.",
"The Choob Team",
"[email protected]",
"$Rev$$Date$"
};
}
public String[] helpTopics = { "UsingCreate", "CreateExamples", "UsingGet" };
public String[] helpUsingCreate = {
"There's 4 ways of calling Quote.Create.",
"If you pass no parameters (or action: or privmsg:), the most recent line (or action) that's long enough will be quoted.",
"With just a nickname (or privmsg:<Nick>), the most recent line from that nick will be quoted.",
"With action:<Nick>, the most recent action from that nick will be quoted.",
"Finally, you can specify one or 2 regular expression searches. If"
+ " you specify just one, the most recent matching line will be quoted."
+ " With 2, the first one matches the start of the quote, and the"
+ " second matches the end. Previous quote commands are skipped when doing"
+ " any regex matching.",
"'Long enough' in this context means at least " + MINLENGTH
+ " characters, and at least " + MINWORDS + " words.",
"Note that nicknames are always made into their short form: 'privmsg:fred|bed' will quote people called 'fred', 'fred|busy', etc.",
"See CreateExamples for some examples."
};
// A class to track the scores of a person.
class ScoreTracker implements Comparable
{
public String name;
public int count;
// Create a new ScoreTracker, given the name of the person.
public ScoreTracker(String tname)
{
name=tname;
}
public void addQuote()
{
count++;
}
// Compare to another ScoreTracker.
public int compareTo(Object o)
{
// Ignore the "null" case.
if (o == null)
return 1;
return ((ScoreTracker)o).count - count;
}
}
public String[] helpCreateExamples = {
"'Quote.Create action:Fred' will quote the most recent action from Fred, regardless of length.",
"'Quote.Create privmsg:' will quote the most recent line that's long enough.",
"'Quote.Create fred:/blizzard/ /suck/' will quote the most recent possible quote starting with fred saying 'Blizzard', ending with the first line containing 'suck'."
};
public String[] helpUsingGet = {
"There are several clauses you can use to select quotes.",
"You can specify a number, which will be used as a quote ID.",
"A clause '<Selector>:<Relation><Number>', where <Selector> is one of 'score' or 'length', <Relation> is '>', '<' or '=' and <Number> is some number.",
"You can use 'quoter:<Nick>' to get quotes made by <Nick>.",
"Finally, you can use '<Nick>', '/<Regex>/' or '<Nick>:/<Regex>/' to match only quotes from <Nick>, quotes matching <Regex> or quotes where <Nick> said something matching <Regex>."
};
public String[] helpCommandCreate = {
"Create a new quote. See Quote.UsingCreate for more info.",
"[ [privmsg:][<Nick>] | action:[<Nick>] | [<Nick>:]/<Regex>/ [[<Nick>:]/<Regex>/] ]",
"<Nick> is a nickname to quote",
"<Regex> is a regular expression to use to match lines"
};
public void commandCreate( Message mes ) throws ChoobException
{
if (!(mes instanceof ChannelEvent))
{
irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" );
return;
}
String chan = ((ChannelEvent)mes).getChannel();
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
String param = mods.util.getParamString(mes).trim();
// Default is privmsg
if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) )
param = "privmsg:" + param;
final List<Message> lines = new ArrayList<Message>();
if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// First digit is a number. That means the rest are, too! (Or at least, we assume so.)
String bits[] = param.split(" +");
int offset = 0;
int size;
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters.");
return;
}
else if (bits.length == 2)
{
try
{
offset = Integer.parseInt(bits[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer...");
return;
}
}
try
{
size = Integer.parseInt(bits[0]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer...");
return;
}
if (offset < 0)
{
irc.sendContextReply(mes, "Can't quote things that haven't happened yet!");
return;
}
else if (size < 1)
{
irc.sendContextReply(mes, "Can't quote an empty quote!");
return;
}
else if (offset + size > history.size())
{
irc.sendContextReply(mes, "Can't quote -- memory like a seive!");
return;
}
// Must do this backwards
for(int i=offset + size - 1; i>=offset; i--)
lines.add(history.get(i));
}
else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1)
{
// It's a nickname.
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter.");
return;
}
String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase();
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
irc.sendContextReply(mes, "No quote found for nickname " + findNick + ".");
return;
}
}
else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:"))
{
Class thing;
if (param.toLowerCase().startsWith("action:"))
thing = ChannelAction.class;
else
thing = ChannelMessage.class;
// It's an action from a nickname
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter.");
return;
}
bits = bits[0].split(":");
String findNick;
if (bits.length == 2)
findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase();
else
findNick = null;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (!thing.isInstance(line))
continue;
if (findNick != null)
{
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
else
{
// Check length etc.
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
if (findNick != null)
irc.sendContextReply(mes, "No quotes found for nickname " + findNick + ".");
else
irc.sendContextReply(mes, "No recent quotes of that type!");
return;
}
}
else
{
// Final case: Regex quoting.
// Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]
// What's allowed in the //s:
final String slashslashcontent="[^/]";
// The '[NICK{:| }]/REGEX/' bit:
final String token="(?:([^\\s:/]+)[:\\s])?/(" + slashslashcontent + "+)/";
// The '[NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]' bit:
Matcher ma = Pattern.compile(token + "(?:\\s+" + token + ")?", Pattern.CASE_INSENSITIVE).matcher(param);
if (!ma.matches())
{
irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it.");
return;
}
String startNick, startRegex, endNick, endRegex;
if (ma.group(4) != null)
{
// The second parameter exists ==> multiline quote
startNick = ma.group(1);
startRegex = "(?i).*" + ma.group(2) + ".*";
endNick = ma.group(3);
endRegex = "(?i).*" + ma.group(4) + ".*";
}
else
{
startNick = null;
startRegex = null;
endNick = ma.group(1);
endRegex = "(?i).*" + ma.group(2) + ".*";
}
if (startNick != null)
startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase();
if (endNick != null)
endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase();
// OK, do the match!
int endIndex = -1, startIndex = -1;
for(int i=0; i<history.size(); i++)
{
final Message line = history.get(i);
// Completely disregard lines that are quotey.
if (ignorePattern.matcher(line.getMessage()).find())
continue;
System.out.println("<" + line.getNick() + "> " + line.getMessage());
final String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase();
if ( endRegex != null )
{
// Not matched the end yet (the regex being null is an indicator for us having matched it, obviously. But only the end regex).
if ((endNick == null || endNick.equals(nick))
&& line.getMessage().matches(endRegex))
{
// But have matched now...
endRegex = null;
endIndex = i;
// If we weren't doing a multiline regex quote, this is actually the start index.
if ( startRegex == null )
{
startIndex = i;
// And hence we're done.
break;
}
}
}
else // ..the end has been matched, and we're doing a multiline, so we're looking for the start:
{
if ((startNick == null || startNick.equals(nick)) && line.getMessage().matches(startRegex))
{
// It matches, huzzah, we're done:
startIndex = i;
break;
}
}
}
if (endIndex == -1) // We failed to match the 'first' line:
{
if (startRegex == null) // We wern't going for a multi-line match:
irc.sendContextReply(mes, "Sorry, couldn't find the line you were after.");
else
irc.sendContextReply(mes, "Sorry, the second regex (for the ending line) didn't match anything, not checking for the start line.");
return;
}
if (startIndex == -1)
{
final Message endLine=history.get(endIndex);
irc.sendContextReply(mes, "Sorry, the first regex (for the start line) couldn't be matched before the end-line I chose: " + formatPreviewLine(endLine.getNick(), endLine.getMessage(), endLine instanceof ChannelAction));
return;
}
for(int i=startIndex; i>=endIndex; i--)
lines.add(history.get(i));
}
// Have some lines.
// Is it a sensible size?
if (lines.size() > MAXLINES)
{
irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines.");
return;
}
// Check for people suspiciously quoting themselves.
// For now, that's just if they are the final line in the quote.
Message last = lines.get(lines.size() - 1);
//*/ Remove the first slash to comment me out.
if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0
&& last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0)
{
// Suspicious!
irc.sendContextReply(mes, "Sorry, no quoting yourself!");
return;
} //*/
// OK, build a QuoteObject...
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.size();
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.size());
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<lines.size(); i++)
{
QuoteLine quoteLine = new QuoteLine();
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick());
quoteLine.message = lines.get(i).getMessage();
quoteLine.isAction = (lines.get(i) instanceof ChannelAction);
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 1);
- irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) );
+ irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": (" +
+ new SimpleDateFormat("h:mma").format(new Date(lines.get(0).getMillis())).toLowerCase() +
+ ") " + formatPreview(quoteLines)
+ );
}
public String[] helpCommandAdd = {
"Add a quote to the database.",
"<Nick> <Text> [ ||| <Nick> <Text> ... ]",
"the nickname of the person who said the text (of the form '<nick>' or '* nick' or just simply 'nick')",
"the text that was actually said"
};
public java.security.Permission permissionCommandAdd = new ChoobPermission("plugins.quote.add");
public void commandAdd(Message mes)
{
mods.security.checkNickPerm(permissionCommandAdd, mes);
String params = mods.util.getParamString( mes );
String[] lines = params.split("\\s+\\|\\|\\|\\s+");
final QuoteLine[] content = new QuoteLine[lines.length];
for(int i=0; i<lines.length; i++)
{
String line = lines[i];
String nick, text;
boolean action = false;
if (line.charAt(0) == '*')
{
int spacePos1 = line.indexOf(' ');
if (spacePos1 == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
int spacePos2 = line.indexOf(' ', spacePos1 + 1);
if (spacePos2 == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
nick = line.substring(spacePos1 + 1, spacePos2);
text = line.substring(spacePos2 + 1);
action = true;
}
else if (line.charAt(0) == '<')
{
int spacePos = line.indexOf(' ');
if (spacePos == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
else if (line.charAt(spacePos - 1) != '>')
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
nick = line.substring(1, spacePos - 1);
text = line.substring(spacePos + 1);
}
else
{
int spacePos = line.indexOf(' ');
if (spacePos == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
nick = line.substring(0, spacePos);
text = line.substring(spacePos + 1);
}
QuoteLine quoteLine = new QuoteLine();
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(nick);
quoteLine.message = text;
quoteLine.isAction = action;
content[i] = quoteLine;
}
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.length;
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.length);
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
// Have to set ID etc. here in case transaction blows up.
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<content.length; i++)
{
QuoteLine quoteLine = content[i];
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
addLastQuote(mes.getContext(), quote, 1);
irc.sendContextReply( mes, "OK, added quote " + quote.id + ": " + formatPreview(quoteLines) );
}
private final String formatPreviewLine(final String nick, final String message, final boolean isAction)
{
String text, prefix;
if (message.length() > EXCERPT)
text = message.substring(0, 27) + "...";
else
text = message;
if (isAction)
prefix = "* " + nick;
else
prefix = "<" + nick + ">";
return prefix + " " + text;
}
private String formatPreview(List<QuoteLine> lines)
{
if (lines.size() == 1)
{
final QuoteLine line = lines.get(0);
return formatPreviewLine(line.nick, line.message, line.isAction);
}
else
{
// last is initalised above
QuoteLine first = lines.get(0);
String firstText;
if (first.isAction)
firstText = "* " + first.nick;
else
firstText = "<" + first.nick + ">";
if (first.message.length() > EXCERPT)
firstText += " " + first.message.substring(0, 27) + "...";
else
firstText += " " + first.message;
QuoteLine last = lines.get(lines.size() - 1);
String lastText;
if (last.isAction)
lastText = "* " + last.nick;
else
lastText = "<" + last.nick + ">";
if (last.message.length() > EXCERPT)
lastText += " " + last.message.substring(0, 27) + "...";
else
lastText += " " + last.message;
return firstText + " -> " + lastText;
}
}
public String[] helpCommandGet = {
"Get a random quote from the database.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandGet( Message mes ) throws ChoobException
{
String whereClause = getClause( mods.util.getParamString( mes ) );
List quotes;
try
{
quotes = mods.odb.retrieve( QuoteObject.class, "SORT BY RANDOM LIMIT (1) " + whereClause );
}
catch (ObjectDBError e)
{
if (e.getCause() instanceof java.sql.SQLException)
{
irc.sendContextReply( mes, "Could not retrieve: " + e.getCause() );
return;
}
else
throw e;
}
if (quotes.size() == 0)
{
irc.sendContextReply( mes, "No quotes found!" );
return;
}
QuoteObject quote = (QuoteObject)quotes.get(0);
List lines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id + " ORDER BY lineNumber");
Iterator l = lines.iterator();
if (!l.hasNext())
{
irc.sendContextReply( mes, "Found quote " + quote.id + " but it was empty!" );
return;
}
while(l.hasNext())
{
QuoteLine line = (QuoteLine)l.next();
if (line.isAction)
irc.sendContextMessage( mes, "* " + line.nick + " " + line.message );
else
irc.sendContextMessage( mes, "<" + line.nick + "> " + line.message );
}
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 0);
}
public String[] helpApiSingleLineQuote = {
"Get a single line quote from the specified nickname, optionally adding it to the recent quotes list for the passed context.",
"Either the single line quote, or null if there was none.",
"<nick> [<context>]",
"the nickname to get a quote from",
"the optional context in which the quote will be displayed"
};
public String apiSingleLineQuote(String nick)
{
return apiSingleLineQuote(nick, null);
}
public String apiSingleLineQuote(String nick, String context)
{
String whereClause = getClause(nick + " length:=1");
List quotes = mods.odb.retrieve( QuoteObject.class, "SORT BY RANDOM LIMIT (1) " + whereClause );
if (quotes.size() == 0)
return null;
QuoteObject quote = (QuoteObject)quotes.get(0);
List <QuoteLine>lines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id );
if (lines.size() == 0)
{
System.err.println("Found quote " + quote.id + " but it was empty!" );
return null;
}
if (context != null)
addLastQuote(context, quote, 0);
QuoteLine line = lines.get(0);
if (line.isAction)
return "/me " + line.message;
else
return line.message;
}
private void addLastQuote(String context, QuoteObject quote, int type)
{
synchronized(recentQuotes)
{
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null)
{
recent = new LinkedList<RecentQuote>();
recentQuotes.put( context, recent );
}
RecentQuote info = new RecentQuote();
info.quote = quote;
info.time = System.currentTimeMillis();
info.type = type;
recent.add(0, info);
while (recent.size() > RECENTLENGTH)
recent.remove( RECENTLENGTH );
}
}
public String[] helpCommandCount = {
"Get the number of matching quotes.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandCount( Message mes ) throws ChoobException
{
final String whereClause = getClause( mods.util.getParamString( mes ) );
final List<QuoteObject> quoteCounts = mods.odb.retrieve( QuoteObject.class, whereClause );
final Set<Integer> ids = new HashSet<Integer>();
for (QuoteObject q : quoteCounts)
ids.add(q.id);
final int count = ids.size();
if (count == 0)
irc.sendContextReply( mes, "Sorry, no quotes match!" );
else if (count == 1)
irc.sendContextReply( mes, "There's just the one quote..." );
else
irc.sendContextReply( mes, "There are " + count + " quotes!" );
}
/*
public String[] helpCommandScores = {
"Returns the most quoted people.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandScores( Message mes ) throws ChoobException
{
final String whereClause = getClause( mods.util.getParamString( mes ) );
//final List<QuoteObject> quoteIds = ;
HashMap <String, ScoreTracker> scores = new HashMap<String, ScoreTracker>();
final List<QuoteObject> quoteCounts = mods.odb.retrieve( QuoteObject.class, whereClause );
final Set<Integer> ids = new HashSet<Integer>();
for (QuoteObject q : quoteCounts)
ids.add(q.id);
ScoreTracker st;
for (Integer qid : ids)
{
Set<String> credititedThisQuote = new HashSet<String>();
for (QuoteLine line : (List<QuoteLine>)mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + qid))
{
//System.out.println("Crediting " + line.nick + " for their work in " + qid);
if (!credititedThisQuote.contains(line.nick))
{
if ((st = scores.get(line.nick)) == null)
scores.put(line.nick, st = new ScoreTracker(line.nick));
st.addQuote();
credititedThisQuote.add(line.nick);
}
}
}
ArrayList<ScoreTracker> l = new ArrayList(scores.values());
Collections.sort(l);
StringBuilder b = new StringBuilder("Top scorers: ");
int i=1;
for (ListIterator<ScoreTracker> it = l.listIterator(); it.hasNext() && it.nextIndex() < 5; i++)
{
ScoreTracker p = it.next();
b.append(i).append(") ").append(p.name).append(" with ").append(p.count).append(", ");
}
irc.sendContextReply(mes, b.toString());
}
*/
// quotekarma, quotesummary
public String[] helpCommandSummary = {
"Get a summary of matching quotes.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandSummary( Message mes ) throws ChoobException
{
String whereClause = getClause( mods.util.getParamString(mes) );
List<QuoteObject> quoteKarmasSpam = mods.odb.retrieve( QuoteObject.class, whereClause );
Map<Integer, QuoteObject> quoteKarmaIds = new HashMap<Integer, QuoteObject>();
for (QuoteObject q : quoteKarmasSpam)
quoteKarmaIds.put(q.id, q);
List<Integer> quoteKarmas = new ArrayList<Integer>();
for (QuoteObject q : quoteKarmaIds.values())
quoteKarmas.add(q.score);
int count = quoteKarmas.size();
int nonZeroCount = 0;
int total = 0;
int max = 0, min = 0;
for(Integer i: quoteKarmas)
{
total += i;
if (i != 0)
{
nonZeroCount++;
if (i < min)
min = i;
else if (i > max)
max = i;
}
}
DecimalFormat format = new DecimalFormat("##0.00");
String avKarma = format.format((double) total / (double) count);
String avNonZeroKarma = format.format((double) total / (double) nonZeroCount);
if (count == 0)
irc.sendContextReply( mes, "Sorry, no quotes found!" );
else if (count == 1)
irc.sendContextReply( mes, "I only found one quote; karma is " + total + "." );
else
irc.sendContextReply( mes, "Found " + count + " quotes. The total karma is " + total + ", average " + avKarma + ". " + nonZeroCount + " quotes had a karma; average for these is " + avNonZeroKarma + ". Min karma is " + min + " and max is " + max + "." );
}
public String[] helpCommandInfo = {
"Get info about a particular quote.",
"[ <QuoteID> ]",
"<QuoteID> is the ID of a quote"
};
public void commandInfo( Message mes ) throws ChoobException
{
int quoteID = -1;
List<String> params = mods.util.getParams(mes);
if ( params.size() > 2 )
{
irc.sendContextReply( mes, "Syntax: 'Quote.Info " + helpCommandInfo[1] + "'." );
return;
}
// Check input
try
{
if ( params.size() == 2 )
quoteID = Integer.parseInt( params.get(1) );
}
catch ( NumberFormatException e )
{
irc.sendContextReply( mes, "Syntax: 'Quote.Info " + helpCommandInfo[1] + "'." );
return;
}
if (quoteID == -1)
{
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
quoteID = recent.get(0).quote.id;
}
}
List<QuoteObject> quotes = mods.odb.retrieve( QuoteObject.class, "WHERE id = " + quoteID );
if (quotes.size() == 0)
{
irc.sendContextReply( mes, "Quote " + quoteID + " does not exist!" );
return;
}
QuoteObject quote = quotes.get(0);
if (quote.time == 0)
irc.sendContextReply(mes, "Quote #" + quote.id + ": Quoted by " + quote.quoter + " at Bob knows when. This is a " + quote.lines + " line quote with a karma of " + quote.score + " (" + quote.up + " up, " + quote.down + " down)." );
else
irc.sendContextReply(mes, "Quote #" + quote.id + ": Quoted by " + quote.quoter + " on " + (new Date(quote.time)) + ". This is a " + quote.lines + " line quote with a karma of " + quote.score + " (" + quote.up + " up, " + quote.down + " down)." );
}
public String[] helpCommandRemove = {
"Remove your most recently added quote.",
};
public void commandRemove( Message mes ) throws ChoobException
{
// Quotes are stored by context...
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
String nick = mods.nick.getBestPrimaryNick(mes.getNick()).toLowerCase();
String hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
Iterator<RecentQuote> iter = recent.iterator();
QuoteObject quote = null;
RecentQuote info = null;
while(iter.hasNext())
{
info = iter.next();
if (info.type == 1 && info.quote.quoter.toLowerCase().equals(nick)
&& info.quote.hostmask.equals(hostmask))
{
quote = info.quote;
break;
}
}
if (quote == null)
{
irc.sendContextReply( mes, "Sorry, you haven't quoted anything recently here!" );
return;
}
final QuoteObject theQuote = quote;
final List<QuoteLine> quoteLines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id );
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
delete(theQuote);
// Now have a quote ID!
for(QuoteLine line: quoteLines)
{
delete(line);
}
}});
recent.remove(info); // So the next unquote doesn't hit it
irc.sendContextReply( mes, "OK, unquoted quote " + quote.id + " (" + formatPreview(quoteLines) + ")." );
}
}
public String[] helpCommandLast = {
"Get a list of recent quote IDs.",
"[<Count>]",
"<Count> is the maximum number to return (default is 1)"
};
public void commandLast( Message mes ) throws ChoobException
{
// Get a count...
int count = 1;
String param = mods.util.getParamString(mes);
try
{
if ( param.length() > 0 )
count = Integer.parseInt( param );
}
catch ( NumberFormatException e )
{
irc.sendContextReply( mes, "'" + param + "' is not a valid integer!" );
return;
}
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
// Ugly hack to avoid lack of last()...
ListIterator<RecentQuote> iter = recent.listIterator();
RecentQuote info = null;
QuoteObject quote = null;
boolean first = true;
String output = null;
int remain = count;
while(iter.hasNext() && remain-- > 0)
{
info = iter.next();
if (!first)
output = output + ", " + info.quote.id;
else
output = "" + info.quote.id;
first = false;
}
if (count == 1)
irc.sendContextReply( mes, "Most recent quote ID: " + output + "." );
else
irc.sendContextReply( mes, "Most recent quote IDs (most recent first): " + output + "." );
}
}
public String[] helpCommandKarmaMod = {
"Increase or decrease the karma of a quote.",
"<Direction> [<ID>]",
"<Direction> is 'up' or 'down'",
"<ID> is an optional quote ID (default is to use the most recent)"
};
public synchronized void commandKarmaMod( Message mes ) throws ChoobException
{
int quoteID = -1;
boolean up = true;
List<String> params = mods.util.getParams(mes);
if (params.size() == 1 || params.size() > 3)
{
irc.sendContextReply( mes, "Syntax: quote.KarmaMod {up|down} [number]" );
return;
}
// Check input
try
{
if ( params.size() == 3 )
quoteID = Integer.parseInt( params.get(2) );
}
catch ( NumberFormatException e )
{
// History dictates that this be ignored.
}
if ( params.get(1).toLowerCase().equals("down") )
up = false;
else if ( params.get(1).toLowerCase().equals("up") )
up = true;
else
{
irc.sendContextReply( mes, "Syntax: quote.KarmaMod {up|down} [number]" );
return;
}
String leet;
if (up)
leet = "l33t";
else
leet = "lame";
if (quoteID == -1)
{
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
quoteID = recent.get(0).quote.id;
}
}
List quotes = mods.odb.retrieve( QuoteObject.class, "WHERE id = " + quoteID );
if (quotes.size() == 0)
{
irc.sendContextReply( mes, "No such quote to " + leet + "!" );
return;
}
QuoteObject quote = (QuoteObject)quotes.get(0);
if (up)
{
if (quote.score == THRESHOLD - 1)
{
if (mods.security.hasNickPerm( new ChoobPermission( "quote.delete" ), mes ))
{
quote.score++;
quote.up++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now leet enough to be seen! Current karma is " + quote.score + "." );
}
else
{
irc.sendContextReply( mes, "Sorry, that quote is on the karma threshold. Only an admin can make it more leet!" );
return;
}
}
else
{
quote.score++;
quote.up++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now more leet! Current karma is " + quote.score + "." );
}
}
else if (quote.score == THRESHOLD)
{
if (mods.security.hasNickPerm( new ChoobPermission( "quote.delete" ), mes ))
{
quote.score--;
quote.down++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now too lame to be seen! Current karma is " + quote.score + "." );
}
else
{
irc.sendContextReply( mes, "Sorry, that quote is on the karma threshold. Only an admin can make it more lame!" );
return;
}
}
else
{
quote.score--;
quote.down++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now more lame! Current karma is " + quote.score + "." );
}
mods.odb.update(quote);
}
/**
* Simple parser for quote searches...
*/
private String getClause(String text)
{
List<String> clauses = new ArrayList<String>();
boolean score = false; // True if score clause added.
int pos = text.equals("") ? -1 : 0;
int joins = 0;
while(pos != -1)
{
// Avoid problems with initial zero value...
if (pos != 0)
pos++;
// Initially, cut at space
int endPos = text.indexOf(' ', pos);
if (endPos == -1)
endPos = text.length();
String param = text.substring(pos, endPos);
String user = null; // User for regexes. Used later.
int colon = param.indexOf(':');
int slash = param.indexOf('/');
// If there is a /, make sure the color is before it.
if ((slash >= 0) && (colon > slash))
colon = -1;
boolean fiddled = false; // Set to true if param already parsed
if (colon != -1)
{
String first = param.substring(0, colon).toLowerCase();
param = param.substring(colon + 1);
if (param.length()==0)
throw new ChoobError("Empty selector: " + first);
if (param.charAt(0) == '/')
{
// This must be a regex with a user parameter. Save for later.
user = mods.nick.getBestPrimaryNick( first );
pos = pos + colon + 1;
}
// OK, not a regex. What else might it be?
else if (first.equals("length"))
{
// Length modifier.
if (param.length() <= 1)
throw new ChoobError("Invalid/empty length selector.");
char op = param.charAt(0);
if (op != '>' && op != '<' && op != '=')
throw new ChoobError("Invalid length selector: " + param);
int length;
try
{
length = Integer.parseInt(param.substring(1));
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid length selector: " + param);
}
clauses.add("lines " + op + " " + length);
fiddled = true;
}
else if (first.equals("quoter"))
{
if (param.length() < 1)
throw new ChoobError("Empty quoter nickname.");
clauses.add("quoter = \"" + mods.odb.escapeString(param) + "\"");
fiddled = true;
}
else if (first.equals("score"))
{
if (param.length() <= 1)
throw new ChoobError("Invalid/empty score selector.");
char op = param.charAt(0);
if (op != '>' && op != '<' && op != '=')
throw new ChoobError("Invalid score selector: " + param);
int value;
try
{
value = Integer.parseInt(param.substring(1));
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid score selector: " + param);
}
clauses.add("score " + op + " " + value);
score = true;
fiddled = true;
}
else if (first.equals("id"))
{
if (param.length() <= 1)
throw new ChoobError("Invalid/empty id selector.");
char op = param.charAt(0);
if (op != '>' && op != '<' && op != '=')
throw new ChoobError("Invalid id selector: " + param);
int value;
try
{
value = Integer.parseInt(param.substring(1));
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid id selector: " + param);
}
clauses.add("id " + op + " " + value);
fiddled = true;
}
// That's all the special cases out of the way. If we're still
// here, were's screwed...
else
{
throw new ChoobError("Unknown selector type: " + first);
}
}
if (fiddled)
{ } // Do nothing
// Right. We know that we either have a quoted nickname or a regex...
else if (param.charAt(0) == '/')
{
// This is a regex, then.
// Get a matcher on th region from here to the end of the string...
Matcher ma = Pattern.compile("^(?:\\\\.|[^\\\\/])*?/", Pattern.CASE_INSENSITIVE).matcher(text).region(pos+1,text.length());
if (!ma.find())
throw new ChoobError("Regular expression has no end!");
int end = ma.end();
String regex = text.substring(pos + 1, end - 1);
clauses.add("join"+joins+".message RLIKE \"" + mods.odb.escapeString(regex) + "\"");
if (user != null)
clauses.add("join"+joins+".nick = \"" + mods.odb.escapeString(user) + "\"");
clauses.add("join"+joins+".quoteID = id");
joins++;
pos = end-1; // In case there's a space, this is the /
}
else if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// Number -> Quote-by-ID
int value;
try
{
value = Integer.parseInt(param);
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid quote number: " + param);
}
clauses.add("id = " + value);
}
else
{
// This is a name
user = mods.nick.getBestPrimaryNick( param );
clauses.add("join"+joins+".nick = \"" + mods.odb.escapeString(user) + "\"");
clauses.add("join"+joins+".quoteID = id");
joins++;
}
// Make sure we skip any double spaces...
pos = text.indexOf(' ', pos + 1);
while( pos < text.length() - 1 && text.charAt(pos + 1) == ' ')
{
pos++;
}
// And that we haven't hopped off the end...
if (pos == text.length() - 1)
pos = -1;
}
// All those joins hate MySQL.
if (joins > MAXJOINS)
throw new ChoobError("Sorry, due to MySQL being whorish, only " + MAXJOINS + " nickname or line clause(s) allowed for now.");
else if (clauses.size() > MAXCLAUSES)
throw new ChoobError("Sorry, due to MySQL being whorish, only " + MAXCLAUSES + " clause(s) allowed for now.");
if (!score)
clauses.add("score > " + (THRESHOLD - 1));
StringBuffer search = new StringBuffer();
for(int i=0; i<joins; i++)
search.append("WITH " + QuoteLine.class.getName() + " AS join" + i + " ");
if (clauses.size() > 0)
{
search.append("WHERE ");
for(int i=0; i<clauses.size(); i++)
{
if (i != 0)
search.append(" AND ");
search.append(clauses.get(i));
}
}
return search.toString();
}
public String[] optionsUser = { "JoinMessage", "JoinQuote" };
public String[] optionsUserDefaults = { "1", "1" };
public boolean optionCheckUserJoinQuote( String optionValue, String userName ) { return _optionCheck( optionValue ); }
public boolean optionCheckUserJoinMessage( String optionValue, String userName ) { return _optionCheck( optionValue ); }
public String[] optionsGeneral = { "JoinMessage", "JoinQuote" };
public String[] optionsGeneralDefaults = { "1", "1" };
public boolean optionCheckGeneralJoinQuote( String optionValue ) { return _optionCheck( optionValue ); }
public boolean optionCheckGeneralJoinMessage( String optionValue ) { return _optionCheck( optionValue ); }
public String[] helpOptionJoinQuote = {
"Determine whether or not you recieve a quote upon joining a channel.",
"Set this to \"0\" to disable quotes, \"1\" to enable them (default),"
+ " or \"<N>:<Chans>\" with <N> \"0\" or \"1\" and <Chans> a"
+ " comma-seperated list of channels to apply <N> to. Other channels get"
+ " the opposite.",
"Example: \"1:#bots\" to enable only for #bots, or \"0:#compsoc,#tech\""
+ " to enable everywhere but #compsoc and #tech."
};
public String[] helpOptionJoinMessage = {
"Determine whether or not you recieve a message upon joining a channel.",
"Set this to \"0\" to disable quotes, \"1\" to enable them (default),"
+ " or \"<N>:<Chans>\" with <N> \"0\" or \"1\" and <Chans> a"
+ " comma-seperated list of channels to apply <N> to. Other channels get"
+ " the opposite.",
"Example: \"1:#bots\" to enable only for #bots, or \"0:#compsoc,#tech\""
+ " to enable everywhere but #compsoc and #tech."
};
// format: {0,1}[:<chanlist>]
private boolean _optionCheck(String optionValue)
{
String[] parts = optionValue.split(":", -1);
if (parts.length > 2)
return false;
if (!parts[0].equals("1") && !parts[0].equals("0"))
return false;
if (parts.length > 1)
{
// Make sure they're all channels.
String[] chans = parts[1].split(",");
for(int i=0; i<chans.length; i++)
{
if (!chans[i].startsWith("#"))
return false;
}
return true;
}
else
return true;
}
private boolean shouldMessage( ChannelJoin ev )
{
return checkOption( ev, "JoinMessage" );
}
private boolean shouldQuote( ChannelJoin ev )
{
return checkOption( ev, "JoinQuote" );
}
private boolean checkOption( ChannelJoin ev, String name )
{
return checkOption(ev, name, true) && checkOption(ev, name, false);
}
private boolean checkOption( ChannelJoin ev, String name, boolean global )
{
try
{
String value;
if (global)
value = (String)mods.plugin.callAPI("Options", "GetGeneralOption", name, "1");
else
value = (String)mods.plugin.callAPI("Options", "GetUserOption", ev.getNick(), name, "1");
String[] parts = value.split(":", -1);
boolean soFar;
if (parts[0].equals("1"))
soFar = true;
else
soFar = false;
if (parts.length > 1)
{
// If it's in the list, same, else invert.
String[] chans = parts[1].split(",");
String lcChan = ev.getChannel().toLowerCase();
for(int i=0; i<chans.length; i++)
{
if (chans[i].toLowerCase().equals(lcChan))
return soFar;
}
return !soFar;
}
else
// No list, so always same as first param.
return soFar;
}
catch (ChoobNoSuchCallException e)
{
return true;
}
}
public void onJoin( ChannelJoin ev, Modules mods, IRCInterface irc )
{
if (ev.getLogin().equalsIgnoreCase("Choob")) // XXX
return;
if (shouldMessage(ev))
{
String quote;
if ( shouldQuote(ev) )
quote = apiSingleLineQuote( ev.getNick(), ev.getContext() );
else
quote = null;
final String greeting="Hello, ";
if (quote == null)
irc.sendContextMessage( ev, greeting + ev.getNick() + "!");
else
{
for (String nick : irc.getUsers(ev.getChannel()))
{
if ( nick.equals( ev.getNick() ) )
continue;
quote = quote.replaceAll(
nick.replaceAll("([^a-zA-Z0-9_])", "\\\\$1"),
nick.replaceAll("([a-zA-Z])([^, ]+)","$1'$2")
);
}
irc.sendContextMessage( ev, greeting + ev.getNick() + ": \"" + quote + "\"");
}
}
}
}
| true | true | public void commandCreate( Message mes ) throws ChoobException
{
if (!(mes instanceof ChannelEvent))
{
irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" );
return;
}
String chan = ((ChannelEvent)mes).getChannel();
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
String param = mods.util.getParamString(mes).trim();
// Default is privmsg
if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) )
param = "privmsg:" + param;
final List<Message> lines = new ArrayList<Message>();
if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// First digit is a number. That means the rest are, too! (Or at least, we assume so.)
String bits[] = param.split(" +");
int offset = 0;
int size;
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters.");
return;
}
else if (bits.length == 2)
{
try
{
offset = Integer.parseInt(bits[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer...");
return;
}
}
try
{
size = Integer.parseInt(bits[0]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer...");
return;
}
if (offset < 0)
{
irc.sendContextReply(mes, "Can't quote things that haven't happened yet!");
return;
}
else if (size < 1)
{
irc.sendContextReply(mes, "Can't quote an empty quote!");
return;
}
else if (offset + size > history.size())
{
irc.sendContextReply(mes, "Can't quote -- memory like a seive!");
return;
}
// Must do this backwards
for(int i=offset + size - 1; i>=offset; i--)
lines.add(history.get(i));
}
else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1)
{
// It's a nickname.
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter.");
return;
}
String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase();
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
irc.sendContextReply(mes, "No quote found for nickname " + findNick + ".");
return;
}
}
else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:"))
{
Class thing;
if (param.toLowerCase().startsWith("action:"))
thing = ChannelAction.class;
else
thing = ChannelMessage.class;
// It's an action from a nickname
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter.");
return;
}
bits = bits[0].split(":");
String findNick;
if (bits.length == 2)
findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase();
else
findNick = null;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (!thing.isInstance(line))
continue;
if (findNick != null)
{
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
else
{
// Check length etc.
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
if (findNick != null)
irc.sendContextReply(mes, "No quotes found for nickname " + findNick + ".");
else
irc.sendContextReply(mes, "No recent quotes of that type!");
return;
}
}
else
{
// Final case: Regex quoting.
// Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]
// What's allowed in the //s:
final String slashslashcontent="[^/]";
// The '[NICK{:| }]/REGEX/' bit:
final String token="(?:([^\\s:/]+)[:\\s])?/(" + slashslashcontent + "+)/";
// The '[NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]' bit:
Matcher ma = Pattern.compile(token + "(?:\\s+" + token + ")?", Pattern.CASE_INSENSITIVE).matcher(param);
if (!ma.matches())
{
irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it.");
return;
}
String startNick, startRegex, endNick, endRegex;
if (ma.group(4) != null)
{
// The second parameter exists ==> multiline quote
startNick = ma.group(1);
startRegex = "(?i).*" + ma.group(2) + ".*";
endNick = ma.group(3);
endRegex = "(?i).*" + ma.group(4) + ".*";
}
else
{
startNick = null;
startRegex = null;
endNick = ma.group(1);
endRegex = "(?i).*" + ma.group(2) + ".*";
}
if (startNick != null)
startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase();
if (endNick != null)
endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase();
// OK, do the match!
int endIndex = -1, startIndex = -1;
for(int i=0; i<history.size(); i++)
{
final Message line = history.get(i);
// Completely disregard lines that are quotey.
if (ignorePattern.matcher(line.getMessage()).find())
continue;
System.out.println("<" + line.getNick() + "> " + line.getMessage());
final String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase();
if ( endRegex != null )
{
// Not matched the end yet (the regex being null is an indicator for us having matched it, obviously. But only the end regex).
if ((endNick == null || endNick.equals(nick))
&& line.getMessage().matches(endRegex))
{
// But have matched now...
endRegex = null;
endIndex = i;
// If we weren't doing a multiline regex quote, this is actually the start index.
if ( startRegex == null )
{
startIndex = i;
// And hence we're done.
break;
}
}
}
else // ..the end has been matched, and we're doing a multiline, so we're looking for the start:
{
if ((startNick == null || startNick.equals(nick)) && line.getMessage().matches(startRegex))
{
// It matches, huzzah, we're done:
startIndex = i;
break;
}
}
}
if (endIndex == -1) // We failed to match the 'first' line:
{
if (startRegex == null) // We wern't going for a multi-line match:
irc.sendContextReply(mes, "Sorry, couldn't find the line you were after.");
else
irc.sendContextReply(mes, "Sorry, the second regex (for the ending line) didn't match anything, not checking for the start line.");
return;
}
if (startIndex == -1)
{
final Message endLine=history.get(endIndex);
irc.sendContextReply(mes, "Sorry, the first regex (for the start line) couldn't be matched before the end-line I chose: " + formatPreviewLine(endLine.getNick(), endLine.getMessage(), endLine instanceof ChannelAction));
return;
}
for(int i=startIndex; i>=endIndex; i--)
lines.add(history.get(i));
}
// Have some lines.
// Is it a sensible size?
if (lines.size() > MAXLINES)
{
irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines.");
return;
}
// Check for people suspiciously quoting themselves.
// For now, that's just if they are the final line in the quote.
Message last = lines.get(lines.size() - 1);
//*/ Remove the first slash to comment me out.
if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0
&& last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0)
{
// Suspicious!
irc.sendContextReply(mes, "Sorry, no quoting yourself!");
return;
} //*/
// OK, build a QuoteObject...
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.size();
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.size());
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<lines.size(); i++)
{
QuoteLine quoteLine = new QuoteLine();
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick());
quoteLine.message = lines.get(i).getMessage();
quoteLine.isAction = (lines.get(i) instanceof ChannelAction);
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 1);
irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) );
}
| public void commandCreate( Message mes ) throws ChoobException
{
if (!(mes instanceof ChannelEvent))
{
irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" );
return;
}
String chan = ((ChannelEvent)mes).getChannel();
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
String param = mods.util.getParamString(mes).trim();
// Default is privmsg
if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) )
param = "privmsg:" + param;
final List<Message> lines = new ArrayList<Message>();
if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// First digit is a number. That means the rest are, too! (Or at least, we assume so.)
String bits[] = param.split(" +");
int offset = 0;
int size;
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters.");
return;
}
else if (bits.length == 2)
{
try
{
offset = Integer.parseInt(bits[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer...");
return;
}
}
try
{
size = Integer.parseInt(bits[0]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer...");
return;
}
if (offset < 0)
{
irc.sendContextReply(mes, "Can't quote things that haven't happened yet!");
return;
}
else if (size < 1)
{
irc.sendContextReply(mes, "Can't quote an empty quote!");
return;
}
else if (offset + size > history.size())
{
irc.sendContextReply(mes, "Can't quote -- memory like a seive!");
return;
}
// Must do this backwards
for(int i=offset + size - 1; i>=offset; i--)
lines.add(history.get(i));
}
else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1)
{
// It's a nickname.
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter.");
return;
}
String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase();
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
irc.sendContextReply(mes, "No quote found for nickname " + findNick + ".");
return;
}
}
else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:"))
{
Class thing;
if (param.toLowerCase().startsWith("action:"))
thing = ChannelAction.class;
else
thing = ChannelMessage.class;
// It's an action from a nickname
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter.");
return;
}
bits = bits[0].split(":");
String findNick;
if (bits.length == 2)
findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase();
else
findNick = null;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (!thing.isInstance(line))
continue;
if (findNick != null)
{
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
else
{
// Check length etc.
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
if (findNick != null)
irc.sendContextReply(mes, "No quotes found for nickname " + findNick + ".");
else
irc.sendContextReply(mes, "No recent quotes of that type!");
return;
}
}
else
{
// Final case: Regex quoting.
// Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]
// What's allowed in the //s:
final String slashslashcontent="[^/]";
// The '[NICK{:| }]/REGEX/' bit:
final String token="(?:([^\\s:/]+)[:\\s])?/(" + slashslashcontent + "+)/";
// The '[NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]' bit:
Matcher ma = Pattern.compile(token + "(?:\\s+" + token + ")?", Pattern.CASE_INSENSITIVE).matcher(param);
if (!ma.matches())
{
irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it.");
return;
}
String startNick, startRegex, endNick, endRegex;
if (ma.group(4) != null)
{
// The second parameter exists ==> multiline quote
startNick = ma.group(1);
startRegex = "(?i).*" + ma.group(2) + ".*";
endNick = ma.group(3);
endRegex = "(?i).*" + ma.group(4) + ".*";
}
else
{
startNick = null;
startRegex = null;
endNick = ma.group(1);
endRegex = "(?i).*" + ma.group(2) + ".*";
}
if (startNick != null)
startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase();
if (endNick != null)
endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase();
// OK, do the match!
int endIndex = -1, startIndex = -1;
for(int i=0; i<history.size(); i++)
{
final Message line = history.get(i);
// Completely disregard lines that are quotey.
if (ignorePattern.matcher(line.getMessage()).find())
continue;
System.out.println("<" + line.getNick() + "> " + line.getMessage());
final String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase();
if ( endRegex != null )
{
// Not matched the end yet (the regex being null is an indicator for us having matched it, obviously. But only the end regex).
if ((endNick == null || endNick.equals(nick))
&& line.getMessage().matches(endRegex))
{
// But have matched now...
endRegex = null;
endIndex = i;
// If we weren't doing a multiline regex quote, this is actually the start index.
if ( startRegex == null )
{
startIndex = i;
// And hence we're done.
break;
}
}
}
else // ..the end has been matched, and we're doing a multiline, so we're looking for the start:
{
if ((startNick == null || startNick.equals(nick)) && line.getMessage().matches(startRegex))
{
// It matches, huzzah, we're done:
startIndex = i;
break;
}
}
}
if (endIndex == -1) // We failed to match the 'first' line:
{
if (startRegex == null) // We wern't going for a multi-line match:
irc.sendContextReply(mes, "Sorry, couldn't find the line you were after.");
else
irc.sendContextReply(mes, "Sorry, the second regex (for the ending line) didn't match anything, not checking for the start line.");
return;
}
if (startIndex == -1)
{
final Message endLine=history.get(endIndex);
irc.sendContextReply(mes, "Sorry, the first regex (for the start line) couldn't be matched before the end-line I chose: " + formatPreviewLine(endLine.getNick(), endLine.getMessage(), endLine instanceof ChannelAction));
return;
}
for(int i=startIndex; i>=endIndex; i--)
lines.add(history.get(i));
}
// Have some lines.
// Is it a sensible size?
if (lines.size() > MAXLINES)
{
irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines.");
return;
}
// Check for people suspiciously quoting themselves.
// For now, that's just if they are the final line in the quote.
Message last = lines.get(lines.size() - 1);
//*/ Remove the first slash to comment me out.
if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0
&& last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0)
{
// Suspicious!
irc.sendContextReply(mes, "Sorry, no quoting yourself!");
return;
} //*/
// OK, build a QuoteObject...
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.size();
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.size());
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<lines.size(); i++)
{
QuoteLine quoteLine = new QuoteLine();
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick());
quoteLine.message = lines.get(i).getMessage();
quoteLine.isAction = (lines.get(i) instanceof ChannelAction);
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 1);
irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": (" +
new SimpleDateFormat("h:mma").format(new Date(lines.get(0).getMillis())).toLowerCase() +
") " + formatPreview(quoteLines)
);
}
|
diff --git a/src/web/org/openmrs/web/controller/ConceptFormController.java b/src/web/org/openmrs/web/controller/ConceptFormController.java
index 34aac050..a9346428 100644
--- a/src/web/org/openmrs/web/controller/ConceptFormController.java
+++ b/src/web/org/openmrs/web/controller/ConceptFormController.java
@@ -1,823 +1,824 @@
/**
* 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;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.ConceptAnswer;
import org.openmrs.ConceptComplex;
import org.openmrs.ConceptDescription;
import org.openmrs.ConceptMap;
import org.openmrs.ConceptName;
import org.openmrs.ConceptNumeric;
import org.openmrs.ConceptSet;
import org.openmrs.Form;
import org.openmrs.api.APIException;
import org.openmrs.api.ConceptNameType;
import org.openmrs.api.ConceptService;
import org.openmrs.api.ConceptsLockedException;
import org.openmrs.api.DuplicateConceptNameException;
import org.openmrs.api.context.Context;
import org.openmrs.propertyeditor.ConceptAnswersEditor;
import org.openmrs.propertyeditor.ConceptClassEditor;
import org.openmrs.propertyeditor.ConceptDatatypeEditor;
import org.openmrs.propertyeditor.ConceptSetsEditor;
import org.openmrs.propertyeditor.ConceptSourceEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.validator.ConceptValidator;
import org.openmrs.web.WebConstants;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.util.StringUtils;
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;
/**
* This is the controlling class for hte conceptForm.jsp page. It initBinder and formBackingObject
* are called before page load. After submission, formBackingObject (because we're not a session
* form), processFormSubmission, and onSubmit methods are called
*
* @see org.openmrs.Concept
*/
public class ConceptFormController extends SimpleFormController {
/** Logger for this class and subclasses */
private static final Log log = LogFactory.getLog(ConceptFormController.class);
/**
* Allows for other Objects 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)
*/
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
ConceptFormBackingObject commandObject = (ConceptFormBackingObject) binder.getTarget();
NumberFormat nf = NumberFormat.getInstance(Context.getLocale());
binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, nf, true));
binder.registerCustomEditor(java.lang.Double.class, new CustomNumberEditor(java.lang.Double.class, nf, true));
binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(SimpleDateFormat.getDateInstance(
SimpleDateFormat.SHORT, Context.getLocale()), true));
binder.registerCustomEditor(org.openmrs.ConceptClass.class, new ConceptClassEditor());
binder.registerCustomEditor(org.openmrs.ConceptDatatype.class, new ConceptDatatypeEditor());
binder.registerCustomEditor(java.util.Collection.class, "concept.conceptSets", new ConceptSetsEditor(commandObject
.getConcept().getConceptSets()));
binder.registerCustomEditor(java.util.Collection.class, "concept.answers", new ConceptAnswersEditor(commandObject
.getConcept().getAnswers(true)));
binder.registerCustomEditor(org.openmrs.ConceptSource.class, new ConceptSourceEditor());
}
/**
* @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object,
BindException errors) throws Exception {
Concept concept = ((ConceptFormBackingObject) object).getConcept();
ConceptService cs = Context.getConceptService();
// check to see if they clicked next/previous concept:
String jumpAction = request.getParameter("jumpAction");
if (jumpAction != null) {
Concept newConcept = null;
if ("previous".equals(jumpAction))
newConcept = cs.getPrevConcept(concept);
else if ("next".equals(jumpAction))
newConcept = cs.getNextConcept(concept);
if (newConcept != null)
return new ModelAndView(new RedirectView(getSuccessView() + "?conceptId=" + newConcept.getConceptId()));
else
return new ModelAndView(new RedirectView(getSuccessView()));
}
return super.processFormSubmission(request, response, object, errors);
}
/**
* 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)
* @should display numeric values from table
* @should copy numeric values into numeric concepts
* @should return a concept with a null id if no match is found
*/
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
ConceptService cs = Context.getConceptService();
if (Context.isAuthenticated()) {
ConceptFormBackingObject conceptBackingObject = (ConceptFormBackingObject) obj;
MessageSourceAccessor msa = getMessageSourceAccessor();
String action = request.getParameter("action");
if (action.equals(msa.getMessage("Concept.delete", "Delete Concept"))) {
Concept concept = conceptBackingObject.getConcept();
try {
cs.purgeConcept(concept);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Concept.deleted");
return new ModelAndView(new RedirectView("index.htm"));
}
catch (ConceptsLockedException cle) {
log.error("Tried to delete concept while concepts were locked", cle);
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.concepts.locked");
}
catch (DataIntegrityViolationException e) {
log.error("Unable to delete a concept because it is in use: " + concept, e);
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.delete");
}
catch (Exception e) {
log.error("Unable to delete concept because an error occurred: " + concept, e);
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.delete");
}
// return to the edit screen because an error was thrown
return new ModelAndView(new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));
} else {
Concept concept = conceptBackingObject.getConceptFromFormData();
//if the user is editing a concept, initialise the associated creator property
//this is aimed at avoiding a lazy initialisation exception when rendering
//the jsp after validation has failed
if (concept.getConceptId() != null)
concept.getCreator().getPersonName();
try {
new ConceptValidator().validate(concept, errors);
if (!errors.hasErrors()) {
cs.saveConcept(concept);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Concept.saved");
return new ModelAndView(new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));
}
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.save");
}
catch (ConceptsLockedException cle) {
log.error("Tried to save concept while concepts were locked", cle);
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.concepts.locked");
errors.reject("concept", "Concept.concepts.locked");
}
catch (DuplicateConceptNameException e) {
log.error("Tried to save concept with a duplicate name");
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.save");
errors.rejectValue("concept", "Concept.name.duplicate");
}
catch (APIException e) {
log.error("Error while trying to save concept", e);
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.save");
errors.reject("concept", "Concept.cannot.save");
}
// return to the edit form because an error was thrown
return showForm(request, response, errors);
}
}
return new ModelAndView(new RedirectView(getFormView()));
}
/**
* 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)
*/
@Override
protected ConceptFormBackingObject formBackingObject(HttpServletRequest request) throws ServletException {
String conceptId = request.getParameter("conceptId");
try {
ConceptService cs = Context.getConceptService();
Concept concept = cs.getConcept(Integer.valueOf(conceptId));
if (concept == null) {
return new ConceptFormBackingObject(new Concept());
} else {
return new ConceptFormBackingObject(concept);
}
}
catch (NumberFormatException ex) {
return new ConceptFormBackingObject(new Concept());
}
}
/**
* Called prior to form display. Allows for data to be put in the request to be used in the view
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
*/
@Override
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
ConceptService cs = Context.getConceptService();
String defaultVerbose = "false";
if (Context.isAuthenticated())
defaultVerbose = Context.getAuthenticatedUser().getUserProperty(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE);
map.put("defaultVerbose", defaultVerbose.equals("true") ? true : false);
map.put("tags", cs.getAllConceptNameTags());
//get complete class and datatype lists
map.put("classes", cs.getAllConceptClasses());
map.put("datatypes", cs.getAllConceptDatatypes());
String conceptId = request.getParameter("conceptId");
boolean dataTypeReadOnly = false;
try {
Concept concept = cs.getConcept(Integer.valueOf(conceptId));
dataTypeReadOnly = cs.hasAnyObservation(concept);
if (concept != null && concept.getDatatype().isBoolean())
map.put("isBoolean", true);
}
catch (NumberFormatException ex) {
// nothing to do
}
map.put("dataTypeReadOnly", dataTypeReadOnly);
//get complex handlers
map.put("handlers", Context.getObsService().getHandlers());
// make spring locale available to jsp
map.put("locale", Context.getLocale()); // should be same string format as conceptNamesByLocale map keys
return map;
}
/**
* Class that represents all data on this form
*/
public class ConceptFormBackingObject {
public Concept concept = null;
public List<Locale> locales = null;
public Map<Locale, ConceptName> namesByLocale = new HashMap<Locale, ConceptName>();
public Map<Locale, ConceptName> shortNamesByLocale = new HashMap<Locale, ConceptName>();
public Map<Locale, List<ConceptName>> synonymsByLocale = new HashMap<Locale, List<ConceptName>>();
public Map<Locale, ConceptDescription> descriptionsByLocale = new HashMap<Locale, ConceptDescription>();
public Map<Locale, List<ConceptName>> indexTermsByLocale = new HashMap<Locale, List<ConceptName>>();
public List<ConceptMap> mappings; // a "lazy list" version of the concept.getMappings() list
public Double hiAbsolute;
public Double lowAbsolute;
public Double lowCritical;
public Double hiCritical;
public Double lowNormal;
public Double hiNormal;
public boolean precise = false;
public String units;
public String handlerKey;
public Map<Locale, String> preferredNamesByLocale = new HashMap<Locale, String>();
/**
* Default constructor must take in a Concept object to create itself
*
* @param concept The concept for this page
*/
@SuppressWarnings("unchecked")
public ConceptFormBackingObject(Concept concept) {
this.concept = concept;
this.locales = Context.getAdministrationService().getAllowedLocales();
for (Locale locale : locales) {
ConceptName preferredName = concept.getPreferredName(locale);
preferredNamesByLocale.put(locale, (preferredName != null ? preferredName.getName() : null));
namesByLocale.put(locale, concept.getFullySpecifiedName(locale));
shortNamesByLocale.put(locale, concept.getShortNameInLocale(locale));
synonymsByLocale.put(locale, (List<ConceptName>) concept.getSynonyms(locale));
descriptionsByLocale.put(locale, concept.getDescription(locale, true));
indexTermsByLocale.put(locale, (List<ConceptName>) concept.getIndexTermsForLocale(locale));
// put in default values so the binding doesn't fail
if (namesByLocale.get(locale) == null)
namesByLocale.put(locale, new ConceptName(null, locale));
if (shortNamesByLocale.get(locale) == null)
shortNamesByLocale.put(locale, new ConceptName(null, locale));
if (descriptionsByLocale.get(locale) == null)
descriptionsByLocale.put(locale, new ConceptDescription(null, locale));
synonymsByLocale.put(locale, ListUtils.lazyList(synonymsByLocale.get(locale), FactoryUtils
.instantiateFactory(ConceptName.class)));
indexTermsByLocale.put(locale, ListUtils.lazyList(indexTermsByLocale.get(locale), FactoryUtils
.instantiateFactory(ConceptName.class)));
}
// turn the list objects into lazy lists
mappings = ListUtils.lazyList(new Vector(concept.getConceptMappings()), FactoryUtils
.instantiateFactory(ConceptMap.class));
if (concept.isNumeric()) {
ConceptNumeric cn = (ConceptNumeric) concept;
this.hiAbsolute = cn.getHiAbsolute();
this.lowAbsolute = cn.getLowAbsolute();
this.lowCritical = cn.getLowCritical();
this.hiCritical = cn.getHiCritical();
this.lowNormal = cn.getLowNormal();
this.hiNormal = cn.getHiNormal();
this.precise = cn.getPrecise();
this.units = cn.getUnits();
} else if (concept.isComplex()) {
ConceptComplex complex = (ConceptComplex) concept;
this.handlerKey = complex.getHandler();
}
}
/**
* This method takes all the form data from the input boxes and puts it onto the concept
* object so that it can be saved to the database
*
* @return the concept to be saved to the database
*/
public Concept getConceptFromFormData() {
// add all the new names/descriptions to the concept
for (Locale locale : locales) {
ConceptName fullySpecifiedNameInLocale = namesByLocale.get(locale);
if (StringUtils.hasText(fullySpecifiedNameInLocale.getName())) {
concept.setFullySpecifiedName(fullySpecifiedNameInLocale);
if (fullySpecifiedNameInLocale.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale))) {
concept.setPreferredName(fullySpecifiedNameInLocale);
}
}
ConceptName shortNameInLocale = shortNamesByLocale.get(locale);
if (StringUtils.hasText(shortNameInLocale.getName())) {
concept.setShortName(shortNameInLocale);
}
for (ConceptName synonym : synonymsByLocale.get(locale)) {
if (synonym != null && StringUtils.hasText(synonym.getName())) {
synonym.setLocale(locale);
- if (synonym.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale))) {
+ //donot set voided names otherwise setPreferredname(() will throw an exception
+ if (synonym.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale)) && !synonym.isVoided()) {
concept.setPreferredName(synonym);
} else if (!concept.getNames().contains(synonym) && !concept.hasName(synonym.getName(), locale)) {
//we leave systemTag field as null to indicate that it is a synonym
concept.addName(synonym);
}
//if the user removed this synonym with a void reason, returned to the page due validation errors,
//then they chose to cancel the removal of the synonym but forgot to clear the void reason text box,
//clear the text
if (!synonym.isVoided())
synonym.setVoidReason(null);
else if (synonym.isVoided() && !StringUtils.hasText(synonym.getVoidReason()))
synonym.setVoidReason(Context.getMessageSourceService().getMessage(
"Concept.name.default.voidReason"));
}
}
for (ConceptName indexTerm : indexTermsByLocale.get(locale)) {
if (indexTerm != null && StringUtils.hasText(indexTerm.getName())) {
if (!concept.getNames().contains(indexTerm) && !concept.hasName(indexTerm.getName(), locale)) {
indexTerm.setConceptNameType(ConceptNameType.INDEX_TERM);
indexTerm.setLocale(locale);
concept.addName(indexTerm);
}
if (!indexTerm.isVoided())
indexTerm.setVoidReason(null);
else if (indexTerm.isVoided() && !StringUtils.hasText(indexTerm.getVoidReason()))
indexTerm.setVoidReason(Context.getMessageSourceService().getMessage(
"Concept.name.default.voidReason"));
}
}
ConceptDescription descInLocale = descriptionsByLocale.get(locale);
if (StringUtils.hasLength(descInLocale.getDescription())
&& !concept.getDescriptions().contains(descInLocale)) {
concept.addDescription(descInLocale);
}
}
// add in all the mappings
for (ConceptMap map : mappings) {
if (map != null) {
if (map.getSourceCode() == null) {
// because of the _mappings[x].sourceCode input name in the jsp, the sourceCode will be empty for
// deleted mappings. remove those from the concept object now.
concept.removeConceptMapping(map);
} else if (!concept.getConceptMappings().contains(map)) {
// assumes null sources also don't get here
concept.addConceptMapping(map);
}
}
}
// if the user unchecked the concept sets box, erase past saved sets
if (!concept.isSet()) {
if (concept.getConceptSets() != null) {
concept.getConceptSets().clear();
}
}
// if the user changed the datatype to be non "Coded", erase past saved datatypes
if (!concept.getDatatype().isCoded()) {
if (concept.getAnswers(true) != null) {
concept.getAnswers(true).clear();
}
}
// add in subobject specific code
if (concept.getDatatype().getName().equals("Numeric")) {
ConceptNumeric cn;
if (concept instanceof ConceptNumeric)
cn = (ConceptNumeric) concept;
else {
cn = new ConceptNumeric(concept);
}
cn.setHiAbsolute(hiAbsolute);
cn.setLowAbsolute(lowAbsolute);
cn.setHiCritical(hiCritical);
cn.setLowCritical(lowCritical);
cn.setHiNormal(hiNormal);
cn.setLowNormal(lowNormal);
cn.setPrecise(precise);
cn.setUnits(units);
concept = cn;
} else if (concept.getDatatype().getName().equals("Complex")) {
ConceptComplex complexConcept;
if (concept instanceof ConceptComplex)
complexConcept = (ConceptComplex) concept;
else {
complexConcept = new ConceptComplex(concept);
}
complexConcept.setHandler(handlerKey);
concept = complexConcept;
}
return concept;
}
/**
* @return the concept
*/
public Concept getConcept() {
return concept;
}
/**
* @param concept the concept to set
*/
public void setConcept(Concept concept) {
this.concept = concept;
}
/**
* @return the locales
*/
public List<Locale> getLocales() {
return locales;
}
/**
* @param locales the locales to set
*/
public void setLocales(List<Locale> locales) {
this.locales = locales;
}
/**
* @return the namesByLocale
*/
public Map<Locale, ConceptName> getNamesByLocale() {
return namesByLocale;
}
/**
* @param namesByLocale the namesByLocale to set
*/
public void setNamesByLocale(Map<Locale, ConceptName> namesByLocale) {
this.namesByLocale = namesByLocale;
}
/**
* @return the shortNamesByLocale
*/
public Map<Locale, ConceptName> getShortNamesByLocale() {
return shortNamesByLocale;
}
/**
* @param shortNamesByLocale the shortNamesByLocale to set
*/
public void setShortNamesByLocale(Map<Locale, ConceptName> shortNamesByLocale) {
this.shortNamesByLocale = shortNamesByLocale;
}
/**
* @return the descriptionsByLocale
*/
public Map<Locale, ConceptDescription> getDescriptionsByLocale() {
return descriptionsByLocale;
}
/**
* @param descriptionsByLocale the descriptionsByLocale to set
*/
public void setDescriptionsByLocale(Map<Locale, ConceptDescription> descriptionsByLocale) {
this.descriptionsByLocale = descriptionsByLocale;
}
/**
* @return the mappings
*/
public List<ConceptMap> getMappings() {
return mappings;
}
/**
* @param mappings the mappings to set
*/
public void setMappings(List<ConceptMap> mappings) {
this.mappings = mappings;
}
/**
* @return the synonymsByLocale
*/
public Map<Locale, List<ConceptName>> getSynonymsByLocale() {
return synonymsByLocale;
}
/**
* @param synonymsByLocale the synonymsByLocale to set
*/
public void setSynonymsByLocale(Map<Locale, List<ConceptName>> synonymsByLocale) {
this.synonymsByLocale = synonymsByLocale;
}
/**
* @return the hiAbsolute
*/
public Double getHiAbsolute() {
return hiAbsolute;
}
/**
* @param hiAbsolute the hiAbsolute to set
*/
public void setHiAbsolute(Double hiAbsolute) {
this.hiAbsolute = hiAbsolute;
}
/**
* @return the lowAbsolute
*/
public Double getLowAbsolute() {
return lowAbsolute;
}
/**
* @param lowAbsolute the lowAbsolute to set
*/
public void setLowAbsolute(Double lowAbsolute) {
this.lowAbsolute = lowAbsolute;
}
/**
* @return the lowCritical
*/
public Double getLowCritical() {
return lowCritical;
}
/**
* @param lowCritical the lowCritical to set
*/
public void setLowCritical(Double lowCritical) {
this.lowCritical = lowCritical;
}
/**
* @return the hiCritical
*/
public Double getHiCritical() {
return hiCritical;
}
/**
* @param hiCritical the hiCritical to set
*/
public void setHiCritical(Double hiCritical) {
this.hiCritical = hiCritical;
}
/**
* @return the lowNormal
*/
public Double getLowNormal() {
return lowNormal;
}
/**
* @param lowNormal the lowNormal to set
*/
public void setLowNormal(Double lowNormal) {
this.lowNormal = lowNormal;
}
/**
* @return the hiNormal
*/
public Double getHiNormal() {
return hiNormal;
}
/**
* @param hiNormal the hiNormal to set
*/
public void setHiNormal(Double hiNormal) {
this.hiNormal = hiNormal;
}
/**
* @return the precise
*/
public boolean isPrecise() {
return precise;
}
/**
* @param precise the precise to set
*/
public void setPrecise(boolean precise) {
this.precise = precise;
}
/**
* @return the units
*/
public String getUnits() {
return units;
}
/**
* @param units the units to set
*/
public void setUnits(String units) {
this.units = units;
}
/**
* @return the handlerKey
*/
public String getHandlerKey() {
return handlerKey;
}
/**
* @param handlerKey the handlerKey to set
*/
public void setHandlerKey(String handlerKey) {
this.handlerKey = handlerKey;
}
/**
* @return the indexTermsByLocale
*/
public Map<Locale, List<ConceptName>> getIndexTermsByLocale() {
return indexTermsByLocale;
}
/**
* @param indexTermsByLocale the indexTermsByLocale to set
*/
public void setIndexTermsByLocale(Map<Locale, List<ConceptName>> indexTermsByLocale) {
this.indexTermsByLocale = indexTermsByLocale;
}
/**
* Get the forms that this concept is declared to be used in
*
* @return
*/
public List<Form> getFormsInUse() {
return Context.getFormService().getFormsContainingConcept(concept);
}
/**
* Get the other concept questions that this concept is declared as an answer for
*
* @return
*/
public List<Concept> getQuestionsAnswered() {
return Context.getConceptService().getConceptsByAnswer(concept);
}
/**
* Get the sets that this concept is declared to be a child member of
*
* @return
*/
public List<ConceptSet> getContainedInSets() {
return Context.getConceptService().getSetsContainingConcept(concept);
}
/**
* Get the answers for this concept with decoded names. The keys to this map are the
* conceptIds or the conceptIds^drugId if applicable
*
* @return
*/
public Map<String, String> getConceptAnswers() {
Map<String, String> conceptAnswers = new LinkedHashMap<String, String>();
// get concept answers with locale decoded names
for (ConceptAnswer answer : concept.getAnswers(true)) {
log.debug("getting answers");
String key = answer.getAnswerConcept().getConceptId().toString();
ConceptName cn = answer.getAnswerConcept().getName(Context.getLocale());
String name = "";
if (cn != null)
name = cn.toString();
if (answer.getAnswerDrug() != null) {
// if this answer is a drug, append the drug id information
key = key + "^" + answer.getAnswerDrug().getDrugId();
name = answer.getAnswerDrug().getFullName(Context.getLocale());
}
if (answer.getAnswerConcept().isRetired())
name = "<span class='retired'>" + name + "</span>";
conceptAnswers.put(key, name);
}
return conceptAnswers;
}
/**
* @return the preferredNamesByLocale
*/
public Map<Locale, String> getPreferredNamesByLocale() {
return preferredNamesByLocale;
}
/**
* @param preferredNamesByLocale the preferredNamesByLocale to set
*/
public void setPreferredNamesByLocale(Map<Locale, String> preferredNamesByLocale) {
this.preferredNamesByLocale = preferredNamesByLocale;
}
}
}
| true | true | public Concept getConceptFromFormData() {
// add all the new names/descriptions to the concept
for (Locale locale : locales) {
ConceptName fullySpecifiedNameInLocale = namesByLocale.get(locale);
if (StringUtils.hasText(fullySpecifiedNameInLocale.getName())) {
concept.setFullySpecifiedName(fullySpecifiedNameInLocale);
if (fullySpecifiedNameInLocale.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale))) {
concept.setPreferredName(fullySpecifiedNameInLocale);
}
}
ConceptName shortNameInLocale = shortNamesByLocale.get(locale);
if (StringUtils.hasText(shortNameInLocale.getName())) {
concept.setShortName(shortNameInLocale);
}
for (ConceptName synonym : synonymsByLocale.get(locale)) {
if (synonym != null && StringUtils.hasText(synonym.getName())) {
synonym.setLocale(locale);
if (synonym.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale))) {
concept.setPreferredName(synonym);
} else if (!concept.getNames().contains(synonym) && !concept.hasName(synonym.getName(), locale)) {
//we leave systemTag field as null to indicate that it is a synonym
concept.addName(synonym);
}
//if the user removed this synonym with a void reason, returned to the page due validation errors,
//then they chose to cancel the removal of the synonym but forgot to clear the void reason text box,
//clear the text
if (!synonym.isVoided())
synonym.setVoidReason(null);
else if (synonym.isVoided() && !StringUtils.hasText(synonym.getVoidReason()))
synonym.setVoidReason(Context.getMessageSourceService().getMessage(
"Concept.name.default.voidReason"));
}
}
for (ConceptName indexTerm : indexTermsByLocale.get(locale)) {
if (indexTerm != null && StringUtils.hasText(indexTerm.getName())) {
if (!concept.getNames().contains(indexTerm) && !concept.hasName(indexTerm.getName(), locale)) {
indexTerm.setConceptNameType(ConceptNameType.INDEX_TERM);
indexTerm.setLocale(locale);
concept.addName(indexTerm);
}
if (!indexTerm.isVoided())
indexTerm.setVoidReason(null);
else if (indexTerm.isVoided() && !StringUtils.hasText(indexTerm.getVoidReason()))
indexTerm.setVoidReason(Context.getMessageSourceService().getMessage(
"Concept.name.default.voidReason"));
}
}
ConceptDescription descInLocale = descriptionsByLocale.get(locale);
if (StringUtils.hasLength(descInLocale.getDescription())
&& !concept.getDescriptions().contains(descInLocale)) {
concept.addDescription(descInLocale);
}
}
// add in all the mappings
for (ConceptMap map : mappings) {
if (map != null) {
if (map.getSourceCode() == null) {
// because of the _mappings[x].sourceCode input name in the jsp, the sourceCode will be empty for
// deleted mappings. remove those from the concept object now.
concept.removeConceptMapping(map);
} else if (!concept.getConceptMappings().contains(map)) {
// assumes null sources also don't get here
concept.addConceptMapping(map);
}
}
}
// if the user unchecked the concept sets box, erase past saved sets
if (!concept.isSet()) {
if (concept.getConceptSets() != null) {
concept.getConceptSets().clear();
}
}
// if the user changed the datatype to be non "Coded", erase past saved datatypes
if (!concept.getDatatype().isCoded()) {
if (concept.getAnswers(true) != null) {
concept.getAnswers(true).clear();
}
}
// add in subobject specific code
if (concept.getDatatype().getName().equals("Numeric")) {
ConceptNumeric cn;
if (concept instanceof ConceptNumeric)
cn = (ConceptNumeric) concept;
else {
cn = new ConceptNumeric(concept);
}
cn.setHiAbsolute(hiAbsolute);
cn.setLowAbsolute(lowAbsolute);
cn.setHiCritical(hiCritical);
cn.setLowCritical(lowCritical);
cn.setHiNormal(hiNormal);
cn.setLowNormal(lowNormal);
cn.setPrecise(precise);
cn.setUnits(units);
concept = cn;
} else if (concept.getDatatype().getName().equals("Complex")) {
ConceptComplex complexConcept;
if (concept instanceof ConceptComplex)
complexConcept = (ConceptComplex) concept;
else {
complexConcept = new ConceptComplex(concept);
}
complexConcept.setHandler(handlerKey);
concept = complexConcept;
}
return concept;
}
| public Concept getConceptFromFormData() {
// add all the new names/descriptions to the concept
for (Locale locale : locales) {
ConceptName fullySpecifiedNameInLocale = namesByLocale.get(locale);
if (StringUtils.hasText(fullySpecifiedNameInLocale.getName())) {
concept.setFullySpecifiedName(fullySpecifiedNameInLocale);
if (fullySpecifiedNameInLocale.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale))) {
concept.setPreferredName(fullySpecifiedNameInLocale);
}
}
ConceptName shortNameInLocale = shortNamesByLocale.get(locale);
if (StringUtils.hasText(shortNameInLocale.getName())) {
concept.setShortName(shortNameInLocale);
}
for (ConceptName synonym : synonymsByLocale.get(locale)) {
if (synonym != null && StringUtils.hasText(synonym.getName())) {
synonym.setLocale(locale);
//donot set voided names otherwise setPreferredname(() will throw an exception
if (synonym.getName().equalsIgnoreCase(preferredNamesByLocale.get(locale)) && !synonym.isVoided()) {
concept.setPreferredName(synonym);
} else if (!concept.getNames().contains(synonym) && !concept.hasName(synonym.getName(), locale)) {
//we leave systemTag field as null to indicate that it is a synonym
concept.addName(synonym);
}
//if the user removed this synonym with a void reason, returned to the page due validation errors,
//then they chose to cancel the removal of the synonym but forgot to clear the void reason text box,
//clear the text
if (!synonym.isVoided())
synonym.setVoidReason(null);
else if (synonym.isVoided() && !StringUtils.hasText(synonym.getVoidReason()))
synonym.setVoidReason(Context.getMessageSourceService().getMessage(
"Concept.name.default.voidReason"));
}
}
for (ConceptName indexTerm : indexTermsByLocale.get(locale)) {
if (indexTerm != null && StringUtils.hasText(indexTerm.getName())) {
if (!concept.getNames().contains(indexTerm) && !concept.hasName(indexTerm.getName(), locale)) {
indexTerm.setConceptNameType(ConceptNameType.INDEX_TERM);
indexTerm.setLocale(locale);
concept.addName(indexTerm);
}
if (!indexTerm.isVoided())
indexTerm.setVoidReason(null);
else if (indexTerm.isVoided() && !StringUtils.hasText(indexTerm.getVoidReason()))
indexTerm.setVoidReason(Context.getMessageSourceService().getMessage(
"Concept.name.default.voidReason"));
}
}
ConceptDescription descInLocale = descriptionsByLocale.get(locale);
if (StringUtils.hasLength(descInLocale.getDescription())
&& !concept.getDescriptions().contains(descInLocale)) {
concept.addDescription(descInLocale);
}
}
// add in all the mappings
for (ConceptMap map : mappings) {
if (map != null) {
if (map.getSourceCode() == null) {
// because of the _mappings[x].sourceCode input name in the jsp, the sourceCode will be empty for
// deleted mappings. remove those from the concept object now.
concept.removeConceptMapping(map);
} else if (!concept.getConceptMappings().contains(map)) {
// assumes null sources also don't get here
concept.addConceptMapping(map);
}
}
}
// if the user unchecked the concept sets box, erase past saved sets
if (!concept.isSet()) {
if (concept.getConceptSets() != null) {
concept.getConceptSets().clear();
}
}
// if the user changed the datatype to be non "Coded", erase past saved datatypes
if (!concept.getDatatype().isCoded()) {
if (concept.getAnswers(true) != null) {
concept.getAnswers(true).clear();
}
}
// add in subobject specific code
if (concept.getDatatype().getName().equals("Numeric")) {
ConceptNumeric cn;
if (concept instanceof ConceptNumeric)
cn = (ConceptNumeric) concept;
else {
cn = new ConceptNumeric(concept);
}
cn.setHiAbsolute(hiAbsolute);
cn.setLowAbsolute(lowAbsolute);
cn.setHiCritical(hiCritical);
cn.setLowCritical(lowCritical);
cn.setHiNormal(hiNormal);
cn.setLowNormal(lowNormal);
cn.setPrecise(precise);
cn.setUnits(units);
concept = cn;
} else if (concept.getDatatype().getName().equals("Complex")) {
ConceptComplex complexConcept;
if (concept instanceof ConceptComplex)
complexConcept = (ConceptComplex) concept;
else {
complexConcept = new ConceptComplex(concept);
}
complexConcept.setHandler(handlerKey);
concept = complexConcept;
}
return concept;
}
|
diff --git a/src/com/android/exchange/service/EmailSyncAdapterService.java b/src/com/android/exchange/service/EmailSyncAdapterService.java
index d4d69bcb..93aa0a4b 100644
--- a/src/com/android/exchange/service/EmailSyncAdapterService.java
+++ b/src/com/android/exchange/service/EmailSyncAdapterService.java
@@ -1,835 +1,835 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.service;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.text.format.DateUtils;
import com.android.emailcommon.Api;
import com.android.emailcommon.TempDirectory;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.AccountColumns;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.service.IEmailService;
import com.android.emailcommon.service.IEmailServiceCallback;
import com.android.emailcommon.service.SearchParams;
import com.android.emailcommon.service.ServiceProxy;
import com.android.emailcommon.utility.IntentUtilities;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.Eas;
import com.android.exchange.R.drawable;
import com.android.exchange.R.string;
import com.android.exchange.adapter.PingParser;
import com.android.exchange.adapter.Search;
import com.android.exchange.eas.EasFolderSync;
import com.android.exchange.eas.EasMoveItems;
import com.android.exchange.eas.EasOperation;
import com.android.exchange.eas.EasPing;
import com.android.exchange.eas.EasSync;
import com.android.mail.providers.UIProvider.AccountCapabilities;
import com.android.mail.utils.LogUtils;
import java.util.HashMap;
import java.util.HashSet;
/**
* Service for communicating with Exchange servers. There are three main parts of this class:
* TODO: Flesh out these comments.
* 1) An {@link AbstractThreadedSyncAdapter} to handle actually performing syncs.
* 2) Bookkeeping for running Ping requests, which handles push notifications.
* 3) An {@link IEmailService} Stub to handle RPC from the UI.
*/
public class EmailSyncAdapterService extends AbstractSyncAdapterService {
private static final String TAG = Eas.LOG_TAG;
/**
* The amount of time between periodic syncs intended to ensure that push hasn't died.
*/
private static final long KICK_SYNC_INTERVAL =
DateUtils.HOUR_IN_MILLIS / DateUtils.SECOND_IN_MILLIS;
/** Controls whether we do a periodic "kick" to restart the ping. */
private static final boolean SCHEDULE_KICK = false;
/**
* If sync extras do not include a mailbox id, then we want to perform a full sync.
*/
private static final long FULL_ACCOUNT_SYNC = Mailbox.NO_MAILBOX;
/** Projection used for getting email address for an account. */
private static final String[] ACCOUNT_EMAIL_PROJECTION = { AccountColumns.EMAIL_ADDRESS };
private static final Object sSyncAdapterLock = new Object();
private static AbstractThreadedSyncAdapter sSyncAdapter = null;
/**
* Bookkeeping for handling synchronization between pings and syncs.
* "Ping" refers to a hanging POST or GET that is used to receive push notifications. Ping is
* the term for the Exchange command, but this code should be generic enough to be easily
* extended to IMAP.
* "Sync" refers to an actual sync command to either fetch mail state, account state, or send
* mail (send is implemented as "sync the outbox").
* TODO: Outbox sync probably need not stop a ping in progress.
* Basic rules of how these interact (note that all rules are per account):
* - Only one ping or sync may run at a time.
* - Due to how {@link AbstractThreadedSyncAdapter} works, sync requests will not occur while
* a sync is in progress.
* - On the other hand, ping requests may come in while handling a ping.
* - "Ping request" is shorthand for "a request to change our ping parameters", which includes
* a request to stop receiving push notifications.
* - If neither a ping nor a sync is running, then a request for either will run it.
* - If a sync is running, new ping requests block until the sync completes.
* - If a ping is running, a new sync request stops the ping and creates a pending ping
* (which blocks until the sync completes).
* - If a ping is running, a new ping request stops the ping and either starts a new one or
* does nothing, as appopriate (since a ping request can be to stop pushing).
* - As an optimization, while a ping request is waiting to run, subsequent ping requests are
* ignored (the pending ping will pick up the latest ping parameters at the time it runs).
*/
public class SyncHandlerSynchronizer {
/**
* Map of account id -> ping handler.
* For a given account id, there are three possible states:
* 1) If no ping or sync is currently running, there is no entry in the map for the account.
* 2) If a ping is running, there is an entry with the appropriate ping handler.
* 3) If there is a sync running, there is an entry with null as the value.
* We cannot have more than one ping or sync running at a time.
*/
private final HashMap<Long, PingTask> mPingHandlers = new HashMap<Long, PingTask>();
/**
* Wait until neither a sync nor a ping is running on this account, and then return.
* If there's a ping running, actively stop it. (For syncs, we have to just wait.)
* @param accountId The account we want to wait for.
*/
private synchronized void waitUntilNoActivity(final long accountId) {
while (mPingHandlers.containsKey(accountId)) {
final PingTask pingHandler = mPingHandlers.get(accountId);
if (pingHandler != null) {
pingHandler.stop();
}
try {
wait();
} catch (final InterruptedException e) {
// TODO: When would this happen, and how should I handle it?
}
}
}
/**
* Use this to see if we're currently syncing, as opposed to pinging or doing nothing.
* @param accountId The account to check.
* @return Whether that account is currently running a sync.
*/
private synchronized boolean isRunningSync(final long accountId) {
return (mPingHandlers.containsKey(accountId) && mPingHandlers.get(accountId) == null);
}
/**
* If there are no running pings, stop the service.
*/
private void stopServiceIfNoPings() {
for (final PingTask pingHandler : mPingHandlers.values()) {
if (pingHandler != null) {
return;
}
}
EmailSyncAdapterService.this.stopSelf();
}
/**
* Called prior to starting a sync to update our bookkeeping. We don't actually run the sync
* here; the caller must do that.
* @param accountId The account on which we are running a sync.
*/
public synchronized void startSync(final long accountId) {
waitUntilNoActivity(accountId);
mPingHandlers.put(accountId, null);
}
/**
* Starts or restarts a ping for an account, if the current account state indicates that it
* wants to push.
* @param account The account whose ping is being modified.
*/
public synchronized void modifyPing(final Account account) {
// If a sync is currently running, it will start a ping when it's done, so there's no
// need to do anything right now.
if (isRunningSync(account.mId)) {
return;
}
// Don't ping for accounts that haven't performed initial sync.
if (EmailContent.isInitialSyncKey(account.mSyncKey)) {
return;
}
// Determine if this account needs pushes. All of the following must be true:
// - The account's sync interval must indicate that it wants push.
// - At least one content type must be sync-enabled in the account manager.
// - At least one mailbox of a sync-enabled type must have automatic sync enabled.
final EmailSyncAdapterService service = EmailSyncAdapterService.this;
final android.accounts.Account amAccount = new android.accounts.Account(
account.mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
boolean pushNeeded = false;
if (account.mSyncInterval == Account.CHECK_INTERVAL_PUSH) {
final HashSet<String> authsToSync = getAuthsToSync(amAccount);
// If we have at least one sync-enabled content type, check for syncing mailboxes.
if (!authsToSync.isEmpty()) {
final Cursor c = Mailbox.getMailboxesForPush(service.getContentResolver(),
account.mId);
if (c != null) {
try {
while (c.moveToNext()) {
final int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (authsToSync.contains(Mailbox.getAuthority(mailboxType))) {
pushNeeded = true;
break;
}
}
} finally {
c.close();
}
}
}
}
// Stop, start, or restart the ping as needed, as well as the ping kicker periodic sync.
final PingTask pingSyncHandler = mPingHandlers.get(account.mId);
final Bundle extras = new Bundle(1);
extras.putBoolean(Mailbox.SYNC_EXTRA_PUSH_ONLY, true);
if (pushNeeded) {
// First start or restart the ping as appropriate.
if (pingSyncHandler != null) {
pingSyncHandler.restart();
} else {
// Start a new ping.
// Note: unlike startSync, we CANNOT allow the caller to do the actual work.
// If we return before the ping starts, there's a race condition where another
// ping or sync might start first. It only works for startSync because sync is
// higher priority than ping (i.e. a ping can't start while a sync is pending)
// and only one sync can run at a time.
final PingTask pingHandler = new PingTask(service, account, amAccount, this);
mPingHandlers.put(account.mId, pingHandler);
pingHandler.start();
// Whenever we have a running ping, make sure this service stays running.
service.startService(new Intent(service, EmailSyncAdapterService.class));
}
if (SCHEDULE_KICK) {
ContentResolver.addPeriodicSync(amAccount, EmailContent.AUTHORITY, extras,
KICK_SYNC_INTERVAL);
}
} else {
if (pingSyncHandler != null) {
pingSyncHandler.stop();
}
if (SCHEDULE_KICK) {
ContentResolver.removePeriodicSync(amAccount, EmailContent.AUTHORITY, extras);
}
}
}
/**
* Updates the synchronization bookkeeping when a sync is done.
* @param account The account whose sync just finished.
*/
public synchronized void syncComplete(final Account account) {
mPingHandlers.remove(account.mId);
// Syncs can interrupt pings, so we should check if we need to start one now.
modifyPing(account);
stopServiceIfNoPings();
notifyAll();
}
/**
* Updates the synchronization bookkeeping when a ping is done. Also requests a ping-only
* sync if necessary.
* @param amAccount The {@link android.accounts.Account} for this account.
* @param accountId The account whose ping just finished.
* @param pingStatus The status value from {@link PingParser} for the last ping performed.
* This cannot be one of the values that results in another ping, so this
* function only needs to handle the terminal statuses.
*/
public synchronized void pingComplete(final android.accounts.Account amAccount,
final long accountId, final int pingStatus) {
mPingHandlers.remove(accountId);
// TODO: if (pingStatus == PingParser.STATUS_FAILED), notify UI.
// TODO: if (pingStatus == PingParser.STATUS_REQUEST_TOO_MANY_FOLDERS), notify UI.
if (pingStatus == EasOperation.RESULT_REQUEST_FAILURE) {
// Request a new ping through the SyncManager. This will do the right thing if the
// exception was due to loss of network connectivity, etc. (i.e. it will wait for
// network to restore and then request it).
EasPing.requestPing(amAccount);
} else {
stopServiceIfNoPings();
}
// TODO: It might be the case that only STATUS_CHANGES_FOUND and
// STATUS_FOLDER_REFRESH_NEEDED need to notifyAll(). Think this through.
notifyAll();
}
}
private final SyncHandlerSynchronizer mSyncHandlerMap = new SyncHandlerSynchronizer();
/**
* The binder for IEmailService.
*/
private final IEmailService.Stub mBinder = new IEmailService.Stub() {
private String getEmailAddressForAccount(final long accountId) {
final String emailAddress = Utility.getFirstRowString(EmailSyncAdapterService.this,
Account.CONTENT_URI, ACCOUNT_EMAIL_PROJECTION, Account.ID_SELECTION,
new String[] {Long.toString(accountId)}, null, 0);
if (emailAddress == null) {
LogUtils.e(TAG, "Could not find email address for account %d", accountId);
}
return emailAddress;
}
@Override
public Bundle validate(final HostAuth hostAuth) {
LogUtils.d(TAG, "IEmailService.validate");
return new EasFolderSync(EmailSyncAdapterService.this, hostAuth).validate();
}
@Override
public Bundle autoDiscover(final String username, final String password) {
LogUtils.d(TAG, "IEmailService.autoDiscover");
return new EasAutoDiscover(EmailSyncAdapterService.this, username, password)
.doAutodiscover();
}
@Override
public void updateFolderList(final long accountId) {
LogUtils.d(TAG, "IEmailService.updateFolderList: %d", accountId);
final String emailAddress = getEmailAddressForAccount(accountId);
if (emailAddress != null) {
final Bundle extras = new Bundle(1);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
ContentResolver.requestSync(new android.accounts.Account(
emailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
EmailContent.AUTHORITY, extras);
}
}
@Override
public void setLogging(final int flags) {
// TODO: fix this?
// Protocol logging
Eas.setUserDebug(flags);
// Sync logging
//setUserDebug(flags);
}
@Override
public void loadAttachment(final IEmailServiceCallback callback, final long attachmentId,
final boolean background) {
LogUtils.d(TAG, "IEmailService.loadAttachment: %d", attachmentId);
// TODO: Prevent this from happening in parallel with a sync?
EasAttachmentLoader.loadAttachment(EmailSyncAdapterService.this, attachmentId,
callback);
}
@Override
public void sendMeetingResponse(final long messageId, final int response) {
LogUtils.d(TAG, "IEmailService.sendMeetingResponse: %d, %d", messageId, response);
EasMeetingResponder.sendMeetingResponse(EmailSyncAdapterService.this, messageId,
response);
}
/**
* Delete PIM (calendar, contacts) data for the specified account
*
* @param emailAddress the email address for the account whose data should be deleted
*/
@Override
public void deleteAccountPIMData(final String emailAddress) {
LogUtils.d(TAG, "IEmailService.deleteAccountPIMData");
if (emailAddress != null) {
final Context context = EmailSyncAdapterService.this;
EasContactsSyncHandler.wipeAccountFromContentProvider(context, emailAddress);
EasCalendarSyncHandler.wipeAccountFromContentProvider(context, emailAddress);
}
// TODO: Run account reconciler?
}
@Override
public int searchMessages(final long accountId, final SearchParams searchParams,
final long destMailboxId) {
LogUtils.d(TAG, "IEmailService.searchMessages");
return Search.searchMessages(EmailSyncAdapterService.this, accountId, searchParams,
destMailboxId);
// TODO: may need an explicit callback to replace the one to IEmailServiceCallback.
}
@Override
public void sendMail(final long accountId) {}
@Override
public int getCapabilities(final Account acct) {
String easVersion = acct.mProtocolVersion;
Double easVersionDouble = 2.5D;
if (easVersion != null) {
try {
easVersionDouble = Double.parseDouble(easVersion);
} catch (NumberFormatException e) {
// Stick with 2.5
}
}
if (easVersionDouble >= 12.0D) {
return AccountCapabilities.SYNCABLE_FOLDERS |
AccountCapabilities.SERVER_SEARCH |
AccountCapabilities.FOLDER_SERVER_SEARCH |
AccountCapabilities.SMART_REPLY |
AccountCapabilities.UNDO |
AccountCapabilities.DISCARD_CONVERSATION_DRAFTS;
} else {
return AccountCapabilities.SYNCABLE_FOLDERS |
AccountCapabilities.SMART_REPLY |
AccountCapabilities.UNDO |
AccountCapabilities.DISCARD_CONVERSATION_DRAFTS;
}
}
@Override
public void serviceUpdated(final String emailAddress) {
// Not required for EAS
}
// All IEmailService messages below are UNCALLED in Email.
// TODO: Remove.
@Deprecated
@Override
public int getApiLevel() {
return Api.LEVEL;
}
@Deprecated
@Override
public void startSync(long mailboxId, boolean userRequest, int deltaMessageCount) {}
@Deprecated
@Override
public void stopSync(long mailboxId) {}
@Deprecated
@Override
public void loadMore(long messageId) {}
@Deprecated
@Override
public boolean createFolder(long accountId, String name) {
return false;
}
@Deprecated
@Override
public boolean deleteFolder(long accountId, String name) {
return false;
}
@Deprecated
@Override
public boolean renameFolder(long accountId, String oldName, String newName) {
return false;
}
@Deprecated
@Override
public void hostChanged(long accountId) {}
};
public EmailSyncAdapterService() {
super();
}
/**
* {@link AsyncTask} for restarting pings for all accounts that need it.
*/
private static final String PUSH_ACCOUNTS_SELECTION =
AccountColumns.SYNC_INTERVAL + "=" + Integer.toString(Account.CHECK_INTERVAL_PUSH);
private class RestartPingsTask extends AsyncTask<Void, Void, Void> {
private final ContentResolver mContentResolver;
private final SyncHandlerSynchronizer mSyncHandlerMap;
private boolean mAnyAccounts;
public RestartPingsTask(final ContentResolver contentResolver,
final SyncHandlerSynchronizer syncHandlerMap) {
mContentResolver = contentResolver;
mSyncHandlerMap = syncHandlerMap;
}
@Override
protected Void doInBackground(Void... params) {
final Cursor c = mContentResolver.query(Account.CONTENT_URI,
Account.CONTENT_PROJECTION, PUSH_ACCOUNTS_SELECTION, null, null);
if (c != null) {
try {
mAnyAccounts = (c.getCount() != 0);
while (c.moveToNext()) {
final Account account = new Account();
account.restore(c);
mSyncHandlerMap.modifyPing(account);
}
} finally {
c.close();
}
} else {
mAnyAccounts = false;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (!mAnyAccounts) {
LogUtils.d(TAG, "stopping for no accounts");
EmailSyncAdapterService.this.stopSelf();
}
}
}
@Override
public void onCreate() {
LogUtils.i(TAG, "onCreate()");
super.onCreate();
startService(new Intent(this, EmailSyncAdapterService.class));
// Restart push for all accounts that need it.
new RestartPingsTask(getContentResolver(), mSyncHandlerMap).executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR);
}
@Override
public void onDestroy() {
LogUtils.i(TAG, "onDestroy()");
super.onDestroy();
for (PingTask task : mSyncHandlerMap.mPingHandlers.values()) {
if (task != null) {
task.stop();
}
}
}
@Override
public IBinder onBind(Intent intent) {
if (intent.getAction().equals(Eas.EXCHANGE_SERVICE_INTENT_ACTION)) {
return mBinder;
}
return super.onBind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null &&
TextUtils.equals(Eas.EXCHANGE_SERVICE_INTENT_ACTION, intent.getAction())) {
if (intent.getBooleanExtra(ServiceProxy.EXTRA_FORCE_SHUTDOWN, false)) {
// We've been asked to forcibly shutdown. This happens if email accounts are
// deleted, otherwise we can get errors if services are still running for
// accounts that are now gone.
// TODO: This is kind of a hack, it would be nicer if we could handle it correctly
// if accounts disappear out from under us.
LogUtils.d(TAG, "Forced shutdown, killing process");
System.exit(-1);
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
protected AbstractThreadedSyncAdapter getSyncAdapter() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapterImpl(this);
}
return sSyncAdapter;
}
}
// TODO: Handle cancelSync() appropriately.
private class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
public SyncAdapterImpl(Context context) {
super(context, true /* autoInitialize */);
}
@Override
public void onPerformSync(final android.accounts.Account acct, final Bundle extras,
final String authority, final ContentProviderClient provider,
final SyncResult syncResult) {
LogUtils.i(TAG, "onPerformSync: %s, %s", acct.toString(), extras.toString());
TempDirectory.setTempDirectory(EmailSyncAdapterService.this);
// TODO: Perform any connectivity checks, bail early if we don't have proper network
// for this sync operation.
final Context context = getContext();
final ContentResolver cr = context.getContentResolver();
// Get the EmailContent Account
final Account account;
final Cursor accountCursor = cr.query(Account.CONTENT_URI, Account.CONTENT_PROJECTION,
AccountColumns.EMAIL_ADDRESS + "=?", new String[] {acct.name}, null);
try {
if (!accountCursor.moveToFirst()) {
// Could not load account.
// TODO: improve error handling.
LogUtils.w(TAG, "onPerformSync: could not load account %s, %s",
acct.toString(), extras.toString());
return;
}
account = new Account();
account.restore(accountCursor);
} finally {
accountCursor.close();
}
// Figure out what we want to sync, based on the extras and our account sync status.
final boolean isInitialSync = EmailContent.isInitialSyncKey(account.mSyncKey);
final long[] mailboxIds = Mailbox.getMailboxIdsFromBundle(extras);
final int mailboxType = extras.getInt(Mailbox.SYNC_EXTRA_MAILBOX_TYPE,
Mailbox.TYPE_NONE);
// A "full sync" means no specific mailbox or type filter was requested.
final boolean isFullSync = (mailboxIds == null && mailboxType == Mailbox.TYPE_NONE);
// A FolderSync is necessary for full sync, initial sync, and account only sync.
final boolean accountOnly = Mailbox.isAccountOnlyExtras(extras);
final boolean pushOnly = Mailbox.isPushOnlyExtras(extras);
final boolean isFolderSync = (isFullSync || isInitialSync || accountOnly);
// If we're just twiddling the push, we do the lightweight thing and bail early.
if (pushOnly && !isFolderSync) {
mSyncHandlerMap.modifyPing(account);
LogUtils.i(TAG, "onPerformSync: mailbox push only %s, %s",
acct.toString(), extras.toString());
return;
}
// Do the bookkeeping for starting a sync, including stopping a ping if necessary.
mSyncHandlerMap.startSync(account.mId);
// Perform a FolderSync if necessary.
if (isFolderSync) {
final EasFolderSync folderSync = new EasFolderSync(context, account);
folderSync.doFolderSync(syncResult);
}
// Perform email upsync for this account. Moves first, then state changes.
if (!isInitialSync) {
EasMoveItems move = new EasMoveItems(context, account);
move.upsyncMovedMessages(syncResult);
// TODO: EasSync should eventually handle both up and down; for now, it's used
// purely for upsync.
EasSync upsync = new EasSync(context, account);
upsync.upsync(syncResult);
}
// TODO: Should we refresh account here? It may have changed while waiting for any
// pings to stop. It may not matter since the things that may have been twiddled might
// not affect syncing.
if (mailboxIds != null) {
// Sync the mailbox that was explicitly requested.
for (final long mailboxId : mailboxIds) {
syncMailbox(context, cr, acct, account, mailboxId, extras, syncResult, null,
true);
}
- } else if (accountOnly) {
+ } else if (!accountOnly) {
// We have to sync multiple folders.
final Cursor c;
if (isFullSync) {
// Full account sync includes all mailboxes that participate in system sync.
c = Mailbox.getMailboxIdsForSync(cr, account.mId);
} else {
// Type-filtered sync should only get the mailboxes of a specific type.
c = Mailbox.getMailboxIdsForSyncByType(cr, account.mId, mailboxType);
}
if (c != null) {
try {
final HashSet<String> authsToSync = getAuthsToSync(acct);
while (c.moveToNext()) {
syncMailbox(context, cr, acct, account, c.getLong(0), extras,
syncResult, authsToSync, false);
}
} finally {
c.close();
}
}
}
// Clean up the bookkeeping, including restarting ping if necessary.
mSyncHandlerMap.syncComplete(account);
// TODO: It may make sense to have common error handling here. Two possible mechanisms:
// 1) performSync return value can signal some useful info.
// 2) syncResult can contain useful info.
LogUtils.i(TAG, "onPerformSync: finished %s, %s", acct.toString(), extras.toString());
}
/**
* Update the mailbox's sync status with the provider and, if we're finished with the sync,
* write the last sync time as well.
* @param context Our {@link Context}.
* @param mailbox The mailbox whose sync status to update.
* @param cv A {@link ContentValues} object to use for updating the provider.
* @param syncStatus The status for the current sync.
*/
private void updateMailbox(final Context context, final Mailbox mailbox,
final ContentValues cv, final int syncStatus) {
cv.put(Mailbox.UI_SYNC_STATUS, syncStatus);
if (syncStatus == EmailContent.SYNC_STATUS_NONE) {
cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
}
mailbox.update(context, cv);
}
private boolean syncMailbox(final Context context, final ContentResolver cr,
final android.accounts.Account acct, final Account account, final long mailboxId,
final Bundle extras, final SyncResult syncResult, final HashSet<String> authsToSync,
final boolean isMailboxSync) {
final Mailbox mailbox = Mailbox.restoreMailboxWithId(context, mailboxId);
if (mailbox == null) {
return false;
}
if (mailbox.mAccountKey != account.mId) {
LogUtils.e(TAG, "Mailbox does not match account: %s, %s", acct.toString(),
extras.toString());
return false;
}
if (authsToSync != null && !authsToSync.contains(Mailbox.getAuthority(mailbox.mType))) {
// We are asking for an account sync, but this mailbox type is not configured for
// sync.
return false;
}
if (mailbox.mType == Mailbox.TYPE_DRAFTS) {
// TODO: Because we don't have bidirectional sync working, trying to downsync
// the drafts folder is confusing. b/11158759
// For now, just disable all syncing of DRAFTS type folders.
// Automatic syncing should always be disabled, but we also stop it here to ensure
// that we won't sync even if the user attempts to force a sync from the UI.
LogUtils.d(TAG, "Skipping sync of DRAFTS folder");
return false;
}
final boolean success;
// Non-mailbox syncs are whole account syncs initiated by the AccountManager and are
// treated as background syncs.
// TODO: Push will be treated as "user" syncs, and probably should be background.
final ContentValues cv = new ContentValues(2);
updateMailbox(context, mailbox, cv, isMailboxSync ?
EmailContent.SYNC_STATUS_USER : EmailContent.SYNC_STATUS_BACKGROUND);
if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
final EasOutboxSyncHandler outboxSyncHandler =
new EasOutboxSyncHandler(context, account, mailbox);
outboxSyncHandler.performSync();
success = true;
} else if(mailbox.isSyncable()) {
final EasSyncHandler syncHandler = EasSyncHandler.getEasSyncHandler(context, cr,
acct, account, mailbox, extras, syncResult);
success = (syncHandler != null);
if (syncHandler != null) {
syncHandler.performSync(syncResult);
}
} else {
success = false;
}
updateMailbox(context, mailbox, cv, EmailContent.SYNC_STATUS_NONE);
if (syncResult.stats.numAuthExceptions > 0) {
showAuthNotification(account.mId, account.mEmailAddress);
}
return success;
}
}
private void showAuthNotification(long accountId, String accountName) {
final PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
createAccountSettingsIntent(accountId, accountName),
0);
final Notification notification = new Builder(this)
.setContentTitle(this.getString(string.auth_error_notification_title))
.setContentText(this.getString(
string.auth_error_notification_text, accountName))
.setSmallIcon(drawable.stat_notify_auth)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
final NotificationManager nm = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify("AuthError", 0, notification);
}
/**
* Create and return an intent to display (and edit) settings for a specific account, or -1
* for any/all accounts. If an account name string is provided, a warning dialog will be
* displayed as well.
*/
public static Intent createAccountSettingsIntent(long accountId, String accountName) {
final Uri.Builder builder = IntentUtilities.createActivityIntentUrlBuilder(
IntentUtilities.PATH_SETTINGS);
IntentUtilities.setAccountId(builder, accountId);
IntentUtilities.setAccountName(builder, accountName);
return new Intent(Intent.ACTION_EDIT, builder.build());
}
/**
* Determine which content types are set to sync for an account.
* @param account The account whose sync settings we're looking for.
* @return The authorities for the content types we want to sync for account.
*/
private static HashSet<String> getAuthsToSync(final android.accounts.Account account) {
final HashSet<String> authsToSync = new HashSet();
if (ContentResolver.getSyncAutomatically(account, EmailContent.AUTHORITY)) {
authsToSync.add(EmailContent.AUTHORITY);
}
if (ContentResolver.getSyncAutomatically(account, CalendarContract.AUTHORITY)) {
authsToSync.add(CalendarContract.AUTHORITY);
}
if (ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY)) {
authsToSync.add(ContactsContract.AUTHORITY);
}
return authsToSync;
}
}
| true | true | public void onPerformSync(final android.accounts.Account acct, final Bundle extras,
final String authority, final ContentProviderClient provider,
final SyncResult syncResult) {
LogUtils.i(TAG, "onPerformSync: %s, %s", acct.toString(), extras.toString());
TempDirectory.setTempDirectory(EmailSyncAdapterService.this);
// TODO: Perform any connectivity checks, bail early if we don't have proper network
// for this sync operation.
final Context context = getContext();
final ContentResolver cr = context.getContentResolver();
// Get the EmailContent Account
final Account account;
final Cursor accountCursor = cr.query(Account.CONTENT_URI, Account.CONTENT_PROJECTION,
AccountColumns.EMAIL_ADDRESS + "=?", new String[] {acct.name}, null);
try {
if (!accountCursor.moveToFirst()) {
// Could not load account.
// TODO: improve error handling.
LogUtils.w(TAG, "onPerformSync: could not load account %s, %s",
acct.toString(), extras.toString());
return;
}
account = new Account();
account.restore(accountCursor);
} finally {
accountCursor.close();
}
// Figure out what we want to sync, based on the extras and our account sync status.
final boolean isInitialSync = EmailContent.isInitialSyncKey(account.mSyncKey);
final long[] mailboxIds = Mailbox.getMailboxIdsFromBundle(extras);
final int mailboxType = extras.getInt(Mailbox.SYNC_EXTRA_MAILBOX_TYPE,
Mailbox.TYPE_NONE);
// A "full sync" means no specific mailbox or type filter was requested.
final boolean isFullSync = (mailboxIds == null && mailboxType == Mailbox.TYPE_NONE);
// A FolderSync is necessary for full sync, initial sync, and account only sync.
final boolean accountOnly = Mailbox.isAccountOnlyExtras(extras);
final boolean pushOnly = Mailbox.isPushOnlyExtras(extras);
final boolean isFolderSync = (isFullSync || isInitialSync || accountOnly);
// If we're just twiddling the push, we do the lightweight thing and bail early.
if (pushOnly && !isFolderSync) {
mSyncHandlerMap.modifyPing(account);
LogUtils.i(TAG, "onPerformSync: mailbox push only %s, %s",
acct.toString(), extras.toString());
return;
}
// Do the bookkeeping for starting a sync, including stopping a ping if necessary.
mSyncHandlerMap.startSync(account.mId);
// Perform a FolderSync if necessary.
if (isFolderSync) {
final EasFolderSync folderSync = new EasFolderSync(context, account);
folderSync.doFolderSync(syncResult);
}
// Perform email upsync for this account. Moves first, then state changes.
if (!isInitialSync) {
EasMoveItems move = new EasMoveItems(context, account);
move.upsyncMovedMessages(syncResult);
// TODO: EasSync should eventually handle both up and down; for now, it's used
// purely for upsync.
EasSync upsync = new EasSync(context, account);
upsync.upsync(syncResult);
}
// TODO: Should we refresh account here? It may have changed while waiting for any
// pings to stop. It may not matter since the things that may have been twiddled might
// not affect syncing.
if (mailboxIds != null) {
// Sync the mailbox that was explicitly requested.
for (final long mailboxId : mailboxIds) {
syncMailbox(context, cr, acct, account, mailboxId, extras, syncResult, null,
true);
}
} else if (accountOnly) {
// We have to sync multiple folders.
final Cursor c;
if (isFullSync) {
// Full account sync includes all mailboxes that participate in system sync.
c = Mailbox.getMailboxIdsForSync(cr, account.mId);
} else {
// Type-filtered sync should only get the mailboxes of a specific type.
c = Mailbox.getMailboxIdsForSyncByType(cr, account.mId, mailboxType);
}
if (c != null) {
try {
final HashSet<String> authsToSync = getAuthsToSync(acct);
while (c.moveToNext()) {
syncMailbox(context, cr, acct, account, c.getLong(0), extras,
syncResult, authsToSync, false);
}
} finally {
c.close();
}
}
}
// Clean up the bookkeeping, including restarting ping if necessary.
mSyncHandlerMap.syncComplete(account);
// TODO: It may make sense to have common error handling here. Two possible mechanisms:
// 1) performSync return value can signal some useful info.
// 2) syncResult can contain useful info.
LogUtils.i(TAG, "onPerformSync: finished %s, %s", acct.toString(), extras.toString());
}
| public void onPerformSync(final android.accounts.Account acct, final Bundle extras,
final String authority, final ContentProviderClient provider,
final SyncResult syncResult) {
LogUtils.i(TAG, "onPerformSync: %s, %s", acct.toString(), extras.toString());
TempDirectory.setTempDirectory(EmailSyncAdapterService.this);
// TODO: Perform any connectivity checks, bail early if we don't have proper network
// for this sync operation.
final Context context = getContext();
final ContentResolver cr = context.getContentResolver();
// Get the EmailContent Account
final Account account;
final Cursor accountCursor = cr.query(Account.CONTENT_URI, Account.CONTENT_PROJECTION,
AccountColumns.EMAIL_ADDRESS + "=?", new String[] {acct.name}, null);
try {
if (!accountCursor.moveToFirst()) {
// Could not load account.
// TODO: improve error handling.
LogUtils.w(TAG, "onPerformSync: could not load account %s, %s",
acct.toString(), extras.toString());
return;
}
account = new Account();
account.restore(accountCursor);
} finally {
accountCursor.close();
}
// Figure out what we want to sync, based on the extras and our account sync status.
final boolean isInitialSync = EmailContent.isInitialSyncKey(account.mSyncKey);
final long[] mailboxIds = Mailbox.getMailboxIdsFromBundle(extras);
final int mailboxType = extras.getInt(Mailbox.SYNC_EXTRA_MAILBOX_TYPE,
Mailbox.TYPE_NONE);
// A "full sync" means no specific mailbox or type filter was requested.
final boolean isFullSync = (mailboxIds == null && mailboxType == Mailbox.TYPE_NONE);
// A FolderSync is necessary for full sync, initial sync, and account only sync.
final boolean accountOnly = Mailbox.isAccountOnlyExtras(extras);
final boolean pushOnly = Mailbox.isPushOnlyExtras(extras);
final boolean isFolderSync = (isFullSync || isInitialSync || accountOnly);
// If we're just twiddling the push, we do the lightweight thing and bail early.
if (pushOnly && !isFolderSync) {
mSyncHandlerMap.modifyPing(account);
LogUtils.i(TAG, "onPerformSync: mailbox push only %s, %s",
acct.toString(), extras.toString());
return;
}
// Do the bookkeeping for starting a sync, including stopping a ping if necessary.
mSyncHandlerMap.startSync(account.mId);
// Perform a FolderSync if necessary.
if (isFolderSync) {
final EasFolderSync folderSync = new EasFolderSync(context, account);
folderSync.doFolderSync(syncResult);
}
// Perform email upsync for this account. Moves first, then state changes.
if (!isInitialSync) {
EasMoveItems move = new EasMoveItems(context, account);
move.upsyncMovedMessages(syncResult);
// TODO: EasSync should eventually handle both up and down; for now, it's used
// purely for upsync.
EasSync upsync = new EasSync(context, account);
upsync.upsync(syncResult);
}
// TODO: Should we refresh account here? It may have changed while waiting for any
// pings to stop. It may not matter since the things that may have been twiddled might
// not affect syncing.
if (mailboxIds != null) {
// Sync the mailbox that was explicitly requested.
for (final long mailboxId : mailboxIds) {
syncMailbox(context, cr, acct, account, mailboxId, extras, syncResult, null,
true);
}
} else if (!accountOnly) {
// We have to sync multiple folders.
final Cursor c;
if (isFullSync) {
// Full account sync includes all mailboxes that participate in system sync.
c = Mailbox.getMailboxIdsForSync(cr, account.mId);
} else {
// Type-filtered sync should only get the mailboxes of a specific type.
c = Mailbox.getMailboxIdsForSyncByType(cr, account.mId, mailboxType);
}
if (c != null) {
try {
final HashSet<String> authsToSync = getAuthsToSync(acct);
while (c.moveToNext()) {
syncMailbox(context, cr, acct, account, c.getLong(0), extras,
syncResult, authsToSync, false);
}
} finally {
c.close();
}
}
}
// Clean up the bookkeeping, including restarting ping if necessary.
mSyncHandlerMap.syncComplete(account);
// TODO: It may make sense to have common error handling here. Two possible mechanisms:
// 1) performSync return value can signal some useful info.
// 2) syncResult can contain useful info.
LogUtils.i(TAG, "onPerformSync: finished %s, %s", acct.toString(), extras.toString());
}
|
diff --git a/CSipSimple/src/com/csipsimple/wizards/impl/FastVoip.java b/CSipSimple/src/com/csipsimple/wizards/impl/FastVoip.java
index 0df26e89..98aeb628 100644
--- a/CSipSimple/src/com/csipsimple/wizards/impl/FastVoip.java
+++ b/CSipSimple/src/com/csipsimple/wizards/impl/FastVoip.java
@@ -1,44 +1,44 @@
/**
* Copyright (C) 2010 Regis Montoya (aka r3gis - www.r3gis.fr)
* 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.wizards.impl;
import com.csipsimple.api.SipProfile;
public class FastVoip extends SimpleImplementation {
@Override
protected String getDomain() {
return "fastvoip.com";
}
@Override
protected String getDefaultName() {
return "FastVoip";
}
@Override
public SipProfile buildAccount(SipProfile account) {
SipProfile acc = super.buildAccount(account);
- acc.proxies = new String[] {"sip:proxy.fastvoip.com"};
+ acc.proxies = new String[] {"sip:sip.fastvoip.com"};
acc.transport = SipProfile.TRANSPORT_UDP;
return acc;
}
}
| true | true | public SipProfile buildAccount(SipProfile account) {
SipProfile acc = super.buildAccount(account);
acc.proxies = new String[] {"sip:proxy.fastvoip.com"};
acc.transport = SipProfile.TRANSPORT_UDP;
return acc;
}
| public SipProfile buildAccount(SipProfile account) {
SipProfile acc = super.buildAccount(account);
acc.proxies = new String[] {"sip:sip.fastvoip.com"};
acc.transport = SipProfile.TRANSPORT_UDP;
return acc;
}
|
diff --git a/play-dcep-distributedetalis/src/main/java/eu/play_project/dcep/distributedetalis/join/HistoricalQueryContainer.java b/play-dcep-distributedetalis/src/main/java/eu/play_project/dcep/distributedetalis/join/HistoricalQueryContainer.java
index 24eab74f..c3952877 100644
--- a/play-dcep-distributedetalis/src/main/java/eu/play_project/dcep/distributedetalis/join/HistoricalQueryContainer.java
+++ b/play-dcep-distributedetalis/src/main/java/eu/play_project/dcep/distributedetalis/join/HistoricalQueryContainer.java
@@ -1,182 +1,182 @@
/**
*
*/
package eu.play_project.dcep.distributedetalis.join;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Ningyuan Pan
*
*/
public class HistoricalQueryContainer {
final static String SELECT = "SELECT";
final static String WHERE = "WHERE";
final static String VALUES = "VALUES";
final static String GRAPH = "GRAPH";
final static String STREAM = " :stream ";
//private static PutGetProxyRegister proxyRegis = PutGetProxyRegister.getInstance();
private final List<String> vvariables = new ArrayList<String>();
private final Map<String, List<String>> map;
private String query;
private final Logger logger = LoggerFactory.getLogger(HistoricalQueryContainer.class);
public HistoricalQueryContainer(String query, Map<String, List<String>> variableBindings){
if(query == null)
throw new IllegalArgumentException("Original query should not be null");
map = variableBindings;
if(map != null)
this.query = addVALUES(query);
else
this.query = query;
}
public String getQuery(){
return query;
}
/*
* Add VALUES block into querys
*/
private String addVALUES(String oquery){
int count = 0, index = 0;
StringBuilder sparqlb = new StringBuilder(oquery);
index = oquery.indexOf(VALUES);
if(index != -1){
//TODO
throw new IllegalArgumentException("Original query already has VALUES block");
}
else {
index = oquery.indexOf(WHERE);
logger.debug("where index: "+index);
// add vlues block in where block
if(index != -1){
while(index < oquery.length()){
if(oquery.charAt(index) == '{'){
count++;
}
else if(oquery.charAt(index) == '}'){
//count--;
if(count == 0){
break;
}
}
index++;
}
String vb = makeVALUES();
sparqlb.insert(index, vb);
}
}
return sparqlb.toString();
}
/*
* Make VALUES block using variables and its values
*/
private String makeVALUES(){
StringBuilder ret = new StringBuilder();
if(makeVariableList()){
ret.append("\n VALUES (");
for(int i = 0; i < vvariables.size(); i++){
ret.append(vvariables.get(i));
}
ret.append(" ) {\n");
ret = makeBody(ret, null, 0);
ret.append("}");
}
return ret.toString();
}
private boolean makeVariableList(){
boolean ret = false;
for(String variable : map.keySet()){
logger.debug("Add variable to list: " + variable);
vvariables.add(variable);
ret = true;
}
return ret;
}
/*
* Make VALUES body of all combinations of values
*/
private StringBuilder makeBody(StringBuilder ret, StringBuilder p, int depth){
StringBuilder path = p;
String pathMinusOne;
if(depth == vvariables.size()){
path.append(") ");
ret.append(path);
}
else if(depth == 0){
path = new StringBuilder();
List<String> values = map.get(vvariables.get(depth));
if(values == null || values.isEmpty()){
path.append("( UNDEF ");
ret = makeBody(ret, path, depth+1);
}
else{
for(int i = 0; i < values.size(); i++){
path.delete(0, path.length());
path.append("( "+values.get(i)+" ");
ret = makeBody(ret, path, depth+1);
}
}
}
else{
pathMinusOne = path.toString();
logger.debug(vvariables.get(depth));
- logger.debug(map.get(vvariables.get(depth)).toString());
+ logger.debug("{}", map.get(vvariables.get(depth)));
List<String> values = map.get(vvariables.get(depth));
if(values == null || values.isEmpty()){
path.append("UNDEF ");
ret = makeBody(ret, path, depth+1);
}
else{
for(int i = 0; i < values.size(); i++){
path.delete(0, path.length());
path.append(pathMinusOne);
path.append(values.get(i)+" ");
ret = makeBody(ret, path, depth+1);
}
}
}
return ret;
}
/*private String getAimStream(){
String ret = null;
StringBuilder sb = new StringBuilder();
int index = 0, size = STREAM.length();
char c;
index = oquery.indexOf(STREAM, index);
while(index != -1){
index += size;
c = oquery.charAt(index++);
while(c != ' '){
if(c != '<' && c != '>'){
sb.append(c);
}
c = oquery.charAt(index++);
}
ret = sb.toString();
logger.info("Aim stream: "+ret);
sb.delete(0, sb.length());
index = oquery.indexOf(STREAM, index);
}
return ret;
}*/
}
| true | true | private StringBuilder makeBody(StringBuilder ret, StringBuilder p, int depth){
StringBuilder path = p;
String pathMinusOne;
if(depth == vvariables.size()){
path.append(") ");
ret.append(path);
}
else if(depth == 0){
path = new StringBuilder();
List<String> values = map.get(vvariables.get(depth));
if(values == null || values.isEmpty()){
path.append("( UNDEF ");
ret = makeBody(ret, path, depth+1);
}
else{
for(int i = 0; i < values.size(); i++){
path.delete(0, path.length());
path.append("( "+values.get(i)+" ");
ret = makeBody(ret, path, depth+1);
}
}
}
else{
pathMinusOne = path.toString();
logger.debug(vvariables.get(depth));
logger.debug(map.get(vvariables.get(depth)).toString());
List<String> values = map.get(vvariables.get(depth));
if(values == null || values.isEmpty()){
path.append("UNDEF ");
ret = makeBody(ret, path, depth+1);
}
else{
for(int i = 0; i < values.size(); i++){
path.delete(0, path.length());
path.append(pathMinusOne);
path.append(values.get(i)+" ");
ret = makeBody(ret, path, depth+1);
}
}
}
return ret;
}
| private StringBuilder makeBody(StringBuilder ret, StringBuilder p, int depth){
StringBuilder path = p;
String pathMinusOne;
if(depth == vvariables.size()){
path.append(") ");
ret.append(path);
}
else if(depth == 0){
path = new StringBuilder();
List<String> values = map.get(vvariables.get(depth));
if(values == null || values.isEmpty()){
path.append("( UNDEF ");
ret = makeBody(ret, path, depth+1);
}
else{
for(int i = 0; i < values.size(); i++){
path.delete(0, path.length());
path.append("( "+values.get(i)+" ");
ret = makeBody(ret, path, depth+1);
}
}
}
else{
pathMinusOne = path.toString();
logger.debug(vvariables.get(depth));
logger.debug("{}", map.get(vvariables.get(depth)));
List<String> values = map.get(vvariables.get(depth));
if(values == null || values.isEmpty()){
path.append("UNDEF ");
ret = makeBody(ret, path, depth+1);
}
else{
for(int i = 0; i < values.size(); i++){
path.delete(0, path.length());
path.append(pathMinusOne);
path.append(values.get(i)+" ");
ret = makeBody(ret, path, depth+1);
}
}
}
return ret;
}
|
diff --git a/reflection/src/org/jvnet/jaxb/reflection/JAXBModelFactory.java b/reflection/src/org/jvnet/jaxb/reflection/JAXBModelFactory.java
index 752763a9..eb572e3b 100644
--- a/reflection/src/org/jvnet/jaxb/reflection/JAXBModelFactory.java
+++ b/reflection/src/org/jvnet/jaxb/reflection/JAXBModelFactory.java
@@ -1,125 +1,125 @@
package org.jvnet.jaxb.reflection;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import com.sun.xml.bind.v2.model.annotation.AnnotationReader;
import com.sun.xml.bind.v2.model.annotation.RuntimeAnnotationReader;
import com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader;
import com.sun.xml.bind.v2.model.core.ErrorHandler;
import com.sun.xml.bind.v2.model.core.Ref;
import com.sun.xml.bind.v2.model.core.TypeInfoSet;
import com.sun.xml.bind.v2.model.impl.ModelBuilder;
import com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder;
import com.sun.xml.bind.v2.model.nav.Navigator;
import com.sun.xml.bind.v2.model.runtime.RuntimeTypeInfoSet;
import com.sun.xml.bind.v2.runtime.IllegalAnnotationsException;
/**
* Factory methods to build JAXB models.
*
* @author Kohsuke Kawaguchi
*/
// this is a facade to ModelBuilder
public abstract class JAXBModelFactory {
private JAXBModelFactory() {} // no instanciation please
/**
* Creates a new JAXB model from
* classes represented in arbitrary reflection library.
*
* @param reader
* used to read annotations from classes. must not be null.
* @param navigator
* abstraction layer of the underlying Java reflection library.
* must not be null.
* @param errorHandler
* Receives errors found during the processing.
*
* @return
* null if any error was reported during the processing.
* If no error is reported, a non-null valid object.
*/
public static <T,C,F,M> TypeInfoSet<T,C,F,M> create(
AnnotationReader<T,C,F,M> reader,
Navigator<T,C,F,M> navigator,
ErrorHandler errorHandler,
Collection<C> classes ) {
- ModelBuilder<T,C,F,M> builder = new ModelBuilder<T,C,F,M>(reader,navigator,Collections.<Class,Class>emptyMap(),null);
+ ModelBuilder<T,C,F,M> builder = new ModelBuilder<T,C,F,M>(reader,navigator,Collections.<C,C>emptyMap(),null);
builder.setErrorHandler(errorHandler);
for( C c : classes )
builder.getTypeInfo(new Ref<T,C>(navigator.use(c)));
return builder.link();
}
/**
* Creates a new JAXB model from
* classes represented in <tt>java.lang.reflect</tt>.
*
* @param reader
* used to read annotations from classes. must not be null.
* @param errorHandler
* Receives errors found during the processing.
*
* @return
* null if any error was reported during the processing.
* If no error is reported, a non-null valid object.
*/
public static RuntimeTypeInfoSet create(
RuntimeAnnotationReader reader,
ErrorHandler errorHandler,
Class... classes ) {
RuntimeModelBuilder builder = new RuntimeModelBuilder(null,reader,Collections.<Class,Class>emptyMap(),null);
builder.setErrorHandler(errorHandler);
for( Class c : classes )
builder.getTypeInfo(new Ref<Type,Class>(c));
return builder.link();
}
/**
* Creates a new JAXB model from
* classes represented in <tt>java.lang.reflect</tt>.
*
* <p>
* This version reads annotations from the classes directly.
*
* @param errorHandler
* Receives errors found during the processing.
*
* @return
* null if any error was reported during the processing.
* If no error is reported, a non-null valid object.
*/
public static RuntimeTypeInfoSet create(
ErrorHandler errorHandler,
Class... classes ) {
return create( new RuntimeInlineAnnotationReader(), errorHandler, classes );
}
/**
* Creates a new JAXB model from
* classes represented in <tt>java.lang.reflect</tt>.
*
* <p>
* This version reads annotations from the classes directly,
* and throw any error reported as an exception
*
* @return
* null if any error was reported during the processing.
* If no error is reported, a non-null valid object.
* @throws IllegalAnnotationsException
* if there was any incorrect use of annotations in the specified set of classes.
*/
public static RuntimeTypeInfoSet create(Class... classes ) throws IllegalAnnotationsException {
IllegalAnnotationsException.Builder errorListener = new IllegalAnnotationsException.Builder();
RuntimeTypeInfoSet r = create(errorListener, classes);
errorListener.check();
return r;
}
}
| true | true | public static <T,C,F,M> TypeInfoSet<T,C,F,M> create(
AnnotationReader<T,C,F,M> reader,
Navigator<T,C,F,M> navigator,
ErrorHandler errorHandler,
Collection<C> classes ) {
ModelBuilder<T,C,F,M> builder = new ModelBuilder<T,C,F,M>(reader,navigator,Collections.<Class,Class>emptyMap(),null);
builder.setErrorHandler(errorHandler);
for( C c : classes )
builder.getTypeInfo(new Ref<T,C>(navigator.use(c)));
return builder.link();
}
| public static <T,C,F,M> TypeInfoSet<T,C,F,M> create(
AnnotationReader<T,C,F,M> reader,
Navigator<T,C,F,M> navigator,
ErrorHandler errorHandler,
Collection<C> classes ) {
ModelBuilder<T,C,F,M> builder = new ModelBuilder<T,C,F,M>(reader,navigator,Collections.<C,C>emptyMap(),null);
builder.setErrorHandler(errorHandler);
for( C c : classes )
builder.getTypeInfo(new Ref<T,C>(navigator.use(c)));
return builder.link();
}
|
diff --git a/src/bspkrs/treecapitator/fml/IDResolverMappingList.java b/src/bspkrs/treecapitator/fml/IDResolverMappingList.java
index 1ef14a2..8502b9f 100644
--- a/src/bspkrs/treecapitator/fml/IDResolverMappingList.java
+++ b/src/bspkrs/treecapitator/fml/IDResolverMappingList.java
@@ -1,262 +1,262 @@
package bspkrs.treecapitator.fml;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Properties;
import bspkrs.treecapitator.TCLog;
import bspkrs.treecapitator.TCSettings;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
@SuppressWarnings("rawtypes")
public class IDResolverMappingList implements List
{
private ArrayList<IDResolverMapping> list;
private static IDResolverMappingList instance;
public static IDResolverMappingList instance()
{
if (instance == null)
new IDResolverMappingList();
return instance;
}
private IDResolverMappingList()
{
instance = this;
list = new ArrayList<IDResolverMapping>();
init();
}
@SuppressWarnings("unchecked")
private void init()
{
/*
* Get IDs from ID Resolver if it's loaded
*/
if (Loader.isModLoaded(TCSettings.idResolverModID))
{
TCLog.info("ID Resolver has been detected. Processing ID config...");
Properties idrKnownIDs = null;
try
{
Class clazz = Class.forName("sharose.mods.idresolver.IDResolverMasic");
- idrKnownIDs = ObfuscationReflectionHelper.getPrivateValue(clazz, null, "knownIDs");
+ idrKnownIDs = (Properties) ObfuscationReflectionHelper.getPrivateValue(clazz, null, "knownIDs");
}
catch (Throwable e)
{
TCLog.debug("Error getting knownIDs from ID Resolver: %s", e.getMessage());
e.printStackTrace();
}
if (idrKnownIDs != null)
{
for (String key : idrKnownIDs.stringPropertyNames())
{
String value = idrKnownIDs.getProperty(key);
try
{
if (!key.startsWith("ItemID.") && !key.startsWith("BlockID."))
continue;
IDResolverMapping mapping = new IDResolverMapping(key + "=" + value);
if (mapping.oldID != 0 && mapping.newID != 0 && !mapping.isStaticMapping())
{
// IDs are not the same, add to the list of managed IDs
add(mapping);
TCLog.debug("Adding entry: %s", key + "=" + value);
}
else
TCLog.debug("Ignoring entry: %s", key + "=" + value);
}
catch (Throwable e)
{
TCLog.severe("Exception caught for line: %s", key + "=" + value);
}
}
}
}
else
TCLog.info("ID Resolver (Mod ID \"%s\") is not loaded.", TCSettings.idResolverModID);
}
public boolean hasMappingForModAndID(String className, int oldID)
{
Iterator i = list.iterator();
while (i.hasNext())
{
IDResolverMapping mapping = (IDResolverMapping) i.next();
if (mapping.modClassName.equals(className) && mapping.oldID == oldID)
return true;
}
return false;
}
public IDResolverMapping getMappingForModAndOldID(String className, int oldID)
{
Iterator i = list.iterator();
while (i.hasNext())
{
IDResolverMapping mapping = (IDResolverMapping) i.next();
if (mapping.modClassName.equals(className) && mapping.oldID == oldID)
return mapping;
}
return null;
}
@Override
public int size()
{
return list.size();
}
@Override
public boolean isEmpty()
{
return list.isEmpty();
}
@Override
public boolean contains(Object o)
{
return list.contains(o);
}
@Override
public Iterator iterator()
{
return list.iterator();
}
@SuppressWarnings("unchecked")
public ArrayList<IDResolverMapping> toArrayList()
{
return (ArrayList<IDResolverMapping>) list.clone();
}
@Override
public Object[] toArray()
{
return list.toArray();
}
@Override
public Object[] toArray(Object[] a)
{
return list.toArray(a);
}
@Override
public boolean add(Object e)
{
return list.add((IDResolverMapping) e);
}
@Override
public boolean remove(Object o)
{
return list.remove(o);
}
@Override
public boolean containsAll(Collection c)
{
return list.containsAll(c);
}
@SuppressWarnings("unchecked")
@Override
public boolean addAll(Collection c)
{
return list.addAll(c);
}
@SuppressWarnings("unchecked")
@Override
public boolean addAll(int index, Collection c)
{
return list.addAll(index, c);
}
@Override
public boolean removeAll(Collection c)
{
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection c)
{
return list.retainAll(c);
}
@Override
public void clear()
{
list.clear();
}
@Override
public Object get(int index)
{
return list.get(index);
}
@Override
public Object set(int index, Object element)
{
return list.set(index, (IDResolverMapping) element);
}
@Override
public void add(int index, Object element)
{
list.add(index, (IDResolverMapping) element);
}
@Override
public Object remove(int index)
{
return list.remove(index);
}
@Override
public int indexOf(Object o)
{
return list.indexOf(o);
}
@Override
public int lastIndexOf(Object o)
{
return list.lastIndexOf(o);
}
@Override
public ListIterator listIterator()
{
return list.listIterator();
}
@Override
public ListIterator listIterator(int index)
{
return list.listIterator(index);
}
@Override
public List subList(int fromIndex, int toIndex)
{
return list.subList(fromIndex, toIndex);
}
}
| true | true | private void init()
{
/*
* Get IDs from ID Resolver if it's loaded
*/
if (Loader.isModLoaded(TCSettings.idResolverModID))
{
TCLog.info("ID Resolver has been detected. Processing ID config...");
Properties idrKnownIDs = null;
try
{
Class clazz = Class.forName("sharose.mods.idresolver.IDResolverMasic");
idrKnownIDs = ObfuscationReflectionHelper.getPrivateValue(clazz, null, "knownIDs");
}
catch (Throwable e)
{
TCLog.debug("Error getting knownIDs from ID Resolver: %s", e.getMessage());
e.printStackTrace();
}
if (idrKnownIDs != null)
{
for (String key : idrKnownIDs.stringPropertyNames())
{
String value = idrKnownIDs.getProperty(key);
try
{
if (!key.startsWith("ItemID.") && !key.startsWith("BlockID."))
continue;
IDResolverMapping mapping = new IDResolverMapping(key + "=" + value);
if (mapping.oldID != 0 && mapping.newID != 0 && !mapping.isStaticMapping())
{
// IDs are not the same, add to the list of managed IDs
add(mapping);
TCLog.debug("Adding entry: %s", key + "=" + value);
}
else
TCLog.debug("Ignoring entry: %s", key + "=" + value);
}
catch (Throwable e)
{
TCLog.severe("Exception caught for line: %s", key + "=" + value);
}
}
}
}
else
TCLog.info("ID Resolver (Mod ID \"%s\") is not loaded.", TCSettings.idResolverModID);
}
| private void init()
{
/*
* Get IDs from ID Resolver if it's loaded
*/
if (Loader.isModLoaded(TCSettings.idResolverModID))
{
TCLog.info("ID Resolver has been detected. Processing ID config...");
Properties idrKnownIDs = null;
try
{
Class clazz = Class.forName("sharose.mods.idresolver.IDResolverMasic");
idrKnownIDs = (Properties) ObfuscationReflectionHelper.getPrivateValue(clazz, null, "knownIDs");
}
catch (Throwable e)
{
TCLog.debug("Error getting knownIDs from ID Resolver: %s", e.getMessage());
e.printStackTrace();
}
if (idrKnownIDs != null)
{
for (String key : idrKnownIDs.stringPropertyNames())
{
String value = idrKnownIDs.getProperty(key);
try
{
if (!key.startsWith("ItemID.") && !key.startsWith("BlockID."))
continue;
IDResolverMapping mapping = new IDResolverMapping(key + "=" + value);
if (mapping.oldID != 0 && mapping.newID != 0 && !mapping.isStaticMapping())
{
// IDs are not the same, add to the list of managed IDs
add(mapping);
TCLog.debug("Adding entry: %s", key + "=" + value);
}
else
TCLog.debug("Ignoring entry: %s", key + "=" + value);
}
catch (Throwable e)
{
TCLog.severe("Exception caught for line: %s", key + "=" + value);
}
}
}
}
else
TCLog.info("ID Resolver (Mod ID \"%s\") is not loaded.", TCSettings.idResolverModID);
}
|
diff --git a/app2/src/com/handbagdevices/handbag/PacketGenerator.java b/app2/src/com/handbagdevices/handbag/PacketGenerator.java
index 92434ff..88a5e93 100644
--- a/app2/src/com/handbagdevices/handbag/PacketGenerator.java
+++ b/app2/src/com/handbagdevices/handbag/PacketGenerator.java
@@ -1,38 +1,38 @@
package com.handbagdevices.handbag;
import java.util.*;
import android.text.TextUtils;
class PacketGenerator {
private static String encodeField(String content) {
if (content.startsWith("[")
|| content.contains(";")
|| content.contains("\n")) {
- // TODO: Explictly create formatter instance?
+ // TODO: Explicitly create formatter instance?
// (Due to comment in String.format docs:
// "...somewhat costly in terms of memory and
// time...if you rely on it for formatting a large
// number of strings, consider creating and reusing
// your own Formatter instance instead.")
content = String.format("[%d]%s", content.length(), content);
}
return content;
}
public static String fromArray(String[] fields) {
List<String> encodedFields = new ArrayList<String>();
for (String field : fields) {
encodedFields.add(encodeField(field));
}
// TODO: Replace all use of "[", ";" & "\n" in code with constants.
return TextUtils.join(";", encodedFields) + "\n";
}
}
| true | true | private static String encodeField(String content) {
if (content.startsWith("[")
|| content.contains(";")
|| content.contains("\n")) {
// TODO: Explictly create formatter instance?
// (Due to comment in String.format docs:
// "...somewhat costly in terms of memory and
// time...if you rely on it for formatting a large
// number of strings, consider creating and reusing
// your own Formatter instance instead.")
content = String.format("[%d]%s", content.length(), content);
}
return content;
}
| private static String encodeField(String content) {
if (content.startsWith("[")
|| content.contains(";")
|| content.contains("\n")) {
// TODO: Explicitly create formatter instance?
// (Due to comment in String.format docs:
// "...somewhat costly in terms of memory and
// time...if you rely on it for formatting a large
// number of strings, consider creating and reusing
// your own Formatter instance instead.")
content = String.format("[%d]%s", content.length(), content);
}
return content;
}
|
diff --git a/src/java/nl/b3p/viewer/admin/stripes/ApplicationTreeLayerActionBean.java b/src/java/nl/b3p/viewer/admin/stripes/ApplicationTreeLayerActionBean.java
index 2a2069258..b37765b83 100644
--- a/src/java/nl/b3p/viewer/admin/stripes/ApplicationTreeLayerActionBean.java
+++ b/src/java/nl/b3p/viewer/admin/stripes/ApplicationTreeLayerActionBean.java
@@ -1,319 +1,319 @@
/*
* Copyright (C) 2012 B3Partners B.V.
*
* 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 nl.b3p.viewer.admin.stripes;
import java.io.StringReader;
import java.util.*;
import javax.annotation.security.RolesAllowed;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.config.app.*;
import nl.b3p.viewer.config.security.Group;
import nl.b3p.viewer.config.services.*;
import org.json.*;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Jytte Schaeffer
*/
@UrlBinding("/action/applicationtreelayer")
@StrictBinding
@RolesAllowed({Group.ADMIN, Group.APPLICATION_ADMIN})
public class ApplicationTreeLayerActionBean extends ApplicationActionBean {
private static final String JSP = "/WEB-INF/jsp/application/applicationTreeLayer.jsp";
@Validate
private ApplicationLayer applicationLayer;
private List<Group> allGroups;
@Validate
private List<String> groupsRead = new ArrayList<String>();
@Validate
private List<String> groupsWrite = new ArrayList<String>();
@Validate
private Map<String, String> details = new HashMap<String, String>();
private List<AttributeDescriptor> attributesList = new ArrayList<AttributeDescriptor>();
@Validate
private List<String> selectedAttributes = new ArrayList<String>();
private boolean editable;
@Validate
private JSONArray attributesJSON = new JSONArray();
@Validate
private String attribute;
@DefaultHandler
public Resolution view() {
return new ForwardResolution(JSP);
}
@DontValidate
public Resolution edit() throws JSONException {
if (applicationLayer != null) {
details = applicationLayer.getDetails();
groupsRead.addAll(applicationLayer.getReaders());
groupsWrite.addAll(applicationLayer.getWriters());
Layer layer = (Layer) Stripersist.getEntityManager().createQuery("from Layer "
+ "where service = :service "
+ "and name = :name").setParameter("service", applicationLayer.getService()).setParameter("name", applicationLayer.getLayerName()).getSingleResult();
if (layer.getFeatureType() != null) {
SimpleFeatureType sft = layer.getFeatureType();
editable = sft.isWriteable();
attributesList = sft.getAttributes();
/*
* When a layer has attributes, but the applicationLayer doesn't
* have configuredAttributes, (because attributes where added
* after layer was added to an applicationTree) the
* configuredAttributes are made and saved for the
* applicationLayer. Otherwise the user can never configure edit
* and selection/filter.
*/
if ((applicationLayer.getAttributes() == null || applicationLayer.getAttributes().size() < 1) && (attributesList != null && attributesList.size() > 0)) {
for (Iterator it = attributesList.iterator(); it.hasNext();) {
AttributeDescriptor attribute = (AttributeDescriptor) it.next();
ConfiguredAttribute confAttribute = new ConfiguredAttribute();
confAttribute.setAttributeName(attribute.getName());
Stripersist.getEntityManager().persist(confAttribute);
applicationLayer.getAttributes().add(confAttribute);
}
Stripersist.getEntityManager().persist(applicationLayer);
application.authorizationsModified();
Stripersist.getEntityManager().getTransaction().commit();
}
for (Iterator it = applicationLayer.getAttributes().iterator(); it.hasNext();) {
ConfiguredAttribute ca = (ConfiguredAttribute) it.next();
//set visible
if (ca.isVisible()) {
selectedAttributes.add(ca.getAttributeName());
}
}
//set editable
makeAttributeJSONArray(attributesJSON, attributesList, sft);
}
}
return new ForwardResolution(JSP);
}
public Resolution getUniqueValues() throws JSONException {
JSONObject json = new JSONObject();
json.put("success", Boolean.FALSE);
try {
Layer layer = (Layer) Stripersist.getEntityManager().createQuery("from Layer "
+ "where service = :service "
+ "and name = :name").setParameter("service", applicationLayer.getService()).setParameter("name", applicationLayer.getLayerName()).getSingleResult();
if (layer.getFeatureType() != null) {
SimpleFeatureType sft = layer.getFeatureType();
List<String> beh = sft.calculateUniqueValues(attribute);
json.put("uniqueValues", new JSONArray(beh));
json.put("success", Boolean.TRUE);
}
} catch (Exception e) {
json.put("msg",e.toString());
}
return new StreamingResolution("application/json", new StringReader(json.toString()));
}
@Before(stages = LifecycleStage.BindingAndValidation)
@SuppressWarnings("unchecked")
public void load() {
allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList();
}
public Resolution save() throws JSONException {
applicationLayer.getDetails().clear();
applicationLayer.getDetails().putAll(details);
applicationLayer.getReaders().clear();
for (String groupName : groupsRead) {
applicationLayer.getReaders().add(groupName);
}
applicationLayer.getWriters().clear();
for (String groupName : groupsWrite) {
applicationLayer.getWriters().add(groupName);
}
if (applicationLayer.getAttributes() != null && applicationLayer.getAttributes().size() > 0) {
List<ConfiguredAttribute> appAttributes = applicationLayer.getAttributes();
int i = 0;
for (Iterator it = appAttributes.iterator(); it.hasNext();) {
ConfiguredAttribute appAttribute = (ConfiguredAttribute) it.next();
//save visible
if (selectedAttributes.contains(appAttribute.getAttributeName())) {
appAttribute.setVisible(true);
} else {
appAttribute.setVisible(false);
}
//save editable
if (attributesJSON.length() > i) {
JSONObject attribute = attributesJSON.getJSONObject(i);
if (attribute.has("editable")) {
appAttribute.setEditable(new Boolean(attribute.get("editable").toString()));
}
if (attribute.has("editalias")) {
appAttribute.setEditAlias(attribute.get("editalias").toString());
}
if (attribute.has("editvalues")) {
appAttribute.setEditValues(attribute.get("editvalues").toString());
}
if (attribute.has("editHeight")) {
appAttribute.setEditHeight(attribute.get("editHeight").toString());
}
//save selectable
if (attribute.has("selectable")) {
appAttribute.setSelectable(new Boolean(attribute.get("selectable").toString()));
}
if (attribute.has("filterable")) {
appAttribute.setFilterable(new Boolean(attribute.get("filterable").toString()));
}
if (attribute.has("defaultValue")) {
appAttribute.setDefaultValue(attribute.get("defaultValue").toString());
}
}
i++;
}
}
Stripersist.getEntityManager().persist(applicationLayer);
application.authorizationsModified();
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen"));
- return new ForwardResolution(JSP);
+ return edit();
}
private void makeAttributeJSONArray(JSONArray array, List<AttributeDescriptor> ftAttributes, SimpleFeatureType sft) throws JSONException {
List<ConfiguredAttribute> appAttributes = applicationLayer.getAttributes();
int i = 0;
for (Iterator it = appAttributes.iterator(); it.hasNext();) {
ConfiguredAttribute appAttribute = (ConfiguredAttribute) it.next();
JSONObject j = appAttribute.toJSONObject();
if (attributesList.size() > i) {
j.put("alias", attributesList.get(i).getAlias());
}
for (AttributeDescriptor ad : ftAttributes) {
if (ad.getName().equals(appAttribute.getAttributeName())) {
j.put("featureTypeAttribute", ad.toJSONObject());
break;
}
}
array.put(j);
i++;
}
}
//<editor-fold defaultstate="collapsed" desc="getters & setters">
public ApplicationLayer getApplicationLayer() {
return applicationLayer;
}
public void setApplicationLayer(ApplicationLayer applicationLayer) {
this.applicationLayer = applicationLayer;
}
public List<Group> getAllGroups() {
return allGroups;
}
public void setAllGroups(List<Group> allGroups) {
this.allGroups = allGroups;
}
public Map<String, String> getDetails() {
return details;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
public List<String> getSelectedAttributes() {
return selectedAttributes;
}
public void setSelectedAttributes(List<String> selectedAttributes) {
this.selectedAttributes = selectedAttributes;
}
public List<AttributeDescriptor> getAttributesList() {
return attributesList;
}
public void setAttributesList(List<AttributeDescriptor> attributesList) {
this.attributesList = attributesList;
}
public JSONArray getAttributesJSON() {
return attributesJSON;
}
public void setAttributesJSON(JSONArray attributesJSON) {
this.attributesJSON = attributesJSON;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public List<String> getGroupsWrite() {
return groupsWrite;
}
public void setGroupsWrite(List<String> groupsWrite) {
this.groupsWrite = groupsWrite;
}
public List<String> getGroupsRead() {
return groupsRead;
}
public void setGroupsRead(List<String> groupsRead) {
this.groupsRead = groupsRead;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
//</editor-fold>
}
| true | true | public Resolution save() throws JSONException {
applicationLayer.getDetails().clear();
applicationLayer.getDetails().putAll(details);
applicationLayer.getReaders().clear();
for (String groupName : groupsRead) {
applicationLayer.getReaders().add(groupName);
}
applicationLayer.getWriters().clear();
for (String groupName : groupsWrite) {
applicationLayer.getWriters().add(groupName);
}
if (applicationLayer.getAttributes() != null && applicationLayer.getAttributes().size() > 0) {
List<ConfiguredAttribute> appAttributes = applicationLayer.getAttributes();
int i = 0;
for (Iterator it = appAttributes.iterator(); it.hasNext();) {
ConfiguredAttribute appAttribute = (ConfiguredAttribute) it.next();
//save visible
if (selectedAttributes.contains(appAttribute.getAttributeName())) {
appAttribute.setVisible(true);
} else {
appAttribute.setVisible(false);
}
//save editable
if (attributesJSON.length() > i) {
JSONObject attribute = attributesJSON.getJSONObject(i);
if (attribute.has("editable")) {
appAttribute.setEditable(new Boolean(attribute.get("editable").toString()));
}
if (attribute.has("editalias")) {
appAttribute.setEditAlias(attribute.get("editalias").toString());
}
if (attribute.has("editvalues")) {
appAttribute.setEditValues(attribute.get("editvalues").toString());
}
if (attribute.has("editHeight")) {
appAttribute.setEditHeight(attribute.get("editHeight").toString());
}
//save selectable
if (attribute.has("selectable")) {
appAttribute.setSelectable(new Boolean(attribute.get("selectable").toString()));
}
if (attribute.has("filterable")) {
appAttribute.setFilterable(new Boolean(attribute.get("filterable").toString()));
}
if (attribute.has("defaultValue")) {
appAttribute.setDefaultValue(attribute.get("defaultValue").toString());
}
}
i++;
}
}
Stripersist.getEntityManager().persist(applicationLayer);
application.authorizationsModified();
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen"));
return new ForwardResolution(JSP);
}
| public Resolution save() throws JSONException {
applicationLayer.getDetails().clear();
applicationLayer.getDetails().putAll(details);
applicationLayer.getReaders().clear();
for (String groupName : groupsRead) {
applicationLayer.getReaders().add(groupName);
}
applicationLayer.getWriters().clear();
for (String groupName : groupsWrite) {
applicationLayer.getWriters().add(groupName);
}
if (applicationLayer.getAttributes() != null && applicationLayer.getAttributes().size() > 0) {
List<ConfiguredAttribute> appAttributes = applicationLayer.getAttributes();
int i = 0;
for (Iterator it = appAttributes.iterator(); it.hasNext();) {
ConfiguredAttribute appAttribute = (ConfiguredAttribute) it.next();
//save visible
if (selectedAttributes.contains(appAttribute.getAttributeName())) {
appAttribute.setVisible(true);
} else {
appAttribute.setVisible(false);
}
//save editable
if (attributesJSON.length() > i) {
JSONObject attribute = attributesJSON.getJSONObject(i);
if (attribute.has("editable")) {
appAttribute.setEditable(new Boolean(attribute.get("editable").toString()));
}
if (attribute.has("editalias")) {
appAttribute.setEditAlias(attribute.get("editalias").toString());
}
if (attribute.has("editvalues")) {
appAttribute.setEditValues(attribute.get("editvalues").toString());
}
if (attribute.has("editHeight")) {
appAttribute.setEditHeight(attribute.get("editHeight").toString());
}
//save selectable
if (attribute.has("selectable")) {
appAttribute.setSelectable(new Boolean(attribute.get("selectable").toString()));
}
if (attribute.has("filterable")) {
appAttribute.setFilterable(new Boolean(attribute.get("filterable").toString()));
}
if (attribute.has("defaultValue")) {
appAttribute.setDefaultValue(attribute.get("defaultValue").toString());
}
}
i++;
}
}
Stripersist.getEntityManager().persist(applicationLayer);
application.authorizationsModified();
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen"));
return edit();
}
|
diff --git a/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java b/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java
index 543b1f61e..fe0abc4ef 100644
--- a/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java
+++ b/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java
@@ -1,197 +1,197 @@
/*
* 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.linkable.features;
import static com.bloatit.framework.webprocessor.context.Context.tr;
import static com.bloatit.framework.webprocessor.context.Context.trn;
import java.math.BigDecimal;
import com.bloatit.data.queries.EmptyPageIterable;
import com.bloatit.framework.utils.PageIterable;
import com.bloatit.framework.utils.datetime.DateUtils;
import com.bloatit.framework.utils.datetime.TimeRenderer;
import com.bloatit.framework.utils.i18n.CurrencyLocale;
import com.bloatit.framework.webprocessor.components.HtmlDiv;
import com.bloatit.framework.webprocessor.components.HtmlLink;
import com.bloatit.framework.webprocessor.components.HtmlParagraph;
import com.bloatit.framework.webprocessor.components.HtmlSpan;
import com.bloatit.framework.webprocessor.components.HtmlTitle;
import com.bloatit.framework.webprocessor.components.PlaceHolderElement;
import com.bloatit.framework.webprocessor.components.meta.HtmlElement;
import com.bloatit.framework.webprocessor.components.meta.HtmlMixedText;
import com.bloatit.framework.webprocessor.context.Context;
import com.bloatit.model.ElveosUserToken;
import com.bloatit.model.Feature;
import com.bloatit.model.Offer;
import com.bloatit.web.url.MakeOfferPageUrl;
public class FeatureOfferListComponent extends HtmlDiv {
protected FeatureOfferListComponent(final Feature feature, ElveosUserToken userToken) {
super();
PageIterable<Offer> offers = new EmptyPageIterable<Offer>();
offers = feature.getOffers();
int nbUnselected = offers.size();
final Offer selectedOffer = feature.getSelectedOffer();
if (selectedOffer != null) {
nbUnselected--;
}
final HtmlDiv offersBlock = new HtmlDiv("offers_block");
switch (feature.getFeatureState()) {
case PENDING: {
offersBlock.add(new HtmlTitle(tr("No offer"), 1));
final BicolumnOfferBlock block = new BicolumnOfferBlock(true);
offersBlock.add(block);
- block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer is selected by default.")));
+ block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer will be selected by default.")));
final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(tr("Make an offer"));
link.setCssClass("button");
final HtmlDiv noOffer = new HtmlDiv("no_offer_block");
{
noOffer.add(link);
}
block.addInRightColumn(noOffer);
}
break;
case PREPARING: {
offersBlock.add(new HtmlTitle(tr("Selected offer"), 1));
// Selected
final BicolumnOfferBlock block = new BicolumnOfferBlock(true);
offersBlock.add(block);
// Generating the left column
block.addInLeftColumn(new HtmlParagraph(tr("The selected offer is the one with the more popularity.")));
if (selectedOffer != null) {
if (feature.getValidationDate() != null && DateUtils.isInTheFuture(feature.getValidationDate())) {
final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate()));
final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution());
if (amountLeft.compareTo(BigDecimal.ZERO) > 0) {
final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft);
final HtmlSpan timeSpan = new HtmlSpan("bold");
timeSpan.addText(renderer.getTimeString());
final HtmlMixedText timeToValid = new HtmlMixedText(tr("This offer will be validated in about <0::>. After this time, the offer will go into development as soon as the requested amount is available ({0} left).",
currency.getSimpleEuroString()),
timeSpan);
final HtmlParagraph element = new HtmlParagraph(timeToValid);
block.addInLeftColumn(element);
} else {
final HtmlSpan timeSpan = new HtmlSpan("bold");
timeSpan.addText(renderer.getTimeString());
final HtmlMixedText timeToValid = new HtmlMixedText("This offer will go into development in about <0::>.", timeSpan);
block.addInLeftColumn(timeToValid);
}
} else {
final BigDecimal amountLeft = feature.getSelectedOffer().getAmount().subtract(feature.getContribution());
final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft);
block.addInLeftColumn(new HtmlParagraph(tr("This offer is validated and will go into development as soon as the requested amount is available ({0} left).",
currency.toString())));
}
// Generating the right column
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
}
// UnSelected
offersBlock.add(new HtmlTitle(trn("Unselected offer ({0})", "Unselected offers ({0})", nbUnselected, nbUnselected), 1));
final BicolumnOfferBlock unselectedBlock = new BicolumnOfferBlock(true);
offersBlock.add(unselectedBlock);
unselectedBlock.addInLeftColumn(new MakeOfferPageUrl(feature).getHtmlLink(tr("Make a concurrent offer")));
unselectedBlock.addInLeftColumn(new HtmlParagraph("The concurrent offers must be voted enough to become the selected offer."));
for (final Offer offer : offers) {
if (offer != selectedOffer) {
unselectedBlock.addInRightColumn(new OfferBlock(offer, false, userToken));
}
}
break;
}
case DEVELOPPING:
final BicolumnOfferBlock block;
offersBlock.add(new HtmlTitle(tr("Offer in development"), 1));
offersBlock.add(block = new BicolumnOfferBlock(true));
block.addInLeftColumn(new HtmlParagraph(tr("This offer is in development. You can discuss about it in the comments.")));
if (selectedOffer != null && selectedOffer.hasRelease()) {
block.addInLeftColumn(new HtmlParagraph(tr("Test the last release and report bugs.")));
}
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock, userToken);
break;
case FINISHED:
offersBlock.add(new HtmlTitle(tr("Finished offer"), 1));
offersBlock.add(block = new BicolumnOfferBlock(true));
block.addInLeftColumn(new HtmlParagraph(tr("This offer is finished.")));
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock, userToken);
break;
case DISCARDED:
offersBlock.add(new HtmlTitle(tr("Feature discarded ..."), 1));
break;
default:
break;
}
add(offersBlock);
}
private void generateOldOffersList(final PageIterable<Offer> offers,
final int nbUnselected,
final Offer selectedOffer,
final HtmlDiv offersBlock,
ElveosUserToken userToken) {
// UnSelected
offersBlock.add(new HtmlTitle(trn("Old offer ({0})", "Old offers ({0})", nbUnselected, nbUnselected), 1));
final BicolumnOfferBlock unselectedBlock = new BicolumnOfferBlock(true);
offersBlock.add(unselectedBlock);
unselectedBlock.addInLeftColumn(new HtmlParagraph(tr("These offers have not been selected and will never be developed.")));
for (final Offer offer : offers) {
if (offer != selectedOffer) {
unselectedBlock.addInRightColumn(new OfferBlock(offer, false, userToken));
}
}
}
private static class BicolumnOfferBlock extends HtmlDiv {
private final PlaceHolderElement leftColumn = new PlaceHolderElement();
private final PlaceHolderElement rightColumn = new PlaceHolderElement();
public BicolumnOfferBlock(final boolean isSelected) {
super("offer_type_block");
HtmlDiv divSelected;
if (isSelected) {
divSelected = new HtmlDiv("offer_selected_description");
} else {
divSelected = new HtmlDiv("offer_unselected_description");
}
add(new HtmlDiv("offer_type_left_column").add(divSelected.add(leftColumn)));
add(new HtmlDiv("offer_type_right_column").add(rightColumn));
}
public void addInLeftColumn(final HtmlElement elment) {
leftColumn.add(elment);
}
public void addInRightColumn(final HtmlElement elment) {
rightColumn.add(elment);
}
}
}
| true | true | protected FeatureOfferListComponent(final Feature feature, ElveosUserToken userToken) {
super();
PageIterable<Offer> offers = new EmptyPageIterable<Offer>();
offers = feature.getOffers();
int nbUnselected = offers.size();
final Offer selectedOffer = feature.getSelectedOffer();
if (selectedOffer != null) {
nbUnselected--;
}
final HtmlDiv offersBlock = new HtmlDiv("offers_block");
switch (feature.getFeatureState()) {
case PENDING: {
offersBlock.add(new HtmlTitle(tr("No offer"), 1));
final BicolumnOfferBlock block = new BicolumnOfferBlock(true);
offersBlock.add(block);
block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer is selected by default.")));
final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(tr("Make an offer"));
link.setCssClass("button");
final HtmlDiv noOffer = new HtmlDiv("no_offer_block");
{
noOffer.add(link);
}
block.addInRightColumn(noOffer);
}
break;
case PREPARING: {
offersBlock.add(new HtmlTitle(tr("Selected offer"), 1));
// Selected
final BicolumnOfferBlock block = new BicolumnOfferBlock(true);
offersBlock.add(block);
// Generating the left column
block.addInLeftColumn(new HtmlParagraph(tr("The selected offer is the one with the more popularity.")));
if (selectedOffer != null) {
if (feature.getValidationDate() != null && DateUtils.isInTheFuture(feature.getValidationDate())) {
final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate()));
final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution());
if (amountLeft.compareTo(BigDecimal.ZERO) > 0) {
final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft);
final HtmlSpan timeSpan = new HtmlSpan("bold");
timeSpan.addText(renderer.getTimeString());
final HtmlMixedText timeToValid = new HtmlMixedText(tr("This offer will be validated in about <0::>. After this time, the offer will go into development as soon as the requested amount is available ({0} left).",
currency.getSimpleEuroString()),
timeSpan);
final HtmlParagraph element = new HtmlParagraph(timeToValid);
block.addInLeftColumn(element);
} else {
final HtmlSpan timeSpan = new HtmlSpan("bold");
timeSpan.addText(renderer.getTimeString());
final HtmlMixedText timeToValid = new HtmlMixedText("This offer will go into development in about <0::>.", timeSpan);
block.addInLeftColumn(timeToValid);
}
} else {
final BigDecimal amountLeft = feature.getSelectedOffer().getAmount().subtract(feature.getContribution());
final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft);
block.addInLeftColumn(new HtmlParagraph(tr("This offer is validated and will go into development as soon as the requested amount is available ({0} left).",
currency.toString())));
}
// Generating the right column
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
}
// UnSelected
offersBlock.add(new HtmlTitle(trn("Unselected offer ({0})", "Unselected offers ({0})", nbUnselected, nbUnselected), 1));
final BicolumnOfferBlock unselectedBlock = new BicolumnOfferBlock(true);
offersBlock.add(unselectedBlock);
unselectedBlock.addInLeftColumn(new MakeOfferPageUrl(feature).getHtmlLink(tr("Make a concurrent offer")));
unselectedBlock.addInLeftColumn(new HtmlParagraph("The concurrent offers must be voted enough to become the selected offer."));
for (final Offer offer : offers) {
if (offer != selectedOffer) {
unselectedBlock.addInRightColumn(new OfferBlock(offer, false, userToken));
}
}
break;
}
case DEVELOPPING:
final BicolumnOfferBlock block;
offersBlock.add(new HtmlTitle(tr("Offer in development"), 1));
offersBlock.add(block = new BicolumnOfferBlock(true));
block.addInLeftColumn(new HtmlParagraph(tr("This offer is in development. You can discuss about it in the comments.")));
if (selectedOffer != null && selectedOffer.hasRelease()) {
block.addInLeftColumn(new HtmlParagraph(tr("Test the last release and report bugs.")));
}
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock, userToken);
break;
case FINISHED:
offersBlock.add(new HtmlTitle(tr("Finished offer"), 1));
offersBlock.add(block = new BicolumnOfferBlock(true));
block.addInLeftColumn(new HtmlParagraph(tr("This offer is finished.")));
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock, userToken);
break;
case DISCARDED:
offersBlock.add(new HtmlTitle(tr("Feature discarded ..."), 1));
break;
default:
break;
}
add(offersBlock);
}
| protected FeatureOfferListComponent(final Feature feature, ElveosUserToken userToken) {
super();
PageIterable<Offer> offers = new EmptyPageIterable<Offer>();
offers = feature.getOffers();
int nbUnselected = offers.size();
final Offer selectedOffer = feature.getSelectedOffer();
if (selectedOffer != null) {
nbUnselected--;
}
final HtmlDiv offersBlock = new HtmlDiv("offers_block");
switch (feature.getFeatureState()) {
case PENDING: {
offersBlock.add(new HtmlTitle(tr("No offer"), 1));
final BicolumnOfferBlock block = new BicolumnOfferBlock(true);
offersBlock.add(block);
block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer will be selected by default.")));
final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(tr("Make an offer"));
link.setCssClass("button");
final HtmlDiv noOffer = new HtmlDiv("no_offer_block");
{
noOffer.add(link);
}
block.addInRightColumn(noOffer);
}
break;
case PREPARING: {
offersBlock.add(new HtmlTitle(tr("Selected offer"), 1));
// Selected
final BicolumnOfferBlock block = new BicolumnOfferBlock(true);
offersBlock.add(block);
// Generating the left column
block.addInLeftColumn(new HtmlParagraph(tr("The selected offer is the one with the more popularity.")));
if (selectedOffer != null) {
if (feature.getValidationDate() != null && DateUtils.isInTheFuture(feature.getValidationDate())) {
final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate()));
final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution());
if (amountLeft.compareTo(BigDecimal.ZERO) > 0) {
final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft);
final HtmlSpan timeSpan = new HtmlSpan("bold");
timeSpan.addText(renderer.getTimeString());
final HtmlMixedText timeToValid = new HtmlMixedText(tr("This offer will be validated in about <0::>. After this time, the offer will go into development as soon as the requested amount is available ({0} left).",
currency.getSimpleEuroString()),
timeSpan);
final HtmlParagraph element = new HtmlParagraph(timeToValid);
block.addInLeftColumn(element);
} else {
final HtmlSpan timeSpan = new HtmlSpan("bold");
timeSpan.addText(renderer.getTimeString());
final HtmlMixedText timeToValid = new HtmlMixedText("This offer will go into development in about <0::>.", timeSpan);
block.addInLeftColumn(timeToValid);
}
} else {
final BigDecimal amountLeft = feature.getSelectedOffer().getAmount().subtract(feature.getContribution());
final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft);
block.addInLeftColumn(new HtmlParagraph(tr("This offer is validated and will go into development as soon as the requested amount is available ({0} left).",
currency.toString())));
}
// Generating the right column
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
}
// UnSelected
offersBlock.add(new HtmlTitle(trn("Unselected offer ({0})", "Unselected offers ({0})", nbUnselected, nbUnselected), 1));
final BicolumnOfferBlock unselectedBlock = new BicolumnOfferBlock(true);
offersBlock.add(unselectedBlock);
unselectedBlock.addInLeftColumn(new MakeOfferPageUrl(feature).getHtmlLink(tr("Make a concurrent offer")));
unselectedBlock.addInLeftColumn(new HtmlParagraph("The concurrent offers must be voted enough to become the selected offer."));
for (final Offer offer : offers) {
if (offer != selectedOffer) {
unselectedBlock.addInRightColumn(new OfferBlock(offer, false, userToken));
}
}
break;
}
case DEVELOPPING:
final BicolumnOfferBlock block;
offersBlock.add(new HtmlTitle(tr("Offer in development"), 1));
offersBlock.add(block = new BicolumnOfferBlock(true));
block.addInLeftColumn(new HtmlParagraph(tr("This offer is in development. You can discuss about it in the comments.")));
if (selectedOffer != null && selectedOffer.hasRelease()) {
block.addInLeftColumn(new HtmlParagraph(tr("Test the last release and report bugs.")));
}
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock, userToken);
break;
case FINISHED:
offersBlock.add(new HtmlTitle(tr("Finished offer"), 1));
offersBlock.add(block = new BicolumnOfferBlock(true));
block.addInLeftColumn(new HtmlParagraph(tr("This offer is finished.")));
block.addInRightColumn(new OfferBlock(selectedOffer, true, userToken));
generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock, userToken);
break;
case DISCARDED:
offersBlock.add(new HtmlTitle(tr("Feature discarded ..."), 1));
break;
default:
break;
}
add(offersBlock);
}
|
diff --git a/src/org/jruby/util/Dir.java b/src/org/jruby/util/Dir.java
index 8f3da0dba..913c35b9c 100644
--- a/src/org/jruby/util/Dir.java
+++ b/src/org/jruby/util/Dir.java
@@ -1,602 +1,602 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* 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) 2007 Ola Bini <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of 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 CPL, 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 CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.util;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* This class exists as a counterpart to the dir.c file in
* MRI source. It contains many methods useful for
* File matching and Globbing.
*
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
public class Dir {
public final static boolean DOSISH = System.getProperty("os.name").indexOf("Windows") != -1;
public final static boolean CASEFOLD_FILESYSTEM = DOSISH;
public final static int FNM_NOESCAPE = 0x01;
public final static int FNM_PATHNAME = 0x02;
public final static int FNM_DOTMATCH = 0x04;
public final static int FNM_CASEFOLD = 0x08;
public final static int FNM_SYSCASE = CASEFOLD_FILESYSTEM ? FNM_CASEFOLD : 0;
public final static int FNM_NOMATCH = 1;
public final static int FNM_ERROR = 2;
public final static byte[] EMPTY = new byte[0];
public final static byte[] SLASH = new byte[]{'/'};
public final static byte[] STAR = new byte[]{'*'};
public final static byte[] DOUBLE_STAR = new byte[]{'*','*'};
private static boolean isdirsep(byte c) {
return DOSISH ? (c == '\\' || c == '/') : c == '/';
}
private static int rb_path_next(byte[] _s, int s, int len) {
while(s < len && !isdirsep(_s[s])) {
s++;
}
return s;
}
public static int fnmatch(byte[] _pat, int pstart, int plen, byte[] string, int sstart, int slen, int flags) {
byte c;
char test;
int s = sstart;
int pat = pstart;
int len = plen;
boolean escape = (flags & FNM_NOESCAPE) == 0;
boolean pathname = (flags & FNM_PATHNAME) != 0;
boolean period = (flags & FNM_DOTMATCH) == 0;
boolean nocase = (flags & FNM_CASEFOLD) != 0;
while(pat<len) {
c = _pat[pat++];
switch(c) {
case '?':
if(s >= slen || (pathname && isdirsep(string[s])) ||
(period && string[s] == '.' && (s == 0 || (pathname && isdirsep(string[s-1]))))) {
return FNM_NOMATCH;
}
s++;
break;
case '*':
while(pat < len && (c = _pat[pat++]) == '*');
if((period && string[s] == '.' && (s == 0 || (pathname && isdirsep(string[s-1]))))) {
return FNM_NOMATCH;
}
if(pat >= len) {
if(pathname && rb_path_next(string, s, slen) < slen) {
return FNM_NOMATCH;
} else {
return 0;
}
} else if((pathname && isdirsep(c))) {
s = rb_path_next(string, s, slen);
if(s < slen) {
s++;
break;
}
return FNM_NOMATCH;
}
test = (char)((escape && c == '\\' ? _pat[pat] : c)&0xFF);
test = Character.toLowerCase(test);
pat--;
while(s < slen) {
if((c == '?' || c == '[' || Character.toLowerCase(string[s]) == test) &&
fnmatch(_pat, pat, plen, string, s, slen, flags | FNM_DOTMATCH) == 0) {
return 0;
} else if((pathname && isdirsep(string[s]))) {
break;
}
s++;
}
return FNM_NOMATCH;
case '[':
if(s >= slen || (pathname && isdirsep(string[s]) ||
(period && string[s] == '.' && (s == 0 || (pathname && isdirsep(string[s-1])))))) {
return FNM_NOMATCH;
}
pat = range(_pat, pat, plen, (char)(string[s]&0xFF), flags);
if(pat == -1) {
return FNM_NOMATCH;
}
s++;
break;
case '\\':
if(escape &&
(!DOSISH ||
(pat < len && "*?[]\\".indexOf((char)_pat[pat]) != -1))) {
if(pat >= len) {
c = '\\';
} else {
c = _pat[pat++];
}
}
default:
if(s >= slen) {
return FNM_NOMATCH;
}
if(DOSISH && (pathname && isdirsep(c) && isdirsep(string[s]))) {
} else {
if(Character.toLowerCase((char)c) != Character.toLowerCase(string[s])) {
return FNM_NOMATCH;
}
}
s++;
break;
}
}
return s >= slen ? 0 : FNM_NOMATCH;
}
public static int range(byte[] _pat, int pat, int len, char test, int flags) {
boolean not;
boolean ok = false;
boolean nocase = (flags & FNM_CASEFOLD) != 0;
boolean escape = (flags & FNM_NOESCAPE) == 0;
not = _pat[pat] == '!' || _pat[pat] == '^';
if(not) {
pat++;
}
test = Character.toLowerCase(test);
while(_pat[pat] != ']') {
int cstart, cend;
if(escape && _pat[pat] == '\\') {
pat++;
}
if(pat >= len) {
return -1;
}
cstart = cend = (char)(_pat[pat++]&0xFF);
if(_pat[pat] == '-' && _pat[pat+1] != ']') {
pat++;
if(escape && _pat[pat] == '\\') {
pat++;
}
if(pat >= len) {
return -1;
}
cend = (char)(_pat[pat++] & 0xFF);
}
if(Character.toLowerCase(cstart) <= test && test <= Character.toLowerCase(cend)) {
ok = true;
}
}
return ok == not ? -1 : pat + 1;
}
public static List push_glob(String cwd, byte[] str, int p, int pend, int flags) {
int buf;
int nest, maxnest;
int status = 0;
boolean noescape = (flags & FNM_NOESCAPE) != 0;
List ary = new ArrayList();
while(p < pend) {
nest = maxnest = 0;
while(p<pend && str[p] == 0) {
p++;
}
buf = p;
while(p<pend && str[p] != 0) {
if(str[p] == '{') {
nest++;
maxnest++;
} else if(str[p] == '}') {
nest--;
} else if(!noescape && str[p] == '\\') {
if(++p == pend) {
break;
}
}
p++;
}
if(maxnest == 0) {
status = push_globs(cwd, ary, str, buf, pend, flags);
if(status != 0) {
break;
}
} else if(nest == 0) {
status = push_braces(cwd, ary, str, buf, pend, flags);
if(status != 0) {
break;
}
}
/* else unmatched braces */
}
return ary;
}
private static interface GlobFunc {
int call(byte[] ptr, int p, int len, Object ary);
}
private static class GlobArgs {
GlobFunc func;
int c = -1;
List v;
}
public final static GlobFunc push_pattern = new GlobFunc() {
public int call(byte[] ptr, int p, int len, Object ary) {
((List)ary).add(new ByteList(ptr, p, len));
return 0;
}
};
public final static GlobFunc glob_caller = new GlobFunc() {
public int call(byte[] ptr, int p, int len, Object ary) {
GlobArgs args = (GlobArgs)ary;
args.c = p;
return args.func.call(ptr, args.c, len, args.v);
}
};
private static int push_braces(String cwd, List ary, byte[] str, int _s, int slen, int flags) {
ByteList buf = new ByteList();
int b;
int s, p, t, lbrace, rbrace;
int nest = 0;
int status = 0;
s = p = 0;
s = p = _s;
lbrace = rbrace = -1;
while(p<slen) {
if(str[p] == '{') {
lbrace = p;
break;
}
p++;
}
while(p<slen) {
if(str[p] == '{') {
nest++;
} else if(str[p] == '}' && --nest == 0) {
rbrace = p;
break;
}
p++;
}
if(lbrace != -1 && rbrace != -1) {
p = lbrace;
while(str[p] != '}') {
t = p + 1;
for(p = t; p<slen && str[p] != '}' && str[p]!=','; p++) {
/* skip inner braces */
if(str[p] == '{') {
nest = 1;
while(str[++p] != '}' || --nest != 0) {
if(str[p] == '{') {
nest++;
}
}
}
}
buf.length(0);
buf.append(str,s,lbrace-s);
b = lbrace-s;
buf.append(str, t, p-t);
buf.append(str, rbrace+1, slen-(rbrace+1));
status = push_braces(cwd, ary, buf.bytes, 0, buf.realSize, flags);
if(status != 0) {
break;
}
}
} else {
status = push_globs(cwd, ary, str, s, slen, flags);
}
return status;
}
private static int push_globs(String cwd, List ary, byte[] str, int s, int slen, int flags) {
return rb_glob2(cwd, str, s, slen, flags, push_pattern, ary);
}
private static int rb_glob2(String cwd, byte[] _path, int path, int plen, int flags, GlobFunc func, List arg) {
GlobArgs args = new GlobArgs();
args.func = func;
args.v = arg;
flags |= FNM_SYSCASE;
return glob_helper(cwd, _path, path, plen, -1, flags, glob_caller, args);
}
private static boolean has_magic(byte[] str, int s, int send, int slen, int flags) {
int p = s;
byte c;
int open = 0;
boolean escape = (flags & FNM_NOESCAPE) == 0;
boolean nocase = (flags & FNM_CASEFOLD) != 0;
while(p < slen) {
c = str[p++];
switch(c) {
case '?':
case '*':
return true;
case '[': /* Only accept an open brace if there is a close */
open++; /* brace to match it. Bracket expressions must be */
continue; /* complete, according to Posix.2 */
case ']':
if(open > 0) {
return true;
}
continue;
case '\\':
if(escape && p == slen) {
return false;
}
break;
default:
if(FNM_SYSCASE==0 && Character.isLetter((char)(c&0xFF)) && nocase) {
return true;
}
}
if(send != -1 && p >= send) {
break;
}
}
return false;
}
private static int remove_backslashes(byte[] pa, int p, int len) {
int pend = len;
int t = p;
while(p < pend) {
if(pa[p] == '\\') {
if(++p == pend) {
break;
}
}
pa[t++] = pa[p++];
}
return t;
}
private static int strchr(byte[] _s, int s, byte ch) {
for(int i=s,e=_s.length;i<e; i++) {
if(_s[i] == ch) {
return i-s;
}
}
return -1;
}
private static byte[] extract_path(byte[] _p, int p, int pend) {
byte[] alloc;
int len;
len = pend-p;
if(len > 1 && _p[pend-1] == '/' && (!DOSISH || (len < 2 || _p[pend-2] != ':'))) {
len--;
}
alloc = new byte[len];
System.arraycopy(_p,p,alloc,0,len);
return alloc;
}
private static byte[] extract_elem(byte[] _p, int p, int pend) {
int _pend = strchr(_p,p,(byte)'/');
if(_pend == -1 || (_pend+p) > pend) {
_pend = pend;
}else {
_pend+=p;
}
return extract_path(_p, p, _pend);
}
private static boolean BASE(byte[] base) {
return DOSISH ?
(base.length > 0 && !((isdirsep(base[0]) && base.length < 2) || (base[1] == ':' && isdirsep(base[2]) && base.length < 4)))
:
(base.length > 0 && !(isdirsep(base[0]) && base.length < 2));
}
private static int glob_helper(String cwd, byte[] _path, int path, int plen, int sub, int flags, GlobFunc func, GlobArgs arg) {
int p,m;
int status = 0;
ByteList buf = new ByteList();
byte[] newpath = null;
File st;
List link = new ArrayList();
p = sub != -1 ? sub : path;
if(!has_magic(_path, p, -1, plen, flags)) {
if(DOSISH || (flags & FNM_NOESCAPE) == 0) {
newpath = new byte[plen];
System.arraycopy(_path,0,newpath,0,plen);
if(sub != -1) {
p = (sub - path);
plen = remove_backslashes(newpath, p, plen);
sub = p;
} else {
plen = remove_backslashes(newpath, 0, plen);
_path = newpath;
}
}
- if(_path[path] == '/') {
+ if(_path[path] == '/' || (DOSISH && path+2<plen && _path[path+1] == ':' && isdirsep(_path[path+2]))) {
if(new File(new String(_path, path, plen - path)).exists()) {
status = func.call(_path, path, plen, arg);
}
} else {
if(new File(cwd, new String(_path, path, plen - path)).exists()) {
status = func.call(_path, path, plen, arg);
}
}
return status;
}
mainLoop: while(p != -1 && status == 0) {
if(_path[p] == '/') {
p++;
}
m = strchr(_path, p, (byte)'/');
if(has_magic(_path, p, (m == -1 ? m : p+m), plen, flags)) {
finalize: do {
byte[] base = extract_path(_path, path, p);
byte[] dir;
byte[] magic;
boolean recursive = false;
if(path == p) {
dir = new byte[]{'.'};
} else {
dir = base;
}
magic = extract_elem(_path,p,plen);
- if(dir[0] == '/') {
+ if(dir[0] == '/' || (DOSISH && 2<dir.length && dir[1] == ':' && isdirsep(dir[2]))) {
st = new File(new String(dir));
} else {
st = new File(cwd, new String(dir));
}
if(!st.exists()) {
break mainLoop;
}
if(st.isDirectory()) {
if(m != -1 && Arrays.equals(magic, DOUBLE_STAR)) {
int n = base.length;
recursive = true;
buf.length(0);
buf.append(base);
buf.append(_path, p + (base.length > 0 ? m : m + 1), plen - (p + (base.length > 0 ? m : m + 1)));
status = glob_helper(cwd, buf.bytes, 0, buf.realSize, n, flags, func, arg);
if(status != 0) {
break finalize;
}
}
} else {
break mainLoop;
}
String[] dirp = st.list();
for(int i=0;i<dirp.length;i++) {
if(recursive) {
byte[] bs = dirp[i].getBytes();
if(fnmatch(STAR,0,1,bs,0,bs.length,flags) != 0) {
continue;
}
buf.length(0);
buf.append(base);
buf.append( BASE(base) ? SLASH : EMPTY );
buf.append(dirp[i].getBytes());
- if(buf.bytes[0] == '/') {
+ if(buf.bytes[0] == '/' || (DOSISH && 2<buf.realSize && buf.bytes[1] == ':' && isdirsep(buf.bytes[2]))) {
st = new File(new String(buf.bytes,0,buf.realSize));
} else {
st = new File(cwd, new String(buf.bytes,0,buf.realSize));
}
if(!st.exists()) {
continue;
}
if(st.isDirectory()) {
int t = buf.realSize;
buf.append(SLASH);
buf.append(DOUBLE_STAR);
buf.append(_path, p+m, plen-(p+m));
status = glob_helper(cwd, buf.bytes, 0, buf.realSize, t, flags, func, arg);
if(status != 0) {
break;
}
}
continue;
}
byte[] bs = dirp[i].getBytes();
if(fnmatch(magic,0,magic.length,bs,0,bs.length,flags) == 0) {
buf.length(0);
buf.append(base);
buf.append( BASE(base) ? SLASH : EMPTY );
buf.append(dirp[i].getBytes());
if(m == -1) {
status = func.call(buf.bytes,0,buf.realSize,arg);
if(status != 0) {
break;
}
continue;
}
link.add(buf);
buf = new ByteList();
}
}
} while(false);
if(link.size() > 0) {
for(Iterator iter = link.iterator();iter.hasNext();) {
if(status == 0) {
ByteList b = (ByteList)iter.next();
- if(b.bytes[0] == '/') {
+ if(b.bytes[0] == '/' || (DOSISH && 2<b.realSize && b.bytes[1] == ':' && isdirsep(b.bytes[2]))) {
st = new File(cwd, new String(b.bytes, 0, b.realSize));
} else {
st = new File(new String(b.bytes, 0, b.realSize));
}
if(st.exists() && st.isDirectory()) {
int len = b.realSize;
buf.length(0);
buf.append(b);
buf.append(_path, p+m, plen-(p+m));
status = glob_helper(cwd,buf.bytes,0,buf.realSize,len,flags,func,arg);
}
}
}
break mainLoop;
}
}
p = (m == -1 ? m : p+m);
}
return status;
}
public static void main(String[] args) throws Exception {
String PATTERN = "*/**/*{.rb,.so,.jar}";
String CWD = new java.io.File(".").getAbsolutePath();
byte[] pt = PATTERN.getBytes("ISO8859-1");
long before = System.currentTimeMillis();
for(int i=0;i<5 ;i++) {
push_glob(CWD, pt, 0, pt.length, 0);
}
long after = System.currentTimeMillis();
System.err.println("10 Globs took " + (after-before) + " millis");
}
}// Dir
| false | true | private static int glob_helper(String cwd, byte[] _path, int path, int plen, int sub, int flags, GlobFunc func, GlobArgs arg) {
int p,m;
int status = 0;
ByteList buf = new ByteList();
byte[] newpath = null;
File st;
List link = new ArrayList();
p = sub != -1 ? sub : path;
if(!has_magic(_path, p, -1, plen, flags)) {
if(DOSISH || (flags & FNM_NOESCAPE) == 0) {
newpath = new byte[plen];
System.arraycopy(_path,0,newpath,0,plen);
if(sub != -1) {
p = (sub - path);
plen = remove_backslashes(newpath, p, plen);
sub = p;
} else {
plen = remove_backslashes(newpath, 0, plen);
_path = newpath;
}
}
if(_path[path] == '/') {
if(new File(new String(_path, path, plen - path)).exists()) {
status = func.call(_path, path, plen, arg);
}
} else {
if(new File(cwd, new String(_path, path, plen - path)).exists()) {
status = func.call(_path, path, plen, arg);
}
}
return status;
}
mainLoop: while(p != -1 && status == 0) {
if(_path[p] == '/') {
p++;
}
m = strchr(_path, p, (byte)'/');
if(has_magic(_path, p, (m == -1 ? m : p+m), plen, flags)) {
finalize: do {
byte[] base = extract_path(_path, path, p);
byte[] dir;
byte[] magic;
boolean recursive = false;
if(path == p) {
dir = new byte[]{'.'};
} else {
dir = base;
}
magic = extract_elem(_path,p,plen);
if(dir[0] == '/') {
st = new File(new String(dir));
} else {
st = new File(cwd, new String(dir));
}
if(!st.exists()) {
break mainLoop;
}
if(st.isDirectory()) {
if(m != -1 && Arrays.equals(magic, DOUBLE_STAR)) {
int n = base.length;
recursive = true;
buf.length(0);
buf.append(base);
buf.append(_path, p + (base.length > 0 ? m : m + 1), plen - (p + (base.length > 0 ? m : m + 1)));
status = glob_helper(cwd, buf.bytes, 0, buf.realSize, n, flags, func, arg);
if(status != 0) {
break finalize;
}
}
} else {
break mainLoop;
}
String[] dirp = st.list();
for(int i=0;i<dirp.length;i++) {
if(recursive) {
byte[] bs = dirp[i].getBytes();
if(fnmatch(STAR,0,1,bs,0,bs.length,flags) != 0) {
continue;
}
buf.length(0);
buf.append(base);
buf.append( BASE(base) ? SLASH : EMPTY );
buf.append(dirp[i].getBytes());
if(buf.bytes[0] == '/') {
st = new File(new String(buf.bytes,0,buf.realSize));
} else {
st = new File(cwd, new String(buf.bytes,0,buf.realSize));
}
if(!st.exists()) {
continue;
}
if(st.isDirectory()) {
int t = buf.realSize;
buf.append(SLASH);
buf.append(DOUBLE_STAR);
buf.append(_path, p+m, plen-(p+m));
status = glob_helper(cwd, buf.bytes, 0, buf.realSize, t, flags, func, arg);
if(status != 0) {
break;
}
}
continue;
}
byte[] bs = dirp[i].getBytes();
if(fnmatch(magic,0,magic.length,bs,0,bs.length,flags) == 0) {
buf.length(0);
buf.append(base);
buf.append( BASE(base) ? SLASH : EMPTY );
buf.append(dirp[i].getBytes());
if(m == -1) {
status = func.call(buf.bytes,0,buf.realSize,arg);
if(status != 0) {
break;
}
continue;
}
link.add(buf);
buf = new ByteList();
}
}
} while(false);
if(link.size() > 0) {
for(Iterator iter = link.iterator();iter.hasNext();) {
if(status == 0) {
ByteList b = (ByteList)iter.next();
if(b.bytes[0] == '/') {
st = new File(cwd, new String(b.bytes, 0, b.realSize));
} else {
st = new File(new String(b.bytes, 0, b.realSize));
}
if(st.exists() && st.isDirectory()) {
int len = b.realSize;
buf.length(0);
buf.append(b);
buf.append(_path, p+m, plen-(p+m));
status = glob_helper(cwd,buf.bytes,0,buf.realSize,len,flags,func,arg);
}
}
}
break mainLoop;
}
}
p = (m == -1 ? m : p+m);
}
return status;
}
| private static int glob_helper(String cwd, byte[] _path, int path, int plen, int sub, int flags, GlobFunc func, GlobArgs arg) {
int p,m;
int status = 0;
ByteList buf = new ByteList();
byte[] newpath = null;
File st;
List link = new ArrayList();
p = sub != -1 ? sub : path;
if(!has_magic(_path, p, -1, plen, flags)) {
if(DOSISH || (flags & FNM_NOESCAPE) == 0) {
newpath = new byte[plen];
System.arraycopy(_path,0,newpath,0,plen);
if(sub != -1) {
p = (sub - path);
plen = remove_backslashes(newpath, p, plen);
sub = p;
} else {
plen = remove_backslashes(newpath, 0, plen);
_path = newpath;
}
}
if(_path[path] == '/' || (DOSISH && path+2<plen && _path[path+1] == ':' && isdirsep(_path[path+2]))) {
if(new File(new String(_path, path, plen - path)).exists()) {
status = func.call(_path, path, plen, arg);
}
} else {
if(new File(cwd, new String(_path, path, plen - path)).exists()) {
status = func.call(_path, path, plen, arg);
}
}
return status;
}
mainLoop: while(p != -1 && status == 0) {
if(_path[p] == '/') {
p++;
}
m = strchr(_path, p, (byte)'/');
if(has_magic(_path, p, (m == -1 ? m : p+m), plen, flags)) {
finalize: do {
byte[] base = extract_path(_path, path, p);
byte[] dir;
byte[] magic;
boolean recursive = false;
if(path == p) {
dir = new byte[]{'.'};
} else {
dir = base;
}
magic = extract_elem(_path,p,plen);
if(dir[0] == '/' || (DOSISH && 2<dir.length && dir[1] == ':' && isdirsep(dir[2]))) {
st = new File(new String(dir));
} else {
st = new File(cwd, new String(dir));
}
if(!st.exists()) {
break mainLoop;
}
if(st.isDirectory()) {
if(m != -1 && Arrays.equals(magic, DOUBLE_STAR)) {
int n = base.length;
recursive = true;
buf.length(0);
buf.append(base);
buf.append(_path, p + (base.length > 0 ? m : m + 1), plen - (p + (base.length > 0 ? m : m + 1)));
status = glob_helper(cwd, buf.bytes, 0, buf.realSize, n, flags, func, arg);
if(status != 0) {
break finalize;
}
}
} else {
break mainLoop;
}
String[] dirp = st.list();
for(int i=0;i<dirp.length;i++) {
if(recursive) {
byte[] bs = dirp[i].getBytes();
if(fnmatch(STAR,0,1,bs,0,bs.length,flags) != 0) {
continue;
}
buf.length(0);
buf.append(base);
buf.append( BASE(base) ? SLASH : EMPTY );
buf.append(dirp[i].getBytes());
if(buf.bytes[0] == '/' || (DOSISH && 2<buf.realSize && buf.bytes[1] == ':' && isdirsep(buf.bytes[2]))) {
st = new File(new String(buf.bytes,0,buf.realSize));
} else {
st = new File(cwd, new String(buf.bytes,0,buf.realSize));
}
if(!st.exists()) {
continue;
}
if(st.isDirectory()) {
int t = buf.realSize;
buf.append(SLASH);
buf.append(DOUBLE_STAR);
buf.append(_path, p+m, plen-(p+m));
status = glob_helper(cwd, buf.bytes, 0, buf.realSize, t, flags, func, arg);
if(status != 0) {
break;
}
}
continue;
}
byte[] bs = dirp[i].getBytes();
if(fnmatch(magic,0,magic.length,bs,0,bs.length,flags) == 0) {
buf.length(0);
buf.append(base);
buf.append( BASE(base) ? SLASH : EMPTY );
buf.append(dirp[i].getBytes());
if(m == -1) {
status = func.call(buf.bytes,0,buf.realSize,arg);
if(status != 0) {
break;
}
continue;
}
link.add(buf);
buf = new ByteList();
}
}
} while(false);
if(link.size() > 0) {
for(Iterator iter = link.iterator();iter.hasNext();) {
if(status == 0) {
ByteList b = (ByteList)iter.next();
if(b.bytes[0] == '/' || (DOSISH && 2<b.realSize && b.bytes[1] == ':' && isdirsep(b.bytes[2]))) {
st = new File(cwd, new String(b.bytes, 0, b.realSize));
} else {
st = new File(new String(b.bytes, 0, b.realSize));
}
if(st.exists() && st.isDirectory()) {
int len = b.realSize;
buf.length(0);
buf.append(b);
buf.append(_path, p+m, plen-(p+m));
status = glob_helper(cwd,buf.bytes,0,buf.realSize,len,flags,func,arg);
}
}
}
break mainLoop;
}
}
p = (m == -1 ? m : p+m);
}
return status;
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/GameLauncher.java b/src/main/java/org/spoutcraft/launcher/GameLauncher.java
index e2d50b3..3fa34fb 100644
--- a/src/main/java/org/spoutcraft/launcher/GameLauncher.java
+++ b/src/main/java/org/spoutcraft/launcher/GameLauncher.java
@@ -1,207 +1,208 @@
/*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/>
* Spoutcraft is licensed under the Spout License Version 1.
*
* Spoutcraft is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the Spout License Version 1.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the Spout License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spoutcraft.launcher;
import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.spoutcraft.launcher.api.Event;
import org.spoutcraft.launcher.api.Launcher;
import org.spoutcraft.launcher.entrypoint.SpoutcraftLauncher;
import org.spoutcraft.launcher.exceptions.CorruptedMinecraftJarException;
import org.spoutcraft.launcher.exceptions.MinecraftVerifyException;
import org.spoutcraft.launcher.launch.MinecraftLauncher;
import org.spoutcraft.launcher.skin.components.LoginFrame;
import org.spoutcraft.launcher.technic.Modpack;
import org.spoutcraft.launcher.util.Utils;
public class GameLauncher extends JFrame implements WindowListener {
private static final long serialVersionUID = 1L;
private net.minecraft.Launcher minecraft;
public static final int RETRYING_LAUNCH = -1;
public static final int ERROR_IN_LAUNCH = 0;
public static final int SUCCESSFUL_LAUNCH = 1;
public GameLauncher() {
super("Spoutcraft");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.addWindowListener(this);
setIconImage(Toolkit.getDefaultToolkit().getImage(LoginFrame.spoutcraftIcon));
}
public void runGame(String user, String session, String downloadTicket) {
runGame(user, session, downloadTicket, null);
}
public void runGame(String user, String session, String downloadTicket, Modpack modpack) {
if (modpack != null) {
System.out.println(modpack.getDisplayName());
System.out.println(modpack.getName());
this.setTitle(modpack.getDisplayName());
File icon = new File(Utils.getAssetsDirectory(), modpack.getName() + File.separator + "icon.png");
if (icon.exists()) {
this.setIconImage(Toolkit.getDefaultToolkit().createImage(icon.getAbsolutePath()));
}
}
Dimension size = WindowMode.getModeById(Settings.getWindowModeId()).getDimension(this);
Point centeredLoc = WindowMode.getModeById(Settings.getWindowModeId()).getCenteredLocation(Launcher.getLoginFrame());
this.setLocation(centeredLoc);
this.setSize(size);
Launcher.getGameUpdater().setWaiting(true);
while (!Launcher.getGameUpdater().isFinished()) {
try {
Thread.sleep(100);
}
catch (InterruptedException ignore) { }
}
Applet applet = null;
try {
applet = MinecraftLauncher.getMinecraftApplet(Launcher.getGameUpdater().getBuild().getLibraries());
} catch (CorruptedMinecraftJarException corruption) {
corruption.printStackTrace();
} catch (MinecraftVerifyException verify) {
Launcher.clearCache();
JOptionPane.showMessageDialog(getParent(), "Your Minecraft installation is corrupt, but has been cleaned. \nTry to login again.\n\n If that fails, close and restart the appplication.");
this.setVisible(false);
this.dispose();
Launcher.getLoginFrame().enableForm();
return;
}
if (applet == null) {
String message = "Failed to launch Spoutcraft!";
this.setVisible(false);
JOptionPane.showMessageDialog(getParent(), message);
this.dispose();
Launcher.getLoginFrame().enableForm();
return;
}
StartupParameters params = Utils.getStartupParameters();
minecraft = new net.minecraft.Launcher(applet);
minecraft.addParameter("username", user);
minecraft.addParameter("sessionid", session);
minecraft.addParameter("downloadticket", downloadTicket);
minecraft.addParameter("spoutcraftlauncher", "true");
minecraft.addParameter("portable", params.isPortable() + "");
+ minecraft.addParameter("stand-alone", "true");
if (params.getServer() != null) {
minecraft.addParameter("server", params.getServer());
if (params.getPort() != null) {
minecraft.addParameter("port", params.getPort());
} else {
minecraft.addParameter("port", "25565");
}
} else if (Settings.getDirectJoin() != null && Settings.getDirectJoin().length() > 0) {
String address = Settings.getDirectJoin();
String port = "25565";
if (address.contains(":")) {
String[] s = address.split(":");
address = s[0];
port = s[1];
}
minecraft.addParameter("server", address);
minecraft.addParameter("port", port);
}
if (params.getProxyHost() != null) {
minecraft.addParameter("proxy_host", params.getProxyHost());
}
if (params.getProxyPort() != null) {
minecraft.addParameter("proxy_port", params.getProxyPort());
}
if (params.getProxyUser() != null) {
minecraft.addParameter("proxy_user", params.getProxyUser());
}
if (params.getProxyPassword() != null) {
minecraft.addParameter("proxy_pass", params.getProxyPassword());
}
//minecraft.addParameter("fullscreen", WindowMode.getModeById(Settings.getWindowModeId()) == WindowMode.FULL_SCREEN ? "true" : "false");
applet.setStub(minecraft);
this.add(minecraft);
validate();
this.setVisible(true);
minecraft.init();
minecraft.setSize(getWidth(), getHeight());
minecraft.start();
Launcher.getLoginFrame().onEvent(Event.GAME_LAUNCH);
return;
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
SpoutcraftLauncher.destroyConsole();
if (this.minecraft != null) {
this.minecraft.stop();
this.minecraft.destroy();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) { }
}
System.out.println("Exiting Spoutcraft");
this.dispose();
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
}
| true | true | public void runGame(String user, String session, String downloadTicket, Modpack modpack) {
if (modpack != null) {
System.out.println(modpack.getDisplayName());
System.out.println(modpack.getName());
this.setTitle(modpack.getDisplayName());
File icon = new File(Utils.getAssetsDirectory(), modpack.getName() + File.separator + "icon.png");
if (icon.exists()) {
this.setIconImage(Toolkit.getDefaultToolkit().createImage(icon.getAbsolutePath()));
}
}
Dimension size = WindowMode.getModeById(Settings.getWindowModeId()).getDimension(this);
Point centeredLoc = WindowMode.getModeById(Settings.getWindowModeId()).getCenteredLocation(Launcher.getLoginFrame());
this.setLocation(centeredLoc);
this.setSize(size);
Launcher.getGameUpdater().setWaiting(true);
while (!Launcher.getGameUpdater().isFinished()) {
try {
Thread.sleep(100);
}
catch (InterruptedException ignore) { }
}
Applet applet = null;
try {
applet = MinecraftLauncher.getMinecraftApplet(Launcher.getGameUpdater().getBuild().getLibraries());
} catch (CorruptedMinecraftJarException corruption) {
corruption.printStackTrace();
} catch (MinecraftVerifyException verify) {
Launcher.clearCache();
JOptionPane.showMessageDialog(getParent(), "Your Minecraft installation is corrupt, but has been cleaned. \nTry to login again.\n\n If that fails, close and restart the appplication.");
this.setVisible(false);
this.dispose();
Launcher.getLoginFrame().enableForm();
return;
}
if (applet == null) {
String message = "Failed to launch Spoutcraft!";
this.setVisible(false);
JOptionPane.showMessageDialog(getParent(), message);
this.dispose();
Launcher.getLoginFrame().enableForm();
return;
}
StartupParameters params = Utils.getStartupParameters();
minecraft = new net.minecraft.Launcher(applet);
minecraft.addParameter("username", user);
minecraft.addParameter("sessionid", session);
minecraft.addParameter("downloadticket", downloadTicket);
minecraft.addParameter("spoutcraftlauncher", "true");
minecraft.addParameter("portable", params.isPortable() + "");
if (params.getServer() != null) {
minecraft.addParameter("server", params.getServer());
if (params.getPort() != null) {
minecraft.addParameter("port", params.getPort());
} else {
minecraft.addParameter("port", "25565");
}
} else if (Settings.getDirectJoin() != null && Settings.getDirectJoin().length() > 0) {
String address = Settings.getDirectJoin();
String port = "25565";
if (address.contains(":")) {
String[] s = address.split(":");
address = s[0];
port = s[1];
}
minecraft.addParameter("server", address);
minecraft.addParameter("port", port);
}
if (params.getProxyHost() != null) {
minecraft.addParameter("proxy_host", params.getProxyHost());
}
if (params.getProxyPort() != null) {
minecraft.addParameter("proxy_port", params.getProxyPort());
}
if (params.getProxyUser() != null) {
minecraft.addParameter("proxy_user", params.getProxyUser());
}
if (params.getProxyPassword() != null) {
minecraft.addParameter("proxy_pass", params.getProxyPassword());
}
//minecraft.addParameter("fullscreen", WindowMode.getModeById(Settings.getWindowModeId()) == WindowMode.FULL_SCREEN ? "true" : "false");
applet.setStub(minecraft);
this.add(minecraft);
validate();
this.setVisible(true);
minecraft.init();
minecraft.setSize(getWidth(), getHeight());
minecraft.start();
Launcher.getLoginFrame().onEvent(Event.GAME_LAUNCH);
return;
}
| public void runGame(String user, String session, String downloadTicket, Modpack modpack) {
if (modpack != null) {
System.out.println(modpack.getDisplayName());
System.out.println(modpack.getName());
this.setTitle(modpack.getDisplayName());
File icon = new File(Utils.getAssetsDirectory(), modpack.getName() + File.separator + "icon.png");
if (icon.exists()) {
this.setIconImage(Toolkit.getDefaultToolkit().createImage(icon.getAbsolutePath()));
}
}
Dimension size = WindowMode.getModeById(Settings.getWindowModeId()).getDimension(this);
Point centeredLoc = WindowMode.getModeById(Settings.getWindowModeId()).getCenteredLocation(Launcher.getLoginFrame());
this.setLocation(centeredLoc);
this.setSize(size);
Launcher.getGameUpdater().setWaiting(true);
while (!Launcher.getGameUpdater().isFinished()) {
try {
Thread.sleep(100);
}
catch (InterruptedException ignore) { }
}
Applet applet = null;
try {
applet = MinecraftLauncher.getMinecraftApplet(Launcher.getGameUpdater().getBuild().getLibraries());
} catch (CorruptedMinecraftJarException corruption) {
corruption.printStackTrace();
} catch (MinecraftVerifyException verify) {
Launcher.clearCache();
JOptionPane.showMessageDialog(getParent(), "Your Minecraft installation is corrupt, but has been cleaned. \nTry to login again.\n\n If that fails, close and restart the appplication.");
this.setVisible(false);
this.dispose();
Launcher.getLoginFrame().enableForm();
return;
}
if (applet == null) {
String message = "Failed to launch Spoutcraft!";
this.setVisible(false);
JOptionPane.showMessageDialog(getParent(), message);
this.dispose();
Launcher.getLoginFrame().enableForm();
return;
}
StartupParameters params = Utils.getStartupParameters();
minecraft = new net.minecraft.Launcher(applet);
minecraft.addParameter("username", user);
minecraft.addParameter("sessionid", session);
minecraft.addParameter("downloadticket", downloadTicket);
minecraft.addParameter("spoutcraftlauncher", "true");
minecraft.addParameter("portable", params.isPortable() + "");
minecraft.addParameter("stand-alone", "true");
if (params.getServer() != null) {
minecraft.addParameter("server", params.getServer());
if (params.getPort() != null) {
minecraft.addParameter("port", params.getPort());
} else {
minecraft.addParameter("port", "25565");
}
} else if (Settings.getDirectJoin() != null && Settings.getDirectJoin().length() > 0) {
String address = Settings.getDirectJoin();
String port = "25565";
if (address.contains(":")) {
String[] s = address.split(":");
address = s[0];
port = s[1];
}
minecraft.addParameter("server", address);
minecraft.addParameter("port", port);
}
if (params.getProxyHost() != null) {
minecraft.addParameter("proxy_host", params.getProxyHost());
}
if (params.getProxyPort() != null) {
minecraft.addParameter("proxy_port", params.getProxyPort());
}
if (params.getProxyUser() != null) {
minecraft.addParameter("proxy_user", params.getProxyUser());
}
if (params.getProxyPassword() != null) {
minecraft.addParameter("proxy_pass", params.getProxyPassword());
}
//minecraft.addParameter("fullscreen", WindowMode.getModeById(Settings.getWindowModeId()) == WindowMode.FULL_SCREEN ? "true" : "false");
applet.setStub(minecraft);
this.add(minecraft);
validate();
this.setVisible(true);
minecraft.init();
minecraft.setSize(getWidth(), getHeight());
minecraft.start();
Launcher.getLoginFrame().onEvent(Event.GAME_LAUNCH);
return;
}
|
diff --git a/org.maven.ide.eclipse/src/org/maven/ide/eclipse/archetype/ArchetypeCatalogsWriter.java b/org.maven.ide.eclipse/src/org/maven/ide/eclipse/archetype/ArchetypeCatalogsWriter.java
index bb73149e..d7ea4ed8 100644
--- a/org.maven.ide.eclipse/src/org/maven/ide/eclipse/archetype/ArchetypeCatalogsWriter.java
+++ b/org.maven.ide.eclipse/src/org/maven/ide/eclipse/archetype/ArchetypeCatalogsWriter.java
@@ -1,159 +1,161 @@
/*******************************************************************************
* Copyright (c) 2008 Sonatype, Inc.
* 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.maven.ide.eclipse.archetype;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLFilterImpl;
import org.maven.ide.eclipse.archetype.ArchetypeCatalogFactory.LocalCatalogFactory;
import org.maven.ide.eclipse.archetype.ArchetypeCatalogFactory.RemoteCatalogFactory;
import org.maven.ide.eclipse.core.MavenLogger;
/**
* Archetype catalogs writer
*
* @author Eugene Kuleshov
*/
public class ArchetypeCatalogsWriter {
private static final String ELEMENT_CATALOGS = "archetypeCatalogs";
private static final String ELEMENT_CATALOG = "catalog";
private static final String ATT_CATALOG_TYPE = "type";
private static final String ATT_CATALOG_LOCATION = "location";
public static final String ATT_CATALOG_DESCRIPTION = "description";
private static final String TYPE_LOCAL = "local";
private static final String TYPE_REMOTE = "remote";
public Collection<ArchetypeCatalogFactory> readArchetypeCatalogs(InputStream is) throws IOException {
Collection<ArchetypeCatalogFactory> catalogs = new ArrayList<ArchetypeCatalogFactory>();
try {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
parser.parse(is, new ArchetypeCatalogsContentHandler(catalogs));
} catch(SAXException ex) {
String msg = "Unable to parse Archetype catalogs list";
MavenLogger.log(msg, ex);
throw new IOException(msg + "; " + ex.getMessage());
} catch(ParserConfigurationException ex) {
String msg = "Unable to parse Archetype catalogs list";
MavenLogger.log(msg, ex);
throw new IOException(msg + "; " + ex.getMessage());
}
return catalogs;
}
public void writeArchetypeCatalogs(final Collection<ArchetypeCatalogFactory> catalogs, OutputStream os) throws IOException {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new SAXSource(new XMLArchetypeCatalogsWriter(catalogs), new InputSource()), new StreamResult(os));
} catch(TransformerFactoryConfigurationError ex) {
throw new IOException("Unable to write Archetype catalogs; " + ex.getMessage());
} catch(TransformerException ex) {
throw new IOException("Unable to write Archetype catalogs; " + ex.getMessage());
}
}
static class XMLArchetypeCatalogsWriter extends XMLFilterImpl {
private final Collection<ArchetypeCatalogFactory> catalogs;
public XMLArchetypeCatalogsWriter(Collection<ArchetypeCatalogFactory> catalogs) {
this.catalogs = catalogs;
}
public void parse(InputSource input) throws SAXException {
ContentHandler handler = getContentHandler();
handler.startDocument();
handler.startElement(null, ELEMENT_CATALOGS, ELEMENT_CATALOGS, new AttributesImpl());
for(ArchetypeCatalogFactory factory : this.catalogs) {
if(factory.isEditable()) {
if(factory instanceof LocalCatalogFactory) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(null, ATT_CATALOG_TYPE, ATT_CATALOG_TYPE, null, TYPE_LOCAL);
attrs.addAttribute(null, ATT_CATALOG_LOCATION, ATT_CATALOG_LOCATION, null, factory.getId());
+ attrs.addAttribute(null, ATT_CATALOG_DESCRIPTION, ATT_CATALOG_DESCRIPTION, null, factory.getDescription());
handler.startElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG, attrs);
handler.endElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG);
} else if(factory instanceof RemoteCatalogFactory) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(null, ATT_CATALOG_TYPE, ATT_CATALOG_TYPE, null, TYPE_REMOTE);
attrs.addAttribute(null, ATT_CATALOG_LOCATION, ATT_CATALOG_LOCATION, null, factory.getId());
+ attrs.addAttribute(null, ATT_CATALOG_DESCRIPTION, ATT_CATALOG_DESCRIPTION, null, factory.getDescription());
handler.startElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG, attrs);
handler.endElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG);
}
}
}
handler.endElement(null, ELEMENT_CATALOGS, ELEMENT_CATALOGS);
handler.endDocument();
}
}
static class ArchetypeCatalogsContentHandler extends DefaultHandler {
private Collection<ArchetypeCatalogFactory> catalogs;
public ArchetypeCatalogsContentHandler(Collection<ArchetypeCatalogFactory> catalogs) {
this.catalogs = catalogs;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if(ELEMENT_CATALOG.equals(qName) && attributes != null) {
String type = attributes.getValue(ATT_CATALOG_TYPE);
if(TYPE_LOCAL.equals(type)) {
String path = attributes.getValue(ATT_CATALOG_LOCATION);
if(path!=null) {
String description = attributes.getValue(ATT_CATALOG_DESCRIPTION);
catalogs.add(new LocalCatalogFactory(path, description, true));
}
} else if(TYPE_REMOTE.equals(type)) {
String url = attributes.getValue(ATT_CATALOG_LOCATION);
if(url!=null) {
String description = attributes.getValue(ATT_CATALOG_DESCRIPTION);
catalogs.add(new RemoteCatalogFactory(url, description, true));
}
}
}
}
}
}
| false | true | public void parse(InputSource input) throws SAXException {
ContentHandler handler = getContentHandler();
handler.startDocument();
handler.startElement(null, ELEMENT_CATALOGS, ELEMENT_CATALOGS, new AttributesImpl());
for(ArchetypeCatalogFactory factory : this.catalogs) {
if(factory.isEditable()) {
if(factory instanceof LocalCatalogFactory) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(null, ATT_CATALOG_TYPE, ATT_CATALOG_TYPE, null, TYPE_LOCAL);
attrs.addAttribute(null, ATT_CATALOG_LOCATION, ATT_CATALOG_LOCATION, null, factory.getId());
handler.startElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG, attrs);
handler.endElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG);
} else if(factory instanceof RemoteCatalogFactory) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(null, ATT_CATALOG_TYPE, ATT_CATALOG_TYPE, null, TYPE_REMOTE);
attrs.addAttribute(null, ATT_CATALOG_LOCATION, ATT_CATALOG_LOCATION, null, factory.getId());
handler.startElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG, attrs);
handler.endElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG);
}
}
}
handler.endElement(null, ELEMENT_CATALOGS, ELEMENT_CATALOGS);
handler.endDocument();
}
| public void parse(InputSource input) throws SAXException {
ContentHandler handler = getContentHandler();
handler.startDocument();
handler.startElement(null, ELEMENT_CATALOGS, ELEMENT_CATALOGS, new AttributesImpl());
for(ArchetypeCatalogFactory factory : this.catalogs) {
if(factory.isEditable()) {
if(factory instanceof LocalCatalogFactory) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(null, ATT_CATALOG_TYPE, ATT_CATALOG_TYPE, null, TYPE_LOCAL);
attrs.addAttribute(null, ATT_CATALOG_LOCATION, ATT_CATALOG_LOCATION, null, factory.getId());
attrs.addAttribute(null, ATT_CATALOG_DESCRIPTION, ATT_CATALOG_DESCRIPTION, null, factory.getDescription());
handler.startElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG, attrs);
handler.endElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG);
} else if(factory instanceof RemoteCatalogFactory) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(null, ATT_CATALOG_TYPE, ATT_CATALOG_TYPE, null, TYPE_REMOTE);
attrs.addAttribute(null, ATT_CATALOG_LOCATION, ATT_CATALOG_LOCATION, null, factory.getId());
attrs.addAttribute(null, ATT_CATALOG_DESCRIPTION, ATT_CATALOG_DESCRIPTION, null, factory.getDescription());
handler.startElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG, attrs);
handler.endElement(null, ELEMENT_CATALOG, ELEMENT_CATALOG);
}
}
}
handler.endElement(null, ELEMENT_CATALOGS, ELEMENT_CATALOGS);
handler.endDocument();
}
|
diff --git a/src/test/java/org/atlasapi/beans/FullToSimpleModelTranslatorTest.java b/src/test/java/org/atlasapi/beans/FullToSimpleModelTranslatorTest.java
index 95d16997..c612ba68 100644
--- a/src/test/java/org/atlasapi/beans/FullToSimpleModelTranslatorTest.java
+++ b/src/test/java/org/atlasapi/beans/FullToSimpleModelTranslatorTest.java
@@ -1,145 +1,145 @@
package org.atlasapi.beans;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.util.Currency;
import java.util.List;
import java.util.Set;
import org.atlasapi.media.TransportSubType;
import org.atlasapi.media.TransportType;
import org.atlasapi.media.entity.Actor;
import org.atlasapi.media.entity.Countries;
import org.atlasapi.media.entity.CrewMember;
import org.atlasapi.media.entity.Encoding;
import org.atlasapi.media.entity.Episode;
import org.atlasapi.media.entity.Location;
import org.atlasapi.media.entity.Policy;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.media.entity.Restriction;
import org.atlasapi.media.entity.Version;
import org.atlasapi.media.entity.Policy.RevenueContract;
import org.atlasapi.media.entity.simple.ContentQueryResult;
import org.atlasapi.media.entity.simple.Item;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.metabroadcast.common.currency.Price;
import com.metabroadcast.common.media.MimeType;
import com.metabroadcast.common.servlet.StubHttpServletRequest;
import com.metabroadcast.common.servlet.StubHttpServletResponse;
@RunWith(JMock.class)
public class FullToSimpleModelTranslatorTest {
private final Mockery context = new Mockery();
private StubHttpServletRequest request;
private StubHttpServletResponse response;
@Before
public void setUp() throws Exception {
this.request = new StubHttpServletRequest();
this.response = new StubHttpServletResponse();
}
@Test
public void testTranslatesItemsInFullModel() throws Exception {
final AtlasModelWriter xmlOutputter = context.mock(AtlasModelWriter.class);
Set<Object> graph = Sets.newHashSet();
graph.add(new Episode());
context.checking(new Expectations() {{
one(xmlOutputter).writeTo(with(request), with(response), with(simpleGraph()));
}});
new FullToSimpleModelTranslator(xmlOutputter).writeTo(request, response, graph);
}
protected Matcher<Set<Object>> simpleGraph() {
return new TypeSafeMatcher<Set<Object>> () {
@Override
public boolean matchesSafely(Set<Object> beans) {
if (beans.size() != 1) { return false; }
Object bean = Iterables.getOnlyElement(beans);
if (!(bean instanceof ContentQueryResult)) { return false; }
ContentQueryResult output = (ContentQueryResult) bean;
if (output.getContents().size() != 1) { return false; }
return true;
}
public void describeTo(Description description) {
// TODO Auto-generated method stub
}};
}
public void testCanCreateSimpleItemFromFullItem() throws Exception {
org.atlasapi.media.entity.Item fullItem = new org.atlasapi.media.entity.Item();
Version version = new Version();
Restriction restriction = new Restriction();
restriction.setRestricted(true);
restriction.setMessage("adults only");
version.setRestriction(restriction);
Encoding encoding = new Encoding();
encoding.setDataContainerFormat(MimeType.VIDEO_3GPP);
version.addManifestedAs(encoding);
Location location = new Location();
location.setUri("http://example.com");
location.setPolicy(new Policy().withRevenueContract(RevenueContract.PAY_TO_BUY).withPrice(new Price(Currency.getInstance("GBP"), 99)).withAvailableCountries(Countries.GB));
Location embed = new Location();
embed.setTransportType(TransportType.EMBED);
embed.setEmbedId("embedId");
embed.setTransportSubType(TransportSubType.BRIGHTCOVE);
encoding.addAvailableAt(location);
encoding.addAvailableAt(embed);
fullItem.addVersion(version);
fullItem.setTitle("Collings and Herrin");
- CrewMember person = Actor.actor("Andrew Collings", "Dirt-bag Humperdink", Publisher.BBC);
+ CrewMember person = Actor.actor("hisID", "Andrew Collings", "Dirt-bag Humperdink", Publisher.BBC);
fullItem.addPerson(person);
Item simpleItem = FullToSimpleModelTranslator.simpleItemFrom(fullItem);
List<org.atlasapi.media.entity.simple.Person> people = simpleItem.getPeople();
org.atlasapi.media.entity.simple.Person simpleActor = Iterables.getOnlyElement(people);
assertThat(simpleActor.getCharacter(), is("Dirt-bag Humperdink"));
assertThat(simpleActor.getName(), is("Andrew Collings"));
Set<org.atlasapi.media.entity.simple.Location> simpleLocations = simpleItem.getLocations();
assertThat(simpleLocations.size(), is(2));
org.atlasapi.media.entity.simple.Location simpleLocation = Iterables.getFirst(simpleLocations, null);
assertThat(simpleLocation.getUri(), is("http://example.com"));
assertThat(simpleLocation.getDataContainerFormat(), is(MimeType.VIDEO_3GPP.toString()));
assertThat(simpleLocation.getRestriction().getMessage(), is("adults only"));
assertThat(simpleLocation.getRevenueContract(), is("pay_to_buy"));
assertThat(simpleLocation.getCurrency(), is("GBP"));
assertThat(simpleLocation.getPrice(), is(99));
assertThat(simpleLocation.getAvailableCountries().size(), is(1));
assertThat(simpleLocation.getAvailableCountries().iterator().next(), is("GB"));
org.atlasapi.media.entity.simple.Location simpleEmbed = Iterables.getLast(simpleLocations, null);
assertThat(simpleEmbed.getEmbedId(), is("embedId"));
assertThat(simpleEmbed.getTransportType(), is("embed"));
assertThat(simpleEmbed.getTransportSubType(), is("brightcove"));
assertThat(simpleItem.getTitle(), is("Collings and Herrin"));
}
}
| true | true | public void testCanCreateSimpleItemFromFullItem() throws Exception {
org.atlasapi.media.entity.Item fullItem = new org.atlasapi.media.entity.Item();
Version version = new Version();
Restriction restriction = new Restriction();
restriction.setRestricted(true);
restriction.setMessage("adults only");
version.setRestriction(restriction);
Encoding encoding = new Encoding();
encoding.setDataContainerFormat(MimeType.VIDEO_3GPP);
version.addManifestedAs(encoding);
Location location = new Location();
location.setUri("http://example.com");
location.setPolicy(new Policy().withRevenueContract(RevenueContract.PAY_TO_BUY).withPrice(new Price(Currency.getInstance("GBP"), 99)).withAvailableCountries(Countries.GB));
Location embed = new Location();
embed.setTransportType(TransportType.EMBED);
embed.setEmbedId("embedId");
embed.setTransportSubType(TransportSubType.BRIGHTCOVE);
encoding.addAvailableAt(location);
encoding.addAvailableAt(embed);
fullItem.addVersion(version);
fullItem.setTitle("Collings and Herrin");
CrewMember person = Actor.actor("Andrew Collings", "Dirt-bag Humperdink", Publisher.BBC);
fullItem.addPerson(person);
Item simpleItem = FullToSimpleModelTranslator.simpleItemFrom(fullItem);
List<org.atlasapi.media.entity.simple.Person> people = simpleItem.getPeople();
org.atlasapi.media.entity.simple.Person simpleActor = Iterables.getOnlyElement(people);
assertThat(simpleActor.getCharacter(), is("Dirt-bag Humperdink"));
assertThat(simpleActor.getName(), is("Andrew Collings"));
Set<org.atlasapi.media.entity.simple.Location> simpleLocations = simpleItem.getLocations();
assertThat(simpleLocations.size(), is(2));
org.atlasapi.media.entity.simple.Location simpleLocation = Iterables.getFirst(simpleLocations, null);
assertThat(simpleLocation.getUri(), is("http://example.com"));
assertThat(simpleLocation.getDataContainerFormat(), is(MimeType.VIDEO_3GPP.toString()));
assertThat(simpleLocation.getRestriction().getMessage(), is("adults only"));
assertThat(simpleLocation.getRevenueContract(), is("pay_to_buy"));
assertThat(simpleLocation.getCurrency(), is("GBP"));
assertThat(simpleLocation.getPrice(), is(99));
assertThat(simpleLocation.getAvailableCountries().size(), is(1));
assertThat(simpleLocation.getAvailableCountries().iterator().next(), is("GB"));
org.atlasapi.media.entity.simple.Location simpleEmbed = Iterables.getLast(simpleLocations, null);
assertThat(simpleEmbed.getEmbedId(), is("embedId"));
assertThat(simpleEmbed.getTransportType(), is("embed"));
assertThat(simpleEmbed.getTransportSubType(), is("brightcove"));
assertThat(simpleItem.getTitle(), is("Collings and Herrin"));
}
| public void testCanCreateSimpleItemFromFullItem() throws Exception {
org.atlasapi.media.entity.Item fullItem = new org.atlasapi.media.entity.Item();
Version version = new Version();
Restriction restriction = new Restriction();
restriction.setRestricted(true);
restriction.setMessage("adults only");
version.setRestriction(restriction);
Encoding encoding = new Encoding();
encoding.setDataContainerFormat(MimeType.VIDEO_3GPP);
version.addManifestedAs(encoding);
Location location = new Location();
location.setUri("http://example.com");
location.setPolicy(new Policy().withRevenueContract(RevenueContract.PAY_TO_BUY).withPrice(new Price(Currency.getInstance("GBP"), 99)).withAvailableCountries(Countries.GB));
Location embed = new Location();
embed.setTransportType(TransportType.EMBED);
embed.setEmbedId("embedId");
embed.setTransportSubType(TransportSubType.BRIGHTCOVE);
encoding.addAvailableAt(location);
encoding.addAvailableAt(embed);
fullItem.addVersion(version);
fullItem.setTitle("Collings and Herrin");
CrewMember person = Actor.actor("hisID", "Andrew Collings", "Dirt-bag Humperdink", Publisher.BBC);
fullItem.addPerson(person);
Item simpleItem = FullToSimpleModelTranslator.simpleItemFrom(fullItem);
List<org.atlasapi.media.entity.simple.Person> people = simpleItem.getPeople();
org.atlasapi.media.entity.simple.Person simpleActor = Iterables.getOnlyElement(people);
assertThat(simpleActor.getCharacter(), is("Dirt-bag Humperdink"));
assertThat(simpleActor.getName(), is("Andrew Collings"));
Set<org.atlasapi.media.entity.simple.Location> simpleLocations = simpleItem.getLocations();
assertThat(simpleLocations.size(), is(2));
org.atlasapi.media.entity.simple.Location simpleLocation = Iterables.getFirst(simpleLocations, null);
assertThat(simpleLocation.getUri(), is("http://example.com"));
assertThat(simpleLocation.getDataContainerFormat(), is(MimeType.VIDEO_3GPP.toString()));
assertThat(simpleLocation.getRestriction().getMessage(), is("adults only"));
assertThat(simpleLocation.getRevenueContract(), is("pay_to_buy"));
assertThat(simpleLocation.getCurrency(), is("GBP"));
assertThat(simpleLocation.getPrice(), is(99));
assertThat(simpleLocation.getAvailableCountries().size(), is(1));
assertThat(simpleLocation.getAvailableCountries().iterator().next(), is("GB"));
org.atlasapi.media.entity.simple.Location simpleEmbed = Iterables.getLast(simpleLocations, null);
assertThat(simpleEmbed.getEmbedId(), is("embedId"));
assertThat(simpleEmbed.getTransportType(), is("embed"));
assertThat(simpleEmbed.getTransportSubType(), is("brightcove"));
assertThat(simpleItem.getTitle(), is("Collings and Herrin"));
}
|
diff --git a/user/src/com/google/gwt/user/server/rpc/RPCServletUtils.java b/user/src/com/google/gwt/user/server/rpc/RPCServletUtils.java
index 63179bd9b..c020de981 100644
--- a/user/src/com/google/gwt/user/server/rpc/RPCServletUtils.java
+++ b/user/src/com/google/gwt/user/server/rpc/RPCServletUtils.java
@@ -1,257 +1,272 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.server.rpc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Utility class containing helper methods used by servlets that integrate with
* the RPC system.
*/
public class RPCServletUtils {
private static final String ACCEPT_ENCODING = "Accept-Encoding";
private static final String ATTACHMENT = "attachment";
private static final String CHARSET_UTF8 = "UTF-8";
private static final String CONTENT_DISPOSITION = "Content-Disposition";
private static final String CONTENT_ENCODING = "Content-Encoding";
private static final String CONTENT_ENCODING_GZIP = "gzip";
private static final String CONTENT_TYPE_APPLICATION_JSON_UTF8 = "application/json; charset=utf-8";
private static final String EXPECTED_CHARSET = "charset=utf-8";
private static final String EXPECTED_CONTENT_TYPE = "text/x-gwt-rpc";
private static final String GENERIC_FAILURE_MSG = "The call failed on the server; see server log for details";
/**
* Controls the compression threshold at and below which no compression will
* take place.
*/
private static final int UNCOMPRESSED_BYTE_SIZE_LIMIT = 256;
/**
* Returns <code>true</code> if the {@link HttpServletRequest} accepts Gzip
* encoding. This is done by checking that the accept-encoding header
* specifies gzip as a supported encoding.
*
* @param request the request instance to test for gzip encoding acceptance
* @return <code>true</code> if the {@link HttpServletRequest} accepts Gzip
* encoding
*/
public static boolean acceptsGzipEncoding(HttpServletRequest request) {
assert (request != null);
String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
if (null == acceptEncoding) {
return false;
}
return (acceptEncoding.indexOf(CONTENT_ENCODING_GZIP) != -1);
}
/**
* Returns <code>true</code> if the response content's estimated UTF-8 byte
* length exceeds 256 bytes.
*
* @param content the contents of the response
* @return <code>true</code> if the response content's estimated UTF-8 byte
* length exceeds 256 bytes
*/
public static boolean exceedsUncompressedContentLengthLimit(String content) {
return (content.length() * 2) > UNCOMPRESSED_BYTE_SIZE_LIMIT;
}
/**
* Returns the content of an {@link HttpServletRequest} by decoding it using
* the UTF-8 charset.
*
* @param request the servlet request whose content we want to read
* @return the content of an {@link HttpServletRequest} by decoding it using
* the UTF-8 charset
* @throws IOException if the requests input stream cannot be accessed, read
* from or closed
* @throws ServletException if the content length of the request is not
* specified of if the request's content type is not
* 'text/x-gwt-rpc' and 'charset=utf-8'
*/
public static String readContentAsUtf8(HttpServletRequest request)
throws IOException, ServletException {
int contentLength = request.getContentLength();
if (contentLength == -1) {
// Content length must be known.
throw new ServletException("Content-Length must be specified");
}
String contentType = request.getContentType();
boolean contentTypeIsOkay = false;
// Content-Type must be specified.
if (contentType != null) {
contentType = contentType.toLowerCase();
- // The type must be be distinct
+ /*
+ * The Content-Type must be text/x-gwt-rpc.
+ *
+ * NOTE:We use startsWith because some servlet engines, i.e. Tomcat, do
+ * not remove the charset component but others do.
+ */
if (contentType.startsWith(EXPECTED_CONTENT_TYPE)) {
- if (contentType.indexOf(EXPECTED_CHARSET) != -1) {
- contentTypeIsOkay = true;
+ String characterEncoding = request.getCharacterEncoding();
+ if (characterEncoding != null) {
+ /*
+ * TODO: It would seem that we should be able to use equalsIgnoreCase
+ * here instead of indexOf. Need to be sure that servlet engines
+ * return a properly parsed character encoding string if we decide to
+ * make this change.
+ */
+ if (characterEncoding.toLowerCase().indexOf(
+ CHARSET_UTF8.toLowerCase()) != -1) {
+ contentTypeIsOkay = true;
+ }
}
}
}
if (!contentTypeIsOkay) {
throw new ServletException("Content-Type must be '"
+ EXPECTED_CONTENT_TYPE + "' with '" + EXPECTED_CHARSET + "'.");
}
InputStream in = request.getInputStream();
try {
byte[] payload = new byte[contentLength];
int offset = 0;
int len = contentLength;
int byteCount;
while (offset < contentLength) {
byteCount = in.read(payload, offset, len);
if (byteCount == -1) {
throw new ServletException("Client did not send " + contentLength
+ " bytes as expected");
}
offset += byteCount;
len -= byteCount;
}
return new String(payload, CHARSET_UTF8);
} finally {
if (in != null) {
in.close();
}
}
}
/**
* Returns <code>true</code> if the request accepts gzip encoding and the
* the response content's estimated UTF-8 byte length exceeds 256 bytes.
*
* @param request the request associated with the response content
* @param responseContent a string that will be
* @return <code>true</code> if the request accepts gzip encoding and the
* the response content's estimated UTF-8 byte length exceeds 256
* bytes
*/
public static boolean shouldGzipResponseContent(HttpServletRequest request,
String responseContent) {
return acceptsGzipEncoding(request)
&& exceedsUncompressedContentLengthLimit(responseContent);
}
/**
* Write the response content into the {@link HttpServletResponse}. If
* <code>gzipResponse</code> is <code>true</code>, the response content
* will be gzipped prior to being written into the response.
*
* @param servletContext servlet context for this response
* @param response response instance
* @param responseContent a string containing the response content
* @param gzipResponse if <code>true</code> the response content will be
* gzip encoded before being written into the response
* @throws IOException if reading, writing, or closing the response's output
* stream fails
*/
public static void writeResponse(ServletContext servletContext,
HttpServletResponse response, String responseContent, boolean gzipResponse)
throws IOException {
byte[] responseBytes = responseContent.getBytes(CHARSET_UTF8);
if (gzipResponse) {
// Compress the reply and adjust headers.
//
ByteArrayOutputStream output = null;
GZIPOutputStream gzipOutputStream = null;
Throwable caught = null;
try {
output = new ByteArrayOutputStream(responseBytes.length);
gzipOutputStream = new GZIPOutputStream(output);
gzipOutputStream.write(responseBytes);
gzipOutputStream.finish();
gzipOutputStream.flush();
response.setHeader(CONTENT_ENCODING, CONTENT_ENCODING_GZIP);
responseBytes = output.toByteArray();
} catch (IOException e) {
caught = e;
} finally {
if (null != gzipOutputStream) {
gzipOutputStream.close();
}
if (null != output) {
output.close();
}
}
if (caught != null) {
servletContext.log("Unable to compress response", caught);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
// Send the reply.
//
response.setContentLength(responseBytes.length);
response.setContentType(CONTENT_TYPE_APPLICATION_JSON_UTF8);
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader(CONTENT_DISPOSITION, ATTACHMENT);
response.getOutputStream().write(responseBytes);
}
/**
* Called when the servlet itself has a problem, rather than the invoked
* third-party method. It writes a simple 500 message back to the client.
*
* @param servletContext
* @param response
* @param failure
*/
public static void writeResponseForUnexpectedFailure(
ServletContext servletContext, HttpServletResponse response,
Throwable failure) {
servletContext.log("Exception while dispatching incoming RPC call", failure);
// Send GENERIC_FAILURE_MSG with 500 status.
//
try {
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write(GENERIC_FAILURE_MSG);
} catch (IOException ex) {
servletContext.log(
"respondWithUnexpectedFailure failed while sending the previous failure to the client",
ex);
}
}
private RPCServletUtils() {
// Not instantiable
}
}
| false | true | public static String readContentAsUtf8(HttpServletRequest request)
throws IOException, ServletException {
int contentLength = request.getContentLength();
if (contentLength == -1) {
// Content length must be known.
throw new ServletException("Content-Length must be specified");
}
String contentType = request.getContentType();
boolean contentTypeIsOkay = false;
// Content-Type must be specified.
if (contentType != null) {
contentType = contentType.toLowerCase();
// The type must be be distinct
if (contentType.startsWith(EXPECTED_CONTENT_TYPE)) {
if (contentType.indexOf(EXPECTED_CHARSET) != -1) {
contentTypeIsOkay = true;
}
}
}
if (!contentTypeIsOkay) {
throw new ServletException("Content-Type must be '"
+ EXPECTED_CONTENT_TYPE + "' with '" + EXPECTED_CHARSET + "'.");
}
InputStream in = request.getInputStream();
try {
byte[] payload = new byte[contentLength];
int offset = 0;
int len = contentLength;
int byteCount;
while (offset < contentLength) {
byteCount = in.read(payload, offset, len);
if (byteCount == -1) {
throw new ServletException("Client did not send " + contentLength
+ " bytes as expected");
}
offset += byteCount;
len -= byteCount;
}
return new String(payload, CHARSET_UTF8);
} finally {
if (in != null) {
in.close();
}
}
}
| public static String readContentAsUtf8(HttpServletRequest request)
throws IOException, ServletException {
int contentLength = request.getContentLength();
if (contentLength == -1) {
// Content length must be known.
throw new ServletException("Content-Length must be specified");
}
String contentType = request.getContentType();
boolean contentTypeIsOkay = false;
// Content-Type must be specified.
if (contentType != null) {
contentType = contentType.toLowerCase();
/*
* The Content-Type must be text/x-gwt-rpc.
*
* NOTE:We use startsWith because some servlet engines, i.e. Tomcat, do
* not remove the charset component but others do.
*/
if (contentType.startsWith(EXPECTED_CONTENT_TYPE)) {
String characterEncoding = request.getCharacterEncoding();
if (characterEncoding != null) {
/*
* TODO: It would seem that we should be able to use equalsIgnoreCase
* here instead of indexOf. Need to be sure that servlet engines
* return a properly parsed character encoding string if we decide to
* make this change.
*/
if (characterEncoding.toLowerCase().indexOf(
CHARSET_UTF8.toLowerCase()) != -1) {
contentTypeIsOkay = true;
}
}
}
}
if (!contentTypeIsOkay) {
throw new ServletException("Content-Type must be '"
+ EXPECTED_CONTENT_TYPE + "' with '" + EXPECTED_CHARSET + "'.");
}
InputStream in = request.getInputStream();
try {
byte[] payload = new byte[contentLength];
int offset = 0;
int len = contentLength;
int byteCount;
while (offset < contentLength) {
byteCount = in.read(payload, offset, len);
if (byteCount == -1) {
throw new ServletException("Client did not send " + contentLength
+ " bytes as expected");
}
offset += byteCount;
len -= byteCount;
}
return new String(payload, CHARSET_UTF8);
} finally {
if (in != null) {
in.close();
}
}
}
|
diff --git a/src/au/gov/naa/digipres/xena/plugin/image/test/JpegGuesserTester.java b/src/au/gov/naa/digipres/xena/plugin/image/test/JpegGuesserTester.java
index b79c743c..2691856d 100644
--- a/src/au/gov/naa/digipres/xena/plugin/image/test/JpegGuesserTester.java
+++ b/src/au/gov/naa/digipres/xena/plugin/image/test/JpegGuesserTester.java
@@ -1,63 +1,63 @@
/*
* Created on 11/01/2006
* andrek24
*
*/
package au.gov.naa.digipres.xena.plugin.image.test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import au.gov.naa.digipres.xena.kernel.XenaException;
import au.gov.naa.digipres.xena.kernel.XenaInputSource;
import au.gov.naa.digipres.xena.kernel.guesser.Guess;
import au.gov.naa.digipres.xena.plugin.image.JpegGuesser;
public class JpegGuesserTester {
public static void main(String[] argv){
JpegGuesser guesser = new JpegGuesser();
XenaInputSource xis = null;
- List fileNameList = new ArrayList();
+ List<String> fileNameList = new ArrayList<String>();
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
for (Iterator iter = fileNameList.iterator(); iter.hasNext();) {
String fileName = (String) iter.next();
try {
xis = new XenaInputSource(new File(fileName));
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
try {
Guess guess = guesser.guess(xis);
System.out.println(guess.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (XenaException xe) {
xe.printStackTrace();
}
}
}
}
| true | true | public static void main(String[] argv){
JpegGuesser guesser = new JpegGuesser();
XenaInputSource xis = null;
List fileNameList = new ArrayList();
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
for (Iterator iter = fileNameList.iterator(); iter.hasNext();) {
String fileName = (String) iter.next();
try {
xis = new XenaInputSource(new File(fileName));
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
try {
Guess guess = guesser.guess(xis);
System.out.println(guess.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (XenaException xe) {
xe.printStackTrace();
}
}
}
| public static void main(String[] argv){
JpegGuesser guesser = new JpegGuesser();
XenaInputSource xis = null;
List<String> fileNameList = new ArrayList<String>();
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
fileNameList.add("d:\\test_data\\dino.jpg");
for (Iterator iter = fileNameList.iterator(); iter.hasNext();) {
String fileName = (String) iter.next();
try {
xis = new XenaInputSource(new File(fileName));
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
try {
Guess guess = guesser.guess(xis);
System.out.println(guess.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (XenaException xe) {
xe.printStackTrace();
}
}
}
|
diff --git a/xstream/src/java/com/thoughtworks/xstream/converters/collections/PropertiesConverter.java b/xstream/src/java/com/thoughtworks/xstream/converters/collections/PropertiesConverter.java
index 99657d5d..7ae71f29 100644
--- a/xstream/src/java/com/thoughtworks/xstream/converters/collections/PropertiesConverter.java
+++ b/xstream/src/java/com/thoughtworks/xstream/converters/collections/PropertiesConverter.java
@@ -1,91 +1,91 @@
/*
* Copyright (C) 2004, 2005 Joe Walnes.
* Copyright (C) 2006, 2007, 2008 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 23. February 2004 by Joe Walnes
*/
package com.thoughtworks.xstream.converters.collections;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.core.util.Fields;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
/**
* Special converter for java.util.Properties that stores
* properties in a more compact form than java.util.Map.
* <p/>
* <p>Because all entries of a Properties instance
* are Strings, a single element is used for each property
* with two attributes; one for key and one for value.</p>
* <p>Additionally, default properties are also serialized, if they are present.</p>
*
* @author Joe Walnes
* @author Kevin Ring
*/
public class PropertiesConverter implements Converter {
private final static Field defaultsField = Fields.find(Properties.class, "defaults");
private final boolean sort;
public PropertiesConverter() {
this(false);
}
public PropertiesConverter(boolean sort) {
this.sort = sort;
}
public boolean canConvert(Class type) {
return Properties.class == type;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Properties properties = (Properties) source;
- Map map = sort ? new TreeMap(properties) : properties;
+ Map map = sort ? (Map)new TreeMap(properties) : (Map)properties;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
writer.startNode("property");
writer.addAttribute("name", entry.getKey().toString());
writer.addAttribute("value", entry.getValue().toString());
writer.endNode();
}
Properties defaults = (Properties) Fields.read(defaultsField, properties);
if (defaults != null) {
writer.startNode("defaults");
marshal(defaults, writer, context);
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Properties properties = new Properties();
while (reader.hasMoreChildren()) {
reader.moveDown();
if (reader.getNodeName().equals("defaults")) {
Properties defaults = (Properties) unmarshal(reader, context);
Fields.write(defaultsField, properties, defaults);
} else {
String name = reader.getAttribute("name");
String value = reader.getAttribute("value");
properties.setProperty(name, value);
}
reader.moveUp();
}
return properties;
}
}
| true | true | public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Properties properties = (Properties) source;
Map map = sort ? new TreeMap(properties) : properties;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
writer.startNode("property");
writer.addAttribute("name", entry.getKey().toString());
writer.addAttribute("value", entry.getValue().toString());
writer.endNode();
}
Properties defaults = (Properties) Fields.read(defaultsField, properties);
if (defaults != null) {
writer.startNode("defaults");
marshal(defaults, writer, context);
writer.endNode();
}
}
| public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Properties properties = (Properties) source;
Map map = sort ? (Map)new TreeMap(properties) : (Map)properties;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
writer.startNode("property");
writer.addAttribute("name", entry.getKey().toString());
writer.addAttribute("value", entry.getValue().toString());
writer.endNode();
}
Properties defaults = (Properties) Fields.read(defaultsField, properties);
if (defaults != null) {
writer.startNode("defaults");
marshal(defaults, writer, context);
writer.endNode();
}
}
|
diff --git a/src/ise/gameoflife/participants/GroupDataModel.java b/src/ise/gameoflife/participants/GroupDataModel.java
index 4fa653a..3811664 100644
--- a/src/ise/gameoflife/participants/GroupDataModel.java
+++ b/src/ise/gameoflife/participants/GroupDataModel.java
@@ -1,257 +1,256 @@
package ise.gameoflife.participants;
import ise.gameoflife.environment.PublicEnvironmentConnection;
import ise.gameoflife.inputs.Proposition;
import ise.gameoflife.models.History;
import ise.gameoflife.models.UnmodifiableHistory;
import ise.gameoflife.models.GroupDataInitialiser;
import ise.gameoflife.models.ScaledDouble;
import ise.gameoflife.models.Tuple;
import ise.gameoflife.tokens.AgentType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.UUID;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import presage.abstractparticipant.APlayerDataModel;
/**
* Stub for groups
* @author Olly
*/
class GroupDataModel extends APlayerDataModel
{
private static final long serialVersionUID = 1L;
@Element
private String name;
/**
* Array list of GroupDataModel members
*/
@ElementList
private ArrayList<String> memberList;
@Element
private History<Double> economicPosition;
@Element
private History<HashMap<Proposition,Integer>> propositionHistory;
private AgentType groupStrategy;
private List<String> panel = new LinkedList<String>();
@Element
private History<Double> reservedFoodHistory;
@Deprecated
GroupDataModel()
{
super();
}
/**
* Create a new instance of the GroupDataModel, automatically generating a new
* UUID
* @param randomseed The random number seed to use with this class
* @return The new GroupDataModel
*/
@SuppressWarnings("AccessingNonPublicFieldOfAnotherObject")
public static GroupDataModel createNew(GroupDataInitialiser init)
{
GroupDataModel ret = new GroupDataModel();
ret.myId = UUID.randomUUID().toString();
ret.memberList = new ArrayList<String>();
ret.myrolesString = "<group>";
ret.randomseed = init.getRandomSeed();
ret.name = init.getName();
ret.economicPosition = new History<Double>(50);
ret.propositionHistory = new History<HashMap<Proposition, Integer>>(50);
ret.economicPosition.newEntry(init.getInitialEconomicBelief());
ret.reservedFoodHistory = new History<Double>(50);
ret.reservedFoodHistory.newEntry(0.0);
return ret;
}
/**
* Get the group id that this group has
* @return The UUID of this group
*/
@Override
public String getId()
{
return myId;
}
List<String> getMemberList()
{
return Collections.unmodifiableList(memberList);
}
double getCurrentEconomicPoisition()
{
return economicPosition.getValue();
}
void setEconomicPosition(double pos)
{
economicPosition.setValue(pos);
}
UnmodifiableHistory<Double> getEconomicPoisition()
{
return economicPosition.getUnmodifableHistory();
}
void clearRoundData()
{
economicPosition.newEntry(true);
propositionHistory.newEntry(null);
reservedFoodHistory.newEntry(true);
}
void addMember(String a)
{
memberList.add(a);
}
void removeMember(String a)
{
memberList.remove(a);
}
@Override
public void onInitialise()
{
// Nothing to see here. Move along, citizen!
}
/**
* Get a re-distribution safe copy of this object. The returned object is
* backed by this one, so their is no need to keep calling this to receive
* updated data.
* @return
*/
public PublicGroupDataModel getPublicVersion()
{
return new PublicGroupDataModel(this);
}
public String getName()
{
return name;
}
public Map<Proposition, Integer> getTurnsProposals()
{
if (propositionHistory.isEmpty()) return null;
HashMap<Proposition, Integer> d = propositionHistory.getValue();
if (d == null) return null;
return Collections.unmodifiableMap(d);
}
void setProposals(HashMap<Proposition, Integer> p)
{
propositionHistory.setValue(p);
}
double getEstimatedSocialLocation()
{
/*
* Algorithm:
* - The leaders are those people trust most
* - The social location is ratio(ish) of leaders to group members
* - This can be modelled as the the deviation of the trust values
* - If one agent is trusted more than others, high deviation
* - This represents an autocracy
* - The values used to find standard deviation will be the average of each
* agent's opinion of an agent
*/
List<Double> avg_trusts = new ArrayList<Double>(memberList.size());
PublicEnvironmentConnection ec = PublicEnvironmentConnection.getInstance();
if (ec == null) return 0.5;
// Find how trusted each agent is on average
for (String candidate : memberList)
{
int n = 0;
double sum = 0;
for (String truster : memberList)
{
PublicAgentDataModel dm = ec.getAgentById(truster);
Double t = (dm == null ? null : dm.getTrust(candidate));
if (t != null && !candidate.equals(truster))
{
sum += t;
++n;
}
}
if (n > 0) avg_trusts.add(sum / n);
}
int n = avg_trusts.size();
// No agents have any trust values for any other
if (n == 0) return 0.5;
// Calculate the average overall trust for an agent
double sum = 0;
for (Double v : avg_trusts) sum += v;
double mu = sum / n;
// Calculate the std deviation of overall trust in agents
double variance = 0;
for (Double v : avg_trusts) variance += (v - mu)*(v - mu);
double st_dev = 2 * Math.sqrt(variance / n);
- st_dev = ScaledDouble.scale(st_dev, n, mu);
- return 1- st_dev;
+ return 1- ScaledDouble.scale(st_dev, n, mu);
}
List<String> getPanel(){
return this.panel;
}
void setPanel(List<String> nPanel){
this.panel = nPanel;
}
AgentType getGroupStrategy(){
return groupStrategy;
}
void setGroupStrategy(AgentType strategy){
this.groupStrategy = strategy;
}
void setReservedFoodHistory(double pooledFood){
reservedFoodHistory.setValue(pooledFood);
}
double getCurrentReservedFood()
{
return reservedFoodHistory.getValue();
}
History<Double> getReservedFoodHistory()
{
return reservedFoodHistory.getUnmodifableHistory();
}
int size()
{
return memberList.size();
}
}
| true | true | double getEstimatedSocialLocation()
{
/*
* Algorithm:
* - The leaders are those people trust most
* - The social location is ratio(ish) of leaders to group members
* - This can be modelled as the the deviation of the trust values
* - If one agent is trusted more than others, high deviation
* - This represents an autocracy
* - The values used to find standard deviation will be the average of each
* agent's opinion of an agent
*/
List<Double> avg_trusts = new ArrayList<Double>(memberList.size());
PublicEnvironmentConnection ec = PublicEnvironmentConnection.getInstance();
if (ec == null) return 0.5;
// Find how trusted each agent is on average
for (String candidate : memberList)
{
int n = 0;
double sum = 0;
for (String truster : memberList)
{
PublicAgentDataModel dm = ec.getAgentById(truster);
Double t = (dm == null ? null : dm.getTrust(candidate));
if (t != null && !candidate.equals(truster))
{
sum += t;
++n;
}
}
if (n > 0) avg_trusts.add(sum / n);
}
int n = avg_trusts.size();
// No agents have any trust values for any other
if (n == 0) return 0.5;
// Calculate the average overall trust for an agent
double sum = 0;
for (Double v : avg_trusts) sum += v;
double mu = sum / n;
// Calculate the std deviation of overall trust in agents
double variance = 0;
for (Double v : avg_trusts) variance += (v - mu)*(v - mu);
double st_dev = 2 * Math.sqrt(variance / n);
st_dev = ScaledDouble.scale(st_dev, n, mu);
return 1- st_dev;
}
| double getEstimatedSocialLocation()
{
/*
* Algorithm:
* - The leaders are those people trust most
* - The social location is ratio(ish) of leaders to group members
* - This can be modelled as the the deviation of the trust values
* - If one agent is trusted more than others, high deviation
* - This represents an autocracy
* - The values used to find standard deviation will be the average of each
* agent's opinion of an agent
*/
List<Double> avg_trusts = new ArrayList<Double>(memberList.size());
PublicEnvironmentConnection ec = PublicEnvironmentConnection.getInstance();
if (ec == null) return 0.5;
// Find how trusted each agent is on average
for (String candidate : memberList)
{
int n = 0;
double sum = 0;
for (String truster : memberList)
{
PublicAgentDataModel dm = ec.getAgentById(truster);
Double t = (dm == null ? null : dm.getTrust(candidate));
if (t != null && !candidate.equals(truster))
{
sum += t;
++n;
}
}
if (n > 0) avg_trusts.add(sum / n);
}
int n = avg_trusts.size();
// No agents have any trust values for any other
if (n == 0) return 0.5;
// Calculate the average overall trust for an agent
double sum = 0;
for (Double v : avg_trusts) sum += v;
double mu = sum / n;
// Calculate the std deviation of overall trust in agents
double variance = 0;
for (Double v : avg_trusts) variance += (v - mu)*(v - mu);
double st_dev = 2 * Math.sqrt(variance / n);
return 1- ScaledDouble.scale(st_dev, n, mu);
}
|
diff --git a/src/org/biojavax/bio/seq/io/FastaFormat.java b/src/org/biojavax/bio/seq/io/FastaFormat.java
index 34d399b7e..d9a53911e 100644
--- a/src/org/biojavax/bio/seq/io/FastaFormat.java
+++ b/src/org/biojavax/bio/seq/io/FastaFormat.java
@@ -1,278 +1,278 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojavax.bio.seq.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.io.ParseException;
import org.biojava.bio.seq.io.SeqIOListener;
import org.biojava.bio.seq.io.SymbolTokenization;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.SimpleSymbolList;
import org.biojava.bio.symbol.Symbol;
import org.biojava.bio.symbol.SymbolList;
import org.biojava.utils.ChangeVetoException;
import org.biojavax.Namespace;
import org.biojavax.SimpleNamespace;
import org.biojavax.RichObjectFactory;
import org.biojavax.bio.seq.RichSequence;
/**
* Format object representing FASTA files. These files are almost pure
* sequence data.
* @author Thomas Down
* @author Matthew Pocock
* @author Greg Cox
* @author Lukas Kall
* @author Richard Holland
*/
public class FastaFormat extends RichSequenceFormat.HeaderlessFormat {
// Register this format with the format auto-guesser.
static {
RichSequence.IOTools.registerFormat(FastaFormat.class);
}
/**
* The name of this format
*/
public static final String FASTA_FORMAT = "FASTA";
// header line
protected static final Pattern hp = Pattern.compile(">(\\S+)(\\s+(.*))?");
// description chunk
protected static final Pattern dp = Pattern.compile( "^(gi\\|(\\d+)\\|)*(\\S+)\\|(\\S+?)(\\.(\\d+))*\\|(\\S+)$");
protected static final Pattern readableFiles = Pattern.compile(".*(fa|fas)$");
protected static final Pattern aminoAcids = Pattern.compile(".*[FLIPQE].*");
/**
* {@inheritDoc}
* A file is in FASTA format if the name ends with fa or fas, or the file starts with ">".
*/
public boolean canRead(File file) throws IOException {
if (readableFiles.matcher(file.getName()).matches()) return true;
BufferedReader br = new BufferedReader(new FileReader(file));
boolean readable = br.readLine().startsWith(">");
br.close();
return readable;
}
/**
* {@inheritDoc}
* Returns an protein parser if the first line of sequence contains any of F/L/I/P/Q/E,
* otherwise returns a DNA tokenizer.
*/
public SymbolTokenization guessSymbolTokenization(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
br.readLine(); // discard first line
boolean aa = aminoAcids.matcher(br.readLine()).matches();
br.close();
if (aa) return RichSequence.IOTools.getProteinParser();
else return RichSequence.IOTools.getDNAParser();
}
/**
* {@inheritDoc}
*/
public boolean readSequence(
BufferedReader reader,
SymbolTokenization symParser,
SeqIOListener listener
) throws
IllegalSymbolException,
IOException,
ParseException {
if (!(listener instanceof RichSeqIOListener)) throw new IllegalArgumentException("Only accepting RichSeqIOListeners today");
return this.readRichSequence(reader,symParser,(RichSeqIOListener)listener,null);
}
/**
* {@inheritDoc}
* If namespace is null, then the namespace of the sequence in the fasta is used.
* If the namespace is null and so is the namespace of the sequence in the fasta,
* then the default namespace is used.
*/
public boolean readRichSequence(
BufferedReader reader,
SymbolTokenization symParser,
RichSeqIOListener rsiol,
Namespace ns
) throws
IllegalSymbolException,
IOException,
ParseException {
String line = reader.readLine();
if (line == null) {
throw new IOException("Premature stream end");
}
while(line.length() == 0) {
line = reader.readLine();
if (line == null) {
throw new IOException("Premature stream end");
}
}
if (!line.startsWith(">")) {
throw new IOException("Stream does not appear to contain FASTA formatted data: " + line);
}
rsiol.startSequence();
Matcher m = hp.matcher(line);
if (!m.matches()) {
throw new IOException("Stream does not appear to contain FASTA formatted data: " + line);
}
String name = m.group(1);
String desc = m.group(3);
m = dp.matcher(name);
if (m.matches()) {
String gi = m.group(2);
String namespace = m.group(3);
String accession = m.group(4);
String verString = m.group(6);
int version = verString==null?0:Integer.parseInt(verString);
name = m.group(7);
rsiol.setAccession(accession);
rsiol.setVersion(version);
if (gi!=null) rsiol.setIdentifier(gi);
if (ns==null) rsiol.setNamespace((Namespace)RichObjectFactory.getObject(SimpleNamespace.class,new Object[]{namespace}));
else rsiol.setNamespace(ns);
} else {
rsiol.setAccession(name);
rsiol.setNamespace((ns==null?RichObjectFactory.getDefaultNamespace():ns));
}
rsiol.setName(name);
if (!this.getElideComments()) rsiol.setDescription(desc);
StringBuffer seq = new StringBuffer();
boolean hasMoreSeq = true;
while (hasMoreSeq) {
reader.mark(500);
line = reader.readLine();
if (line!=null) {
line = line.trim();
- if (line.charAt(0)=='>') {
+ if (line.length() > 0 && line.charAt(0)=='>') {
reader.reset();
hasMoreSeq = false;
} else {
seq.append(line);
}
} else {
hasMoreSeq = false;
}
}
if (!this.getElideSymbols()) {
try {
SymbolList sl = new SimpleSymbolList(symParser,
seq.toString().replaceAll("\\s+","").replaceAll("[\\.|~]","-"));
rsiol.addSymbols(symParser.getAlphabet(),
(Symbol[])(sl.toList().toArray(new Symbol[0])),
0, sl.length());
} catch (Exception e) {
throw new ParseException(e);
}
}
rsiol.endSequence();
return line!=null;
}
/**
* {@inheritDoc}
*/
public void writeSequence(Sequence seq, PrintStream os) throws IOException {
if (this.getPrintStream()==null) this.setPrintStream(os);
this.writeSequence(seq, RichObjectFactory.getDefaultNamespace());
}
/**
* {@inheritDoc}
*/
public void writeSequence(Sequence seq, String format, PrintStream os) throws IOException {
if (this.getPrintStream()==null) this.setPrintStream(os);
if (!format.equals(this.getDefaultFormat())) throw new IllegalArgumentException("Unknown format: "+format);
this.writeSequence(seq, RichObjectFactory.getDefaultNamespace());
}
/**
* {@inheritDoc}
* If namespace is null, then the sequence's own namespace is used.
*/
public void writeSequence(Sequence seq, Namespace ns) throws IOException {
RichSequence rs;
try {
if (seq instanceof RichSequence) rs = (RichSequence)seq;
else rs = RichSequence.Tools.enrich(seq);
} catch (ChangeVetoException e) {
IOException e2 = new IOException("Unable to enrich sequence");
e2.initCause(e);
throw e2;
}
this.getPrintStream().print(">");
String identifier = rs.getIdentifier();
if (identifier!=null && !"".equals(identifier)) {
this.getPrintStream().print("gi|");
this.getPrintStream().print(identifier);
this.getPrintStream().print("|");
}
this.getPrintStream().print((ns==null?rs.getNamespace().getName():ns.getName()));
this.getPrintStream().print("|");
this.getPrintStream().print(rs.getAccession());
this.getPrintStream().print(".");
this.getPrintStream().print(rs.getVersion());
this.getPrintStream().print("|");
this.getPrintStream().print(rs.getName());
this.getPrintStream().print(" ");
String desc = rs.getDescription();
if (desc!=null && !"".equals(desc)) this.getPrintStream().print(desc.replaceAll("\\n"," "));
this.getPrintStream().println();
int length = rs.length();
for (int pos = 1; pos <= length; pos += this.getLineWidth()) {
int end = Math.min(pos + this.getLineWidth() - 1, length);
this.getPrintStream().println(rs.subStr(pos, end));
}
}
/**
* {@inheritDoc}
*/
public String getDefaultFormat() {
return FASTA_FORMAT;
}
}
| true | true | public boolean readRichSequence(
BufferedReader reader,
SymbolTokenization symParser,
RichSeqIOListener rsiol,
Namespace ns
) throws
IllegalSymbolException,
IOException,
ParseException {
String line = reader.readLine();
if (line == null) {
throw new IOException("Premature stream end");
}
while(line.length() == 0) {
line = reader.readLine();
if (line == null) {
throw new IOException("Premature stream end");
}
}
if (!line.startsWith(">")) {
throw new IOException("Stream does not appear to contain FASTA formatted data: " + line);
}
rsiol.startSequence();
Matcher m = hp.matcher(line);
if (!m.matches()) {
throw new IOException("Stream does not appear to contain FASTA formatted data: " + line);
}
String name = m.group(1);
String desc = m.group(3);
m = dp.matcher(name);
if (m.matches()) {
String gi = m.group(2);
String namespace = m.group(3);
String accession = m.group(4);
String verString = m.group(6);
int version = verString==null?0:Integer.parseInt(verString);
name = m.group(7);
rsiol.setAccession(accession);
rsiol.setVersion(version);
if (gi!=null) rsiol.setIdentifier(gi);
if (ns==null) rsiol.setNamespace((Namespace)RichObjectFactory.getObject(SimpleNamespace.class,new Object[]{namespace}));
else rsiol.setNamespace(ns);
} else {
rsiol.setAccession(name);
rsiol.setNamespace((ns==null?RichObjectFactory.getDefaultNamespace():ns));
}
rsiol.setName(name);
if (!this.getElideComments()) rsiol.setDescription(desc);
StringBuffer seq = new StringBuffer();
boolean hasMoreSeq = true;
while (hasMoreSeq) {
reader.mark(500);
line = reader.readLine();
if (line!=null) {
line = line.trim();
if (line.charAt(0)=='>') {
reader.reset();
hasMoreSeq = false;
} else {
seq.append(line);
}
} else {
hasMoreSeq = false;
}
}
if (!this.getElideSymbols()) {
try {
SymbolList sl = new SimpleSymbolList(symParser,
seq.toString().replaceAll("\\s+","").replaceAll("[\\.|~]","-"));
rsiol.addSymbols(symParser.getAlphabet(),
(Symbol[])(sl.toList().toArray(new Symbol[0])),
0, sl.length());
} catch (Exception e) {
throw new ParseException(e);
}
}
rsiol.endSequence();
return line!=null;
}
| public boolean readRichSequence(
BufferedReader reader,
SymbolTokenization symParser,
RichSeqIOListener rsiol,
Namespace ns
) throws
IllegalSymbolException,
IOException,
ParseException {
String line = reader.readLine();
if (line == null) {
throw new IOException("Premature stream end");
}
while(line.length() == 0) {
line = reader.readLine();
if (line == null) {
throw new IOException("Premature stream end");
}
}
if (!line.startsWith(">")) {
throw new IOException("Stream does not appear to contain FASTA formatted data: " + line);
}
rsiol.startSequence();
Matcher m = hp.matcher(line);
if (!m.matches()) {
throw new IOException("Stream does not appear to contain FASTA formatted data: " + line);
}
String name = m.group(1);
String desc = m.group(3);
m = dp.matcher(name);
if (m.matches()) {
String gi = m.group(2);
String namespace = m.group(3);
String accession = m.group(4);
String verString = m.group(6);
int version = verString==null?0:Integer.parseInt(verString);
name = m.group(7);
rsiol.setAccession(accession);
rsiol.setVersion(version);
if (gi!=null) rsiol.setIdentifier(gi);
if (ns==null) rsiol.setNamespace((Namespace)RichObjectFactory.getObject(SimpleNamespace.class,new Object[]{namespace}));
else rsiol.setNamespace(ns);
} else {
rsiol.setAccession(name);
rsiol.setNamespace((ns==null?RichObjectFactory.getDefaultNamespace():ns));
}
rsiol.setName(name);
if (!this.getElideComments()) rsiol.setDescription(desc);
StringBuffer seq = new StringBuffer();
boolean hasMoreSeq = true;
while (hasMoreSeq) {
reader.mark(500);
line = reader.readLine();
if (line!=null) {
line = line.trim();
if (line.length() > 0 && line.charAt(0)=='>') {
reader.reset();
hasMoreSeq = false;
} else {
seq.append(line);
}
} else {
hasMoreSeq = false;
}
}
if (!this.getElideSymbols()) {
try {
SymbolList sl = new SimpleSymbolList(symParser,
seq.toString().replaceAll("\\s+","").replaceAll("[\\.|~]","-"));
rsiol.addSymbols(symParser.getAlphabet(),
(Symbol[])(sl.toList().toArray(new Symbol[0])),
0, sl.length());
} catch (Exception e) {
throw new ParseException(e);
}
}
rsiol.endSequence();
return line!=null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.