diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java b/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java
index 59732e9..6394c75 100644
--- a/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java
+++ b/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java
@@ -1,357 +1,356 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.grails.maven.plugin;
import org.grails.maven.plugin.tools.GrailsServices;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.artifact.MavenMetadataSource;
import org.apache.maven.model.Dependency;
import org.codehaus.groovy.grails.cli.support.GrailsRootLoader;
import org.codehaus.groovy.grails.cli.support.GrailsBuildHelper;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.*;
/**
* Common services for all Mojos using Grails
*
* @author <a href="mailto:[email protected]">Arnaud HERITIER</a>
* @author Peter Ledbrook
* @version $Id$
*/
public abstract class AbstractGrailsMojo extends AbstractMojo {
/**
* The directory where is launched the mvn command.
*
* @parameter default-value="${basedir}"
* @required
*/
protected File basedir;
/**
* The Grails environment to use.
*
* @parameter expression="${grails.env}"
*/
protected String env;
/**
* The directory where is launched the mvn command.
*
* @parameter expression="${nonInteractive}" default-value="false"
* @required
*/
protected boolean nonInteractive;
/**
* POM
*
* @parameter expression="${project}"
* @readonly
* @required
*/
protected MavenProject project;
/**
* @component
*/
private ArtifactResolver artifactResolver;
/**
* @component
*/
private ArtifactFactory artifactFactory;
/**
* @component
*/
private ArtifactCollector artifactCollector;
/**
* @component
*/
private ArtifactMetadataSource artifactMetadataSource;
/**
* @parameter expression="${localRepository}"
* @required
* @readonly
*/
private ArtifactRepository localRepository;
/**
* @parameter expression="${project.remoteArtifactRepositories}"
* @required
* @readonly
*/
private List remoteRepositories;
/**
* @component
*/
private MavenProjectBuilder projectBuilder;
/**
* @component
* @readonly
*/
private GrailsServices grailsServices;
protected File getBasedir() {
if(basedir == null) {
throw new RuntimeException("Your subclass have a field called 'basedir'. Remove it and use getBasedir() " +
"instead.");
}
return this.basedir;
}
/**
* OutputStream to write the content of stdout.
*/
private OutputStream infoOutputStream = new OutputStream() {
StringBuffer buffer = new StringBuffer();
public void write(int b) throws IOException {
if (b == '\n') {
getLog().info(buffer.toString());
buffer.setLength(0);
} else {
buffer.append((char) b);
}
}
};
/**
* OutputStream to write the content of stderr.
*/
private OutputStream warnOutputStream = new OutputStream() {
StringBuffer buffer = new StringBuffer();
public void write(int b) throws IOException {
if (b == '\n') {
getLog().warn(buffer.toString());
buffer.setLength(0);
} else {
buffer.append((char) b);
}
}
};
protected GrailsServices getGrailsServices() throws MojoExecutionException {
grailsServices.setBasedir(basedir);
return grailsServices;
}
protected void runGrails(String targetName) throws MojoExecutionException {
runGrails(targetName, null, false);
}
protected void runGrails(String targetName, String args, boolean includeProjectDeps) throws MojoExecutionException {
// First get the dependencies specified by the plugin.
Set deps = getGrailsPluginDependencies();
// Now add the project dependencies if necessary.
if (includeProjectDeps) {
deps.addAll(this.project.getRuntimeArtifacts());
}
URL[] classpath;
try {
classpath = new URL[deps.size() + 1];
int index = 0;
for (Iterator iter = deps.iterator(); iter.hasNext();) {
classpath[index++] = ((Artifact) iter.next()).getFile().toURI().toURL();
}
// Add the "tools.jar" to the classpath so that the Grails
// scripts can run native2ascii. First assume that "java.home"
// points to a JRE within a JDK.
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome, "../lib/tools.jar");
if (!toolsJar.exists()) {
// The "tools.jar" cannot be found with that path, so
// now try with the assumption that "java.home" points
// to a JDK.
toolsJar = new File(javaHome, "tools.jar");
}
classpath[classpath.length - 1] = toolsJar.toURI().toURL();
- System.setProperty("base.dir", basedir.getAbsolutePath());
GrailsRootLoader rootLoader = new GrailsRootLoader(classpath, getClass().getClassLoader());
- GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader);
+ GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader, null, basedir.getAbsolutePath());
configureBuildSettings(helper);
// mainClass.getDeclaredMethod("setOut", new Class[]{ PrintStream.class }).invoke(
// scriptRunner,
// new Object[] { new PrintStream(infoOutputStream) });
// If the command is running in non-interactive mode, we
// need to pass on the relevant argument.
if (this.nonInteractive) {
args = args == null ? "--non-interactive" : "--non-interactive " + args;
}
int retval = helper.execute(targetName, args, env);
if (retval != 0) {
throw new MojoExecutionException("Grails returned non-zero value: " + retval);
}
} catch (MojoExecutionException ex) {
// Simply rethrow it.
throw ex;
} catch (Exception ex) {
throw new MojoExecutionException("Unable to start Grails", ex);
}
}
private Set getGrailsPluginDependencies() throws MojoExecutionException {
Artifact pluginArtifact = findArtifact(this.project.getPluginArtifacts(), "org.grails", "grails-maven-plugin");
MavenProject project = null;
try {
project = this.projectBuilder.buildFromRepository(pluginArtifact,
this.remoteRepositories,
this.localRepository);
} catch (ProjectBuildingException ex) {
throw new MojoExecutionException("Failed to get information about Grails Maven Plugin", ex);
}
List deps = artifactsByGroupId(dependenciesToArtifacts(project.getDependencies()), "org.grails");
Set pluginDependencies = new HashSet();
for (Iterator iter = deps.iterator(); iter.hasNext();) {
pluginDependencies.addAll(getPluginDependencies((Artifact) iter.next()));
}
return pluginDependencies;
}
private void configureBuildSettings(GrailsBuildHelper helper)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, MojoExecutionException, NoSuchMethodException, InvocationTargetException {
String targetDir = this.project.getBuild().getDirectory();
helper.setCompileDependencies(artifactsToFiles(this.project.getCompileArtifacts()));
helper.setTestDependencies(artifactsToFiles(this.project.getTestArtifacts()));
helper.setRuntimeDependencies(artifactsToFiles(this.project.getRuntimeArtifacts()));
helper.setProjectWorkDir(new File(targetDir));
helper.setClassesDir(new File(targetDir, "classes"));
helper.setTestClassesDir(new File(targetDir, "test-classes"));
helper.setResourcesDir(new File(targetDir, "resources"));
helper.setProjectPluginsDir(new File(this.project.getBasedir(), "plugins"));
}
private Set getPluginDependencies(Artifact pom) throws MojoExecutionException {
try {
MavenProject project = this.projectBuilder.buildFromRepository(pom,
this.remoteRepositories,
this.localRepository);
//get all of the dependencies for the executable project
List dependencies = project.getDependencies();
//make Artifacts of all the dependencies
Set dependencyArtifacts =
MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies, null, null, null);
ArtifactResolutionResult result = artifactCollector.collect(
dependencyArtifacts,
project.getArtifact(),
this.localRepository,
this.remoteRepositories,
this.artifactMetadataSource,
null,
Collections.EMPTY_LIST);
dependencyArtifacts.addAll(result.getArtifacts());
//not forgetting the Artifact of the project itself
dependencyArtifacts.add(project.getArtifact());
//resolve all dependencies transitively to obtain a comprehensive list of assemblies
for (Iterator iter = dependencyArtifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
this.artifactResolver.resolve(artifact, this.remoteRepositories, this.localRepository);
}
return dependencyArtifacts;
} catch ( Exception ex ) {
throw new MojoExecutionException("Encountered problems resolving dependencies of the executable " +
"in preparation for its execution.", ex);
}
}
private List artifactsToFiles(Collection artifacts) {
List files = new ArrayList(artifacts.size());
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
files.add(((Artifact) iter.next()).getFile());
}
return files;
}
private Artifact findArtifact(Collection artifacts, String groupId, String artifactId) {
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)) {
return artifact;
}
}
return null;
}
private List artifactsByGroupId(Collection artifacts, String groupId) {
List inGroup = new ArrayList(artifacts.size());
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
if (artifact.getGroupId().equals(groupId)) {
inGroup.add(artifact);
}
}
return inGroup;
}
private List dependenciesToArtifacts(Collection deps) {
List artifacts = new ArrayList(deps.size());
for (Iterator iter = deps.iterator(); iter.hasNext();) {
artifacts.add(dependencyToArtifact((Dependency) iter.next()));
}
return artifacts;
}
private Artifact dependencyToArtifact(Dependency dep) {
return this.artifactFactory.createBuildArtifact(
dep.getGroupId(),
dep.getArtifactId(),
dep.getVersion(),
"pom");
}
}
| false | true | protected void runGrails(String targetName, String args, boolean includeProjectDeps) throws MojoExecutionException {
// First get the dependencies specified by the plugin.
Set deps = getGrailsPluginDependencies();
// Now add the project dependencies if necessary.
if (includeProjectDeps) {
deps.addAll(this.project.getRuntimeArtifacts());
}
URL[] classpath;
try {
classpath = new URL[deps.size() + 1];
int index = 0;
for (Iterator iter = deps.iterator(); iter.hasNext();) {
classpath[index++] = ((Artifact) iter.next()).getFile().toURI().toURL();
}
// Add the "tools.jar" to the classpath so that the Grails
// scripts can run native2ascii. First assume that "java.home"
// points to a JRE within a JDK.
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome, "../lib/tools.jar");
if (!toolsJar.exists()) {
// The "tools.jar" cannot be found with that path, so
// now try with the assumption that "java.home" points
// to a JDK.
toolsJar = new File(javaHome, "tools.jar");
}
classpath[classpath.length - 1] = toolsJar.toURI().toURL();
System.setProperty("base.dir", basedir.getAbsolutePath());
GrailsRootLoader rootLoader = new GrailsRootLoader(classpath, getClass().getClassLoader());
GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader);
configureBuildSettings(helper);
// mainClass.getDeclaredMethod("setOut", new Class[]{ PrintStream.class }).invoke(
// scriptRunner,
// new Object[] { new PrintStream(infoOutputStream) });
// If the command is running in non-interactive mode, we
// need to pass on the relevant argument.
if (this.nonInteractive) {
args = args == null ? "--non-interactive" : "--non-interactive " + args;
}
int retval = helper.execute(targetName, args, env);
if (retval != 0) {
throw new MojoExecutionException("Grails returned non-zero value: " + retval);
}
} catch (MojoExecutionException ex) {
// Simply rethrow it.
throw ex;
} catch (Exception ex) {
throw new MojoExecutionException("Unable to start Grails", ex);
}
}
| protected void runGrails(String targetName, String args, boolean includeProjectDeps) throws MojoExecutionException {
// First get the dependencies specified by the plugin.
Set deps = getGrailsPluginDependencies();
// Now add the project dependencies if necessary.
if (includeProjectDeps) {
deps.addAll(this.project.getRuntimeArtifacts());
}
URL[] classpath;
try {
classpath = new URL[deps.size() + 1];
int index = 0;
for (Iterator iter = deps.iterator(); iter.hasNext();) {
classpath[index++] = ((Artifact) iter.next()).getFile().toURI().toURL();
}
// Add the "tools.jar" to the classpath so that the Grails
// scripts can run native2ascii. First assume that "java.home"
// points to a JRE within a JDK.
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome, "../lib/tools.jar");
if (!toolsJar.exists()) {
// The "tools.jar" cannot be found with that path, so
// now try with the assumption that "java.home" points
// to a JDK.
toolsJar = new File(javaHome, "tools.jar");
}
classpath[classpath.length - 1] = toolsJar.toURI().toURL();
GrailsRootLoader rootLoader = new GrailsRootLoader(classpath, getClass().getClassLoader());
GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader, null, basedir.getAbsolutePath());
configureBuildSettings(helper);
// mainClass.getDeclaredMethod("setOut", new Class[]{ PrintStream.class }).invoke(
// scriptRunner,
// new Object[] { new PrintStream(infoOutputStream) });
// If the command is running in non-interactive mode, we
// need to pass on the relevant argument.
if (this.nonInteractive) {
args = args == null ? "--non-interactive" : "--non-interactive " + args;
}
int retval = helper.execute(targetName, args, env);
if (retval != 0) {
throw new MojoExecutionException("Grails returned non-zero value: " + retval);
}
} catch (MojoExecutionException ex) {
// Simply rethrow it.
throw ex;
} catch (Exception ex) {
throw new MojoExecutionException("Unable to start Grails", ex);
}
}
|
diff --git a/CluePath/src/ClueBoard/RoomCell.java b/CluePath/src/ClueBoard/RoomCell.java
index 9e0bcb7..094c4b1 100644
--- a/CluePath/src/ClueBoard/RoomCell.java
+++ b/CluePath/src/ClueBoard/RoomCell.java
@@ -1,61 +1,61 @@
package ClueBoard;
import java.awt.Color;
import java.awt.Graphics;
public class RoomCell extends BoardCell {
public enum DoorDirection {UP, DOWN, LEFT, RIGHT, NONE};
private DoorDirection doorDirection;
private char roomInitial;
public RoomCell (String temp){
roomInitial = temp.charAt(0);
if(temp.length() > 1){
char direction = temp.charAt(1);
if(direction == 'U') doorDirection = DoorDirection.UP;
if(direction == 'D') doorDirection = DoorDirection.DOWN;
if(direction == 'L') doorDirection = DoorDirection.LEFT;
if(direction == 'R') doorDirection = DoorDirection.RIGHT;
}else{
doorDirection=DoorDirection.NONE;
}
}
public boolean isRoom() {
return true;
}
public boolean isDoorway(){
if(doorDirection!=DoorDirection.NONE){
return true;
}else{
return false;
}
}
public char getRoomInitial() {
return roomInitial;
}
public DoorDirection getDoorDirection() {
return doorDirection;
}
public void draw(Graphics g, int size, int x, int y) {
if(isDoorway()) {
g.setColor(Color.GREEN);
if(doorDirection == doorDirection.UP) {
g.fillRect(x * size, y * size, size, 10);
} else if (doorDirection == doorDirection.DOWN) {
- g.fillRect(x * size, (y + (size - 10)) * size, size, 10);
+ g.fillRect(x * size, (y * size) + (size - 10), size, 10);
} else if (doorDirection == doorDirection.LEFT) {
g.fillRect(x * size, y * size, 10, size);
} else if (doorDirection == doorDirection.RIGHT) {
- g.fillRect((x + (size - 10)) * size, y * size, 10, size);
+ g.fillRect((x * size) + (size - 10) , y * size, 10, size);
}
}
}
}
| false | true | public void draw(Graphics g, int size, int x, int y) {
if(isDoorway()) {
g.setColor(Color.GREEN);
if(doorDirection == doorDirection.UP) {
g.fillRect(x * size, y * size, size, 10);
} else if (doorDirection == doorDirection.DOWN) {
g.fillRect(x * size, (y + (size - 10)) * size, size, 10);
} else if (doorDirection == doorDirection.LEFT) {
g.fillRect(x * size, y * size, 10, size);
} else if (doorDirection == doorDirection.RIGHT) {
g.fillRect((x + (size - 10)) * size, y * size, 10, size);
}
}
}
| public void draw(Graphics g, int size, int x, int y) {
if(isDoorway()) {
g.setColor(Color.GREEN);
if(doorDirection == doorDirection.UP) {
g.fillRect(x * size, y * size, size, 10);
} else if (doorDirection == doorDirection.DOWN) {
g.fillRect(x * size, (y * size) + (size - 10), size, 10);
} else if (doorDirection == doorDirection.LEFT) {
g.fillRect(x * size, y * size, 10, size);
} else if (doorDirection == doorDirection.RIGHT) {
g.fillRect((x * size) + (size - 10) , y * size, 10, size);
}
}
}
|
diff --git a/src/main/java/uk/ac/ebi/fgpt/webapp/SubmissionController.java b/src/main/java/uk/ac/ebi/fgpt/webapp/SubmissionController.java
index c211a38..e82c4f5 100644
--- a/src/main/java/uk/ac/ebi/fgpt/webapp/SubmissionController.java
+++ b/src/main/java/uk/ac/ebi/fgpt/webapp/SubmissionController.java
@@ -1,261 +1,261 @@
package uk.ac.ebi.fgpt.webapp;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mged.magetab.error.ErrorItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException;
import uk.ac.ebi.arrayexpress2.magetab.listener.ErrorItemListener;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.SampleData;
import uk.ac.ebi.arrayexpress2.sampletab.parser.SampleTabParser;
import uk.ac.ebi.arrayexpress2.sampletab.renderer.SampleTabWriter;
import uk.ac.ebi.fgpt.sampletab.AccessionerENA;
import uk.ac.ebi.fgpt.sampletab.Corrector;
import uk.ac.ebi.fgpt.sampletab.utils.SampleTabUtils;
/**
* A spring controller that returns an accessioned version of a POSTed SampleTab
*
* @author Adam Faulconbridge
* @date 02/05/12
*/
@Controller
@RequestMapping
public class SubmissionController {
private Logger log = LoggerFactory.getLogger(getClass());
private final File path;
private AccessionerENA accessioner;
private Corrector corrector;
public SubmissionController() {
Properties properties = new Properties();
try {
InputStream is = SubmissionController.class.getResourceAsStream("/sampletab.properties");
properties.load(is);
} catch (IOException e) {
log.error("Unable to read resource properties", e);
path = null;
return;
}
path = new File(properties.getProperty("submissionpath"));
if (!path.exists()){
//TODO throw error
log.error("Submission path "+path+" does not exist");
}
properties = new Properties();
try {
InputStream is = AccessionerController.class.getResourceAsStream("/oracle.properties");
properties.load(is);
} catch (IOException e) {
log.error("Unable to read resource properties", e);
return;
}
String host = properties.getProperty("hostname");
Integer port = new Integer(properties.getProperty("port"));
String database = properties.getProperty("database");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
try {
accessioner = new AccessionerENA(host, port, database, username, password);
} catch (ClassNotFoundException e) {
log.error("Unable to create accessioner", e);
accessioner = null;
} catch (SQLException e) {
log.error("Unable to create accessioner", e);
accessioner = null;
}
corrector = new Corrector();
}
private synchronized int getNewSubID() throws IOException{
int maxSubID = 0;
Pattern pattern = Pattern.compile("^GSB-([0-9]+)$");
File pathSubdir = new File(path, "GSB");
for (File subdir : pathSubdir.listFiles()) {
if (!subdir.isDirectory()) {
continue;
} else {
log.info("Looking at subid "+subdir.getName()+" with pattern "+pattern.pattern());
Matcher match = pattern.matcher(subdir.getName());
if (match.matches()) {
log.info("Found match with "+match.groupCount()+" groups "+match.group(1));
Integer subid = new Integer(match.group(1));
if (subid > maxSubID) {
maxSubID = subid;
}
}
}
}
maxSubID++;
File subDir = new File(path.getAbsolutePath(), SampleTabUtils.getSubmissionDirFile("GSB-"+maxSubID).toString());
if (!subDir.mkdirs()) {
throw new IOException("Unable to create submission directory");
}
return maxSubID;
}
private Outcome getErrorOutcome(String message, String comment) {
Outcome o = new Outcome();
List<Map<String,String>> errorList = new ArrayList<Map<String,String>>();
Map<String, String> errorMap = new HashMap<String, String>();
//errorMap.put("type", errorItem.getErrorType());
//errorMap.put("code", new Integer(errorItem.getErrorCode()).toString());
//errorMap.put("line", new Integer(errorItem.getLine()).toString());
//errorMap.put("col", new Integer(errorItem.getCol()).toString());
errorMap.put("message", message);
errorMap.put("comment", comment);
errorList.add(errorMap);
o.setErrors(errorList);
return o;
}
@RequestMapping(value = "/v1/json/sb", method = RequestMethod.POST)
public @ResponseBody Outcome doSubmission(@RequestBody SampleTabRequest sampletab, String apikey) {
boolean isSRA = false;
boolean isCGAP = false;
//test API key
//generate keys with following python:
// "".join([random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for x in xrange(16)])
if (apikey != null && apikey.equals("NZ80KZ7G13NHYDM3")) {
//SRA
isSRA = true;
} else if (apikey != null && apikey.equals("XWURYU77KWT663IQ")) {
//CGAP
isCGAP = true;
} else if (apikey != null && apikey.equals("FZJ5VRBEZEJ5ZDP8")) {
//BBMRI.eu
} else if (apikey != null && apikey.equals("Y1Y1PKRGPP7PWD82")) {
//internal
} else {
//invalid API key, return errors
return getErrorOutcome("Invalid API key ("+apikey+")", "Contact [email protected] for assistance");
}
// setup an overall try/catch to catch and report all errors
try {
//setup parser to listen for errors
SampleTabParser<SampleData> parser = new SampleTabParser<SampleData>();
final List<ErrorItem> errorItems;
errorItems = new ArrayList<ErrorItem>();
parser.addErrorItemListener(new ErrorItemListener() {
public void errorOccurred(ErrorItem item) {
errorItems.add(item);
}
});
SampleData sampledata = null;
//convert json object to string
String singleString = sampletab.asSingleString();
//setup the string as an input stream
InputStream is = new ByteArrayInputStream(singleString.getBytes("UTF-8"));
try {
//parse the input into sampletab
//will also validate
sampledata = parser.parse(is);
} catch (ParseException e) {
//catch parsing errors for malformed submissions
log.error("parsing error", e);
return new Outcome(null, e.getErrorItems());
}
//look at submission id
if (isSRA) {
//extra validation for SRA
if (sampledata.msi.submissionIdentifier == null || !sampledata.msi.submissionIdentifier.matches("^GEN-[ERD]R[AP][0-9]+$")) {
return getErrorOutcome("Submission identifier invalid", "SRA submission identifier must match regular expression ^GEN-[SED]R[AP][0-9]+$");
}
} else if (isCGAP) {
//extra validation for HipScip
if (sampledata.msi.submissionIdentifier == null || !sampledata.msi.submissionIdentifier.matches("^GCG-HipSci$")) {
return getErrorOutcome("Submission identifier invalid", "Submission identifier must match GCG-HipSci");
}
//do some re-routing
sampledata.msi.submissionIdentifier = "GSB-3";
} else {
//must be a GSB submission ID
if (sampledata.msi.submissionIdentifier == null || sampledata.msi.submissionIdentifier.length() == 0) {
sampledata.msi.submissionIdentifier = "GSB-"+getNewSubID();
} else if (!sampledata.msi.submissionIdentifier.matches("^GSB-[1-9][0-9]*$")) {
return getErrorOutcome("Submission identifier invalid", "Submission identifier must match regular expression ^GSB-[1-9][0-9]*$");
}
}
File subdir = SampleTabUtils.getSubmissionDirFile(sampledata.msi.submissionIdentifier);
subdir = new File(path.toString(), subdir.toString());
File outFile = new File(subdir, "sampletab.pre.txt");
//assign accessions to sampletab object
synchronized(accessioner) {
sampledata = accessioner.convert(sampledata);
}
//correct errors
synchronized(corrector) {
corrector.correct(sampledata);
}
SampleTabWriter writer = null;
try {
- if (!subdir.mkdirs()) {
+ if (!subdir.exists() && !subdir.mkdirs()) {
throw new IOException("Unable to create parent directories");
}
writer = new SampleTabWriter(new BufferedWriter(new FileWriter(outFile)));
writer.write(sampledata);
} catch (IOException e) {
log.error("Problem writing to "+outFile, e);
return getErrorOutcome("Unable to store submission", "Retry later or contact [email protected] if this error persists");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
//do nothing
}
}
}
//return the submitted file, and any generated errors
return new Outcome(sampledata, errorItems);
} catch (Exception e) {
//general catch all for other errors, e.g SQL, IO
log.error("Unrecognized error", e);
return getErrorOutcome("Unknown error", "Contact [email protected] for assistance");
}
}
}
| true | true | public @ResponseBody Outcome doSubmission(@RequestBody SampleTabRequest sampletab, String apikey) {
boolean isSRA = false;
boolean isCGAP = false;
//test API key
//generate keys with following python:
// "".join([random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for x in xrange(16)])
if (apikey != null && apikey.equals("NZ80KZ7G13NHYDM3")) {
//SRA
isSRA = true;
} else if (apikey != null && apikey.equals("XWURYU77KWT663IQ")) {
//CGAP
isCGAP = true;
} else if (apikey != null && apikey.equals("FZJ5VRBEZEJ5ZDP8")) {
//BBMRI.eu
} else if (apikey != null && apikey.equals("Y1Y1PKRGPP7PWD82")) {
//internal
} else {
//invalid API key, return errors
return getErrorOutcome("Invalid API key ("+apikey+")", "Contact [email protected] for assistance");
}
// setup an overall try/catch to catch and report all errors
try {
//setup parser to listen for errors
SampleTabParser<SampleData> parser = new SampleTabParser<SampleData>();
final List<ErrorItem> errorItems;
errorItems = new ArrayList<ErrorItem>();
parser.addErrorItemListener(new ErrorItemListener() {
public void errorOccurred(ErrorItem item) {
errorItems.add(item);
}
});
SampleData sampledata = null;
//convert json object to string
String singleString = sampletab.asSingleString();
//setup the string as an input stream
InputStream is = new ByteArrayInputStream(singleString.getBytes("UTF-8"));
try {
//parse the input into sampletab
//will also validate
sampledata = parser.parse(is);
} catch (ParseException e) {
//catch parsing errors for malformed submissions
log.error("parsing error", e);
return new Outcome(null, e.getErrorItems());
}
//look at submission id
if (isSRA) {
//extra validation for SRA
if (sampledata.msi.submissionIdentifier == null || !sampledata.msi.submissionIdentifier.matches("^GEN-[ERD]R[AP][0-9]+$")) {
return getErrorOutcome("Submission identifier invalid", "SRA submission identifier must match regular expression ^GEN-[SED]R[AP][0-9]+$");
}
} else if (isCGAP) {
//extra validation for HipScip
if (sampledata.msi.submissionIdentifier == null || !sampledata.msi.submissionIdentifier.matches("^GCG-HipSci$")) {
return getErrorOutcome("Submission identifier invalid", "Submission identifier must match GCG-HipSci");
}
//do some re-routing
sampledata.msi.submissionIdentifier = "GSB-3";
} else {
//must be a GSB submission ID
if (sampledata.msi.submissionIdentifier == null || sampledata.msi.submissionIdentifier.length() == 0) {
sampledata.msi.submissionIdentifier = "GSB-"+getNewSubID();
} else if (!sampledata.msi.submissionIdentifier.matches("^GSB-[1-9][0-9]*$")) {
return getErrorOutcome("Submission identifier invalid", "Submission identifier must match regular expression ^GSB-[1-9][0-9]*$");
}
}
File subdir = SampleTabUtils.getSubmissionDirFile(sampledata.msi.submissionIdentifier);
subdir = new File(path.toString(), subdir.toString());
File outFile = new File(subdir, "sampletab.pre.txt");
//assign accessions to sampletab object
synchronized(accessioner) {
sampledata = accessioner.convert(sampledata);
}
//correct errors
synchronized(corrector) {
corrector.correct(sampledata);
}
SampleTabWriter writer = null;
try {
if (!subdir.mkdirs()) {
throw new IOException("Unable to create parent directories");
}
writer = new SampleTabWriter(new BufferedWriter(new FileWriter(outFile)));
writer.write(sampledata);
} catch (IOException e) {
log.error("Problem writing to "+outFile, e);
return getErrorOutcome("Unable to store submission", "Retry later or contact [email protected] if this error persists");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
//do nothing
}
}
}
//return the submitted file, and any generated errors
return new Outcome(sampledata, errorItems);
} catch (Exception e) {
//general catch all for other errors, e.g SQL, IO
log.error("Unrecognized error", e);
return getErrorOutcome("Unknown error", "Contact [email protected] for assistance");
}
}
| public @ResponseBody Outcome doSubmission(@RequestBody SampleTabRequest sampletab, String apikey) {
boolean isSRA = false;
boolean isCGAP = false;
//test API key
//generate keys with following python:
// "".join([random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for x in xrange(16)])
if (apikey != null && apikey.equals("NZ80KZ7G13NHYDM3")) {
//SRA
isSRA = true;
} else if (apikey != null && apikey.equals("XWURYU77KWT663IQ")) {
//CGAP
isCGAP = true;
} else if (apikey != null && apikey.equals("FZJ5VRBEZEJ5ZDP8")) {
//BBMRI.eu
} else if (apikey != null && apikey.equals("Y1Y1PKRGPP7PWD82")) {
//internal
} else {
//invalid API key, return errors
return getErrorOutcome("Invalid API key ("+apikey+")", "Contact [email protected] for assistance");
}
// setup an overall try/catch to catch and report all errors
try {
//setup parser to listen for errors
SampleTabParser<SampleData> parser = new SampleTabParser<SampleData>();
final List<ErrorItem> errorItems;
errorItems = new ArrayList<ErrorItem>();
parser.addErrorItemListener(new ErrorItemListener() {
public void errorOccurred(ErrorItem item) {
errorItems.add(item);
}
});
SampleData sampledata = null;
//convert json object to string
String singleString = sampletab.asSingleString();
//setup the string as an input stream
InputStream is = new ByteArrayInputStream(singleString.getBytes("UTF-8"));
try {
//parse the input into sampletab
//will also validate
sampledata = parser.parse(is);
} catch (ParseException e) {
//catch parsing errors for malformed submissions
log.error("parsing error", e);
return new Outcome(null, e.getErrorItems());
}
//look at submission id
if (isSRA) {
//extra validation for SRA
if (sampledata.msi.submissionIdentifier == null || !sampledata.msi.submissionIdentifier.matches("^GEN-[ERD]R[AP][0-9]+$")) {
return getErrorOutcome("Submission identifier invalid", "SRA submission identifier must match regular expression ^GEN-[SED]R[AP][0-9]+$");
}
} else if (isCGAP) {
//extra validation for HipScip
if (sampledata.msi.submissionIdentifier == null || !sampledata.msi.submissionIdentifier.matches("^GCG-HipSci$")) {
return getErrorOutcome("Submission identifier invalid", "Submission identifier must match GCG-HipSci");
}
//do some re-routing
sampledata.msi.submissionIdentifier = "GSB-3";
} else {
//must be a GSB submission ID
if (sampledata.msi.submissionIdentifier == null || sampledata.msi.submissionIdentifier.length() == 0) {
sampledata.msi.submissionIdentifier = "GSB-"+getNewSubID();
} else if (!sampledata.msi.submissionIdentifier.matches("^GSB-[1-9][0-9]*$")) {
return getErrorOutcome("Submission identifier invalid", "Submission identifier must match regular expression ^GSB-[1-9][0-9]*$");
}
}
File subdir = SampleTabUtils.getSubmissionDirFile(sampledata.msi.submissionIdentifier);
subdir = new File(path.toString(), subdir.toString());
File outFile = new File(subdir, "sampletab.pre.txt");
//assign accessions to sampletab object
synchronized(accessioner) {
sampledata = accessioner.convert(sampledata);
}
//correct errors
synchronized(corrector) {
corrector.correct(sampledata);
}
SampleTabWriter writer = null;
try {
if (!subdir.exists() && !subdir.mkdirs()) {
throw new IOException("Unable to create parent directories");
}
writer = new SampleTabWriter(new BufferedWriter(new FileWriter(outFile)));
writer.write(sampledata);
} catch (IOException e) {
log.error("Problem writing to "+outFile, e);
return getErrorOutcome("Unable to store submission", "Retry later or contact [email protected] if this error persists");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
//do nothing
}
}
}
//return the submitted file, and any generated errors
return new Outcome(sampledata, errorItems);
} catch (Exception e) {
//general catch all for other errors, e.g SQL, IO
log.error("Unrecognized error", e);
return getErrorOutcome("Unknown error", "Contact [email protected] for assistance");
}
}
|
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java
index c08c2531..da3b1fe8 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java
@@ -1,405 +1,408 @@
/**
* 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.hive.ql.optimizer.ppr;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluator;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.GraphWalker;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.NodeProcessor;
import org.apache.hadoop.hive.ql.lib.Rule;
import org.apache.hadoop.hive.ql.lib.RuleRegExp;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.optimizer.Transform;
import org.apache.hadoop.hive.ql.parse.ErrorMsg;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.PrunedPartitionList;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPAnd;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.thrift.TException;
/**
* The transformation step that does partition pruning.
*
*/
public class PartitionPruner implements Transform {
// The log
private static final Log LOG = LogFactory
.getLog("hive.ql.optimizer.ppr.PartitionPruner");
/*
* (non-Javadoc)
*
* @see
* org.apache.hadoop.hive.ql.optimizer.Transform#transform(org.apache.hadoop
* .hive.ql.parse.ParseContext)
*/
@Override
public ParseContext transform(ParseContext pctx) throws SemanticException {
// create a the context for walking operators
OpWalkerCtx opWalkerCtx = new OpWalkerCtx(pctx.getOpToPartPruner());
Map<Rule, NodeProcessor> opRules = new LinkedHashMap<Rule, NodeProcessor>();
opRules.put(new RuleRegExp("R1", "(TS%FIL%)|(TS%FIL%FIL%)"), OpProcFactory
.getFilterProc());
// The dispatcher fires the processor corresponding to the closest matching
// rule and passes the context along
Dispatcher disp = new DefaultRuleDispatcher(OpProcFactory.getDefaultProc(),
opRules, opWalkerCtx);
GraphWalker ogw = new DefaultGraphWalker(disp);
// Create a list of topop nodes
ArrayList<Node> topNodes = new ArrayList<Node>();
topNodes.addAll(pctx.getTopOps().values());
ogw.startWalking(topNodes, null);
pctx.setHasNonPartCols(opWalkerCtx.getHasNonPartCols());
return pctx;
}
/**
* Find out whether the condition only contains partitioned columns. Note that
* if the table is not partitioned, the function always returns true.
* condition.
*
* @param tab
* the table object
* @param expr
* the pruner expression for the table
*/
public static boolean onlyContainsPartnCols(Table tab, ExprNodeDesc expr) {
if (!tab.isPartitioned() || (expr == null)) {
return true;
}
if (expr instanceof ExprNodeColumnDesc) {
String colName = ((ExprNodeColumnDesc) expr).getColumn();
return tab.isPartitionKey(colName);
}
// It cannot contain a non-deterministic function
if ((expr instanceof ExprNodeGenericFuncDesc)
&& !FunctionRegistry.isDeterministic(((ExprNodeGenericFuncDesc) expr)
.getGenericUDF())) {
return false;
}
// All columns of the expression must be parttioned columns
List<ExprNodeDesc> children = expr.getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
if (!onlyContainsPartnCols(tab, children.get(i))) {
return false;
}
}
}
return true;
}
/**
* Get the partition list for the table that satisfies the partition pruner
* condition.
*
* @param tab
* the table object for the alias
* @param prunerExpr
* the pruner expression for the alias
* @param conf
* for checking whether "strict" mode is on.
* @param alias
* for generating error message only.
* @return the partition list for the table that satisfies the partition
* pruner condition.
* @throws HiveException
*/
public static PrunedPartitionList prune(Table tab, ExprNodeDesc prunerExpr,
HiveConf conf, String alias,
Map<String, PrunedPartitionList> prunedPartitionsMap) throws HiveException {
LOG.trace("Started pruning partiton");
LOG.trace("dbname = " + tab.getDbName());
LOG.trace("tabname = " + tab.getTableName());
LOG.trace("prune Expression = " + prunerExpr);
String key = tab.getDbName() + "." + tab.getTableName() + ";";
if (prunerExpr != null) {
key = key + prunerExpr.getExprString();
}
PrunedPartitionList ret = prunedPartitionsMap.get(key);
if (ret != null) {
return ret;
}
LinkedHashSet<Partition> true_parts = new LinkedHashSet<Partition>();
LinkedHashSet<Partition> unkn_parts = new LinkedHashSet<Partition>();
LinkedHashSet<Partition> denied_parts = new LinkedHashSet<Partition>();
try {
StructObjectInspector rowObjectInspector = (StructObjectInspector) tab
.getDeserializer().getObjectInspector();
Object[] rowWithPart = new Object[2];
if (tab.isPartitioned()) {
// If the "strict" mode is on, we have to provide partition pruner for
// each table.
if ("strict".equalsIgnoreCase(HiveConf.getVar(conf,
HiveConf.ConfVars.HIVEMAPREDMODE))) {
if (!hasColumnExpr(prunerExpr)) {
throw new SemanticException(ErrorMsg.NO_PARTITION_PREDICATE
.getMsg("for Alias \"" + alias + "\" Table \""
+ tab.getTableName() + "\""));
}
}
if (prunerExpr == null) {
- // add all partitions corresponding to the table
+ // This can happen when hive.mapred.mode=nonstrict and there is no predicates at all
+ // Add all partitions to the unknown_parts so that a MR job is generated.
true_parts.addAll(Hive.get().getPartitions(tab));
} else {
// remove non-partition columns
ExprNodeDesc compactExpr = prunerExpr.clone();
compactExpr = compactExpr(compactExpr);
LOG.debug("Filter w/ compacting: " +
((compactExpr != null) ? compactExpr.getExprString(): "null") +
"; filter w/o compacting: " +
((prunerExpr != null) ? prunerExpr.getExprString(): "null"));
if (compactExpr == null) {
- true_parts.addAll(Hive.get().getPartitions(tab));
+ // This could happen when hive.mapred.mode=nonstrict and all the predicates
+ // are on non-partition columns.
+ unkn_parts.addAll(Hive.get().getPartitions(tab));
} else if (Utilities.checkJDOPushDown(tab, compactExpr)) {
String filter = compactExpr.getExprString();
String oldFilter = prunerExpr.getExprString();
if (filter.equals(oldFilter)) {
// pruneExpr contains only partition columns
pruneByPushDown(tab, true_parts, filter);
} else {
// pruneExpr contains non-partition columns
pruneByPushDown(tab, unkn_parts, filter);
}
} else {
pruneBySequentialScan(tab, true_parts, unkn_parts, denied_parts, prunerExpr, rowObjectInspector);
}
}
LOG.debug("tabname = " + tab.getTableName() + " is partitioned");
} else {
true_parts.addAll(Hive.get().getPartitions(tab));
}
} catch (HiveException e) {
throw e;
} catch (Exception e) {
throw new HiveException(e);
}
// Now return the set of partitions
ret = new PrunedPartitionList(true_parts, unkn_parts, denied_parts);
prunedPartitionsMap.put(key, ret);
return ret;
}
/**
* Taking a partition pruning expression, remove the null operands.
* @param expr original partition pruning expression.
* @return partition pruning expression that only contains partition columns.
*/
static private ExprNodeDesc compactExpr(ExprNodeDesc expr) {
if (expr instanceof ExprNodeConstantDesc) {
if (((ExprNodeConstantDesc)expr).getValue() == null) {
return null;
} else {
return expr;
}
} else if (expr instanceof ExprNodeGenericFuncDesc) {
GenericUDF udf = ((ExprNodeGenericFuncDesc)expr).getGenericUDF();
if (udf instanceof GenericUDFOPAnd ||
udf instanceof GenericUDFOPOr) {
List<ExprNodeDesc> children = ((ExprNodeGenericFuncDesc)expr).getChildren();
ExprNodeDesc left = children.get(0);
children.set(0, compactExpr(left));
ExprNodeDesc right = children.get(1);
children.set(1, compactExpr(right));
if (children.get(0) == null && children.get(1) == null) {
return null;
} else if (children.get(0) == null) {
return children.get(1);
} else if (children.get(1) == null) {
return children.get(0);
}
}
return expr;
}
return expr;
}
/**
* Pruning partition using JDO filtering.
* @param tab the table containing the partitions.
* @param true_parts the resulting partitions.
* @param filter the SQL predicate that involves only partition columns
* @throws HiveException
* @throws MetaException
* @throws NoSuchObjectException
* @throws TException
*/
static private void pruneByPushDown(Table tab, Set<Partition> true_parts, String filter)
throws HiveException, MetaException, NoSuchObjectException, TException {
Hive db = Hive.get();
List<Partition> parts = db.getPartitionsByFilter(tab, filter);
true_parts.addAll(parts);
return;
}
/**
* Pruning partition by getting the partition names first and pruning using Hive expression
* evaluator.
* @param tab the table containing the partitions.
* @param true_parts the resulting partitions if the partition pruning expression only contains
* partition columns.
* @param unkn_parts the resulting partitions if the partition pruning expression that only contains
* non-partition columns.
* @param denied_parts pruned out partitions.
* @param prunerExpr the SQL predicate that involves partition columns.
* @param rowObjectInspector object inspector used by the evaluator
* @throws Exception
*/
static private void pruneBySequentialScan(Table tab, Set<Partition> true_parts, Set<Partition> unkn_parts,
Set<Partition> denied_parts, ExprNodeDesc prunerExpr, StructObjectInspector rowObjectInspector)
throws Exception {
List<String> trueNames = null;
List<String> unknNames = null;
Utilities.PerfLogBegin(LOG, "prune-listing");
List<String> partNames = Hive.get().getPartitionNames(tab.getDbName(),
tab.getTableName(), (short) -1);
List<FieldSchema> pCols = tab.getPartCols();
List<String> partCols = new ArrayList<String>(pCols.size());
List<String> values = new ArrayList<String>(pCols.size());
Object[] objectWithPart = new Object[2];
for (FieldSchema pCol : pCols) {
partCols.add(pCol.getName());
}
Map<PrimitiveObjectInspector, ExprNodeEvaluator> handle = PartExprEvalUtils.prepareExpr(
prunerExpr, partCols, rowObjectInspector);
for (String partName : partNames) {
// Set all the variables here
LinkedHashMap<String, String> partSpec = Warehouse
.makeSpecFromName(partName);
values.clear();
for (Map.Entry<String, String> kv: partSpec.entrySet()) {
values.add(kv.getValue());
}
objectWithPart[1] = values;
// evaluate the expression tree
Boolean r = (Boolean) PartExprEvalUtils.evaluateExprOnPart(handle, objectWithPart);
if (r == null) {
if (unknNames == null) {
unknNames = new LinkedList<String>();
}
unknNames.add(partName);
LOG.debug("retained unknown partition: " + partName);
} else if (Boolean.TRUE.equals(r)) {
if (trueNames == null) {
trueNames = new LinkedList<String>();
}
trueNames.add(partName);
LOG.debug("retained partition: " + partName);
}
}
Utilities.PerfLogEnd(LOG, "prune-listing");
Utilities.PerfLogBegin(LOG, "partition-retrieving");
if (trueNames != null) {
List<Partition> parts = Hive.get().getPartitionsByNames(tab, trueNames);
true_parts.addAll(parts);
}
if (unknNames != null) {
List<Partition> parts = Hive.get().getPartitionsByNames(tab, unknNames);
unkn_parts.addAll(parts);
}
Utilities.PerfLogEnd(LOG, "partition-retrieving");
}
/**
* Whether the expression contains a column node or not.
*/
public static boolean hasColumnExpr(ExprNodeDesc desc) {
// Return false for null
if (desc == null) {
return false;
}
// Return true for exprNodeColumnDesc
if (desc instanceof ExprNodeColumnDesc) {
return true;
}
// Return true in case one of the children is column expr.
List<ExprNodeDesc> children = desc.getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
if (hasColumnExpr(children.get(i))) {
return true;
}
}
}
// Return false otherwise
return false;
}
}
| false | true | public static PrunedPartitionList prune(Table tab, ExprNodeDesc prunerExpr,
HiveConf conf, String alias,
Map<String, PrunedPartitionList> prunedPartitionsMap) throws HiveException {
LOG.trace("Started pruning partiton");
LOG.trace("dbname = " + tab.getDbName());
LOG.trace("tabname = " + tab.getTableName());
LOG.trace("prune Expression = " + prunerExpr);
String key = tab.getDbName() + "." + tab.getTableName() + ";";
if (prunerExpr != null) {
key = key + prunerExpr.getExprString();
}
PrunedPartitionList ret = prunedPartitionsMap.get(key);
if (ret != null) {
return ret;
}
LinkedHashSet<Partition> true_parts = new LinkedHashSet<Partition>();
LinkedHashSet<Partition> unkn_parts = new LinkedHashSet<Partition>();
LinkedHashSet<Partition> denied_parts = new LinkedHashSet<Partition>();
try {
StructObjectInspector rowObjectInspector = (StructObjectInspector) tab
.getDeserializer().getObjectInspector();
Object[] rowWithPart = new Object[2];
if (tab.isPartitioned()) {
// If the "strict" mode is on, we have to provide partition pruner for
// each table.
if ("strict".equalsIgnoreCase(HiveConf.getVar(conf,
HiveConf.ConfVars.HIVEMAPREDMODE))) {
if (!hasColumnExpr(prunerExpr)) {
throw new SemanticException(ErrorMsg.NO_PARTITION_PREDICATE
.getMsg("for Alias \"" + alias + "\" Table \""
+ tab.getTableName() + "\""));
}
}
if (prunerExpr == null) {
// add all partitions corresponding to the table
true_parts.addAll(Hive.get().getPartitions(tab));
} else {
// remove non-partition columns
ExprNodeDesc compactExpr = prunerExpr.clone();
compactExpr = compactExpr(compactExpr);
LOG.debug("Filter w/ compacting: " +
((compactExpr != null) ? compactExpr.getExprString(): "null") +
"; filter w/o compacting: " +
((prunerExpr != null) ? prunerExpr.getExprString(): "null"));
if (compactExpr == null) {
true_parts.addAll(Hive.get().getPartitions(tab));
} else if (Utilities.checkJDOPushDown(tab, compactExpr)) {
String filter = compactExpr.getExprString();
String oldFilter = prunerExpr.getExprString();
if (filter.equals(oldFilter)) {
// pruneExpr contains only partition columns
pruneByPushDown(tab, true_parts, filter);
} else {
// pruneExpr contains non-partition columns
pruneByPushDown(tab, unkn_parts, filter);
}
} else {
pruneBySequentialScan(tab, true_parts, unkn_parts, denied_parts, prunerExpr, rowObjectInspector);
}
}
LOG.debug("tabname = " + tab.getTableName() + " is partitioned");
} else {
true_parts.addAll(Hive.get().getPartitions(tab));
}
} catch (HiveException e) {
throw e;
} catch (Exception e) {
throw new HiveException(e);
}
// Now return the set of partitions
ret = new PrunedPartitionList(true_parts, unkn_parts, denied_parts);
prunedPartitionsMap.put(key, ret);
return ret;
}
| public static PrunedPartitionList prune(Table tab, ExprNodeDesc prunerExpr,
HiveConf conf, String alias,
Map<String, PrunedPartitionList> prunedPartitionsMap) throws HiveException {
LOG.trace("Started pruning partiton");
LOG.trace("dbname = " + tab.getDbName());
LOG.trace("tabname = " + tab.getTableName());
LOG.trace("prune Expression = " + prunerExpr);
String key = tab.getDbName() + "." + tab.getTableName() + ";";
if (prunerExpr != null) {
key = key + prunerExpr.getExprString();
}
PrunedPartitionList ret = prunedPartitionsMap.get(key);
if (ret != null) {
return ret;
}
LinkedHashSet<Partition> true_parts = new LinkedHashSet<Partition>();
LinkedHashSet<Partition> unkn_parts = new LinkedHashSet<Partition>();
LinkedHashSet<Partition> denied_parts = new LinkedHashSet<Partition>();
try {
StructObjectInspector rowObjectInspector = (StructObjectInspector) tab
.getDeserializer().getObjectInspector();
Object[] rowWithPart = new Object[2];
if (tab.isPartitioned()) {
// If the "strict" mode is on, we have to provide partition pruner for
// each table.
if ("strict".equalsIgnoreCase(HiveConf.getVar(conf,
HiveConf.ConfVars.HIVEMAPREDMODE))) {
if (!hasColumnExpr(prunerExpr)) {
throw new SemanticException(ErrorMsg.NO_PARTITION_PREDICATE
.getMsg("for Alias \"" + alias + "\" Table \""
+ tab.getTableName() + "\""));
}
}
if (prunerExpr == null) {
// This can happen when hive.mapred.mode=nonstrict and there is no predicates at all
// Add all partitions to the unknown_parts so that a MR job is generated.
true_parts.addAll(Hive.get().getPartitions(tab));
} else {
// remove non-partition columns
ExprNodeDesc compactExpr = prunerExpr.clone();
compactExpr = compactExpr(compactExpr);
LOG.debug("Filter w/ compacting: " +
((compactExpr != null) ? compactExpr.getExprString(): "null") +
"; filter w/o compacting: " +
((prunerExpr != null) ? prunerExpr.getExprString(): "null"));
if (compactExpr == null) {
// This could happen when hive.mapred.mode=nonstrict and all the predicates
// are on non-partition columns.
unkn_parts.addAll(Hive.get().getPartitions(tab));
} else if (Utilities.checkJDOPushDown(tab, compactExpr)) {
String filter = compactExpr.getExprString();
String oldFilter = prunerExpr.getExprString();
if (filter.equals(oldFilter)) {
// pruneExpr contains only partition columns
pruneByPushDown(tab, true_parts, filter);
} else {
// pruneExpr contains non-partition columns
pruneByPushDown(tab, unkn_parts, filter);
}
} else {
pruneBySequentialScan(tab, true_parts, unkn_parts, denied_parts, prunerExpr, rowObjectInspector);
}
}
LOG.debug("tabname = " + tab.getTableName() + " is partitioned");
} else {
true_parts.addAll(Hive.get().getPartitions(tab));
}
} catch (HiveException e) {
throw e;
} catch (Exception e) {
throw new HiveException(e);
}
// Now return the set of partitions
ret = new PrunedPartitionList(true_parts, unkn_parts, denied_parts);
prunedPartitionsMap.put(key, ret);
return ret;
}
|
diff --git a/org.eclipse.jubula.tools/src/org/eclipse/jubula/tools/i18n/I18n.java b/org.eclipse.jubula.tools/src/org/eclipse/jubula/tools/i18n/I18n.java
index a5c411bcf..830173500 100644
--- a/org.eclipse.jubula.tools/src/org/eclipse/jubula/tools/i18n/I18n.java
+++ b/org.eclipse.jubula.tools/src/org/eclipse/jubula/tools/i18n/I18n.java
@@ -1,120 +1,120 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 BREDEX GmbH.
* 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:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.tools.i18n;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jubula.tools.constants.StringConstants;
/**
* @author BREDEX GmbH
* @created 08.09.2004
*/
public class I18n {
/** the logger */
private static Log log = LogFactory.getLog(I18n.class);
/**
* Name of the Bundle.
*/
private static final String BUNDLE_NAME = "org.eclipse.jubula.tools.i18n.guidancerStrings"; //$NON-NLS-1$
/**
* Resource bundle, contains locale-specific objects.
*/
private static ResourceBundle resourceBundle = null;
static {
try {
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
} catch (MissingResourceException mre) {
log.error("Cannot find I18N-resource bundle!"); //$NON-NLS-1$
}
}
/**
* Constructor
*/
private I18n() {
// private constructor to prevent instantiation of class utitlity
}
/**
* Gets the internationalized String by a given key.
*
* @param key
* the key for the internationalized String.
* @return a internationalized <code>String</code>.
*/
public static String getString(String key) {
return getString(key, true);
}
/**
* Gets the internationalized String by a given key.
*
* @param key
* the key for the internationalized String.
* @param fallBack
* returns the key if no value found
* @return a internationalized <code>String</code>.
*/
public static String getString(String key, boolean fallBack) {
if (key == null) {
return StringConstants.EMPTY;
}
if (StringConstants.EMPTY.equals(key)) {
return key;
}
String str = StringConstants.EMPTY;
try {
str = resourceBundle.getString(key);
} catch (MissingResourceException mre) {
if (fallBack) {
return key;
}
}
return str;
}
/**
* returns an internationalized string for the given key
*
* @param key
* the key
* @param args
* the arguments needed to generate the string
* @return the internationalized string
*/
public static String getString(String key, Object[] args) {
if (StringConstants.EMPTY.equals(key)) {
return key;
}
try {
MessageFormat formatter = new MessageFormat(
resourceBundle.getString(key));
return formatter.format(args);
} catch (MissingResourceException e) {
log.error(e.toString());
StringBuffer buf = new StringBuffer(key);
- for (int i = 0; i < args.length; i++) {
+ for (int i = 0; args != null && i < args.length; i++) {
if (args[i] != null) {
- buf.append(" "); //$NON-NLS-1$
+ buf.append(StringConstants.SPACE);
buf.append(args[i]);
}
}
return buf.toString();
}
}
}
| false | true | public static String getString(String key, Object[] args) {
if (StringConstants.EMPTY.equals(key)) {
return key;
}
try {
MessageFormat formatter = new MessageFormat(
resourceBundle.getString(key));
return formatter.format(args);
} catch (MissingResourceException e) {
log.error(e.toString());
StringBuffer buf = new StringBuffer(key);
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(args[i]);
}
}
return buf.toString();
}
}
| public static String getString(String key, Object[] args) {
if (StringConstants.EMPTY.equals(key)) {
return key;
}
try {
MessageFormat formatter = new MessageFormat(
resourceBundle.getString(key));
return formatter.format(args);
} catch (MissingResourceException e) {
log.error(e.toString());
StringBuffer buf = new StringBuffer(key);
for (int i = 0; args != null && i < args.length; i++) {
if (args[i] != null) {
buf.append(StringConstants.SPACE);
buf.append(args[i]);
}
}
return buf.toString();
}
}
|
diff --git a/library/src/com/cyrilmottier/polaris2/maps/model/UrlTileProvider.java b/library/src/com/cyrilmottier/polaris2/maps/model/UrlTileProvider.java
index 7c915cb..727729a 100644
--- a/library/src/com/cyrilmottier/polaris2/maps/model/UrlTileProvider.java
+++ b/library/src/com/cyrilmottier/polaris2/maps/model/UrlTileProvider.java
@@ -1,44 +1,44 @@
/*
* Copyright (C) 2013 Cyril Mottier (http://cyrilmottier.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyrilmottier.polaris2.maps.model;
import java.net.URL;
public abstract class UrlTileProvider implements TileProvider {
final com.google.android.gms.maps.model.UrlTileProvider mOriginal;
public UrlTileProvider(int width, int height) {
mOriginal = new com.google.android.gms.maps.model.UrlTileProvider(width, height) {
@Override
public URL getTileUrl(int x, int y, int zoom) {
return innerGetTileUrl(x, y, zoom);
}
private URL innerGetTileUrl(int x, int y, int zoom) {
- return getTileUrl(x, y, zoom);
+ return UrlTileProvider.this.getTileUrl(x, y, zoom);
}
};
}
@Override
public final Tile getTile(int x, int y, int zoom) {
return new Tile(mOriginal.getTile(x, y, zoom));
}
public abstract URL getTileUrl(int x, int y, int zoom);
}
| true | true | public UrlTileProvider(int width, int height) {
mOriginal = new com.google.android.gms.maps.model.UrlTileProvider(width, height) {
@Override
public URL getTileUrl(int x, int y, int zoom) {
return innerGetTileUrl(x, y, zoom);
}
private URL innerGetTileUrl(int x, int y, int zoom) {
return getTileUrl(x, y, zoom);
}
};
}
| public UrlTileProvider(int width, int height) {
mOriginal = new com.google.android.gms.maps.model.UrlTileProvider(width, height) {
@Override
public URL getTileUrl(int x, int y, int zoom) {
return innerGetTileUrl(x, y, zoom);
}
private URL innerGetTileUrl(int x, int y, int zoom) {
return UrlTileProvider.this.getTileUrl(x, y, zoom);
}
};
}
|
diff --git a/src/main/java/com/eli/web/action/MainSearch.java b/src/main/java/com/eli/web/action/MainSearch.java
index c5993a9..80e9d76 100644
--- a/src/main/java/com/eli/web/action/MainSearch.java
+++ b/src/main/java/com/eli/web/action/MainSearch.java
@@ -1,231 +1,237 @@
package com.eli.web.action;
import com.eli.index.controller.CacheMemberDao;
import com.eli.index.controller.Member;
import com.eli.index.document.DiscussionDoc;
import com.eli.index.manager.MultiNRTSearcherAgent;
import com.eli.index.manager.ZhihuIndexManager;
import com.eli.web.BasicAction;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.util.Version;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class MainSearch extends BasicAction {
private static final Logger logger = Logger.getLogger(MainSearch.class);
private static Analyzer analyzer= new CJKAnalyzer(Version.LUCENE_36);
private CacheMemberDao memberDao = CacheMemberDao.INSTANCE;
private DateFormat weiredFormat = new SimpleDateFormat("yyyyMMddHHmmss");
private DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
protected void execute() throws IOException {
String token = super.getParam("q", "");
String avatar_url = null;
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "10"));
int _type = Integer.parseInt(super.getParam("type", "0"));
String adv = super.getParam("adv", "no");
String author = super.getParam("author", "").trim();
String reply = super.getParam("reply", "no");
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("type", _type);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = new TermQuery(new Term("content.NGRAM", ""));
Query sub1 = new TermQuery(new Term("title.NGRAM", ""));
if (token.trim().length() != 0) {
sub = qp.parse(token);
sub1 = qp1.parse(token);
}
Query sub2 = new TermQuery(new Term("name.None", token));
BooleanQuery query = new BooleanQuery();
if (_type == 0) {
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
query.add(sub2, BooleanClause.Occur.SHOULD);
if (adv.equals("yes") && author.length() > 0) {
int memberId = getMemberId(author);
if (memberId > 0) {
TermQuery specialNameQuery = new TermQuery(new Term("author.None", memberId + ""));
BooleanQuery tmpQuery = new BooleanQuery();
tmpQuery.add(specialNameQuery, BooleanClause.Occur.MUST);
if (token.trim().length() > 0)
tmpQuery.add(query, BooleanClause.Occur.MUST);
query = tmpQuery;
}
}
if (adv.equals("no") || (adv.equals("yes") && reply.equals("no"))) {
BooleanQuery tmpQuery = new BooleanQuery();
- TermQuery filterQuery = new TermQuery(new Term("seqOfThread.None", "0"));
+ TermQuery filterQuery1 = new TermQuery(new Term("seqOfThread.None", "0"));
+ TermQuery filterQuery2 = new TermQuery(new Term("type.None", "topic"));
+ TermQuery filterQuery3 = new TermQuery(new Term("type.None", "member"));
+ BooleanQuery filterQuery = new BooleanQuery();
+ filterQuery.add(filterQuery1, BooleanClause.Occur.SHOULD);
+ filterQuery.add(filterQuery2, BooleanClause.Occur.SHOULD);
+ filterQuery.add(filterQuery3, BooleanClause.Occur.SHOULD);
tmpQuery.add(filterQuery, BooleanClause.Occur.MUST);
tmpQuery.add(query, BooleanClause.Occur.MUST);
query = tmpQuery;
}
} else {
Query sub3 = new TermQuery(new Term("type.None", _type == 1 ? "topic" : "member"));
BooleanQuery sub4 = new BooleanQuery();
sub4.add(sub, BooleanClause.Occur.SHOULD);
sub4.add(sub1, BooleanClause.Occur.SHOULD);
sub4.add(sub2, BooleanClause.Occur.SHOULD);
query.add(sub3, BooleanClause.Occur.MUST);
query.add(sub4, BooleanClause.Occur.MUST);
}
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"search-red\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer, 60));
super.put("total", hits.totalHits);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
String type = doc.get("type.None");
Map<String,Object> map = new HashMap<String, Object>();
if (type.equals("member")) {
content = "以琳用户";
title = doc.get("name.None");
avatar_url = doc.get("avatar.None");
if (avatar_url == null || avatar_url.length() == 0)
avatar_url = "http://new.elimautism.org/images/face/0003.gif";
} else {
if (title == null)
title = "";
if (content == null)
content = "";
String hContent = getFragmentsWithHighlightedTerms(analyzer, query, "content.NGRAM", content,10, 70);
String hTitle = getFragmentsWithHighlightedTerms(analyzer, query, "title.NGRAM", title, 10, 200);
logger.info(hTitle);
logger.info(hContent);
if (hTitle == null && title.length() == 0)
hTitle = "无标题";
else if(hTitle == null)
hTitle = title.substring(0, Math.min(25, title.length()));
if (hContent == null && (content == null || content.length() == 0))
hContent = "无内容";
else if(hContent == null)
hContent = content.substring(0, Math.min(80, content.length()));
if (type.equals("topic"))
hTitle = "论坛板块:" + hTitle;
content = hContent;
title = hTitle;
avatar_url = null;
if (type.equals("discussion")) {
DiscussionDoc discussion = new DiscussionDoc(doc);
map.put("created", formatWeiredDate(discussion.getDate()));
map.put("hits", discussion.getHits());
Member member = memberDao.getMember(discussion.author);
if (member != null) {
map.put("author_name", member.getName());
map.put("author_url", member.getUrl());
} else {
map.put("author_name", "以琳用户");
map.put("author_url", "#");
}
}
}
String url = doc.get("url.None");
map.put("content", content);
map.put("title", title);
map.put("url", url);
map.put("type", type);
if (avatar_url != null)
map.put("avatar", avatar_url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("reply", reply);
super.put("author", author);
super.put("adv", adv);
super.put("ret", ret);
}
public static String getFragmentsWithHighlightedTerms(Analyzer analyzer, Query query,
String fieldName, String fieldContents, int fragmentNumber, int fragmentSize) throws IOException, InvalidTokenOffsetsException {
fieldContents = StringUtils.replaceEach(fieldContents, new String[]{"&", "\"", "<", ">"}, new String[]{"&", """, "<", ">"});
TokenStream stream = TokenSources.getTokenStream(fieldName, fieldContents, analyzer);
QueryScorer scorer = new QueryScorer(query);
Fragmenter fragmenter = new SimpleSpanFragmenter(scorer, fragmentSize);
// Highlighter highlighter = new Highlighter(scorer);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"search-red\">", "</span>"), scorer);
highlighter.setTextFragmenter(fragmenter);
highlighter.setMaxDocCharsToAnalyze(Integer.MAX_VALUE);
String fragments = highlighter.getBestFragment(stream, fieldContents);
return fragments;
}
public String formatWeiredDate(String wd) {
try {
Date date = weiredFormat.parse(wd);
wd = format.format(date);
} catch (Exception e) {
logger.error(e);
} finally {
return wd;
}
}
public int getMemberId(String query) {
if (query != null) {
query = query.trim();
return memberDao.getMemberId(query);
}
return 0;
}
}
| true | true | protected void execute() throws IOException {
String token = super.getParam("q", "");
String avatar_url = null;
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "10"));
int _type = Integer.parseInt(super.getParam("type", "0"));
String adv = super.getParam("adv", "no");
String author = super.getParam("author", "").trim();
String reply = super.getParam("reply", "no");
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("type", _type);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = new TermQuery(new Term("content.NGRAM", ""));
Query sub1 = new TermQuery(new Term("title.NGRAM", ""));
if (token.trim().length() != 0) {
sub = qp.parse(token);
sub1 = qp1.parse(token);
}
Query sub2 = new TermQuery(new Term("name.None", token));
BooleanQuery query = new BooleanQuery();
if (_type == 0) {
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
query.add(sub2, BooleanClause.Occur.SHOULD);
if (adv.equals("yes") && author.length() > 0) {
int memberId = getMemberId(author);
if (memberId > 0) {
TermQuery specialNameQuery = new TermQuery(new Term("author.None", memberId + ""));
BooleanQuery tmpQuery = new BooleanQuery();
tmpQuery.add(specialNameQuery, BooleanClause.Occur.MUST);
if (token.trim().length() > 0)
tmpQuery.add(query, BooleanClause.Occur.MUST);
query = tmpQuery;
}
}
if (adv.equals("no") || (adv.equals("yes") && reply.equals("no"))) {
BooleanQuery tmpQuery = new BooleanQuery();
TermQuery filterQuery = new TermQuery(new Term("seqOfThread.None", "0"));
tmpQuery.add(filterQuery, BooleanClause.Occur.MUST);
tmpQuery.add(query, BooleanClause.Occur.MUST);
query = tmpQuery;
}
} else {
Query sub3 = new TermQuery(new Term("type.None", _type == 1 ? "topic" : "member"));
BooleanQuery sub4 = new BooleanQuery();
sub4.add(sub, BooleanClause.Occur.SHOULD);
sub4.add(sub1, BooleanClause.Occur.SHOULD);
sub4.add(sub2, BooleanClause.Occur.SHOULD);
query.add(sub3, BooleanClause.Occur.MUST);
query.add(sub4, BooleanClause.Occur.MUST);
}
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"search-red\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer, 60));
super.put("total", hits.totalHits);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
String type = doc.get("type.None");
Map<String,Object> map = new HashMap<String, Object>();
if (type.equals("member")) {
content = "以琳用户";
title = doc.get("name.None");
avatar_url = doc.get("avatar.None");
if (avatar_url == null || avatar_url.length() == 0)
avatar_url = "http://new.elimautism.org/images/face/0003.gif";
} else {
if (title == null)
title = "";
if (content == null)
content = "";
String hContent = getFragmentsWithHighlightedTerms(analyzer, query, "content.NGRAM", content,10, 70);
String hTitle = getFragmentsWithHighlightedTerms(analyzer, query, "title.NGRAM", title, 10, 200);
logger.info(hTitle);
logger.info(hContent);
if (hTitle == null && title.length() == 0)
hTitle = "无标题";
else if(hTitle == null)
hTitle = title.substring(0, Math.min(25, title.length()));
if (hContent == null && (content == null || content.length() == 0))
hContent = "无内容";
else if(hContent == null)
hContent = content.substring(0, Math.min(80, content.length()));
if (type.equals("topic"))
hTitle = "论坛板块:" + hTitle;
content = hContent;
title = hTitle;
avatar_url = null;
if (type.equals("discussion")) {
DiscussionDoc discussion = new DiscussionDoc(doc);
map.put("created", formatWeiredDate(discussion.getDate()));
map.put("hits", discussion.getHits());
Member member = memberDao.getMember(discussion.author);
if (member != null) {
map.put("author_name", member.getName());
map.put("author_url", member.getUrl());
} else {
map.put("author_name", "以琳用户");
map.put("author_url", "#");
}
}
}
String url = doc.get("url.None");
map.put("content", content);
map.put("title", title);
map.put("url", url);
map.put("type", type);
if (avatar_url != null)
map.put("avatar", avatar_url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("reply", reply);
super.put("author", author);
super.put("adv", adv);
super.put("ret", ret);
}
| protected void execute() throws IOException {
String token = super.getParam("q", "");
String avatar_url = null;
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "10"));
int _type = Integer.parseInt(super.getParam("type", "0"));
String adv = super.getParam("adv", "no");
String author = super.getParam("author", "").trim();
String reply = super.getParam("reply", "no");
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("type", _type);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = new TermQuery(new Term("content.NGRAM", ""));
Query sub1 = new TermQuery(new Term("title.NGRAM", ""));
if (token.trim().length() != 0) {
sub = qp.parse(token);
sub1 = qp1.parse(token);
}
Query sub2 = new TermQuery(new Term("name.None", token));
BooleanQuery query = new BooleanQuery();
if (_type == 0) {
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
query.add(sub2, BooleanClause.Occur.SHOULD);
if (adv.equals("yes") && author.length() > 0) {
int memberId = getMemberId(author);
if (memberId > 0) {
TermQuery specialNameQuery = new TermQuery(new Term("author.None", memberId + ""));
BooleanQuery tmpQuery = new BooleanQuery();
tmpQuery.add(specialNameQuery, BooleanClause.Occur.MUST);
if (token.trim().length() > 0)
tmpQuery.add(query, BooleanClause.Occur.MUST);
query = tmpQuery;
}
}
if (adv.equals("no") || (adv.equals("yes") && reply.equals("no"))) {
BooleanQuery tmpQuery = new BooleanQuery();
TermQuery filterQuery1 = new TermQuery(new Term("seqOfThread.None", "0"));
TermQuery filterQuery2 = new TermQuery(new Term("type.None", "topic"));
TermQuery filterQuery3 = new TermQuery(new Term("type.None", "member"));
BooleanQuery filterQuery = new BooleanQuery();
filterQuery.add(filterQuery1, BooleanClause.Occur.SHOULD);
filterQuery.add(filterQuery2, BooleanClause.Occur.SHOULD);
filterQuery.add(filterQuery3, BooleanClause.Occur.SHOULD);
tmpQuery.add(filterQuery, BooleanClause.Occur.MUST);
tmpQuery.add(query, BooleanClause.Occur.MUST);
query = tmpQuery;
}
} else {
Query sub3 = new TermQuery(new Term("type.None", _type == 1 ? "topic" : "member"));
BooleanQuery sub4 = new BooleanQuery();
sub4.add(sub, BooleanClause.Occur.SHOULD);
sub4.add(sub1, BooleanClause.Occur.SHOULD);
sub4.add(sub2, BooleanClause.Occur.SHOULD);
query.add(sub3, BooleanClause.Occur.MUST);
query.add(sub4, BooleanClause.Occur.MUST);
}
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"search-red\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer, 60));
super.put("total", hits.totalHits);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
String type = doc.get("type.None");
Map<String,Object> map = new HashMap<String, Object>();
if (type.equals("member")) {
content = "以琳用户";
title = doc.get("name.None");
avatar_url = doc.get("avatar.None");
if (avatar_url == null || avatar_url.length() == 0)
avatar_url = "http://new.elimautism.org/images/face/0003.gif";
} else {
if (title == null)
title = "";
if (content == null)
content = "";
String hContent = getFragmentsWithHighlightedTerms(analyzer, query, "content.NGRAM", content,10, 70);
String hTitle = getFragmentsWithHighlightedTerms(analyzer, query, "title.NGRAM", title, 10, 200);
logger.info(hTitle);
logger.info(hContent);
if (hTitle == null && title.length() == 0)
hTitle = "无标题";
else if(hTitle == null)
hTitle = title.substring(0, Math.min(25, title.length()));
if (hContent == null && (content == null || content.length() == 0))
hContent = "无内容";
else if(hContent == null)
hContent = content.substring(0, Math.min(80, content.length()));
if (type.equals("topic"))
hTitle = "论坛板块:" + hTitle;
content = hContent;
title = hTitle;
avatar_url = null;
if (type.equals("discussion")) {
DiscussionDoc discussion = new DiscussionDoc(doc);
map.put("created", formatWeiredDate(discussion.getDate()));
map.put("hits", discussion.getHits());
Member member = memberDao.getMember(discussion.author);
if (member != null) {
map.put("author_name", member.getName());
map.put("author_url", member.getUrl());
} else {
map.put("author_name", "以琳用户");
map.put("author_url", "#");
}
}
}
String url = doc.get("url.None");
map.put("content", content);
map.put("title", title);
map.put("url", url);
map.put("type", type);
if (avatar_url != null)
map.put("avatar", avatar_url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("reply", reply);
super.put("author", author);
super.put("adv", adv);
super.put("ret", ret);
}
|
diff --git a/cipango-sip/src/main/java/org/cipango/sip/SipGenerator.java b/cipango-sip/src/main/java/org/cipango/sip/SipGenerator.java
index efc9166..10da78d 100644
--- a/cipango-sip/src/main/java/org/cipango/sip/SipGenerator.java
+++ b/cipango-sip/src/main/java/org/cipango/sip/SipGenerator.java
@@ -1,128 +1,129 @@
package org.cipango.sip;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.Set;
import javax.servlet.sip.SipServletMessage.HeaderForm;
import javax.servlet.sip.URI;
import org.cipango.util.StringUtil;
import static org.cipango.sip.SipHeader.*;
public class SipGenerator
{
private Set<SipHeader> _fixedHeaders = EnumSet.of(VIA, FROM, TO, CALL_ID);
public void generateRequest(ByteBuffer buffer, String method, URI requestUri, SipFields sipFields, byte[] content, HeaderForm headerForm)
{
generateRequestLine(buffer, method, requestUri);
generateHeaders(buffer, sipFields, headerForm);
if (content != null)
buffer.put(content);
}
public void generateResponse(ByteBuffer buffer, int status, String reason, SipFields sipFields, byte[] content, HeaderForm headerForm)
{
generateResponseLine(buffer, status, reason);
generateHeaders(buffer, sipFields, headerForm);
if (content != null)
buffer.put(content);
}
private void generateRequestLine(ByteBuffer buffer,String method, URI requestUri)
{
buffer.put(StringUtil.getUtf8Bytes(method));
buffer.put(SipGrammar.SPACE);
buffer.put(StringUtil.getUtf8Bytes(requestUri.toString()));
buffer.put(SipGrammar.SPACE);
buffer.put(SipVersion.SIP_2_0.toBuffer());
buffer.put(SipGrammar.CRLF);
}
private void generateResponseLine(ByteBuffer buffer, int status, String reason)
{
PreparedResponse prepared = status < __responses.length ? __responses[status] : null;
if (prepared != null)
{
if (reason == null)
buffer.put(prepared._responseLine);
else
{
buffer.put(prepared._schemeCode);
buffer.put(StringUtil.getBytes(reason, StringUtil.__UTF8));
buffer.put(SipGrammar.CRLF);
}
}
else
{
buffer.put(SipVersion.SIP_2_0.toBuffer());
buffer.put(SipGrammar.SPACE);
buffer.put((byte) ('0' + status / 100));
buffer.put((byte) ('0' + (status % 100) / 10));
buffer.put((byte) ('0' + (status % 10)));
buffer.put(SipGrammar.SPACE);
if (reason != null)
buffer.put(StringUtil.getBytes(reason, StringUtil.__UTF8));
+ buffer.put(SipGrammar.CRLF);
}
}
private void generateHeaders(ByteBuffer buffer, SipFields sipFields, HeaderForm headerForm)
{
if (sipFields != null)
{
for (SipFields.Field field : sipFields)
{
field.putTo(buffer, headerForm);
}
}
buffer.put(SipGrammar.CRLF);
}
private static class PreparedResponse
{
byte[] _reason;
byte[] _schemeCode;
byte[] _responseLine;
}
private static final PreparedResponse[] __responses = new PreparedResponse[SipStatus.MAX_CODE+1];
static
{
int versionLength = SipVersion.SIP_2_0.toString().length();
for (int i = 0; i < __responses.length; i++)
{
SipStatus status = SipStatus.get(i);
if (status == null)
continue;
String reason = status.getReason();
byte[] line = new byte[versionLength+5+reason.length()+2];
SipVersion.SIP_2_0.toBuffer().get(line, 0, versionLength);
line[versionLength+0] = ' ';
line[versionLength+1] = (byte) ('0' + i/100);
line[versionLength+2] = (byte) ('0' + (i%100) /10);
line[versionLength+3] = (byte) ('0' + (i%10));
line[versionLength+4] = ' ';
for (int j = 0; j < reason.length(); j++)
line[versionLength+5+j] = (byte) reason.charAt(j);
line[versionLength+5+reason.length()] = SipGrammar.CR;
line[versionLength+6+reason.length()] = SipGrammar.LF;
__responses[i] = new PreparedResponse();
__responses[i]._reason = new byte[line.length-versionLength-7];
System.arraycopy(line,versionLength+5,__responses[i]._reason,0,line.length-versionLength-7);
__responses[i]._schemeCode=new byte[versionLength+5];
System.arraycopy(line,0,__responses[i]._schemeCode,0,versionLength+5);
__responses[i]._responseLine=line;
}
}
public static void main(String[] args) {
}
}
| true | true | private void generateResponseLine(ByteBuffer buffer, int status, String reason)
{
PreparedResponse prepared = status < __responses.length ? __responses[status] : null;
if (prepared != null)
{
if (reason == null)
buffer.put(prepared._responseLine);
else
{
buffer.put(prepared._schemeCode);
buffer.put(StringUtil.getBytes(reason, StringUtil.__UTF8));
buffer.put(SipGrammar.CRLF);
}
}
else
{
buffer.put(SipVersion.SIP_2_0.toBuffer());
buffer.put(SipGrammar.SPACE);
buffer.put((byte) ('0' + status / 100));
buffer.put((byte) ('0' + (status % 100) / 10));
buffer.put((byte) ('0' + (status % 10)));
buffer.put(SipGrammar.SPACE);
if (reason != null)
buffer.put(StringUtil.getBytes(reason, StringUtil.__UTF8));
}
}
| private void generateResponseLine(ByteBuffer buffer, int status, String reason)
{
PreparedResponse prepared = status < __responses.length ? __responses[status] : null;
if (prepared != null)
{
if (reason == null)
buffer.put(prepared._responseLine);
else
{
buffer.put(prepared._schemeCode);
buffer.put(StringUtil.getBytes(reason, StringUtil.__UTF8));
buffer.put(SipGrammar.CRLF);
}
}
else
{
buffer.put(SipVersion.SIP_2_0.toBuffer());
buffer.put(SipGrammar.SPACE);
buffer.put((byte) ('0' + status / 100));
buffer.put((byte) ('0' + (status % 100) / 10));
buffer.put((byte) ('0' + (status % 10)));
buffer.put(SipGrammar.SPACE);
if (reason != null)
buffer.put(StringUtil.getBytes(reason, StringUtil.__UTF8));
buffer.put(SipGrammar.CRLF);
}
}
|
diff --git a/src/java/com/idega/presentation/ui/InterfaceObject.java b/src/java/com/idega/presentation/ui/InterfaceObject.java
index c3921b060..65c37c65e 100755
--- a/src/java/com/idega/presentation/ui/InterfaceObject.java
+++ b/src/java/com/idega/presentation/ui/InterfaceObject.java
@@ -1,613 +1,613 @@
//idega 2000 - Tryggvi Larusson
/*
*Copyright 2000 idega.is All Rights Reserved.
*/
package com.idega.presentation.ui;
import java.io.*;
import java.util.*;
import com.idega.presentation.*;
/**
*@author <a href="mailto:[email protected]">Tryggvi Larusson</a>
*@version 1.2
*/
public abstract class InterfaceObject extends PresentationObject {
protected boolean keepStatus;
private boolean _checkObject = false;
private boolean _disableObject = false;
private boolean _checkDisabled = false;
private boolean _inFocus = false;
private boolean _changeValue = false;
private boolean _selectValues = false;
public static final String ACTION_ON_BLUR = "onBlur";
public static final String ACTION_ON_CHANGE = "onChange";
public static final String ACTION_ON_CLICK = "onClick";
public static final String ACTION_ON_FOCUS = "onFocus";
public static final String ACTION_ON_KEY_DOWN = "onKeyDown";
public static final String ACTION_ON_KEY_UP = "onKeyUp";
public static final String ACTION_ON_SELECT = "onSelect";
public static final String ACTION_ON_SUBMIT = "onSubmit";
public InterfaceObject() {
super();
setID();
keepStatus = false;
}
/**
* Returns true if the interface object is enclosed by a form object.
* @return boolean
*/
protected boolean isEnclosedByForm() {
if (getForm() != null)
return true;
return false;
}
/**
* Returns true if the interface object in on a page.
* @return boolean
*/
protected boolean hasParentPage() {
if (getParentPage() != null)
return true;
return false;
}
/**
* Sets an action event to perform on this object.
* @param actionType The type of action.
* @param action The action to perform.
*/
private void setOnAction(String actionType, String action) {
setAttributeMultivalued(actionType, action);
}
/**
* Sets the action to perform when the interface object is on focus.
* @param action The action to perform.
*/
public void setOnFocus(String action) {
setOnAction(ACTION_ON_FOCUS, action);
}
/**
* Sets the action to perform when the interface object is set out of focus.
* @param action The action to perform.
*/
public void setOnBlur(String action) {
setOnAction(ACTION_ON_BLUR, action);
}
/**
* Sets the action to perform when the interface object is selected.
* @param action The action to perform.
*/
public void setOnSelect(String action) {
setOnAction(ACTION_ON_SELECT, action);
}
/**
* Sets the action to perform when the interface object is changed.
* @param action The action to perform.
*/
public void setOnChange(String action) {
setOnAction(ACTION_ON_CHANGE, action);
}
/**
* Sets the action to perform when the interface object is on clicked.
* @param action The action to perform.
*/
public void setOnClick(String action) {
setOnAction(ACTION_ON_CLICK, action);
}
/**
* Sets the action to perform when a key is pressed down in the interface object.
* @param action The action to perform.
*/
public void setOnKeyDown(String action) {
setOnAction(ACTION_ON_KEY_DOWN, action);
}
/**
* Sets the action to perform when a key is released in the interface object.
* @param action The action to perform.
*/
public void setOnKeyUp(String action) {
setOnAction(ACTION_ON_KEY_UP, action);
}
/**
* Returns the action to perform when the interface object is in focus.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnFocus() {
return getAttribute(ACTION_ON_FOCUS);
}
/**
* Returns the action to perform when the interface object is set out of focus.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnBlur() {
return getAttribute(ACTION_ON_BLUR);
}
/**
* Returns the action to perform when the interface object is in selected.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnSelect() {
return getAttribute(ACTION_ON_SELECT);
}
/**
* Returns the action to perform when the interface object is in changed.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnChange() {
return getAttribute(ACTION_ON_CHANGE);
}
/**
* Returns the action to perform when the interface object is in clicked.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnClick() {
return getAttribute(ACTION_ON_CLICK);
}
/**
* Returns the action to perform when a key is pressed down in the interface object.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnKeyDown() {
return getAttribute(ACTION_ON_KEY_DOWN);
}
/**
* Returns the action to perform when a key is released in the interface object.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnKeyUp() {
return getAttribute(ACTION_ON_KEY_UP);
}
/**
* Sets the value of the interface object.
* @param value The value to set.
*/
public void setValue(String value) {
setAttribute("value", value);
}
/**
* Sets the value of the interface object.
* @param value The value to set.
*/
public void setValue(int value) {
setValue(Integer.toString(value));
}
/**
* Sets the content (value) of the interface object.
* @param value The content to set.
*/
public void setContent(String content) {
setValue(content);
}
/**
* Returns the value set for the interface object.
* @return String The value set.
*/
public String getValue() {
if (isAttributeSet("value"))
return getAttribute("value");
return "";
}
/**
* Returns the content (value) set for the interface object.
* @return String The content set.
*/
public String getContent() {
return getValue();
}
/**
* Sets the action to perform when the parent form is submitted.
* @param action The action to perform.
*/
public void setOnSubmit(String action) {
setOnAction("onSubmit", action);
}
/**
* Returns the action to perform when the parent form is submitted.
* @return String The action to perform. Returns null if no action is set.
*/
public String getOnSubmit() {
return getAttribute("onSubmit");
}
/**
* Sets the given interface object(s) to be checked/unchecked when this object is
* clicked on.
* @param action The action to perform on.
* @param objectToCheck The interface object(s) to check.
* @param check Checks if boolean is true, unchecks otherwise.
*/
public void setToCheckOnAction(String action, String objectToCheck, boolean check) {
setToCheckOnAction(action, objectToCheck, check, true);
}
/**
* Sets the interface object(s) with the given name to be checked/unchecked when this
* object is clicked on.
* @param objectName The name of the interface object(s) to check.
* @param check Checks if boolean is true, unchecks otherwise.
*/
public void setToCheckOnClick(String objectName, boolean check) {
setToCheckOnAction(ACTION_ON_CLICK, objectName, check, true);
}
/**
* Sets the given interface object(s) to be checked/unchecked when this object is
* clicked on.
* @param objectToCheck The interface object(s) to check.
* @param check Checks if boolean is true, unchecks otherwise.
*/
public void setToCheckOnClick(InterfaceObject objectToCheck, boolean check) {
setToCheckOnAction(ACTION_ON_CLICK, objectToCheck.getName(), check, true);
}
/**
* Sets the interface object(s) with the given name to be checked/unchecked when this
* object receives the action specified.
* @param action The action to perform on.
* @param objectName The name of the interface object(s) to check.
* @param check Checks if boolean is true, unchecks otherwise.
* @param checkDisabled If true checks all, otherwise not disabled objects.
*/
public void setToCheckOnAction(String action, String objectName, boolean check, boolean checkDisabled) {
_checkObject = true;
_checkDisabled = checkDisabled;
if (checkDisabled)
setOnAction(action, "checkAllObjects(findObj('" + objectName + "'),'" + String.valueOf(check) + "')");
else
setOnAction(action, "checkEnabledObjects(findObj('" + objectName + "'),'" + String.valueOf(check) + "')");
}
/**
* Sets the interface object(s) with the given name to be checked/unchecked when this
* object is clicked on.
* @param objectName The name of the interface object(s) to check.
* @param check Checks if boolean is true, unchecks otherwise.
* @param checkDisabled If true checks all, otherwise not disabled objects.
*/
public void setToCheckOnClick(String objectName, boolean check, boolean checkDisabled) {
setToCheckOnAction(ACTION_ON_CLICK, objectName, check, checkDisabled);
}
/**
* Sets the given interface object(s) to be checked/unchecked when this object is
* clicked on.
* @param objectToCheck The interface object(s) to check.
* @param check Checks if boolean is true, unchecks otherwise.
* @param checkDisabled If true checks all, otherwise not disabled objects.
*/
public void setToCheckOnClick(InterfaceObject objectToCheck, boolean check, boolean checkDisabled) {
setToCheckOnAction(ACTION_ON_CLICK, objectToCheck.getName(), check, checkDisabled);
}
/**
* Sets the interface object(s) with the given name to be enabled when this object
* receives the action specified.
* @param action The action to perform on.
* @param objectToEnable The name of the interface object(s) to enable.
* @param enable Set to true to disable, false will enable.
*/
public void setToDisableOnAction(String action, String objectName, boolean disable) {
_disableObject = true;
setOnAction(action, "disableObject(findObj('" + objectName + "'),'" + String.valueOf(disable) + "')");
}
/**
* Sets the interface object(s) with the given name to be enabled when this object is
* clicked on.
* @param objectToEnable The name of the interface object(s) to enable.
* @param enable Set to true to disable, false will enable.
*/
public void setToDisableOnClick(String objectName, boolean disable) {
setToDisableOnAction(ACTION_ON_CLICK,objectName,disable);
}
/**
* Sets the given interface object to be enabled when this object is clicked on.
* @param objectToEnable The interface object to enable.
* @param enable Set to true to disable, false will enable.
*/
public void setToDisableOnClick(InterfaceObject objectToEnable, boolean disable) {
setToDisableOnClick(objectToEnable.getName(), disable);
}
/**
* Sets the value of the given interface object when this object receives the action
* specified.
* @param action The action to perform on.
* @param objectToChange The interface object to change value of.
* @param value The new value to set.
*/
public void setValueOnAction(String action, InterfaceObject objectToChange, String value) {
setValueOnAction(action, objectToChange.getName(), value);
}
/**
* Sets the value of the interface object with the given namewhen this object receives
* the action specified.
* @param action The action to perform on.
* @param objectName The name of the interface object to change value of.
* @param value The new value to set.
*/
public void setValueOnAction(String action, String objectName, String value) {
_changeValue = true;
setOnAction(action, "changeValue(findObj('"+objectName+"'),'"+value+"');");
}
/**
* Sets the value of the given interface object when this object is clicked.
* @param objectToChange The interface object to change value of.
* @param value The new value to set.
*/
public void setValueOnClick(InterfaceObject objectToChange, String value) {
setValueOnAction(ACTION_ON_CLICK, objectToChange.getName(), value);
}
/**
* Sets the value of the interface object with the given name when this object is clicked.
* @param objectName The name of the interface object to change value of.
* @param value The new value to set.
*/
public void setValueOnClick(String objectName, String value) {
setValueOnAction(ACTION_ON_CLICK, objectName, value);
}
/**
* Sets the given interface object as selected when this object receives the action
* specified.
* @param action The action to perform on.
* @param objectToChange The interface object to set selected value of.
* @param selected Set true to select, false otherwise.
*/
public void setSelectedOnAction(String action, InterfaceObject objectToChange, boolean selected) {
setSelectedOnAction(action, objectToChange.getName(), selected);
}
/**
* Sets the interface object with the given name as selected when this object receives
* the action specified.
* @param action The action to perform on.
* @param objectName The name of the interface object to set selected value of.
* @param selected Set true to select, false otherwise.
*/
public void setSelectedOnAction(String action, String objectName, boolean selected) {
_selectValues = true;
setOnAction(action, "selectValues(findObj('"+objectName+"'),'"+selected+"');");
}
/**
* Sets the interface object in focus on page load.
* @param inFocus Set to true to set focus on object, false otherwise.
*/
public void setInFocusOnPageLoad(boolean inFocus) {
_inFocus = inFocus;
}
/**
* Sets the interface object to submit its parent form on click.
* Must have a parent form to function correctly.
*/
public void setToSubmit() {
setOnClick("this.form.submit()");
}
/**
* Sets whether the interface object is disabled or not.
* @param disabled The status to set.
*/
public void setDisabled(boolean disabled) {
if (disabled)
setAttribute("disabled");
else
this.removeAttribute("disabled");
}
/**
* Returns the disabled status of the interface object.
* @return boolean True if object is disabled, false otherwise.
*/
public boolean getDisabled() {
if (isAttributeSet("disabled"))
return true;
return false;
}
/**
* Sets the description for the interface object.
* @param description The description to set.
*/
public void setDescription(String description) {
setAttribute("title", description);
}
/**
* Returns the description set to the interface object.
* @return String The description set, null otherwise.
*/
public String getDescription() {
if (isAttributeSet("title"))
return getAttribute("title");
return null;
}
/**
* A method that handles the actions to perform to keep the status of the interface
* object on performed actions. Override if interface object can keep its status on
* actions.
* @param iwc
*/
public abstract void handleKeepStatus(IWContext iwc);
/**
* Returns true if interface object is to keep its status when an action is performed.
* @return boolean True if status is kept, false otherwise.
*/
public boolean statusKeptOnAction() {
return keepStatus;
}
/**
* Sets to keep the status on the interface object when an action is performed.
* @param boolean True if interface object is to keep status, false otherwise.
*/
public void keepStatusOnAction(boolean keepStatus) {
this.keepStatus = keepStatus;
}
/**
* Sets to keep the status on the interface object when an action is performed.
*/
public void keepStatusOnAction() {
keepStatusOnAction(true);
}
public void _print(IWContext iwc) throws Exception {
if (statusKeptOnAction())
handleKeepStatus(iwc);
super._print(iwc);
}
public Object clone() {
InterfaceObject obj = null;
try {
obj = (InterfaceObject) super.clone();
obj.keepStatus = this.keepStatus;
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return obj;
}
public void _main(IWContext iwc) throws Exception {
super._main(iwc);
if (isEnclosedByForm()) {
if (_checkObject) {
if (_checkDisabled)
getScript().addFunction("checkAllObjects", "function checkAllObjects (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].checked=eval(value);\n \t}\n else\n \tinputs.checked=eval(value);\n}");
else
getScript().addFunction("checkEnabledObjects", "function checkEnabledObjects (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \tif ( inputs[i].disabled == false )\n \t\tinputs[i].checked=eval(value);\n \t}\n else\n \tif (inputs.disabled == false)\n \t\tinputs.checked=eval(value);\n}");
}
if (_disableObject) {
getScript().addFunction("disableObject", "function disableObject (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].disabled=eval(value);\n \t}\n else\n inputs.disabled=eval(value);\n}");
}
if (_changeValue) {
getScript().addFunction("changeValue", "function changeValue (input,newValue) {\n input.value=newValue;\n}");
}
if (_selectValues) {
- getScript().addFunction("selectValues", "function selectValues (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].selected=eval(value);\n \t}\n else\n \tinputs.selected=eval(value);\n}");
+ getScript().addFunction("selectValues", "function selectValues (inputs,value) {\n if (inputs.length > 0) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].selected=eval(value);\n }\n }");
}
}
if (_inFocus && hasParentPage()) {
getParentPage().setOnLoad("findObj('" + getName() + "').focus();");
}
}
/**
* Returns the <code>Script</code> associated with the parent <code>Form</code>. If the
* interface object has no parent form this method returns null.
* @return Script
*/
protected Script getScript() {
if ( getForm() != null ) {
if (getForm().getAssociatedFormScript() == null) {
getForm().setAssociatedFormScript(new Script());
}
return getForm().getAssociatedFormScript();
}
return null;
}
/**
* Returns the enclosing form, returns null if no form present.
* @return Form The form enclosing the interface object.
*/
public Form getForm() {
return getParentForm();
}
/**
* Sets the width of the interface object with a style tag.
* @param width The width to set.
*/
public void setWidth(String width) {
setWidthStyle(width);
}
/**
* Sets the height of the interface object with a style tag.
* @param height The height to set.
*/
public void setHeight(String height) {
setHeightStyle(height);
}
/**
* Sets the tab index for the interface object, that is the index for where in the tab
* row the object is in the parent form.
* @param index The index to set.
*/
public void setTabIndex(int index) {
setAttribute("tabindex", String.valueOf(index));
}
/**
* Returns the tab index set for the interface object. Returns -1 if no value is set.
* @return int
*/
public int getTabIndex() {
if (isAttributeSet("tabindex"))
return Integer.parseInt(getAttribute("tabindex"));
return -1;
}
/**
* Sets whether the interface object shall be read only or not.
* @param readOnly The boolean value to set.
*/
public void setReadOnly(boolean readOnly) {
if (readOnly)
setAttribute("readonly");
else
removeAttribute("readonly");
}
/**
* Returns true if interface object is set as read only, false otherwise.
* @return boolean
*/
public boolean getReadOnly() {
if (isAttributeSet("readonly"))
return true;
return false;
}
}
| true | true | public void _main(IWContext iwc) throws Exception {
super._main(iwc);
if (isEnclosedByForm()) {
if (_checkObject) {
if (_checkDisabled)
getScript().addFunction("checkAllObjects", "function checkAllObjects (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].checked=eval(value);\n \t}\n else\n \tinputs.checked=eval(value);\n}");
else
getScript().addFunction("checkEnabledObjects", "function checkEnabledObjects (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \tif ( inputs[i].disabled == false )\n \t\tinputs[i].checked=eval(value);\n \t}\n else\n \tif (inputs.disabled == false)\n \t\tinputs.checked=eval(value);\n}");
}
if (_disableObject) {
getScript().addFunction("disableObject", "function disableObject (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].disabled=eval(value);\n \t}\n else\n inputs.disabled=eval(value);\n}");
}
if (_changeValue) {
getScript().addFunction("changeValue", "function changeValue (input,newValue) {\n input.value=newValue;\n}");
}
if (_selectValues) {
getScript().addFunction("selectValues", "function selectValues (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].selected=eval(value);\n \t}\n else\n \tinputs.selected=eval(value);\n}");
}
}
if (_inFocus && hasParentPage()) {
getParentPage().setOnLoad("findObj('" + getName() + "').focus();");
}
}
| public void _main(IWContext iwc) throws Exception {
super._main(iwc);
if (isEnclosedByForm()) {
if (_checkObject) {
if (_checkDisabled)
getScript().addFunction("checkAllObjects", "function checkAllObjects (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].checked=eval(value);\n \t}\n else\n \tinputs.checked=eval(value);\n}");
else
getScript().addFunction("checkEnabledObjects", "function checkEnabledObjects (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \tif ( inputs[i].disabled == false )\n \t\tinputs[i].checked=eval(value);\n \t}\n else\n \tif (inputs.disabled == false)\n \t\tinputs.checked=eval(value);\n}");
}
if (_disableObject) {
getScript().addFunction("disableObject", "function disableObject (inputs,value) {\n if (inputs.length > 1) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].disabled=eval(value);\n \t}\n else\n inputs.disabled=eval(value);\n}");
}
if (_changeValue) {
getScript().addFunction("changeValue", "function changeValue (input,newValue) {\n input.value=newValue;\n}");
}
if (_selectValues) {
getScript().addFunction("selectValues", "function selectValues (inputs,value) {\n if (inputs.length > 0) {\n \tfor(var i=0;i<inputs.length;i++)\n \t\tinputs[i].selected=eval(value);\n }\n }");
}
}
if (_inFocus && hasParentPage()) {
getParentPage().setOnLoad("findObj('" + getName() + "').focus();");
}
}
|
diff --git a/E_EYE_O-RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/views/LoginView.java b/E_EYE_O-RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/views/LoginView.java
index c007d74..bef13ec 100644
--- a/E_EYE_O-RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/views/LoginView.java
+++ b/E_EYE_O-RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/views/LoginView.java
@@ -1,183 +1,182 @@
package com.jtbdevelopment.e_eye_o.ria.vaadin.views;
import com.jtbdevelopment.e_eye_o.DAO.ReadOnlyDAO;
import com.jtbdevelopment.e_eye_o.entities.AppUser;
import com.jtbdevelopment.e_eye_o.ria.vaadin.components.Logo;
import com.jtbdevelopment.e_eye_o.ria.vaadin.views.passwordreset.ResetRequest;
import com.jtbdevelopment.e_eye_o.ria.vaadin.views.registration.LegalView;
import com.vaadin.event.ShortcutAction;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.*;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.Runo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Date: 2/24/13
* Time: 8:24 PM
* <p/>
* Largely based on Spring Security Example by Nicolas Frankel at
* https://github.com/nfrankel/More-Vaadin/tree/master/springsecurity-integration
*/
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoginView extends VerticalLayout implements View {
public static final String VIEW_NAME = "Login";
private final TextField loginField = new TextField("Email Address");
private final PasswordField passwordField = new PasswordField("Password");
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private ReadOnlyDAO readOnlyDAO;
@Autowired
private PersistentTokenBasedRememberMeServices rememberMeServices;
@Autowired
private Logo logo;
@PostConstruct
public void PostConstruct() {
setSpacing(true);
setMargin(true);
setSizeFull();
Layout titleSection = getTitleSection();
addComponent(titleSection);
setComponentAlignment(titleSection, Alignment.MIDDLE_CENTER);
Layout loginSection = getLoginSection();
addComponent(loginSection);
setComponentAlignment(loginSection, Alignment.BOTTOM_CENTER);
Layout helpSection = getSignUpResetSection();
addComponent(helpSection);
setComponentAlignment(helpSection, Alignment.TOP_CENTER);
}
private Layout getLoginSection() {
VerticalLayout loginSection = new VerticalLayout();
FormLayout form = new FormLayout();
form.setWidth(null);
form.setHeight(null);
loginSection.addComponent(form);
loginSection.setComponentAlignment(form, Alignment.MIDDLE_CENTER);
form.addComponent(loginField);
form.setComponentAlignment(loginField, Alignment.TOP_CENTER);
form.addComponent(passwordField);
form.setComponentAlignment(passwordField, Alignment.TOP_CENTER);
final CheckBox rememberMe = new CheckBox("Remember Me");
rememberMe.setValue(Boolean.FALSE);
form.addComponent(rememberMe);
form.setComponentAlignment(rememberMe, Alignment.TOP_CENTER);
Button loginButton = new Button("Login");
loginButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
loginButton.addStyleName(Runo.BUTTON_DEFAULT);
form.addComponent(loginButton);
form.setComponentAlignment(loginButton, Alignment.TOP_CENTER);
loginButton.addStyleName("primary");
loginButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
loginButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
Authentication authentication;
final String login = loginField.getValue();
final String password = passwordField.getValue();
try {
authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
if (rememberMe.getValue()) {
final VaadinRequest currentRequest = VaadinService.getCurrentRequest();
final VaadinResponse currentResponse = VaadinService.getCurrentResponse();
final String key = rememberMeServices.getParameter();
rememberMeServices.loginSuccess(new FakeRememberMeFlag(key, (VaadinServletRequest) currentRequest), (VaadinServletResponse) currentResponse, authentication);
}
} catch (AuthenticationException e) {
- // TODO - capture login ok but account inactive/unconfirmed
- Notification.show("Failed to login.", Notification.Type.ERROR_MESSAGE);
+ Notification.show("Failed to login. Username or password does not match an active account.", Notification.Type.ERROR_MESSAGE);
return;
}
AppUser user = readOnlyDAO.getUser(login);
if (user == null) {
Notification.show("This is embarrassing", Notification.Type.ERROR_MESSAGE);
return;
}
SecurityContextHolder.getContext().setAuthentication(authentication);
getParent().getUI().getSession().close();
getParent().getUI().getPage().setLocation("/E-EYE-O");
loginField.setValue("");
passwordField.setValue("");
}
});
return loginSection;
}
private Layout getSignUpResetSection() {
VerticalLayout helpSection = new VerticalLayout();
HorizontalLayout horizontalLayout = new HorizontalLayout();
horizontalLayout.setSpacing(true);
Link registerLink = new Link("Register for Account", new ExternalResource("#!" + LegalView.VIEW_NAME));
horizontalLayout.addComponent(registerLink);
Link forgotPasswordLink = new Link("Forgot Password?", new ExternalResource("#!" + ResetRequest.VIEW_NAME));
horizontalLayout.addComponent(forgotPasswordLink);
helpSection.addComponent(horizontalLayout);
helpSection.setComponentAlignment(horizontalLayout, Alignment.MIDDLE_CENTER);
return helpSection;
}
private Layout getTitleSection() {
VerticalLayout titleSection = new VerticalLayout();
Label title = new Label("Welcome to");
title.setSizeUndefined();
title.addStyleName("bold");
titleSection.addComponent(title);
titleSection.setComponentAlignment(title, Alignment.MIDDLE_CENTER);
logo.addStyleName("big-logo");
titleSection.addComponent(logo);
titleSection.setComponentAlignment(logo, Alignment.MIDDLE_CENTER);
return titleSection;
}
@Override
public void enter(final ViewChangeListener.ViewChangeEvent event) {
getUI().setFocusedComponent(loginField);
}
private static class FakeRememberMeFlag extends HttpServletRequestWrapper {
private final String rememberMeParameter;
private FakeRememberMeFlag(final String rememberMeParameter, final VaadinServletRequest vaadinServletRequest) {
super(vaadinServletRequest);
this.rememberMeParameter = rememberMeParameter;
}
@Override
public String getParameter(final String name) {
if (rememberMeParameter.equals(name))
return "1";
return super.getParameter(name);
}
}
}
| true | true | private Layout getLoginSection() {
VerticalLayout loginSection = new VerticalLayout();
FormLayout form = new FormLayout();
form.setWidth(null);
form.setHeight(null);
loginSection.addComponent(form);
loginSection.setComponentAlignment(form, Alignment.MIDDLE_CENTER);
form.addComponent(loginField);
form.setComponentAlignment(loginField, Alignment.TOP_CENTER);
form.addComponent(passwordField);
form.setComponentAlignment(passwordField, Alignment.TOP_CENTER);
final CheckBox rememberMe = new CheckBox("Remember Me");
rememberMe.setValue(Boolean.FALSE);
form.addComponent(rememberMe);
form.setComponentAlignment(rememberMe, Alignment.TOP_CENTER);
Button loginButton = new Button("Login");
loginButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
loginButton.addStyleName(Runo.BUTTON_DEFAULT);
form.addComponent(loginButton);
form.setComponentAlignment(loginButton, Alignment.TOP_CENTER);
loginButton.addStyleName("primary");
loginButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
loginButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
Authentication authentication;
final String login = loginField.getValue();
final String password = passwordField.getValue();
try {
authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
if (rememberMe.getValue()) {
final VaadinRequest currentRequest = VaadinService.getCurrentRequest();
final VaadinResponse currentResponse = VaadinService.getCurrentResponse();
final String key = rememberMeServices.getParameter();
rememberMeServices.loginSuccess(new FakeRememberMeFlag(key, (VaadinServletRequest) currentRequest), (VaadinServletResponse) currentResponse, authentication);
}
} catch (AuthenticationException e) {
// TODO - capture login ok but account inactive/unconfirmed
Notification.show("Failed to login.", Notification.Type.ERROR_MESSAGE);
return;
}
AppUser user = readOnlyDAO.getUser(login);
if (user == null) {
Notification.show("This is embarrassing", Notification.Type.ERROR_MESSAGE);
return;
}
SecurityContextHolder.getContext().setAuthentication(authentication);
getParent().getUI().getSession().close();
getParent().getUI().getPage().setLocation("/E-EYE-O");
loginField.setValue("");
passwordField.setValue("");
}
});
return loginSection;
}
| private Layout getLoginSection() {
VerticalLayout loginSection = new VerticalLayout();
FormLayout form = new FormLayout();
form.setWidth(null);
form.setHeight(null);
loginSection.addComponent(form);
loginSection.setComponentAlignment(form, Alignment.MIDDLE_CENTER);
form.addComponent(loginField);
form.setComponentAlignment(loginField, Alignment.TOP_CENTER);
form.addComponent(passwordField);
form.setComponentAlignment(passwordField, Alignment.TOP_CENTER);
final CheckBox rememberMe = new CheckBox("Remember Me");
rememberMe.setValue(Boolean.FALSE);
form.addComponent(rememberMe);
form.setComponentAlignment(rememberMe, Alignment.TOP_CENTER);
Button loginButton = new Button("Login");
loginButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
loginButton.addStyleName(Runo.BUTTON_DEFAULT);
form.addComponent(loginButton);
form.setComponentAlignment(loginButton, Alignment.TOP_CENTER);
loginButton.addStyleName("primary");
loginButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
loginButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
Authentication authentication;
final String login = loginField.getValue();
final String password = passwordField.getValue();
try {
authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
if (rememberMe.getValue()) {
final VaadinRequest currentRequest = VaadinService.getCurrentRequest();
final VaadinResponse currentResponse = VaadinService.getCurrentResponse();
final String key = rememberMeServices.getParameter();
rememberMeServices.loginSuccess(new FakeRememberMeFlag(key, (VaadinServletRequest) currentRequest), (VaadinServletResponse) currentResponse, authentication);
}
} catch (AuthenticationException e) {
Notification.show("Failed to login. Username or password does not match an active account.", Notification.Type.ERROR_MESSAGE);
return;
}
AppUser user = readOnlyDAO.getUser(login);
if (user == null) {
Notification.show("This is embarrassing", Notification.Type.ERROR_MESSAGE);
return;
}
SecurityContextHolder.getContext().setAuthentication(authentication);
getParent().getUI().getSession().close();
getParent().getUI().getPage().setLocation("/E-EYE-O");
loginField.setValue("");
passwordField.setValue("");
}
});
return loginSection;
}
|
diff --git a/src/jp/knct/di/c6t/ui/exploration/ExplorationDetailActivity.java b/src/jp/knct/di/c6t/ui/exploration/ExplorationDetailActivity.java
index 2163627..22e84fb 100644
--- a/src/jp/knct/di/c6t/ui/exploration/ExplorationDetailActivity.java
+++ b/src/jp/knct/di/c6t/ui/exploration/ExplorationDetailActivity.java
@@ -1,68 +1,68 @@
package jp.knct.di.c6t.ui.exploration;
import jp.knct.di.c6t.IntentData;
import jp.knct.di.c6t.R;
import jp.knct.di.c6t.model.Exploration;
import jp.knct.di.c6t.util.ActivityUtil;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class ExplorationDetailActivity extends Activity implements OnClickListener {
private Exploration mExploration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exploration_detail);
mExploration = getIntent().getParcelableExtra(IntentData.EXTRA_KEY_EXPLORATION);
putExplorationDataIntoComponents(mExploration);
ActivityUtil.setOnClickListener(this, this, new int[] {
R.id.exploration_detail_join,
R.id.exploration_detail_calender,
R.id.exploration_detail_share,
});
}
private void putExplorationDataIntoComponents(Exploration exploration) {
new ActivityUtil(this)
.setText(R.id.exploration_detail_name, exploration.getRoute().getName())
.setText(R.id.exploration_detail_host, exploration.getHost().getName())
.setText(R.id.exploration_detail_start_location, exploration.getRoute().getStartLocation().toString())
.setText(R.id.exploration_detail_description, exploration.getDescription());
}
@Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.exploration_detail_join:
intent = new Intent(this, ExplorationStartActivity.class)
.putExtra(IntentData.EXTRA_KEY_EXPLORATION, mExploration);
startActivity(intent);
break;
case R.id.exploration_detail_calender:
// TODO
break;
case R.id.exploration_detail_share:
intent = new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_EMAIL, "")
.putExtra(Intent.EXTRA_SUBJECT, "�T��:" + mExploration.getRoute().getName())
.putExtra(Intent.EXTRA_TEXT, mExploration.getDescription());
- startActivity(Intent.createChooser(intent, "���[���𑗂�"));
+ startActivity(Intent.createChooser(intent, "���L"));
break;
default:
break;
}
}
}
| true | true | public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.exploration_detail_join:
intent = new Intent(this, ExplorationStartActivity.class)
.putExtra(IntentData.EXTRA_KEY_EXPLORATION, mExploration);
startActivity(intent);
break;
case R.id.exploration_detail_calender:
// TODO
break;
case R.id.exploration_detail_share:
intent = new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_EMAIL, "")
.putExtra(Intent.EXTRA_SUBJECT, "�T��:" + mExploration.getRoute().getName())
.putExtra(Intent.EXTRA_TEXT, mExploration.getDescription());
startActivity(Intent.createChooser(intent, "���[���𑗂�"));
break;
default:
break;
}
}
| public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.exploration_detail_join:
intent = new Intent(this, ExplorationStartActivity.class)
.putExtra(IntentData.EXTRA_KEY_EXPLORATION, mExploration);
startActivity(intent);
break;
case R.id.exploration_detail_calender:
// TODO
break;
case R.id.exploration_detail_share:
intent = new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_EMAIL, "")
.putExtra(Intent.EXTRA_SUBJECT, "�T��:" + mExploration.getRoute().getName())
.putExtra(Intent.EXTRA_TEXT, mExploration.getDescription());
startActivity(Intent.createChooser(intent, "���L"));
break;
default:
break;
}
}
|
diff --git a/src/main/java/org/infoscoop/request/filter/GadgetFilter.java b/src/main/java/org/infoscoop/request/filter/GadgetFilter.java
index d93d104c..218935a7 100644
--- a/src/main/java/org/infoscoop/request/filter/GadgetFilter.java
+++ b/src/main/java/org/infoscoop/request/filter/GadgetFilter.java
@@ -1,452 +1,452 @@
/* infoScoop OpenSource
* Copyright (C) 2010 Beacon IT Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0-standalone.html>.
*/
package org.infoscoop.request.filter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shindig.common.util.ResourceLoader;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.infoscoop.request.ProxyRequest;
import org.infoscoop.util.NoOpEntityResolver;
import org.infoscoop.util.XmlUtil;
import org.infoscoop.widgetconf.I18NConverter;
import org.infoscoop.widgetconf.WidgetConfUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class GadgetFilter extends ProxyFilter {
private static final Log log = LogFactory.getLog(GadgetFilter.class);
private static final String PARAM_MODULE_ID = "__MODULE_ID__";
private static final String PARAM_STATIC_CONTENT_URL = "__STATIC_CONTENT_URL__";
private static final String PARAM_HOST_PREFIX = "__HOST_PREFIX__";
private static final String PARAM_TAB_ID = "__TAB_ID__";
private static final String DATA_PATH = "features/i18n/data/";
private static final String DATE_TIME_PATH = DATA_PATH + "DateTimeConstants__";
private static final String DATE_NUMBER_PATH = DATA_PATH + "NumberFormatConstants__";
private DocumentBuilderFactory factory;
public GadgetFilter() {
factory = DocumentBuilderFactory.newInstance();
factory.setValidating( false );
}
private Document gadget2dom( InputStream responseBody )
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(NoOpEntityResolver.getInstance());
Document doc = builder.parse(responseBody);
return doc;
}
public static byte[] gadget2html( String baseUrl,Document doc,
- Map<String,String> urlParameters,I18NConverter i18n ) throws Exception {
+ Map<String,String> urlParameters,I18NConverter i18n,Locale locale) throws Exception {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String version = getModuleVersion(doc);
double validVersion = compareVersion(version, "2.0");
String quirks = getQuirks(doc);
VelocityContext context = new VelocityContext();
//quirks mode
context.put("doctype", getDoctype(validVersion, quirks));
context.put("charset", getCharset(validVersion, quirks));
context.put("baseUrl",baseUrl );
context.put("content",replaceContentStr( doc,i18n,urlParameters ) );
context.put("widgetId",urlParameters.get( PARAM_MODULE_ID));
context.put("staticContentURL",urlParameters.get( PARAM_STATIC_CONTENT_URL ));
context.put("hostPrefix",urlParameters.get( PARAM_HOST_PREFIX ));
context.put("tabId",urlParameters.get( PARAM_TAB_ID ));
context.put("gadgetUrl",urlParameters.get( "url" ));
// ModulePrefs
JSONObject req = getRequires( xpath,doc,urlParameters.get( "view" ));
context.put("requires", req);
if(req.has("opensocial-i18n")){
String localeName = getLocaleNameForLoadingI18NConstants(locale);
String dateTimeConstants = DATE_TIME_PATH + localeName + ".js";
String numberFormatConstants = DATE_NUMBER_PATH + localeName + ".js";
StringBuilder sb = new StringBuilder();
try {
sb.append(ResourceLoader.getContent(dateTimeConstants))
.append("\n")
.append(ResourceLoader.getContent(numberFormatConstants));
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception(e);
}
context.put("i18nDataConstants", sb.toString());
}
context.put("oauthServicesJson", getOAuthServicesJson( xpath,doc ));
context.put("oauth2ServicesJson", getOAuth2ServicesJson( xpath,doc ));
context.put("i18nMsgs", new JSONObject( i18n.getMsgs()));
context.put("userPrefs",getUserPrefs( urlParameters ));
context.put("dir",i18n.getDirection());
StringWriter writer = new StringWriter();
Template template = Velocity.getTemplate("gadget-html.vm", "UTF-8");
template.merge( context,writer );
return writer.toString().getBytes("UTF-8");
}
static String getLocaleNameForLoadingI18NConstants(Locale locale) {
String localeName = "en";
String language = locale.getLanguage();
String country = locale.getCountry();
if (!language.equalsIgnoreCase("ALL")) {
try {
ResourceLoader.getContent((DATE_TIME_PATH + localeName + ".js"));
localeName = language;
} catch (IOException e) {
// ignore
}
}
if (!country.equalsIgnoreCase("ALL")) {
try {
ResourceLoader.getContent(DATE_TIME_PATH + localeName + '_' + country + ".js");
localeName += '_' + country;
} catch (IOException e) {
// ignore
}
}
return localeName;
}
private static String getModuleVersion(Document doc) throws Exception {
NodeList moduleNodes = doc.getElementsByTagName("Module");
Node versionNode = moduleNodes.item(0).getAttributes().getNamedItem("specificationVersion");
String version = "";
if(versionNode != null){
version = versionNode.getNodeValue();
}
return version;
}
private static String getQuirks(Document doc) throws Exception {
NodeList prefsNodes = doc.getElementsByTagName("ModulePrefs");
Node quirksNode = prefsNodes.item(0).getAttributes().getNamedItem("doctype");
String quirks = "";
if(quirksNode != null){
quirks = quirksNode.getNodeValue();
}
return quirks;
}
private static double compareVersion(String version, String target) {
if(version.equals("")){
return 1.0;
}
String[] versionArr = version.split("\\.");
String[] specArr = target.split("\\.");
if(!version.equals(target)){
int len = 0;
if(versionArr.length > specArr.length){
len = specArr.length;
}else{
len = versionArr.length;
}
for(int i = 0; i < len; i++){
int ver = Integer.parseInt(versionArr[i]);
int spec = Integer.parseInt(specArr[i]);
if(ver > spec){
target = versionArr[0] + "." +versionArr[1];
break;
}else if(ver < spec){
break;
}
}
}
return Double.parseDouble(target);
}
private static String getDoctype( double version, String quirks ) {
String doctype = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">";
if(!quirks.equals("quirksmode") && version >= 2.0){
doctype = "<!DOCTYPE html>";
}
return doctype;
}
private static String getCharset( double version, String quirks ) {
String charset = "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">";
if(!quirks.equals("quirksmode") && version >= 2.0){
charset = "<meta charset=\"UTF-8\">";
}
return charset;
}
private static Map<String,String> getUrlParameters( Map<String,String> filterParameters ) {
Map<String,String> parameters = new HashMap<String,String>();
for( String key : filterParameters.keySet()) {
String value = filterParameters.get( key );
if( key.startsWith("up_") && key.length() > 3 )
key = "__UP_"+key.substring(3)+"__";
parameters.put( key,value );
}
return parameters;
}
private static String replaceContentStr( Document doc,I18NConverter i18n,
Map<String,String> urlParameters ) throws Exception {
NodeList contentNodeList = doc.getElementsByTagName("Content");
if( contentNodeList.getLength() == 0 )
return "";
Node content = contentNodeList.item(0);
String contentStr = XmlUtil.getChildText(content);
contentStr = i18n.replace(contentStr);
for( Map.Entry<String,String> param : urlParameters.entrySet() ) {
String key = param.getKey();
if( !PARAM_MODULE_ID.equals( key ) &&
!( key.startsWith("__UP_") && key.endsWith("__")))
continue;
contentStr = contentStr.replaceAll( key,Matcher.quoteReplacement( param.getValue() ));
}
return contentStr;
}
private static JSONObject getRequires( XPath xpath,Document doc,String viewType ) throws XPathExpressionException,JSONException {
JSONObject requires = new JSONObject();
requires.put("core",new JSONObject());
requires.put("core.io",new JSONObject());
requires.put("rpc",new JSONObject());
NodeList requireNodes = ( NodeList )xpath.evaluate(
"/Module/ModulePrefs/Require|/Module/ModulePrefs/Optional",doc,XPathConstants.NODESET );
for (int i = 0; i < requireNodes.getLength(); i++) {
Element require = ( Element )requireNodes.item(i);
String requireViewType = require.getAttribute("views").toLowerCase();
if(requireViewType != null && !requireViewType.equals("")){
if(requireViewType.indexOf("default") > -1 && viewType.equals("home")){
requires.put( require.getAttribute("feature").toLowerCase(),getRequireParams( xpath,require ));
}else if(requireViewType.indexOf(viewType) > -1){
requires.put( require.getAttribute("feature").toLowerCase(),getRequireParams( xpath,require ));
}
}else{
requires.put( require.getAttribute("feature").toLowerCase(),getRequireParams( xpath,require ));
}
}
requires.put("infoscoop",new JSONObject());
return requires;
}
private static JSONObject getRequireParams( XPath xpath,Element require ) throws XPathExpressionException,JSONException {
JSONObject params = new JSONObject();
NodeList paramNodes = ( NodeList )xpath.evaluate("Param[@name]",require,XPathConstants.NODESET );
for( int j=0;j<paramNodes.getLength();j++ ) {
Element param = ( Element )paramNodes.item( j );
params.put( param.getAttribute("name").toLowerCase(),param.getTextContent() );
}
return params;
}
private static String getOAuthServicesJson(XPath xpath, Document doc) throws XPathExpressionException, JSONException {
JSONObject services = new JSONObject();
NodeList serviceNodes = ( NodeList )xpath.evaluate(
"/Module/ModulePrefs/OAuth/Service",doc,XPathConstants.NODESET );
for( int j=0;j<serviceNodes.getLength();j++ ) {
Element serviceEl = ( Element )serviceNodes.item( j );
JSONObject service = new JSONObject();
NodeList nodeList = serviceEl.getElementsByTagName("Request");
if(nodeList.getLength() > 0){
Element requestEl = (Element)nodeList.item(0);
service.put("requestTokenURL", requestEl.getAttribute("url"));
String method = requestEl.getAttribute("method");
if(method != null)
service.put("requestTokenMethod", requestEl.getAttribute("method"));
}
nodeList = serviceEl.getElementsByTagName("Authorization");
if(nodeList.getLength() > 0){
Element requestEl = (Element)nodeList.item(0);
service.put("userAuthorizationURL", requestEl.getAttribute("url"));
}
nodeList = serviceEl.getElementsByTagName("Access");
if(nodeList.getLength() > 0){
Element requestEl = (Element)nodeList.item(0);
service.put("accessTokenURL", requestEl.getAttribute("url"));
String method = requestEl.getAttribute("method");
if(method != null)
service.put("accessTokenMethod", requestEl.getAttribute("method"));
}
services.put(serviceEl.getAttribute("name"), service);
}
return services.toString();
}
private static String getOAuth2ServicesJson(XPath xpath, Document doc) throws XPathExpressionException, JSONException {
JSONObject services = new JSONObject();
NodeList serviceNodes = ( NodeList )xpath.evaluate(
"/Module/ModulePrefs/OAuth2/Service",doc,XPathConstants.NODESET );
for( int j=0;j<serviceNodes.getLength();j++ ) {
Element serviceEl = ( Element )serviceNodes.item( j );
JSONObject service = new JSONObject();
NodeList nodeList = serviceEl.getElementsByTagName("Authorization");
if(nodeList.getLength() > 0){
Element requestEl = (Element)nodeList.item(0);
service.put("userAuthorizationURL", requestEl.getAttribute("url"));
}
nodeList = serviceEl.getElementsByTagName("Token");
if(nodeList.getLength() > 0){
Element requestEl = (Element)nodeList.item(0);
service.put("accessTokenURL", requestEl.getAttribute("url"));
}
service.put("scope", serviceEl.getAttribute("scope"));
services.put(serviceEl.getAttribute("name"), service);
}
return services.toString();
}
private static JSONObject getUserPrefs( Map<String,String> filterParameters ) {
JSONObject userPrefs = new JSONObject();
for( String key : filterParameters.keySet() ) {
if( key.startsWith("__UP_") ) {
try {
userPrefs.put( key.substring(5,key.length() -2 ),filterParameters.get( key ));
} catch( JSONException ex ) {
throw new RuntimeException( ex );
}
}
}
return userPrefs;
}
protected int preProcess(HttpClient client, HttpMethod method, ProxyRequest request) {
// String uploadType = request.getFilterParameter("uploadType");
String uploadType = null;
String url = request.getOriginalURL();
if( url.startsWith("upload__"))
uploadType = url.substring( 8,url.lastIndexOf("/"));
if( uploadType != null && !"".equals( uploadType )) {
Map<String,String> urlParameters = getUrlParameters( request.getFilterParameters() );
WidgetConfUtil.GadgetContext context = new WidgetConfUtil.GadgetContext().setUrl(url);
try {
InputStream data = context.getUploadGadget(urlParameters.get( PARAM_HOST_PREFIX ));
if( data == null )
return 404;
request.setResponseBody(data);
// request.setResponseBody( postProcess( request, request.getResponseBody() ));
return org.infoscoop.request.filter.ProxyFilterContainer.EXECUTE_POST_STATUS;
} catch( IOException ex ) {
throw new RuntimeException( ex );
} catch (Exception e) {
log.error(e.getMessage(), e);
return 500;
}
}
return 0;
}
protected InputStream postProcess(
ProxyRequest request, InputStream responseStream ) throws IOException {
request.putResponseHeader("Cache-Control", "no-cache");
byte[] responseBytes = null;
try {
int timeout = 0;
try{
String timeoutHeader = request.getRequestHeader("MSDPortal-Timeout");
timeout = Integer.parseInt( timeoutHeader ) - 1000;
} catch(NumberFormatException e){ }
Document doc = gadget2dom( responseStream );
Map<String,String> urlParameters = getUrlParameters( request.getFilterParameters() );
WidgetConfUtil.GadgetContext context = new WidgetConfUtil.GadgetContext()
.setTimeout( timeout )
.setUrl( request.getOriginalURL() )
.setHostPrefix( urlParameters.get( PARAM_HOST_PREFIX ));
Locale locale = request.getLocale();
responseBytes = gadget2html( context.getBaseUrl(),doc,urlParameters,
context.getI18NConveter( locale,doc ), locale);
} catch ( Exception ex ) {
log.error("unexpected error ocurred.", ex );
responseBytes = "unexpected error ocurred.".getBytes("UTF-8");
}
//request.setResponseBody(new ByteArrayInputStream(responseBytes));
request.putResponseHeader("Content-Length",Integer.toString( responseBytes.length ));
request.putResponseHeader("Content-Type","text/html; charset=\"utf-8\"");
return new ByteArrayInputStream(responseBytes);
}
}
| true | true | public static byte[] gadget2html( String baseUrl,Document doc,
Map<String,String> urlParameters,I18NConverter i18n ) throws Exception {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String version = getModuleVersion(doc);
double validVersion = compareVersion(version, "2.0");
String quirks = getQuirks(doc);
VelocityContext context = new VelocityContext();
//quirks mode
context.put("doctype", getDoctype(validVersion, quirks));
context.put("charset", getCharset(validVersion, quirks));
context.put("baseUrl",baseUrl );
context.put("content",replaceContentStr( doc,i18n,urlParameters ) );
context.put("widgetId",urlParameters.get( PARAM_MODULE_ID));
context.put("staticContentURL",urlParameters.get( PARAM_STATIC_CONTENT_URL ));
context.put("hostPrefix",urlParameters.get( PARAM_HOST_PREFIX ));
context.put("tabId",urlParameters.get( PARAM_TAB_ID ));
context.put("gadgetUrl",urlParameters.get( "url" ));
// ModulePrefs
JSONObject req = getRequires( xpath,doc,urlParameters.get( "view" ));
context.put("requires", req);
if(req.has("opensocial-i18n")){
String localeName = getLocaleNameForLoadingI18NConstants(locale);
String dateTimeConstants = DATE_TIME_PATH + localeName + ".js";
String numberFormatConstants = DATE_NUMBER_PATH + localeName + ".js";
StringBuilder sb = new StringBuilder();
try {
sb.append(ResourceLoader.getContent(dateTimeConstants))
.append("\n")
.append(ResourceLoader.getContent(numberFormatConstants));
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception(e);
}
context.put("i18nDataConstants", sb.toString());
}
context.put("oauthServicesJson", getOAuthServicesJson( xpath,doc ));
context.put("oauth2ServicesJson", getOAuth2ServicesJson( xpath,doc ));
context.put("i18nMsgs", new JSONObject( i18n.getMsgs()));
context.put("userPrefs",getUserPrefs( urlParameters ));
context.put("dir",i18n.getDirection());
StringWriter writer = new StringWriter();
Template template = Velocity.getTemplate("gadget-html.vm", "UTF-8");
template.merge( context,writer );
return writer.toString().getBytes("UTF-8");
}
| public static byte[] gadget2html( String baseUrl,Document doc,
Map<String,String> urlParameters,I18NConverter i18n,Locale locale) throws Exception {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String version = getModuleVersion(doc);
double validVersion = compareVersion(version, "2.0");
String quirks = getQuirks(doc);
VelocityContext context = new VelocityContext();
//quirks mode
context.put("doctype", getDoctype(validVersion, quirks));
context.put("charset", getCharset(validVersion, quirks));
context.put("baseUrl",baseUrl );
context.put("content",replaceContentStr( doc,i18n,urlParameters ) );
context.put("widgetId",urlParameters.get( PARAM_MODULE_ID));
context.put("staticContentURL",urlParameters.get( PARAM_STATIC_CONTENT_URL ));
context.put("hostPrefix",urlParameters.get( PARAM_HOST_PREFIX ));
context.put("tabId",urlParameters.get( PARAM_TAB_ID ));
context.put("gadgetUrl",urlParameters.get( "url" ));
// ModulePrefs
JSONObject req = getRequires( xpath,doc,urlParameters.get( "view" ));
context.put("requires", req);
if(req.has("opensocial-i18n")){
String localeName = getLocaleNameForLoadingI18NConstants(locale);
String dateTimeConstants = DATE_TIME_PATH + localeName + ".js";
String numberFormatConstants = DATE_NUMBER_PATH + localeName + ".js";
StringBuilder sb = new StringBuilder();
try {
sb.append(ResourceLoader.getContent(dateTimeConstants))
.append("\n")
.append(ResourceLoader.getContent(numberFormatConstants));
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception(e);
}
context.put("i18nDataConstants", sb.toString());
}
context.put("oauthServicesJson", getOAuthServicesJson( xpath,doc ));
context.put("oauth2ServicesJson", getOAuth2ServicesJson( xpath,doc ));
context.put("i18nMsgs", new JSONObject( i18n.getMsgs()));
context.put("userPrefs",getUserPrefs( urlParameters ));
context.put("dir",i18n.getDirection());
StringWriter writer = new StringWriter();
Template template = Velocity.getTemplate("gadget-html.vm", "UTF-8");
template.merge( context,writer );
return writer.toString().getBytes("UTF-8");
}
|
diff --git a/common/logisticspipes/config/Configs.java b/common/logisticspipes/config/Configs.java
index 4a9eeb8d..1c6e031b 100644
--- a/common/logisticspipes/config/Configs.java
+++ b/common/logisticspipes/config/Configs.java
@@ -1,498 +1,498 @@
package logisticspipes.config;
import java.io.File;
import logisticspipes.LogisticsPipes;
import logisticspipes.proxy.MainProxy;
import net.minecraft.src.ModLoader;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
public class Configs {
public static final String CATEGORY_MULTITHREAD = "multiThread";
// Ids
public static int ItemLiquidContainerId = 6864;
public static int ItemUpgradeManagerId = 6865;
public static int ItemUpgradeId = 6866;
public static int ItemPartsId = 6867;
public static int ItemHUDId = 6868;
public static int ItemCardId = 6869;
public static int ItemDiskId = 6870;
public static int ItemModuleId = 6871;
public static int LOGISTICSREMOTEORDERER_ID = 6872;
public static int LOGISTICSNETWORKMONITOR_ID = 6873;
public static int LOGISTICSPIPE_BASIC_ID = 6874;
public static int LOGISTICSPIPE_REQUEST_ID = 6875;
public static int LOGISTICSPIPE_PROVIDER_ID = 6876;
public static int LOGISTICSPIPE_CRAFTING_ID = 6877;
public static int LOGISTICSPIPE_SATELLITE_ID = 6878;
public static int LOGISTICSPIPE_SUPPLIER_ID = 6879;
public static int LOGISTICSPIPE_BUILDERSUPPLIER_ID = 6880;
public static int LOGISTICSPIPE_CHASSI1_ID = 6881;
public static int LOGISTICSPIPE_CHASSI2_ID = 6882;
public static int LOGISTICSPIPE_CHASSI3_ID = 6883;
public static int LOGISTICSPIPE_CHASSI4_ID = 6884;
public static int LOGISTICSPIPE_CHASSI5_ID = 6885;
public static int LOGISTICSPIPE_LIQUIDSUPPLIER_ID = 6886;
public static int LOGISTICSPIPE_CRAFTING_MK2_ID = 6887;
public static int LOGISTICSPIPE_REQUEST_MK2_ID = 6888;
public static int LOGISTICSPIPE_REMOTE_ORDERER_ID = 6889;
public static int LOGISTICSPIPE_PROVIDER_MK2_ID = 6890;
public static int LOGISTICSPIPE_APIARIST_ANALYSER_ID = 6891;
public static int LOGISTICSPIPE_APIARIST_SINK_ID = 6892;
public static int LOGISTICSPIPE_INVSYSCON_ID = 6893;
public static int LOGISTICSPIPE_ENTRANCE_ID = 6894;
public static int LOGISTICSPIPE_DESTINATION_ID = 6895;
public static int LOGISTICSPIPE_CRAFTING_MK3_ID = 6896;
public static int LOGISTICSPIPE_FIREWALL_ID = 6897;
public static int LOGISTICSPIPE_LIQUID_CONNECTOR = 6901;
public static int LOGISTICSPIPE_LIQUID_BASIC = 6902;
public static int LOGISTICSPIPE_LIQUID_INSERTION = 6903;
public static int LOGISTICSPIPE_LIQUID_PROVIDER = 6904;
public static int LOGISTICSPIPE_LIQUID_REQUEST = 6905;
public static int LOGISTICSCRAFTINGSIGNCREATOR_ID = 6900;
private static Configuration configuration;
// Configrables
public static int LOGISTICS_DETECTION_LENGTH = 50;
public static int LOGISTICS_DETECTION_COUNT = 100;
public static int LOGISTICS_DETECTION_FREQUENCY = 20;
public static boolean LOGISTICS_ORDERER_COUNT_INVERTWHEEL = false;
public static boolean LOGISTICS_ORDERER_PAGE_INVERTWHEEL = false;
public static final float LOGISTICS_ROUTED_SPEED_MULTIPLIER = 20F;
public static final float LOGISTICS_DEFAULTROUTED_SPEED_MULTIPLIER = 10F;
public static int LOGISTICS_HUD_RENDER_DISTANCE = 15;
public static boolean LOGISTICS_POWER_USAGE_DISABLED = false;
public static boolean LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = false;
public static boolean ToolTipInfo = LogisticsPipes.DEBUG;
public static boolean MANDATORY_CARPENTER_RECIPES = true;
public static boolean ENABLE_PARTICLE_FX = true;
//GuiOrderer Popup setting
public static boolean displayPopup = true;
//BlockID
public static int LOGISTICS_SIGN_ID = 1100;
public static int LOGISTICS_SOLID_BLOCK_ID = 1101;
//MultiThread
public static boolean multiThreadEnabled = true;
public static int multiThreadNumber = 4;
public static int multiThreadPriority = Thread.NORM_PRIORITY;
public static int powerUsageMultiplyer = 1;
private static void readoldconfig() {
Property logisticRemoteOrdererIdProperty = configuration.get("logisticsRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSREMOTEORDERER_ID);
Property logisticNetworkMonitorIdProperty = configuration.get("logisticsNetworkMonitor.id", Configuration.CATEGORY_ITEM, LOGISTICSNETWORKMONITOR_ID);
Property logisticPipeIdProperty = configuration.get("logisticsPipe.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BASIC_ID);
Property logisticPipeRequesterIdProperty = configuration.get("logisticsPipeRequester.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_ID);
Property logisticPipeProviderIdProperty = configuration.get("logisticsPipeProvider.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_ID);
Property logisticPipeCraftingIdProperty = configuration.get("logisticsPipeCrafting.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_ID);
Property logisticPipeSatelliteIdProperty = configuration.get("logisticsPipeSatellite.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SATELLITE_ID);
Property logisticPipeSupplierIdProperty = configuration.get("logisticsPipeSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_SUPPLIER_ID);
Property logisticPipeChassi1IdProperty = configuration.get("logisticsPipeChassi1.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI1_ID);
Property logisticPipeChassi2IdProperty = configuration.get("logisticsPipeChassi2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI2_ID);
Property logisticPipeChassi3IdProperty = configuration.get("logisticsPipeChassi3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI3_ID);
Property logisticPipeChassi4IdProperty = configuration.get("logisticsPipeChassi4.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI4_ID);
Property logisticPipeChassi5IdProperty = configuration.get("logisticsPipeChassi5.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CHASSI5_ID);
Property logisticPipeCraftingMK2IdProperty = configuration.get("logisticsPipeCraftingMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK2_ID);
Property logisticPipeCraftingMK3IdProperty = configuration.get("logisticsPipeCraftingMK3.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_CRAFTING_MK3_ID);
Property logisticPipeRequesterMK2IdProperty = configuration.get("logisticsPipeRequesterMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REQUEST_MK2_ID);
Property logisticPipeProviderMK2IdProperty = configuration.get("logisticsPipeProviderMK2.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_PROVIDER_MK2_ID);
Property logisticPipeApiaristAnalyserIdProperty = configuration.get("logisticsPipeApiaristAnalyser.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_ANALYSER_ID);
Property logisticPipeRemoteOrdererIdProperty = configuration.get("logisticsPipeRemoteOrderer.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_REMOTE_ORDERER_ID);
Property logisticPipeApiaristSinkIdProperty = configuration.get("logisticsPipeApiaristSink.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_APIARIST_SINK_ID);
Property logisticModuleIdProperty = configuration.get("logisticsModules.id", Configuration.CATEGORY_ITEM, ItemModuleId);
Property logisticItemDiskIdProperty = configuration.get("logisticsDisk.id", Configuration.CATEGORY_ITEM, ItemDiskId);
Property logisticItemHUDIdProperty = configuration.get("logisticsHUD.id", Configuration.CATEGORY_ITEM, ItemHUDId);
Property logisticItemPartsIdProperty = configuration.get("logisticsHUDParts.id", Configuration.CATEGORY_ITEM, ItemPartsId);
Property logisticCraftingSignCreatorIdProperty = configuration.get("logisticsCraftingSignCreator.id", Configuration.CATEGORY_ITEM, LOGISTICSCRAFTINGSIGNCREATOR_ID);
Property logisticPipeBuilderSupplierIdProperty = configuration.get("logisticsPipeBuilderSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_BUILDERSUPPLIER_ID);
Property logisticPipeLiquidSupplierIdProperty = configuration.get("logisticsPipeLiquidSupplier.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
Property logisticInvSysConIdProperty = configuration.get("logisticInvSysCon.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_INVSYSCON_ID);
Property logisticEntranceIdProperty = configuration.get("logisticEntrance.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_ENTRANCE_ID);
Property logisticDestinationIdProperty = configuration.get("logisticDestination.id", Configuration.CATEGORY_ITEM, LOGISTICSPIPE_DESTINATION_ID);
Property logisticItemCardIdProperty = configuration.get("logisticItemCard.id", Configuration.CATEGORY_ITEM, ItemCardId);
Property detectionLength = configuration.get("detectionLength", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_LENGTH);
Property detectionCount = configuration.get("detectionCount", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_COUNT);
Property detectionFrequency = configuration.get("detectionFrequency", Configuration.CATEGORY_GENERAL, LOGISTICS_DETECTION_FREQUENCY);
Property countInvertWheelProperty = configuration.get("ordererCountInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
Property pageInvertWheelProperty = configuration.get("ordererPageInvertWheel", Configuration.CATEGORY_GENERAL, LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
Property pageDisplayPopupProperty = configuration.get("displayPopup", Configuration.CATEGORY_GENERAL, displayPopup);
if(configuration.categories.containsKey(Configuration.CATEGORY_BLOCK) && configuration.categories.get(Configuration.CATEGORY_BLOCK).containsKey("logisticsBlockId")) {
Property logisticsBlockId = configuration.get("logisticsBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsBlockId.value);
configuration.categories.get(Configuration.CATEGORY_BLOCK).remove("logisticsBlockId");
}
Property logisticsSignId = configuration.get("logisticsSignId", Configuration.CATEGORY_BLOCK, LOGISTICS_SIGN_ID);
Property logisticsSolidBlockId = configuration.get("logisticsSolidBlockId", Configuration.CATEGORY_BLOCK, LOGISTICS_SOLID_BLOCK_ID);
Property logisticsPowerUsageDisable = configuration.get("powerUsageDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_POWER_USAGE_DISABLED);
Property logisticsTileGenericReplacementDisable = configuration.get("TileReplaceDisabled", Configuration.CATEGORY_GENERAL, LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
Property logisticsHUDRenderDistance = configuration.get("HUDRenderDistance", Configuration.CATEGORY_GENERAL, LOGISTICS_HUD_RENDER_DISTANCE);
Property mandatoryCarpenterRecipies = configuration.get("mandatoryCarpenterRecipies", Configuration.CATEGORY_GENERAL, MANDATORY_CARPENTER_RECIPES);
Property enableParticleFX = configuration.get("enableParticleFX", Configuration.CATEGORY_GENERAL, ENABLE_PARTICLE_FX);
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK3_ID = Integer.parseInt(logisticPipeCraftingMK3IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logisticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logisticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logisticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
MANDATORY_CARPENTER_RECIPES = Boolean.parseBoolean(mandatoryCarpenterRecipies.value);
ENABLE_PARTICLE_FX = Boolean.parseBoolean(enableParticleFX.value);
}
@SuppressWarnings("deprecation")
public static void load() {
File configFile = null;
if(MainProxy.isClient()) {
configFile = new File(net.minecraft.client.Minecraft.getMinecraftDir(), "config/LogisticsPipes.cfg");
} else if(MainProxy.isServer()) {
configFile = net.minecraft.server.MinecraftServer.getServer().getFile("config/LogisticsPipes.cfg");
} else {
ModLoader.getLogger().severe("No server, no client? Where am I running?");
return;
}
configuration = new Configuration(configFile);
configuration.load();
if(configuration.hasCategory("logisticspipe.id") || configuration.hasCategory("logisticsPipe.id")) {
readoldconfig();
configuration.categories.clear();
}
Property logisticRemoteOrdererIdProperty = configuration.getItem("logisticsRemoteOrderer.id", LOGISTICSREMOTEORDERER_ID);
logisticRemoteOrdererIdProperty.comment = "The item id for the remote orderer";
Property logisticNetworkMonitorIdProperty = configuration.getItem("logisticsNetworkMonitor.id", LOGISTICSNETWORKMONITOR_ID);
logisticNetworkMonitorIdProperty.comment = "The item id for the network monitor";
Property logisticPipeIdProperty = configuration.getItem("logisticsPipe.id", LOGISTICSPIPE_BASIC_ID);
logisticPipeIdProperty.comment = "The item id for the basic logistics pipe";
Property logisticPipeRequesterIdProperty = configuration.getItem("logisticsPipeRequester.id", LOGISTICSPIPE_REQUEST_ID);
logisticPipeRequesterIdProperty.comment = "The item id for the requesting logistics pipe";
Property logisticPipeProviderIdProperty = configuration.getItem("logisticsPipeProvider.id", LOGISTICSPIPE_PROVIDER_ID);
logisticPipeProviderIdProperty.comment = "The item id for the providing logistics pipe";
Property logisticPipeCraftingIdProperty = configuration.getItem("logisticsPipeCrafting.id", LOGISTICSPIPE_CRAFTING_ID);
logisticPipeCraftingIdProperty.comment = "The item id for the crafting logistics pipe";
Property logisticPipeSatelliteIdProperty = configuration.getItem("logisticsPipeSatellite.id", LOGISTICSPIPE_SATELLITE_ID);
logisticPipeSatelliteIdProperty.comment = "The item id for the crafting satellite pipe";
Property logisticPipeSupplierIdProperty = configuration.getItem("logisticsPipeSupplier.id", LOGISTICSPIPE_SUPPLIER_ID);
logisticPipeSupplierIdProperty.comment = "The item id for the supplier pipe";
Property logisticPipeChassi1IdProperty = configuration.getItem("logisticsPipeChassi1.id", LOGISTICSPIPE_CHASSI1_ID);
logisticPipeChassi1IdProperty.comment = "The item id for the chassi1";
Property logisticPipeChassi2IdProperty = configuration.getItem("logisticsPipeChassi2.id", LOGISTICSPIPE_CHASSI2_ID);
logisticPipeChassi2IdProperty.comment = "The item id for the chassi2";
Property logisticPipeChassi3IdProperty = configuration.getItem("logisticsPipeChassi3.id", LOGISTICSPIPE_CHASSI3_ID);
logisticPipeChassi3IdProperty.comment = "The item id for the chassi3";
Property logisticPipeChassi4IdProperty = configuration.getItem("logisticsPipeChassi4.id", LOGISTICSPIPE_CHASSI4_ID);
logisticPipeChassi4IdProperty.comment = "The item id for the chassi4";
Property logisticPipeChassi5IdProperty = configuration.getItem("logisticsPipeChassi5.id", LOGISTICSPIPE_CHASSI5_ID);
logisticPipeChassi5IdProperty.comment = "The item id for the chassi5";
Property logisticPipeCraftingMK2IdProperty = configuration.getItem("logisticsPipeCraftingMK2.id", LOGISTICSPIPE_CRAFTING_MK2_ID);
logisticPipeCraftingMK2IdProperty.comment = "The item id for the crafting logistics pipe MK2";
Property logisticPipeCraftingMK3IdProperty = configuration.getItem("logisticsPipeCraftingMK3.id", LOGISTICSPIPE_CRAFTING_MK3_ID);
logisticPipeCraftingMK3IdProperty.comment = "The item id for the crafting logistics pipe MK3";
Property logisticPipeFirewallIdProperty = configuration.getItem("logisticsPipeFirewall.id", LOGISTICSPIPE_FIREWALL_ID);
logisticPipeFirewallIdProperty.comment = "The item id for the firewall logistics pipe";
//DEBUG (TEST) ONLY (LIQUID)
Property logisticPipeLiquidConnectorIdProperty = null;
Property logisticPipeLiquidBasicIdProperty = null;
Property logisticPipeLiquidInsertionIdProperty = null;
Property logisticPipeLiquidProviderIdProperty = null;
Property logisticPipeLiquidRequestIdProperty = null;
if(LogisticsPipes.DEBUG) {
logisticPipeLiquidConnectorIdProperty = configuration.getItem("logisticPipeLiquidConnector.id", LOGISTICSPIPE_LIQUID_CONNECTOR);
logisticPipeLiquidConnectorIdProperty.comment = "The item id for the liquid connector pipe.";
logisticPipeLiquidBasicIdProperty = configuration.getItem("logisticPipeLiquidBasic.id", LOGISTICSPIPE_LIQUID_BASIC);
logisticPipeLiquidBasicIdProperty.comment = "The item id for the liquid basic pipe.";
logisticPipeLiquidInsertionIdProperty = configuration.getItem("logisticPipeLiquidInsertion.id", LOGISTICSPIPE_LIQUID_INSERTION);
logisticPipeLiquidInsertionIdProperty.comment = "The item id for the liquid insertion pipe.";
logisticPipeLiquidProviderIdProperty = configuration.getItem("logisticPipeLiquidProvider.id", LOGISTICSPIPE_LIQUID_PROVIDER);
logisticPipeLiquidProviderIdProperty.comment = "The item id for the liquid provider pipe.";
logisticPipeLiquidRequestIdProperty = configuration.getItem("logisticPipeLiquidRequest.id", LOGISTICSPIPE_LIQUID_REQUEST);
logisticPipeLiquidRequestIdProperty.comment = "The item id for the liquid requestor pipe.";
}
Property logisticPipeRequesterMK2IdProperty = configuration.getItem("logisticsPipeRequesterMK2.id", LOGISTICSPIPE_REQUEST_MK2_ID);
logisticPipeRequesterMK2IdProperty.comment = "The item id for the requesting logistics pipe MK2";
Property logisticPipeProviderMK2IdProperty = configuration.getItem("logisticsPipeProviderMK2.id", LOGISTICSPIPE_PROVIDER_MK2_ID);
logisticPipeProviderMK2IdProperty.comment = "The item id for the provider logistics pipe MK2";
Property logisticPipeApiaristAnalyserIdProperty = configuration.getItem("logisticsPipeApiaristAnalyser.id", LOGISTICSPIPE_APIARIST_ANALYSER_ID);
logisticPipeApiaristAnalyserIdProperty.comment = "The item id for the apiarist logistics analyser pipe";
Property logisticPipeRemoteOrdererIdProperty = configuration.getItem("logisticsPipeRemoteOrderer.id", LOGISTICSPIPE_REMOTE_ORDERER_ID);
logisticPipeRemoteOrdererIdProperty.comment = "The item id for the remote orderer logistics pipe";
Property logisticPipeApiaristSinkIdProperty = configuration.getItem("logisticsPipeApiaristSink.id", LOGISTICSPIPE_APIARIST_SINK_ID);
logisticPipeApiaristSinkIdProperty.comment = "The item id for the apiarist logistics sink pipe";
Property logisticModuleIdProperty = configuration.getItem("logisticsModules.id", ItemModuleId);
logisticModuleIdProperty.comment = "The item id for the modules";
Property logisticUpgradeIdProperty = configuration.getItem("logisticsUpgrades.id", ItemUpgradeId);
logisticUpgradeIdProperty.comment = "The item id for the upgrades";
Property logisticUpgradeManagerIdProperty = configuration.getItem("logisticsUpgradeManager.id", ItemUpgradeManagerId);
logisticUpgradeManagerIdProperty.comment = "The item id for the upgrade manager";
Property logisticItemDiskIdProperty = configuration.getItem("logisticsDisk.id", ItemDiskId);
logisticItemDiskIdProperty.comment = "The item id for the disk";
Property logisticItemHUDIdProperty = configuration.getItem("logisticsHUD.id", ItemHUDId);
logisticItemHUDIdProperty.comment = "The item id for the Logistics HUD glasses";
Property logisticItemPartsIdProperty = configuration.getItem("logisticsHUDParts.id", ItemPartsId);
logisticItemPartsIdProperty.comment = "The item id for the Logistics item parts";
Property logisticCraftingSignCreatorIdProperty = configuration.getItem("logisticsCraftingSignCreator.id", LOGISTICSCRAFTINGSIGNCREATOR_ID);
logisticCraftingSignCreatorIdProperty.comment = "The item id for the crafting sign creator";
Property logisticPipeBuilderSupplierIdProperty = configuration.getItem("logisticsPipeBuilderSupplier.id", LOGISTICSPIPE_BUILDERSUPPLIER_ID);
logisticPipeBuilderSupplierIdProperty.comment = "The item id for the builder supplier pipe";
Property logisticPipeLiquidSupplierIdProperty = configuration.getItem("logisticsPipeLiquidSupplier.id", LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
logisticPipeLiquidSupplierIdProperty.comment = "The item id for the liquid supplier pipe";
Property logisticInvSysConIdProperty = configuration.getItem("logisticInvSysCon.id", LOGISTICSPIPE_INVSYSCON_ID);
logisticInvSysConIdProperty.comment = "The item id for the inventory system connector pipe";
Property logisticEntranceIdProperty = configuration.getItem("logisticEntrance.id", LOGISTICSPIPE_ENTRANCE_ID);
logisticEntranceIdProperty.comment = "The item id for the logistics system entrance pipe";
Property logisticDestinationIdProperty = configuration.getItem("logisticDestination.id", LOGISTICSPIPE_DESTINATION_ID);
logisticDestinationIdProperty.comment = "The item id for the logistics system destination pipe";
Property logisticItemCardIdProperty = configuration.getItem("logisticItemCard.id", ItemCardId);
logisticItemCardIdProperty.comment = "The item id for the logistics item card";
//DEBUG (TEST) ONLY
Property logisticsLiquidContainerIdProperty = null;
if(LogisticsPipes.DEBUG) {
logisticsLiquidContainerIdProperty = configuration.getItem("LogisticsLiquidContainer.id", ItemLiquidContainerId);
logisticsLiquidContainerIdProperty.comment = "The item id for the logistics liquid container";
}
Property detectionLength = configuration.get(Configuration.CATEGORY_GENERAL, "detectionLength", LOGISTICS_DETECTION_LENGTH);
detectionLength.comment = "The maximum shortest length between logistics pipes. This is an indicator on the maxim depth of the recursion algorithm to discover logistics neighbours. A low value might use less CPU, a high value will allow longer pipe sections";
Property detectionCount = configuration.get(Configuration.CATEGORY_GENERAL, "detectionCount", LOGISTICS_DETECTION_COUNT);
- detectionCount.comment = "The maximum number of buildcraft pipees (including forks) between logistics pipes. This is an indicator of the maximum ammount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
+ detectionCount.comment = "The maximum number of buildcraft pipes (including forks) between logistics pipes. This is an indicator of the maximum amount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
Property detectionFrequency = configuration.get(Configuration.CATEGORY_GENERAL, "detectionFrequency", LOGISTICS_DETECTION_FREQUENCY);
detectionFrequency.comment = "The amount of time that passes between checks to see if it is still connected to its neighbours. A low value will mean that it will detect changes faster but use more CPU. A high value means detection takes longer, but CPU consumption is reduced. A value of 20 will check about every second";
Property countInvertWheelProperty = configuration.get(Configuration.CATEGORY_GENERAL, "ordererCountInvertWheel", LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
countInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order number of items";
Property pageInvertWheelProperty = configuration.get(Configuration.CATEGORY_GENERAL, "ordererPageInvertWheel", LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
pageInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order pages";
Property pageDisplayPopupProperty = configuration.get(Configuration.CATEGORY_GENERAL, "displayPopup", displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
Property logisticsSignId = configuration.getBlock("logisticsSignId", LOGISTICS_SIGN_ID);
logisticsSignId.comment = "The ID of the LogisticsPipes Sign";
Property logisticsSolidBlockId = configuration.getBlock("logisticsSolidBlockId", LOGISTICS_SOLID_BLOCK_ID);
logisticsSolidBlockId.comment = "The ID of the LogisticsPipes Solid Block";
Property logisticsPowerUsageDisable = configuration.get(Configuration.CATEGORY_GENERAL, "powerUsageDisabled", LOGISTICS_POWER_USAGE_DISABLED);
logisticsPowerUsageDisable.comment = "Diable the power usage trough LogisticsPipes";
Property logisticsTileGenericReplacementDisable = configuration.get(Configuration.CATEGORY_GENERAL, "TileReplaceDisabled", LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
logisticsTileGenericReplacementDisable.comment = "Diable the Replacement of the TileGenericPipe trough the LogisticsTileGenericPipe";
Property logisticsHUDRenderDistance = configuration.get(Configuration.CATEGORY_GENERAL, "HUDRenderDistance", LOGISTICS_HUD_RENDER_DISTANCE);
logisticsHUDRenderDistance.comment = "The max. distance between a player and the HUD that get's shown in blocks.";
Property mandatoryCarpenterRecipes = configuration.get(Configuration.CATEGORY_GENERAL, "mandatoryCarpenterRecipes", MANDATORY_CARPENTER_RECIPES);
mandatoryCarpenterRecipes.comment = "Whether or not the Carpenter is required to craft Forestry related pipes/modules.";
Property enableParticleFX = configuration.get(Configuration.CATEGORY_GENERAL, "enableParticleFX", ENABLE_PARTICLE_FX);
enableParticleFX.comment = "Whether or not special particles will spawn.";
Property powerUsageMultiplyerPref = configuration.get(Configuration.CATEGORY_GENERAL, "powerUsageMultiplyer", powerUsageMultiplyer);
powerUsageMultiplyerPref.comment = "A Multiplyer for the power usage.";
Property multiThread = configuration.get(CATEGORY_MULTITHREAD, "enabled", multiThreadEnabled);
multiThread.comment = "Enabled the Logistics Pipes multiThread function to allow the network.";
Property multiThreadCount = configuration.get(CATEGORY_MULTITHREAD, "count", multiThreadNumber);
multiThreadCount.comment = "Number of running Threads.";
Property multiThreadPrio = configuration.get(CATEGORY_MULTITHREAD, "priority", multiThreadPriority);
multiThreadPrio.comment = "Priority of the multiThread Threads. 10 is highest, 5 normal, 1 lowest";
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemUpgradeId = Integer.parseInt(logisticUpgradeIdProperty.value);
ItemUpgradeManagerId = Integer.parseInt(logisticUpgradeManagerIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
//DEBUG (TEST) ONLY
if(LogisticsPipes.DEBUG) {
ItemLiquidContainerId = Integer.parseInt(logisticsLiquidContainerIdProperty.value);
}
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK3_ID = Integer.parseInt(logisticPipeCraftingMK3IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICSPIPE_FIREWALL_ID = logisticPipeFirewallIdProperty.getInt();
//DEBUG (TEST) ONLY (LIQUID)
if(LogisticsPipes.DEBUG) {
LOGISTICSPIPE_LIQUID_CONNECTOR = logisticPipeLiquidConnectorIdProperty.getInt();
LOGISTICSPIPE_LIQUID_BASIC = logisticPipeLiquidBasicIdProperty.getInt();
LOGISTICSPIPE_LIQUID_INSERTION = logisticPipeLiquidInsertionIdProperty.getInt();
LOGISTICSPIPE_LIQUID_PROVIDER = logisticPipeLiquidProviderIdProperty.getInt();
LOGISTICSPIPE_LIQUID_REQUEST = logisticPipeLiquidRequestIdProperty.getInt();
}
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logisticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logisticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logisticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
MANDATORY_CARPENTER_RECIPES = Boolean.parseBoolean(mandatoryCarpenterRecipes.value);
ENABLE_PARTICLE_FX = Boolean.parseBoolean(enableParticleFX.value);
multiThreadEnabled = multiThread.getBoolean(multiThreadEnabled);
multiThreadNumber = multiThreadCount.getInt();
if(multiThreadNumber < 1) {
multiThreadNumber = 1;
multiThreadCount.value = Integer.toString(multiThreadNumber);
}
multiThreadPriority = multiThreadPrio.getInt();
if(multiThreadPriority < 1 || multiThreadPriority > 10) {
multiThreadPriority = Thread.NORM_PRIORITY;
multiThreadPrio.value = Integer.toString(Thread.NORM_PRIORITY);
}
powerUsageMultiplyer = powerUsageMultiplyerPref.getInt();
if(powerUsageMultiplyer < 1) {
powerUsageMultiplyer = 1;
powerUsageMultiplyerPref.value = "1";
}
configuration.save();
}
public static void savePopupState() {
Property pageDisplayPopupProperty = configuration.get(Configuration.CATEGORY_GENERAL, "displayPopup", displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
pageDisplayPopupProperty.value = Boolean.toString(displayPopup);
configuration.save();
}
}
| true | true | public static void load() {
File configFile = null;
if(MainProxy.isClient()) {
configFile = new File(net.minecraft.client.Minecraft.getMinecraftDir(), "config/LogisticsPipes.cfg");
} else if(MainProxy.isServer()) {
configFile = net.minecraft.server.MinecraftServer.getServer().getFile("config/LogisticsPipes.cfg");
} else {
ModLoader.getLogger().severe("No server, no client? Where am I running?");
return;
}
configuration = new Configuration(configFile);
configuration.load();
if(configuration.hasCategory("logisticspipe.id") || configuration.hasCategory("logisticsPipe.id")) {
readoldconfig();
configuration.categories.clear();
}
Property logisticRemoteOrdererIdProperty = configuration.getItem("logisticsRemoteOrderer.id", LOGISTICSREMOTEORDERER_ID);
logisticRemoteOrdererIdProperty.comment = "The item id for the remote orderer";
Property logisticNetworkMonitorIdProperty = configuration.getItem("logisticsNetworkMonitor.id", LOGISTICSNETWORKMONITOR_ID);
logisticNetworkMonitorIdProperty.comment = "The item id for the network monitor";
Property logisticPipeIdProperty = configuration.getItem("logisticsPipe.id", LOGISTICSPIPE_BASIC_ID);
logisticPipeIdProperty.comment = "The item id for the basic logistics pipe";
Property logisticPipeRequesterIdProperty = configuration.getItem("logisticsPipeRequester.id", LOGISTICSPIPE_REQUEST_ID);
logisticPipeRequesterIdProperty.comment = "The item id for the requesting logistics pipe";
Property logisticPipeProviderIdProperty = configuration.getItem("logisticsPipeProvider.id", LOGISTICSPIPE_PROVIDER_ID);
logisticPipeProviderIdProperty.comment = "The item id for the providing logistics pipe";
Property logisticPipeCraftingIdProperty = configuration.getItem("logisticsPipeCrafting.id", LOGISTICSPIPE_CRAFTING_ID);
logisticPipeCraftingIdProperty.comment = "The item id for the crafting logistics pipe";
Property logisticPipeSatelliteIdProperty = configuration.getItem("logisticsPipeSatellite.id", LOGISTICSPIPE_SATELLITE_ID);
logisticPipeSatelliteIdProperty.comment = "The item id for the crafting satellite pipe";
Property logisticPipeSupplierIdProperty = configuration.getItem("logisticsPipeSupplier.id", LOGISTICSPIPE_SUPPLIER_ID);
logisticPipeSupplierIdProperty.comment = "The item id for the supplier pipe";
Property logisticPipeChassi1IdProperty = configuration.getItem("logisticsPipeChassi1.id", LOGISTICSPIPE_CHASSI1_ID);
logisticPipeChassi1IdProperty.comment = "The item id for the chassi1";
Property logisticPipeChassi2IdProperty = configuration.getItem("logisticsPipeChassi2.id", LOGISTICSPIPE_CHASSI2_ID);
logisticPipeChassi2IdProperty.comment = "The item id for the chassi2";
Property logisticPipeChassi3IdProperty = configuration.getItem("logisticsPipeChassi3.id", LOGISTICSPIPE_CHASSI3_ID);
logisticPipeChassi3IdProperty.comment = "The item id for the chassi3";
Property logisticPipeChassi4IdProperty = configuration.getItem("logisticsPipeChassi4.id", LOGISTICSPIPE_CHASSI4_ID);
logisticPipeChassi4IdProperty.comment = "The item id for the chassi4";
Property logisticPipeChassi5IdProperty = configuration.getItem("logisticsPipeChassi5.id", LOGISTICSPIPE_CHASSI5_ID);
logisticPipeChassi5IdProperty.comment = "The item id for the chassi5";
Property logisticPipeCraftingMK2IdProperty = configuration.getItem("logisticsPipeCraftingMK2.id", LOGISTICSPIPE_CRAFTING_MK2_ID);
logisticPipeCraftingMK2IdProperty.comment = "The item id for the crafting logistics pipe MK2";
Property logisticPipeCraftingMK3IdProperty = configuration.getItem("logisticsPipeCraftingMK3.id", LOGISTICSPIPE_CRAFTING_MK3_ID);
logisticPipeCraftingMK3IdProperty.comment = "The item id for the crafting logistics pipe MK3";
Property logisticPipeFirewallIdProperty = configuration.getItem("logisticsPipeFirewall.id", LOGISTICSPIPE_FIREWALL_ID);
logisticPipeFirewallIdProperty.comment = "The item id for the firewall logistics pipe";
//DEBUG (TEST) ONLY (LIQUID)
Property logisticPipeLiquidConnectorIdProperty = null;
Property logisticPipeLiquidBasicIdProperty = null;
Property logisticPipeLiquidInsertionIdProperty = null;
Property logisticPipeLiquidProviderIdProperty = null;
Property logisticPipeLiquidRequestIdProperty = null;
if(LogisticsPipes.DEBUG) {
logisticPipeLiquidConnectorIdProperty = configuration.getItem("logisticPipeLiquidConnector.id", LOGISTICSPIPE_LIQUID_CONNECTOR);
logisticPipeLiquidConnectorIdProperty.comment = "The item id for the liquid connector pipe.";
logisticPipeLiquidBasicIdProperty = configuration.getItem("logisticPipeLiquidBasic.id", LOGISTICSPIPE_LIQUID_BASIC);
logisticPipeLiquidBasicIdProperty.comment = "The item id for the liquid basic pipe.";
logisticPipeLiquidInsertionIdProperty = configuration.getItem("logisticPipeLiquidInsertion.id", LOGISTICSPIPE_LIQUID_INSERTION);
logisticPipeLiquidInsertionIdProperty.comment = "The item id for the liquid insertion pipe.";
logisticPipeLiquidProviderIdProperty = configuration.getItem("logisticPipeLiquidProvider.id", LOGISTICSPIPE_LIQUID_PROVIDER);
logisticPipeLiquidProviderIdProperty.comment = "The item id for the liquid provider pipe.";
logisticPipeLiquidRequestIdProperty = configuration.getItem("logisticPipeLiquidRequest.id", LOGISTICSPIPE_LIQUID_REQUEST);
logisticPipeLiquidRequestIdProperty.comment = "The item id for the liquid requestor pipe.";
}
Property logisticPipeRequesterMK2IdProperty = configuration.getItem("logisticsPipeRequesterMK2.id", LOGISTICSPIPE_REQUEST_MK2_ID);
logisticPipeRequesterMK2IdProperty.comment = "The item id for the requesting logistics pipe MK2";
Property logisticPipeProviderMK2IdProperty = configuration.getItem("logisticsPipeProviderMK2.id", LOGISTICSPIPE_PROVIDER_MK2_ID);
logisticPipeProviderMK2IdProperty.comment = "The item id for the provider logistics pipe MK2";
Property logisticPipeApiaristAnalyserIdProperty = configuration.getItem("logisticsPipeApiaristAnalyser.id", LOGISTICSPIPE_APIARIST_ANALYSER_ID);
logisticPipeApiaristAnalyserIdProperty.comment = "The item id for the apiarist logistics analyser pipe";
Property logisticPipeRemoteOrdererIdProperty = configuration.getItem("logisticsPipeRemoteOrderer.id", LOGISTICSPIPE_REMOTE_ORDERER_ID);
logisticPipeRemoteOrdererIdProperty.comment = "The item id for the remote orderer logistics pipe";
Property logisticPipeApiaristSinkIdProperty = configuration.getItem("logisticsPipeApiaristSink.id", LOGISTICSPIPE_APIARIST_SINK_ID);
logisticPipeApiaristSinkIdProperty.comment = "The item id for the apiarist logistics sink pipe";
Property logisticModuleIdProperty = configuration.getItem("logisticsModules.id", ItemModuleId);
logisticModuleIdProperty.comment = "The item id for the modules";
Property logisticUpgradeIdProperty = configuration.getItem("logisticsUpgrades.id", ItemUpgradeId);
logisticUpgradeIdProperty.comment = "The item id for the upgrades";
Property logisticUpgradeManagerIdProperty = configuration.getItem("logisticsUpgradeManager.id", ItemUpgradeManagerId);
logisticUpgradeManagerIdProperty.comment = "The item id for the upgrade manager";
Property logisticItemDiskIdProperty = configuration.getItem("logisticsDisk.id", ItemDiskId);
logisticItemDiskIdProperty.comment = "The item id for the disk";
Property logisticItemHUDIdProperty = configuration.getItem("logisticsHUD.id", ItemHUDId);
logisticItemHUDIdProperty.comment = "The item id for the Logistics HUD glasses";
Property logisticItemPartsIdProperty = configuration.getItem("logisticsHUDParts.id", ItemPartsId);
logisticItemPartsIdProperty.comment = "The item id for the Logistics item parts";
Property logisticCraftingSignCreatorIdProperty = configuration.getItem("logisticsCraftingSignCreator.id", LOGISTICSCRAFTINGSIGNCREATOR_ID);
logisticCraftingSignCreatorIdProperty.comment = "The item id for the crafting sign creator";
Property logisticPipeBuilderSupplierIdProperty = configuration.getItem("logisticsPipeBuilderSupplier.id", LOGISTICSPIPE_BUILDERSUPPLIER_ID);
logisticPipeBuilderSupplierIdProperty.comment = "The item id for the builder supplier pipe";
Property logisticPipeLiquidSupplierIdProperty = configuration.getItem("logisticsPipeLiquidSupplier.id", LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
logisticPipeLiquidSupplierIdProperty.comment = "The item id for the liquid supplier pipe";
Property logisticInvSysConIdProperty = configuration.getItem("logisticInvSysCon.id", LOGISTICSPIPE_INVSYSCON_ID);
logisticInvSysConIdProperty.comment = "The item id for the inventory system connector pipe";
Property logisticEntranceIdProperty = configuration.getItem("logisticEntrance.id", LOGISTICSPIPE_ENTRANCE_ID);
logisticEntranceIdProperty.comment = "The item id for the logistics system entrance pipe";
Property logisticDestinationIdProperty = configuration.getItem("logisticDestination.id", LOGISTICSPIPE_DESTINATION_ID);
logisticDestinationIdProperty.comment = "The item id for the logistics system destination pipe";
Property logisticItemCardIdProperty = configuration.getItem("logisticItemCard.id", ItemCardId);
logisticItemCardIdProperty.comment = "The item id for the logistics item card";
//DEBUG (TEST) ONLY
Property logisticsLiquidContainerIdProperty = null;
if(LogisticsPipes.DEBUG) {
logisticsLiquidContainerIdProperty = configuration.getItem("LogisticsLiquidContainer.id", ItemLiquidContainerId);
logisticsLiquidContainerIdProperty.comment = "The item id for the logistics liquid container";
}
Property detectionLength = configuration.get(Configuration.CATEGORY_GENERAL, "detectionLength", LOGISTICS_DETECTION_LENGTH);
detectionLength.comment = "The maximum shortest length between logistics pipes. This is an indicator on the maxim depth of the recursion algorithm to discover logistics neighbours. A low value might use less CPU, a high value will allow longer pipe sections";
Property detectionCount = configuration.get(Configuration.CATEGORY_GENERAL, "detectionCount", LOGISTICS_DETECTION_COUNT);
detectionCount.comment = "The maximum number of buildcraft pipees (including forks) between logistics pipes. This is an indicator of the maximum ammount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
Property detectionFrequency = configuration.get(Configuration.CATEGORY_GENERAL, "detectionFrequency", LOGISTICS_DETECTION_FREQUENCY);
detectionFrequency.comment = "The amount of time that passes between checks to see if it is still connected to its neighbours. A low value will mean that it will detect changes faster but use more CPU. A high value means detection takes longer, but CPU consumption is reduced. A value of 20 will check about every second";
Property countInvertWheelProperty = configuration.get(Configuration.CATEGORY_GENERAL, "ordererCountInvertWheel", LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
countInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order number of items";
Property pageInvertWheelProperty = configuration.get(Configuration.CATEGORY_GENERAL, "ordererPageInvertWheel", LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
pageInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order pages";
Property pageDisplayPopupProperty = configuration.get(Configuration.CATEGORY_GENERAL, "displayPopup", displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
Property logisticsSignId = configuration.getBlock("logisticsSignId", LOGISTICS_SIGN_ID);
logisticsSignId.comment = "The ID of the LogisticsPipes Sign";
Property logisticsSolidBlockId = configuration.getBlock("logisticsSolidBlockId", LOGISTICS_SOLID_BLOCK_ID);
logisticsSolidBlockId.comment = "The ID of the LogisticsPipes Solid Block";
Property logisticsPowerUsageDisable = configuration.get(Configuration.CATEGORY_GENERAL, "powerUsageDisabled", LOGISTICS_POWER_USAGE_DISABLED);
logisticsPowerUsageDisable.comment = "Diable the power usage trough LogisticsPipes";
Property logisticsTileGenericReplacementDisable = configuration.get(Configuration.CATEGORY_GENERAL, "TileReplaceDisabled", LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
logisticsTileGenericReplacementDisable.comment = "Diable the Replacement of the TileGenericPipe trough the LogisticsTileGenericPipe";
Property logisticsHUDRenderDistance = configuration.get(Configuration.CATEGORY_GENERAL, "HUDRenderDistance", LOGISTICS_HUD_RENDER_DISTANCE);
logisticsHUDRenderDistance.comment = "The max. distance between a player and the HUD that get's shown in blocks.";
Property mandatoryCarpenterRecipes = configuration.get(Configuration.CATEGORY_GENERAL, "mandatoryCarpenterRecipes", MANDATORY_CARPENTER_RECIPES);
mandatoryCarpenterRecipes.comment = "Whether or not the Carpenter is required to craft Forestry related pipes/modules.";
Property enableParticleFX = configuration.get(Configuration.CATEGORY_GENERAL, "enableParticleFX", ENABLE_PARTICLE_FX);
enableParticleFX.comment = "Whether or not special particles will spawn.";
Property powerUsageMultiplyerPref = configuration.get(Configuration.CATEGORY_GENERAL, "powerUsageMultiplyer", powerUsageMultiplyer);
powerUsageMultiplyerPref.comment = "A Multiplyer for the power usage.";
Property multiThread = configuration.get(CATEGORY_MULTITHREAD, "enabled", multiThreadEnabled);
multiThread.comment = "Enabled the Logistics Pipes multiThread function to allow the network.";
Property multiThreadCount = configuration.get(CATEGORY_MULTITHREAD, "count", multiThreadNumber);
multiThreadCount.comment = "Number of running Threads.";
Property multiThreadPrio = configuration.get(CATEGORY_MULTITHREAD, "priority", multiThreadPriority);
multiThreadPrio.comment = "Priority of the multiThread Threads. 10 is highest, 5 normal, 1 lowest";
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemUpgradeId = Integer.parseInt(logisticUpgradeIdProperty.value);
ItemUpgradeManagerId = Integer.parseInt(logisticUpgradeManagerIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
//DEBUG (TEST) ONLY
if(LogisticsPipes.DEBUG) {
ItemLiquidContainerId = Integer.parseInt(logisticsLiquidContainerIdProperty.value);
}
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK3_ID = Integer.parseInt(logisticPipeCraftingMK3IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICSPIPE_FIREWALL_ID = logisticPipeFirewallIdProperty.getInt();
//DEBUG (TEST) ONLY (LIQUID)
if(LogisticsPipes.DEBUG) {
LOGISTICSPIPE_LIQUID_CONNECTOR = logisticPipeLiquidConnectorIdProperty.getInt();
LOGISTICSPIPE_LIQUID_BASIC = logisticPipeLiquidBasicIdProperty.getInt();
LOGISTICSPIPE_LIQUID_INSERTION = logisticPipeLiquidInsertionIdProperty.getInt();
LOGISTICSPIPE_LIQUID_PROVIDER = logisticPipeLiquidProviderIdProperty.getInt();
LOGISTICSPIPE_LIQUID_REQUEST = logisticPipeLiquidRequestIdProperty.getInt();
}
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logisticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logisticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logisticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
MANDATORY_CARPENTER_RECIPES = Boolean.parseBoolean(mandatoryCarpenterRecipes.value);
ENABLE_PARTICLE_FX = Boolean.parseBoolean(enableParticleFX.value);
multiThreadEnabled = multiThread.getBoolean(multiThreadEnabled);
multiThreadNumber = multiThreadCount.getInt();
if(multiThreadNumber < 1) {
multiThreadNumber = 1;
multiThreadCount.value = Integer.toString(multiThreadNumber);
}
multiThreadPriority = multiThreadPrio.getInt();
if(multiThreadPriority < 1 || multiThreadPriority > 10) {
multiThreadPriority = Thread.NORM_PRIORITY;
multiThreadPrio.value = Integer.toString(Thread.NORM_PRIORITY);
}
powerUsageMultiplyer = powerUsageMultiplyerPref.getInt();
if(powerUsageMultiplyer < 1) {
powerUsageMultiplyer = 1;
powerUsageMultiplyerPref.value = "1";
}
configuration.save();
}
| public static void load() {
File configFile = null;
if(MainProxy.isClient()) {
configFile = new File(net.minecraft.client.Minecraft.getMinecraftDir(), "config/LogisticsPipes.cfg");
} else if(MainProxy.isServer()) {
configFile = net.minecraft.server.MinecraftServer.getServer().getFile("config/LogisticsPipes.cfg");
} else {
ModLoader.getLogger().severe("No server, no client? Where am I running?");
return;
}
configuration = new Configuration(configFile);
configuration.load();
if(configuration.hasCategory("logisticspipe.id") || configuration.hasCategory("logisticsPipe.id")) {
readoldconfig();
configuration.categories.clear();
}
Property logisticRemoteOrdererIdProperty = configuration.getItem("logisticsRemoteOrderer.id", LOGISTICSREMOTEORDERER_ID);
logisticRemoteOrdererIdProperty.comment = "The item id for the remote orderer";
Property logisticNetworkMonitorIdProperty = configuration.getItem("logisticsNetworkMonitor.id", LOGISTICSNETWORKMONITOR_ID);
logisticNetworkMonitorIdProperty.comment = "The item id for the network monitor";
Property logisticPipeIdProperty = configuration.getItem("logisticsPipe.id", LOGISTICSPIPE_BASIC_ID);
logisticPipeIdProperty.comment = "The item id for the basic logistics pipe";
Property logisticPipeRequesterIdProperty = configuration.getItem("logisticsPipeRequester.id", LOGISTICSPIPE_REQUEST_ID);
logisticPipeRequesterIdProperty.comment = "The item id for the requesting logistics pipe";
Property logisticPipeProviderIdProperty = configuration.getItem("logisticsPipeProvider.id", LOGISTICSPIPE_PROVIDER_ID);
logisticPipeProviderIdProperty.comment = "The item id for the providing logistics pipe";
Property logisticPipeCraftingIdProperty = configuration.getItem("logisticsPipeCrafting.id", LOGISTICSPIPE_CRAFTING_ID);
logisticPipeCraftingIdProperty.comment = "The item id for the crafting logistics pipe";
Property logisticPipeSatelliteIdProperty = configuration.getItem("logisticsPipeSatellite.id", LOGISTICSPIPE_SATELLITE_ID);
logisticPipeSatelliteIdProperty.comment = "The item id for the crafting satellite pipe";
Property logisticPipeSupplierIdProperty = configuration.getItem("logisticsPipeSupplier.id", LOGISTICSPIPE_SUPPLIER_ID);
logisticPipeSupplierIdProperty.comment = "The item id for the supplier pipe";
Property logisticPipeChassi1IdProperty = configuration.getItem("logisticsPipeChassi1.id", LOGISTICSPIPE_CHASSI1_ID);
logisticPipeChassi1IdProperty.comment = "The item id for the chassi1";
Property logisticPipeChassi2IdProperty = configuration.getItem("logisticsPipeChassi2.id", LOGISTICSPIPE_CHASSI2_ID);
logisticPipeChassi2IdProperty.comment = "The item id for the chassi2";
Property logisticPipeChassi3IdProperty = configuration.getItem("logisticsPipeChassi3.id", LOGISTICSPIPE_CHASSI3_ID);
logisticPipeChassi3IdProperty.comment = "The item id for the chassi3";
Property logisticPipeChassi4IdProperty = configuration.getItem("logisticsPipeChassi4.id", LOGISTICSPIPE_CHASSI4_ID);
logisticPipeChassi4IdProperty.comment = "The item id for the chassi4";
Property logisticPipeChassi5IdProperty = configuration.getItem("logisticsPipeChassi5.id", LOGISTICSPIPE_CHASSI5_ID);
logisticPipeChassi5IdProperty.comment = "The item id for the chassi5";
Property logisticPipeCraftingMK2IdProperty = configuration.getItem("logisticsPipeCraftingMK2.id", LOGISTICSPIPE_CRAFTING_MK2_ID);
logisticPipeCraftingMK2IdProperty.comment = "The item id for the crafting logistics pipe MK2";
Property logisticPipeCraftingMK3IdProperty = configuration.getItem("logisticsPipeCraftingMK3.id", LOGISTICSPIPE_CRAFTING_MK3_ID);
logisticPipeCraftingMK3IdProperty.comment = "The item id for the crafting logistics pipe MK3";
Property logisticPipeFirewallIdProperty = configuration.getItem("logisticsPipeFirewall.id", LOGISTICSPIPE_FIREWALL_ID);
logisticPipeFirewallIdProperty.comment = "The item id for the firewall logistics pipe";
//DEBUG (TEST) ONLY (LIQUID)
Property logisticPipeLiquidConnectorIdProperty = null;
Property logisticPipeLiquidBasicIdProperty = null;
Property logisticPipeLiquidInsertionIdProperty = null;
Property logisticPipeLiquidProviderIdProperty = null;
Property logisticPipeLiquidRequestIdProperty = null;
if(LogisticsPipes.DEBUG) {
logisticPipeLiquidConnectorIdProperty = configuration.getItem("logisticPipeLiquidConnector.id", LOGISTICSPIPE_LIQUID_CONNECTOR);
logisticPipeLiquidConnectorIdProperty.comment = "The item id for the liquid connector pipe.";
logisticPipeLiquidBasicIdProperty = configuration.getItem("logisticPipeLiquidBasic.id", LOGISTICSPIPE_LIQUID_BASIC);
logisticPipeLiquidBasicIdProperty.comment = "The item id for the liquid basic pipe.";
logisticPipeLiquidInsertionIdProperty = configuration.getItem("logisticPipeLiquidInsertion.id", LOGISTICSPIPE_LIQUID_INSERTION);
logisticPipeLiquidInsertionIdProperty.comment = "The item id for the liquid insertion pipe.";
logisticPipeLiquidProviderIdProperty = configuration.getItem("logisticPipeLiquidProvider.id", LOGISTICSPIPE_LIQUID_PROVIDER);
logisticPipeLiquidProviderIdProperty.comment = "The item id for the liquid provider pipe.";
logisticPipeLiquidRequestIdProperty = configuration.getItem("logisticPipeLiquidRequest.id", LOGISTICSPIPE_LIQUID_REQUEST);
logisticPipeLiquidRequestIdProperty.comment = "The item id for the liquid requestor pipe.";
}
Property logisticPipeRequesterMK2IdProperty = configuration.getItem("logisticsPipeRequesterMK2.id", LOGISTICSPIPE_REQUEST_MK2_ID);
logisticPipeRequesterMK2IdProperty.comment = "The item id for the requesting logistics pipe MK2";
Property logisticPipeProviderMK2IdProperty = configuration.getItem("logisticsPipeProviderMK2.id", LOGISTICSPIPE_PROVIDER_MK2_ID);
logisticPipeProviderMK2IdProperty.comment = "The item id for the provider logistics pipe MK2";
Property logisticPipeApiaristAnalyserIdProperty = configuration.getItem("logisticsPipeApiaristAnalyser.id", LOGISTICSPIPE_APIARIST_ANALYSER_ID);
logisticPipeApiaristAnalyserIdProperty.comment = "The item id for the apiarist logistics analyser pipe";
Property logisticPipeRemoteOrdererIdProperty = configuration.getItem("logisticsPipeRemoteOrderer.id", LOGISTICSPIPE_REMOTE_ORDERER_ID);
logisticPipeRemoteOrdererIdProperty.comment = "The item id for the remote orderer logistics pipe";
Property logisticPipeApiaristSinkIdProperty = configuration.getItem("logisticsPipeApiaristSink.id", LOGISTICSPIPE_APIARIST_SINK_ID);
logisticPipeApiaristSinkIdProperty.comment = "The item id for the apiarist logistics sink pipe";
Property logisticModuleIdProperty = configuration.getItem("logisticsModules.id", ItemModuleId);
logisticModuleIdProperty.comment = "The item id for the modules";
Property logisticUpgradeIdProperty = configuration.getItem("logisticsUpgrades.id", ItemUpgradeId);
logisticUpgradeIdProperty.comment = "The item id for the upgrades";
Property logisticUpgradeManagerIdProperty = configuration.getItem("logisticsUpgradeManager.id", ItemUpgradeManagerId);
logisticUpgradeManagerIdProperty.comment = "The item id for the upgrade manager";
Property logisticItemDiskIdProperty = configuration.getItem("logisticsDisk.id", ItemDiskId);
logisticItemDiskIdProperty.comment = "The item id for the disk";
Property logisticItemHUDIdProperty = configuration.getItem("logisticsHUD.id", ItemHUDId);
logisticItemHUDIdProperty.comment = "The item id for the Logistics HUD glasses";
Property logisticItemPartsIdProperty = configuration.getItem("logisticsHUDParts.id", ItemPartsId);
logisticItemPartsIdProperty.comment = "The item id for the Logistics item parts";
Property logisticCraftingSignCreatorIdProperty = configuration.getItem("logisticsCraftingSignCreator.id", LOGISTICSCRAFTINGSIGNCREATOR_ID);
logisticCraftingSignCreatorIdProperty.comment = "The item id for the crafting sign creator";
Property logisticPipeBuilderSupplierIdProperty = configuration.getItem("logisticsPipeBuilderSupplier.id", LOGISTICSPIPE_BUILDERSUPPLIER_ID);
logisticPipeBuilderSupplierIdProperty.comment = "The item id for the builder supplier pipe";
Property logisticPipeLiquidSupplierIdProperty = configuration.getItem("logisticsPipeLiquidSupplier.id", LOGISTICSPIPE_LIQUIDSUPPLIER_ID);
logisticPipeLiquidSupplierIdProperty.comment = "The item id for the liquid supplier pipe";
Property logisticInvSysConIdProperty = configuration.getItem("logisticInvSysCon.id", LOGISTICSPIPE_INVSYSCON_ID);
logisticInvSysConIdProperty.comment = "The item id for the inventory system connector pipe";
Property logisticEntranceIdProperty = configuration.getItem("logisticEntrance.id", LOGISTICSPIPE_ENTRANCE_ID);
logisticEntranceIdProperty.comment = "The item id for the logistics system entrance pipe";
Property logisticDestinationIdProperty = configuration.getItem("logisticDestination.id", LOGISTICSPIPE_DESTINATION_ID);
logisticDestinationIdProperty.comment = "The item id for the logistics system destination pipe";
Property logisticItemCardIdProperty = configuration.getItem("logisticItemCard.id", ItemCardId);
logisticItemCardIdProperty.comment = "The item id for the logistics item card";
//DEBUG (TEST) ONLY
Property logisticsLiquidContainerIdProperty = null;
if(LogisticsPipes.DEBUG) {
logisticsLiquidContainerIdProperty = configuration.getItem("LogisticsLiquidContainer.id", ItemLiquidContainerId);
logisticsLiquidContainerIdProperty.comment = "The item id for the logistics liquid container";
}
Property detectionLength = configuration.get(Configuration.CATEGORY_GENERAL, "detectionLength", LOGISTICS_DETECTION_LENGTH);
detectionLength.comment = "The maximum shortest length between logistics pipes. This is an indicator on the maxim depth of the recursion algorithm to discover logistics neighbours. A low value might use less CPU, a high value will allow longer pipe sections";
Property detectionCount = configuration.get(Configuration.CATEGORY_GENERAL, "detectionCount", LOGISTICS_DETECTION_COUNT);
detectionCount.comment = "The maximum number of buildcraft pipes (including forks) between logistics pipes. This is an indicator of the maximum amount of nodes the recursion algorithm will visit before giving up. As it is possible to fork a pipe connection using standard BC pipes the algorithm will attempt to discover all available destinations through that pipe. Do note that the logistics system will not interfere with the operation of non-logistics pipes. So a forked pipe will usually be sup-optimal, but it is possible. A low value might reduce CPU usage, a high value will be able to handle more complex pipe setups. If you never fork your connection between the logistics pipes this has the same meaning as detectionLength and the lower of the two will be used";
Property detectionFrequency = configuration.get(Configuration.CATEGORY_GENERAL, "detectionFrequency", LOGISTICS_DETECTION_FREQUENCY);
detectionFrequency.comment = "The amount of time that passes between checks to see if it is still connected to its neighbours. A low value will mean that it will detect changes faster but use more CPU. A high value means detection takes longer, but CPU consumption is reduced. A value of 20 will check about every second";
Property countInvertWheelProperty = configuration.get(Configuration.CATEGORY_GENERAL, "ordererCountInvertWheel", LOGISTICS_ORDERER_COUNT_INVERTWHEEL);
countInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order number of items";
Property pageInvertWheelProperty = configuration.get(Configuration.CATEGORY_GENERAL, "ordererPageInvertWheel", LOGISTICS_ORDERER_PAGE_INVERTWHEEL);
pageInvertWheelProperty.comment = "Inverts the the mouse wheel scrolling for remote order pages";
Property pageDisplayPopupProperty = configuration.get(Configuration.CATEGORY_GENERAL, "displayPopup", displayPopup);
pageDisplayPopupProperty.comment = "Set the default configuration for the popup of the Orderer Gui. Should it be used?";
Property logisticsSignId = configuration.getBlock("logisticsSignId", LOGISTICS_SIGN_ID);
logisticsSignId.comment = "The ID of the LogisticsPipes Sign";
Property logisticsSolidBlockId = configuration.getBlock("logisticsSolidBlockId", LOGISTICS_SOLID_BLOCK_ID);
logisticsSolidBlockId.comment = "The ID of the LogisticsPipes Solid Block";
Property logisticsPowerUsageDisable = configuration.get(Configuration.CATEGORY_GENERAL, "powerUsageDisabled", LOGISTICS_POWER_USAGE_DISABLED);
logisticsPowerUsageDisable.comment = "Diable the power usage trough LogisticsPipes";
Property logisticsTileGenericReplacementDisable = configuration.get(Configuration.CATEGORY_GENERAL, "TileReplaceDisabled", LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED);
logisticsTileGenericReplacementDisable.comment = "Diable the Replacement of the TileGenericPipe trough the LogisticsTileGenericPipe";
Property logisticsHUDRenderDistance = configuration.get(Configuration.CATEGORY_GENERAL, "HUDRenderDistance", LOGISTICS_HUD_RENDER_DISTANCE);
logisticsHUDRenderDistance.comment = "The max. distance between a player and the HUD that get's shown in blocks.";
Property mandatoryCarpenterRecipes = configuration.get(Configuration.CATEGORY_GENERAL, "mandatoryCarpenterRecipes", MANDATORY_CARPENTER_RECIPES);
mandatoryCarpenterRecipes.comment = "Whether or not the Carpenter is required to craft Forestry related pipes/modules.";
Property enableParticleFX = configuration.get(Configuration.CATEGORY_GENERAL, "enableParticleFX", ENABLE_PARTICLE_FX);
enableParticleFX.comment = "Whether or not special particles will spawn.";
Property powerUsageMultiplyerPref = configuration.get(Configuration.CATEGORY_GENERAL, "powerUsageMultiplyer", powerUsageMultiplyer);
powerUsageMultiplyerPref.comment = "A Multiplyer for the power usage.";
Property multiThread = configuration.get(CATEGORY_MULTITHREAD, "enabled", multiThreadEnabled);
multiThread.comment = "Enabled the Logistics Pipes multiThread function to allow the network.";
Property multiThreadCount = configuration.get(CATEGORY_MULTITHREAD, "count", multiThreadNumber);
multiThreadCount.comment = "Number of running Threads.";
Property multiThreadPrio = configuration.get(CATEGORY_MULTITHREAD, "priority", multiThreadPriority);
multiThreadPrio.comment = "Priority of the multiThread Threads. 10 is highest, 5 normal, 1 lowest";
LOGISTICSNETWORKMONITOR_ID = Integer.parseInt(logisticNetworkMonitorIdProperty.value);
LOGISTICSREMOTEORDERER_ID = Integer.parseInt(logisticRemoteOrdererIdProperty.value);
ItemModuleId = Integer.parseInt(logisticModuleIdProperty.value);
ItemUpgradeId = Integer.parseInt(logisticUpgradeIdProperty.value);
ItemUpgradeManagerId = Integer.parseInt(logisticUpgradeManagerIdProperty.value);
ItemDiskId = Integer.parseInt(logisticItemDiskIdProperty.value);
ItemCardId = Integer.parseInt(logisticItemCardIdProperty.value);
ItemHUDId = Integer.parseInt(logisticItemHUDIdProperty.value);
ItemPartsId = Integer.parseInt(logisticItemPartsIdProperty.value);
//DEBUG (TEST) ONLY
if(LogisticsPipes.DEBUG) {
ItemLiquidContainerId = Integer.parseInt(logisticsLiquidContainerIdProperty.value);
}
LOGISTICSPIPE_BASIC_ID = Integer.parseInt(logisticPipeIdProperty.value);
LOGISTICSPIPE_REQUEST_ID = Integer.parseInt(logisticPipeRequesterIdProperty.value);
LOGISTICSPIPE_PROVIDER_ID = Integer.parseInt(logisticPipeProviderIdProperty.value);
LOGISTICSPIPE_CRAFTING_ID = Integer.parseInt(logisticPipeCraftingIdProperty.value);
LOGISTICSPIPE_SATELLITE_ID = Integer.parseInt(logisticPipeSatelliteIdProperty.value);
LOGISTICSPIPE_SUPPLIER_ID = Integer.parseInt(logisticPipeSupplierIdProperty.value);
LOGISTICSPIPE_CHASSI1_ID = Integer.parseInt(logisticPipeChassi1IdProperty.value);
LOGISTICSPIPE_CHASSI2_ID = Integer.parseInt(logisticPipeChassi2IdProperty.value);
LOGISTICSPIPE_CHASSI3_ID = Integer.parseInt(logisticPipeChassi3IdProperty.value);
LOGISTICSPIPE_CHASSI4_ID = Integer.parseInt(logisticPipeChassi4IdProperty.value);
LOGISTICSPIPE_CHASSI5_ID = Integer.parseInt(logisticPipeChassi5IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK2_ID = Integer.parseInt(logisticPipeCraftingMK2IdProperty.value);
LOGISTICSPIPE_CRAFTING_MK3_ID = Integer.parseInt(logisticPipeCraftingMK3IdProperty.value);
LOGISTICSPIPE_REQUEST_MK2_ID = Integer.parseInt(logisticPipeRequesterMK2IdProperty.value);
LOGISTICSPIPE_PROVIDER_MK2_ID = Integer.parseInt(logisticPipeProviderMK2IdProperty.value);
LOGISTICSPIPE_REMOTE_ORDERER_ID = Integer.parseInt(logisticPipeRemoteOrdererIdProperty.value);
LOGISTICSPIPE_APIARIST_ANALYSER_ID = Integer.parseInt(logisticPipeApiaristAnalyserIdProperty.value);
LOGISTICSPIPE_APIARIST_SINK_ID = Integer.parseInt(logisticPipeApiaristSinkIdProperty.value);
LOGISTICSPIPE_ENTRANCE_ID = Integer.parseInt(logisticEntranceIdProperty.value);
LOGISTICSPIPE_DESTINATION_ID = Integer.parseInt(logisticDestinationIdProperty.value);
LOGISTICSPIPE_INVSYSCON_ID = Integer.parseInt(logisticInvSysConIdProperty.value);
LOGISTICS_SIGN_ID = Integer.parseInt(logisticsSignId.value);
LOGISTICS_SOLID_BLOCK_ID = Integer.parseInt(logisticsSolidBlockId.value);
LOGISTICSPIPE_FIREWALL_ID = logisticPipeFirewallIdProperty.getInt();
//DEBUG (TEST) ONLY (LIQUID)
if(LogisticsPipes.DEBUG) {
LOGISTICSPIPE_LIQUID_CONNECTOR = logisticPipeLiquidConnectorIdProperty.getInt();
LOGISTICSPIPE_LIQUID_BASIC = logisticPipeLiquidBasicIdProperty.getInt();
LOGISTICSPIPE_LIQUID_INSERTION = logisticPipeLiquidInsertionIdProperty.getInt();
LOGISTICSPIPE_LIQUID_PROVIDER = logisticPipeLiquidProviderIdProperty.getInt();
LOGISTICSPIPE_LIQUID_REQUEST = logisticPipeLiquidRequestIdProperty.getInt();
}
LOGISTICS_DETECTION_LENGTH = Integer.parseInt(detectionLength.value);
LOGISTICS_DETECTION_COUNT = Integer.parseInt(detectionCount.value);
LOGISTICS_DETECTION_FREQUENCY = Math.max(Integer.parseInt(detectionFrequency.value), 1);
LOGISTICS_ORDERER_COUNT_INVERTWHEEL = Boolean.parseBoolean(countInvertWheelProperty.value);
LOGISTICS_ORDERER_PAGE_INVERTWHEEL = Boolean.parseBoolean(pageInvertWheelProperty.value);
LOGISTICS_POWER_USAGE_DISABLED = Boolean.parseBoolean(logisticsPowerUsageDisable.value);
LOGISTICS_TILE_GENERIC_PIPE_REPLACEMENT_DISABLED = Boolean.parseBoolean(logisticsTileGenericReplacementDisable.value);
LOGISTICSCRAFTINGSIGNCREATOR_ID = Integer.parseInt(logisticCraftingSignCreatorIdProperty.value);
LOGISTICS_HUD_RENDER_DISTANCE = Integer.parseInt(logisticsHUDRenderDistance.value);
displayPopup = Boolean.parseBoolean(pageDisplayPopupProperty.value);
LOGISTICSPIPE_BUILDERSUPPLIER_ID = Integer.parseInt(logisticPipeBuilderSupplierIdProperty.value);
LOGISTICSPIPE_LIQUIDSUPPLIER_ID = Integer.parseInt(logisticPipeLiquidSupplierIdProperty.value);
MANDATORY_CARPENTER_RECIPES = Boolean.parseBoolean(mandatoryCarpenterRecipes.value);
ENABLE_PARTICLE_FX = Boolean.parseBoolean(enableParticleFX.value);
multiThreadEnabled = multiThread.getBoolean(multiThreadEnabled);
multiThreadNumber = multiThreadCount.getInt();
if(multiThreadNumber < 1) {
multiThreadNumber = 1;
multiThreadCount.value = Integer.toString(multiThreadNumber);
}
multiThreadPriority = multiThreadPrio.getInt();
if(multiThreadPriority < 1 || multiThreadPriority > 10) {
multiThreadPriority = Thread.NORM_PRIORITY;
multiThreadPrio.value = Integer.toString(Thread.NORM_PRIORITY);
}
powerUsageMultiplyer = powerUsageMultiplyerPref.getInt();
if(powerUsageMultiplyer < 1) {
powerUsageMultiplyer = 1;
powerUsageMultiplyerPref.value = "1";
}
configuration.save();
}
|
diff --git a/handwritten/java/regressiontest/cluster/AddExampleData.java b/handwritten/java/regressiontest/cluster/AddExampleData.java
index 88608835d..8c6309de1 100644
--- a/handwritten/java/regressiontest/cluster/AddExampleData.java
+++ b/handwritten/java/regressiontest/cluster/AddExampleData.java
@@ -1,29 +1,29 @@
package regressiontest.cluster;
import java.io.File;
import org.molgenis.framework.db.Database;
import org.molgenis.util.TarGz;
import plugins.archiveexportimport.ArchiveExportImportPlugin;
import plugins.archiveexportimport.XgapCsvImport;
import plugins.archiveexportimport.XgapExcelImport;
public class AddExampleData
{
public AddExampleData(Database db) throws Exception
{
- File tarFu = new File("./data/xqtlwb/gcc_xqtl.tar.gz");
+ File tarFu = new File("./publicdata/xqtl/gcc_xqtl.tar.gz");
File extractDir = TarGz.tarExtract(tarFu);
if (ArchiveExportImportPlugin.isExcelFormatXGAPArchive(extractDir))
{
new XgapExcelImport(extractDir, db);
}
else
{
new XgapCsvImport(extractDir, db);
}
}
}
| true | true | public AddExampleData(Database db) throws Exception
{
File tarFu = new File("./data/xqtlwb/gcc_xqtl.tar.gz");
File extractDir = TarGz.tarExtract(tarFu);
if (ArchiveExportImportPlugin.isExcelFormatXGAPArchive(extractDir))
{
new XgapExcelImport(extractDir, db);
}
else
{
new XgapCsvImport(extractDir, db);
}
}
| public AddExampleData(Database db) throws Exception
{
File tarFu = new File("./publicdata/xqtl/gcc_xqtl.tar.gz");
File extractDir = TarGz.tarExtract(tarFu);
if (ArchiveExportImportPlugin.isExcelFormatXGAPArchive(extractDir))
{
new XgapExcelImport(extractDir, db);
}
else
{
new XgapCsvImport(extractDir, db);
}
}
|
diff --git a/ass2/src/main/java/com/dsp/ass2/Join.java b/ass2/src/main/java/com/dsp/ass2/Join.java
index 0d2dd11..766a72b 100644
--- a/ass2/src/main/java/com/dsp/ass2/Join.java
+++ b/ass2/src/main/java/com/dsp/ass2/Join.java
@@ -1,113 +1,113 @@
package com.dsp.ass2;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.io.LongWritable;
public class Join {
public static class MapClass extends Mapper<LongWritable, Text, Text, Text> {
private Text word = new Text();
// Write { <w1,w2> : w1, c(w1), c(w1,w2) }
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
// Fetch words from value.
String[] words = value.toString().split(Utils.delim);
String w1 = words[0],
w2 = words[1],
cW1 = words[2],
cW1W2 = words[3];
Text newValue = new Text(w1 + Utils.delim + cW1 + Utils.delim + cW1W2);
word.set(w1 + Utils.delim + w2);
context.write(word, newValue);
word.set(w2 + Utils.delim + w1);
context.write(word, newValue);
}
}
public static class ReduceClass extends Reducer<Text,Text,Text,Text> {
// For every <w1,w2> - Write { <w1,w2> : c(w1), c(w2), c(w1,w2) }
@Override
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String cW1 = "0", cW2 = "0", cW1W2 = "0";
// Fetch w1, w2, c(w1), c(w2), c(w1,w2).
String[] w1w2 = key.toString().split(Utils.delim);
String w1 = w1w2[0],
w2 = w1w2[1];
String[] counters;
for (Text value : values) {
- counters = value.toString().counters(Utils.delim);
+ counters = value.toString().split(Utils.delim);
cW1W2 = counters[2];
if (counters[0].equals(w1)) {
cW1 = counters[1];
} else {
cW2 = counters[1];
}
}
Text newKey = new Text(w1 + Utils.delim + w2),
newValue = new Text(cW1 + Utils.delim + cW2 + Utils.delim + cW1W2);
context.write(newKey, newValue);
}
}
public static class PartitionerClass extends Partitioner<Text, Text> {
// TODO make this smarter.
@Override
public int getPartition(Text key, Text value, int numPartitions) {
return getLanguage(key) % numPartitions;
}
private int getLanguage(Text key) {
if (key.getLength() > 0) {
int c = key.charAt(0);
if (c >= Long.decode("0x05D0").longValue() && c <= Long.decode("0x05EA").longValue())
return 1;
}
return 0;
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("mapred.reduce.slowstart.completed.maps", "1");
//conf.set("mapred.map.tasks","10");
//conf.set("mapred.reduce.tasks","2");
Job job = new Job(conf, "Join");
job.setJarByClass(Join.class);
job.setMapperClass(MapClass.class);
job.setPartitionerClass(PartitionerClass.class);
// job.setCombinerClass(CombineClass.class);
job.setReducerClass(ReduceClass.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| true | true | public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String cW1 = "0", cW2 = "0", cW1W2 = "0";
// Fetch w1, w2, c(w1), c(w2), c(w1,w2).
String[] w1w2 = key.toString().split(Utils.delim);
String w1 = w1w2[0],
w2 = w1w2[1];
String[] counters;
for (Text value : values) {
counters = value.toString().counters(Utils.delim);
cW1W2 = counters[2];
if (counters[0].equals(w1)) {
cW1 = counters[1];
} else {
cW2 = counters[1];
}
}
Text newKey = new Text(w1 + Utils.delim + w2),
newValue = new Text(cW1 + Utils.delim + cW2 + Utils.delim + cW1W2);
context.write(newKey, newValue);
}
| public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String cW1 = "0", cW2 = "0", cW1W2 = "0";
// Fetch w1, w2, c(w1), c(w2), c(w1,w2).
String[] w1w2 = key.toString().split(Utils.delim);
String w1 = w1w2[0],
w2 = w1w2[1];
String[] counters;
for (Text value : values) {
counters = value.toString().split(Utils.delim);
cW1W2 = counters[2];
if (counters[0].equals(w1)) {
cW1 = counters[1];
} else {
cW2 = counters[1];
}
}
Text newKey = new Text(w1 + Utils.delim + w2),
newValue = new Text(cW1 + Utils.delim + cW2 + Utils.delim + cW1W2);
context.write(newKey, newValue);
}
|
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java
index 5366bd025..d6e11d7f4 100644
--- a/src/com/android/settings/TextToSpeechSettings.java
+++ b/src/com/android/settings/TextToSpeechSettings.java
@@ -1,721 +1,720 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import static android.provider.Settings.Secure.TTS_USE_DEFAULTS;
import static android.provider.Settings.Secure.TTS_DEFAULT_RATE;
import static android.provider.Settings.Secure.TTS_DEFAULT_LANG;
import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY;
import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT;
import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH;
import static android.provider.Settings.Secure.TTS_ENABLED_PLUGINS;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.CheckBoxPreference;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class TextToSpeechSettings extends PreferenceActivity implements
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener,
TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechSettings";
private static final String SYSTEM_TTS = "com.svox.pico";
private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example";
private static final String KEY_TTS_INSTALL_DATA = "tts_install_data";
private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings";
private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate";
private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang";
private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country";
private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant";
private static final String KEY_TTS_DEFAULT_SYNTH = "tts_default_synth";
private static final String KEY_PLUGIN_ENABLED_PREFIX = "ENABLED_";
private static final String KEY_PLUGIN_SETTINGS_PREFIX = "SETTINGS_";
// TODO move default Locale values to TextToSpeech.Engine
private static final String DEFAULT_LANG_VAL = "eng";
private static final String DEFAULT_COUNTRY_VAL = "USA";
private static final String DEFAULT_VARIANT_VAL = "";
private static final String LOCALE_DELIMITER = "-";
private static final String FALLBACK_TTS_DEFAULT_SYNTH =
TextToSpeech.Engine.DEFAULT_SYNTH;
private Preference mPlayExample = null;
private Preference mInstallData = null;
private CheckBoxPreference mUseDefaultPref = null;
private ListPreference mDefaultRatePref = null;
private ListPreference mDefaultLocPref = null;
private ListPreference mDefaultSynthPref = null;
private String mDefaultLanguage = null;
private String mDefaultCountry = null;
private String mDefaultLocVariant = null;
private String mDefaultEng = "";
private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
// Array of strings used to demonstrate TTS in the different languages.
private String[] mDemoStrings;
// Index of the current string to use for the demo.
private int mDemoStringIndex = 0;
private boolean mEnableDemo = false;
private boolean mVoicesMissing = false;
private TextToSpeech mTts = null;
private boolean mTtsStarted = false;
/**
* Request code (arbitrary value) for voice data check through
* startActivityForResult.
*/
private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
private static final int GET_SAMPLE_TEXT = 1983;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_settings);
addEngineSpecificSettings();
mDemoStrings = getResources().getStringArray(R.array.tts_demo_strings);
setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
mEnableDemo = false;
mTtsStarted = false;
mTts = new TextToSpeech(this, this);
}
@Override
protected void onStart() {
super.onStart();
if (mTtsStarted){
// whenever we return to this screen, we don't know the state of the
// system, so we have to recheck that we can play the demo, or it must be disabled.
// TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount
initClickers();
updateWidgetState();
checkVoiceData();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTts != null) {
mTts.shutdown();
}
}
private void addEngineSpecificSettings() {
PreferenceGroup enginesCategory = (PreferenceGroup) findPreference("tts_engines_section");
Intent intent = new Intent("android.intent.action.START_TTS_ENGINE");
ResolveInfo[] enginesArray = new ResolveInfo[0];
PackageManager pm = getPackageManager();
enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray);
for (int i = 0; i < enginesArray.length; i++) {
String prefKey = "";
final String pluginPackageName = enginesArray[i].activityInfo.packageName;
if (!enginesArray[i].activityInfo.packageName.equals(SYSTEM_TTS)) {
CheckBoxPreference chkbxPref = new CheckBoxPreference(this);
prefKey = KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName;
chkbxPref.setKey(prefKey);
chkbxPref.setTitle(enginesArray[i].loadLabel(pm));
enginesCategory.addPreference(chkbxPref);
}
if (pluginHasSettings(pluginPackageName)) {
Preference pref = new Preference(this);
prefKey = KEY_PLUGIN_SETTINGS_PREFIX + pluginPackageName;
pref.setKey(prefKey);
pref.setTitle(enginesArray[i].loadLabel(pm));
CharSequence settingsLabel = getResources().getString(
R.string.tts_engine_name_settings, enginesArray[i].loadLabel(pm));
pref.setSummary(settingsLabel);
pref.setOnPreferenceClickListener(new OnPreferenceClickListener(){
public boolean onPreferenceClick(Preference preference){
Intent i = new Intent();
i.setClassName(pluginPackageName,
pluginPackageName + ".EngineSettings");
startActivity(i);
return true;
}
});
enginesCategory.addPreference(pref);
}
}
}
private boolean pluginHasSettings(String pluginPackageName) {
PackageManager pm = getPackageManager();
Intent i = new Intent();
i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings");
if (pm.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY) != null){
return true;
}
return false;
}
private void initClickers() {
mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE);
mPlayExample.setOnPreferenceClickListener(this);
mInstallData = findPreference(KEY_TTS_INSTALL_DATA);
mInstallData.setOnPreferenceClickListener(this);
}
private void initDefaultSettings() {
ContentResolver resolver = getContentResolver();
// Find the default TTS values in the settings, initialize and store the
// settings if they are not found.
// "Use Defaults"
int useDefault = 0;
mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT);
try {
useDefault = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS);
} catch (SettingNotFoundException e) {
// "use default" setting not found, initialize it
useDefault = TextToSpeech.Engine.USE_DEFAULTS;
Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, useDefault);
}
mUseDefaultPref.setChecked(useDefault == 1);
mUseDefaultPref.setOnPreferenceChangeListener(this);
// Default synthesis engine
mDefaultSynthPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH);
loadEngines();
mDefaultSynthPref.setOnPreferenceChangeListener(this);
String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH);
if (engine == null) {
// TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech
engine = FALLBACK_TTS_DEFAULT_SYNTH;
Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine);
}
mDefaultEng = engine;
// Default rate
mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE);
try {
mDefaultRate = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE);
} catch (SettingNotFoundException e) {
// default rate setting not found, initialize it
mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, mDefaultRate);
}
mDefaultRatePref.setValue(String.valueOf(mDefaultRate));
mDefaultRatePref.setOnPreferenceChangeListener(this);
// Default language / country / variant : these three values map to a single ListPref
// representing the matching Locale
mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG);
initDefaultLang();
mDefaultLocPref.setOnPreferenceChangeListener(this);
}
/**
* Ask the current default engine to launch the matching CHECK_TTS_DATA activity
* to check the required TTS files are properly installed.
*/
private void checkVoiceData() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
}
}
}
/**
* Ask the current default engine to launch the matching INSTALL_TTS_DATA activity
* so the required TTS files are properly installed.
*/
private void installVoiceData() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivity(intent);
}
}
}
/**
* Ask the current default engine to return a string of sample text to be
* spoken to the user.
*/
private void getSampleText() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
// TODO (clchen): Replace Intent string with the actual
// Intent defined in the list of platform Intents.
intent.setAction("android.speech.tts.engine.GET_SAMPLE_TEXT");
intent.putExtra("language", mDefaultLanguage);
intent.putExtra("country", mDefaultCountry);
intent.putExtra("variant", mDefaultLocVariant);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivityForResult(intent, GET_SAMPLE_TEXT);
}
}
}
/**
* Called when the TTS engine is initialized.
*/
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
mEnableDemo = true;
if (mDefaultLanguage == null) {
mDefaultLanguage = Locale.getDefault().getISO3Language();
}
if (mDefaultCountry == null) {
mDefaultCountry = Locale.getDefault().getISO3Country();
}
if (mDefaultLocVariant == null) {
mDefaultLocVariant = new String();
}
mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
mTts.setSpeechRate((float)(mDefaultRate/100.0f));
initDefaultSettings();
initClickers();
updateWidgetState();
checkVoiceData();
mTtsStarted = true;
Log.v(TAG, "TTS engine for settings screen initialized.");
} else {
Log.v(TAG, "TTS engine for settings screen failed to initialize successfully.");
mEnableDemo = false;
}
updateWidgetState();
}
/**
* Called when voice data integrity check returns
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (data == null){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
- // TODO (clchen): Add these extras to TextToSpeech.Engine
ArrayList<String> available =
- data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES");
+ data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
ArrayList<String> unavailable =
- data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES");
+ data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
if ((available == null) || (unavailable == null)){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
if (available.size() > 0){
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
ListPreference ttsLanguagePref =
(ListPreference) findPreference("tts_default_lang");
CharSequence[] entries = new CharSequence[available.size()];
CharSequence[] entryValues = new CharSequence[available.size()];
for (int i=0; i<available.size(); i++){
String[] langCountryVariant = available.get(i).split("-");
Locale loc = null;
if (langCountryVariant.length == 1){
loc = new Locale(langCountryVariant[0]);
} else if (langCountryVariant.length == 2){
loc = new Locale(langCountryVariant[0], langCountryVariant[1]);
} else if (langCountryVariant.length == 3){
loc = new Locale(langCountryVariant[0], langCountryVariant[1],
langCountryVariant[2]);
}
if (loc != null){
entries[i] = loc.getDisplayName();
entryValues[i] = available.get(i);
}
}
ttsLanguagePref.setEntries(entries);
ttsLanguagePref.setEntryValues(entryValues);
mEnableDemo = true;
// Make sure that the default language can be used.
int languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
if (languageResult < TextToSpeech.LANG_AVAILABLE){
Locale currentLocale = Locale.getDefault();
mDefaultLanguage = currentLocale.getISO3Language();
mDefaultCountry = currentLocale.getISO3Country();
mDefaultLocVariant = currentLocale.getVariant();
languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
// If the default Locale isn't supported, just choose the first available
// language so that there is at least something.
if (languageResult < TextToSpeech.LANG_AVAILABLE){
parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString());
mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
}
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
}
} else {
mEnableDemo = false;
}
if (unavailable.size() > 0){
mVoicesMissing = true;
} else {
mVoicesMissing = false;
}
updateWidgetState();
} else if (requestCode == GET_SAMPLE_TEXT) {
if (resultCode == TextToSpeech.LANG_AVAILABLE) {
String sample = getString(R.string.tts_demo);
if ((data != null) && (data.getStringExtra("sampleText") != null)) {
sample = data.getStringExtra("sampleText");
}
if (mTts != null) {
mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
// TODO: Display an error here to the user.
Log.e(TAG, "Did not have a sample string for the requested language");
}
}
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) {
// "Use Defaults"
int value = (Boolean)objValue ? 1 : 0;
Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS,
value);
Log.i(TAG, "TTS use default settings is "+objValue.toString());
} else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) {
// Default rate
mDefaultRate = Integer.parseInt((String) objValue);
try {
Settings.Secure.putInt(getContentResolver(),
TTS_DEFAULT_RATE, mDefaultRate);
if (mTts != null) {
mTts.setSpeechRate((float)(mDefaultRate/100.0f));
}
Log.i(TAG, "TTS default rate is " + mDefaultRate);
} catch (NumberFormatException e) {
Log.e(TAG, "could not persist default TTS rate setting", e);
}
} else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) {
// Default locale
ContentResolver resolver = getContentResolver();
parseLocaleInfo((String) objValue);
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
Log.v(TAG, "TTS default lang/country/variant set to "
+ mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant);
if (mTts != null) {
mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
}
int newIndex = mDefaultLocPref.findIndexOfValue((String)objValue);
Log.v("Settings", " selected is " + newIndex);
mDemoStringIndex = newIndex > -1 ? newIndex : 0;
} else if (KEY_TTS_DEFAULT_SYNTH.equals(preference.getKey())) {
mDefaultEng = objValue.toString();
Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, mDefaultEng);
if (mTts != null) {
mTts.setEngineByPackageName(mDefaultEng);
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
checkVoiceData();
}
Log.v("Settings", "The default synth is: " + objValue.toString());
}
return true;
}
/**
* Called when mPlayExample or mInstallData is clicked
*/
public boolean onPreferenceClick(Preference preference) {
if (preference == mPlayExample) {
// Get the sample text from the TTS engine; onActivityResult will do
// the actual speaking
getSampleText();
return true;
}
if (preference == mInstallData) {
installVoiceData();
// quit this activity so it needs to be restarted after installation of the voice data
finish();
return true;
}
return false;
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (Utils.isMonkeyRunning()) {
return false;
}
if (preference instanceof CheckBoxPreference) {
final CheckBoxPreference chkPref = (CheckBoxPreference) preference;
if (!chkPref.getKey().equals(KEY_TTS_USE_DEFAULT)){
if (chkPref.isChecked()) {
chkPref.setChecked(false);
AlertDialog d = (new AlertDialog.Builder(this))
.setTitle(android.R.string.dialog_alert_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(getString(R.string.tts_engine_security_warning,
chkPref.getTitle()))
.setCancelable(true)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
chkPref.setChecked(true);
loadEngines();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
d.show();
} else {
loadEngines();
}
return true;
}
}
return false;
}
private void updateWidgetState() {
mPlayExample.setEnabled(mEnableDemo);
mUseDefaultPref.setEnabled(mEnableDemo);
mDefaultRatePref.setEnabled(mEnableDemo);
mDefaultLocPref.setEnabled(mEnableDemo);
mInstallData.setEnabled(mVoicesMissing);
}
private void parseLocaleInfo(String locale) {
StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER);
mDefaultLanguage = "";
mDefaultCountry = "";
mDefaultLocVariant = "";
if (tokenizer.hasMoreTokens()) {
mDefaultLanguage = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
mDefaultCountry = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
mDefaultLocVariant = tokenizer.nextToken().trim();
}
}
/**
* Initialize the default language in the UI and in the preferences.
* After this method has been invoked, the default language is a supported Locale.
*/
private void initDefaultLang() {
// if there isn't already a default language preference
if (!hasLangPref()) {
// if the current Locale is supported
if (isCurrentLocSupported()) {
// then use the current Locale as the default language
useCurrentLocAsDefault();
} else {
// otherwise use a default supported Locale as the default language
useSupportedLocAsDefault();
}
}
// Update the language preference list with the default language and the matching
// demo string (at this stage there is a default language pref)
ContentResolver resolver = getContentResolver();
mDefaultLanguage = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
mDefaultCountry = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY);
mDefaultLocVariant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT);
// update the demo string
mDemoStringIndex = mDefaultLocPref.findIndexOfValue(mDefaultLanguage + LOCALE_DELIMITER
+ mDefaultCountry);
if (mDemoStringIndex > -1){
mDefaultLocPref.setValueIndex(mDemoStringIndex);
}
}
/**
* (helper function for initDefaultLang() )
* Returns whether there is a default language in the TTS settings.
*/
private boolean hasLangPref() {
String language = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_LANG);
return (language != null);
}
/**
* (helper function for initDefaultLang() )
* Returns whether the current Locale is supported by this Settings screen
*/
private boolean isCurrentLocSupported() {
String currentLocID = Locale.getDefault().getISO3Language() + LOCALE_DELIMITER
+ Locale.getDefault().getISO3Country();
return (mDefaultLocPref.findIndexOfValue(currentLocID) > -1);
}
/**
* (helper function for initDefaultLang() )
* Sets the default language in TTS settings to be the current Locale.
* This should only be used after checking that the current Locale is supported.
*/
private void useCurrentLocAsDefault() {
Locale currentLocale = Locale.getDefault();
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, currentLocale.getISO3Language());
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, currentLocale.getISO3Country());
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, currentLocale.getVariant());
}
/**
* (helper function for initDefaultLang() )
* Sets the default language in TTS settings to be one known to be supported
*/
private void useSupportedLocAsDefault() {
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, DEFAULT_LANG_VAL);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, DEFAULT_COUNTRY_VAL);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, DEFAULT_VARIANT_VAL);
}
private void loadEngines() {
ListPreference enginesPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH);
// TODO (clchen): Try to see if it is possible to be more efficient here
// and not search for plugins again.
Intent intent = new Intent("android.intent.action.START_TTS_ENGINE");
ResolveInfo[] enginesArray = new ResolveInfo[0];
PackageManager pm = getPackageManager();
enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray);
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<CharSequence> values = new ArrayList<CharSequence>();
String enabledEngines = "";
for (int i = 0; i < enginesArray.length; i++) {
String pluginPackageName = enginesArray[i].activityInfo.packageName;
if (pluginPackageName.equals(SYSTEM_TTS)) {
entries.add(enginesArray[i].loadLabel(pm));
values.add(pluginPackageName);
} else {
CheckBoxPreference pref = (CheckBoxPreference) findPreference(
KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName);
if ((pref != null) && pref.isChecked()){
entries.add(enginesArray[i].loadLabel(pm));
values.add(pluginPackageName);
enabledEngines = enabledEngines + pluginPackageName + " ";
}
}
}
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_ENABLED_PLUGINS, enabledEngines);
CharSequence entriesArray[] = new CharSequence[entries.size()];
CharSequence valuesArray[] = new CharSequence[values.size()];
enginesPref.setEntries(entries.toArray(entriesArray));
enginesPref.setEntryValues(values.toArray(valuesArray));
// Set the selected engine based on the saved preference
String selectedEngine = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_SYNTH);
int selectedEngineIndex = enginesPref.findIndexOfValue(selectedEngine);
if (selectedEngineIndex == -1){
selectedEngineIndex = enginesPref.findIndexOfValue(SYSTEM_TTS);
}
enginesPref.setValueIndex(selectedEngineIndex);
}
}
| false | true | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (data == null){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
// TODO (clchen): Add these extras to TextToSpeech.Engine
ArrayList<String> available =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES");
ArrayList<String> unavailable =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES");
if ((available == null) || (unavailable == null)){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
if (available.size() > 0){
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
ListPreference ttsLanguagePref =
(ListPreference) findPreference("tts_default_lang");
CharSequence[] entries = new CharSequence[available.size()];
CharSequence[] entryValues = new CharSequence[available.size()];
for (int i=0; i<available.size(); i++){
String[] langCountryVariant = available.get(i).split("-");
Locale loc = null;
if (langCountryVariant.length == 1){
loc = new Locale(langCountryVariant[0]);
} else if (langCountryVariant.length == 2){
loc = new Locale(langCountryVariant[0], langCountryVariant[1]);
} else if (langCountryVariant.length == 3){
loc = new Locale(langCountryVariant[0], langCountryVariant[1],
langCountryVariant[2]);
}
if (loc != null){
entries[i] = loc.getDisplayName();
entryValues[i] = available.get(i);
}
}
ttsLanguagePref.setEntries(entries);
ttsLanguagePref.setEntryValues(entryValues);
mEnableDemo = true;
// Make sure that the default language can be used.
int languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
if (languageResult < TextToSpeech.LANG_AVAILABLE){
Locale currentLocale = Locale.getDefault();
mDefaultLanguage = currentLocale.getISO3Language();
mDefaultCountry = currentLocale.getISO3Country();
mDefaultLocVariant = currentLocale.getVariant();
languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
// If the default Locale isn't supported, just choose the first available
// language so that there is at least something.
if (languageResult < TextToSpeech.LANG_AVAILABLE){
parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString());
mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
}
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
}
} else {
mEnableDemo = false;
}
if (unavailable.size() > 0){
mVoicesMissing = true;
} else {
mVoicesMissing = false;
}
updateWidgetState();
} else if (requestCode == GET_SAMPLE_TEXT) {
if (resultCode == TextToSpeech.LANG_AVAILABLE) {
String sample = getString(R.string.tts_demo);
if ((data != null) && (data.getStringExtra("sampleText") != null)) {
sample = data.getStringExtra("sampleText");
}
if (mTts != null) {
mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
// TODO: Display an error here to the user.
Log.e(TAG, "Did not have a sample string for the requested language");
}
}
}
| protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (data == null){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
ArrayList<String> available =
data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
ArrayList<String> unavailable =
data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
if ((available == null) || (unavailable == null)){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
if (available.size() > 0){
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
ListPreference ttsLanguagePref =
(ListPreference) findPreference("tts_default_lang");
CharSequence[] entries = new CharSequence[available.size()];
CharSequence[] entryValues = new CharSequence[available.size()];
for (int i=0; i<available.size(); i++){
String[] langCountryVariant = available.get(i).split("-");
Locale loc = null;
if (langCountryVariant.length == 1){
loc = new Locale(langCountryVariant[0]);
} else if (langCountryVariant.length == 2){
loc = new Locale(langCountryVariant[0], langCountryVariant[1]);
} else if (langCountryVariant.length == 3){
loc = new Locale(langCountryVariant[0], langCountryVariant[1],
langCountryVariant[2]);
}
if (loc != null){
entries[i] = loc.getDisplayName();
entryValues[i] = available.get(i);
}
}
ttsLanguagePref.setEntries(entries);
ttsLanguagePref.setEntryValues(entryValues);
mEnableDemo = true;
// Make sure that the default language can be used.
int languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
if (languageResult < TextToSpeech.LANG_AVAILABLE){
Locale currentLocale = Locale.getDefault();
mDefaultLanguage = currentLocale.getISO3Language();
mDefaultCountry = currentLocale.getISO3Country();
mDefaultLocVariant = currentLocale.getVariant();
languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
// If the default Locale isn't supported, just choose the first available
// language so that there is at least something.
if (languageResult < TextToSpeech.LANG_AVAILABLE){
parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString());
mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
}
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
}
} else {
mEnableDemo = false;
}
if (unavailable.size() > 0){
mVoicesMissing = true;
} else {
mVoicesMissing = false;
}
updateWidgetState();
} else if (requestCode == GET_SAMPLE_TEXT) {
if (resultCode == TextToSpeech.LANG_AVAILABLE) {
String sample = getString(R.string.tts_demo);
if ((data != null) && (data.getStringExtra("sampleText") != null)) {
sample = data.getStringExtra("sampleText");
}
if (mTts != null) {
mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
// TODO: Display an error here to the user.
Log.e(TAG, "Did not have a sample string for the requested language");
}
}
}
|
diff --git a/src/main/java/water/parser/ValueString.java b/src/main/java/water/parser/ValueString.java
index 4041d5b02..3631a4f4b 100644
--- a/src/main/java/water/parser/ValueString.java
+++ b/src/main/java/water/parser/ValueString.java
@@ -1,113 +1,113 @@
package water.parser;
import java.util.ArrayList;
public final class ValueString {
byte [] _buf;
int _off;
int _length;
ArrayList<Integer> _skips = new ArrayList<Integer>();
public ValueString() {}
public ValueString(byte [] buf, int off, int len){
_buf = buf;
_off = off;
_length = len;
}
public ValueString(String from) {
_buf = from.getBytes();
_off = 0;
_length = _buf.length;
}
public ValueString(byte [] buf){
this(buf,0,buf.length);
}
@Override
public int hashCode(){
int hash = 0;
if(_skips.isEmpty()){
int n = _off + _length;
for (int i = _off; i < n; ++i)
hash = 31 * hash + _buf[i];
return hash;
} else {
int i = _off;
for(int n:_skips){
for(; i < _off+n; ++i)
hash = 31*hash + _buf[i];
++i;
}
int n = _off + _length;
for(; i < n; ++i)
hash = 31*hash + _buf[i];
return hash;
}
}
void addChar(){++_length;}
void skipChar(){_skips.add(_length++);}
void addBuff(byte [] bits){
byte [] buf = new byte[_length];
int l1 = _buf.length-_off;
System.arraycopy(_buf, _off, buf, 0, l1);
System.arraycopy(bits, 0, buf, l1, _length-l1);
_off = 0;
_buf = buf;
}
@Override
public String toString(){
if(_skips.isEmpty())return new String(_buf,_off,_length);
StringBuilder sb = new StringBuilder();
int off = _off;
for(int next:_skips){
int len = _off+next-off;
sb.append(new String(_buf,off,len));
off += len + 1;
}
sb.append(new String(_buf,off,_length-off+_off));
return sb.toString();
}
void set(byte [] buf, int off, int len){
_buf = buf;
_off = off;
_length = len;
_skips.clear();
}
public ValueString setTo(String what) {
_buf = what.getBytes();
_off = 0;
_length = _buf.length;
_skips.clear();
return this;
}
@Override public boolean equals(Object o){
if(!(o instanceof ValueString)) return false;
ValueString str = (ValueString)o;
- if(str._length != _length)return false;
if(_skips.isEmpty() && str._skips.isEmpty()){ // no skipped chars
+ if(str._length != _length)return false;
for(int i = 0; i < _length; ++i)
if(_buf[_off+i] != str._buf[str._off+i]) return false;
}else if(str._skips.isEmpty()){ // only this has skipped chars
if(_length - _skips.size() != str._length)return false;
int j = 0;
int i = _off;
for(int n:_skips){
for(; i < _off+n; ++i)
if(_buf[i] != str._buf[j++])return false;
++i;
}
int n = _off + _length;
for(; i < n; ++i) if(_buf[i] != str._buf[j++])return false;
} else return toString().equals(str.toString()); // both strings have skipped chars, unnecessarily complicated so just turn it into a string (which skips the chars), should not happen too often
return true;
}
}
| false | true | @Override public boolean equals(Object o){
if(!(o instanceof ValueString)) return false;
ValueString str = (ValueString)o;
if(str._length != _length)return false;
if(_skips.isEmpty() && str._skips.isEmpty()){ // no skipped chars
for(int i = 0; i < _length; ++i)
if(_buf[_off+i] != str._buf[str._off+i]) return false;
}else if(str._skips.isEmpty()){ // only this has skipped chars
if(_length - _skips.size() != str._length)return false;
int j = 0;
int i = _off;
for(int n:_skips){
for(; i < _off+n; ++i)
if(_buf[i] != str._buf[j++])return false;
++i;
}
int n = _off + _length;
for(; i < n; ++i) if(_buf[i] != str._buf[j++])return false;
} else return toString().equals(str.toString()); // both strings have skipped chars, unnecessarily complicated so just turn it into a string (which skips the chars), should not happen too often
return true;
}
| @Override public boolean equals(Object o){
if(!(o instanceof ValueString)) return false;
ValueString str = (ValueString)o;
if(_skips.isEmpty() && str._skips.isEmpty()){ // no skipped chars
if(str._length != _length)return false;
for(int i = 0; i < _length; ++i)
if(_buf[_off+i] != str._buf[str._off+i]) return false;
}else if(str._skips.isEmpty()){ // only this has skipped chars
if(_length - _skips.size() != str._length)return false;
int j = 0;
int i = _off;
for(int n:_skips){
for(; i < _off+n; ++i)
if(_buf[i] != str._buf[j++])return false;
++i;
}
int n = _off + _length;
for(; i < n; ++i) if(_buf[i] != str._buf[j++])return false;
} else return toString().equals(str.toString()); // both strings have skipped chars, unnecessarily complicated so just turn it into a string (which skips the chars), should not happen too often
return true;
}
|
diff --git a/nexus/nexus-test-harness/nexus-test-harness-its/src/test/java/org/sonatype/nexus/integrationtests/nxcm2124/NXCM2124CheckConsoleDocumentationIT.java b/nexus/nexus-test-harness/nexus-test-harness-its/src/test/java/org/sonatype/nexus/integrationtests/nxcm2124/NXCM2124CheckConsoleDocumentationIT.java
index 0f20972bb..cf4b1f6dd 100644
--- a/nexus/nexus-test-harness/nexus-test-harness-its/src/test/java/org/sonatype/nexus/integrationtests/nxcm2124/NXCM2124CheckConsoleDocumentationIT.java
+++ b/nexus/nexus-test-harness/nexus-test-harness-its/src/test/java/org/sonatype/nexus/integrationtests/nxcm2124/NXCM2124CheckConsoleDocumentationIT.java
@@ -1,23 +1,23 @@
package org.sonatype.nexus.integrationtests.nxcm2124;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.restlet.data.Response;
import org.sonatype.nexus.integrationtests.AbstractNexusIntegrationTest;
import org.sonatype.nexus.integrationtests.RequestFacade;
public class NXCM2124CheckConsoleDocumentationIT
extends AbstractNexusIntegrationTest
{
@Test
public void checkDoc()
throws IOException
{
- Response r = RequestFacade.doGetRequest( "pluginConsole/docs/index.html" );
+ Response r = RequestFacade.doGetRequest( "nexus-plugin-console-plugin/docs/index.html" );
Assert.assertTrue( r.getStatus().isSuccess() );
}
}
| true | true | public void checkDoc()
throws IOException
{
Response r = RequestFacade.doGetRequest( "pluginConsole/docs/index.html" );
Assert.assertTrue( r.getStatus().isSuccess() );
}
| public void checkDoc()
throws IOException
{
Response r = RequestFacade.doGetRequest( "nexus-plugin-console-plugin/docs/index.html" );
Assert.assertTrue( r.getStatus().isSuccess() );
}
|
diff --git a/src/main/java/com/laytonsmith/commandhelper/CommandHelperInterpreterListener.java b/src/main/java/com/laytonsmith/commandhelper/CommandHelperInterpreterListener.java
index 9ecee6a6..a2c61f58 100644
--- a/src/main/java/com/laytonsmith/commandhelper/CommandHelperInterpreterListener.java
+++ b/src/main/java/com/laytonsmith/commandhelper/CommandHelperInterpreterListener.java
@@ -1,165 +1,166 @@
package com.laytonsmith.commandhelper;
import com.laytonsmith.abstraction.enums.MCChatColor;
import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.abstraction.bukkit.BukkitMCPlayer;
import com.laytonsmith.core.*;
import com.laytonsmith.core.constructs.Token;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import java.io.File;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerQuitEvent;
/**
*
* @author Layton
*/
public class CommandHelperInterpreterListener implements Listener {
private Set<String> interpreterMode = Collections.synchronizedSet(new HashSet<String>());
private CommandHelperPlugin plugin;
Map<String, String> multilineMode = new HashMap<String, String>();
public boolean isInInterpreterMode(MCPlayer p){
return (interpreterMode.contains(p.getName()));
}
public CommandHelperInterpreterListener(CommandHelperPlugin plugin){
this.plugin = plugin;
}
@EventHandler(priority= EventPriority.LOWEST)
public void onPlayerChat(final AsyncPlayerChatEvent event) {
if (interpreterMode.contains(event.getPlayer().getName())) {
final MCPlayer p = new BukkitMCPlayer(event.getPlayer());
event.setCancelled(true);
StaticLayer.SetFutureRunnable(0, new Runnable() {
public void run() {
textLine(p, event.getMessage());
}
});
}
}
@EventHandler(priority= EventPriority.NORMAL)
public void onPlayerQuit(PlayerQuitEvent event) {
interpreterMode.remove(event.getPlayer().getName());
multilineMode.remove(event.getPlayer().getName());
}
@EventHandler(priority= EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (interpreterMode.contains(event.getPlayer().getName())) {
MCPlayer p = new BukkitMCPlayer(event.getPlayer());
textLine(p, event.getMessage());
event.setCancelled(true);
}
}
public void textLine(MCPlayer p, String line) {
if (line.equals("-")) {
//Exit interpreter mode
interpreterMode.remove(p.getName());
Static.SendMessage(p, MCChatColor.YELLOW + "Now exiting interpreter mode");
} else if (line.equals(">>>")) {
//Start multiline mode
if (multilineMode.containsKey(p.getName())) {
Static.SendMessage(p, MCChatColor.RED + "You are already in multiline mode!");
} else {
multilineMode.put(p.getName(), "");
Static.SendMessage(p, MCChatColor.YELLOW + "You are now in multiline mode. Type <<< on a line by itself to execute.");
Static.SendMessage(p, ":" + MCChatColor.GRAY + ">>>");
}
} else if (line.equals("<<<")) {
//Execute multiline
Static.SendMessage(p, ":" + MCChatColor.GRAY + "<<<");
String script = multilineMode.get(p.getName());
multilineMode.remove(p.getName());
try {
execute(script, p);
} catch (ConfigCompileException e) {
Static.SendMessage(p, MCChatColor.RED + e.getMessage() + ":" + e.getLineNum());
}
} else {
if (multilineMode.containsKey(p.getName())) {
//Queue multiline
multilineMode.put(p.getName(), multilineMode.get(p.getName()) + line + "\n");
Static.SendMessage(p, ":" + MCChatColor.GRAY + line);
} else {
try {
//Execute single line
execute(line, p);
} catch (ConfigCompileException ex) {
Static.SendMessage(p, MCChatColor.RED + ex.getMessage());
}
}
}
}
public void reload() {
}
public void execute(String script, final MCPlayer p) throws ConfigCompileException {
List<Token> stream = MethodScriptCompiler.lex(script, new File("Interpreter"));
ParseTree tree = MethodScriptCompiler.compile(stream);
interpreterMode.remove(p.getName());
GlobalEnv gEnv = new GlobalEnv(plugin.executionQueue, plugin.profiler, plugin.persistanceNetwork, plugin.permissionsResolver, plugin.chDirectory);
CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
cEnv.SetPlayer(p);
Environment env = Environment.createEnvironment(gEnv, cEnv);
try {
MethodScriptCompiler.registerAutoIncludes(env, null);
MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {
public void done(String output) {
output = output.trim();
if (output.isEmpty()) {
Static.SendMessage(p, ":");
} else {
if (output.startsWith("/")) {
//Run the command
Static.SendMessage(p, ":" + MCChatColor.YELLOW + output);
p.chat(output);
} else {
//output the results
Static.SendMessage(p, ":" + MCChatColor.GREEN + output);
}
}
interpreterMode.add(p.getName());
}
}, null);
} catch (CancelCommandException e) {
interpreterMode.add(p.getName());
} catch(ConfigRuntimeException e) {
- ConfigRuntimeException.React(e);
+ ConfigRuntimeException.React(e, env);
Static.SendMessage(p, MCChatColor.RED + e.toString());
+ interpreterMode.add(p.getName());
} catch(Exception e){
Static.SendMessage(p, MCChatColor.RED + e.toString());
Logger.getLogger(CommandHelperInterpreterListener.class.getName()).log(Level.SEVERE, null, e);
interpreterMode.add(p.getName());
}
}
public void startInterpret(String playername) {
interpreterMode.add(playername);
}
}
| false | true | public void execute(String script, final MCPlayer p) throws ConfigCompileException {
List<Token> stream = MethodScriptCompiler.lex(script, new File("Interpreter"));
ParseTree tree = MethodScriptCompiler.compile(stream);
interpreterMode.remove(p.getName());
GlobalEnv gEnv = new GlobalEnv(plugin.executionQueue, plugin.profiler, plugin.persistanceNetwork, plugin.permissionsResolver, plugin.chDirectory);
CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
cEnv.SetPlayer(p);
Environment env = Environment.createEnvironment(gEnv, cEnv);
try {
MethodScriptCompiler.registerAutoIncludes(env, null);
MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {
public void done(String output) {
output = output.trim();
if (output.isEmpty()) {
Static.SendMessage(p, ":");
} else {
if (output.startsWith("/")) {
//Run the command
Static.SendMessage(p, ":" + MCChatColor.YELLOW + output);
p.chat(output);
} else {
//output the results
Static.SendMessage(p, ":" + MCChatColor.GREEN + output);
}
}
interpreterMode.add(p.getName());
}
}, null);
} catch (CancelCommandException e) {
interpreterMode.add(p.getName());
} catch(ConfigRuntimeException e) {
ConfigRuntimeException.React(e);
Static.SendMessage(p, MCChatColor.RED + e.toString());
} catch(Exception e){
Static.SendMessage(p, MCChatColor.RED + e.toString());
Logger.getLogger(CommandHelperInterpreterListener.class.getName()).log(Level.SEVERE, null, e);
interpreterMode.add(p.getName());
}
}
| public void execute(String script, final MCPlayer p) throws ConfigCompileException {
List<Token> stream = MethodScriptCompiler.lex(script, new File("Interpreter"));
ParseTree tree = MethodScriptCompiler.compile(stream);
interpreterMode.remove(p.getName());
GlobalEnv gEnv = new GlobalEnv(plugin.executionQueue, plugin.profiler, plugin.persistanceNetwork, plugin.permissionsResolver, plugin.chDirectory);
CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
cEnv.SetPlayer(p);
Environment env = Environment.createEnvironment(gEnv, cEnv);
try {
MethodScriptCompiler.registerAutoIncludes(env, null);
MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {
public void done(String output) {
output = output.trim();
if (output.isEmpty()) {
Static.SendMessage(p, ":");
} else {
if (output.startsWith("/")) {
//Run the command
Static.SendMessage(p, ":" + MCChatColor.YELLOW + output);
p.chat(output);
} else {
//output the results
Static.SendMessage(p, ":" + MCChatColor.GREEN + output);
}
}
interpreterMode.add(p.getName());
}
}, null);
} catch (CancelCommandException e) {
interpreterMode.add(p.getName());
} catch(ConfigRuntimeException e) {
ConfigRuntimeException.React(e, env);
Static.SendMessage(p, MCChatColor.RED + e.toString());
interpreterMode.add(p.getName());
} catch(Exception e){
Static.SendMessage(p, MCChatColor.RED + e.toString());
Logger.getLogger(CommandHelperInterpreterListener.class.getName()).log(Level.SEVERE, null, e);
interpreterMode.add(p.getName());
}
}
|
diff --git a/frost-wot/source/frost/fileTransfer/download/DownloadTicker.java b/frost-wot/source/frost/fileTransfer/download/DownloadTicker.java
index fd378f81..e2ac7d02 100644
--- a/frost-wot/source/frost/fileTransfer/download/DownloadTicker.java
+++ b/frost-wot/source/frost/fileTransfer/download/DownloadTicker.java
@@ -1,265 +1,266 @@
/*
* Created on Apr 24, 2004
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package frost.fileTransfer.download;
import java.util.*;
import javax.swing.event.EventListenerList;
import frost.*;
/**
*
*/
public class DownloadTicker extends Thread {
private SettingsClass settings;
private DownloadPanel panel;
private DownloadModel model;
private int counter;
/**
* The number of allocated threads is used to limit the total of threads
* that can be running at a given time, whereas the number of running
* threads is the number of threads that are actually running.
*/
private int allocatedThreads = 0;
private int runningThreads = 0;
private Object threadCountLock = new Object();
protected EventListenerList listenerList = new EventListenerList();
/**
* Used to sort FrostDownloadItems by lastUpdateStartTimeMillis ascending.
*/
static final Comparator downloadDlStopMillisCmp = new Comparator() {
public int compare(Object o1, Object o2) {
FrostDownloadItem value1 = (FrostDownloadItem) o1;
FrostDownloadItem value2 = (FrostDownloadItem) o2;
if (value1.getLastDownloadStopTimeMillis() > value2.getLastDownloadStopTimeMillis())
return 1;
else if (
value1.getLastDownloadStopTimeMillis() < value2.getLastDownloadStopTimeMillis())
return -1;
else
return 0;
}
};
/**
* @param name
*/
public DownloadTicker(
SettingsClass newSettings,
DownloadModel newModel,
DownloadPanel newPanel) {
super("Download");
settings = newSettings;
model = newModel;
panel = newPanel;
}
/**
* Adds a <code>DownloadTickerListener</code> to the DownloadTicker.
* @param listener the <code>DownloadTickerListener</code> to be added
*/
public void addDownloadTickerListener(DownloadTickerListener listener) {
listenerList.add(DownloadTickerListener.class, listener);
}
/**
* This method is called to find out if a new thread can start. It temporarily
* allocates it and it will have to be relased when it is no longer
* needed (no matter whether the thread was actually used or not).
* @return true if a new thread can start. False otherwise.
*/
private boolean allocateThread() {
synchronized (threadCountLock) {
if (allocatedThreads < settings.getIntValue("downloadThreads")) {
allocatedThreads++;
return true;
}
}
return false;
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @see EventListenerList
*/
protected void fireThreadCountChanged() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == DownloadTickerListener.class) {
((DownloadTickerListener) listeners[i + 1]).threadCountChanged();
}
}
}
/**
* This method is used to release a thread.
*/
private void releaseThread() {
synchronized (threadCountLock) {
if (allocatedThreads > 0) {
allocatedThreads--;
}
}
}
/**
* This method returns the number of threads that are running
* @return the number of threads that are running
*/
public int getRunningThreads() {
return runningThreads;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
super.run();
while (true) {
Mixed.wait(1000);
// this method is called by a timer each second, so this counter counts seconds
counter++;
updateDownloadCountLabel();
startDownloadThread();
removeFinishedDownloads();
}
}
/**
* This method is usually called from a thread to notify the ticker that
* the thread has finished (so that it can notify its listeners of the fact). It also
* releases the thread so that new threads can start if needed.
*/
void threadFinished() {
runningThreads--;
fireThreadCountChanged();
releaseThread();
}
/**
* This method is called from a thread to notify the ticker that
* the thread has started (so that it can notify its listeners of the fact)
*/
void threadStarted() {
runningThreads++;
fireThreadCountChanged();
}
/**
*
*/
private void removeFinishedDownloads() {
if (counter % 300 == 0 && settings.getBoolValue("removeFinishedDownloads")) {
model.removeFinishedDownloads();
}
}
/**
* Removes an <code>DownloadTickerListener</code> from the DownloadTicker.
* @param listener the <code>DownloadTickerListener</code> to be removed
*/
public void removeDownloadTickerListener(DownloadTickerListener listener) {
listenerList.remove(DownloadTickerListener.class, listener);
}
/**
* Updates the download items count label. The label shows all WAITING items in download table.
* Called periodically by timer_actionPerformed().
*/
public void updateDownloadCountLabel() {
if (settings.getBoolValue(SettingsClass.DISABLE_DOWNLOADS) == true)
return;
int waitingItems = 0;
for (int x = 0; x < model.getItemCount(); x++) {
FrostDownloadItem dlItem = (FrostDownloadItem) model.getItemAt(x);
if (dlItem.getState() == FrostDownloadItem.STATE_WAITING) {
waitingItems++;
}
}
panel.setDownloadItemCount(waitingItems);
}
/**
*
*/
private void startDownloadThread() {
if (panel.isDownloadingActivated() && allocateThread()) {
boolean threadLaunched = false;
FrostDownloadItem dlItem = selectNextDownloadItem();
if (dlItem != null) {
dlItem.setState(FrostDownloadItem.STATE_TRYING);
DownloadThread newRequest = new DownloadThread(this, dlItem, model, settings);
newRequest.start();
threadLaunched = true;
}
if (!threadLaunched) {
releaseThread();
}
}
}
/**
* Chooses next download item to start from download table.
* @return the next download item to start downloading or null if a suitable
* one was not found.
*/
private FrostDownloadItem selectNextDownloadItem() {
// get the item with state "Waiting", minimum htl and not over maximum htl
ArrayList waitingItems = new ArrayList();
for (int i = 0; i < model.getItemCount(); i++) {
FrostDownloadItem dlItem = (FrostDownloadItem) model.getItemAt(i);
if ((dlItem.getState() == FrostDownloadItem.STATE_WAITING
&& (dlItem.getEnableDownload() == null
|| dlItem.getEnableDownload().booleanValue()
== true) // && dlItem.getRetries() <= frame1.frostSettings.getIntValue("downloadMaxRetries")
)
|| ((dlItem.getState() == FrostDownloadItem.STATE_REQUESTED
|| dlItem.getState() == FrostDownloadItem.STATE_REQUESTING)
&& dlItem.getKey() != null
&& (dlItem.getEnableDownload() == null
|| dlItem.getEnableDownload().booleanValue() == true))) {
// check if waittime is expired
long waittimeMillis = settings.getIntValue("downloadWaittime") * 60 * 1000;
// min->millisec
- if (settings.getBoolValue("downloadRestartFailedDownloads")
- && (System.currentTimeMillis() - dlItem.getLastDownloadStopTimeMillis())
- > waittimeMillis) {
+ if (dlItem.getLastDownloadStopTimeMillis() == 0 || // never started
+ (settings.getBoolValue("downloadRestartFailedDownloads")
+ && (System.currentTimeMillis() - dlItem.getLastDownloadStopTimeMillis()) > waittimeMillis))
+ {
waitingItems.add(dlItem);
}
}
}
if (waitingItems.size() == 0)
return null;
if (waitingItems.size() > 1) { // performance issues
Collections.sort(waitingItems, downloadDlStopMillisCmp);
}
return (FrostDownloadItem) waitingItems.get(0);
}
}
| true | true | private FrostDownloadItem selectNextDownloadItem() {
// get the item with state "Waiting", minimum htl and not over maximum htl
ArrayList waitingItems = new ArrayList();
for (int i = 0; i < model.getItemCount(); i++) {
FrostDownloadItem dlItem = (FrostDownloadItem) model.getItemAt(i);
if ((dlItem.getState() == FrostDownloadItem.STATE_WAITING
&& (dlItem.getEnableDownload() == null
|| dlItem.getEnableDownload().booleanValue()
== true) // && dlItem.getRetries() <= frame1.frostSettings.getIntValue("downloadMaxRetries")
)
|| ((dlItem.getState() == FrostDownloadItem.STATE_REQUESTED
|| dlItem.getState() == FrostDownloadItem.STATE_REQUESTING)
&& dlItem.getKey() != null
&& (dlItem.getEnableDownload() == null
|| dlItem.getEnableDownload().booleanValue() == true))) {
// check if waittime is expired
long waittimeMillis = settings.getIntValue("downloadWaittime") * 60 * 1000;
// min->millisec
if (settings.getBoolValue("downloadRestartFailedDownloads")
&& (System.currentTimeMillis() - dlItem.getLastDownloadStopTimeMillis())
> waittimeMillis) {
waitingItems.add(dlItem);
}
}
}
if (waitingItems.size() == 0)
return null;
if (waitingItems.size() > 1) { // performance issues
Collections.sort(waitingItems, downloadDlStopMillisCmp);
}
return (FrostDownloadItem) waitingItems.get(0);
}
| private FrostDownloadItem selectNextDownloadItem() {
// get the item with state "Waiting", minimum htl and not over maximum htl
ArrayList waitingItems = new ArrayList();
for (int i = 0; i < model.getItemCount(); i++) {
FrostDownloadItem dlItem = (FrostDownloadItem) model.getItemAt(i);
if ((dlItem.getState() == FrostDownloadItem.STATE_WAITING
&& (dlItem.getEnableDownload() == null
|| dlItem.getEnableDownload().booleanValue()
== true) // && dlItem.getRetries() <= frame1.frostSettings.getIntValue("downloadMaxRetries")
)
|| ((dlItem.getState() == FrostDownloadItem.STATE_REQUESTED
|| dlItem.getState() == FrostDownloadItem.STATE_REQUESTING)
&& dlItem.getKey() != null
&& (dlItem.getEnableDownload() == null
|| dlItem.getEnableDownload().booleanValue() == true))) {
// check if waittime is expired
long waittimeMillis = settings.getIntValue("downloadWaittime") * 60 * 1000;
// min->millisec
if (dlItem.getLastDownloadStopTimeMillis() == 0 || // never started
(settings.getBoolValue("downloadRestartFailedDownloads")
&& (System.currentTimeMillis() - dlItem.getLastDownloadStopTimeMillis()) > waittimeMillis))
{
waitingItems.add(dlItem);
}
}
}
if (waitingItems.size() == 0)
return null;
if (waitingItems.size() > 1) { // performance issues
Collections.sort(waitingItems, downloadDlStopMillisCmp);
}
return (FrostDownloadItem) waitingItems.get(0);
}
|
diff --git a/src/GUI/LogInAnotherUserPanel.java b/src/GUI/LogInAnotherUserPanel.java
index 7c1b514..fc1ce17 100644
--- a/src/GUI/LogInAnotherUserPanel.java
+++ b/src/GUI/LogInAnotherUserPanel.java
@@ -1,296 +1,297 @@
package GUI;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import main.BlasterCardListener;
import main.Machine;
import main.Tool;
import main.User;
import main.Validator;
public class LogInAnotherUserPanel extends ContentPanel {
private JButton saveButton;
private JButton goButton;
private JButton logOutUser;
private ButtonListener buttonListener;
private JTextField cwidField;
private JScrollPane scroller1;
private JScrollPane scroller2;
private JScrollPane scroller3;
private JPanel selectionPanel;
private JPanel machines;
private JPanel availableTools;
private JPanel checkedOutTools;
private User user;
private User current;
public LogInAnotherUserPanel() {
// All the fonts are in ContentPanel.
super("Sign In Another User");
current = Driver.getAccessTracker().getCurrentUser();
buttonListener = new ButtonListener();
selectionPanel = new JPanel(new GridLayout(1, 3));
JLabel cwidLabel = new JLabel("Enter CWID:");
cwidField = new JTextField();
cwidField.setFont(textFont);
cwidField.addActionListener(buttonListener);
cwidLabel.setFont(borderFont);
goButton = new JButton("Go");
goButton.setFont(buttonFont);
goButton.addActionListener(buttonListener);
machines = new JPanel();
availableTools = new JPanel();
checkedOutTools = new JPanel();
machines.setLayout(new GridLayout(0, 1));
availableTools.setLayout(new GridLayout(0, 1));
checkedOutTools.setLayout(new GridLayout(0, 1));
scroller1 = new JScrollPane(machines, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroller2 = new JScrollPane(availableTools, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroller3 = new JScrollPane(checkedOutTools, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
TitledBorder border1 = new TitledBorder("Select Machines");
TitledBorder border2 = new TitledBorder("Check Out Tools");
TitledBorder border3 = new TitledBorder("Return Tools");
border1.setTitleFont(borderFont);
border2.setTitleFont(borderFont);
border3.setTitleFont(borderFont);
scroller1.setBorder(border1);
scroller2.setBorder(border2);
scroller3.setBorder(border3);
selectionPanel.add(scroller1);
selectionPanel.add(scroller2);
selectionPanel.add(scroller3);
logOutUser = new JButton("Sign Out User");
logOutUser.setFont(buttonFont);
logOutUser.addActionListener(buttonListener);
JPanel cwidPanel = new JPanel(new GridLayout(1, 3));
cwidPanel.add(cwidLabel);
cwidPanel.add(cwidField);
cwidPanel.add(goButton);
saveButton = new JButton("Save");
saveButton.setFont(buttonFont);
saveButton.addActionListener(buttonListener);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.6;
c.weighty = 0.1;
c.gridx = 1;
c.gridy = 1;
add(cwidPanel, c);
c.fill = GridBagConstraints.NONE;
c.weightx = 0.0;
c.weighty = 0.1;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 2;
add(logOutUser, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.3;
c.weighty = 0.5;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 3;
add(selectionPanel, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.0;
c.weighty = 0.1;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 4;
add(saveButton, c);
c.weighty = 0.1;
c.gridy = 5;
add(new JPanel(), c);
}
public void showMessage(String message) {
JOptionPane.showMessageDialog(this, message);
}
private void showMachines() {
machines.removeAll();
for ( Machine m : user.getCertifiedMachines() ) {
JCheckBox cb = new JCheckBox(m.getName() + " [" + m.getID() + "]");
cb.setHorizontalAlignment(JCheckBox.LEFT);
cb.setFont(checkBoxFont);
machines.add(cb);
if (user.getCurrentEntry().getMachinesUsed().contains(m)){
cb.setEnabled(false);
}
}
}
private void showaAvailableTools() {
availableTools.removeAll();
for ( Tool t : Driver.getAccessTracker().getTools()) {
JCheckBox cb = new JCheckBox(t.getName() + " [" + t.getUPC() + "]");
cb.setHorizontalAlignment(JCheckBox.LEFT);
cb.setFont(checkBoxFont);
if (!user.getToolsCheckedOut().contains(t))
availableTools.add(cb);
if (t.isCheckedOut()) {
cb.setEnabled(false);
}
}
}
private void showCheckedOutTools() {
checkedOutTools.removeAll();
for ( Tool t : user.getToolsCheckedOut()) {
JCheckBox cb = new JCheckBox(t.getName() + " [" + t.getUPC() + "]");
cb.setHorizontalAlignment(JCheckBox.LEFT);
cb.setFont(checkBoxFont);
checkedOutTools.add(cb);
}
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if ( e.getSource() == saveButton) {
if ( user == null ) {
showMessage("Please enter the user's CWID.");
} else {
ArrayList<Machine> machinesSelected = new ArrayList<Machine>();
for ( int i = 0; i < machines.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) machines.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Machine m : Driver.getAccessTracker().getMachines() ) {
String ID = m.getID();
if ( s.equals(ID) ) {
machinesSelected.add(m);
}
}
}
}
ArrayList<Tool> availableToolsSelected = new ArrayList<Tool>();
for ( int i = 0; i < availableTools.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) availableTools.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Tool t : Driver.getAccessTracker().getTools() ) {
String UPC = t.getUPC();
if ( s.equals(UPC) ) {
availableToolsSelected.add(t);
}
}
}
}
ArrayList<Tool> checkedOutToolsSelected = new ArrayList<Tool>();
for ( int i = 0; i < checkedOutTools.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) checkedOutTools.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Tool t : Driver.getAccessTracker().getTools() ) {
String UPC = t.getUPC();
if ( s.equals(UPC) ) {
checkedOutToolsSelected.add(t);
}
}
}
}
for (Machine m : machinesSelected) {
user.useMachine(m);
}
user.getCurrentEntry().addMachinesUsed(machinesSelected);
for (Tool t : availableToolsSelected) {
user.checkoutTool(t);
}
user.getCurrentEntry().addToolsCheckedOut(availableToolsSelected);
if (checkedOutToolsSelected.size() > 0){
user.returnTools(checkedOutToolsSelected);
user.getCurrentEntry().addToolsReturned(checkedOutToolsSelected);
}
}
clearFields();
} else if ( e.getSource() == goButton || e.getSource() == cwidField ) {
if (cwidField.getText().equals("")) {
showMessage("Please enter 8-digit CWID, numbers only.");
+ clearFields();
} else {
String input = BlasterCardListener.strip(cwidField.getText());
if (!Validator.isValidCWID(input)) {
return;
}
if (!input.equals(current.getCWID())) {
user = Driver.getAccessTracker().processLogIn(input);
Driver.getAccessTracker().setCurrentUser(current);
System.out.println(user);
cwidField.setText(user.getFirstName() + " " + user.getLastName() + " [" + user.getDepartment() + "]");
showMachines();
showaAvailableTools();
showCheckedOutTools();
} else {
cwidField.setText("");
showMessage("You can't sign yourself in again. Sorry");
}
}
} else if ( e.getSource() == logOutUser) {
if (user != null) {
Driver.getAccessTracker().processLogOut(user.getCWID());
clearFields();
}
}
}
}
// Clears all the text fields to empty, and set the user null.
private void clearFields() {
cwidField.setText("");
user = null;
machines.removeAll();
availableTools.removeAll();
checkedOutTools.removeAll();
Driver.getAccessTracker().setCurrentUser(current);
}
}
| true | true | public void actionPerformed(ActionEvent e) {
if ( e.getSource() == saveButton) {
if ( user == null ) {
showMessage("Please enter the user's CWID.");
} else {
ArrayList<Machine> machinesSelected = new ArrayList<Machine>();
for ( int i = 0; i < machines.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) machines.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Machine m : Driver.getAccessTracker().getMachines() ) {
String ID = m.getID();
if ( s.equals(ID) ) {
machinesSelected.add(m);
}
}
}
}
ArrayList<Tool> availableToolsSelected = new ArrayList<Tool>();
for ( int i = 0; i < availableTools.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) availableTools.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Tool t : Driver.getAccessTracker().getTools() ) {
String UPC = t.getUPC();
if ( s.equals(UPC) ) {
availableToolsSelected.add(t);
}
}
}
}
ArrayList<Tool> checkedOutToolsSelected = new ArrayList<Tool>();
for ( int i = 0; i < checkedOutTools.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) checkedOutTools.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Tool t : Driver.getAccessTracker().getTools() ) {
String UPC = t.getUPC();
if ( s.equals(UPC) ) {
checkedOutToolsSelected.add(t);
}
}
}
}
for (Machine m : machinesSelected) {
user.useMachine(m);
}
user.getCurrentEntry().addMachinesUsed(machinesSelected);
for (Tool t : availableToolsSelected) {
user.checkoutTool(t);
}
user.getCurrentEntry().addToolsCheckedOut(availableToolsSelected);
if (checkedOutToolsSelected.size() > 0){
user.returnTools(checkedOutToolsSelected);
user.getCurrentEntry().addToolsReturned(checkedOutToolsSelected);
}
}
clearFields();
} else if ( e.getSource() == goButton || e.getSource() == cwidField ) {
if (cwidField.getText().equals("")) {
showMessage("Please enter 8-digit CWID, numbers only.");
} else {
String input = BlasterCardListener.strip(cwidField.getText());
if (!Validator.isValidCWID(input)) {
return;
}
if (!input.equals(current.getCWID())) {
user = Driver.getAccessTracker().processLogIn(input);
Driver.getAccessTracker().setCurrentUser(current);
System.out.println(user);
cwidField.setText(user.getFirstName() + " " + user.getLastName() + " [" + user.getDepartment() + "]");
showMachines();
showaAvailableTools();
showCheckedOutTools();
} else {
cwidField.setText("");
showMessage("You can't sign yourself in again. Sorry");
}
}
} else if ( e.getSource() == logOutUser) {
if (user != null) {
Driver.getAccessTracker().processLogOut(user.getCWID());
clearFields();
}
}
}
| public void actionPerformed(ActionEvent e) {
if ( e.getSource() == saveButton) {
if ( user == null ) {
showMessage("Please enter the user's CWID.");
} else {
ArrayList<Machine> machinesSelected = new ArrayList<Machine>();
for ( int i = 0; i < machines.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) machines.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Machine m : Driver.getAccessTracker().getMachines() ) {
String ID = m.getID();
if ( s.equals(ID) ) {
machinesSelected.add(m);
}
}
}
}
ArrayList<Tool> availableToolsSelected = new ArrayList<Tool>();
for ( int i = 0; i < availableTools.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) availableTools.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Tool t : Driver.getAccessTracker().getTools() ) {
String UPC = t.getUPC();
if ( s.equals(UPC) ) {
availableToolsSelected.add(t);
}
}
}
}
ArrayList<Tool> checkedOutToolsSelected = new ArrayList<Tool>();
for ( int i = 0; i < checkedOutTools.getComponentCount(); ++i ) {
JCheckBox cb = (JCheckBox) checkedOutTools.getComponent(i);
if ( cb.isSelected() ) {
String s = cb.getText();
s = s.substring(s.indexOf('[') + 1, s.indexOf(']'));
for ( Tool t : Driver.getAccessTracker().getTools() ) {
String UPC = t.getUPC();
if ( s.equals(UPC) ) {
checkedOutToolsSelected.add(t);
}
}
}
}
for (Machine m : machinesSelected) {
user.useMachine(m);
}
user.getCurrentEntry().addMachinesUsed(machinesSelected);
for (Tool t : availableToolsSelected) {
user.checkoutTool(t);
}
user.getCurrentEntry().addToolsCheckedOut(availableToolsSelected);
if (checkedOutToolsSelected.size() > 0){
user.returnTools(checkedOutToolsSelected);
user.getCurrentEntry().addToolsReturned(checkedOutToolsSelected);
}
}
clearFields();
} else if ( e.getSource() == goButton || e.getSource() == cwidField ) {
if (cwidField.getText().equals("")) {
showMessage("Please enter 8-digit CWID, numbers only.");
clearFields();
} else {
String input = BlasterCardListener.strip(cwidField.getText());
if (!Validator.isValidCWID(input)) {
return;
}
if (!input.equals(current.getCWID())) {
user = Driver.getAccessTracker().processLogIn(input);
Driver.getAccessTracker().setCurrentUser(current);
System.out.println(user);
cwidField.setText(user.getFirstName() + " " + user.getLastName() + " [" + user.getDepartment() + "]");
showMachines();
showaAvailableTools();
showCheckedOutTools();
} else {
cwidField.setText("");
showMessage("You can't sign yourself in again. Sorry");
}
}
} else if ( e.getSource() == logOutUser) {
if (user != null) {
Driver.getAccessTracker().processLogOut(user.getCWID());
clearFields();
}
}
}
|
diff --git a/src/main/java/me/limebyte/endercraftessentials/EventListener.java b/src/main/java/me/limebyte/endercraftessentials/EventListener.java
index e002f07..b7ea429 100644
--- a/src/main/java/me/limebyte/endercraftessentials/EventListener.java
+++ b/src/main/java/me/limebyte/endercraftessentials/EventListener.java
@@ -1,155 +1,159 @@
package me.limebyte.endercraftessentials;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.kitteh.tag.TagAPI;
public class EventListener implements Listener {
private static final Material LIGHT_LEVEL_ITEM = Material.GLOWSTONE_DUST;
private static final Material HUNGER_INFO_ITEM = Material.POISONOUS_POTATO;
private static final String REI_PREFIX = "&0&0";
private static final String REI_SUFFIX = "&e&f";
@SuppressWarnings("unused")
private static final String REI_CAVE_MAPPING = "&1";
private static final String REI_PLAYER_RADAR = "&2";
private static final String REI_ANIMAL_RADAR = "&3";
@SuppressWarnings("unused")
private static final String REI_MOB_RADAR = "&4";
@SuppressWarnings("unused")
private static final String REI_SLIME_RADAR = "&5";
private static final String REI_SQUID_RADAR = "&6";
@SuppressWarnings("unused")
private static final String REI_LIVING_RADAR = "&7";
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getItem() != null) {
if (event.getItem().getType() == LIGHT_LEVEL_ITEM) {
Block block = event.getClickedBlock().getRelative(event.getBlockFace());
int lightLevel = block.getLightLevel();
event.getPlayer().sendMessage(ChatColor.GOLD + "The light level of the selected block is " + lightLevel + ".");
}
+ }
+ }
+ if (event.getAction() == Action.RIGHT_CLICK_AIR) {
+ if (event.getItem() != null) {
if (event.getItem().getType() == HUNGER_INFO_ITEM) {
Player player = event.getPlayer();
String title = ChatColor.GOLD + " --- " +
ChatColor.ITALIC + "Hunger Info" +
ChatColor.RESET + ChatColor.GOLD + " --- ";
player.sendMessage(title);
player.sendMessage(ChatColor.WHITE + "FoodLevel: " + player.getFoodLevel());
player.sendMessage(ChatColor.WHITE + "Saturation: " + player.getSaturation());
player.sendMessage(ChatColor.WHITE + "Exhaustion: " + player.getExhaustion());
player.sendMessage(ChatColor.GOLD + " ------------------- ");
}
}
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
setDisplayName(player);
String welcome = ChatColor.DARK_PURPLE + "Welcome to Endercraft " + player.getDisplayName() + "!";
String message = REI_PREFIX + REI_PLAYER_RADAR + REI_ANIMAL_RADAR + REI_SQUID_RADAR + REI_SUFFIX;
player.sendMessage(ChatColor.translateAlternateColorCodes('&', message) + welcome);
event.setJoinMessage(event.getJoinMessage().replaceAll(player.getName(), player.getDisplayName()));
if (isPranked(player)) {
player.sendMessage("You have pranked");
player.sendMessage("but are now outranked.");
player.sendMessage("Blocks for code,");
player.sendMessage("pranks echoed.");
player.sendMessage("Not to be rude,");
player.sendMessage("but I have called you a noob.");
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
event.setQuitMessage(event.getQuitMessage().replaceAll(player.getName(), player.getDisplayName()));
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
event.setDeathMessage(event.getDeathMessage().replaceAll(player.getName(), player.getDisplayName()));
}
@EventHandler
public void onNameplate(PlayerReceiveNameTagEvent event) {
if (!event.isModified()) {
Player player = event.getNamedPlayer();
String name = player.getName();
String displayName = player.getDisplayName();
if (name.equalsIgnoreCase("bj2864") || name.equalsIgnoreCase("bg1345") || isPranked(player)) {
event.setTag(displayName);
}
}
}
private void setDisplayName(Player player) {
String name = player.getName();
if (name.equalsIgnoreCase("limebyte")) {
rename(player, "LimeByte");
} else if (name.equalsIgnoreCase("bj2864")) {
rename(player, "BennyBoi");
} else if (name.equalsIgnoreCase("bg1345")) {
rename(player, "Ashpof");
} else if (name.equalsIgnoreCase("tegdim")) {
rename(player, "Tegdim");
}
if (isPranked(player)) {
rename(player, "Noob");
}
}
private void rename(Player player, String name) {
player.setDisplayName(name);
TagAPI.refreshPlayer(player);
setPlayerListName(player, name);
}
private void setPlayerListName(Player player, String name) {
try {
player.setPlayerListName(name);
} catch (IllegalArgumentException e) {
try {
String number = String.valueOf(System.currentTimeMillis() % 9);
if (16 - name.length() < 3) {
player.setPlayerListName(name.substring(0, 16 - 3) + " " + number);
} else {
player.setPlayerListName(name + " " + number);
}
} catch (IllegalArgumentException e1) {
setPlayerListName(player, name);
}
}
}
private boolean isPranked(Player player) {
for (String name : EndercraftEssentials.getPrankedNames()) {
if (player.getName().equalsIgnoreCase(name)) return true;
}
return false;
}
}
| false | true | public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getItem() != null) {
if (event.getItem().getType() == LIGHT_LEVEL_ITEM) {
Block block = event.getClickedBlock().getRelative(event.getBlockFace());
int lightLevel = block.getLightLevel();
event.getPlayer().sendMessage(ChatColor.GOLD + "The light level of the selected block is " + lightLevel + ".");
}
if (event.getItem().getType() == HUNGER_INFO_ITEM) {
Player player = event.getPlayer();
String title = ChatColor.GOLD + " --- " +
ChatColor.ITALIC + "Hunger Info" +
ChatColor.RESET + ChatColor.GOLD + " --- ";
player.sendMessage(title);
player.sendMessage(ChatColor.WHITE + "FoodLevel: " + player.getFoodLevel());
player.sendMessage(ChatColor.WHITE + "Saturation: " + player.getSaturation());
player.sendMessage(ChatColor.WHITE + "Exhaustion: " + player.getExhaustion());
player.sendMessage(ChatColor.GOLD + " ------------------- ");
}
}
}
}
| public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getItem() != null) {
if (event.getItem().getType() == LIGHT_LEVEL_ITEM) {
Block block = event.getClickedBlock().getRelative(event.getBlockFace());
int lightLevel = block.getLightLevel();
event.getPlayer().sendMessage(ChatColor.GOLD + "The light level of the selected block is " + lightLevel + ".");
}
}
}
if (event.getAction() == Action.RIGHT_CLICK_AIR) {
if (event.getItem() != null) {
if (event.getItem().getType() == HUNGER_INFO_ITEM) {
Player player = event.getPlayer();
String title = ChatColor.GOLD + " --- " +
ChatColor.ITALIC + "Hunger Info" +
ChatColor.RESET + ChatColor.GOLD + " --- ";
player.sendMessage(title);
player.sendMessage(ChatColor.WHITE + "FoodLevel: " + player.getFoodLevel());
player.sendMessage(ChatColor.WHITE + "Saturation: " + player.getSaturation());
player.sendMessage(ChatColor.WHITE + "Exhaustion: " + player.getExhaustion());
player.sendMessage(ChatColor.GOLD + " ------------------- ");
}
}
}
}
|
diff --git a/src/main/java/org/swfparser/StatementBlockImpl.java b/src/main/java/org/swfparser/StatementBlockImpl.java
index f8ed019..fd82af3 100755
--- a/src/main/java/org/swfparser/StatementBlockImpl.java
+++ b/src/main/java/org/swfparser/StatementBlockImpl.java
@@ -1,1213 +1,1215 @@
/*
* StatementBlockImpl.java
* @Author Oleg Gorobets
* Created: 24.07.2007
* CVS-ID: $Id:
*************************************************************************/
package org.swfparser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.springframework.util.StringUtils;
import org.apache.log4j.Logger;
import org.swfparser.annotations.NewAnalyzer;
import org.swfparser.exception.StatementBlockException;
import org.swfparser.operation.*;
import org.swfparser.operation.StoreRegisterOperation.RegisterHandle;
import org.swfparser.pattern.BreakPattern;
import org.swfparser.pattern.ContinuePattern;
import org.swfparser.pattern.DoWhilePattern;
import org.swfparser.pattern.ForInPattern;
import org.swfparser.pattern.IfElsePattern;
import org.swfparser.pattern.IfPattern;
import org.swfparser.pattern.Pattern;
import org.swfparser.pattern.SkipForDoWhilePattern;
import org.swfparser.pattern.SkipPattern;
import org.swfparser.pattern.SwitchPattern;
import org.swfparser.pattern.TellTargetPattern;
import org.swfparser.pattern.WhilePattern;
import org.swfparser.util.PrintfFormat;
import com.jswiff.io.OutputBitStream;
import com.jswiff.swfrecords.actions.Action;
import com.jswiff.swfrecords.actions.ActionConstants;
import com.jswiff.swfrecords.actions.Branch;
import com.jswiff.swfrecords.actions.ConstantPool;
import com.jswiff.swfrecords.actions.DefineFunction;
import com.jswiff.swfrecords.actions.DefineFunction2;
import com.jswiff.swfrecords.actions.GetURL2;
import com.jswiff.swfrecords.actions.GoToFrame;
import com.jswiff.swfrecords.actions.GoToFrame2;
import com.jswiff.swfrecords.actions.GoToLabel;
import com.jswiff.swfrecords.actions.NullStackValue;
import com.jswiff.swfrecords.actions.Pop;
import com.jswiff.swfrecords.actions.Push;
import com.jswiff.swfrecords.actions.SetTarget;
import com.jswiff.swfrecords.actions.SetTarget2;
import com.jswiff.swfrecords.actions.StackValue;
import com.jswiff.swfrecords.actions.StoreRegister;
import com.jswiff.swfrecords.actions.Try;
import com.jswiff.swfrecords.actions.UndefinedStackValue;
import com.jswiff.swfrecords.actions.WaitForFrame;
import com.jswiff.swfrecords.actions.WaitForFrame2;
import com.jswiff.swfrecords.actions.With;
public class StatementBlockImpl implements StatementBlock {
private static Logger logger = Logger.getLogger(StatementBlockImpl.class);
private List<Operation> statements = new ArrayList<Operation>();
private static PrintfFormat actionFormat = new PrintfFormat("A:0x%02X (%s) label:%s");
private ExecutionContext context;
private StatementBlockMoment moment = new StatementBlockMoment();
private boolean canAddStatements = true;
public void read(List<Action> actions) throws StatementBlockException {
boolean isRootBlock = context.getOperationStack().isEmpty();
Operation enclosingOperation=null;
String blockName;
moment.setActions(actions);
boolean newLabelsWereBuilt = false;
if (isRootBlock) {
blockName = "$ (rootMovie)" ;
newLabelsWereBuilt=true;
// context.setPatternAnalyzer(new PatternAnalyzer(actions));
PatternAnalyzerEx patternAnalyzerEx = new PatternAnalyzerEx(new PatternContext(), actions);
patternAnalyzerEx.analyze();
context.setPatternAnalyzerEx(patternAnalyzerEx);
} else {
enclosingOperation = context.getOperationStack().peek();
blockName = enclosingOperation.getClass().getSimpleName();
if (enclosingOperation.getClass().getAnnotation(NewAnalyzer.class)!=null) {
// context.setPatternAnalyzer(new PatternAnalyzer(actions));
PatternAnalyzerEx patternAnalyzerEx = new PatternAnalyzerEx(new PatternContext(), actions);
patternAnalyzerEx.analyze();
context.setPatternAnalyzerEx(patternAnalyzerEx);
newLabelsWereBuilt=true;
}
}
// read all labels
logger.debug(" : : : BLOCK START : : : - blockName: " + blockName+", actions.size = "+actions.size());//+", Stack size : " + stack.size());
String regInfo="REGS:";
String labelInfo = newLabelsWereBuilt ? "LABELS BUILT: " : "LABELS INHERITED: ";
int yui=1;
for (Operation op : context.getRegisters()) {
regInfo += (yui++) + " => " + op + ",";
}
if (context.getPatternAnalyzerEx()!=null) {
for (String lab : context.getPatternAnalyzerEx().getLabels().keySet()) {
labelInfo += lab + ", ";
}
}
logger.debug(regInfo);
logger.debug(labelInfo);
// for (Action action : actions) {
//
// if (action instanceof Branch) {
// Branch branch = (Branch) action;
// logger.debug(
// actionFormat.sprintf(new Object[]{action.getCode(),ActionConstants.getActionName(action.getCode())}) +
// " L:"+action.getLabel()+" BL:"+branch.getBranchLabel()
// );
// } else {
// logger.debug(
// actionFormat.sprintf(new Object[]{action.getCode(),ActionConstants.getActionName(action.getCode())}) +
// " L:"+action.getLabel()
// );
// }
// }
// actionIndex = actions.size();
int actionIndex = 0;
Map<Operation, Action> stackOperationToActionMap = new IdentityHashMap<Operation, Action>();
try {
while (actionIndex < actions.size()) {
Action action = actions.get(actionIndex);
// set context
moment.setActionIndex(actionIndex);
moment.setStatements(statements);
context.getMomentStack().push(moment);
String label = action.getLabel();
logger.debug(
"=== " +
ActionConstants.getActionName(action.getCode()) + " === " +
(label != null ? label : " (label=null)"));
int actionIndexShift=1;
if (context.getPatternAnalyzerEx()!=null && context.getPatternAnalyzerEx().getPatternByLabel(action.getLabel())!=null) {
Pattern branchPattern = context.getPatternAnalyzerEx().getPatternByLabel(action.getLabel());
logger.debug("Branch pattern found: "+branchPattern);
handleByPattern(actionIndex, action);
actionIndexShift+=branchPattern.size();
} else {
actionIndexShift+=handleByActionCode(action);
}
// map newly added operations to this action
for (Operation operation : context.getExecStack()) {
if (!stackOperationToActionMap.containsKey(operation)) {
stackOperationToActionMap.put(operation, action);
}
}
context.getMomentStack().pop();
actionIndex += actionIndexShift;
logger.debug("STACK, length = "+context.getExecStack().size() + ", values=" + context.getExecStack());
}
} catch (EmptyStackException e) {
e.printStackTrace();
Stack<Operation> operationStack = context.getOperationStack();
while (!operationStack.isEmpty()) {
logger.debug("OP_STACK_TRACE: "+operationStack.pop());
}
logger.debug("~~~~~ Writing UNFINISHED BLOCK statements ~~~");
for (Operation op : statements) {
String endOfStatement = CodeUtil.endOfStatement(op);
logger.debug(op.getStringValue(0)+endOfStatement+" // "+op+"\n");
}
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputBitStream outputBitStream = new OutputBitStream(byteArrayOutputStream);
for (Action a : actions) {
a.write(outputBitStream);
}
statements.clear();
ByteCodeOperation byteCodeOperation = new ByteCodeOperation(byteArrayOutputStream.toByteArray());
statements.add(byteCodeOperation);
logger.debug("Adding bytecode operation\n"+byteCodeOperation.getStringValue(0));
} catch (IOException e1) {
e1.printStackTrace();
}
throw new StatementBlockException(e);
} catch (StatementBlockException e) {
e.printStackTrace();
Stack<Operation> operationStack = context.getOperationStack();
while (!operationStack.isEmpty()) {
logger.debug("OP_STACK_TRACE: "+operationStack.pop());
}
logger.debug("~~~~~ Writing UNFINISHED BLOCK statements ~~~");
for (Operation op : statements) {
String endOfStatement = CodeUtil.endOfStatement(op);
logger.debug(op.getStringValue(0)+endOfStatement+" // "+op.getClass().getName()+"\n");
}
throw new StatementBlockException(e);
}
postProcessStatements();
if (isRootBlock) {
checkStackInTheEndOfTheBlock(stackOperationToActionMap);
logger.debug("~~~~~ Writing statements ~~~");
for (Operation op : statements) {
String endOfStatement = CodeUtil.endOfStatement(op);
logger.debug(op.getStringValue(0)+endOfStatement+" // "+op.getClass().getName()+"\n");
}
}
logger.debug(" : : : BLOCK FINISHED : : : - blockName: " + blockName);
}
protected void checkStackInTheEndOfTheBlock(Map<Operation, Action> stackOperationToActionMap) {
logger.debug("Checking stack before writing statements...");
Stack<Operation> stack = context.getExecStack();
if (stack.isEmpty()) {
logger.debug("STACK is empty ... OK");
} else {
logger.debug("STACK length: " + stack.size());
for (Operation operation : stack) {
logger.debug("Checking "+operation+". Maps to action "+stackOperationToActionMap.get(operation));
}
}
}
private void handleByPattern(int actionIndex, Action action) throws StatementBlockException {
// Pattern branchPattern = context.getPatternAnalyzer().getPatternByLabel(action.getLabel());
Pattern branchPattern = context.getPatternAnalyzerEx().getPatternByLabel(action.getLabel());
Class branchPatternClass = branchPattern.getClass();
Stack<Operation> stack = context.getExecStack();
if (branchPatternClass.equals( SwitchPattern.class )) {
addStatement( new SwitchOperation(context, (SwitchPattern) branchPattern));
}
if (branchPatternClass.equals( TellTargetPattern.class )) {
if (action instanceof SetTarget) {
SetTarget setTarget = (SetTarget) action;
addStatement( new SetTargetOperation(stack,context,((TellTargetPattern)branchPattern).getActions(),setTarget));
} else if (action instanceof SetTarget2) {
SetTarget2 setTarget = (SetTarget2) action;
addStatement( new SetTarget2Operation(stack,context,((TellTargetPattern)branchPattern).getActions(),setTarget));
}
return;
}
if (branchPatternClass.equals( WhilePattern.class )) {
Operation op = new WhileOperation(stack,((WhilePattern)branchPattern).getActions(),context);
addStatement(op);
return;
}
if (branchPatternClass.equals( DoWhilePattern.class )) {
canAddStatements = true;
Operation op = new DoWhileOperation(stack,((DoWhilePattern)branchPattern).getActions(),context);
logger.debug("Adding "+op+" to statement");
addStatement(op);
return;
}
if (branchPatternClass.equals( IfElsePattern.class )) {
Operation op = new IfElseOperation(stack,context,((IfElsePattern)branchPattern).getIfActions(),((IfElsePattern)branchPattern).getElseActions());
addStatement(op);
return;
}
if (branchPatternClass.equals( ContinuePattern.class )) {
addStatement(new SimpleOperation("continue"));
return;
}
if (branchPatternClass.equals( BreakPattern.class )) {
addStatement(new SimpleOperation("break"));
return;
}
// should go before SkipPattern
if (branchPatternClass.equals( SkipForDoWhilePattern.class )) {
canAddStatements = false;
// context.getPatternAnalyzer().clearBranchPattern(action.getLabel());
context.getPatternAnalyzerEx().clearBranchPattern(action.getLabel());
handleByActionCode(action);
return;
}
if (branchPatternClass.equals( SkipPattern.class )) {
return;
}
if (branchPatternClass.equals( ForInPattern.class )) {
addStatement(new ForInOperation(context,((ForInPattern)branchPattern).getActions(),((ForInPattern)branchPattern).getVarActions()));
return;
}
//
// If pattern should go the last!!!
//
if (branchPatternClass.equals( IfPattern.class )) {
Operation op = new IfOperation(stack,((IfPattern)branchPattern).getActions(),context);
addStatement(op);
return;
}
}
private int handleByActionCode(Action action) throws StatementBlockException {
int additionalActionShift = 0;
Stack<Operation> stack = context.getExecStack();
Operation op;
// int actionIndexShift = 1; // default
switch (action.getCode()) {
case ActionConstants.CONSTANT_POOL:
ConstantPool constantPool = (ConstantPool)action;
context.getConstants().addAll(constantPool.getConstants());
logger.debug("Loaded constants, length: "+context.getConstants().size() + ", values: " + context.getConstants());
break;
case ActionConstants.PUSH :
handlePush((Push)action,stack);
break;
case ActionConstants.PUSH_DUPLICATE :
stack.push(stack.peek());
break;
case ActionConstants.POP :
if (stack.isEmpty()) {
logger.error("Empty stack and POP() found");
break;
} else {
boolean writePop = stack.peek() instanceof DualUse;
if (writePop && !statements.isEmpty()) {
// check last statement
// if it is StoreRegister than do NOT write this POP()
Operation lastStatement = statements.get(statements.size()-1);
if (lastStatement instanceof StoreRegisterOperation) {
// writePop = lastStatement.getClass().getAnnotation(DoNotWritePop.class) == null;
writePop = ((StoreRegisterOperation) lastStatement).getOp() != ((ExecutionStack) stack).peek();
}
}
if (writePop) {
logger.debug("Writing POP()");
((DualUse)stack.peek()).markAsStatement();
addStatement(stack.pop());
} else {
logger.debug("Skipping POP()");
stack.pop();
}
}
break;
case ActionConstants.STACK_SWAP:
Operation item1 = stack.pop();
Operation item2 = stack.pop();
stack.push(item1);
stack.push(item2);
break;
case ActionConstants.DEFINE_LOCAL :
op = new DefineLocalOperation(stack);
addStatement(op);
break;
case ActionConstants.DEFINE_LOCAL_2 :
op = new DefineLocal2Operation(stack);
addStatement(op);
break;
//
// TODO: group simple operations
//
case ActionConstants.PREVIOUS_FRAME :
addStatement(new SimpleOperation("prevFrame()"));
break;
case ActionConstants.NEXT_FRAME:
stack.push(new SimpleOperation("nextFrame()"));
break;
case ActionConstants.PLAY:
if (!statements.isEmpty() && (statements.get(statements.size()-1) instanceof ActionAware)) {
((ActionAware)statements.get(statements.size()-1)).setAction(GotoFrameOperation.ACTION_PLAY);
} else {
addStatement(new SimpleOperation("play()"));
}
break;
case ActionConstants.STOP :
addStatement(new SimpleOperation("stop()"));
break;
case ActionConstants.STOP_SOUNDS:
addStatement(new SimpleOperation("stopAllSounds()"));
break;
case ActionConstants.GET_TIME:
stack.push(new SimpleFunctionOperation("getTimer()"));
break;
case ActionConstants.THROW:
addStatement(new ThrowOperation(stack));
break;
//
// Arithmetic operations
//
case ActionConstants.ADD:
case ActionConstants.ADD_2:
stack.push(new AddOperation(stack,action));
break;
case ActionConstants.SUBTRACT:
stack.push(new SubtractOperation(stack,action));
break;
case ActionConstants.DIVIDE:
stack.push(new DivideOperation(stack,action));
break;
case ActionConstants.MULTIPLY:
stack.push(new MultiplyOperation(stack,action));
break;
case ActionConstants.MODULO:
op = new ModuloOperation(stack,action);
stack.push(op);
break;
case ActionConstants.INCREMENT:
op = new SimpleIncrementOperation(stack);
stack.push(op);
break;
case ActionConstants.DECREMENT:
op = new SimpleDecrementOperation(stack);
stack.push(op);
break;
case ActionConstants.STRING_ADD:
stack.push(new StringAddOperation(stack));
break;
//
// Boolean operations
//
case ActionConstants.LESS:
case ActionConstants.LESS_2:
op = new LessOperation(stack);
stack.push(op);
break;
case ActionConstants.EQUALS:
case ActionConstants.EQUALS_2:
stack.push(new EqualsOperation(stack));
break;
case ActionConstants.STRICT_EQUALS:
stack.push(new StrictEqualsOperation(stack));
break;
case ActionConstants.GREATER:
op = new GreaterOperation(stack);
stack.push(op);
break;
case ActionConstants.AND:
stack.push(new AndOperation(stack));
break;
case ActionConstants.OR:
stack.push(new OrOperation(stack));
break;
case ActionConstants.GET_VARIABLE:
op = new GetVariableOperation(stack);
stack.push(op);
break;
case ActionConstants.CALL_METHOD:
stack.push(new CallMethodOperation(stack));
break;
case ActionConstants.SET_MEMBER:
op = new SetMemberOperation(stack);
addStatement(op);
break;
case ActionConstants.DEFINE_FUNCTION:
DefineFunction defineFunction = (DefineFunction)action;
op = new DefineFunctionOperation(stack,context,defineFunction);
if (StringUtils.hasText(defineFunction.getName())) {
addStatement(op); // function as statement
} else {
stack.push(op); // function as operation, put it to stack
}
break;
case ActionConstants.DEFINE_FUNCTION_2:
DefineFunction2 defineFunction2 = (DefineFunction2)action;
op = new DefineFunction2Operation(stack,defineFunction2,context);
if (StringUtils.hasText(defineFunction2.getName())) {
addStatement(op); // function as statement
} else {
stack.push(op); // function as operation, put it to stack
}
break;
case ActionConstants.GET_MEMBER:
stack.push( new GetMemberOperation(stack) );
break;
case ActionConstants.GET_PROPERTY:
stack.push( new GetPropertyOperation(stack) );
break;
//
// Type convertion funcs
//
case ActionConstants.TO_INTEGER:
stack.push(new ToIntegerOperation(stack));
break;
case ActionConstants.TO_NUMBER:
stack.push(new ToNumberOperation(stack));
break;
case ActionConstants.TO_STRING:
stack.push(new ToStringOperation(stack));
break;
// TODO: Check LABEL_OUT
case ActionConstants.JUMP:
case ActionConstants.IF:
Branch branch = (Branch) action;
throw new StatementBlockException("Should be handled by pattern: "+action);
case ActionConstants.DELETE:
addStatement(new DeleteOperation(stack));
stack.push(new TrueOperation()); // TODO should be the result of the DeleteOperation?
break;
case ActionConstants.DELETE_2:
addStatement(new Delete2Operation(stack));
break;
case ActionConstants.NOT:
op = new NotOperation(stack);
// op = NotOperation.createNotOperation(stack);
stack.push(op);
break;
case ActionConstants.GET_URL:
op = new GetURLOperation(action);
addStatement(op); // ???
// finishThisBlock = true;
break;
case ActionConstants.GET_URL_2:
op = new GetURL2Operation(stack,(GetURL2)action);
addStatement(op); // ???
// finishThisBlock = true;
break;
case ActionConstants.SET_VARIABLE:
op = new SetVariableOperation(context);
addStatement(op);
break;
case ActionConstants.STORE_REGISTER:
op = new StoreRegisterOperation(context, ( StoreRegister ) action);
- addStatement(op);
+ addStatement(op);
// Push the variable into the register instead of the code.
// This used to break constructor definitions, where `__R1 = function(){}` is the constructor
// and `function(){}` had been pushed into the register, instead of `__R1`.
- stack.pop();
- Push pushAction = new Push();
- StackValue stackValue = new StackValue();
- stackValue.setRegisterNumber( (short) ((StoreRegisterOperation) op).getRegisterNumber());
- pushAction.addValue(stackValue);
- handlePush(pushAction, stack);
+ if (stack.peek() instanceof DefineFunction2Operation || stack.peek() instanceof DefineFunctionOperation) { // This might also be valid for many other cases, but lets be as narrow as possible.
+ stack.pop();
+ StackValue stackValue = new StackValue();
+ stackValue.setRegisterNumber( (short) ((StoreRegisterOperation) op).getRegisterNumber());
+ Push pushAction = new Push();
+ pushAction.addValue(stackValue);
+ handlePush(pushAction, stack);
+ }
break;
case ActionConstants.INIT_ARRAY:
stack.push(new InitArrayOperation(stack));
break;
case ActionConstants.INIT_OBJECT:
stack.push(new InitObjectOperation(stack));
break;
case ActionConstants.NEW_OBJECT:
stack.push( new NewObjectOperation(context) );
break;
case ActionConstants.NEW_METHOD:
stack.push( new NewMethodOperation(context) );
break;
case ActionConstants.CALL_FUNCTION:
op = new CallFunctionOperation(stack);
stack.push(op);
break;
case ActionConstants.GO_TO_FRAME:
op = new GotoFrameOperation((GoToFrame)action);
// stack.push(op);
addStatement(op);
break;
case ActionConstants.GO_TO_FRAME_2:
op = new GotoFrame2Operation(stack,(GoToFrame2)action);
// stack.push(op);
addStatement(op);
break;
case ActionConstants.GO_TO_LABEL:
addStatement(new GotoLabelOperation(stack,(GoToLabel)action));
break;
case ActionConstants.TRACE:
addStatement( new TraceOperation(stack));
break;
case ActionConstants.RANDOM_NUMBER:
op = new RandomOperation(stack);
stack.push(op);
break;
case ActionConstants.REMOVE_SPRITE:
addStatement(new RemoveMovieClipOperation(stack));
break;
case ActionConstants.RETURN:
addStatement( new ReturnOperation(stack));
break;
case ActionConstants.SET_PROPERTY:
addStatement( new SetPropertyOperation(stack));
break;
case ActionConstants.START_DRAG:
addStatement(new StartDragOperation(stack));
break;
case ActionConstants.END_DRAG:
addStatement(new SimpleOperation("stopDrag()"));
break;
case ActionConstants.STRING_GREATER:
stack.push(new GreaterOperation(stack));
break;
case ActionConstants.STRING_LESS:
stack.push(new LessOperation(stack));
break;
/*
ActionTargetPath
If the object in the stack is of type MovieClip, the object's target path is pushed on the stack
in dot notation. If the object is not a MovieClip, the result is undefined rather than the
movie clip target path.
ActionTargetPath does the following:
1. Pops the object off the stack.
2. Pushes the target path onto the stack.
*/
case ActionConstants.TARGET_PATH:
stack.push( new TargetPathOperation(stack) );
break;
case ActionConstants.TYPE_OF:
stack.push(new TypeOfOperation(stack));
break;
case ActionConstants.WITH:
addStatement( new WithOperation(stack,context,(With) action));
break;
case ActionConstants.TRY:
addStatement( new TryCatchOperation(stack,context,(Try) action));
break;
case ActionConstants.CAST_OP:
stack.push( new CastOperation(stack) );
break;
case ActionConstants.CLONE_SPRITE:
addStatement( new CloneSpriteOperation(stack));
break;
case ActionConstants.ENUMERATE:
case ActionConstants.ENUMERATE_2:
throw new StatementBlockException("ENUMERATE should be handled by pattern: "+action);
case ActionConstants.EXTENDS:
addStatement( new ExtendsOperation(stack));
break;
case ActionConstants.IMPLEMENTS_OP:
addStatement( new ImplementsOperation(stack));
break;
case ActionConstants.INSTANCE_OF:
stack.push( new InstanceOfOperation(stack) );
break;
//
// Bitwise operations
//
case ActionConstants.BIT_AND:
stack.push( new BitwiseAndOperation(stack) );
break;
case ActionConstants.BIT_OR:
stack.push( new BitwiseOrOperation(stack) );
break;
case ActionConstants.BIT_L_SHIFT:
stack.push( new BitwiseLShiftOperation(stack) );
break;
case ActionConstants.BIT_R_SHIFT:
stack.push( new BitwiseRShiftOperation(stack) );
break;
case ActionConstants.BIT_XOR:
stack.push( new BitwiseXorOperation(stack) );
break;
case ActionConstants.BIT_U_R_SHIFT:
stack.push( new BitwiseURShiftOperation(stack) );
break;
//
// Deprecated since SWF 5
//
case ActionConstants.ASCII_TO_CHAR:
stack.push(new ChrOperation(stack));
break;
case ActionConstants.CHAR_TO_ASCII:
stack.push(new OrdOperation(stack));
break;
case ActionConstants.M_B_ASCII_TO_CHAR:
stack.push(new MbChrOperation(stack));
break;
case ActionConstants.M_B_CHAR_TO_ASCII:
stack.push(new MbOrdOperation(stack));
break;
case ActionConstants.M_B_STRING_EXTRACT:
stack.push(new MbSubstringOperation(stack));
break;
case ActionConstants.M_B_STRING_LENGTH:
stack.push(new MbLengthOperation(stack));
break;
case ActionConstants.SET_TARGET:
case ActionConstants.SET_TARGET_2:
throw new StatementBlockException("Should be handled by pattern: "+action);
// SetTarget setTarget = (SetTarget) action;
// addStatement( new SetTargetOperation(stack,context,setTarget) );
// break;
// SetTarget2 setTarget2 = (SetTarget2) action;
// addStatement( new SetTarget2Operation(stack,context,setTarget2) );
// break;
case ActionConstants.STRING_EQUALS:
stack.push(new EqualsOperation(stack));
break;
case ActionConstants.STRING_EXTRACT:
stack.push(new StringExtractOperation(stack));
break;
case ActionConstants.STRING_LENGTH:
stack.push(new StringLengthOperation(stack));
break;
case ActionConstants.TOGGLE_QUALITY:
addStatement(new SimpleOperation("toggleHighQuality()"));
break;
case ActionConstants.WAIT_FOR_FRAME:
WaitForFrame waitForFrame = (WaitForFrame) action;
additionalActionShift = waitForFrame.getSkipCount();
List<Action> skipActions = new ArrayList<Action>(additionalActionShift);
int actionIndex = moment.getActionIndex();
for (int j=1;j<=additionalActionShift;j++) {
skipActions.add(moment.getActions().get(actionIndex+j));
}
addStatement( new WaitForFrameOperation(stack,context,waitForFrame,skipActions));
break;
case ActionConstants.WAIT_FOR_FRAME_2:
WaitForFrame2 waitForFrame2 = (WaitForFrame2) action;
additionalActionShift = waitForFrame2.getSkipCount();
skipActions = new ArrayList<Action>(additionalActionShift);
actionIndex = moment.getActionIndex();
for (int j=1;j<=additionalActionShift;j++) {
skipActions.add(moment.getActions().get(actionIndex+j));
}
addStatement( new WaitForFrame2Operation(stack,context,waitForFrame2,skipActions));
break;
case ActionConstants.CALL:
addStatement( new CallOperation(stack));
break;
case ActionConstants.END:
// just skip this action
break;
default:
logger.error("UNSUPPORTED ACTION " + action.getCode());
}
return additionalActionShift;
}
protected void addStatement(Operation op) {
if (canAddStatements) {
if (!(op instanceof SkipOperation) || (op instanceof SkipOperation && !((SkipOperation)op).skip())) {
if (op instanceof OperationFactory) {
op = ((OperationFactory)op).getObject();
}
statements.add(op);
postProcessAfterStatement();
}
}
}
private static int modifiedVarIndex = 1;
private static int modifiedRegIndex = 1000;
protected void postProcessAfterStatement() {
Operation statement = statements.get(statements.size()-1);
logger.debug("Checking stack after "+statement);
Stack<Operation> stack = context.getExecStack();
logger.debug("Stack size is "+stack.size());
// First try handle ++x
if (handlePlusPlusX(statement,stack)) {
return;
}
if (stack.isEmpty()) {
return;
}
if (statement instanceof AssignOperation) {
Operation leftOp = ((AssignOperation)statement).getLeftPart();
while (!leftOp.getOperations().isEmpty()) {
leftOp = leftOp.getOperations().get(0);
}
// Try handle x++
if (handleXPlusPlus(statement,stack)) {
return;
}
// Check strings
if (leftOp instanceof StackValue && StackValue.TYPE_STRING == ((StackValue)leftOp).getType()) {
// Retrieve variable name
String variableName = ((StackValue)leftOp).getString();
for (Operation operation : stack) {
// Check if there is use of GetVariable(variableName) in the stack
Operation operationToFind = new GetVariableOperation(new StackValue(variableName));
List<Operation> operationsToCheck = getAllUnderlyingOperations(operation);
boolean stackContainsAssignmentVariable = false;
List<Operation> operationsToChange = new ArrayList<Operation>();
for (Operation underOp : operationsToCheck) {
if (operationToFind.equals(underOp)) {
logger.debug("The stack contains "+operation+" which itself contains "+underOp+". Fixing it...");
stackContainsAssignmentVariable = true;
operationsToChange.add(underOp);
}
}
if (stackContainsAssignmentVariable) {
/*
* x in stack
* change to:
* 1) x__m = x;
* 2) push getVariable(x__m)
*
*/
String newVariableName = variableName+"__m_"+modifiedVarIndex++;
for (Operation chOp : operationsToChange) {
logger.debug("Changing the name of variable "+variableName+" to "+newVariableName);
((GetVariableOperation)chOp).setOp(new StackValue(newVariableName));
}
statements.add(statements.size()-1, new DefineLocalOperation(new StackValue(newVariableName),new GetVariableOperation(new StackValue(variableName))));
}
}
}
// Check registers
if (leftOp instanceof RegisterHandle) {
RegisterHandle registerHandle = (RegisterHandle) leftOp;
int startStackIdx = stack.size()-1;
// get next action
int thisActionIndex = context.getMomentStack().peek().getActionIndex();
int nextActionIndex = thisActionIndex + 1;
if (nextActionIndex < context.getMomentStack().peek().getActions().size()) {
Action nextAction = context.getMomentStack().peek().getActions().get(nextActionIndex);
if (nextAction instanceof Pop) {
// do not check the top of stack as this value will be discarded
startStackIdx--;
}
}
if (startStackIdx == stack.size()-1) {
Action thisAction = context.getMomentStack().peek().getActions().get(thisActionIndex);
if (thisAction instanceof StoreRegister) {
startStackIdx--;
}
}
// find this register handle in stack
for (int stackIdx = startStackIdx; stackIdx>=0; stackIdx--) {
Operation operation = stack.get(stackIdx);
logger.debug("STACK_VAL = "+operation);
List<Operation> operationsToCheck = getAllUnderlyingOperations(operation);
List<Operation> operationsToChange = new ArrayList<Operation>();
boolean stackContainsAssignmentVariable = false;
for (Operation underOp : operationsToCheck) {
if (registerHandle.equals(underOp)) {
logger.debug("The stack contains "+operation+" which itself contains "+underOp+". Fixing it...");
stackContainsAssignmentVariable = true;
operationsToChange.add(underOp);
}
}
if (stackContainsAssignmentVariable) {
/*
* __Rn in stack
* change to:
* 1) __R__m = x;
* 2) push getVariable(x__m)
*
*/
int oldRegisterNumber = registerHandle.getRegisterNumber();
int newRegisterNumber = modifiedRegIndex++;
for (Operation chOp : operationsToChange) {
logger.debug("Changing name of register variable "+oldRegisterNumber+" to "+newRegisterNumber);
((RegisterHandle)chOp).setRegisterNumber(newRegisterNumber);
}
statements.add(statements.size()-1, new DefineLocalOperation(new RegisterHandle(newRegisterNumber),new RegisterHandle(oldRegisterNumber)));
}
}
}
}
}
private boolean handlePlusPlusX(Operation statement, Stack<Operation> stack) {
statement = getRealStatement(statement);
// get all operations except stack top
List<Operation> allStackOperations = new ArrayList<Operation>();
if (!stack.isEmpty()) {
for (int i = 0; i<stack.size()-1; i++) {
allStackOperations.addAll(getAllUnderlyingOperations(stack.get(i)));
}
}
boolean inc = statement instanceof PostIncrementOperation;
boolean dec = statement instanceof PostDecrementOperation;
if (inc || dec) {
Operation incOperation = ((UnaryOperation)statement).getOp();
if (stack.isEmpty() || !allStackOperations.contains(incOperation)) {
List<Operation> registerOperations = context.getRegisters();
if (!registerOperations.isEmpty() && registerOperations.get(0) instanceof RegisterHandle) {
RegisterHandle registerHandle = (RegisterHandle) registerOperations.get(0);
if (registerHandle.getUndelrlyingOp() instanceof SimpleIncrementOperation) {
SimpleIncrementOperation simpleIncrementOperation = (SimpleIncrementOperation) registerHandle.getUndelrlyingOp();
if (incOperation.equals(simpleIncrementOperation.getOp())) {
logger.debug("Simplified to " + (inc ? "++x" : "--x"));
// remove last statement and change register(0)
statements.remove(statements.size()-1);
statements.remove(registerHandle.getStoreRegisterOp());
context.getRegisters().set(0, inc ? new PreIncrementOperation(incOperation) : new PreDecrementOperation(incOperation));
return true;
}
}
}
}
}
return false;
}
protected boolean handleXPlusPlus(Operation statement, Stack<Operation> stack) {
// get top of stack
Operation stackTop = stack.peek();
// get all operations except stack top
List<Operation> allStackOperations = new ArrayList<Operation>();
for (int i = 0; i<stack.size()-1; i++) {
allStackOperations.addAll(getAllUnderlyingOperations(stack.get(i)));
}
boolean inc = statement instanceof AssignIncrementOperation;
boolean dec = statement instanceof AssignDecrementOperation;
if (inc || dec) {
Operation incOperation = ((UnaryOperation)statement).getOp();
if (!allStackOperations.contains(incOperation)) {
if (stackTop.equals(incOperation)) {
logger.debug("Simplified to "+ (inc ? "x++" : "x--"));
// remove last statement and change top of stack
statements.remove(statements.size()-1);
stack.pop();
stack.push(inc ? new PostIncrementOperation(incOperation) : new PostDecrementOperation(incOperation));
return true;
}
// check registers
// List<Operation> registerOperations = context.getRegisters();
// if (!registerOperations.isEmpty() && registerOperations.get(0) instanceof RegisterHandle) {
// RegisterHandle registerHandle = (RegisterHandle) registerOperations.get(0);
// if (registerHandle.getUndelrlyingOp() instanceof SimpleIncrementOperation) {
// SimpleIncrementOperation simpleIncrementOperation = (SimpleIncrementOperation) registerHandle.getUndelrlyingOp();
// if (incOperation.equals(simpleIncrementOperation.getOp())) {
// logger.debug("Simplified to ++x");
// // remove last statement and change register(0)
// statements.remove(statements.size()-1);
// statements.remove(registerHandle.getStoreRegisterOp());
// context.getRegisters().set(0, new PreIncrementOperation(incOperation));
// return true;
// }
// }
// }
}
int getVariableCount = 0;
int getVariableIdx = 0;
Operation getVariableOp = null;
for (int stackIdx = 0; stackIdx < stack.size() ; stackIdx++) {
Operation stackOperation = stack.get(stackIdx);
if (stackOperation instanceof GetVariableOperation) {
GetVariableOperation variableOp = (GetVariableOperation) stackOperation;
if (incOperation.equals(variableOp)) {
getVariableCount++;
getVariableIdx = stackIdx;
getVariableOp = variableOp;
}
}
}
if (getVariableCount == 1) {
logger.debug("One getVariable found. Replacing it with x++ and removing last statement.");
statements.remove(statements.size()-1);
stack.set(getVariableIdx, inc ? new PostIncrementOperation(getVariableOp) : new PostDecrementOperation(getVariableOp));
return true;
}
}
return false;
}
protected List<Operation> getAllUnderlyingOperations(Operation operation) {
List<Operation> underlyingOperations = new ArrayList<Operation>();
underlyingOperations.add(operation);
for (Operation op : operation.getOperations()) {
underlyingOperations.addAll(getAllUnderlyingOperations(op));
}
return underlyingOperations;
}
protected void handlePush(Push action, Stack<Operation> stack) {
List<StackValue> stackValues = action.getValues();
for (StackValue stackValue : stackValues) {
switch (stackValue.getType()) {
case StackValue.TYPE_STRING :
case StackValue.TYPE_FLOAT :
case StackValue.TYPE_NULL :
case StackValue.TYPE_UNDEFINED :
case StackValue.TYPE_BOOLEAN :
case StackValue.TYPE_DOUBLE :
case StackValue.TYPE_INTEGER :
logger.debug("STACK, pushing: " + stackValue);
stack.push(stackValue);
break;
case StackValue.TYPE_CONSTANT_8 :
int index8 = stackValue.getConstant8();
Operation constant8 = (context.getConstants().size() > index8) ? new StackValue(context.getConstants().get(index8)) : new UndefinedStackValue();
logger.debug("STACK, pushing: " + stackValue+" => " + constant8);
stack.push(constant8);
break;
case StackValue.TYPE_CONSTANT_16 :
int index16 = stackValue.getConstant16();
Operation constant16 = (context.getConstants().size() > index16) ? new StackValue(context.getConstants().get(index16)) : new UndefinedStackValue();
logger.debug("STACK, pushing: " + stackValue+" => " + constant16);
stack.push(constant16);
break;
case StackValue.TYPE_REGISTER :
// logger.debug("V:"+stackValue);
Operation registerValue;
if (context.getRegisters().size()>stackValue.getRegisterNumber()) {
registerValue = context.getRegisters().get(stackValue.getRegisterNumber());
if (registerValue == null) {
registerValue = new NullStackValue();
}
} else {
logger.error("Reference to register #"+stackValue.getRegisterNumber()+", but registers size is "+context.getRegisters().size()+". Pushing undefined. (Fixed by breaking out here, to be verified!!!) This error causes a subsequent error POPing");
registerValue = new UndefinedStackValue();
// break;
}
logger.debug("STACK, pushing: " + stackValue+" => "+registerValue);
stack.push(registerValue);
// Let's only do this for "simple" stack values
// Without it we would get all DefinedFunction2 parameters wrapped in an `eval`.
if (registerValue instanceof StackValue) {
GetVariableOperation item = new GetVariableOperation(stack);
logger.debug("STACK, pushing: " + item);
stack.push(item); // This treats everything that is in a register as a variable, works in all tests I wrote, but that's all the proof I have (wk).
}
break;
default:
logger.error("Unknown stack value type = "+stackValue.getType());
}
}
}
private void postProcessStatements() {
postProcessIncrements();
postProcessFor();
}
private void postProcessFor() {
// TODO Check "for" statements
for (int j=0; j<statements.size(); j++) {
Operation statement = statements.get(j);
if (statement.getClass().equals(WhileOperation.class) && j>0) {
WhileOperation whileOperation = (WhileOperation)statement;
// get condition
Operation condition = whileOperation.getCondition();
// get previous statement
Operation prevStatement = statements.get(j-1);
// get last while operation
if (!whileOperation.getInlineOperations().isEmpty()) {
Operation lastWhileOp = whileOperation.getInlineOperations().get(whileOperation.getInlineOperations().size()-1);
}
}
}
}
private void postProcessIncrements() {
for (int j=0; j<statements.size(); j++) {
Operation statement = statements.get(j);
}
}
private static Operation getRealStatement(Operation statement) {
return (statement instanceof OperationFactory) ? ((OperationFactory)statement).getObject() : statement;
}
public List<Operation> getOperations() {
return statements;
}
public void setExecutionContext(ExecutionContext context) {
this.context = context;
}
}
| false | true | private int handleByActionCode(Action action) throws StatementBlockException {
int additionalActionShift = 0;
Stack<Operation> stack = context.getExecStack();
Operation op;
// int actionIndexShift = 1; // default
switch (action.getCode()) {
case ActionConstants.CONSTANT_POOL:
ConstantPool constantPool = (ConstantPool)action;
context.getConstants().addAll(constantPool.getConstants());
logger.debug("Loaded constants, length: "+context.getConstants().size() + ", values: " + context.getConstants());
break;
case ActionConstants.PUSH :
handlePush((Push)action,stack);
break;
case ActionConstants.PUSH_DUPLICATE :
stack.push(stack.peek());
break;
case ActionConstants.POP :
if (stack.isEmpty()) {
logger.error("Empty stack and POP() found");
break;
} else {
boolean writePop = stack.peek() instanceof DualUse;
if (writePop && !statements.isEmpty()) {
// check last statement
// if it is StoreRegister than do NOT write this POP()
Operation lastStatement = statements.get(statements.size()-1);
if (lastStatement instanceof StoreRegisterOperation) {
// writePop = lastStatement.getClass().getAnnotation(DoNotWritePop.class) == null;
writePop = ((StoreRegisterOperation) lastStatement).getOp() != ((ExecutionStack) stack).peek();
}
}
if (writePop) {
logger.debug("Writing POP()");
((DualUse)stack.peek()).markAsStatement();
addStatement(stack.pop());
} else {
logger.debug("Skipping POP()");
stack.pop();
}
}
break;
case ActionConstants.STACK_SWAP:
Operation item1 = stack.pop();
Operation item2 = stack.pop();
stack.push(item1);
stack.push(item2);
break;
case ActionConstants.DEFINE_LOCAL :
op = new DefineLocalOperation(stack);
addStatement(op);
break;
case ActionConstants.DEFINE_LOCAL_2 :
op = new DefineLocal2Operation(stack);
addStatement(op);
break;
//
// TODO: group simple operations
//
case ActionConstants.PREVIOUS_FRAME :
addStatement(new SimpleOperation("prevFrame()"));
break;
case ActionConstants.NEXT_FRAME:
stack.push(new SimpleOperation("nextFrame()"));
break;
case ActionConstants.PLAY:
if (!statements.isEmpty() && (statements.get(statements.size()-1) instanceof ActionAware)) {
((ActionAware)statements.get(statements.size()-1)).setAction(GotoFrameOperation.ACTION_PLAY);
} else {
addStatement(new SimpleOperation("play()"));
}
break;
case ActionConstants.STOP :
addStatement(new SimpleOperation("stop()"));
break;
case ActionConstants.STOP_SOUNDS:
addStatement(new SimpleOperation("stopAllSounds()"));
break;
case ActionConstants.GET_TIME:
stack.push(new SimpleFunctionOperation("getTimer()"));
break;
case ActionConstants.THROW:
addStatement(new ThrowOperation(stack));
break;
//
// Arithmetic operations
//
case ActionConstants.ADD:
case ActionConstants.ADD_2:
stack.push(new AddOperation(stack,action));
break;
case ActionConstants.SUBTRACT:
stack.push(new SubtractOperation(stack,action));
break;
case ActionConstants.DIVIDE:
stack.push(new DivideOperation(stack,action));
break;
case ActionConstants.MULTIPLY:
stack.push(new MultiplyOperation(stack,action));
break;
case ActionConstants.MODULO:
op = new ModuloOperation(stack,action);
stack.push(op);
break;
case ActionConstants.INCREMENT:
op = new SimpleIncrementOperation(stack);
stack.push(op);
break;
case ActionConstants.DECREMENT:
op = new SimpleDecrementOperation(stack);
stack.push(op);
break;
case ActionConstants.STRING_ADD:
stack.push(new StringAddOperation(stack));
break;
//
// Boolean operations
//
case ActionConstants.LESS:
case ActionConstants.LESS_2:
op = new LessOperation(stack);
stack.push(op);
break;
case ActionConstants.EQUALS:
case ActionConstants.EQUALS_2:
stack.push(new EqualsOperation(stack));
break;
case ActionConstants.STRICT_EQUALS:
stack.push(new StrictEqualsOperation(stack));
break;
case ActionConstants.GREATER:
op = new GreaterOperation(stack);
stack.push(op);
break;
case ActionConstants.AND:
stack.push(new AndOperation(stack));
break;
case ActionConstants.OR:
stack.push(new OrOperation(stack));
break;
case ActionConstants.GET_VARIABLE:
op = new GetVariableOperation(stack);
stack.push(op);
break;
case ActionConstants.CALL_METHOD:
stack.push(new CallMethodOperation(stack));
break;
case ActionConstants.SET_MEMBER:
op = new SetMemberOperation(stack);
addStatement(op);
break;
case ActionConstants.DEFINE_FUNCTION:
DefineFunction defineFunction = (DefineFunction)action;
op = new DefineFunctionOperation(stack,context,defineFunction);
if (StringUtils.hasText(defineFunction.getName())) {
addStatement(op); // function as statement
} else {
stack.push(op); // function as operation, put it to stack
}
break;
case ActionConstants.DEFINE_FUNCTION_2:
DefineFunction2 defineFunction2 = (DefineFunction2)action;
op = new DefineFunction2Operation(stack,defineFunction2,context);
if (StringUtils.hasText(defineFunction2.getName())) {
addStatement(op); // function as statement
} else {
stack.push(op); // function as operation, put it to stack
}
break;
case ActionConstants.GET_MEMBER:
stack.push( new GetMemberOperation(stack) );
break;
case ActionConstants.GET_PROPERTY:
stack.push( new GetPropertyOperation(stack) );
break;
//
// Type convertion funcs
//
case ActionConstants.TO_INTEGER:
stack.push(new ToIntegerOperation(stack));
break;
case ActionConstants.TO_NUMBER:
stack.push(new ToNumberOperation(stack));
break;
case ActionConstants.TO_STRING:
stack.push(new ToStringOperation(stack));
break;
// TODO: Check LABEL_OUT
case ActionConstants.JUMP:
case ActionConstants.IF:
Branch branch = (Branch) action;
throw new StatementBlockException("Should be handled by pattern: "+action);
case ActionConstants.DELETE:
addStatement(new DeleteOperation(stack));
stack.push(new TrueOperation()); // TODO should be the result of the DeleteOperation?
break;
case ActionConstants.DELETE_2:
addStatement(new Delete2Operation(stack));
break;
case ActionConstants.NOT:
op = new NotOperation(stack);
// op = NotOperation.createNotOperation(stack);
stack.push(op);
break;
case ActionConstants.GET_URL:
op = new GetURLOperation(action);
addStatement(op); // ???
// finishThisBlock = true;
break;
case ActionConstants.GET_URL_2:
op = new GetURL2Operation(stack,(GetURL2)action);
addStatement(op); // ???
// finishThisBlock = true;
break;
case ActionConstants.SET_VARIABLE:
op = new SetVariableOperation(context);
addStatement(op);
break;
case ActionConstants.STORE_REGISTER:
op = new StoreRegisterOperation(context, ( StoreRegister ) action);
addStatement(op);
// Push the variable into the register instead of the code.
// This used to break constructor definitions, where `__R1 = function(){}` is the constructor
// and `function(){}` had been pushed into the register, instead of `__R1`.
stack.pop();
Push pushAction = new Push();
StackValue stackValue = new StackValue();
stackValue.setRegisterNumber( (short) ((StoreRegisterOperation) op).getRegisterNumber());
pushAction.addValue(stackValue);
handlePush(pushAction, stack);
break;
case ActionConstants.INIT_ARRAY:
stack.push(new InitArrayOperation(stack));
break;
case ActionConstants.INIT_OBJECT:
stack.push(new InitObjectOperation(stack));
break;
case ActionConstants.NEW_OBJECT:
stack.push( new NewObjectOperation(context) );
break;
case ActionConstants.NEW_METHOD:
stack.push( new NewMethodOperation(context) );
break;
case ActionConstants.CALL_FUNCTION:
op = new CallFunctionOperation(stack);
stack.push(op);
break;
case ActionConstants.GO_TO_FRAME:
op = new GotoFrameOperation((GoToFrame)action);
// stack.push(op);
addStatement(op);
break;
case ActionConstants.GO_TO_FRAME_2:
op = new GotoFrame2Operation(stack,(GoToFrame2)action);
// stack.push(op);
addStatement(op);
break;
case ActionConstants.GO_TO_LABEL:
addStatement(new GotoLabelOperation(stack,(GoToLabel)action));
break;
case ActionConstants.TRACE:
addStatement( new TraceOperation(stack));
break;
case ActionConstants.RANDOM_NUMBER:
op = new RandomOperation(stack);
stack.push(op);
break;
case ActionConstants.REMOVE_SPRITE:
addStatement(new RemoveMovieClipOperation(stack));
break;
case ActionConstants.RETURN:
addStatement( new ReturnOperation(stack));
break;
case ActionConstants.SET_PROPERTY:
addStatement( new SetPropertyOperation(stack));
break;
case ActionConstants.START_DRAG:
addStatement(new StartDragOperation(stack));
break;
case ActionConstants.END_DRAG:
addStatement(new SimpleOperation("stopDrag()"));
break;
case ActionConstants.STRING_GREATER:
stack.push(new GreaterOperation(stack));
break;
case ActionConstants.STRING_LESS:
stack.push(new LessOperation(stack));
break;
/*
ActionTargetPath
If the object in the stack is of type MovieClip, the object's target path is pushed on the stack
in dot notation. If the object is not a MovieClip, the result is undefined rather than the
movie clip target path.
ActionTargetPath does the following:
1. Pops the object off the stack.
2. Pushes the target path onto the stack.
*/
case ActionConstants.TARGET_PATH:
stack.push( new TargetPathOperation(stack) );
break;
case ActionConstants.TYPE_OF:
stack.push(new TypeOfOperation(stack));
break;
case ActionConstants.WITH:
addStatement( new WithOperation(stack,context,(With) action));
break;
case ActionConstants.TRY:
addStatement( new TryCatchOperation(stack,context,(Try) action));
break;
case ActionConstants.CAST_OP:
stack.push( new CastOperation(stack) );
break;
case ActionConstants.CLONE_SPRITE:
addStatement( new CloneSpriteOperation(stack));
break;
case ActionConstants.ENUMERATE:
case ActionConstants.ENUMERATE_2:
throw new StatementBlockException("ENUMERATE should be handled by pattern: "+action);
case ActionConstants.EXTENDS:
addStatement( new ExtendsOperation(stack));
break;
case ActionConstants.IMPLEMENTS_OP:
addStatement( new ImplementsOperation(stack));
break;
case ActionConstants.INSTANCE_OF:
stack.push( new InstanceOfOperation(stack) );
break;
//
// Bitwise operations
//
case ActionConstants.BIT_AND:
stack.push( new BitwiseAndOperation(stack) );
break;
case ActionConstants.BIT_OR:
stack.push( new BitwiseOrOperation(stack) );
break;
case ActionConstants.BIT_L_SHIFT:
stack.push( new BitwiseLShiftOperation(stack) );
break;
case ActionConstants.BIT_R_SHIFT:
stack.push( new BitwiseRShiftOperation(stack) );
break;
case ActionConstants.BIT_XOR:
stack.push( new BitwiseXorOperation(stack) );
break;
case ActionConstants.BIT_U_R_SHIFT:
stack.push( new BitwiseURShiftOperation(stack) );
break;
//
// Deprecated since SWF 5
//
case ActionConstants.ASCII_TO_CHAR:
stack.push(new ChrOperation(stack));
break;
case ActionConstants.CHAR_TO_ASCII:
stack.push(new OrdOperation(stack));
break;
case ActionConstants.M_B_ASCII_TO_CHAR:
stack.push(new MbChrOperation(stack));
break;
case ActionConstants.M_B_CHAR_TO_ASCII:
stack.push(new MbOrdOperation(stack));
break;
case ActionConstants.M_B_STRING_EXTRACT:
stack.push(new MbSubstringOperation(stack));
break;
case ActionConstants.M_B_STRING_LENGTH:
stack.push(new MbLengthOperation(stack));
break;
case ActionConstants.SET_TARGET:
case ActionConstants.SET_TARGET_2:
throw new StatementBlockException("Should be handled by pattern: "+action);
// SetTarget setTarget = (SetTarget) action;
// addStatement( new SetTargetOperation(stack,context,setTarget) );
// break;
// SetTarget2 setTarget2 = (SetTarget2) action;
// addStatement( new SetTarget2Operation(stack,context,setTarget2) );
// break;
case ActionConstants.STRING_EQUALS:
stack.push(new EqualsOperation(stack));
break;
case ActionConstants.STRING_EXTRACT:
stack.push(new StringExtractOperation(stack));
break;
case ActionConstants.STRING_LENGTH:
stack.push(new StringLengthOperation(stack));
break;
case ActionConstants.TOGGLE_QUALITY:
addStatement(new SimpleOperation("toggleHighQuality()"));
break;
case ActionConstants.WAIT_FOR_FRAME:
WaitForFrame waitForFrame = (WaitForFrame) action;
additionalActionShift = waitForFrame.getSkipCount();
List<Action> skipActions = new ArrayList<Action>(additionalActionShift);
int actionIndex = moment.getActionIndex();
for (int j=1;j<=additionalActionShift;j++) {
skipActions.add(moment.getActions().get(actionIndex+j));
}
addStatement( new WaitForFrameOperation(stack,context,waitForFrame,skipActions));
break;
case ActionConstants.WAIT_FOR_FRAME_2:
WaitForFrame2 waitForFrame2 = (WaitForFrame2) action;
additionalActionShift = waitForFrame2.getSkipCount();
skipActions = new ArrayList<Action>(additionalActionShift);
actionIndex = moment.getActionIndex();
for (int j=1;j<=additionalActionShift;j++) {
skipActions.add(moment.getActions().get(actionIndex+j));
}
addStatement( new WaitForFrame2Operation(stack,context,waitForFrame2,skipActions));
break;
case ActionConstants.CALL:
addStatement( new CallOperation(stack));
break;
case ActionConstants.END:
// just skip this action
break;
default:
logger.error("UNSUPPORTED ACTION " + action.getCode());
}
return additionalActionShift;
}
| private int handleByActionCode(Action action) throws StatementBlockException {
int additionalActionShift = 0;
Stack<Operation> stack = context.getExecStack();
Operation op;
// int actionIndexShift = 1; // default
switch (action.getCode()) {
case ActionConstants.CONSTANT_POOL:
ConstantPool constantPool = (ConstantPool)action;
context.getConstants().addAll(constantPool.getConstants());
logger.debug("Loaded constants, length: "+context.getConstants().size() + ", values: " + context.getConstants());
break;
case ActionConstants.PUSH :
handlePush((Push)action,stack);
break;
case ActionConstants.PUSH_DUPLICATE :
stack.push(stack.peek());
break;
case ActionConstants.POP :
if (stack.isEmpty()) {
logger.error("Empty stack and POP() found");
break;
} else {
boolean writePop = stack.peek() instanceof DualUse;
if (writePop && !statements.isEmpty()) {
// check last statement
// if it is StoreRegister than do NOT write this POP()
Operation lastStatement = statements.get(statements.size()-1);
if (lastStatement instanceof StoreRegisterOperation) {
// writePop = lastStatement.getClass().getAnnotation(DoNotWritePop.class) == null;
writePop = ((StoreRegisterOperation) lastStatement).getOp() != ((ExecutionStack) stack).peek();
}
}
if (writePop) {
logger.debug("Writing POP()");
((DualUse)stack.peek()).markAsStatement();
addStatement(stack.pop());
} else {
logger.debug("Skipping POP()");
stack.pop();
}
}
break;
case ActionConstants.STACK_SWAP:
Operation item1 = stack.pop();
Operation item2 = stack.pop();
stack.push(item1);
stack.push(item2);
break;
case ActionConstants.DEFINE_LOCAL :
op = new DefineLocalOperation(stack);
addStatement(op);
break;
case ActionConstants.DEFINE_LOCAL_2 :
op = new DefineLocal2Operation(stack);
addStatement(op);
break;
//
// TODO: group simple operations
//
case ActionConstants.PREVIOUS_FRAME :
addStatement(new SimpleOperation("prevFrame()"));
break;
case ActionConstants.NEXT_FRAME:
stack.push(new SimpleOperation("nextFrame()"));
break;
case ActionConstants.PLAY:
if (!statements.isEmpty() && (statements.get(statements.size()-1) instanceof ActionAware)) {
((ActionAware)statements.get(statements.size()-1)).setAction(GotoFrameOperation.ACTION_PLAY);
} else {
addStatement(new SimpleOperation("play()"));
}
break;
case ActionConstants.STOP :
addStatement(new SimpleOperation("stop()"));
break;
case ActionConstants.STOP_SOUNDS:
addStatement(new SimpleOperation("stopAllSounds()"));
break;
case ActionConstants.GET_TIME:
stack.push(new SimpleFunctionOperation("getTimer()"));
break;
case ActionConstants.THROW:
addStatement(new ThrowOperation(stack));
break;
//
// Arithmetic operations
//
case ActionConstants.ADD:
case ActionConstants.ADD_2:
stack.push(new AddOperation(stack,action));
break;
case ActionConstants.SUBTRACT:
stack.push(new SubtractOperation(stack,action));
break;
case ActionConstants.DIVIDE:
stack.push(new DivideOperation(stack,action));
break;
case ActionConstants.MULTIPLY:
stack.push(new MultiplyOperation(stack,action));
break;
case ActionConstants.MODULO:
op = new ModuloOperation(stack,action);
stack.push(op);
break;
case ActionConstants.INCREMENT:
op = new SimpleIncrementOperation(stack);
stack.push(op);
break;
case ActionConstants.DECREMENT:
op = new SimpleDecrementOperation(stack);
stack.push(op);
break;
case ActionConstants.STRING_ADD:
stack.push(new StringAddOperation(stack));
break;
//
// Boolean operations
//
case ActionConstants.LESS:
case ActionConstants.LESS_2:
op = new LessOperation(stack);
stack.push(op);
break;
case ActionConstants.EQUALS:
case ActionConstants.EQUALS_2:
stack.push(new EqualsOperation(stack));
break;
case ActionConstants.STRICT_EQUALS:
stack.push(new StrictEqualsOperation(stack));
break;
case ActionConstants.GREATER:
op = new GreaterOperation(stack);
stack.push(op);
break;
case ActionConstants.AND:
stack.push(new AndOperation(stack));
break;
case ActionConstants.OR:
stack.push(new OrOperation(stack));
break;
case ActionConstants.GET_VARIABLE:
op = new GetVariableOperation(stack);
stack.push(op);
break;
case ActionConstants.CALL_METHOD:
stack.push(new CallMethodOperation(stack));
break;
case ActionConstants.SET_MEMBER:
op = new SetMemberOperation(stack);
addStatement(op);
break;
case ActionConstants.DEFINE_FUNCTION:
DefineFunction defineFunction = (DefineFunction)action;
op = new DefineFunctionOperation(stack,context,defineFunction);
if (StringUtils.hasText(defineFunction.getName())) {
addStatement(op); // function as statement
} else {
stack.push(op); // function as operation, put it to stack
}
break;
case ActionConstants.DEFINE_FUNCTION_2:
DefineFunction2 defineFunction2 = (DefineFunction2)action;
op = new DefineFunction2Operation(stack,defineFunction2,context);
if (StringUtils.hasText(defineFunction2.getName())) {
addStatement(op); // function as statement
} else {
stack.push(op); // function as operation, put it to stack
}
break;
case ActionConstants.GET_MEMBER:
stack.push( new GetMemberOperation(stack) );
break;
case ActionConstants.GET_PROPERTY:
stack.push( new GetPropertyOperation(stack) );
break;
//
// Type convertion funcs
//
case ActionConstants.TO_INTEGER:
stack.push(new ToIntegerOperation(stack));
break;
case ActionConstants.TO_NUMBER:
stack.push(new ToNumberOperation(stack));
break;
case ActionConstants.TO_STRING:
stack.push(new ToStringOperation(stack));
break;
// TODO: Check LABEL_OUT
case ActionConstants.JUMP:
case ActionConstants.IF:
Branch branch = (Branch) action;
throw new StatementBlockException("Should be handled by pattern: "+action);
case ActionConstants.DELETE:
addStatement(new DeleteOperation(stack));
stack.push(new TrueOperation()); // TODO should be the result of the DeleteOperation?
break;
case ActionConstants.DELETE_2:
addStatement(new Delete2Operation(stack));
break;
case ActionConstants.NOT:
op = new NotOperation(stack);
// op = NotOperation.createNotOperation(stack);
stack.push(op);
break;
case ActionConstants.GET_URL:
op = new GetURLOperation(action);
addStatement(op); // ???
// finishThisBlock = true;
break;
case ActionConstants.GET_URL_2:
op = new GetURL2Operation(stack,(GetURL2)action);
addStatement(op); // ???
// finishThisBlock = true;
break;
case ActionConstants.SET_VARIABLE:
op = new SetVariableOperation(context);
addStatement(op);
break;
case ActionConstants.STORE_REGISTER:
op = new StoreRegisterOperation(context, ( StoreRegister ) action);
addStatement(op);
// Push the variable into the register instead of the code.
// This used to break constructor definitions, where `__R1 = function(){}` is the constructor
// and `function(){}` had been pushed into the register, instead of `__R1`.
if (stack.peek() instanceof DefineFunction2Operation || stack.peek() instanceof DefineFunctionOperation) { // This might also be valid for many other cases, but lets be as narrow as possible.
stack.pop();
StackValue stackValue = new StackValue();
stackValue.setRegisterNumber( (short) ((StoreRegisterOperation) op).getRegisterNumber());
Push pushAction = new Push();
pushAction.addValue(stackValue);
handlePush(pushAction, stack);
}
break;
case ActionConstants.INIT_ARRAY:
stack.push(new InitArrayOperation(stack));
break;
case ActionConstants.INIT_OBJECT:
stack.push(new InitObjectOperation(stack));
break;
case ActionConstants.NEW_OBJECT:
stack.push( new NewObjectOperation(context) );
break;
case ActionConstants.NEW_METHOD:
stack.push( new NewMethodOperation(context) );
break;
case ActionConstants.CALL_FUNCTION:
op = new CallFunctionOperation(stack);
stack.push(op);
break;
case ActionConstants.GO_TO_FRAME:
op = new GotoFrameOperation((GoToFrame)action);
// stack.push(op);
addStatement(op);
break;
case ActionConstants.GO_TO_FRAME_2:
op = new GotoFrame2Operation(stack,(GoToFrame2)action);
// stack.push(op);
addStatement(op);
break;
case ActionConstants.GO_TO_LABEL:
addStatement(new GotoLabelOperation(stack,(GoToLabel)action));
break;
case ActionConstants.TRACE:
addStatement( new TraceOperation(stack));
break;
case ActionConstants.RANDOM_NUMBER:
op = new RandomOperation(stack);
stack.push(op);
break;
case ActionConstants.REMOVE_SPRITE:
addStatement(new RemoveMovieClipOperation(stack));
break;
case ActionConstants.RETURN:
addStatement( new ReturnOperation(stack));
break;
case ActionConstants.SET_PROPERTY:
addStatement( new SetPropertyOperation(stack));
break;
case ActionConstants.START_DRAG:
addStatement(new StartDragOperation(stack));
break;
case ActionConstants.END_DRAG:
addStatement(new SimpleOperation("stopDrag()"));
break;
case ActionConstants.STRING_GREATER:
stack.push(new GreaterOperation(stack));
break;
case ActionConstants.STRING_LESS:
stack.push(new LessOperation(stack));
break;
/*
ActionTargetPath
If the object in the stack is of type MovieClip, the object's target path is pushed on the stack
in dot notation. If the object is not a MovieClip, the result is undefined rather than the
movie clip target path.
ActionTargetPath does the following:
1. Pops the object off the stack.
2. Pushes the target path onto the stack.
*/
case ActionConstants.TARGET_PATH:
stack.push( new TargetPathOperation(stack) );
break;
case ActionConstants.TYPE_OF:
stack.push(new TypeOfOperation(stack));
break;
case ActionConstants.WITH:
addStatement( new WithOperation(stack,context,(With) action));
break;
case ActionConstants.TRY:
addStatement( new TryCatchOperation(stack,context,(Try) action));
break;
case ActionConstants.CAST_OP:
stack.push( new CastOperation(stack) );
break;
case ActionConstants.CLONE_SPRITE:
addStatement( new CloneSpriteOperation(stack));
break;
case ActionConstants.ENUMERATE:
case ActionConstants.ENUMERATE_2:
throw new StatementBlockException("ENUMERATE should be handled by pattern: "+action);
case ActionConstants.EXTENDS:
addStatement( new ExtendsOperation(stack));
break;
case ActionConstants.IMPLEMENTS_OP:
addStatement( new ImplementsOperation(stack));
break;
case ActionConstants.INSTANCE_OF:
stack.push( new InstanceOfOperation(stack) );
break;
//
// Bitwise operations
//
case ActionConstants.BIT_AND:
stack.push( new BitwiseAndOperation(stack) );
break;
case ActionConstants.BIT_OR:
stack.push( new BitwiseOrOperation(stack) );
break;
case ActionConstants.BIT_L_SHIFT:
stack.push( new BitwiseLShiftOperation(stack) );
break;
case ActionConstants.BIT_R_SHIFT:
stack.push( new BitwiseRShiftOperation(stack) );
break;
case ActionConstants.BIT_XOR:
stack.push( new BitwiseXorOperation(stack) );
break;
case ActionConstants.BIT_U_R_SHIFT:
stack.push( new BitwiseURShiftOperation(stack) );
break;
//
// Deprecated since SWF 5
//
case ActionConstants.ASCII_TO_CHAR:
stack.push(new ChrOperation(stack));
break;
case ActionConstants.CHAR_TO_ASCII:
stack.push(new OrdOperation(stack));
break;
case ActionConstants.M_B_ASCII_TO_CHAR:
stack.push(new MbChrOperation(stack));
break;
case ActionConstants.M_B_CHAR_TO_ASCII:
stack.push(new MbOrdOperation(stack));
break;
case ActionConstants.M_B_STRING_EXTRACT:
stack.push(new MbSubstringOperation(stack));
break;
case ActionConstants.M_B_STRING_LENGTH:
stack.push(new MbLengthOperation(stack));
break;
case ActionConstants.SET_TARGET:
case ActionConstants.SET_TARGET_2:
throw new StatementBlockException("Should be handled by pattern: "+action);
// SetTarget setTarget = (SetTarget) action;
// addStatement( new SetTargetOperation(stack,context,setTarget) );
// break;
// SetTarget2 setTarget2 = (SetTarget2) action;
// addStatement( new SetTarget2Operation(stack,context,setTarget2) );
// break;
case ActionConstants.STRING_EQUALS:
stack.push(new EqualsOperation(stack));
break;
case ActionConstants.STRING_EXTRACT:
stack.push(new StringExtractOperation(stack));
break;
case ActionConstants.STRING_LENGTH:
stack.push(new StringLengthOperation(stack));
break;
case ActionConstants.TOGGLE_QUALITY:
addStatement(new SimpleOperation("toggleHighQuality()"));
break;
case ActionConstants.WAIT_FOR_FRAME:
WaitForFrame waitForFrame = (WaitForFrame) action;
additionalActionShift = waitForFrame.getSkipCount();
List<Action> skipActions = new ArrayList<Action>(additionalActionShift);
int actionIndex = moment.getActionIndex();
for (int j=1;j<=additionalActionShift;j++) {
skipActions.add(moment.getActions().get(actionIndex+j));
}
addStatement( new WaitForFrameOperation(stack,context,waitForFrame,skipActions));
break;
case ActionConstants.WAIT_FOR_FRAME_2:
WaitForFrame2 waitForFrame2 = (WaitForFrame2) action;
additionalActionShift = waitForFrame2.getSkipCount();
skipActions = new ArrayList<Action>(additionalActionShift);
actionIndex = moment.getActionIndex();
for (int j=1;j<=additionalActionShift;j++) {
skipActions.add(moment.getActions().get(actionIndex+j));
}
addStatement( new WaitForFrame2Operation(stack,context,waitForFrame2,skipActions));
break;
case ActionConstants.CALL:
addStatement( new CallOperation(stack));
break;
case ActionConstants.END:
// just skip this action
break;
default:
logger.error("UNSUPPORTED ACTION " + action.getCode());
}
return additionalActionShift;
}
|
diff --git a/ShoppingList/src/org/openintents/shopping/provider/ShoppingProvider.java b/ShoppingList/src/org/openintents/shopping/provider/ShoppingProvider.java
index 44551aa..5367f4e 100644
--- a/ShoppingList/src/org/openintents/shopping/provider/ShoppingProvider.java
+++ b/ShoppingList/src/org/openintents/shopping/provider/ShoppingProvider.java
@@ -1,1158 +1,1161 @@
/*
* Copyright (C) 2007-2011 OpenIntents.org
*
* 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.openintents.shopping.provider;
import java.util.HashMap;
import org.openintents.intents.ProviderIntents;
import org.openintents.intents.ProviderUtils;
import org.openintents.shopping.LogConstants;
import org.openintents.shopping.R;
import org.openintents.shopping.library.provider.ShoppingContract;
import org.openintents.shopping.library.provider.ShoppingContract.Contains;
import org.openintents.shopping.library.provider.ShoppingContract.ContainsFull;
import org.openintents.shopping.library.provider.ShoppingContract.ItemStores;
import org.openintents.shopping.library.provider.ShoppingContract.Items;
import org.openintents.shopping.library.provider.ShoppingContract.Lists;
import org.openintents.shopping.library.provider.ShoppingContract.Status;
import org.openintents.shopping.library.provider.ShoppingContract.Stores;
import org.openintents.shopping.library.provider.ShoppingContract.Units;
import org.openintents.shopping.ui.PreferenceActivity;
import org.openintents.shopping.ui.ShoppingActivity;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
* Provides access to a database of shopping items and shopping lists.
*
* ShoppingProvider maintains the following tables:
* * items: items you want to buy
* * lists: shopping lists ("My shopping list", "Bob's shopping list")
* * contains: which item/list/(recipe) is contained in which shopping list.
* * stores:
* * itemstores: (which store carries which item)
*/
public class ShoppingProvider extends ContentProvider {
private ShoppingDatabase mOpenHelper;
static final String TAG = "ShoppingProvider";
private static final boolean debug = false || LogConstants.debug;
private static HashMap<String, String> ITEMS_PROJECTION_MAP;
private static HashMap<String, String> LISTS_PROJECTION_MAP;
private static HashMap<String, String> CONTAINS_PROJECTION_MAP;
private static HashMap<String, String> CONTAINS_FULL_PROJECTION_MAP;
private static HashMap<String, String> CONTAINS_FULL_CHEAPEST_PROJECTION_MAP;
private static HashMap<String, String> STORES_PROJECTION_MAP;
private static HashMap<String, String> ITEMSTORES_PROJECTION_MAP;
private static HashMap<String, String> NOTES_PROJECTION_MAP;
private static HashMap<String, String> UNITS_PROJECTION_MAP;
private static HashMap<String, String> SUBTOTALS_PROJECTION_MAP;
// Basic tables
private static final int ITEMS = 1;
private static final int ITEM_ID = 2;
private static final int LISTS = 3;
private static final int LIST_ID = 4;
private static final int CONTAINS = 5;
private static final int CONTAINS_ID = 6;
private static final int STORES = 7;
private static final int STORES_ID = 8;
private static final int STORES_LISTID = 9;
private static final int ITEMSTORES = 10;
private static final int ITEMSTORES_ID = 11;
private static final int NOTES = 12;
private static final int NOTE_ID = 13;
private static final int UNITS = 14;
private static final int UNITS_ID = 15;
private static final int PREFS = 16;
private static final int ITEMSTORES_ITEMID = 17;
private static final int SUBTOTALS = 18;
private static final int SUBTOTALS_LISTID = 19;
// Derived tables
private static final int CONTAINS_FULL = 101; // combined with items and
// lists
private static final int CONTAINS_FULL_ID = 102;
private static final int ACTIVELIST = 103;
private static final UriMatcher URL_MATCHER;
@Override
public boolean onCreate() {
mOpenHelper = new ShoppingDatabase(getContext());
return true;
}
@Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
long list_id = -1;
if (debug) Log.d(TAG, "Query for URL: " + url);
String defaultOrderBy = null;
String groupBy = null;
switch (URL_MATCHER.match(url)) {
case ITEMS:
qb.setTables("items");
qb.setProjectionMap(ITEMS_PROJECTION_MAP);
defaultOrderBy = Items.DEFAULT_SORT_ORDER;
break;
case ITEM_ID:
qb.setTables("items");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case LISTS:
qb.setTables("lists");
qb.setProjectionMap(LISTS_PROJECTION_MAP);
defaultOrderBy = Lists.DEFAULT_SORT_ORDER;
break;
case LIST_ID:
qb.setTables("lists");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case CONTAINS:
qb.setTables("contains");
qb.setProjectionMap(CONTAINS_PROJECTION_MAP);
defaultOrderBy = Contains.DEFAULT_SORT_ORDER;
break;
case CONTAINS_ID:
qb.setTables("contains");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case CONTAINS_FULL:
if (PreferenceActivity.getUsingPerStorePricesFromPrefs(getContext())) {
qb.setTables("contains, items, lists left outer join itemstores on (items._id = itemstores.item_id)");
qb.setProjectionMap(CONTAINS_FULL_CHEAPEST_PROJECTION_MAP);
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
groupBy = "items._id";
} else {
qb.setTables("contains, items, lists");
qb.setProjectionMap(CONTAINS_FULL_PROJECTION_MAP);
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
}
defaultOrderBy = ContainsFull.DEFAULT_SORT_ORDER;
break;
case CONTAINS_FULL_ID:
qb.setTables("contains, items, lists");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
break;
case STORES:
qb.setTables("stores");
qb.setProjectionMap(STORES_PROJECTION_MAP);
break;
case STORES_ID:
qb.setTables("stores");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case STORES_LISTID:
qb.setTables("stores");
qb.setProjectionMap(STORES_PROJECTION_MAP);
qb.appendWhere("list_id=" + url.getPathSegments().get(1));
break;
case ITEMSTORES:
qb.setTables("itemstores, items, stores");
qb.setProjectionMap(ITEMSTORES_PROJECTION_MAP);
qb.appendWhere("itemstores.item_id = items._id AND itemstores.store_id = stores._id");
break;
case ITEMSTORES_ID:
qb.setTables("itemstores, items, stores");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
qb.appendWhere("itemstores.item_id = items._id AND itemstores.store_id = stores._id");
break;
case ITEMSTORES_ITEMID:
// path segment 1 is "item", path segment 2 is item id, path segment 3 is list id.
qb.setTables("stores left outer join itemstores on (stores._id = itemstores.store_id and " +
"itemstores.item_id = " + url.getPathSegments().get(2) + ")");
qb.appendWhere("stores.list_id = " + url.getPathSegments().get(3) );
break;
case NOTES:
qb.setTables("items");
qb.setProjectionMap(NOTES_PROJECTION_MAP);
break;
case NOTE_ID:
qb.setTables("items");
qb.setProjectionMap(NOTES_PROJECTION_MAP);
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case UNITS:
qb.setTables("units");
qb.setProjectionMap(UNITS_PROJECTION_MAP);
break;
case UNITS_ID:
qb.setTables("units");
qb.setProjectionMap(UNITS_PROJECTION_MAP);
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case ACTIVELIST:
MatrixCursor m = new MatrixCursor(projection);
// assumes only one projection will ever be used,
// asking only for the id of the active list.
SharedPreferences sp = getContext().getSharedPreferences(
"org.openintents.shopping_preferences", Context.MODE_PRIVATE);
list_id = sp.getInt("lastused", 1);
m.addRow(new Object [] {Long.toString(list_id)});
return (Cursor)m;
case PREFS:
m = new MatrixCursor(projection);
// assumes only one projection will ever be used,
// asking only for the id of the active list.
String sortOrder = PreferenceActivity.getSortOrderFromPrefs(getContext(),
ShoppingActivity.MODE_IN_SHOP);
m.addRow(new Object [] {sortOrder});
return (Cursor)m;
case SUBTOTALS_LISTID:
list_id = Long.parseLong(url.getPathSegments().get(1));
// FALLTHROUGH
case SUBTOTALS:
if (list_id == -1) {
// this gets the wrong answer if user has switched lists in this session.
sp = getContext().getSharedPreferences(
"org.openintents.shopping_preferences", Context.MODE_PRIVATE);
list_id = sp.getInt("lastused", 1);
}
qb.setProjectionMap(SUBTOTALS_PROJECTION_MAP);
groupBy = "priority, status";
if (PreferenceActivity.getUsingPerStorePricesFromPrefs(getContext())) {
+ // status added to "group by" to cover the case where there are no store prices
+ // for any checked items. still need to count them separately so Clean List
+ // can be ungreyed.
qb.setTables("(SELECT (min(itemstores.price) * case when ((contains.quantity is null) or (length(contains.quantity) = 0)) then 1 else contains.quantity end) as qty_price, " +
"contains.status as status, contains.priority as priority FROM contains, items left outer join itemstores on (items._id = itemstores.item_id) " +
- "WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3 GROUP BY itemstores.item_id) ");
+ "WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3 GROUP BY itemstores.item_id, status) ");
} else {
qb.setTables("(SELECT (items.price * case when ((contains.quantity is null) or (length(contains.quantity) = 0)) then 1 else contains.quantity end) as qty_price, " +
"contains.status as status, contains.priority as priority FROM contains, items " +
"WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3) ");
}
break;
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
// If no sort order is specified use the default
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = defaultOrderBy;
} else {
orderBy = sort;
}
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
if (debug) {
String qs = qb.buildQuery(projection, selection, null, groupBy, null, orderBy, null);
Log.d(TAG, "Query : " + qs);
}
Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy,
null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), url);
return c;
}
@Override
public Uri insert(Uri url, ContentValues initialValues) {
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
// insert is supported for items or lists
switch (URL_MATCHER.match(url)) {
case ITEMS:
case NOTES:
return insertItem(url, values);
case LISTS:
return insertList(url, values);
case CONTAINS:
return insertContains(url, values);
case CONTAINS_FULL:
throw new IllegalArgumentException("Insert not supported for "
+ url + ", use CONTAINS instead of CONTAINS_FULL.");
case STORES:
return insertStore(url, values);
case ITEMSTORES:
return insertItemStore(url, values);
case UNITS:
return insertUnits(url, values);
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
}
private Uri insertItem(Uri url, ContentValues values) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowID;
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the fields are all set
if (!values.containsKey(Items.NAME)) {
Resources r = getContext().getResources();
values.put(Items.NAME, r.getString(R.string.new_item));
}
if (!values.containsKey(Items.IMAGE)) {
values.put(Items.IMAGE, "");
}
if (!values.containsKey(Items.CREATED_DATE)) {
values.put(Items.CREATED_DATE, now);
}
if (!values.containsKey(Items.MODIFIED_DATE)) {
values.put(Items.MODIFIED_DATE, now);
}
if (!values.containsKey(Items.ACCESSED_DATE)) {
values.put(Items.ACCESSED_DATE, now);
}
// TODO: Here we should check, whether item exists already.
// (see TagsProvider)
// insert the item.
rowID = db.insert("items", "items", values);
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(Items.CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
Intent intent = new Intent(ProviderIntents.ACTION_INSERTED);
intent.setData(uri);
getContext().sendBroadcast(intent);
return uri;
}
// If everything works, we should not reach the following line:
throw new SQLException("Failed to insert row into " + url);
}
private Uri insertList(Uri url, ContentValues values) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowID;
Long now = Long.valueOf(System.currentTimeMillis());
Resources r = Resources.getSystem();
// Make sure that the fields are all set
if (!values.containsKey(Lists.NAME)) {
values.put(Lists.NAME, r.getString(R.string.new_list));
}
if (!values.containsKey(Lists.IMAGE)) {
values.put(Lists.IMAGE, "");
}
if (!values.containsKey(Lists.CREATED_DATE)) {
values.put(Lists.CREATED_DATE, now);
}
if (!values.containsKey(Lists.MODIFIED_DATE)) {
values.put(Lists.MODIFIED_DATE, now);
}
if (!values.containsKey(Lists.ACCESSED_DATE)) {
values.put(Lists.ACCESSED_DATE, now);
}
if (!values.containsKey(Lists.SHARE_CONTACTS)) {
values.put(Lists.SHARE_CONTACTS, "");
}
if (!values.containsKey(Lists.SKIN_BACKGROUND)) {
values.put(Lists.SKIN_BACKGROUND, "");
}
if (!values.containsKey(Lists.SKIN_FONT)) {
values.put(Lists.SKIN_FONT, "");
}
if (!values.containsKey(Lists.SKIN_COLOR)) {
values.put(Lists.SKIN_COLOR, 0);
}
if (!values.containsKey(Lists.SKIN_COLOR_STRIKETHROUGH)) {
values.put(Lists.SKIN_COLOR_STRIKETHROUGH, 0xFF006600);
}
// TODO: Here we should check, whether item exists already.
// (see TagsProvider)
// insert the tag.
rowID = db.insert("lists", "lists", values);
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(Lists.CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
Intent intent = new Intent(ProviderIntents.ACTION_INSERTED);
intent.setData(uri);
getContext().sendBroadcast(intent);
return uri;
}
// If everything works, we should not reach the following line:
throw new SQLException("Failed to insert row into " + url);
}
private Uri insertContains(Uri url, ContentValues values) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Long now = Long.valueOf(System.currentTimeMillis());
Resources r = Resources.getSystem();
// Make sure that the fields are all set
if (!(values.containsKey(Contains.ITEM_ID) && values
.containsKey(Contains.LIST_ID))) {
// At least these values should exist.
throw new SQLException("Failed to insert row into " + url
+ ": ITEM_ID and LIST_ID must be given.");
}
// TODO: Check here that ITEM_ID and LIST_ID
// actually exist in the tables.
if (!values.containsKey(Contains.STATUS)) {
values.put(Contains.STATUS, Status.WANT_TO_BUY);
} else {
// Check here that STATUS is valid.
long s = values.getAsInteger(Contains.STATUS);
if (!Status.isValid(s)) {
throw new SQLException("Failed to insert row into " + url
+ ": Status " + s + " is not valid.");
}
}
if (!values.containsKey(Contains.CREATED_DATE)) {
values.put(Contains.CREATED_DATE, now);
}
if (!values.containsKey(Contains.MODIFIED_DATE)) {
values.put(Contains.MODIFIED_DATE, now);
}
if (!values.containsKey(Contains.ACCESSED_DATE)) {
values.put(Contains.ACCESSED_DATE, now);
}
if (!values.containsKey(Contains.SHARE_CREATED_BY)) {
values.put(Contains.SHARE_CREATED_BY, "");
}
if (!values.containsKey(Contains.SHARE_MODIFIED_BY)) {
values.put(Contains.SHARE_MODIFIED_BY, "");
}
// TODO: Here we should check, whether item exists already.
// (see TagsProvider)
// insert the item.
long rowId = db.insert("contains", "contains", values);
if (rowId > 0) {
Uri uri = ContentUris.withAppendedId(Contains.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(uri, null);
Intent intent = new Intent(ProviderIntents.ACTION_INSERTED);
intent.setData(uri);
getContext().sendBroadcast(intent);
return uri;
}
// If everything works, we should not reach the following line:
throw new SQLException("Failed to insert row into " + url);
}
private Uri insertStore(Uri url, ContentValues values) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowID;
Long now = Long.valueOf(System.currentTimeMillis());
Resources r = Resources.getSystem();
// Make sure that the fields are all set
if (!values.containsKey(Stores.NAME)) {
throw new SQLException("Failed to insert row into " + url
+ ": Store NAME must be given.");
}
if (!values.containsKey(Stores.CREATED_DATE)) {
values.put(Stores.CREATED_DATE, now);
}
if (!values.containsKey(Stores.MODIFIED_DATE)) {
values.put(Stores.MODIFIED_DATE, now);
}
// TODO: Here we should check, whether item exists already.
// (see TagsProvider)
// insert the tag.
rowID = db.insert("stores", "stores", values);
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(Stores.CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
Intent intent = new Intent(ProviderIntents.ACTION_INSERTED);
intent.setData(uri);
getContext().sendBroadcast(intent);
return uri;
}
// If everything works, we should not reach the following line:
throw new SQLException("Failed to insert row into " + url);
}
private Uri insertItemStore(Uri url, ContentValues values) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Long now = Long.valueOf(System.currentTimeMillis());
Resources r = Resources.getSystem();
// Make sure that the fields are all set
if (!(values.containsKey(ItemStores.ITEM_ID) && values
.containsKey(ItemStores.STORE_ID))) {
// At least these values should exist.
throw new SQLException("Failed to insert row into " + url
+ ": ITEM_ID and STORE_ID must be given.");
}
// TODO: Check here that ITEM_ID and STORE_ID
// actually exist in the tables.
if (!values.containsKey(ItemStores.PRICE)) {
values.put(ItemStores.PRICE, -1);
}
if (!values.containsKey(ItemStores.AISLE)) {
values.putNull(ItemStores.AISLE);
}
if (!values.containsKey(ItemStores.CREATED_DATE)) {
values.put(ItemStores.CREATED_DATE, now);
}
if (!values.containsKey(ItemStores.MODIFIED_DATE)) {
values.put(ItemStores.MODIFIED_DATE, now);
}
// TODO: Here we should check, whether item exists already.
// (see TagsProvider)
// insert the item.
long rowId = db.insert("itemstores", "itemstores", values);
if (rowId > 0) {
Uri uri = ContentUris.withAppendedId(ItemStores.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(uri, null);
Intent intent = new Intent(ProviderIntents.ACTION_INSERTED);
intent.setData(uri);
getContext().sendBroadcast(intent);
return uri;
}
// If everything works, we should not reach the following line:
throw new SQLException("Failed to insert row into " + url);
}
private Uri insertUnits(Uri url, ContentValues values) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowID;
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the fields are all set
if (!values.containsKey(Units.NAME)) {
throw new SQLException("Failed to insert row into " + url
+ ": Units NAME must be given.");
}
if (!values.containsKey(Units.CREATED_DATE)) {
values.put(Units.CREATED_DATE, now);
}
if (!values.containsKey(Stores.MODIFIED_DATE)) {
values.put(Units.MODIFIED_DATE, now);
}
// TODO: Here we should check, whether item exists already.
// (see TagsProvider)
// insert the units.
rowID = db.insert("units", "units", values);
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(Units.CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
Intent intent = new Intent(ProviderIntents.ACTION_INSERTED);
intent.setData(uri);
getContext().sendBroadcast(intent);
return uri;
}
// If everything works, we should not reach the following line:
throw new SQLException("Failed to insert row into " + url);
}
@Override
public int delete(Uri url, String where, String[] whereArgs) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
long[] affectedRows = null;
// long rowId;
switch (URL_MATCHER.match(url)) {
case ITEMS:
affectedRows = ProviderUtils.getAffectedRows(db, "items", where,
whereArgs);
count = db.delete("items", where, whereArgs);
break;
case ITEM_ID:
String segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
String whereString;
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
affectedRows = ProviderUtils.getAffectedRows(db, "items", "_id="
+ segment + whereString, whereArgs);
count = db.delete("items", "_id=" + segment + whereString,
whereArgs);
break;
case LISTS:
affectedRows = ProviderUtils.getAffectedRows(db, "lists", where,
whereArgs);
count = db.delete("lists", where, whereArgs);
break;
case LIST_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
affectedRows = ProviderUtils.getAffectedRows(db, "lists", "_id="
+ segment + whereString, whereArgs);
count = db.delete("lists", "_id=" + segment + whereString,
whereArgs);
break;
case CONTAINS:
affectedRows = ProviderUtils.getAffectedRows(db, "contains", where,
whereArgs);
count = db.delete("contains", where, whereArgs);
break;
case CONTAINS_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
affectedRows = ProviderUtils.getAffectedRows(db, "contains", "_id="
+ segment + whereString, whereArgs);
count = db.delete("contains", "_id=" + segment + whereString,
whereArgs);
break;
case NOTE_ID:
// don't delete the row, just the note.
ContentValues values = new ContentValues();
values.putNull("note");
count = update(url, values, null, null);
break;
case STORES:
affectedRows = ProviderUtils.getAffectedRows(db, "stores", where,
whereArgs);
count = db.delete("stores", where, whereArgs);
break;
case ITEMSTORES:
affectedRows = ProviderUtils.getAffectedRows(db, "itemstores", where,
whereArgs);
count = db.delete("itemstores", where, whereArgs);
break;
case ITEMSTORES_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
affectedRows = ProviderUtils.getAffectedRows(db, "itemstores", "_id="
+ segment + whereString, whereArgs);
count = db.delete("itemstores", "_id=" + segment + whereString,
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
getContext().getContentResolver().notifyChange(url, null);
Intent intent = new Intent(ProviderIntents.ACTION_DELETED);
intent.setData(url);
intent.putExtra(ProviderIntents.EXTRA_AFFECTED_ROWS, affectedRows);
getContext().sendBroadcast(intent);
return count;
}
@Override
public int update(Uri url, ContentValues values, String where,
String[] whereArgs) {
if (debug) Log.d(TAG, "update called for: " + url);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
Uri secondUri = null;
// long rowId;
switch (URL_MATCHER.match(url)) {
case ITEMS:
case NOTES:
count = db.update("items", values, where, whereArgs);
break;
case NOTE_ID:
// drop some OI Notepad fields on the floor.
values.remove("title");
values.remove("encrypted");
values.remove("theme");
values.remove("nothing_To_see_here");
// fall through...
case ITEM_ID:
String segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
String whereString;
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = db.update("items", values, "_id=" + segment + whereString,
whereArgs);
secondUri = ShoppingContract.Items.CONTENT_URI;
break;
case LISTS:
count = db.update("lists", values, where, whereArgs);
break;
case LIST_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = db.update("lists", values, "_id=" + segment + whereString,
whereArgs);
break;
case CONTAINS:
count = db.update("contains", values, where, whereArgs);
break;
case CONTAINS_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = db.update("contains", values, "_id=" + segment
+ whereString, whereArgs);
break;
case STORES:
count = db.update("stores", values, where, whereArgs);
break;
case STORES_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = db.update("stores", values, "_id=" + segment
+ whereString, whereArgs);
break;
case ITEMSTORES:
count = db.update("itemstores", values, where, whereArgs);
break;
case ITEMSTORES_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = db.update("itemstores", values, "_id=" + segment
+ whereString, whereArgs);
break;
case UNITS:
count = db.update("units", values, where, whereArgs);
break;
case UNITS_ID:
segment = url.getPathSegments().get(1); // contains rowId
// rowId = Long.parseLong(segment);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = db.update("units", values, "_id=" + segment
+ whereString, whereArgs);
break;
default:
Log.e(TAG, "Update received unknown URL: " + url);
throw new IllegalArgumentException("Unknown URL " + url);
}
getContext().getContentResolver().notifyChange(url, null);
if (secondUri != null){
getContext().getContentResolver().notifyChange(secondUri, null);
}
Intent intent = new Intent(ProviderIntents.ACTION_MODIFIED);
intent.setData(url);
getContext().sendBroadcast(intent);
return count;
}
@Override
public String getType(Uri url) {
switch (URL_MATCHER.match(url)) {
case ITEMS:
return "vnd.android.cursor.dir/vnd.openintents.shopping.item";
case ITEM_ID:
return ShoppingContract.ITEM_TYPE;
case LISTS:
return "vnd.android.cursor.dir/vnd.openintents.shopping.list";
case LIST_ID:
return "vnd.android.cursor.item/vnd.openintents.shopping.list";
case CONTAINS:
return "vnd.android.cursor.dir/vnd.openintents.shopping.contains";
case CONTAINS_ID:
return "vnd.android.cursor.item/vnd.openintents.shopping.contains";
case CONTAINS_FULL:
return "vnd.android.cursor.dir/vnd.openintents.shopping.containsfull";
case CONTAINS_FULL_ID:
return "vnd.android.cursor.item/vnd.openintents.shopping.containsfull";
case STORES:
return "vnd.android.cursor.dir/vnd.openintents.shopping.stores";
case STORES_ID:
case STORES_LISTID:
return "vnd.android.cursor.item/vnd.openintents.shopping.stores";
case NOTES:
return ShoppingContract.Notes.CONTENT_TYPE;
case NOTE_ID:
return ShoppingContract.Notes.CONTENT_ITEM_TYPE;
case ITEMSTORES:
return "vnd.android.cursor.dir/vnd.openintents.shopping.itemstores";
case ITEMSTORES_ID:
return "vnd.android.cursor.item/vnd.openintents.shopping.itemstores";
case ITEMSTORES_ITEMID:
return "vnd.android.cursor.dir/vnd.openintents.shopping.itemstores";
case UNITS:
return "vnd.android.cursor.dir/vnd.openintents.shopping.units";
case UNITS_ID:
return "vnd.android.cursor.item/vnd.openintents.shopping.units";
case ACTIVELIST:
// not sure this is quite right
return "vnd.android.cursor.item/vnd.openintents.shopping.list";
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
}
static {
URL_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
URL_MATCHER.addURI("org.openintents.shopping", "items", ITEMS);
URL_MATCHER.addURI("org.openintents.shopping", "items/#", ITEM_ID);
URL_MATCHER.addURI("org.openintents.shopping", "lists", LISTS);
URL_MATCHER.addURI("org.openintents.shopping", "lists/active", ACTIVELIST);
URL_MATCHER.addURI("org.openintents.shopping", "lists/#", LIST_ID);
URL_MATCHER.addURI("org.openintents.shopping", "contains", CONTAINS);
URL_MATCHER.addURI("org.openintents.shopping", "contains/#",
CONTAINS_ID);
URL_MATCHER.addURI("org.openintents.shopping", "containsfull",
CONTAINS_FULL);
URL_MATCHER.addURI("org.openintents.shopping", "containsfull/#",
CONTAINS_FULL_ID);
URL_MATCHER.addURI("org.openintents.shopping", "stores", STORES);
URL_MATCHER.addURI("org.openintents.shopping", "stores/#", STORES_ID);
URL_MATCHER.addURI("org.openintents.shopping", "itemstores", ITEMSTORES);
URL_MATCHER.addURI("org.openintents.shopping", "itemstores/#",
ITEMSTORES_ID);
URL_MATCHER.addURI("org.openintents.shopping", "itemstores/item/#/#",
ITEMSTORES_ITEMID);
URL_MATCHER.addURI("org.openintents.shopping", "liststores/#",
STORES_LISTID);
URL_MATCHER.addURI("org.openintents.shopping", "notes", NOTES);
URL_MATCHER.addURI("org.openintents.shopping", "notes/#", NOTE_ID);
URL_MATCHER.addURI("org.openintents.shopping", "units", UNITS);
URL_MATCHER.addURI("org.openintents.shopping", "units/#", UNITS_ID);
URL_MATCHER.addURI("org.openintents.shopping", "prefs", PREFS);
// subtotals for the specified list id, or active list if not specified
URL_MATCHER.addURI("org.openintents.shopping", "subtotals/#", SUBTOTALS_LISTID);
URL_MATCHER.addURI("org.openintents.shopping", "subtotals", SUBTOTALS);
ITEMS_PROJECTION_MAP = new HashMap<String, String>();
ITEMS_PROJECTION_MAP.put(Items._ID, "items._id");
ITEMS_PROJECTION_MAP.put(Items.NAME, "items.name");
ITEMS_PROJECTION_MAP.put(Items.IMAGE, "items.image");
ITEMS_PROJECTION_MAP.put(Items.PRICE, "items.price");
ITEMS_PROJECTION_MAP.put(Items.UNITS, "items.units");
ITEMS_PROJECTION_MAP.put(Items.TAGS, "items.tags");
ITEMS_PROJECTION_MAP.put(Items.BARCODE, "items.barcode");
ITEMS_PROJECTION_MAP.put(Items.LOCATION, "items.location");
ITEMS_PROJECTION_MAP.put(Items.DUE_DATE, "items.due");
ITEMS_PROJECTION_MAP.put(Items.CREATED_DATE, "items.created");
ITEMS_PROJECTION_MAP.put(Items.MODIFIED_DATE, "items.modified");
ITEMS_PROJECTION_MAP.put(Items.ACCESSED_DATE, "items.accessed");
LISTS_PROJECTION_MAP = new HashMap<String, String>();
LISTS_PROJECTION_MAP.put(Lists._ID, "lists._id");
LISTS_PROJECTION_MAP.put(Lists.NAME, "lists.name");
LISTS_PROJECTION_MAP.put(Lists.IMAGE, "lists.image");
LISTS_PROJECTION_MAP.put(Lists.CREATED_DATE, "lists.created");
LISTS_PROJECTION_MAP.put(Lists.MODIFIED_DATE, "lists.modified");
LISTS_PROJECTION_MAP.put(Lists.ACCESSED_DATE, "lists.accessed");
LISTS_PROJECTION_MAP.put(Lists.SHARE_NAME, "lists.share_name");
LISTS_PROJECTION_MAP.put(Lists.SHARE_CONTACTS, "lists.share_contacts");
LISTS_PROJECTION_MAP
.put(Lists.SKIN_BACKGROUND, "lists.skin_background");
LISTS_PROJECTION_MAP.put(Lists.SKIN_FONT, "lists.skin_font");
LISTS_PROJECTION_MAP.put(Lists.SKIN_COLOR, "lists.skin_color");
LISTS_PROJECTION_MAP.put(Lists.SKIN_COLOR_STRIKETHROUGH,
"lists.skin_color_strikethrough");
CONTAINS_PROJECTION_MAP = new HashMap<String, String>();
CONTAINS_PROJECTION_MAP.put(Contains._ID, "contains._id");
CONTAINS_PROJECTION_MAP.put(Contains.ITEM_ID, "contains.item_id");
CONTAINS_PROJECTION_MAP.put(Contains.LIST_ID, "contains.list_id");
CONTAINS_PROJECTION_MAP.put(Contains.QUANTITY, "contains.quantity");
CONTAINS_PROJECTION_MAP.put(Contains.PRIORITY, "contains.priority");
CONTAINS_PROJECTION_MAP.put(Contains.STATUS, "contains.status");
CONTAINS_PROJECTION_MAP.put(Contains.CREATED_DATE, "contains.created");
CONTAINS_PROJECTION_MAP
.put(Contains.MODIFIED_DATE, "contains.modified");
CONTAINS_PROJECTION_MAP
.put(Contains.ACCESSED_DATE, "contains.accessed");
CONTAINS_PROJECTION_MAP.put(Contains.SHARE_CREATED_BY,
"contains.share_created_by");
CONTAINS_PROJECTION_MAP.put(Contains.SHARE_MODIFIED_BY,
"contains.share_modified_by");
CONTAINS_FULL_PROJECTION_MAP = new HashMap<String, String>();
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull._ID, "contains._id as _id");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_ID,
"contains.item_id");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.LIST_ID,
"contains.list_id");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.QUANTITY,
"contains.quantity as quantity");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.PRIORITY,
"contains.priority as priority");
CONTAINS_FULL_PROJECTION_MAP
.put(ContainsFull.STATUS, "contains.status");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.CREATED_DATE,
"contains.created");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.MODIFIED_DATE,
"contains.modified");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ACCESSED_DATE,
"contains.accessed");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.SHARE_CREATED_BY,
"contains.share_created_by");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.SHARE_MODIFIED_BY,
"contains.share_modified_by");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_NAME,
"items.name as item_name");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_IMAGE,
"items.image as item_image");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_PRICE,
"items.price as item_price");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_UNITS,
"items.units as item_units");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_TAGS,
"items.tags as item_tags");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.LIST_NAME,
"lists.name as list_name");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.LIST_IMAGE,
"lists.image as list_image");
CONTAINS_FULL_PROJECTION_MAP.put(ContainsFull.ITEM_HAS_NOTE,
"items.note is not NULL and items.note <> '' as item_has_note");
CONTAINS_FULL_CHEAPEST_PROJECTION_MAP =
new HashMap<String, String>(CONTAINS_FULL_PROJECTION_MAP);
CONTAINS_FULL_CHEAPEST_PROJECTION_MAP.put(ContainsFull.ITEM_PRICE,
"min(itemstores.price) as item_price");
UNITS_PROJECTION_MAP = new HashMap<String, String>();
UNITS_PROJECTION_MAP.put(Units._ID, "units._id");
UNITS_PROJECTION_MAP.put(Units.CREATED_DATE, "units.created");
UNITS_PROJECTION_MAP.put(Units.MODIFIED_DATE, "units.modified");
UNITS_PROJECTION_MAP.put(Units.NAME, "units.name");
UNITS_PROJECTION_MAP.put(Units.SINGULAR, "units.singular");
STORES_PROJECTION_MAP = new HashMap<String, String>();
STORES_PROJECTION_MAP.put(Stores._ID, "stores._id");
STORES_PROJECTION_MAP.put(Stores.CREATED_DATE, "stores.created");
STORES_PROJECTION_MAP.put(Stores.MODIFIED_DATE, "stores.modified");
STORES_PROJECTION_MAP.put(Stores.NAME, "stores.name");
STORES_PROJECTION_MAP.put(Stores.LIST_ID, "stores.list_id");
ITEMSTORES_PROJECTION_MAP = new HashMap<String, String>();
ITEMSTORES_PROJECTION_MAP.put(ItemStores._ID, "itemstores._id");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.CREATED_DATE,
"itemstores.created");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.MODIFIED_DATE,
"itemstores.modified");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.ITEM_ID, "itemstores.item_id");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.STORE_ID, "itemstores.store_id");
ITEMSTORES_PROJECTION_MAP.put(Stores.NAME, "stores.name");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.AISLE, "itemstores.aisle");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.PRICE, "itemstores.price");
ITEMSTORES_PROJECTION_MAP.put(ItemStores.STOCKS_ITEM, "itemstores.stocks_item");
NOTES_PROJECTION_MAP = new HashMap<String, String>();
NOTES_PROJECTION_MAP.put(ShoppingContract.Notes._ID, "items._id");
NOTES_PROJECTION_MAP.put(ShoppingContract.Notes.NOTE, "items.note");
NOTES_PROJECTION_MAP.put(ShoppingContract.Notes.TITLE, "null as title");
NOTES_PROJECTION_MAP.put(ShoppingContract.Notes.TAGS, "null as tags");
NOTES_PROJECTION_MAP.put(ShoppingContract.Notes.ENCRYPTED, "null as encrypted");
NOTES_PROJECTION_MAP.put(ShoppingContract.Notes.THEME, "null as theme");
SUBTOTALS_PROJECTION_MAP = new HashMap<String, String>();
SUBTOTALS_PROJECTION_MAP.put(ShoppingContract.Subtotals.COUNT, "count() as count");
SUBTOTALS_PROJECTION_MAP.put(ShoppingContract.Subtotals.PRIORITY, "priority");
SUBTOTALS_PROJECTION_MAP.put(ShoppingContract.Subtotals.SUBTOTAL, "sum(qty_price) as subtotal");
SUBTOTALS_PROJECTION_MAP.put(ShoppingContract.Subtotals.STATUS, "status");
}
}
| false | true | public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
long list_id = -1;
if (debug) Log.d(TAG, "Query for URL: " + url);
String defaultOrderBy = null;
String groupBy = null;
switch (URL_MATCHER.match(url)) {
case ITEMS:
qb.setTables("items");
qb.setProjectionMap(ITEMS_PROJECTION_MAP);
defaultOrderBy = Items.DEFAULT_SORT_ORDER;
break;
case ITEM_ID:
qb.setTables("items");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case LISTS:
qb.setTables("lists");
qb.setProjectionMap(LISTS_PROJECTION_MAP);
defaultOrderBy = Lists.DEFAULT_SORT_ORDER;
break;
case LIST_ID:
qb.setTables("lists");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case CONTAINS:
qb.setTables("contains");
qb.setProjectionMap(CONTAINS_PROJECTION_MAP);
defaultOrderBy = Contains.DEFAULT_SORT_ORDER;
break;
case CONTAINS_ID:
qb.setTables("contains");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case CONTAINS_FULL:
if (PreferenceActivity.getUsingPerStorePricesFromPrefs(getContext())) {
qb.setTables("contains, items, lists left outer join itemstores on (items._id = itemstores.item_id)");
qb.setProjectionMap(CONTAINS_FULL_CHEAPEST_PROJECTION_MAP);
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
groupBy = "items._id";
} else {
qb.setTables("contains, items, lists");
qb.setProjectionMap(CONTAINS_FULL_PROJECTION_MAP);
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
}
defaultOrderBy = ContainsFull.DEFAULT_SORT_ORDER;
break;
case CONTAINS_FULL_ID:
qb.setTables("contains, items, lists");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
break;
case STORES:
qb.setTables("stores");
qb.setProjectionMap(STORES_PROJECTION_MAP);
break;
case STORES_ID:
qb.setTables("stores");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case STORES_LISTID:
qb.setTables("stores");
qb.setProjectionMap(STORES_PROJECTION_MAP);
qb.appendWhere("list_id=" + url.getPathSegments().get(1));
break;
case ITEMSTORES:
qb.setTables("itemstores, items, stores");
qb.setProjectionMap(ITEMSTORES_PROJECTION_MAP);
qb.appendWhere("itemstores.item_id = items._id AND itemstores.store_id = stores._id");
break;
case ITEMSTORES_ID:
qb.setTables("itemstores, items, stores");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
qb.appendWhere("itemstores.item_id = items._id AND itemstores.store_id = stores._id");
break;
case ITEMSTORES_ITEMID:
// path segment 1 is "item", path segment 2 is item id, path segment 3 is list id.
qb.setTables("stores left outer join itemstores on (stores._id = itemstores.store_id and " +
"itemstores.item_id = " + url.getPathSegments().get(2) + ")");
qb.appendWhere("stores.list_id = " + url.getPathSegments().get(3) );
break;
case NOTES:
qb.setTables("items");
qb.setProjectionMap(NOTES_PROJECTION_MAP);
break;
case NOTE_ID:
qb.setTables("items");
qb.setProjectionMap(NOTES_PROJECTION_MAP);
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case UNITS:
qb.setTables("units");
qb.setProjectionMap(UNITS_PROJECTION_MAP);
break;
case UNITS_ID:
qb.setTables("units");
qb.setProjectionMap(UNITS_PROJECTION_MAP);
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case ACTIVELIST:
MatrixCursor m = new MatrixCursor(projection);
// assumes only one projection will ever be used,
// asking only for the id of the active list.
SharedPreferences sp = getContext().getSharedPreferences(
"org.openintents.shopping_preferences", Context.MODE_PRIVATE);
list_id = sp.getInt("lastused", 1);
m.addRow(new Object [] {Long.toString(list_id)});
return (Cursor)m;
case PREFS:
m = new MatrixCursor(projection);
// assumes only one projection will ever be used,
// asking only for the id of the active list.
String sortOrder = PreferenceActivity.getSortOrderFromPrefs(getContext(),
ShoppingActivity.MODE_IN_SHOP);
m.addRow(new Object [] {sortOrder});
return (Cursor)m;
case SUBTOTALS_LISTID:
list_id = Long.parseLong(url.getPathSegments().get(1));
// FALLTHROUGH
case SUBTOTALS:
if (list_id == -1) {
// this gets the wrong answer if user has switched lists in this session.
sp = getContext().getSharedPreferences(
"org.openintents.shopping_preferences", Context.MODE_PRIVATE);
list_id = sp.getInt("lastused", 1);
}
qb.setProjectionMap(SUBTOTALS_PROJECTION_MAP);
groupBy = "priority, status";
if (PreferenceActivity.getUsingPerStorePricesFromPrefs(getContext())) {
qb.setTables("(SELECT (min(itemstores.price) * case when ((contains.quantity is null) or (length(contains.quantity) = 0)) then 1 else contains.quantity end) as qty_price, " +
"contains.status as status, contains.priority as priority FROM contains, items left outer join itemstores on (items._id = itemstores.item_id) " +
"WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3 GROUP BY itemstores.item_id) ");
} else {
qb.setTables("(SELECT (items.price * case when ((contains.quantity is null) or (length(contains.quantity) = 0)) then 1 else contains.quantity end) as qty_price, " +
"contains.status as status, contains.priority as priority FROM contains, items " +
"WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3) ");
}
break;
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
// If no sort order is specified use the default
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = defaultOrderBy;
} else {
orderBy = sort;
}
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
if (debug) {
String qs = qb.buildQuery(projection, selection, null, groupBy, null, orderBy, null);
Log.d(TAG, "Query : " + qs);
}
Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy,
null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), url);
return c;
}
| public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
long list_id = -1;
if (debug) Log.d(TAG, "Query for URL: " + url);
String defaultOrderBy = null;
String groupBy = null;
switch (URL_MATCHER.match(url)) {
case ITEMS:
qb.setTables("items");
qb.setProjectionMap(ITEMS_PROJECTION_MAP);
defaultOrderBy = Items.DEFAULT_SORT_ORDER;
break;
case ITEM_ID:
qb.setTables("items");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case LISTS:
qb.setTables("lists");
qb.setProjectionMap(LISTS_PROJECTION_MAP);
defaultOrderBy = Lists.DEFAULT_SORT_ORDER;
break;
case LIST_ID:
qb.setTables("lists");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case CONTAINS:
qb.setTables("contains");
qb.setProjectionMap(CONTAINS_PROJECTION_MAP);
defaultOrderBy = Contains.DEFAULT_SORT_ORDER;
break;
case CONTAINS_ID:
qb.setTables("contains");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case CONTAINS_FULL:
if (PreferenceActivity.getUsingPerStorePricesFromPrefs(getContext())) {
qb.setTables("contains, items, lists left outer join itemstores on (items._id = itemstores.item_id)");
qb.setProjectionMap(CONTAINS_FULL_CHEAPEST_PROJECTION_MAP);
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
groupBy = "items._id";
} else {
qb.setTables("contains, items, lists");
qb.setProjectionMap(CONTAINS_FULL_PROJECTION_MAP);
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
}
defaultOrderBy = ContainsFull.DEFAULT_SORT_ORDER;
break;
case CONTAINS_FULL_ID:
qb.setTables("contains, items, lists");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
qb.appendWhere("contains.item_id = items._id AND " +
"contains.list_id = lists._id");
break;
case STORES:
qb.setTables("stores");
qb.setProjectionMap(STORES_PROJECTION_MAP);
break;
case STORES_ID:
qb.setTables("stores");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case STORES_LISTID:
qb.setTables("stores");
qb.setProjectionMap(STORES_PROJECTION_MAP);
qb.appendWhere("list_id=" + url.getPathSegments().get(1));
break;
case ITEMSTORES:
qb.setTables("itemstores, items, stores");
qb.setProjectionMap(ITEMSTORES_PROJECTION_MAP);
qb.appendWhere("itemstores.item_id = items._id AND itemstores.store_id = stores._id");
break;
case ITEMSTORES_ID:
qb.setTables("itemstores, items, stores");
qb.appendWhere("_id=" + url.getPathSegments().get(1));
qb.appendWhere("itemstores.item_id = items._id AND itemstores.store_id = stores._id");
break;
case ITEMSTORES_ITEMID:
// path segment 1 is "item", path segment 2 is item id, path segment 3 is list id.
qb.setTables("stores left outer join itemstores on (stores._id = itemstores.store_id and " +
"itemstores.item_id = " + url.getPathSegments().get(2) + ")");
qb.appendWhere("stores.list_id = " + url.getPathSegments().get(3) );
break;
case NOTES:
qb.setTables("items");
qb.setProjectionMap(NOTES_PROJECTION_MAP);
break;
case NOTE_ID:
qb.setTables("items");
qb.setProjectionMap(NOTES_PROJECTION_MAP);
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case UNITS:
qb.setTables("units");
qb.setProjectionMap(UNITS_PROJECTION_MAP);
break;
case UNITS_ID:
qb.setTables("units");
qb.setProjectionMap(UNITS_PROJECTION_MAP);
qb.appendWhere("_id=" + url.getPathSegments().get(1));
break;
case ACTIVELIST:
MatrixCursor m = new MatrixCursor(projection);
// assumes only one projection will ever be used,
// asking only for the id of the active list.
SharedPreferences sp = getContext().getSharedPreferences(
"org.openintents.shopping_preferences", Context.MODE_PRIVATE);
list_id = sp.getInt("lastused", 1);
m.addRow(new Object [] {Long.toString(list_id)});
return (Cursor)m;
case PREFS:
m = new MatrixCursor(projection);
// assumes only one projection will ever be used,
// asking only for the id of the active list.
String sortOrder = PreferenceActivity.getSortOrderFromPrefs(getContext(),
ShoppingActivity.MODE_IN_SHOP);
m.addRow(new Object [] {sortOrder});
return (Cursor)m;
case SUBTOTALS_LISTID:
list_id = Long.parseLong(url.getPathSegments().get(1));
// FALLTHROUGH
case SUBTOTALS:
if (list_id == -1) {
// this gets the wrong answer if user has switched lists in this session.
sp = getContext().getSharedPreferences(
"org.openintents.shopping_preferences", Context.MODE_PRIVATE);
list_id = sp.getInt("lastused", 1);
}
qb.setProjectionMap(SUBTOTALS_PROJECTION_MAP);
groupBy = "priority, status";
if (PreferenceActivity.getUsingPerStorePricesFromPrefs(getContext())) {
// status added to "group by" to cover the case where there are no store prices
// for any checked items. still need to count them separately so Clean List
// can be ungreyed.
qb.setTables("(SELECT (min(itemstores.price) * case when ((contains.quantity is null) or (length(contains.quantity) = 0)) then 1 else contains.quantity end) as qty_price, " +
"contains.status as status, contains.priority as priority FROM contains, items left outer join itemstores on (items._id = itemstores.item_id) " +
"WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3 GROUP BY itemstores.item_id, status) ");
} else {
qb.setTables("(SELECT (items.price * case when ((contains.quantity is null) or (length(contains.quantity) = 0)) then 1 else contains.quantity end) as qty_price, " +
"contains.status as status, contains.priority as priority FROM contains, items " +
"WHERE (contains.item_id = items._id AND contains.list_id = " + list_id + " ) AND contains.status != 3) ");
}
break;
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
// If no sort order is specified use the default
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = defaultOrderBy;
} else {
orderBy = sort;
}
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
if (debug) {
String qs = qb.buildQuery(projection, selection, null, groupBy, null, orderBy, null);
Log.d(TAG, "Query : " + qs);
}
Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy,
null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), url);
return c;
}
|
diff --git a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java
index 32a62f9b7..2685bb25f 100644
--- a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java
+++ b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java
@@ -1,492 +1,500 @@
/**
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.workflow.instance.node;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.drools.WorkItemHandlerNotFoundException;
import org.drools.definition.process.Node;
import org.drools.process.core.Work;
import org.drools.process.instance.WorkItem;
import org.drools.process.instance.WorkItemManager;
import org.drools.process.instance.impl.WorkItemImpl;
import org.drools.runtime.KnowledgeRuntime;
import org.drools.runtime.process.EventListener;
import org.drools.runtime.process.NodeInstance;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.process.instance.ProcessInstance;
import org.jbpm.process.instance.context.variable.VariableScopeInstance;
import org.jbpm.process.instance.impl.XPATHExpressionModifier;
import org.jbpm.workflow.core.node.Assignment;
import org.jbpm.workflow.core.node.DataAssociation;
import org.jbpm.workflow.core.node.WorkItemNode;
import org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory;
import org.jbpm.workflow.instance.impl.WorkItemResolverFactory;
import org.mvel2.MVEL;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Runtime counterpart of a work item node.
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
public class WorkItemNodeInstance extends StateBasedNodeInstance implements EventListener {
private static final Logger _logger = LoggerFactory.getLogger(WorkItemNodeInstance.class);
private static final Logger _assignmentsLogger = LoggerFactory.getLogger("org.jbpm.xpath");
private static final long serialVersionUID = 510l;
private static final Pattern PARAMETER_MATCHER = Pattern.compile("#\\{(\\S+)\\}", Pattern.DOTALL);
private long workItemId = -1;
private transient WorkItem workItem;
private static String serializeXML(org.w3c.dom.Node node) {
if (node == null) {
return null;
}
try {
StringWriter writer = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult streamResult = new StreamResult(writer);
serializer.transform(new DOMSource(node), streamResult);
return writer.toString();
} catch (TransformerConfigurationException e) {
_logger.error(e.getMessage(), e);
} catch (TransformerException e) {
_logger.error(e.getMessage(), e);
}
return null;
}
protected WorkItemNode getWorkItemNode() {
return (WorkItemNode) getNode();
}
public WorkItem getWorkItem() {
if (workItem == null && workItemId >= 0) {
workItem = ((WorkItemManager) ((ProcessInstance) getProcessInstance())
.getKnowledgeRuntime().getWorkItemManager()).getWorkItem(workItemId);
}
return workItem;
}
public long getWorkItemId() {
return workItemId;
}
public void internalSetWorkItemId(long workItemId) {
this.workItemId = workItemId;
}
public void internalSetWorkItem(WorkItem workItem) {
this.workItem = workItem;
}
public boolean isInversionOfControl() {
// TODO
return false;
}
public void internalTrigger(final NodeInstance from, String type) {
super.internalTrigger(from, type);
// TODO this should be included for ruleflow only, not for BPEL
// if (!Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
// throw new IllegalArgumentException(
// "A WorkItemNode only accepts default incoming connections!");
// }
WorkItemNode workItemNode = getWorkItemNode();
createWorkItem(workItemNode);
if (workItemNode.isWaitForCompletion()) {
addWorkItemListener();
}
if (isInversionOfControl()) {
((ProcessInstance) getProcessInstance()).getKnowledgeRuntime()
.update(((ProcessInstance) getProcessInstance()).getKnowledgeRuntime().getFactHandle(this), this);
} else {
try {
((WorkItemManager) ((ProcessInstance) getProcessInstance())
.getKnowledgeRuntime().getWorkItemManager()).internalExecuteWorkItem(
(org.drools.process.instance.WorkItem) workItem);
} catch (WorkItemHandlerNotFoundException wihnfe){
getProcessInstance().setState( ProcessInstance.STATE_ABORTED );
throw wihnfe;
}
}
if (!workItemNode.isWaitForCompletion()) {
triggerCompleted();
}
this.workItemId = workItem.getId();
}
protected WorkItem createWorkItem(WorkItemNode workItemNode) {
Work work = workItemNode.getWork();
workItem = new WorkItemImpl();
((WorkItem) workItem).setName(work.getName());
((WorkItem) workItem).setProcessInstanceId(getProcessInstance().getId());
((WorkItem) workItem).setParameters(new HashMap<String, Object>(work.getParameters()));
for (Iterator<DataAssociation> iterator = workItemNode.getInAssociations().iterator(); iterator.hasNext(); ) {
DataAssociation association = iterator.next();
if(association.getAssignments() == null) {
Object parameterValue = null;
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getSources().get(0));
if (variableScopeInstance != null) {
parameterValue = variableScopeInstance.getVariable(association.getSources().get(0));
} else {
try {
parameterValue = MVEL.eval(association.getSources().get(0), new NodeInstanceResolverFactory(this));
} catch (Throwable t) {
System.err.println("Could not find variable scope for variable " + association.getSources().get(0));
System.err.println("when trying to execute Work Item " + work.getName());
System.err.println("Continuing without setting parameter.");
throw new RuntimeException("Could not find variable scope for variable " + association.getSources().get(0));
}
}
if (parameterValue != null) {
((WorkItem) workItem).setParameter(association.getTarget(), parameterValue);
}
}
else {
String source = association.getSources().get(0);
String target = association.getTarget();
try {
for(Iterator<Assignment> it = association.getAssignments().iterator(); it.hasNext(); ) {
handleAssignment(it.next(), source, target, true);
}
}
catch(XPathExpressionException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (DOMException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (TransformerException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
for (Map.Entry<String, Object> entry: workItem.getParameters().entrySet()) {
if (entry.getValue() instanceof String) {
String s = (String) entry.getValue();
Map<String, String> replacements = new HashMap<String, String>();
Matcher matcher = PARAMETER_MATCHER.matcher(s);
while (matcher.find()) {
String paramName = matcher.group(1);
if (replacements.get(paramName) == null) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
if (variableScopeInstance != null) {
Object variableValue = variableScopeInstance.getVariable(paramName);
String variableValueString = variableValue == null ? "" : variableValue.toString();
replacements.put(paramName, variableValueString);
} else {
try {
Object variableValue = MVEL.eval(paramName, new NodeInstanceResolverFactory(this));
String variableValueString = variableValue == null ? "" : variableValue.toString();
replacements.put(paramName, variableValueString);
} catch (Throwable t) {
System.err.println("Could not find variable scope for variable " + paramName);
System.err.println("when trying to replace variable in string for Work Item " + work.getName());
System.err.println("Continuing without setting parameter.");
}
}
}
}
for (Map.Entry<String, String> replacement: replacements.entrySet()) {
s = s.replace("#{" + replacement.getKey() + "}", replacement.getValue());
}
((WorkItem) workItem).setParameter(entry.getKey(), s);
}
}
return workItem;
}
private void handleAssignment(Assignment assignment, String sourceExpr, String targetExpr, boolean isInput) throws XPathExpressionException, DOMException, TransformerException, ParserConfigurationException {
String from = assignment.getFrom();
String to = assignment.getTo();
XPathFactory factory = XPathFactory.newInstance();
XPath xpathFrom = factory.newXPath();
XPathExpression exprFrom = xpathFrom.compile(from);
XPath xpathTo = factory.newXPath();
XPathExpression exprTo = xpathTo.compile(to);
Object target = null;
Object source = null;
if (isInput) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, sourceExpr);
source = variableScopeInstance.getVariable(sourceExpr);
target = ((WorkItem) workItem).getParameter(targetExpr);
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, targetExpr);
target = variableScopeInstance.getVariable(targetExpr);
source = ((WorkItem) workItem).getResult(sourceExpr);
}
if (_assignmentsLogger.isDebugEnabled()) {
//let's make noise about this assignment
_assignmentsLogger.debug("========== ASSIGN ==========");
- _assignmentsLogger.debug("Assignment between '" + from + "' and '" + to + "'");
+ _assignmentsLogger.debug("Assignment between '" + from + "' with '"+ sourceExpr +"' and '" + to + "' with '" + targetExpr +"'");
_assignmentsLogger.debug("========== SOURCE ==========");
- _assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) source));
+ if (source instanceof org.w3c.dom.Node) {
+ _assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) source));
+ } else {
+ _assignmentsLogger.debug(String.valueOf(source));
+ }
_assignmentsLogger.debug("============================");
_assignmentsLogger.debug("========== TARGET ==========");
- _assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) target));
+ if (target instanceof org.w3c.dom.Node) {
+ _assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) target));
+ } else {
+ _assignmentsLogger.debug(String.valueOf(target));
+ }
_assignmentsLogger.debug("============================");
}
Object targetElem = null;
XPATHExpressionModifier modifier = new XPATHExpressionModifier();
// modify the tree, returning the root node
target = modifier.insertMissingData(to, (org.w3c.dom.Node) target);
// now pick the leaf for this operation
if (target != null) {
org.w3c.dom.Node parent = null;
parent = ((org.w3c.dom.Node) target).getParentNode();
targetElem = exprTo.evaluate(parent, XPathConstants.NODE);
if (targetElem == null) {
throw new RuntimeException("Nothing was selected by the to expression " + to + " on " + targetExpr);
}
}
NodeList nl = null;
if (source instanceof org.w3c.dom.Node) {
nl = (NodeList) exprFrom.evaluate(source, XPathConstants.NODESET);
} else if (source instanceof String) {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
//quirky: create a temporary element, use its nodelist
Element temp = doc.createElementNS(null, "temp");
temp.appendChild(doc.createTextNode((String) source));
nl = temp.getChildNodes();
} else if (source == null) {
// don't throw errors yet ?
throw new RuntimeException("Source value was null for source " + sourceExpr);
}
if (nl.getLength() == 0) {
throw new RuntimeException("Nothing was selected by the from expression " + from + " on " + sourceExpr);
}
for (int i = 0 ; i < nl.getLength(); i++) {
if (!(targetElem instanceof org.w3c.dom.Node)) {
if (nl.item(i) instanceof Attr) {
targetElem = ((Attr) nl.item(i)).getValue();
} else if (nl.item(i) instanceof Text) {
targetElem = ((Text) nl.item(i)).getWholeText();
} else {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
targetElem = doc.importNode(nl.item(i), true);
}
target = targetElem;
} else {
org.w3c.dom.Node n = ((org.w3c.dom.Node) targetElem).getOwnerDocument().importNode(nl.item(i), true);
if (n instanceof Attr) {
((Element) targetElem).setAttributeNode((Attr) n);
} else {
((org.w3c.dom.Node) targetElem).appendChild(n);
}
}
}
if (isInput) {
((WorkItem) workItem).setParameter(targetExpr, target);
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, targetExpr);
variableScopeInstance.setVariable(targetExpr, target);
}
}
public void triggerCompleted(WorkItem workItem) {
this.workItem = workItem;
WorkItemNode workItemNode = getWorkItemNode();
if (workItemNode != null) {
for (Iterator<DataAssociation> iterator = getWorkItemNode().getOutAssociations().iterator(); iterator.hasNext(); ) {
DataAssociation association = iterator.next();
if(association.getAssignments() == null) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getTarget());
if (variableScopeInstance != null) {
Object value = workItem.getResult(association.getSources().get(0));
if (value == null) {
try {
value = MVEL.eval(association.getSources().get(0), new WorkItemResolverFactory(workItem));
} catch (Throwable t) {
_logger.error(t.getMessage(), t);
}
}
variableScopeInstance.setVariable(association.getTarget(), value);
} else {
if (_logger.isDebugEnabled()) {
_logger.debug("Could not find variable scope for variable " + association.getTarget());
_logger.debug("when trying to complete Work Item " + workItem.getName());
_logger.debug("Continuing without setting variable.");
}
}
} else {
String source = association.getSources().get(0);
String target = association.getTarget();
try {
for (Iterator<Assignment> it = association.getAssignments().iterator(); it.hasNext(); ) {
handleAssignment(it.next(), source, target, false);
}
} catch (Exception e) {
_logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
}
}
if (isInversionOfControl()) {
KnowledgeRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
kruntime.update(kruntime.getFactHandle(this), this);
} else {
triggerCompleted();
}
}
public void cancel() {
WorkItem workItem = getWorkItem();
if (workItem != null &&
workItem.getState() != WorkItem.COMPLETED &&
workItem.getState() != WorkItem.ABORTED) {
try {
((WorkItemManager) ((ProcessInstance) getProcessInstance())
.getKnowledgeRuntime().getWorkItemManager()).internalAbortWorkItem(workItemId);
} catch (WorkItemHandlerNotFoundException wihnfe){
getProcessInstance().setState( ProcessInstance.STATE_ABORTED );
throw wihnfe;
}
}
super.cancel();
}
public void addEventListeners() {
super.addEventListeners();
addWorkItemListener();
}
private void addWorkItemListener() {
getProcessInstance().addEventListener("workItemCompleted", this, false);
getProcessInstance().addEventListener("workItemAborted", this, false);
}
public void removeEventListeners() {
super.removeEventListeners();
getProcessInstance().removeEventListener("workItemCompleted", this, false);
getProcessInstance().removeEventListener("workItemAborted", this, false);
}
public void signalEvent(String type, Object event) {
if ("workItemCompleted".equals(type)) {
workItemCompleted((WorkItem) event);
} else if ("workItemAborted".equals(type)) {
workItemAborted((WorkItem) event);
} else {
super.signalEvent(type, event);
}
}
public String[] getEventTypes() {
return new String[] { "workItemCompleted" };
}
public void workItemAborted(WorkItem workItem) {
if ( workItemId == workItem.getId()
|| ( workItemId == -1 && getWorkItem().getId() == workItem.getId()) ) {
removeEventListeners();
triggerCompleted(workItem);
}
}
public void workItemCompleted(WorkItem workItem) {
if ( workItemId == workItem.getId()
|| ( workItemId == -1 && getWorkItem().getId() == workItem.getId()) ) {
removeEventListeners();
triggerCompleted(workItem);
}
}
public String getNodeName() {
Node node = getNode();
if (node == null) {
String nodeName = "[Dynamic]";
WorkItem workItem = getWorkItem();
if (workItem != null) {
nodeName += " " + workItem.getParameter("TaskName");
}
return nodeName;
}
return super.getNodeName();
}
}
| false | true | private void handleAssignment(Assignment assignment, String sourceExpr, String targetExpr, boolean isInput) throws XPathExpressionException, DOMException, TransformerException, ParserConfigurationException {
String from = assignment.getFrom();
String to = assignment.getTo();
XPathFactory factory = XPathFactory.newInstance();
XPath xpathFrom = factory.newXPath();
XPathExpression exprFrom = xpathFrom.compile(from);
XPath xpathTo = factory.newXPath();
XPathExpression exprTo = xpathTo.compile(to);
Object target = null;
Object source = null;
if (isInput) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, sourceExpr);
source = variableScopeInstance.getVariable(sourceExpr);
target = ((WorkItem) workItem).getParameter(targetExpr);
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, targetExpr);
target = variableScopeInstance.getVariable(targetExpr);
source = ((WorkItem) workItem).getResult(sourceExpr);
}
if (_assignmentsLogger.isDebugEnabled()) {
//let's make noise about this assignment
_assignmentsLogger.debug("========== ASSIGN ==========");
_assignmentsLogger.debug("Assignment between '" + from + "' and '" + to + "'");
_assignmentsLogger.debug("========== SOURCE ==========");
_assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) source));
_assignmentsLogger.debug("============================");
_assignmentsLogger.debug("========== TARGET ==========");
_assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) target));
_assignmentsLogger.debug("============================");
}
Object targetElem = null;
XPATHExpressionModifier modifier = new XPATHExpressionModifier();
// modify the tree, returning the root node
target = modifier.insertMissingData(to, (org.w3c.dom.Node) target);
// now pick the leaf for this operation
if (target != null) {
org.w3c.dom.Node parent = null;
parent = ((org.w3c.dom.Node) target).getParentNode();
targetElem = exprTo.evaluate(parent, XPathConstants.NODE);
if (targetElem == null) {
throw new RuntimeException("Nothing was selected by the to expression " + to + " on " + targetExpr);
}
}
NodeList nl = null;
if (source instanceof org.w3c.dom.Node) {
nl = (NodeList) exprFrom.evaluate(source, XPathConstants.NODESET);
} else if (source instanceof String) {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
//quirky: create a temporary element, use its nodelist
Element temp = doc.createElementNS(null, "temp");
temp.appendChild(doc.createTextNode((String) source));
nl = temp.getChildNodes();
} else if (source == null) {
// don't throw errors yet ?
throw new RuntimeException("Source value was null for source " + sourceExpr);
}
if (nl.getLength() == 0) {
throw new RuntimeException("Nothing was selected by the from expression " + from + " on " + sourceExpr);
}
for (int i = 0 ; i < nl.getLength(); i++) {
if (!(targetElem instanceof org.w3c.dom.Node)) {
if (nl.item(i) instanceof Attr) {
targetElem = ((Attr) nl.item(i)).getValue();
} else if (nl.item(i) instanceof Text) {
targetElem = ((Text) nl.item(i)).getWholeText();
} else {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
targetElem = doc.importNode(nl.item(i), true);
}
target = targetElem;
} else {
org.w3c.dom.Node n = ((org.w3c.dom.Node) targetElem).getOwnerDocument().importNode(nl.item(i), true);
if (n instanceof Attr) {
((Element) targetElem).setAttributeNode((Attr) n);
} else {
((org.w3c.dom.Node) targetElem).appendChild(n);
}
}
}
if (isInput) {
((WorkItem) workItem).setParameter(targetExpr, target);
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, targetExpr);
variableScopeInstance.setVariable(targetExpr, target);
}
}
| private void handleAssignment(Assignment assignment, String sourceExpr, String targetExpr, boolean isInput) throws XPathExpressionException, DOMException, TransformerException, ParserConfigurationException {
String from = assignment.getFrom();
String to = assignment.getTo();
XPathFactory factory = XPathFactory.newInstance();
XPath xpathFrom = factory.newXPath();
XPathExpression exprFrom = xpathFrom.compile(from);
XPath xpathTo = factory.newXPath();
XPathExpression exprTo = xpathTo.compile(to);
Object target = null;
Object source = null;
if (isInput) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, sourceExpr);
source = variableScopeInstance.getVariable(sourceExpr);
target = ((WorkItem) workItem).getParameter(targetExpr);
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, targetExpr);
target = variableScopeInstance.getVariable(targetExpr);
source = ((WorkItem) workItem).getResult(sourceExpr);
}
if (_assignmentsLogger.isDebugEnabled()) {
//let's make noise about this assignment
_assignmentsLogger.debug("========== ASSIGN ==========");
_assignmentsLogger.debug("Assignment between '" + from + "' with '"+ sourceExpr +"' and '" + to + "' with '" + targetExpr +"'");
_assignmentsLogger.debug("========== SOURCE ==========");
if (source instanceof org.w3c.dom.Node) {
_assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) source));
} else {
_assignmentsLogger.debug(String.valueOf(source));
}
_assignmentsLogger.debug("============================");
_assignmentsLogger.debug("========== TARGET ==========");
if (target instanceof org.w3c.dom.Node) {
_assignmentsLogger.debug(serializeXML((org.w3c.dom.Node) target));
} else {
_assignmentsLogger.debug(String.valueOf(target));
}
_assignmentsLogger.debug("============================");
}
Object targetElem = null;
XPATHExpressionModifier modifier = new XPATHExpressionModifier();
// modify the tree, returning the root node
target = modifier.insertMissingData(to, (org.w3c.dom.Node) target);
// now pick the leaf for this operation
if (target != null) {
org.w3c.dom.Node parent = null;
parent = ((org.w3c.dom.Node) target).getParentNode();
targetElem = exprTo.evaluate(parent, XPathConstants.NODE);
if (targetElem == null) {
throw new RuntimeException("Nothing was selected by the to expression " + to + " on " + targetExpr);
}
}
NodeList nl = null;
if (source instanceof org.w3c.dom.Node) {
nl = (NodeList) exprFrom.evaluate(source, XPathConstants.NODESET);
} else if (source instanceof String) {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
//quirky: create a temporary element, use its nodelist
Element temp = doc.createElementNS(null, "temp");
temp.appendChild(doc.createTextNode((String) source));
nl = temp.getChildNodes();
} else if (source == null) {
// don't throw errors yet ?
throw new RuntimeException("Source value was null for source " + sourceExpr);
}
if (nl.getLength() == 0) {
throw new RuntimeException("Nothing was selected by the from expression " + from + " on " + sourceExpr);
}
for (int i = 0 ; i < nl.getLength(); i++) {
if (!(targetElem instanceof org.w3c.dom.Node)) {
if (nl.item(i) instanceof Attr) {
targetElem = ((Attr) nl.item(i)).getValue();
} else if (nl.item(i) instanceof Text) {
targetElem = ((Text) nl.item(i)).getWholeText();
} else {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
targetElem = doc.importNode(nl.item(i), true);
}
target = targetElem;
} else {
org.w3c.dom.Node n = ((org.w3c.dom.Node) targetElem).getOwnerDocument().importNode(nl.item(i), true);
if (n instanceof Attr) {
((Element) targetElem).setAttributeNode((Attr) n);
} else {
((org.w3c.dom.Node) targetElem).appendChild(n);
}
}
}
if (isInput) {
((WorkItem) workItem).setParameter(targetExpr, target);
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, targetExpr);
variableScopeInstance.setVariable(targetExpr, target);
}
}
|
diff --git a/src/com/neuron/trafikanten/views/realtime/RealtimeView.java b/src/com/neuron/trafikanten/views/realtime/RealtimeView.java
index 08a71e5..78ea25f 100644
--- a/src/com/neuron/trafikanten/views/realtime/RealtimeView.java
+++ b/src/com/neuron/trafikanten/views/realtime/RealtimeView.java
@@ -1,860 +1,860 @@
/**
* Copyright (C) 2009 Anders Aagaard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
*
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.neuron.trafikanten.views.realtime;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.neuron.trafikanten.HelperFunctions;
import com.neuron.trafikanten.R;
import com.neuron.trafikanten.dataProviders.DataProviderFactory;
import com.neuron.trafikanten.dataProviders.IDeviProvider;
import com.neuron.trafikanten.dataProviders.IRealtimeProvider;
import com.neuron.trafikanten.dataProviders.IDeviProvider.DeviProviderHandler;
import com.neuron.trafikanten.dataProviders.IRealtimeProvider.RealtimeProviderHandler;
import com.neuron.trafikanten.dataSets.DeviData;
import com.neuron.trafikanten.dataSets.RealtimeData;
import com.neuron.trafikanten.dataSets.StationData;
import com.neuron.trafikanten.hacks.StationIcons;
import com.neuron.trafikanten.notification.NotificationDialog;
import com.neuron.trafikanten.tasks.SelectDeviTask;
import com.neuron.trafikanten.tasks.ShowDeviTask;
public class RealtimeView extends ListActivity {
private static final String TAG = "Trafikanten-RealtimeView";
private static final String KEY_LAST_UPDATE = "lastUpdate";
public static final String KEY_DEVILIST = "devilist";
/*
* Options menu:
*/
private static final int REFRESH_ID = Menu.FIRST;
/*
* Context menu:
*/
private static final int NOTIFY_ID = Menu.FIRST;
private static final int DEVI_ID = Menu.FIRST + 1;
/*
* Dialogs
*/
private static final int DIALOG_NOTIFICATION = 1;
private int selectedId = 0;
/*
* Saved instance data
*/
// HACK STATIONICONS, this does not need to be public static
public static StationData station;
private RealtimeAdapter realtimeList;
private long lastUpdate;
private ArrayList<DeviData> deviItems;
/*
* UI
*/
private LinearLayout devi;
private TextView infoText;
/*
* Data providers
*/
private IRealtimeProvider realtimeProvider;
private IDeviProvider deviProvider;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
/*
* Setup view and adapter.
*/
setContentView(R.layout.realtime);
realtimeList = new RealtimeAdapter(this);
devi = (LinearLayout) findViewById(R.id.devi);
infoText = (TextView) findViewById(R.id.emptyText);
/*
* Load instance state
*/
if (savedInstanceState == null) {
Bundle bundle = getIntent().getExtras();
/*
* Most of the time we get a normal StationData.PARCELABLE, but shortcuts sends a simple bundle.
*/
if (bundle.containsKey(StationData.PARCELABLE)) {
station = getIntent().getParcelableExtra(StationData.PARCELABLE);
} else {
station = StationData.readSimpleBundle(bundle);
}
load();
} else {
station = savedInstanceState.getParcelable(StationData.PARCELABLE);
lastUpdate = savedInstanceState.getLong(KEY_LAST_UPDATE);
deviItems = savedInstanceState.getParcelableArrayList(KEY_DEVILIST);
realtimeList.loadInstanceState(savedInstanceState);
realtimeList.notifyDataSetChanged();
infoText.setVisibility(realtimeList.getCount() > 0 ? View.GONE : View.VISIBLE);
}
registerForContextMenu(getListView());
setListAdapter(realtimeList);
refreshTitle();
refreshDevi();
}
final Handler autoRefreshHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
refresh();
autoRefreshHandler.sendEmptyMessageDelayed(0, 10000);
return true;
}
});
/*
* Refreshes the title
*/
private void refreshTitle() {
long lastUpdateDiff = (System.currentTimeMillis() - lastUpdate) / HelperFunctions.SECOND;
if (lastUpdateDiff > 60) {
lastUpdateDiff = lastUpdateDiff / 60;
setTitle("Trafikanten - " + station.stopName + " (" + lastUpdateDiff + "m " + getText(R.string.old) + ")");
} else {
setTitle("Trafikanten - " + station.stopName);
}
}
/*
* Function for creating the default devi text, used both for line data and station data
* deviData can be null if data is StopVisitNote
*/
public static TextView createDefaultDeviText(final Activity context, final String title, final DeviData deviData, boolean station) {
TextView deviText = new TextView(context);
deviText.setText(title);
deviText.setSingleLine();
deviText.setPadding(4, 2, 26, 2);
if (station) {
deviText.setTextColor(Color.BLACK);
deviText.setBackgroundResource(R.drawable.skin_stasjonsdevi);
} else {
deviText.setTextColor(Color.rgb(250, 244, 0));
deviText.setBackgroundResource(R.drawable.skin_sanntiddevi);
}
deviText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new ShowDeviTask(context, deviData);
}
});
return deviText;
}
/*
* Refreshes station specific devi data.
*/
private void refreshDevi() {
if (deviItems == null || deviItems.size() == 0) {
/*
* Nothing to display
*/
devi.setVisibility(View.GONE);
} else {
/*
* Render devi information
*/
devi.setVisibility(View.VISIBLE);
devi.removeAllViews();
for (final DeviData deviData : deviItems) {
devi.addView(createDefaultDeviText(this, deviData.title, deviData, true), new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
}
}
}
/*
* Load data, variable used to prevent updating data set on every iteration.
*/
private void load() {
lastUpdate = System.currentTimeMillis();
setProgressBarIndeterminateVisibility(true);
if (realtimeProvider != null)
realtimeProvider.Stop();
if (deviProvider != null)
deviProvider.Stop();
realtimeList.clear();
realtimeList.notifyDataSetChanged();
realtimeList.itemsAddedWithoutNotify = 0;
realtimeProvider = DataProviderFactory.getRealtimeProvider(new RealtimeProviderHandler() {
@Override
public void onData(RealtimeData realtimeData) {
realtimeList.addItem(realtimeData);
realtimeList.itemsAddedWithoutNotify++;
if (realtimeList.itemsAddedWithoutNotify > 5) {
realtimeList.itemsAddedWithoutNotify = 0;
realtimeList.notifyDataSetChanged();
}
}
@Override
public void onError(Exception exception) {
Log.w(TAG,"onException " + exception);
infoText.setVisibility(View.VISIBLE);
if (exception.getClass().getSimpleName().equals("ParseException")) {
infoText.setText("" + getText(R.string.parseError) + ":" + "\n\n" + exception);
} else {
infoText.setText("" + getText(R.string.exception) + ":" + "\n\n" + exception);
}
setProgressBarIndeterminateVisibility(false);
}
@Override
public void onFinished() {
refreshTitle();
setProgressBarIndeterminateVisibility(false);
/*
* Show info text if view is empty
*/
infoText.setVisibility(realtimeList.getCount() > 0 ? View.GONE : View.VISIBLE);
if (realtimeList.itemsAddedWithoutNotify > 0) {
realtimeList.itemsAddedWithoutNotify = 0;
realtimeList.notifyDataSetChanged();
}
realtimeProvider = null;
loadDevi();
}
});
realtimeProvider.Fetch(station.stationId);
}
/*
* Load devi data
*/
private void loadDevi() {
setProgressBarIndeterminateVisibility(true);
realtimeList.itemsAddedWithoutNotify = 0;
deviItems = new ArrayList<DeviData>();
deviProvider = DataProviderFactory.getDeviProvider(new DeviProviderHandler() {
@Override
public void onData(DeviData deviData) {
if (deviData.lines.size() > 0) {
/*
* Line specific data
*/
realtimeList.addDeviItem(deviData);
realtimeList.itemsAddedWithoutNotify++;
if (realtimeList.itemsAddedWithoutNotify > 5) {
realtimeList.itemsAddedWithoutNotify = 0;
realtimeList.notifyDataSetChanged();
}
} else {
/*
* Station specific data
*/
deviItems.add(deviData);
}
}
@Override
public void onError(Exception exception) {
Log.w(TAG,"onException " + exception);
Toast.makeText(RealtimeView.this, "" + getText(R.string.exception) + "\n" + exception, Toast.LENGTH_LONG).show();
setProgressBarIndeterminateVisibility(false);
}
@Override
public void onFinished() {
refreshDevi();
setProgressBarIndeterminateVisibility(false);
deviProvider = null;
if (realtimeList.itemsAddedWithoutNotify > 0) {
realtimeList.itemsAddedWithoutNotify = 0;
realtimeList.notifyDataSetChanged();
}
}
});
/*
* Create list of lines - first create lineList
*/
ArrayList<String> lineList = new ArrayList<String>();
{
final int count = realtimeList.getCount();
for (int i = 0; i < count; i++) {
final RealtimeData realtimeData = realtimeList.getItem(i);
if (!lineList.contains(realtimeData.line)) {
lineList.add(realtimeData.line);
}
}
}
/*
* Create list of lines - then merge it into a comma seperated list
*/
StringBuffer deviLines = new StringBuffer();
{
final int count = lineList.size();
deviLines.append(lineList.get(0));
for (int i = 1; i < count; i++) {
deviLines.append(",");
deviLines.append(lineList.get(i));
}
}
deviProvider.Fetch(station.stationId, deviLines.toString());
}
/*
* Options menu, visible on menu button.
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
final MenuItem myLocation = menu.add(0, REFRESH_ID, 0, R.string.refresh);
myLocation.setIcon(R.drawable.ic_menu_refresh);
return true;
}
/*
* Options menu item selected, options menu visible on menu button.
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case REFRESH_ID:
load();
break;
}
return super.onOptionsItemSelected(item);
}
/*
* Dialog creation
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_NOTIFICATION:
/*
* notify dialog
*/
return NotificationDialog.getDialog(this);
}
return super.onCreateDialog(id);
}
/*
* Load data into dialog
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
final RealtimeData realtimeData = (RealtimeData) realtimeList.getItem(selectedId);
final String notifyWith = realtimeData.line.equals(realtimeData.destination)
? realtimeData.line
: realtimeData.line + " " + realtimeData.destination;
NotificationDialog.setRealtimeData(realtimeData, station, notifyWith);
super.onPrepareDialog(id, dialog);
}
/*
* onCreate - Context menu is a popup from a longpress on a list item.
* @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final RealtimeData realtimeData = realtimeList.getItem(info.position);
menu.add(0, NOTIFY_ID, 0, R.string.alarm);
if (realtimeData.devi.size() > 0)
menu.add(0, DEVI_ID, 0, R.string.warnings);
}
/*
* onSelected - Context menu is a popup from a longpress on a list item.
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
selectedId = info.position;
switch(item.getItemId()) {
case NOTIFY_ID:
showDialog(DIALOG_NOTIFICATION);
return true;
case DEVI_ID:
final RealtimeData realtimeData = (RealtimeData) realtimeList.getItem(selectedId);
final ArrayList<DeviData> deviPopup = realtimeList.getDevi(realtimeData);
new SelectDeviTask(this, deviPopup);
}
return super.onContextItemSelected(item);
}
private void refresh() {
refreshTitle();
realtimeList.notifyDataSetChanged(); // force refreshing times.
}
/*
* Functions for dealing with program state.
*/
@Override
protected void onPause() {
super.onPause();
autoRefreshHandler.removeMessages(0);
}
@Override
protected void onResume() {
super.onResume();
refresh();
autoRefreshHandler.sendEmptyMessageDelayed(0, 10000);
}
@Override
public void finish() {
/*
* make sure background threads is properly killed off.
*/
if (realtimeProvider != null) {
realtimeProvider.Stop();
}
if (deviProvider != null) {
deviProvider.Stop();
}
super.finish();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(StationData.PARCELABLE, station);
outState.putLong(KEY_LAST_UPDATE, lastUpdate);
outState.putParcelableArrayList(KEY_DEVILIST, deviItems);
realtimeList.saveInstanceState(outState);
}
}
class RealtimePlatformList extends ArrayList<RealtimeData> implements Parcelable {
private static final long serialVersionUID = -8158771022676013360L;
public String platform;
public RealtimePlatformList(String platform) {
super();
this.platform = platform;
}
/*
* @see android.os.Parcelable
*/
@Override
public int describeContents() { return 0; }
/*
* Function for reading the parcel
*/
public RealtimePlatformList(Parcel in) {
platform = in.readString();
in.readList(this, RealtimeData.class.getClassLoader());
}
/*
* Writing current data to parcel.
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(platform);
out.writeList(this);
}
/*
* Used for bundle.getParcel
*/
public static final Parcelable.Creator<RealtimePlatformList> CREATOR = new Parcelable.Creator<RealtimePlatformList>() {
public RealtimePlatformList createFromParcel(Parcel in) {
return new RealtimePlatformList(in);
}
public RealtimePlatformList[] newArray(int size) {
return new RealtimePlatformList[size];
}
};
}
class RealtimeAdapter extends BaseAdapter {
public static final String KEY_REALTIMELIST = "realtimelist";
public static final String KEY_STATIONDEVILIST = "stationdevilist";
public static final String KEY_ITEMSSIZE = "devilistsize";
private LayoutInflater inflater;
private Typeface departuresTypeface;
/*
* Structure:
* platform ->
* line + destination ->
* RealtimeData
*/
private ArrayList<RealtimePlatformList> items = new ArrayList<RealtimePlatformList>();
private int itemsSize = 0; // Cached for performance, this is len(items) + len(item[0]) + len(item[1]) ...
public int itemsAddedWithoutNotify = 0; // List of items added during load without a .notifyDataUpdated
/*
* Devi data:
*/
private ArrayList<DeviData> deviItems = new ArrayList<DeviData>();
/*
* This variable is set by getItem, it indicates this station is the first of the current platform, so platform should be shown.
*/
private boolean renderPlatform = false;
private Activity activity;
public RealtimeAdapter(Activity activity) {
inflater = LayoutInflater.from(activity);
departuresTypeface = Typeface.createFromAsset(activity.getAssets(), "fonts/typewriter.ttf");
this.activity = activity;
}
/*
* Clearing the list
*/
public void clear() {
items.clear();
deviItems.clear();
itemsSize = 0;
}
/*
* Saving instance state
*/
public void saveInstanceState(Bundle outState) {
outState.putParcelableArrayList(KEY_STATIONDEVILIST, deviItems);
outState.putInt(KEY_ITEMSSIZE, itemsSize);
outState.putParcelableArrayList(KEY_REALTIMELIST, items);
}
/*
* Loading instance state
*/
public void loadInstanceState(Bundle inState) {
deviItems = inState.getParcelableArrayList(KEY_STATIONDEVILIST);
itemsSize = inState.getInt(KEY_ITEMSSIZE);
items = inState.getParcelableArrayList(KEY_REALTIMELIST);
}
/*
* Function to add devi data
* - This only cares about devi's linked to a line, station devi's are handled in main class.
*/
public void addDeviItem(DeviData item) {
int pos = deviItems.size();
boolean addDevi = false;
/*
* Scan and add the devi position index to all realtime data
*/
for (RealtimePlatformList realtimePlatformList : items) {
for (RealtimeData d : realtimePlatformList) {
if (item.lines.contains(d.line)) {
addDevi = true;
d.devi.add(pos);
}
}
}
if (addDevi) {
deviItems.add(item);
}
}
/*
* Get a list of devi's assosiated with a line
*/
public ArrayList<DeviData> getDevi(RealtimeData realtimeData) {
ArrayList<DeviData> result = new ArrayList<DeviData>();
for (Integer i : realtimeData.devi) {
result.add(deviItems.get(i));
}
return result;
}
/*
* Simple function that gets (or creates a new) platform in items
*/
public RealtimePlatformList getOrCreatePlatform(String platform) {
/*
* We cant deal with null platforms
*/
if (platform == null)
platform = "";
/*
* If the platform already exists in the database just return it
*/
for (RealtimePlatformList realtimePlatformList : items) {
if (realtimePlatformList.platform.equals(platform)) {
return realtimePlatformList;
}
}
/*
* No platform found, create new
*/
RealtimePlatformList realtimePlatformList = new RealtimePlatformList(platform);
/*
* We make sure the platform list is sorted the same way every time.
*/
int pos = 0;
for (; pos < items.size(); pos++) {
if (platform.compareTo(items.get(pos).platform) < 0) {
break;
}
}
/*
* Finally add it and return
*/
items.add(pos, realtimePlatformList);
return realtimePlatformList;
}
/*
* Adding an item puts it in the platform category, and compressed duplicate data to one entry.
*/
public void addItem(RealtimeData item) {
RealtimePlatformList realtimePlatformList = getOrCreatePlatform(item.departurePlatform);
for (RealtimeData d : realtimePlatformList) {
if (d.destination.equals(item.destination) && d.line.equals(item.line)) {
/*
* Data already exists, we add it to the arrival list and return
*/
d.addDeparture(item.expectedDeparture, item.realtime);
return;
}
}
/*
* Data does not exist, add it
*/
realtimePlatformList.add(item);
itemsSize++;
}
/*
* Standard android.widget.Adapter items, self explanatory.
*/
@Override
public int getCount() {
if (itemsAddedWithoutNotify > 0) {
itemsAddedWithoutNotify = 0;
notifyDataSetChanged(); // This is incase getCount is called between our data set updates, which triggers IllegalStateException, listView does a simple if (mItemCount != mAdapter.getCount()) {
}
return itemsSize;
}
@Override
public long getItemId(int pos) { return pos; }
@Override
public RealtimeData getItem(int pos) {
for (RealtimePlatformList realtimePlatformList : items) {
if (pos < realtimePlatformList.size()) {
if (pos == 0) {
renderPlatform = true;
} else {
renderPlatform = false;
}
return realtimePlatformList.get(pos);
} else {
pos = pos - realtimePlatformList.size();
}
}
return null;
}
/*
* Setup the view
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int pos, View convertView, ViewGroup arg2) {
/*
* Setup holder, for performance and readability.
*/
ViewHolder holder;
if (convertView == null) {
/*
* New view, inflate and setup holder.
*/
convertView = inflater.inflate(R.layout.realtime_list, null);
holder = new ViewHolder();
holder.platform = (TextView) convertView.findViewById(R.id.platform);
holder.line = (TextView) convertView.findViewById(R.id.line);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.destination = (TextView) convertView.findViewById(R.id.destination);
holder.departures = (TextView) convertView.findViewById(R.id.departures);
holder.departures.setTypeface(departuresTypeface);
holder.departures.setMovementMethod(ScrollingMovementMethod.getInstance());
holder.departures.setHorizontallyScrolling(true);
holder.departureInfo = (LinearLayout) convertView.findViewById(R.id.departureInfo);
/*
* Workaround for clickable bug, onListItemClick does not trigger at all if ScrollingMovementMethod is being used.
*/
{
final TableLayout tableLayout = (TableLayout) convertView.findViewById(R.id.tablelayout);
// can use tableLayout.setOnClickListener here as a workaround for click events.
tableLayout.setLongClickable(true);
}
convertView.setTag(holder);
} else {
/*
* Old view found, we can reuse that instead of inflating.
*/
holder = (ViewHolder) convertView.getTag();
}
/*
* Render data to view.
*/
final RealtimeData data = getItem(pos);
holder.departures.setText(data.renderDepartures(activity));
- holder.destination.setText(data.line);
+ holder.destination.setText(data.destination);
if (data.destination.equals(data.line)) {
holder.line.setVisibility(View.GONE);
} else {
holder.line.setText(data.line);
holder.line.setVisibility(View.VISIBLE);
}
if (renderPlatform && data.departurePlatform != null) {
holder.platform.setText("Platform " + data.departurePlatform);
holder.platform.setVisibility(View.VISIBLE);
} else {
holder.platform.setVisibility(View.GONE);
}
holder.icon.setImageResource(StationIcons.hackGetLineIcon(RealtimeView.station, data.line));
/*
* Setup devi
*/
if (data.devi.size() > 0 || data.stopVisitNote != null) {
holder.departureInfo.setVisibility(View.VISIBLE);
holder.departureInfo.removeAllViews();
if (data.stopVisitNote != null) {
/*
* Add stopvisitnote
*/
final TextView stopVisitNote = new TextView(activity);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
stopVisitNote.setText(data.stopVisitNote);
stopVisitNote.setSingleLine();
stopVisitNote.setPadding(4, 2, 6, 2);
stopVisitNote.setTextColor(Color.rgb(250, 244, 0));
stopVisitNote.setBackgroundResource(R.drawable.skin_sanntid_avganger);
stopVisitNote.setMovementMethod(ScrollingMovementMethod.getInstance());
stopVisitNote.setHorizontallyScrolling(true);
holder.departureInfo.addView(stopVisitNote, layoutParams);
}
for (Integer i : data.devi) {
/*
* Add all devi items.
*/
final DeviData devi = deviItems.get(i);
holder.departureInfo.addView(RealtimeView.createDefaultDeviText(activity, devi.title, devi, false), new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
} else {
holder.departureInfo.setVisibility(View.GONE);
}
return convertView;
}
/*
* Class for caching the view.
*/
static class ViewHolder {
TextView platform;
TextView line;
TextView destination;
ImageView icon;
TextView departures;
LinearLayout departureInfo;
}
};
| true | true | public int getCount() {
if (itemsAddedWithoutNotify > 0) {
itemsAddedWithoutNotify = 0;
notifyDataSetChanged(); // This is incase getCount is called between our data set updates, which triggers IllegalStateException, listView does a simple if (mItemCount != mAdapter.getCount()) {
}
return itemsSize;
}
@Override
public long getItemId(int pos) { return pos; }
@Override
public RealtimeData getItem(int pos) {
for (RealtimePlatformList realtimePlatformList : items) {
if (pos < realtimePlatformList.size()) {
if (pos == 0) {
renderPlatform = true;
} else {
renderPlatform = false;
}
return realtimePlatformList.get(pos);
} else {
pos = pos - realtimePlatformList.size();
}
}
return null;
}
/*
* Setup the view
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int pos, View convertView, ViewGroup arg2) {
/*
* Setup holder, for performance and readability.
*/
ViewHolder holder;
if (convertView == null) {
/*
* New view, inflate and setup holder.
*/
convertView = inflater.inflate(R.layout.realtime_list, null);
holder = new ViewHolder();
holder.platform = (TextView) convertView.findViewById(R.id.platform);
holder.line = (TextView) convertView.findViewById(R.id.line);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.destination = (TextView) convertView.findViewById(R.id.destination);
holder.departures = (TextView) convertView.findViewById(R.id.departures);
holder.departures.setTypeface(departuresTypeface);
holder.departures.setMovementMethod(ScrollingMovementMethod.getInstance());
holder.departures.setHorizontallyScrolling(true);
holder.departureInfo = (LinearLayout) convertView.findViewById(R.id.departureInfo);
/*
* Workaround for clickable bug, onListItemClick does not trigger at all if ScrollingMovementMethod is being used.
*/
{
final TableLayout tableLayout = (TableLayout) convertView.findViewById(R.id.tablelayout);
// can use tableLayout.setOnClickListener here as a workaround for click events.
tableLayout.setLongClickable(true);
}
convertView.setTag(holder);
} else {
/*
* Old view found, we can reuse that instead of inflating.
*/
holder = (ViewHolder) convertView.getTag();
}
/*
* Render data to view.
*/
final RealtimeData data = getItem(pos);
holder.departures.setText(data.renderDepartures(activity));
holder.destination.setText(data.line);
if (data.destination.equals(data.line)) {
holder.line.setVisibility(View.GONE);
} else {
holder.line.setText(data.line);
holder.line.setVisibility(View.VISIBLE);
}
if (renderPlatform && data.departurePlatform != null) {
holder.platform.setText("Platform " + data.departurePlatform);
holder.platform.setVisibility(View.VISIBLE);
} else {
holder.platform.setVisibility(View.GONE);
}
holder.icon.setImageResource(StationIcons.hackGetLineIcon(RealtimeView.station, data.line));
/*
* Setup devi
*/
if (data.devi.size() > 0 || data.stopVisitNote != null) {
holder.departureInfo.setVisibility(View.VISIBLE);
holder.departureInfo.removeAllViews();
if (data.stopVisitNote != null) {
/*
* Add stopvisitnote
*/
final TextView stopVisitNote = new TextView(activity);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
stopVisitNote.setText(data.stopVisitNote);
stopVisitNote.setSingleLine();
stopVisitNote.setPadding(4, 2, 6, 2);
stopVisitNote.setTextColor(Color.rgb(250, 244, 0));
stopVisitNote.setBackgroundResource(R.drawable.skin_sanntid_avganger);
stopVisitNote.setMovementMethod(ScrollingMovementMethod.getInstance());
stopVisitNote.setHorizontallyScrolling(true);
holder.departureInfo.addView(stopVisitNote, layoutParams);
}
for (Integer i : data.devi) {
/*
* Add all devi items.
*/
final DeviData devi = deviItems.get(i);
holder.departureInfo.addView(RealtimeView.createDefaultDeviText(activity, devi.title, devi, false), new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
} else {
holder.departureInfo.setVisibility(View.GONE);
}
return convertView;
}
/*
* Class for caching the view.
*/
static class ViewHolder {
TextView platform;
TextView line;
TextView destination;
ImageView icon;
TextView departures;
LinearLayout departureInfo;
}
};
| public int getCount() {
if (itemsAddedWithoutNotify > 0) {
itemsAddedWithoutNotify = 0;
notifyDataSetChanged(); // This is incase getCount is called between our data set updates, which triggers IllegalStateException, listView does a simple if (mItemCount != mAdapter.getCount()) {
}
return itemsSize;
}
@Override
public long getItemId(int pos) { return pos; }
@Override
public RealtimeData getItem(int pos) {
for (RealtimePlatformList realtimePlatformList : items) {
if (pos < realtimePlatformList.size()) {
if (pos == 0) {
renderPlatform = true;
} else {
renderPlatform = false;
}
return realtimePlatformList.get(pos);
} else {
pos = pos - realtimePlatformList.size();
}
}
return null;
}
/*
* Setup the view
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int pos, View convertView, ViewGroup arg2) {
/*
* Setup holder, for performance and readability.
*/
ViewHolder holder;
if (convertView == null) {
/*
* New view, inflate and setup holder.
*/
convertView = inflater.inflate(R.layout.realtime_list, null);
holder = new ViewHolder();
holder.platform = (TextView) convertView.findViewById(R.id.platform);
holder.line = (TextView) convertView.findViewById(R.id.line);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.destination = (TextView) convertView.findViewById(R.id.destination);
holder.departures = (TextView) convertView.findViewById(R.id.departures);
holder.departures.setTypeface(departuresTypeface);
holder.departures.setMovementMethod(ScrollingMovementMethod.getInstance());
holder.departures.setHorizontallyScrolling(true);
holder.departureInfo = (LinearLayout) convertView.findViewById(R.id.departureInfo);
/*
* Workaround for clickable bug, onListItemClick does not trigger at all if ScrollingMovementMethod is being used.
*/
{
final TableLayout tableLayout = (TableLayout) convertView.findViewById(R.id.tablelayout);
// can use tableLayout.setOnClickListener here as a workaround for click events.
tableLayout.setLongClickable(true);
}
convertView.setTag(holder);
} else {
/*
* Old view found, we can reuse that instead of inflating.
*/
holder = (ViewHolder) convertView.getTag();
}
/*
* Render data to view.
*/
final RealtimeData data = getItem(pos);
holder.departures.setText(data.renderDepartures(activity));
holder.destination.setText(data.destination);
if (data.destination.equals(data.line)) {
holder.line.setVisibility(View.GONE);
} else {
holder.line.setText(data.line);
holder.line.setVisibility(View.VISIBLE);
}
if (renderPlatform && data.departurePlatform != null) {
holder.platform.setText("Platform " + data.departurePlatform);
holder.platform.setVisibility(View.VISIBLE);
} else {
holder.platform.setVisibility(View.GONE);
}
holder.icon.setImageResource(StationIcons.hackGetLineIcon(RealtimeView.station, data.line));
/*
* Setup devi
*/
if (data.devi.size() > 0 || data.stopVisitNote != null) {
holder.departureInfo.setVisibility(View.VISIBLE);
holder.departureInfo.removeAllViews();
if (data.stopVisitNote != null) {
/*
* Add stopvisitnote
*/
final TextView stopVisitNote = new TextView(activity);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
stopVisitNote.setText(data.stopVisitNote);
stopVisitNote.setSingleLine();
stopVisitNote.setPadding(4, 2, 6, 2);
stopVisitNote.setTextColor(Color.rgb(250, 244, 0));
stopVisitNote.setBackgroundResource(R.drawable.skin_sanntid_avganger);
stopVisitNote.setMovementMethod(ScrollingMovementMethod.getInstance());
stopVisitNote.setHorizontallyScrolling(true);
holder.departureInfo.addView(stopVisitNote, layoutParams);
}
for (Integer i : data.devi) {
/*
* Add all devi items.
*/
final DeviData devi = deviItems.get(i);
holder.departureInfo.addView(RealtimeView.createDefaultDeviText(activity, devi.title, devi, false), new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
} else {
holder.departureInfo.setVisibility(View.GONE);
}
return convertView;
}
/*
* Class for caching the view.
*/
static class ViewHolder {
TextView platform;
TextView line;
TextView destination;
ImageView icon;
TextView departures;
LinearLayout departureInfo;
}
};
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/TextResourceGeneratorANTLRErrorListener.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/TextResourceGeneratorANTLRErrorListener.java
index 9a20cc92f..03cdd785f 100755
--- a/org.emftext.sdk/src/org/emftext/sdk/codegen/TextResourceGeneratorANTLRErrorListener.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/TextResourceGeneratorANTLRErrorListener.java
@@ -1,83 +1,84 @@
package org.emftext.sdk.codegen;
import org.antlr.tool.ANTLRErrorListener;
import org.antlr.tool.Message;
import org.antlr.tool.ToolMessage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
/**
* An error listener for the ANTLR Tool that reports errors by attaching diagnostics to
* the given resource (containing a concrete syntax model). This ensures that errors that
* occur when the generated grammar file is processed by the ANTLR Tool, are reported. However,
* since the file is generated, such errors should not occur.
*
* @author Jendrik Johannes (jj2)
*/
public class TextResourceGeneratorANTLRErrorListener implements ANTLRErrorListener {
protected Resource csResource;
public TextResourceGeneratorANTLRErrorListener(Resource csResource) {
this.csResource = csResource;
}
public void error(Message msg) {
csResource.getErrors().add(produceDiagnostic(msg));
}
public void error(ToolMessage msg) {
csResource.getErrors().add(produceDiagnostic(msg));
}
public void info(String msg) {
csResource.getWarnings().add(produceDiagnostic(msg));
}
public void warning(Message msg) {
csResource.getWarnings().add(produceDiagnostic(msg));
}
private Diagnostic produceDiagnostic(Message msg) {
return produceDiagnostic(msg + "");
}
/**
* Produces a diagnostic that can be attached to a resource.
* The line and column information will be removed from the
* given message, since they only apply to the generated file
* and not the concrete syntax model itself.
*
* @param msg Message from the ANTLR Tool
* @return the diagnostic
*/
private Diagnostic produceDiagnostic(String msg) {
msg = msg.substring(msg.indexOf(":") + 1);
msg = msg.substring(msg.indexOf(":") + 1);
msg = msg.substring(msg.indexOf(":") + 2);
msg = msg.toString();
- final String text = msg.substring(msg.indexOf(":") + 1);
+ String text = msg.substring(msg.indexOf(":") + 1);
+ final String cleanText = text.replace("\n", "").replace("\r", "");
Diagnostic diagnostic = new Diagnostic() {
public int getColumn() {
return 0;
}
public int getLine() {
return 0;
}
public String getLocation() {
return csResource.getURI().toString();
}
public String getMessage() {
- return text;
+ return cleanText;
}
};
return diagnostic;
}
}
| false | true | private Diagnostic produceDiagnostic(String msg) {
msg = msg.substring(msg.indexOf(":") + 1);
msg = msg.substring(msg.indexOf(":") + 1);
msg = msg.substring(msg.indexOf(":") + 2);
msg = msg.toString();
final String text = msg.substring(msg.indexOf(":") + 1);
Diagnostic diagnostic = new Diagnostic() {
public int getColumn() {
return 0;
}
public int getLine() {
return 0;
}
public String getLocation() {
return csResource.getURI().toString();
}
public String getMessage() {
return text;
}
};
return diagnostic;
}
| private Diagnostic produceDiagnostic(String msg) {
msg = msg.substring(msg.indexOf(":") + 1);
msg = msg.substring(msg.indexOf(":") + 1);
msg = msg.substring(msg.indexOf(":") + 2);
msg = msg.toString();
String text = msg.substring(msg.indexOf(":") + 1);
final String cleanText = text.replace("\n", "").replace("\r", "");
Diagnostic diagnostic = new Diagnostic() {
public int getColumn() {
return 0;
}
public int getLine() {
return 0;
}
public String getLocation() {
return csResource.getURI().toString();
}
public String getMessage() {
return cleanText;
}
};
return diagnostic;
}
|
diff --git a/src/classes/share/javax/media/j3d/OrientedShape3DRetained.java b/src/classes/share/javax/media/j3d/OrientedShape3DRetained.java
index 6db249d..1e338ba 100644
--- a/src/classes/share/javax/media/j3d/OrientedShape3DRetained.java
+++ b/src/classes/share/javax/media/j3d/OrientedShape3DRetained.java
@@ -1,611 +1,611 @@
/*
* $RCSfile$
*
* Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* $Revision$
* $Date$
* $State$
*/
package javax.media.j3d;
import javax.vecmath.*;
import java.util.ArrayList;
class OrientedShape3DRetained extends Shape3DRetained {
static final int ALIGNMENT_CHANGED = LAST_DEFINED_BIT << 1;
static final int AXIS_CHANGED = LAST_DEFINED_BIT << 2;
static final int ROTATION_CHANGED = LAST_DEFINED_BIT << 3;
static final int CONSTANT_SCALE_CHANGED = LAST_DEFINED_BIT << 4;
static final int SCALE_FACTOR_CHANGED = LAST_DEFINED_BIT << 5;
int mode = OrientedShape3D.ROTATE_ABOUT_AXIS;
// Axis about which to rotate.
Vector3f axis = new Vector3f(0.0f, 1.0f, 0.0f);
Point3f rotationPoint = new Point3f(0.0f, 0.0f, 1.0f);
private Vector3d nAxis = new Vector3d(0.0, 1.0, 0.0); // normalized axis
// reused temporaries
private Point3d viewPosition = new Point3d();
private Point3d yUpPoint = new Point3d();
private Vector3d eyeVec = new Vector3d();
private Vector3d yUp = new Vector3d();
private Vector3d zAxis = new Vector3d();
private Vector3d yAxis = new Vector3d();
private Vector3d vector = new Vector3d();
private AxisAngle4d aa = new AxisAngle4d();
private Transform3D xform = new Transform3D(); // used several times
private Transform3D zRotate = new Transform3D();
// For scale invariant mode
boolean constantScale = false;
double scaleFactor = 1.0;
// Frequently used variables for scale invariant computation
// Left and right Vworld to Clip coordinates transforms
private Transform3D left_xform = new Transform3D();
private Transform3D right_xform = new Transform3D();
// Transform for scaling the OrientedShape3D to correct for
// perspective foreshortening
Transform3D scaleXform = new Transform3D();
// Variables for converting between clip to local world coords
private Vector4d im_vec[] = {new Vector4d(), new Vector4d()};
private Vector4d lvec = new Vector4d();
boolean orientedTransformDirty = true;
Transform3D[] orientedTransforms = new Transform3D[1];
static final double EPSILON = 1.0e-6;
/**
* Constructs a OrientedShape3D node with default parameters.
* The default values are as follows:
* <ul>
* alignment mode : ROTATE_ABOUT_AXIS<br>
* alignment axis : Y-axis (0,1,0)<br>
* rotation point : (0,0,1)<br>
*</ul>
*/
public OrientedShape3DRetained() {
super();
this.nodeType = NodeRetained.ORIENTEDSHAPE3D;
}
// initializes alignment mode
void initAlignmentMode(int mode) {
this.mode = mode;
}
/**
* Sets the alignment mode.
* @param mode one of: ROTATE_ABOUT_AXIS or ROTATE_ABOUT_POINT
*/
void setAlignmentMode(int mode) {
if (this.mode != mode) {
initAlignmentMode(mode);
sendChangedMessage(ALIGNMENT_CHANGED, new Integer(mode));
}
}
/**
* Retrieves the alignment mode.
* @return one of: ROTATE_ABOUT_AXIS or ROTATE_ABOUT_POINT
*/
int getAlignmentMode() {
return(mode);
}
// initializes alignment axis
void initAlignmentAxis(Vector3f axis) {
initAlignmentAxis(axis.x, axis.y, axis.z);
}
// initializes alignment axis
void initAlignmentAxis(float x, float y, float z) {
this.axis.set(x,y,z);
double invMag;
invMag = 1.0/Math.sqrt(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z);
nAxis.x = (double)axis.x*invMag;
nAxis.y = (double)axis.y*invMag;
nAxis.z = (double)axis.z*invMag;
}
/**
* Sets the new alignment axis. This is the ray about which this
* OrientedShape3D rotates when the mode is ROTATE_ABOUT_AXIS.
* @param axis the new alignment axis
*/
void setAlignmentAxis(Vector3f axis) {
setAlignmentAxis(axis.x, axis.y, axis.z);
}
/**
* Sets the new alignment axis. This is the ray about which this
* OrientedShape3D rotates when the mode is ROTATE_ABOUT_AXIS.
* @param x the x component of the alignment axis
* @param y the y component of the alignment axis
* @param z the z component of the alignment axis
*/
void setAlignmentAxis(float x, float y, float z) {
initAlignmentAxis(x,y,z);
if (mode == OrientedShape3D.ROTATE_ABOUT_AXIS) {
sendChangedMessage(AXIS_CHANGED, new Vector3f(x,y,z));
}
}
/**
* Retrieves the alignment axis of this OrientedShape3D node,
* and copies it into the specified vector.
* @param axis the vector that will contain the alignment axis
*/
void getAlignmentAxis(Vector3f axis) {
axis.set(this.axis);
}
// initializes rotation point
void initRotationPoint(Point3f point) {
rotationPoint.set(point);
}
// initializes rotation point
void initRotationPoint(float x, float y, float z) {
rotationPoint.set(x,y,z);
}
/**
* Sets the new rotation point. This is the point about which the
* OrientedShape3D rotates when the mode is ROTATE_ABOUT_POINT.
* @param point the new rotation point
*/
void setRotationPoint(Point3f point) {
setRotationPoint(point.x, point.y, point.z);
}
/**
* Sets the new rotation point. This is the point about which the
* OrientedShape3D rotates when the mode is ROTATE_ABOUT_POINT.
* @param x the x component of the rotation point
* @param y the y component of the rotation point
* @param z the z component of the rotation point
*/
void setRotationPoint(float x, float y, float z) {
initRotationPoint(x,y,z);
if (mode == OrientedShape3D.ROTATE_ABOUT_POINT) {
sendChangedMessage(ROTATION_CHANGED, new Point3f(x,y,z));
}
}
/**
* Retrieves the rotation point of this OrientedShape3D node,
* and copies it into the specified vector.
* @param axis the point that will contain the rotation point
*/
void getRotationPoint(Point3f point) {
point.set(rotationPoint);
}
void setConstantScaleEnable(boolean enable) {
if(constantScale != enable) {
initConstantScaleEnable(enable);
sendChangedMessage(CONSTANT_SCALE_CHANGED, new Boolean(enable));
}
}
boolean getConstantScaleEnable() {
return constantScale;
}
void initConstantScaleEnable(boolean cons_scale) {
constantScale = cons_scale;
}
void setScale(double scale) {
initScale(scale);
if(constantScale)
sendChangedMessage(SCALE_FACTOR_CHANGED, new Double(scale));
}
void initScale(double scale) {
scaleFactor = scale;
}
double getScale() {
return scaleFactor;
}
void sendChangedMessage(int component, Object attr) {
J3dMessage changeMessage = new J3dMessage();
changeMessage.type = J3dMessage.ORIENTEDSHAPE3D_CHANGED;
changeMessage.threads = targetThreads ;
changeMessage.universe = universe;
changeMessage.args[0] = getGeomAtomsArray(mirrorShape3D);
changeMessage.args[1] = new Integer(component);
changeMessage.args[2] = attr;
OrientedShape3DRetained[] o3dArr =
new OrientedShape3DRetained[mirrorShape3D.size()];
mirrorShape3D.toArray(o3dArr);
changeMessage.args[3] = o3dArr;
changeMessage.args[4] = this;
VirtualUniverse.mc.processMessage(changeMessage);
}
void updateImmediateMirrorObject(Object[] args) {
int component = ((Integer)args[1]).intValue();
if ((component & (ALIGNMENT_CHANGED |
AXIS_CHANGED |
ROTATION_CHANGED |
CONSTANT_SCALE_CHANGED |
SCALE_FACTOR_CHANGED)) != 0) {
OrientedShape3DRetained[] msArr = (OrientedShape3DRetained[])args[3];
Object obj = args[2];
if ((component & ALIGNMENT_CHANGED) != 0) {
int mode = ((Integer)obj).intValue();
for (int i=0; i< msArr.length; i++) {
msArr[i].initAlignmentMode(mode);
}
}
else if ((component & AXIS_CHANGED) != 0) {
Vector3f axis =(Vector3f) obj;
for (int i=0; i< msArr.length; i++) {
msArr[i].initAlignmentAxis(axis);
}
}
else if ((component & ROTATION_CHANGED) != 0) {
Point3f point =(Point3f) obj;
for (int i=0; i< msArr.length; i++) {
msArr[i].initRotationPoint(point);
}
}
else if((component & CONSTANT_SCALE_CHANGED) != 0) {
boolean bool = ((Boolean)obj).booleanValue();
for (int i=0; i< msArr.length; i++) {
msArr[i].initConstantScaleEnable(bool);
}
}
else if((component & SCALE_FACTOR_CHANGED) != 0) {
double scale = ((Double)obj).doubleValue();
for (int i=0; i< msArr.length; i++) {
msArr[i].initScale(scale);
}
}
}
else {
super.updateImmediateMirrorObject(args);
}
}
Transform3D getOrientedTransform(int viewIndex) {
synchronized(orientedTransforms) {
if (viewIndex >= orientedTransforms.length) {
Transform3D xform = new Transform3D();
Transform3D[] newList = new Transform3D[viewIndex+1];
for (int i = 0; i < orientedTransforms.length; i++) {
newList[i] = orientedTransforms[i];
}
newList[viewIndex] = xform;
orientedTransforms = newList;
}
else {
if (orientedTransforms[viewIndex] == null) {
orientedTransforms[viewIndex] = new Transform3D();
}
}
}
return orientedTransforms[viewIndex];
}
// called on the parent object
// Should be synchronized so that the user thread does not modify the
// OrientedShape3D params while computing the transform
synchronized void updateOrientedTransform(Canvas3D canvas, int viewIndex) {
double angle = 0.0;
double sign;
boolean status;
Transform3D orientedxform = getOrientedTransform(viewIndex);
// get viewplatforms's location in virutal world
if (mode == OrientedShape3D.ROTATE_ABOUT_AXIS) { // rotate about axis
canvas.getCenterEyeInImagePlate(viewPosition);
canvas.getImagePlateToVworld(xform); // xform is imagePlateToLocal
xform.transform(viewPosition);
// get billboard's transform
xform.set(getCurrentLocalToVworld());
xform.invert(); // xform is now vWorldToLocal
// transform the eye position into the billboard's coordinate system
xform.transform(viewPosition);
// eyeVec is a vector from the local origin to the eye pt in local
eyeVec.set(viewPosition);
eyeVec.normalize();
// project the eye into the rotation plane
status = projectToPlane(eyeVec, nAxis);
if (status) {
// project the z axis into the rotation plane
zAxis.x = 0.0;
zAxis.y = 0.0;
zAxis.z = 1.0;
status = projectToPlane(zAxis, nAxis);
}
if (status) {
// compute the sign of the angle by checking if the cross product
// of the two vectors is in the same direction as the normal axis
vector.cross(eyeVec, zAxis);
if (vector.dot(nAxis) > 0.0) {
sign = 1.0;
} else {
sign = -1.0;
}
// compute the angle between the projected eye vector and the
// projected z
double dot = eyeVec.dot(zAxis);
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = sign*Math.acos(dot);
// use -angle because xform is to *undo* rotation by angle
aa.x = nAxis.x;
aa.y = nAxis.y;
aa.z = nAxis.z;
aa.angle = -angle;
orientedxform.set(aa);
}
else {
orientedxform.setIdentity();
}
- } else { // rotate about point
+ } else if(mode == OrientedShape3D.ROTATE_ABOUT_POINT ){ // rotate about point
// Need to rotate Z axis to point to eye, and Y axis to be
// parallel to view platform Y axis, rotating around rotation pt
// get the eye point
canvas.getCenterEyeInImagePlate(viewPosition);
// derive the yUp point
yUpPoint.set(viewPosition);
yUpPoint.y += 0.01; // one cm in Physical space
// transform the points to the Billboard's space
canvas.getImagePlateToVworld(xform); // xform is ImagePlateToVworld
xform.transform(viewPosition);
xform.transform(yUpPoint);
// get billboard's transform
xform.set(getCurrentLocalToVworld());
xform.invert(); // xform is vWorldToLocal
// transfom points to local coord sys
xform.transform(viewPosition);
xform.transform(yUpPoint);
// Make a vector from viewPostion to 0,0,0 in the BB coord sys
eyeVec.set(viewPosition);
eyeVec.normalize();
// create a yUp vector
yUp.set(yUpPoint);
yUp.sub(viewPosition);
yUp.normalize();
// find the plane to rotate z
zAxis.x = 0.0;
zAxis.y = 0.0;
zAxis.z = 1.0;
// rotation axis is cross product of eyeVec and zAxis
vector.cross(eyeVec, zAxis); // vector is cross product
// if cross product is non-zero, vector is rotation axis and
// rotation angle is acos(eyeVec.dot(zAxis)));
double length = vector.length();
if (length > 0.0001) {
double dot = eyeVec.dot(zAxis);
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = Math.acos(dot);
aa.x = vector.x;
aa.y = vector.y;
aa.z = vector.z;
aa.angle = -angle;
zRotate.set(aa);
} else {
// no rotation needed, set to identity (scale = 1.0)
zRotate.set(1.0);
}
// Transform the yAxis by zRotate
yAxis.x = 0.0;
yAxis.y = 1.0;
yAxis.z = 0.0;
zRotate.transform(yAxis);
// project the yAxis onto the plane perp to the eyeVec
status = projectToPlane(yAxis, eyeVec);
if (status) {
// project the yUp onto the plane perp to the eyeVec
status = projectToPlane(yUp, eyeVec);
}
if (status) {
// rotation angle is acos(yUp.dot(yAxis));
double dot = yUp.dot(yAxis);
// Fix numerical error, otherwise acos return NULL
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = Math.acos(dot);
// check the sign by looking a the cross product vs the eyeVec
vector.cross(yUp, yAxis); // vector is cross product
if (eyeVec.dot(vector) < 0) {
angle *= -1;
}
aa.x = eyeVec.x;
aa.y = eyeVec.y;
aa.z = eyeVec.z;
aa.angle = -angle;
xform.set(aa); // xform is now yRotate
// rotate around the rotation point
vector.x = rotationPoint.x;
vector.y = rotationPoint.y;
vector.z = rotationPoint.z; // vector to translate to RP
orientedxform.set(vector); // translate to RP
orientedxform.mul(xform); // yRotate
orientedxform.mul(zRotate); // zRotate
vector.scale(-1.0); // vector to translate back
xform.set(vector); // xform to translate back
orientedxform.mul(xform); // translate back
}
else {
orientedxform.setIdentity();
}
}
//Scale invariant computation
if(constantScale) {
// Back Xform a unit vector to local world coords
canvas.getInverseVworldProjection(left_xform, right_xform);
// the two endpts of the vector have to be transformed
// individually because the Xform is not affine
im_vec[0].set(0.0, 0.0, 0.0, 1.0);
im_vec[1].set(1.0, 0.0, 0.0, 1.0);
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
left_xform.set(getCurrentLocalToVworld());
left_xform.invert();
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
lvec.set(im_vec[1]);
lvec.sub(im_vec[0]);
// We simply need the direction of this vector
lvec.normalize();
im_vec[0].set(0.0, 0.0, 0.0, 1.0);
im_vec[1].set(lvec);
im_vec[1].w = 1.0;
// Forward Xfrom to clip coords
left_xform.set(getCurrentLocalToVworld());
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
canvas.getVworldProjection(left_xform, right_xform);
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
// Perspective division
im_vec[0].x /= im_vec[0].w;
im_vec[0].y /= im_vec[0].w;
im_vec[0].z /= im_vec[0].w;
im_vec[1].x /= im_vec[1].w;
im_vec[1].y /= im_vec[1].w;
im_vec[1].z /= im_vec[1].w;
lvec.set(im_vec[1]);
lvec.sub(im_vec[0]);
// Use the length of this vector to determine the scaling
// factor
double scale = 1/lvec.length();
// Convert to meters
scale *= scaleFactor*canvas.getPhysicalWidth()/2;
// Scale object so that it appears the same size
scaleXform.setScale(scale);
orientedxform.mul(scaleXform);
}
}
private boolean projectToPlane(Vector3d projVec, Vector3d planeVec) {
double dis = planeVec.dot(projVec);
projVec.x = projVec.x - planeVec.x*dis;
projVec.y = projVec.y - planeVec.y*dis;
projVec.z = projVec.z - planeVec.z*dis;
double length = projVec.length();
if (length < EPSILON) { // projVec is parallel to planeVec
return false;
}
projVec.scale(1 / length);
return true;
}
void compile(CompileState compState) {
super.compile(compState);
mergeFlag = SceneGraphObjectRetained.DONT_MERGE;
// don't push the static transform to orientedShape3D
// because orientedShape3D is rendered using vertex array;
// it's not worth pushing the transform here
compState.keepTG = true;
}
void searchGeometryAtoms(UnorderList list) {
list.add(getGeomAtom(getMirrorShape(key)));
}
}
| true | true | synchronized void updateOrientedTransform(Canvas3D canvas, int viewIndex) {
double angle = 0.0;
double sign;
boolean status;
Transform3D orientedxform = getOrientedTransform(viewIndex);
// get viewplatforms's location in virutal world
if (mode == OrientedShape3D.ROTATE_ABOUT_AXIS) { // rotate about axis
canvas.getCenterEyeInImagePlate(viewPosition);
canvas.getImagePlateToVworld(xform); // xform is imagePlateToLocal
xform.transform(viewPosition);
// get billboard's transform
xform.set(getCurrentLocalToVworld());
xform.invert(); // xform is now vWorldToLocal
// transform the eye position into the billboard's coordinate system
xform.transform(viewPosition);
// eyeVec is a vector from the local origin to the eye pt in local
eyeVec.set(viewPosition);
eyeVec.normalize();
// project the eye into the rotation plane
status = projectToPlane(eyeVec, nAxis);
if (status) {
// project the z axis into the rotation plane
zAxis.x = 0.0;
zAxis.y = 0.0;
zAxis.z = 1.0;
status = projectToPlane(zAxis, nAxis);
}
if (status) {
// compute the sign of the angle by checking if the cross product
// of the two vectors is in the same direction as the normal axis
vector.cross(eyeVec, zAxis);
if (vector.dot(nAxis) > 0.0) {
sign = 1.0;
} else {
sign = -1.0;
}
// compute the angle between the projected eye vector and the
// projected z
double dot = eyeVec.dot(zAxis);
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = sign*Math.acos(dot);
// use -angle because xform is to *undo* rotation by angle
aa.x = nAxis.x;
aa.y = nAxis.y;
aa.z = nAxis.z;
aa.angle = -angle;
orientedxform.set(aa);
}
else {
orientedxform.setIdentity();
}
} else { // rotate about point
// Need to rotate Z axis to point to eye, and Y axis to be
// parallel to view platform Y axis, rotating around rotation pt
// get the eye point
canvas.getCenterEyeInImagePlate(viewPosition);
// derive the yUp point
yUpPoint.set(viewPosition);
yUpPoint.y += 0.01; // one cm in Physical space
// transform the points to the Billboard's space
canvas.getImagePlateToVworld(xform); // xform is ImagePlateToVworld
xform.transform(viewPosition);
xform.transform(yUpPoint);
// get billboard's transform
xform.set(getCurrentLocalToVworld());
xform.invert(); // xform is vWorldToLocal
// transfom points to local coord sys
xform.transform(viewPosition);
xform.transform(yUpPoint);
// Make a vector from viewPostion to 0,0,0 in the BB coord sys
eyeVec.set(viewPosition);
eyeVec.normalize();
// create a yUp vector
yUp.set(yUpPoint);
yUp.sub(viewPosition);
yUp.normalize();
// find the plane to rotate z
zAxis.x = 0.0;
zAxis.y = 0.0;
zAxis.z = 1.0;
// rotation axis is cross product of eyeVec and zAxis
vector.cross(eyeVec, zAxis); // vector is cross product
// if cross product is non-zero, vector is rotation axis and
// rotation angle is acos(eyeVec.dot(zAxis)));
double length = vector.length();
if (length > 0.0001) {
double dot = eyeVec.dot(zAxis);
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = Math.acos(dot);
aa.x = vector.x;
aa.y = vector.y;
aa.z = vector.z;
aa.angle = -angle;
zRotate.set(aa);
} else {
// no rotation needed, set to identity (scale = 1.0)
zRotate.set(1.0);
}
// Transform the yAxis by zRotate
yAxis.x = 0.0;
yAxis.y = 1.0;
yAxis.z = 0.0;
zRotate.transform(yAxis);
// project the yAxis onto the plane perp to the eyeVec
status = projectToPlane(yAxis, eyeVec);
if (status) {
// project the yUp onto the plane perp to the eyeVec
status = projectToPlane(yUp, eyeVec);
}
if (status) {
// rotation angle is acos(yUp.dot(yAxis));
double dot = yUp.dot(yAxis);
// Fix numerical error, otherwise acos return NULL
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = Math.acos(dot);
// check the sign by looking a the cross product vs the eyeVec
vector.cross(yUp, yAxis); // vector is cross product
if (eyeVec.dot(vector) < 0) {
angle *= -1;
}
aa.x = eyeVec.x;
aa.y = eyeVec.y;
aa.z = eyeVec.z;
aa.angle = -angle;
xform.set(aa); // xform is now yRotate
// rotate around the rotation point
vector.x = rotationPoint.x;
vector.y = rotationPoint.y;
vector.z = rotationPoint.z; // vector to translate to RP
orientedxform.set(vector); // translate to RP
orientedxform.mul(xform); // yRotate
orientedxform.mul(zRotate); // zRotate
vector.scale(-1.0); // vector to translate back
xform.set(vector); // xform to translate back
orientedxform.mul(xform); // translate back
}
else {
orientedxform.setIdentity();
}
}
//Scale invariant computation
if(constantScale) {
// Back Xform a unit vector to local world coords
canvas.getInverseVworldProjection(left_xform, right_xform);
// the two endpts of the vector have to be transformed
// individually because the Xform is not affine
im_vec[0].set(0.0, 0.0, 0.0, 1.0);
im_vec[1].set(1.0, 0.0, 0.0, 1.0);
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
left_xform.set(getCurrentLocalToVworld());
left_xform.invert();
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
lvec.set(im_vec[1]);
lvec.sub(im_vec[0]);
// We simply need the direction of this vector
lvec.normalize();
im_vec[0].set(0.0, 0.0, 0.0, 1.0);
im_vec[1].set(lvec);
im_vec[1].w = 1.0;
// Forward Xfrom to clip coords
left_xform.set(getCurrentLocalToVworld());
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
canvas.getVworldProjection(left_xform, right_xform);
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
// Perspective division
im_vec[0].x /= im_vec[0].w;
im_vec[0].y /= im_vec[0].w;
im_vec[0].z /= im_vec[0].w;
im_vec[1].x /= im_vec[1].w;
im_vec[1].y /= im_vec[1].w;
im_vec[1].z /= im_vec[1].w;
lvec.set(im_vec[1]);
lvec.sub(im_vec[0]);
// Use the length of this vector to determine the scaling
// factor
double scale = 1/lvec.length();
// Convert to meters
scale *= scaleFactor*canvas.getPhysicalWidth()/2;
// Scale object so that it appears the same size
scaleXform.setScale(scale);
orientedxform.mul(scaleXform);
}
}
| synchronized void updateOrientedTransform(Canvas3D canvas, int viewIndex) {
double angle = 0.0;
double sign;
boolean status;
Transform3D orientedxform = getOrientedTransform(viewIndex);
// get viewplatforms's location in virutal world
if (mode == OrientedShape3D.ROTATE_ABOUT_AXIS) { // rotate about axis
canvas.getCenterEyeInImagePlate(viewPosition);
canvas.getImagePlateToVworld(xform); // xform is imagePlateToLocal
xform.transform(viewPosition);
// get billboard's transform
xform.set(getCurrentLocalToVworld());
xform.invert(); // xform is now vWorldToLocal
// transform the eye position into the billboard's coordinate system
xform.transform(viewPosition);
// eyeVec is a vector from the local origin to the eye pt in local
eyeVec.set(viewPosition);
eyeVec.normalize();
// project the eye into the rotation plane
status = projectToPlane(eyeVec, nAxis);
if (status) {
// project the z axis into the rotation plane
zAxis.x = 0.0;
zAxis.y = 0.0;
zAxis.z = 1.0;
status = projectToPlane(zAxis, nAxis);
}
if (status) {
// compute the sign of the angle by checking if the cross product
// of the two vectors is in the same direction as the normal axis
vector.cross(eyeVec, zAxis);
if (vector.dot(nAxis) > 0.0) {
sign = 1.0;
} else {
sign = -1.0;
}
// compute the angle between the projected eye vector and the
// projected z
double dot = eyeVec.dot(zAxis);
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = sign*Math.acos(dot);
// use -angle because xform is to *undo* rotation by angle
aa.x = nAxis.x;
aa.y = nAxis.y;
aa.z = nAxis.z;
aa.angle = -angle;
orientedxform.set(aa);
}
else {
orientedxform.setIdentity();
}
} else if(mode == OrientedShape3D.ROTATE_ABOUT_POINT ){ // rotate about point
// Need to rotate Z axis to point to eye, and Y axis to be
// parallel to view platform Y axis, rotating around rotation pt
// get the eye point
canvas.getCenterEyeInImagePlate(viewPosition);
// derive the yUp point
yUpPoint.set(viewPosition);
yUpPoint.y += 0.01; // one cm in Physical space
// transform the points to the Billboard's space
canvas.getImagePlateToVworld(xform); // xform is ImagePlateToVworld
xform.transform(viewPosition);
xform.transform(yUpPoint);
// get billboard's transform
xform.set(getCurrentLocalToVworld());
xform.invert(); // xform is vWorldToLocal
// transfom points to local coord sys
xform.transform(viewPosition);
xform.transform(yUpPoint);
// Make a vector from viewPostion to 0,0,0 in the BB coord sys
eyeVec.set(viewPosition);
eyeVec.normalize();
// create a yUp vector
yUp.set(yUpPoint);
yUp.sub(viewPosition);
yUp.normalize();
// find the plane to rotate z
zAxis.x = 0.0;
zAxis.y = 0.0;
zAxis.z = 1.0;
// rotation axis is cross product of eyeVec and zAxis
vector.cross(eyeVec, zAxis); // vector is cross product
// if cross product is non-zero, vector is rotation axis and
// rotation angle is acos(eyeVec.dot(zAxis)));
double length = vector.length();
if (length > 0.0001) {
double dot = eyeVec.dot(zAxis);
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = Math.acos(dot);
aa.x = vector.x;
aa.y = vector.y;
aa.z = vector.z;
aa.angle = -angle;
zRotate.set(aa);
} else {
// no rotation needed, set to identity (scale = 1.0)
zRotate.set(1.0);
}
// Transform the yAxis by zRotate
yAxis.x = 0.0;
yAxis.y = 1.0;
yAxis.z = 0.0;
zRotate.transform(yAxis);
// project the yAxis onto the plane perp to the eyeVec
status = projectToPlane(yAxis, eyeVec);
if (status) {
// project the yUp onto the plane perp to the eyeVec
status = projectToPlane(yUp, eyeVec);
}
if (status) {
// rotation angle is acos(yUp.dot(yAxis));
double dot = yUp.dot(yAxis);
// Fix numerical error, otherwise acos return NULL
if (dot > 1.0f) {
dot = 1.0f;
} else if (dot < -1.0f) {
dot = -1.0f;
}
angle = Math.acos(dot);
// check the sign by looking a the cross product vs the eyeVec
vector.cross(yUp, yAxis); // vector is cross product
if (eyeVec.dot(vector) < 0) {
angle *= -1;
}
aa.x = eyeVec.x;
aa.y = eyeVec.y;
aa.z = eyeVec.z;
aa.angle = -angle;
xform.set(aa); // xform is now yRotate
// rotate around the rotation point
vector.x = rotationPoint.x;
vector.y = rotationPoint.y;
vector.z = rotationPoint.z; // vector to translate to RP
orientedxform.set(vector); // translate to RP
orientedxform.mul(xform); // yRotate
orientedxform.mul(zRotate); // zRotate
vector.scale(-1.0); // vector to translate back
xform.set(vector); // xform to translate back
orientedxform.mul(xform); // translate back
}
else {
orientedxform.setIdentity();
}
}
//Scale invariant computation
if(constantScale) {
// Back Xform a unit vector to local world coords
canvas.getInverseVworldProjection(left_xform, right_xform);
// the two endpts of the vector have to be transformed
// individually because the Xform is not affine
im_vec[0].set(0.0, 0.0, 0.0, 1.0);
im_vec[1].set(1.0, 0.0, 0.0, 1.0);
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
left_xform.set(getCurrentLocalToVworld());
left_xform.invert();
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
lvec.set(im_vec[1]);
lvec.sub(im_vec[0]);
// We simply need the direction of this vector
lvec.normalize();
im_vec[0].set(0.0, 0.0, 0.0, 1.0);
im_vec[1].set(lvec);
im_vec[1].w = 1.0;
// Forward Xfrom to clip coords
left_xform.set(getCurrentLocalToVworld());
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
canvas.getVworldProjection(left_xform, right_xform);
left_xform.transform(im_vec[0]);
left_xform.transform(im_vec[1]);
// Perspective division
im_vec[0].x /= im_vec[0].w;
im_vec[0].y /= im_vec[0].w;
im_vec[0].z /= im_vec[0].w;
im_vec[1].x /= im_vec[1].w;
im_vec[1].y /= im_vec[1].w;
im_vec[1].z /= im_vec[1].w;
lvec.set(im_vec[1]);
lvec.sub(im_vec[0]);
// Use the length of this vector to determine the scaling
// factor
double scale = 1/lvec.length();
// Convert to meters
scale *= scaleFactor*canvas.getPhysicalWidth()/2;
// Scale object so that it appears the same size
scaleXform.setScale(scale);
orientedxform.mul(scaleXform);
}
}
|
diff --git a/src/share/classes/com/sun/cdc/io/j2me/datagram/Protocol.java b/src/share/classes/com/sun/cdc/io/j2me/datagram/Protocol.java
index eb43c794..0a74c0cc 100644
--- a/src/share/classes/com/sun/cdc/io/j2me/datagram/Protocol.java
+++ b/src/share/classes/com/sun/cdc/io/j2me/datagram/Protocol.java
@@ -1,420 +1,420 @@
/*
* @(#)Protocol.java 1.33 06/10/13
*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*
*/
package com.sun.cdc.io.j2me.datagram;
import java.io.*;
import java.net.*;
import javax.microedition.io.*;
import com.sun.cdc.io.j2me.*;
import com.sun.cdc.io.*;
/**
* This implements the "datagram://" protocol for J2SE in a not very
* efficient way.
*
* @version 1.1 11/19/99
*/
public class Protocol extends ConnectionBase implements DatagramConnection,UDPDatagramConnection {
DatagramSocket endpoint;
/**
* Machine name
*/
private String host = null;
/**
* Port
*/
private int port;
private boolean open;
public String getLocalAddress() throws IOException {
if (!open) {
throw new IOException("Connection closed");
}
if (host != null)
return host;
else /* it is datagram://: string, server endpoint */
return InetAddress.getLocalHost().getHostAddress();
}
public int getLocalPort() throws IOException {
if (!open) {
throw new IOException("Connection closed");
}
return endpoint.getLocalPort();
}
/**
* Local function to get the machine address from a string
*/
protected static String getAddress(String name) throws IOException {
/* Look for the : */
int colon = name.indexOf(':');
if(colon < 0) {
throw new IllegalArgumentException("No ':' in protocol name "+name);
}
if(colon == 0) {
return null;
} else {
return parseHostName(name, colon);
}
}
protected static String parseHostName(String connection, int colon) {
/* IPv6 addresses are enclosed within [] */
if ((connection.indexOf("[") == 0) && (connection.indexOf("]") > 0)) {
return parseIPv6Address(connection, colon);
} else {
return parseIPv4Address(connection, colon);
}
}
protected static String parseIPv4Address(String name, int colon) {
return name.substring(0, colon);
}
protected static String parseIPv6Address(String address, int colon) {
int closing = address.indexOf("]");
/* beginning '[' and closing ']' should be included in the hostname*/
return address.substring(0, closing+1);
}
/**
* Local function to get the port number from a string
*/
protected static int getPort(String name) throws IOException, NumberFormatException {
/* Look for the : */
int colon = name.lastIndexOf(':');
if(colon < 0) {
throw new IllegalArgumentException("No ':' in protocol name "+name);
}
return Integer.parseInt(name.substring(colon+1));
}
/*
* throws SecurityException if MIDP permission check fails
* nothing to do for CDC
*/
protected void checkMIDPPermission(String host, int port) {
return;
}
/**
* Open a connection to a target. <p>
*
* The name string for this protocol should be:
* "[address:][port]"
*
* @param name the target of the connection
* @param writeable a flag that is true if the caller intends to
* write to the connection.
* @param timeouts A flag to indicate that the called wants timeout exceptions
*/
public void open(String name, int mode, boolean timeout) throws IOException {
if(name.charAt(0) != '/' || name.charAt(1) != '/') {
throw new IllegalArgumentException("Protocol must start with \"//\" "+name);
}
name = name.substring(2);
- host = getAddress(name);
/*
* If 'name' == null then we are a server endpoint at port 'port'
*
* If 'name' != null we are a client endpoint at an port decided by the system
* and the default address for datagrams to be send is 'host':'port'
*/
/* name does not have port number, just a colon, hence it should at
* system assigned port.
*/
if (name.substring(name.indexOf(':') + 1).length() == 0) {
/* Open a random port for a datagram client */
endpoint = new DatagramSocket();
}
else {
+ host = getAddress(name);
port = getPort(name);
if(port <= 0) {
throw new IllegalArgumentException("Bad port number \"//\" "+name);
}
checkMIDPPermission(host, port);
if(host == null) {
/* Open a server datagram socket (no host given) */
endpoint = new DatagramSocket(port);
} else {
/* Open a random port for a datagram client */
endpoint = new DatagramSocket();
}
}
open = true;
try {
byte[] testbuf = new byte[256];
DatagramPacket testdgram = new DatagramPacket(testbuf, 256);
if (host != null) {
testdgram.setAddress(InetAddress.getByName(host));
} else {
testdgram.setAddress(InetAddress.getByName("localhost"));
}
testdgram.setPort(port);
} catch(NumberFormatException x) {
throw new IllegalArgumentException("Invalid datagram address "
+host+":"+port);
} catch(UnknownHostException x) {
throw new IllegalArgumentException("Unknown host "+host+":"+port);
} catch(SecurityException se) {
// Don't need to report on the security
// exceptions yet at this point
}
}
/**
* Get the address represented by this datagram endpoint
*
* @return address The datagram addre4ss
*/
public String getAddress() {
InetAddress addr = endpoint.getLocalAddress();
return "datagram://" + addr.getHostName() + ":" + addr.getHostAddress();
}
/**
* Get the maximum length a datagram can be.
*
* @return address The length
*/
public int getMaximumLength() throws IOException {
try {
int receiveLen = endpoint.getReceiveBufferSize();
int sendLen = endpoint.getSendBufferSize();
/* return lesser of the two */
return (receiveLen < sendLen ? receiveLen : sendLen);
} catch(java.net.SocketException x) {
throw new IOException(x.getMessage());
}
}
/**
* Get the nominal length of a datagram.
*
* @return address The length
*/
public int getNominalLength() throws IOException {
return getMaximumLength();
}
/**
* Change the timeout period
*
* @param milliseconds The maximum time to wait
*/
public void setTimeout(int milliseconds) {
}
/**
* Send a datagram
*
* @param dgram A datagram
* @exception IOException If an I/O error occurs
*/
public void send(Datagram dgram) throws IOException {
DatagramObject dh = (DatagramObject)dgram;
endpoint.send(dh.dgram);
}
/**
* Receive a datagram
*
* @param dgram A datagram
* @exception IOException If an I/O error occurs
*/
public void receive(Datagram dgram) throws IOException {
DatagramObject dh = (DatagramObject)dgram;
endpoint.receive(dh.dgram);
// Set the return DatagramObject handle to have the address from the
// received DatagramPacket
int recv_port = dh.dgram.getPort();
String recv_host = dh.dgram.getAddress().getHostName();
if(recv_host != null) {
try {
dh.setAddress("datagram://" + recv_host + ":" + recv_port);
} catch(IOException x) {
throw new
RuntimeException("IOException in datagram::receive");
}
} else {
try {
dh.setAddress("datagram://:"+recv_port);
} catch(IOException x) {
throw new RuntimeException("IOException in datagram::receive");
}
}
dh.pointer = 0;
}
/**
* Close the connection to the target.
*
* @exception IOException If an I/O error occurs
*/
public void close() throws IOException {
if (open) {
open = false;
}
endpoint.close();
}
/**
* Get a new datagram object
*
* @return A new datagram
*/
public Datagram newDatagram(int size) throws IllegalArgumentException, IOException {
// Check for negative size
if (size < 0) {
throw new IllegalArgumentException("Size is negative: "+size);
}
return newDatagram(new byte[size], size);
}
/**
* Get a new datagram object
*
* @param addr The address to which the datagram must go
* @return A new datagram
*/
public Datagram newDatagram(int size, String addr) throws IOException ,
IllegalArgumentException {
// Check for negative size
if (size < 0) {
throw new IllegalArgumentException("Size is negative: "+size);
}
return newDatagram(new byte[size], size, addr);
}
/**
* Get a new datagram object
*
* @return A new datagram
*/
public Datagram newDatagram(byte[] buf, int size) throws IOException, IllegalArgumentException {
// Check for negative size
if (size < 0) {
throw new IllegalArgumentException("Size is negative: "+size);
}
// Check if size > max size
try {
if (size > getMaximumLength()) {
throw new IllegalArgumentException("Size: "+size+" is more than max size: "+getMaximumLength());
}
} catch (IOException e) {
throw (e);
}
// Check for a null value for buf
if (buf == null) {
throw new IllegalArgumentException("buf is null");
}
DatagramObject dg = new DatagramObject(new DatagramPacket(buf,size));
if(host != null) {
try {
dg.setAddress("datagram://"+host+":"+port);
} catch(IOException x) {
throw new RuntimeException("IOException in datagram::newDatagram");
}
}
/* Fix CR 6557544 */
/*
else {
try {
dg.setAddress("datagram://:"+port);
} catch(IOException x) {
throw new RuntimeException("IOException in datagram::newDatagram");
}
}
*/
return dg;
}
/**
* Get a new datagram object
*
* @param addr The address to which the datagram must go
* @return A new datagram
*/
public Datagram newDatagram(byte[] buf, int size, String addr) throws IOException , IllegalArgumentException {
// Check for negative size
if (size < 0) {
throw new IllegalArgumentException("Size is negative: "+size);
}
// Check if size > max size
try {
if (size > getMaximumLength()) {
throw new IllegalArgumentException("Size: "+size+" is more than max size: "+getMaximumLength());
}
} catch (IOException e) {
throw (e);
}
// Check if addr is null
if (addr == null) {
throw new IllegalArgumentException("addr is null");
}
// Check for a null value for buf
if (buf == null) {
throw new IllegalArgumentException("buf is null");
}
DatagramObject dh = (DatagramObject)newDatagram(buf, size);
dh.setAddress(addr);
return dh;
}
}
| false | true | public void open(String name, int mode, boolean timeout) throws IOException {
if(name.charAt(0) != '/' || name.charAt(1) != '/') {
throw new IllegalArgumentException("Protocol must start with \"//\" "+name);
}
name = name.substring(2);
host = getAddress(name);
/*
* If 'name' == null then we are a server endpoint at port 'port'
*
* If 'name' != null we are a client endpoint at an port decided by the system
* and the default address for datagrams to be send is 'host':'port'
*/
/* name does not have port number, just a colon, hence it should at
* system assigned port.
*/
if (name.substring(name.indexOf(':') + 1).length() == 0) {
/* Open a random port for a datagram client */
endpoint = new DatagramSocket();
}
else {
port = getPort(name);
if(port <= 0) {
throw new IllegalArgumentException("Bad port number \"//\" "+name);
}
checkMIDPPermission(host, port);
if(host == null) {
/* Open a server datagram socket (no host given) */
endpoint = new DatagramSocket(port);
} else {
/* Open a random port for a datagram client */
endpoint = new DatagramSocket();
}
}
open = true;
try {
byte[] testbuf = new byte[256];
DatagramPacket testdgram = new DatagramPacket(testbuf, 256);
if (host != null) {
testdgram.setAddress(InetAddress.getByName(host));
} else {
testdgram.setAddress(InetAddress.getByName("localhost"));
}
testdgram.setPort(port);
} catch(NumberFormatException x) {
throw new IllegalArgumentException("Invalid datagram address "
+host+":"+port);
} catch(UnknownHostException x) {
throw new IllegalArgumentException("Unknown host "+host+":"+port);
} catch(SecurityException se) {
// Don't need to report on the security
// exceptions yet at this point
}
}
| public void open(String name, int mode, boolean timeout) throws IOException {
if(name.charAt(0) != '/' || name.charAt(1) != '/') {
throw new IllegalArgumentException("Protocol must start with \"//\" "+name);
}
name = name.substring(2);
/*
* If 'name' == null then we are a server endpoint at port 'port'
*
* If 'name' != null we are a client endpoint at an port decided by the system
* and the default address for datagrams to be send is 'host':'port'
*/
/* name does not have port number, just a colon, hence it should at
* system assigned port.
*/
if (name.substring(name.indexOf(':') + 1).length() == 0) {
/* Open a random port for a datagram client */
endpoint = new DatagramSocket();
}
else {
host = getAddress(name);
port = getPort(name);
if(port <= 0) {
throw new IllegalArgumentException("Bad port number \"//\" "+name);
}
checkMIDPPermission(host, port);
if(host == null) {
/* Open a server datagram socket (no host given) */
endpoint = new DatagramSocket(port);
} else {
/* Open a random port for a datagram client */
endpoint = new DatagramSocket();
}
}
open = true;
try {
byte[] testbuf = new byte[256];
DatagramPacket testdgram = new DatagramPacket(testbuf, 256);
if (host != null) {
testdgram.setAddress(InetAddress.getByName(host));
} else {
testdgram.setAddress(InetAddress.getByName("localhost"));
}
testdgram.setPort(port);
} catch(NumberFormatException x) {
throw new IllegalArgumentException("Invalid datagram address "
+host+":"+port);
} catch(UnknownHostException x) {
throw new IllegalArgumentException("Unknown host "+host+":"+port);
} catch(SecurityException se) {
// Don't need to report on the security
// exceptions yet at this point
}
}
|
diff --git a/spacebot-java/src/main/java/nl/nurdspace/irc/spacebot/SpaceBot.java b/spacebot-java/src/main/java/nl/nurdspace/irc/spacebot/SpaceBot.java
index 41e13b4..d60ea13 100644
--- a/spacebot-java/src/main/java/nl/nurdspace/irc/spacebot/SpaceBot.java
+++ b/spacebot-java/src/main/java/nl/nurdspace/irc/spacebot/SpaceBot.java
@@ -1,1065 +1,1069 @@
package nl.nurdspace.irc.spacebot;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.nurdspace.irc.spacebot.dimmer.Dimmer;
import nl.nurdspace.irc.spacebot.dimmer.DimmerDevice;
import nl.nurdspace.irc.spacebot.dimmer.RGBDevice;
import nl.nurdspace.irc.spacebot.dimmer.SimpleDevice;
import nl.nurdspace.irc.spacebot.inventory.HtmlInventory;
import nl.nurdspace.irc.spacebot.inventory.Inventory;
import nl.nurdspace.irc.spacebot.inventory.InventoryLocation;
import org.apache.commons.lang.StringEscapeUtils;
import org.bff.javampd.MPD;
import org.bff.javampd.MPDDatabase;
import org.bff.javampd.MPDDatabase.ScopeType;
import org.bff.javampd.MPDPlayer;
import org.bff.javampd.MPDPlaylist;
import org.bff.javampd.exception.MPDConnectionException;
import org.bff.javampd.exception.MPDPlayerException;
import org.bff.javampd.exception.MPDPlaylistException;
import org.bff.javampd.exception.MPDResponseException;
import org.bff.javampd.objects.MPDSong;
import org.pircbotx.Channel;
import org.pircbotx.Colors;
import org.pircbotx.hooks.Event;
import org.pircbotx.hooks.Listener;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.ActionEvent;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.managers.ListenerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* IRC bot to monitor space status and provide other services.
*
* @author bjornl
*/
public class SpaceBot extends ListenerAdapter implements Listener,
SpaceStatusChangeListener {
/** Logger. */
private static final Logger LOG = LoggerFactory.getLogger(SpaceBot.class);
private static final DecimalFormat TEMP_FORMAT = new DecimalFormat("##0.0");
private static final DecimalFormat SECONDS_FORMAT = new DecimalFormat("00");
private static final String[] KUTMUZIEKBERICHTEN = new String[]{"Niemand luistert nog naar %1$s",
"Van %1$s gaat %2$s spontaan aan de spuitpoep",
"%1$ss is voor lutsers",
"%1$s schaadt de gezondheid. Het kan longkanker en hartklachten veroorzaken.",
"Kut.mu.ziek de; v 1. %1$s",
"Volgens %2$s is %1$s nog erger dan Windows 3.1"};
private final Channel channel;
private final Dimmer dimmer;
private final String mpdHost;
private SerialMonitor serial;
private int dmxChannel;
private int flashRepeats;
private int flashTimeOff;
private int flashTimeOn;
private int lightsOffDelay;
private List<Integer> dimmerChannels;
private List<DimmerDevice> dimmerDevices;
private static final Pattern REPLACE_COMMAND = Pattern
.compile("(^s|[ #!]s)/[^/]+/[^/]*/?"); // ^s/.+/.+|[
// |\\!|\\#]s/.+/.+
private List<Event> events = new ArrayList<Event>(100);
public SpaceBot(Channel channel, Dimmer dimmer, String mpdHost, int dimmerChannel, List<Integer> dimmerChannels, List<DimmerDevice> dimmerDevices) {
this(channel, dimmer, mpdHost, true, dimmerChannel, dimmerChannels, dimmerDevices);
}
public SpaceBot(Channel channel, Dimmer dimmer, String mpdHost, boolean automatic,
int dimmerChannel, List<Integer> dimmerChannels, List<DimmerDevice> dimmerDevices) {
SpaceStatus.getInstance().setOpenAutomatically(automatic);
this.channel = channel;
this.dimmer = dimmer;
this.dmxChannel = dimmerChannel;
this.mpdHost = mpdHost;
this.dimmerChannels = dimmerChannels;
this.dimmerDevices = dimmerDevices;
}
public void setSerialMonitor(SerialMonitor serial) {
this.serial = serial;
}
public void setDimmerChannel(int dimmerChannel) {
this.dmxChannel = dimmerChannel;
}
public void setLightsOffDelay(int lightsOffDelay) {
this.lightsOffDelay = lightsOffDelay;
}
public void setFlashRepeats(int flashRepeats) {
this.flashRepeats = flashRepeats;
}
public void setFlashTimeOn(int flashTimeOn) {
this.flashTimeOn = flashTimeOn;
}
public void setFlashTimeOff(int flashTimeOff) {
this.flashTimeOff = flashTimeOff;
}
/**
* Change the topic according to the given status.
*
* @param open
* true if the space is open, false if it is closed
*/
private void changeTopic(boolean open) {
LOG.trace("changeTopic: open=" + open);
String currentTopic = channel.getTopic();
String cleanTopic;
if (currentTopic.startsWith("Space is ")) {
// Remove current message
if (currentTopic.indexOf("|") > 0) {
cleanTopic = currentTopic.substring(
currentTopic.indexOf("|") + 1).trim();
} else {
cleanTopic = "";
}
} else {
cleanTopic = currentTopic;
}
LOG.debug("changeTopic: cleanTopic=[" + cleanTopic + "]");
String newTopic = getSpaceOpenMessage() + " | " + cleanTopic;
LOG.debug("changeTopic: newTopic=[" + cleanTopic + "]");
if (newTopic.equals(currentTopic)) {
LOG.trace("changeTopic: current topic matches new topic, ignoring");
} else {
channel.getBot().setTopic(channel, newTopic);
LOG.trace("changeTopic: changed topic");
}
}
private String getSpaceOpenMessage() {
LOG.trace("getSpaceOpenMessage: start");
String spaceOpenMessage = "Space is "
+ (SpaceStatus.getInstance().isOpen() ? "OPEN" : "CLOSED");
LOG.trace("getSpaceOpenMessage: spaceOpenMessage=[" + spaceOpenMessage
+ "]");
return spaceOpenMessage;
}
/**
* Easy and recommended way to handle events: Override respective methods in
* {@link ListenerAdapter}.
* <p>
* This example shows how to work with the waitFor ability of PircBotX.
* Follow the inline comments for how this works
* <p>
* *WARNING:* This example requires using a Threaded listener manager (this
* is PircBotX's default)
*
* @param event
* A MessageEvent
* @throws Exception
* If any Exceptions might be thrown, throw them up and let the
* {@link ListenerManager} handle it. This can be removed though
* if not needed
*/
public void onMessage(MessageEvent event) throws Exception {
String message = event.getMessage();
if (Command.isCommand(message)) {
// Command
try {
handleCommand(event);
} catch (RuntimeException e) {
LOG.error("Exception in command", e);
}
} else {
if (isReplaceCommand(message)) {
replace(event);
} else {
// Add the message to the store for future replacements
if (events.size() >= 100) {
events.remove(0);
}
events.add(event);
}
}
}
@Override
public void onAction(ActionEvent event) throws Exception {
if (events.size() >= 100) {
events.remove(0);
}
events.add(event);
}
private void handleCommand(MessageEvent event) {
Command command = new Command(event.getMessage());
if ("flash".equalsIgnoreCase(command.getCommand())) {
this.flash(event);
} else if ("fade".equalsIgnoreCase(command.getCommand())) {
this.fade(event, command);
} else if ("speak".equalsIgnoreCase(command.getCommand()) || "wall".equalsIgnoreCase(command.getCommand())) {
this.wall(event, command);
} else if ("devices".equalsIgnoreCase(command.getCommand())) {
StringBuffer devices = new StringBuffer();
for (int i = 0; i < this.dimmerDevices.size(); i++) {
DimmerDevice device = dimmerDevices.get(i);
devices.append(i).append(": [").append(device).append("] ");
};
event.getBot().sendMessage(event.getChannel(), devices.toString());
} else if ("device".equalsIgnoreCase(command.getCommand())) {
int deviceNumber = Integer.parseInt(command.getArgs()[0].substring(1));
DimmerDevice device = dimmerDevices.get(deviceNumber);
if (device instanceof SimpleDevice) {
StringBuffer buf = new StringBuffer("Device ").append(deviceNumber).append(": ");
buf.append("simple device (channel ").append(device.getChannels().get(0)).append("=").append(dimmer.getCurrentLevel(device.getChannels().get(0))).append(")");
event.getBot().sendMessage(event.getChannel(), buf.toString());
} else if (device instanceof RGBDevice) {
StringBuffer buf = new StringBuffer("Device ").append(deviceNumber).append(": ");
buf.append("RGB device (redchan ").append(device.getChannels().get(0)).append("=");
buf.append(dimmer.getCurrentLevel(device.getChannels().get(0))).append(", greenchan ").append(device.getChannels().get(1)).append("=");
buf.append(dimmer.getCurrentLevel(device.getChannels().get(1))).append(", bluechan ").append(device.getChannels().get(2)).append("=");
buf.append(dimmer.getCurrentLevel(device.getChannels().get(2))).append(")");
event.getBot().sendMessage(event.getChannel(), buf.toString());
} else {
event.getBot().sendMessage(event.getChannel(), "onbekend type device");
}
} else if ("lights".equalsIgnoreCase(command.getCommand())) {
this.lights(event);
} else if ("status".equalsIgnoreCase(command.getCommand())) {
this.status(event);
} else if ("temp".equalsIgnoreCase(command.getCommand())) {
this.temp(event);
} else if ("brul".equalsIgnoreCase(command.getCommand())) {
this.brul(event, command);
} else if ("beledig".equalsIgnoreCase(command.getCommand())) {
this.beledig(event);
} else if ("kutmuziek".equalsIgnoreCase(command.getCommand())) {
this.skipTrack(event, true);
} else if ("find".equalsIgnoreCase(command.getCommand())) {
this.find(event, command);
} else if ("playlist".equalsIgnoreCase(command.getCommand())) {
this.playlist(event);
} else if ("next".equalsIgnoreCase(command.getCommand())) {
this.skipTrack(event, false);
} else if ("previous".equalsIgnoreCase(command.getCommand())) {
this.prevTrack(event, false);
} else if ("prachtmuziek".equalsIgnoreCase(command.getCommand())) {
this.prevTrack(event, true);
} else if ("volume".equalsIgnoreCase(command.getCommand())) {
this.volume(event, command);
} else if ("louder".equalsIgnoreCase(command.getCommand()) || "harder".equalsIgnoreCase(command.getCommand())) {
this.harder(event, command);
} else if ("quieter".equalsIgnoreCase(command.getCommand()) || "zachter".equalsIgnoreCase(command.getCommand())) {
this.zachter(event, command);
} else if ("pause".equalsIgnoreCase(command.getCommand())) {
this.mpdPause(event);
} else if ("stop".equalsIgnoreCase(command.getCommand())) {
this.mpdStop(event);
} else if ("play".equalsIgnoreCase(command.getCommand())) {
this.mpdPlay(event);
} else if ("np".equalsIgnoreCase(command.getCommand())) {
this.showSong(event);
} else if ("element".equalsIgnoreCase(command.getCommand())) {
this.showElement(event, command);
} else if ("lock".equalsIgnoreCase(command.getCommand())) {
this.showLocks(event);
} else if ("open".equalsIgnoreCase(command.getCommand()) || "state".equalsIgnoreCase(command.getCommand())) {
this.showOpen(event);
} else if ("locate".equalsIgnoreCase(command.getCommand()) || "waaris".equalsIgnoreCase(command.getCommand())) {
this.locate(event, command);
} else if ("fixtopic".equalsIgnoreCase(command.getCommand())) {
if (channel.isOp(event.getBot().getUserBot())) {
this.changeTopic(SpaceStatus.getInstance().isOpen());
} else {
event.respond("Can't, I'm not an op! /op me!");
}
}
}
private void locate(MessageEvent event, Command command) {
if (command.getNumberOfArguments() != 1) {
event.respond("geef precies 1 woord als zoekterm");
} else {
HttpURLConnection urlConnection = null;
Inventory inventory = null;
try {
URL url = new URL("http://nurdspace.nl/Expedits");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream input = new BufferedInputStream(urlConnection.getInputStream());
inventory = new HtmlInventory(input);
} catch (MalformedURLException e) {
LOG.error("Lezen van inventory", e);
} catch (IOException e) {
LOG.error("Lezen van inventory", e);
} finally {
urlConnection.disconnect();
}
List<InventoryLocation> locations = inventory.locate(command.getArgs()[0]);
if (locations.size() == 0) {
event.respond("niets gevonden");
} else if (locations.size() > 3) {
event.respond("te veel resultaten: " + locations.size());
} else {
for (InventoryLocation location : locations) {
String contents = location.getContents();
int start = contents.indexOf('<');
int end = contents.indexOf('>', start);
while (start >= 0 && end >= 0) {
contents = contents.substring(0, start) + contents.substring(end + 1);
start = contents.indexOf('<');
end = contents.indexOf('>', start);
}
event.getBot().sendMessage(event.getChannel(), "[" + location.getColumn() + location.getRow() + "] " + StringEscapeUtils.unescapeHtml(contents));
}
}
}
}
private void showLocks(MessageEvent event) {
event.getBot().sendMessage(event.getChannel(), "Front door is " + (SpaceStatus.getInstance().isFrontDoorLocked() == null ? "unknown" : (SpaceStatus.getInstance().isFrontDoorLocked() ? "locked" : "unlocked")));
event.getBot().sendMessage(event.getChannel(), "Back door is " + (SpaceStatus.getInstance().isBackDoorLocked() == null ? "unknown" : (SpaceStatus.getInstance().isBackDoorLocked() ? "locked" : "unlocked")));
}
private void showElement(MessageEvent event, Command command) {
if (command.getNumberOfArguments() > 0) {
Element element;
String arg = command.getArgs()[0];
// Try abbreviation
element = Elements.getInstance().getElementByAbbreviation(arg);
if (element == null) {
// Try number
try {
int number = Integer.parseInt(arg);
element = Elements.getInstance().getElementByNumber(number);
} catch (NumberFormatException e) {
// Not important
}
}
if (element == null) {
// Try name
element = Elements.getInstance().getElementByName(arg);
// TODO scan through list and check part of name
}
if (element == null) {
event.getBot().sendMessage(event.getChannel(), "element '" + arg + "' is unknown");
} else {
event.getBot().sendMessage(event.getChannel(), element.getNumber() + ". " + element.getName() + " (" + element.getAbbreviation() + "); atomic weight: " + element.getWeight());
}
}
}
private void showOpen(MessageEvent event) {
event.getBot().sendMessage(event.getChannel(), getSpaceOpenMessage());
}
private void flash(MessageEvent event) {
if (SpaceStatus.getInstance().isOpen()) {
dimmer.flash(dimmerDevices, this.flashRepeats,
this.flashTimeOn, this.flashTimeOff);
} else {
event.respond("nope, space is closed");
}
}
private void fade(MessageEvent event, Command command) {
if (SpaceStatus.getInstance().isOpen()) {
// Drie formaten: fade <level>; fade <level> <kanaal>; fade <level> #<device>
// Later nog: fade <r,g,b> #<device>
switch (command.getNumberOfArguments()) {
case 0:
event.respond("give me a level or RGB value (and optionally a channel/device)");
break;
case 1:
if (command.getArgs()[0].startsWith("#")) {
// RGB kan niet op default channel
event.respond("give me a device if you want to use rgb!");
} else {
dimmer.fade(dmxChannel, Integer.parseInt(command.getArgs()[0]));
}
break;
case 2:
if (command.getArgs()[0].startsWith("#")) {
if (command.getArgs()[1].startsWith("#")) {
// RGB op device
// Check of device rgb is
int deviceNumber = Integer.parseInt(command.getArgs()[1].substring(1).trim());
if (dimmerDevices.get(deviceNumber) instanceof RGBDevice) {
RGBDevice device = (RGBDevice) dimmerDevices.get(deviceNumber);
if (command.getArgs()[0].length() != 7) {
event.respond("give me an RGB value in hex (rrggbb), like so: #FF0080");
} else {
String red = command.getArgs()[0].substring(1, 3);
String green = command.getArgs()[0].substring(3, 5);
String blue = command.getArgs()[0].substring(5);
dimmer.fadeAbsolute(device.getRed(), Integer.parseInt(red, 16));
dimmer.fadeAbsolute(device.getGreen(), Integer.parseInt(green, 16));
dimmer.fadeAbsolute(device.getBlue(), Integer.parseInt(blue, 16));
}
} else {
event.respond("give me an RGB device if you want to use rgb!");
}
} else {
event.respond("give me a device, not a channel, if you want to use rgb!");
}
} else {
// "Gewoon" level
int level = Integer.parseInt(command.getArgs()[0]);
if ("all".equals(command.getArgs()[1])) {
for (int channel : dimmerChannels) {
dimmer.fade(channel, level);
}
} else if (command.getArgs()[1].startsWith("#")) {
int deviceNumber = Integer.parseInt(command.getArgs()[1].substring(1).trim());
DimmerDevice device = dimmerDevices.get(deviceNumber);
for (int channel : device.getChannels()) {
dimmer.fade(channel, level);
}
} else {
// Ouderwets: level op channel
dimmer.fade(Integer.parseInt(command.getArgs()[1]), level);
}
}
}
} else {
event.respond("nope, space is closed");
}
}
private void lights(MessageEvent event) {
Integer fluorescents = SpaceStatus.getInstance().getFluorescentLighting();
String fluorescentsMessage = "unknown";
if (fluorescents != null) {
Boolean fluorescentsOnOff = SpaceStatus.getInstance().isFluorescentLightOn();
fluorescentsMessage = fluorescents + "/1023";
if (fluorescentsOnOff != null) {
fluorescentsMessage += " (" + (fluorescentsOnOff ? "ON" : "OFF") + ")";
}
}
event.getBot()
.sendMessage(
event.getChannel(),
"Fluorescent lighting "
+ fluorescentsMessage);
StringBuilder dimmedLights = new StringBuilder("Dimmer devices: ");
int deviceNr = 0;
for (DimmerDevice device : dimmerDevices) {
dimmedLights.append(deviceNr++).append("=");
if (device instanceof RGBDevice) {
RGBDevice rgbDevice = (RGBDevice) device;
dimmedLights.append("[").append(dimmer.getCurrentLevel((rgbDevice).getRed()));
dimmedLights.append(",").append(dimmer.getCurrentLevel((rgbDevice).getGreen()));
dimmedLights.append(",").append(dimmer.getCurrentLevel((rgbDevice).getBlue())).append("]");
} else {
dimmedLights.append(dimmer.getCurrentLevel(device.getChannels().iterator().next()));
}
if (deviceNr < dimmerDevices.size()) {
dimmedLights.append(",");
}
}
event.getBot().sendMessage(event.getChannel(), dimmedLights.toString());
}
private void temp(MessageEvent event) {
event.getBot().sendMessage(
event.getChannel(),
"Space temperature is "
+ TEMP_FORMAT.format(SpaceStatus.getInstance()
.getTemperature()) + " degrees Celsius");
}
private void status(MessageEvent event) {
Boolean fluorescents = SpaceStatus.getInstance().isFluorescentLightOn();
String fluorescentsMessage = "fluorescent lights: ";
if (fluorescents == null) {
fluorescentsMessage += "unknown";
} else {
fluorescentsMessage += fluorescents ? "ON" : "OFF";
}
Float temperature = SpaceStatus.getInstance().getTemperature();
String tempMessage = "unknown";
if (temperature != null) {
tempMessage = TEMP_FORMAT.format(temperature) + " C";
}
event.getBot().sendMessage(
event.getChannel(),
getSpaceOpenMessage() + "; " + fluorescentsMessage + "; " + tempMessage);
}
private void beledig(MessageEvent event) {
// TODO implement
}
private void brul(MessageEvent event, Command command) {
String arg;
if (command.getArgumentString() != null) {
arg = command.getArgumentString();
} else {
arg = "zelluf";
}
String brul = Colors.BOLD + arg.toUpperCase()
+ "!" + Colors.NORMAL;
event.getBot().sendMessage(event.getChannel(), brul);
}
private void find(MessageEvent event, Command command) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDDatabase mpdDatabase = mpd.getMPDDatabase();
Collection<MPDSong> songs = mpdDatabase.search(ScopeType.ANY, command.getArgumentString());
Iterator<MPDSong> songIterator = songs.iterator();
if (songs.isEmpty()) {
event.getBot().sendMessage(event.getChannel(), "nothing found");
} else if (songs.size() > 5) {
for (int i = 0; i < 5; i++) {
event.getBot().sendMessage(event.getChannel(), getSongInfo(songIterator.next()));
}
event.getBot().sendMessage(event.getChannel(), "... and " + (songs.size() - 5) + " more");
} else {
while (songIterator.hasNext()) {
event.getBot().sendMessage(event.getChannel(), getSongInfo(songIterator.next()));
}
}
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("find: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("find: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("find: Error connecting", e);
}
}
private void playlist(MessageEvent event) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlaylist playlist = mpd.getMPDPlaylist();
List<MPDSong> songs = playlist.getSongList();
MPDSong current = playlist.getCurrentSong();
int currentIndex = songs.indexOf(current);
int numberOfSongsLeft = songs.size() - currentIndex - 1;
if (songs.isEmpty() || numberOfSongsLeft == 0) {
event.getBot().sendMessage(event.getChannel(), "geen nummers meer in playlist");
} else if (numberOfSongsLeft > 5) {
for (int i = 0; i < 5; i++) {
event.getBot().sendMessage(event.getChannel(), getSongInfo(songs.get(currentIndex + i + 1)));
}
event.getBot().sendMessage(event.getChannel(), "... and " + (songs.size() - currentIndex - 6) + " more");
} else {
for (int i = currentIndex + 1; i < songs.size(); i++) {
event.getBot().sendMessage(event.getChannel(), getSongInfo(songs.get(i)));
}
}
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("playlist: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("playlist: Error connecting", e);
} catch (MPDPlaylistException e) {
event.respond("sorry, couldn't obtain playlist info");
LOG.error("playlist: Error getting current song", e);
}
}
private void skipTrack(MessageEvent event, boolean kutmuziek) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
int random = 0;
StringBuilder songInfoString = null;
if (kutmuziek) {
MPDSong song = mpdPlayer.getCurrentSong();
songInfoString = new StringBuilder();
if (song.getArtist() == null) {
songInfoString.append(song.getTitle()).append(" van ")
.append(song.getFile());
} else {
songInfoString.append(song.getTitle()).append(" van ")
.append(song.getArtist());
}
random = new Random(System.currentTimeMillis()).nextInt(KUTMUZIEKBERICHTEN.length);
}
mpdPlayer.playNext();
mpd.close();
if (kutmuziek) {
LOG.debug("kutmuziek random = " + random);
String message = String.format(KUTMUZIEKBERICHTEN[random], songInfoString.toString(), event.getUser().getNick());
event.getBot().sendMessage(event.getChannel(), message);
}
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't skip the song");
LOG.error("skipTrack: Error skipping", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("skipTrack: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("skipTrack: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("skipTrack: Error connecting", e);
}
}
private void prevTrack(MessageEvent event, boolean prachtmuziek) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
mpdPlayer.playPrev();
StringBuilder songInfoString = null;
if (prachtmuziek) {
MPDSong song = mpdPlayer.getCurrentSong();
songInfoString = new StringBuilder();
if (song.getArtist() == null) {
songInfoString.append(song.getTitle()).append(" van ")
.append(song.getFile());
} else {
songInfoString.append(song.getTitle()).append(" van ")
.append(song.getArtist());
}
}
mpd.close();
if (prachtmuziek) {
String message = String.format("%1$s is voor echte helden zoals %1$s", songInfoString.toString(), event.getUser().getNick());
event.getBot().sendMessage(event.getChannel(), message);
}
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't play previous song");
LOG.error("prevTrack: Error skipping", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("prevTrack: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("prevTrack: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("prevTrack: Error connecting", e);
}
}
private void zachter(MessageEvent event, Command command) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
int hoeveel = 10;
if (command.getNumberOfArguments() == 1) {
hoeveel = Integer.parseInt(command.getArgs()[0]);
}
int huidig = mpdPlayer.getVolume();
int nieuw = huidig - hoeveel;
if (nieuw < 0) {
nieuw = 0;
}
mpdPlayer.setVolume(nieuw);
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't lower volume");
LOG.error("zachter: Error skipping", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("zachter: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("zachter: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("zachter: Error connecting", e);
}
}
private void harder(MessageEvent event, Command command) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
int hoeveel = 10;
if (command.getNumberOfArguments() == 1) {
hoeveel = Integer.parseInt(command.getArgs()[0]);
}
int huidig = mpdPlayer.getVolume();
int nieuw = huidig + hoeveel;
if (nieuw > 100) {
nieuw = 100;
}
mpdPlayer.setVolume(nieuw);
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't skip the song");
LOG.error("harder: Error lowering volume", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("harder: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("harder: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("harder: Error connecting", e);
}
}
private void volume(MessageEvent event, Command command) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
if (command.getNumberOfArguments() == 1) {
int volume = Integer.parseInt(command.getArgs()[0]);
if (volume > 100) {
volume = 100;
} else if (volume < 0) {
volume = 0;
}
mpdPlayer.setVolume(volume);
} else {
int volume = mpdPlayer.getVolume();
event.getBot().sendMessage(event.getChannel(), "volume: " + volume);
}
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't read or change volume");
LOG.error("volume: Error setting or reading volume", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("volume: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("volume: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("volume: Error connecting", e);
}
}
private void mpdPause(MessageEvent event) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
mpdPlayer.pause();
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't pause");
LOG.error("mpdPause: Error skipping", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("mpdPause: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("mpdPause: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("mpdPause: Error connecting", e);
}
}
private void mpdStop(MessageEvent event) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
mpdPlayer.stop();
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't stop");
LOG.error("mpdStop: Error skipping", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("mpdStop: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("mpdStop: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("mpdStop: Error connecting", e);
}
}
private void mpdPlay(MessageEvent event) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
mpdPlayer.play();
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't play");
LOG.error("mpdPlay: Error playing", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("mpdPlay: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("mpdPlay: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("mpdPlay: Error connecting", e);
}
}
private void showSong(MessageEvent event) {
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
MPDSong song = mpdPlayer.getCurrentSong();
event.getBot().sendMessage(event.getChannel(), "np: " + getSongInfo(song));
mpd.close();
} catch (MPDPlayerException e) {
event.respond("sorry, couldn't show the song");
LOG.error("showSong: Error reading current song", e);
} catch (MPDConnectionException e) {
event.respond("sorry, couldn't connect to MPD");
LOG.error("showSong: Error connecting", e);
} catch (MPDResponseException e) {
LOG.error("showSong: Error connecting", e);
} catch (UnknownHostException e) {
event.respond("sorry, couldn't find the MPD host");
LOG.error("showSong: Error connecting", e);
}
}
private String getSongInfo(MPDSong song) {
StringBuilder songInfo = new StringBuilder();
if (song.getArtist() == null) {
songInfo.append(song.getFile()).append(" - ")
.append(song.getTitle());
} else {
songInfo.append(song.getArtist()).append(" - ")
.append(song.getTitle());
int time = song.getLength();
songInfo.append(" [").append(time / 60).append(":");
songInfo.append(SECONDS_FORMAT.format(time % 60))
.append("]");
}
return songInfo.toString();
}
private void wall(MessageEvent event, Command command) {
String text = command.getArgumentString();
if (text != null && serial != null) {
String nick = event.getUser().getNick();
serial.sendToLedPanel(nick.toUpperCase() + "-" + text.toUpperCase() + " - ");
}
}
@Override
public void spaceStatusChanged(int eventType, Object status) {
LOG.trace("spaceStatusChanged: " + eventType);
switch (eventType) {
case SpaceStatusChangeListener.EVENT_SPACE_OPEN_CLOSE:
LOG.trace("spaceStatusChanged: open=" + status);
if (SpaceStatus.getInstance().isOpenAutomatically()) {
this.changeTopic((Boolean) status);
if ((Boolean) status) {
LOG.info("spaceStatusChanged: opened");
LOG.info("spaceStatusChanged: start mpd");
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
mpdPlayer.play();
mpd.close();
} catch (MPDPlayerException e) {
LOG.error("spaceStatusChanged: Error starting music", e);
} catch (MPDConnectionException e) {
LOG.error("spaceStatusChanged: Error starting music", e);
} catch (MPDResponseException e) {
LOG.error("spaceStatusChanged: Error starting music", e);
} catch (UnknownHostException e) {
LOG.error("spaceStatusChanged: Error starting music", e);
}
LOG.info("spaceStatusChanged: lights on");
new Thread() {
@Override
public void run() {
dimmer.fadeIn(dmxChannel);
}
}.start();
LOG.info("spaceStatusChanged: opened, fading in started in separate thread");
} else {
LOG.info("spaceStatusChanged: closed");
LOG.info("spaceStatusChanged: stop mpd");
try {
MPD mpd = new MPD(this.mpdHost, 6600);
MPDPlayer mpdPlayer = mpd.getMPDPlayer();
mpdPlayer.stop();
mpd.close();
} catch (MPDPlayerException e) {
LOG.error("spaceStatusChanged: Error stopping music", e);
} catch (MPDConnectionException e) {
LOG.error("spaceStatusChanged: Error stopping music", e);
} catch (MPDResponseException e) {
LOG.error("spaceStatusChanged: Error stopping music", e);
} catch (UnknownHostException e) {
LOG.error("spaceStatusChanged: Error stopping music", e);
}
LOG.info("spaceStatusChanged: lights off");
new Thread() {
@Override
public void run() {
int i = 0;
for (int channel : dimmerChannels) {
dimmer.fadeOut(channel, lightsOffDelay + 3 * i++);
}
}
}.start();
LOG.info("spaceStatusChanged: fading out started in separate thread");
}
}
break;
case SpaceStatusChangeListener.EVENT_BACK_DOOR_LOCK:
LOG.trace("spaceStatusChanged: backDoorLocked=" + status);
this.channel.getBot().sendMessage(this.channel, "back door was " + (((Boolean) status).booleanValue() ? "locked" : "unlocked"));
break;
case SpaceStatusChangeListener.EVENT_FRONT_DOOR_LOCK:
LOG.trace("spaceStatusChanged: frontDoorLocked=" + status);
this.channel.getBot().sendMessage(this.channel, "front door was " + (((Boolean) status).booleanValue() ? "locked" : "unlocked"));
break;
}
}
private void replace(final MessageEvent event) {
if (isReplaceCommand(event.getMessage())) {
LOG.debug("process: message contains a replace command");
String replaceCommand = getReplaceCommand(event.getMessage());
LOG.debug("process: replace command: " + replaceCommand);
String[] commandElements = replaceCommand.split("/");
String snippet = commandElements[1];
- String replacement = commandElements[2];
- String origin;
+ String replacement;
+ if (commandElements.length > 2) {
+ replacement = commandElements[2];
+ } else {
+ replacement = "";
+ }
List<Event> reversedMessages = new ArrayList<Event>(100);
reversedMessages.addAll(events);
Collections.reverse(reversedMessages);
String messageText;
for (Event aMessage : reversedMessages) {
if (aMessage instanceof MessageEvent) {
messageText = ((MessageEvent) aMessage).getMessage();
} else if (aMessage instanceof ActionEvent) {
messageText = ((ActionEvent) aMessage).getAction();
} else {
LOG.error("process: unsupported message type in store: "
+ aMessage.getClass().getName());
throw new IllegalStateException(
"Unsupported message type in store");
}
if (messageText.contains(snippet)) {
String replaced = messageText.replace(snippet, replacement);
if (aMessage instanceof MessageEvent) {
MessageEvent message = (MessageEvent) aMessage;
aMessage.getBot().sendMessage(
message.getChannel(),
"<" + message.getUser().getNick() + "> " + replaced);
MessageEvent replacedMessage = new MessageEvent(message.getBot(), message.getChannel(), message.getUser(), replaced);
if (events.size() >= 100) {
events.remove(0);
}
events.add(replacedMessage);
} else if (aMessage instanceof ActionEvent) {
ActionEvent action = (ActionEvent) aMessage;
aMessage.getBot().sendMessage(
action.getChannel(),
"* " + action.getUser().getNick() + " "
+ replaced);
ActionEvent replacedAction = new ActionEvent(action.getBot(), action.getUser(), action.getChannel(), replaced);
if (events.size() >= 100) {
events.remove(0);
}
events.add(replacedAction);
}
else {
// This cannot happen
LOG.error("process: unsupported message type in store: "
+ aMessage.getClass().getName());
throw new IllegalStateException(
"Unsupported message type in store");
}
break;
}
}
}
else {
LOG.debug("process: message is not a replace command");
//
// if (messageToProcess instanceof PublicMessage
// || messageToProcess instanceof Action) {
//
// LOG.debug("process: message is added to the store");
//
// messages.addMessage(messageToProcess);
//
// }
//
// return false;
}
}
/**
*
* Detect whether the given message contains a replace command.
*
*
@param message
* the message
*
*
@return true if the message contains a replace command
*/
private boolean isReplaceCommand(final String message) {
return REPLACE_COMMAND.matcher(message).find();
}
/**
*
* Retrieves the replace command from the given message.
*
*
@param message
* the message
*
*
@return true if the message contains a replace command
*/
private String getReplaceCommand(final String message) {
Matcher matcher = REPLACE_COMMAND.matcher(message);
if (!matcher.find()) {
throw new IllegalArgumentException(
"The message does not contain a replace command");
}
return matcher.group();
}
}
| true | true | private void replace(final MessageEvent event) {
if (isReplaceCommand(event.getMessage())) {
LOG.debug("process: message contains a replace command");
String replaceCommand = getReplaceCommand(event.getMessage());
LOG.debug("process: replace command: " + replaceCommand);
String[] commandElements = replaceCommand.split("/");
String snippet = commandElements[1];
String replacement = commandElements[2];
String origin;
List<Event> reversedMessages = new ArrayList<Event>(100);
reversedMessages.addAll(events);
Collections.reverse(reversedMessages);
String messageText;
for (Event aMessage : reversedMessages) {
if (aMessage instanceof MessageEvent) {
messageText = ((MessageEvent) aMessage).getMessage();
} else if (aMessage instanceof ActionEvent) {
messageText = ((ActionEvent) aMessage).getAction();
} else {
LOG.error("process: unsupported message type in store: "
+ aMessage.getClass().getName());
throw new IllegalStateException(
"Unsupported message type in store");
}
if (messageText.contains(snippet)) {
String replaced = messageText.replace(snippet, replacement);
if (aMessage instanceof MessageEvent) {
MessageEvent message = (MessageEvent) aMessage;
aMessage.getBot().sendMessage(
message.getChannel(),
"<" + message.getUser().getNick() + "> " + replaced);
MessageEvent replacedMessage = new MessageEvent(message.getBot(), message.getChannel(), message.getUser(), replaced);
if (events.size() >= 100) {
events.remove(0);
}
events.add(replacedMessage);
} else if (aMessage instanceof ActionEvent) {
ActionEvent action = (ActionEvent) aMessage;
aMessage.getBot().sendMessage(
action.getChannel(),
"* " + action.getUser().getNick() + " "
+ replaced);
ActionEvent replacedAction = new ActionEvent(action.getBot(), action.getUser(), action.getChannel(), replaced);
if (events.size() >= 100) {
events.remove(0);
}
events.add(replacedAction);
}
else {
// This cannot happen
LOG.error("process: unsupported message type in store: "
+ aMessage.getClass().getName());
throw new IllegalStateException(
"Unsupported message type in store");
}
break;
}
}
}
else {
LOG.debug("process: message is not a replace command");
//
// if (messageToProcess instanceof PublicMessage
// || messageToProcess instanceof Action) {
//
// LOG.debug("process: message is added to the store");
//
// messages.addMessage(messageToProcess);
//
// }
//
// return false;
}
}
| private void replace(final MessageEvent event) {
if (isReplaceCommand(event.getMessage())) {
LOG.debug("process: message contains a replace command");
String replaceCommand = getReplaceCommand(event.getMessage());
LOG.debug("process: replace command: " + replaceCommand);
String[] commandElements = replaceCommand.split("/");
String snippet = commandElements[1];
String replacement;
if (commandElements.length > 2) {
replacement = commandElements[2];
} else {
replacement = "";
}
List<Event> reversedMessages = new ArrayList<Event>(100);
reversedMessages.addAll(events);
Collections.reverse(reversedMessages);
String messageText;
for (Event aMessage : reversedMessages) {
if (aMessage instanceof MessageEvent) {
messageText = ((MessageEvent) aMessage).getMessage();
} else if (aMessage instanceof ActionEvent) {
messageText = ((ActionEvent) aMessage).getAction();
} else {
LOG.error("process: unsupported message type in store: "
+ aMessage.getClass().getName());
throw new IllegalStateException(
"Unsupported message type in store");
}
if (messageText.contains(snippet)) {
String replaced = messageText.replace(snippet, replacement);
if (aMessage instanceof MessageEvent) {
MessageEvent message = (MessageEvent) aMessage;
aMessage.getBot().sendMessage(
message.getChannel(),
"<" + message.getUser().getNick() + "> " + replaced);
MessageEvent replacedMessage = new MessageEvent(message.getBot(), message.getChannel(), message.getUser(), replaced);
if (events.size() >= 100) {
events.remove(0);
}
events.add(replacedMessage);
} else if (aMessage instanceof ActionEvent) {
ActionEvent action = (ActionEvent) aMessage;
aMessage.getBot().sendMessage(
action.getChannel(),
"* " + action.getUser().getNick() + " "
+ replaced);
ActionEvent replacedAction = new ActionEvent(action.getBot(), action.getUser(), action.getChannel(), replaced);
if (events.size() >= 100) {
events.remove(0);
}
events.add(replacedAction);
}
else {
// This cannot happen
LOG.error("process: unsupported message type in store: "
+ aMessage.getClass().getName());
throw new IllegalStateException(
"Unsupported message type in store");
}
break;
}
}
}
else {
LOG.debug("process: message is not a replace command");
//
// if (messageToProcess instanceof PublicMessage
// || messageToProcess instanceof Action) {
//
// LOG.debug("process: message is added to the store");
//
// messages.addMessage(messageToProcess);
//
// }
//
// return false;
}
}
|
diff --git a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java
index 8111d87..b6844e2 100644
--- a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java
+++ b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java
@@ -1,663 +1,666 @@
/*
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.csstudio.swt.xygraph.linearscale;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Tick factory produces the different axis ticks. When specifying a format and
* given the screen size parameters and range it will return a list of Ticks
*/
public class TickFactory {
public enum TickFormatting {
/**
* Automatically adjust precision
*/
autoMode,
/**
* Rounded or chopped to the nearest decimal
*/
roundAndChopMode,
/**
* Use Exponent
*/
useExponent,
/**
* Use SI units (k,M,G,etc.)
*/
useSIunits,
/**
* Use external scale provider
*/
useCustom;
}
private TickFormatting formatOfTicks;
private final static BigDecimal EPSILON = new BigDecimal("1.0E-20");
private static final int DIGITS_UPPER_LIMIT = 6; // limit for number of digits to display left of decimal point
private static final int DIGITS_LOWER_LIMIT = -6; // limit for number of zeros to display right of decimal point
private static final double ROUND_FRACTION = 2e-6; // fraction of denominator to round to
private static final BigDecimal BREL_ERROR = new BigDecimal("1e-15");
private static final double REL_ERROR = BREL_ERROR.doubleValue();
private double graphMin;
private double graphMax;
private String tickFormat;
private IScaleProvider scale;
private int intervals; // number of intervals
private boolean isReversed;
/**
* @param format
*/
public TickFactory(IScaleProvider scale) {
this(TickFormatting.useCustom, scale);
}
/**
* @param format
*/
public TickFactory(TickFormatting format, IScaleProvider scale) {
formatOfTicks = format;
this.scale = scale;
}
private String getTickString(double value) {
if (scale!=null) value = scale.getLabel(value);
String returnString = "";
if (Double.isNaN(value))
return returnString;
switch (formatOfTicks) {
case autoMode:
returnString = String.format(tickFormat, value);
break;
case useExponent:
returnString = String.format(tickFormat, value);
break;
case roundAndChopMode:
returnString = String.format("%d", Math.round(value));
break;
case useSIunits:
double absValue = Math.abs(value);
if (absValue == 0.0) {
returnString = String.format("%6.2f", value);
} else if (absValue <= 1E-15) {
returnString = String.format("%6.2ff", value * 1E15);
} else if (absValue <= 1E-12) {
returnString = String.format("%6.2fp", value * 1E12);
} else if (absValue <= 1E-9) {
returnString = String.format("%6.2fn", value * 1E9);
} else if (absValue <= 1E-6) {
returnString = String.format("%6.2fµ", value * 1E6);
} else if (absValue <= 1E-3) {
returnString = String.format("%6.2fm", value * 1E3);
} else if (absValue < 1E3) {
returnString = String.format("%6.2f", value);
} else if (absValue < 1E6) {
returnString = String.format("%6.2fk", value * 1E-3);
} else if (absValue < 1E9) {
returnString = String.format("%6.2fM", value * 1E-6);
} else if (absValue < 1E12) {
returnString = String.format("%6.2fG", value * 1E-9);
} else if (absValue < 1E15) {
returnString = String.format("%6.2fT", value * 1E-12);
} else if (absValue < 1E18)
returnString = String.format("%6.2fP", value * 1E-15);
break;
case useCustom:
returnString = scale.format(value);
break;
}
return returnString;
}
private void createFormatString(final int precision, final boolean b) {
switch (formatOfTicks) {
case autoMode:
tickFormat = b ? String.format("%%.%de", precision) : String.format("%%.%df", precision);
break;
case useExponent:
tickFormat = String.format("%%.%de", precision);
break;
default:
tickFormat = null;
break;
}
}
/**
* Round numerator down to multiples of denominators
* @param n numerator
* @param d denominator
* @return
*/
protected static double roundDown(BigDecimal n, BigDecimal d) {
final int ns = n.signum();
if (ns == 0)
return 0;
final int ds = d.signum();
if (ds == 0)
throw new IllegalArgumentException("Zero denominator is not allowed");
n = n.abs();
d = d.abs();
final BigDecimal[] x = n.divideAndRemainder(d);
double rx = x[1].doubleValue();
if (rx > (1-ROUND_FRACTION)*d.doubleValue()) {
// trim up if close to denominator
x[1] = BigDecimal.ZERO;
x[0] = x[0].add(BigDecimal.ONE);
} else if (rx < ROUND_FRACTION*d.doubleValue()) {
x[1] = BigDecimal.ZERO;
}
final int xs = x[1].signum();
if (xs == 0) {
return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue();
} else if (xs < 0) {
throw new IllegalStateException("Cannot happen!");
}
if (ns != ds)
return x[0].signum() == 0 ? -d.doubleValue() : -x[0].add(BigDecimal.ONE).multiply(d).doubleValue();
return x[0].multiply(d).doubleValue();
}
/**
* Round numerator up to multiples of denominators
* @param n numerator
* @param d denominator
* @return
*/
protected static double roundUp(BigDecimal n, BigDecimal d) {
final int ns = n.signum();
if (ns == 0)
return 0;
final int ds = d.signum();
if (ds == 0)
throw new IllegalArgumentException("Zero denominator is not allowed");
n = n.abs();
d = d.abs();
final BigDecimal[] x = n.divideAndRemainder(d);
double rx = x[1].doubleValue();
if (rx != 0) {
if (rx < ROUND_FRACTION*d.doubleValue()) {
// trim down if close to zero
x[1] = BigDecimal.ZERO;
} else if (rx > (1-ROUND_FRACTION)*d.doubleValue()) {
x[1] = BigDecimal.ZERO;
x[0] = x[0].add(BigDecimal.ONE);
}
}
final int xs = x[1].signum();
if (xs == 0) {
return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue();
} else if (xs < 0) {
throw new IllegalStateException("Cannot happen!");
}
if (ns != ds)
return x[0].signum() == 0 ? 0 : -x[0].multiply(d).doubleValue();
return x[0].add(BigDecimal.ONE).multiply(d).doubleValue();
}
/**
* @param x
* @return floor of log 10
*/
private static int log10(BigDecimal x) {
int c = x.compareTo(BigDecimal.ONE);
int e = 0;
while (c < 0) {
e--;
x = x.scaleByPowerOfTen(1);
c = x.compareTo(BigDecimal.ONE);
}
c = x.compareTo(BigDecimal.TEN);
while (c >= 0) {
e++;
x = x.scaleByPowerOfTen(-1);
c = x.compareTo(BigDecimal.TEN);
}
return e;
}
/**
* @param x
* @param round if true, then round else take ceiling
* @return a nice number
*/
protected static BigDecimal nicenum(BigDecimal x, boolean round) {
int expv; /* exponent of x */
double f; /* fractional part of x */
double nf; /* nice, rounded number */
BigDecimal bf;
expv = log10(x);
bf = x.scaleByPowerOfTen(-expv);
f = bf.doubleValue(); /* between 1 and 10 */
if (round) {
if (f < 1.5)
nf = 1;
else if (f < 2.25)
nf = 2;
else if (f < 7.5)
nf = 5;
else
nf = 10;
}
else if (f <= 1.)
nf = 1;
else if (f <= 2.)
nf = 2;
else if (f <= 5.)
nf = 5;
else
nf = 10;
return BigDecimal.valueOf(BigDecimal.valueOf(nf).scaleByPowerOfTen(expv).doubleValue());
}
private double determineNumTicks(double min, double max, int maxTicks, boolean allowMinMaxOver) {
BigDecimal bMin = BigDecimal.valueOf(min);
BigDecimal bMax = BigDecimal.valueOf(max);
BigDecimal bRange = bMax.subtract(bMin);
if (bRange.signum() < 0) {
BigDecimal bt = bMin;
bMin = bMax;
bMax = bt;
bRange = bRange.negate();
isReversed = true;
} else {
isReversed = false;
}
BigDecimal magnitude = BigDecimal.valueOf(Math.max(Math.abs(min), Math.abs(max)));
// tick points too dense to do anything
if (bRange.compareTo(EPSILON.multiply(magnitude)) < 0) {
return 0;
}
bRange = nicenum(bRange, false);
BigDecimal bUnit;
int nTicks = maxTicks - 1;
if (Math.signum(min)*Math.signum(max) < 0) {
// straddle case
nTicks++;
}
do {
long n;
do { // ensure number of ticks is less or equal to number requested
bUnit = nicenum(BigDecimal.valueOf(bRange.doubleValue() / nTicks), true);
n = bRange.divideToIntegralValue(bUnit).longValue();
} while (n > maxTicks && --nTicks > 0);
if (allowMinMaxOver) {
graphMin = roundDown(bMin, bUnit);
if (graphMin == 0) // ensure positive zero
graphMin = 0;
graphMax = roundUp(bMax, bUnit);
if (graphMax == 0)
graphMax = 0;
} else {
if (isReversed) {
graphMin = max;
graphMax = min;
} else {
graphMin = min;
graphMax = max;
}
}
if (bUnit.compareTo(BREL_ERROR.multiply(magnitude)) <= 0) {
intervals = -1; // signal that we hit the limit of precision
} else {
intervals = (int) Math.round((graphMax - graphMin) / bUnit.doubleValue());
}
} while (intervals > maxTicks && --nTicks > 0);
if (isReversed) {
double t = graphMin;
graphMin = graphMax;
graphMax = t;
}
double tickUnit = isReversed ? -bUnit.doubleValue() : bUnit.doubleValue();
/**
* We get the labelled max and min for determining the precision which
* the ticks should be shown at.
*/
int d = bUnit.scale() == bUnit.precision() ? -bUnit.scale() : bUnit.precision() - bUnit.scale() - 1;
int p = (int) Math.max(Math.floor(Math.log10(Math.abs(graphMin))), Math.floor(Math.log10(Math.abs(graphMax))));
// System.err.println("P: " + bUnit.precision() + ", S: " +
// bUnit.scale() + " => " + d + ", " + p);
if (p <= DIGITS_LOWER_LIMIT || p >= DIGITS_UPPER_LIMIT) {
createFormatString(Math.max(p - d, 0), true);
} else {
createFormatString(Math.max(-d, 0), false);
}
return tickUnit;
}
private boolean inRange(double x, double min, double max) {
if (isReversed) {
return x >= max && x <= min;
}
return x >= min && x <= max;
}
/**
* Generate a list of ticks that span range given by min and max. The maximum number of
* ticks is exceed by one in the case where the range straddles zero.
* @param min
* @param max
* @param maxTicks
* @param allowMinMaxOver allow min/maximum overwrite
* @param tight if true then remove ticks outside range
* @return a list of the ticks for the axis
*/
public List<Tick> generateTicks(double min, double max, int maxTicks,
boolean allowMinMaxOver, final boolean tight) {
List<Tick> ticks = new ArrayList<Tick>();
double tickUnit = determineNumTicks(min, max, maxTicks, allowMinMaxOver);
if (tickUnit == 0)
return ticks;
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
if (Math.abs(p/tickUnit) < REL_ERROR)
p = 0; // ensure positive zero
boolean r = inRange(p, min, max);
if (!tight || r) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
}
int imax = ticks.size();
if (imax > 1) {
if (!tight && allowMinMaxOver) {
Tick t = ticks.get(imax - 1);
if (!isReversed && t.getValue() < max) { // last is >= max
t.setValue(graphMax);
t.setText(getTickString(graphMax));
}
}
} else if (maxTicks > 1) {
if (imax == 0) {
imax++;
Tick newTick = new Tick();
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
if (isReversed) {
newTick.setPosition(1);
} else {
newTick.setPosition(0);
}
ticks.add(newTick);
}
if (imax == 1) {
Tick t = ticks.get(0);
Tick newTick = new Tick();
if (t.getText().equals(getTickString(graphMax))) {
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
ticks.add(0, newTick);
} else {
newTick.setValue(graphMax);
newTick.setText(getTickString(graphMax));
ticks.add(newTick);
}
imax++;
}
}
double lo = tight ? min : ticks.get(0).getValue();
double hi = tight ? max : (imax > 1 ? ticks.get(imax - 1).getValue() : lo);
double range = imax > 1 ? hi - lo : 1;
if (isReversed) {
for (Tick t : ticks) {
t.setPosition(1 - (t.getValue() - lo) / range);
}
} else {
for (Tick t : ticks) {
t.setPosition((t.getValue() - lo) / range);
}
}
return ticks;
}
private static final DecimalFormat CUSTOM_FORMAT = new DecimalFormat("#####0.000");
private static final DecimalFormat INDEX_FORMAT = new DecimalFormat("0");
/**
* Generate a list of ticks that span range given by min and max.
* @param min
* @param max
* @param maxTicks
* @param tight if true then remove ticks outside range (ignored)
* @return a list of the ticks for the axis
*/
public List<Tick> generateIndexBasedTicks(double min, double max, int maxTicks, boolean tight) {
isReversed = min > max;
if (isReversed) {
double t = max;
max = min;
min = t;
}
List<Tick> ticks = new ArrayList<Tick>();
double gRange = nicenum(BigDecimal.valueOf(max - min), false).doubleValue();
double tickUnit = 1;
intervals = 0;
int it = maxTicks - 1;
while (intervals < 1) {
tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange / it++), true).doubleValue());
tickUnit = Math.floor(tickUnit); // make integer
graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit);
graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit);
intervals = (int) Math.floor((graphMax - graphMin) / tickUnit);
+ if (tickUnit == 1) {
+ break;
+ }
}
switch (formatOfTicks) {
case autoMode:
tickFormat = "%g";
break;
case useExponent:
tickFormat = "%e";
break;
default:
tickFormat = null;
break;
}
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
int imax = ticks.size();
double range = imax > 1 ? max - min : 1;
for (Tick t : ticks) {
t.setPosition((t.getValue() - min) / range);
}
if (isReversed) {
Collections.reverse(ticks);
}
if (formatOfTicks == TickFormatting.autoMode) { // override labels
- if (scale.areLabelCustomised()) {
+ if (scale != null && scale.areLabelCustomised()) {
double vmin = Double.POSITIVE_INFINITY;
double vmax = Double.NEGATIVE_INFINITY;
boolean allInts = true;
for (Tick t : ticks) {
double v = Math.abs(scale.getLabel(t.getValue()));
if (Double.isNaN(v))
continue;
if (allInts) {
allInts = Math.abs(v - Math.floor(v)) == 0;
}
v = Math.abs(v);
if (v < vmin && v > 0)
vmin = v;
if (v > vmax)
vmax = v;
}
if (allInts) {
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
if (!Double.isNaN(v))
t.setText(INDEX_FORMAT.format(v));
}
} else if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) {
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
if (!Double.isNaN(v))
t.setText(CUSTOM_FORMAT.format(v));
}
}
} else {
for (Tick t : ticks) {
t.setText(INDEX_FORMAT.format(t.getValue()));
}
}
}
return ticks;
}
private double determineNumLogTicks(double min, double max, int maxTicks,
boolean allowMinMaxOver) {
final boolean isReverse = min > max;
final int loDecade; // lowest decade (or power of ten)
final int hiDecade;
if (isReverse) {
loDecade = (int) Math.floor(Math.log10(max));
hiDecade = (int) Math.ceil(Math.log10(min));
} else {
loDecade = (int) Math.floor(Math.log10(min));
hiDecade = (int) Math.ceil(Math.log10(max));
}
int decades = hiDecade - loDecade;
int unit = 0;
int n;
do {
n = decades/++unit;
} while (n > maxTicks);
double tickUnit = isReverse ? Math.pow(10, -unit) : Math.pow(10, unit);
if (allowMinMaxOver) {
graphMin = Math.pow(10, loDecade);
graphMax = Math.pow(10, hiDecade);
} else {
graphMin = min;
graphMax = max;
}
if (isReverse) {
double t = graphMin;
graphMin = graphMax;
graphMax = t;
}
createFormatString((int) Math.max(-Math.floor(loDecade), 0), false);
return tickUnit;
}
/**
* @param min
* @param max
* @param maxTicks
* @param allowMinMaxOver allow min/maximum overwrite
* @param tight if true then remove ticks outside range
* @return a list of the ticks for the axis
*/
public List<Tick> generateLogTicks(double min, double max, int maxTicks,
boolean allowMinMaxOver, final boolean tight) {
List<Tick> ticks = new ArrayList<Tick>();
double tickUnit = determineNumLogTicks(min, max, maxTicks, allowMinMaxOver);
double p = graphMin;
if (tickUnit > 1) {
final double pmax = graphMax * Math.sqrt(tickUnit);
while (p < pmax) {
if (!tight || (p >= min && p <= max))
if (allowMinMaxOver || p <= max) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
double newTickValue = p * tickUnit;
if (p == newTickValue)
break;
p = newTickValue;
}
final int imax = ticks.size();
if (imax == 1) {
ticks.get(0).setPosition(0.5);
} else if (imax > 1) {
double lo = Math.log(tight ? min : ticks.get(0).getValue());
double hi = Math.log(tight ? max : ticks.get(imax - 1).getValue());
double range = hi - lo;
for (Tick t : ticks) {
t.setPosition((Math.log(t.getValue()) - lo) / range);
}
}
} else {
final double pmin = graphMax * Math.sqrt(tickUnit);
while (p > pmin) {
if (!tight || (p >= max && p <= min))
if (allowMinMaxOver || p <= max) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
}
double newTickValue = p * tickUnit;
if (p == newTickValue)
break;
p = newTickValue;
}
final int imax = ticks.size();
if (imax == 1) {
ticks.get(0).setPosition(0.5);
} else if (imax > 1) {
double lo = Math.log(tight ? max : ticks.get(0).getValue());
double hi = Math.log(tight ? min : ticks.get(imax - 1).getValue());
double range = hi - lo;
for (Tick t : ticks) {
t.setPosition(1 - (Math.log(t.getValue()) - lo) / range);
}
}
}
return ticks;
}
}
| false | true | public List<Tick> generateIndexBasedTicks(double min, double max, int maxTicks, boolean tight) {
isReversed = min > max;
if (isReversed) {
double t = max;
max = min;
min = t;
}
List<Tick> ticks = new ArrayList<Tick>();
double gRange = nicenum(BigDecimal.valueOf(max - min), false).doubleValue();
double tickUnit = 1;
intervals = 0;
int it = maxTicks - 1;
while (intervals < 1) {
tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange / it++), true).doubleValue());
tickUnit = Math.floor(tickUnit); // make integer
graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit);
graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit);
intervals = (int) Math.floor((graphMax - graphMin) / tickUnit);
}
switch (formatOfTicks) {
case autoMode:
tickFormat = "%g";
break;
case useExponent:
tickFormat = "%e";
break;
default:
tickFormat = null;
break;
}
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
int imax = ticks.size();
double range = imax > 1 ? max - min : 1;
for (Tick t : ticks) {
t.setPosition((t.getValue() - min) / range);
}
if (isReversed) {
Collections.reverse(ticks);
}
if (formatOfTicks == TickFormatting.autoMode) { // override labels
if (scale.areLabelCustomised()) {
double vmin = Double.POSITIVE_INFINITY;
double vmax = Double.NEGATIVE_INFINITY;
boolean allInts = true;
for (Tick t : ticks) {
double v = Math.abs(scale.getLabel(t.getValue()));
if (Double.isNaN(v))
continue;
if (allInts) {
allInts = Math.abs(v - Math.floor(v)) == 0;
}
v = Math.abs(v);
if (v < vmin && v > 0)
vmin = v;
if (v > vmax)
vmax = v;
}
if (allInts) {
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
if (!Double.isNaN(v))
t.setText(INDEX_FORMAT.format(v));
}
} else if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) {
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
if (!Double.isNaN(v))
t.setText(CUSTOM_FORMAT.format(v));
}
}
} else {
for (Tick t : ticks) {
t.setText(INDEX_FORMAT.format(t.getValue()));
}
}
}
return ticks;
}
| public List<Tick> generateIndexBasedTicks(double min, double max, int maxTicks, boolean tight) {
isReversed = min > max;
if (isReversed) {
double t = max;
max = min;
min = t;
}
List<Tick> ticks = new ArrayList<Tick>();
double gRange = nicenum(BigDecimal.valueOf(max - min), false).doubleValue();
double tickUnit = 1;
intervals = 0;
int it = maxTicks - 1;
while (intervals < 1) {
tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange / it++), true).doubleValue());
tickUnit = Math.floor(tickUnit); // make integer
graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit);
graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit);
intervals = (int) Math.floor((graphMax - graphMin) / tickUnit);
if (tickUnit == 1) {
break;
}
}
switch (formatOfTicks) {
case autoMode:
tickFormat = "%g";
break;
case useExponent:
tickFormat = "%e";
break;
default:
tickFormat = null;
break;
}
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
int imax = ticks.size();
double range = imax > 1 ? max - min : 1;
for (Tick t : ticks) {
t.setPosition((t.getValue() - min) / range);
}
if (isReversed) {
Collections.reverse(ticks);
}
if (formatOfTicks == TickFormatting.autoMode) { // override labels
if (scale != null && scale.areLabelCustomised()) {
double vmin = Double.POSITIVE_INFINITY;
double vmax = Double.NEGATIVE_INFINITY;
boolean allInts = true;
for (Tick t : ticks) {
double v = Math.abs(scale.getLabel(t.getValue()));
if (Double.isNaN(v))
continue;
if (allInts) {
allInts = Math.abs(v - Math.floor(v)) == 0;
}
v = Math.abs(v);
if (v < vmin && v > 0)
vmin = v;
if (v > vmax)
vmax = v;
}
if (allInts) {
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
if (!Double.isNaN(v))
t.setText(INDEX_FORMAT.format(v));
}
} else if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) {
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
if (!Double.isNaN(v))
t.setText(CUSTOM_FORMAT.format(v));
}
}
} else {
for (Tick t : ticks) {
t.setText(INDEX_FORMAT.format(t.getValue()));
}
}
}
return ticks;
}
|
diff --git a/src/com/orangeleap/tangerine/service/impl/GiftServiceImpl.java b/src/com/orangeleap/tangerine/service/impl/GiftServiceImpl.java
index 139ea319..bd03b8e5 100644
--- a/src/com/orangeleap/tangerine/service/impl/GiftServiceImpl.java
+++ b/src/com/orangeleap/tangerine/service/impl/GiftServiceImpl.java
@@ -1,699 +1,700 @@
package com.orangeleap.tangerine.service.impl;
import java.io.FileWriter;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.orangeleap.tangerine.dao.GiftDao;
import com.orangeleap.tangerine.dao.SiteDao;
import com.orangeleap.tangerine.domain.PaymentHistory;
import com.orangeleap.tangerine.domain.PaymentSource;
import com.orangeleap.tangerine.domain.Person;
import com.orangeleap.tangerine.domain.communication.Address;
import com.orangeleap.tangerine.domain.communication.Phone;
import com.orangeleap.tangerine.domain.customization.EntityDefault;
import com.orangeleap.tangerine.domain.paymentInfo.Commitment;
import com.orangeleap.tangerine.domain.paymentInfo.DistributionLine;
import com.orangeleap.tangerine.domain.paymentInfo.Gift;
import com.orangeleap.tangerine.domain.paymentInfo.Pledge;
import com.orangeleap.tangerine.domain.paymentInfo.RecurringGift;
import com.orangeleap.tangerine.integration.NewGift;
import com.orangeleap.tangerine.service.GiftService;
import com.orangeleap.tangerine.service.PaymentHistoryService;
import com.orangeleap.tangerine.service.PledgeService;
import com.orangeleap.tangerine.service.RecurringGiftService;
import com.orangeleap.tangerine.type.EntityType;
import com.orangeleap.tangerine.type.FormBeanType;
import com.orangeleap.tangerine.type.GiftEntryType;
import com.orangeleap.tangerine.type.GiftType;
import com.orangeleap.tangerine.type.PaymentHistoryType;
import com.orangeleap.tangerine.util.RulesStack;
import com.orangeleap.tangerine.util.StringConstants;
import com.orangeleap.tangerine.web.common.PaginatedResult;
import com.orangeleap.tangerine.web.common.SortInfo;
@Service("giftService")
@Transactional(propagation = Propagation.REQUIRED)
public class GiftServiceImpl extends AbstractPaymentService implements GiftService, ApplicationContextAware {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
@Resource(name = "paymentHistoryService")
private PaymentHistoryService paymentHistoryService;
@Resource(name = "recurringGiftService")
private RecurringGiftService recurringGiftService;
@Resource(name = "pledgeService")
private PledgeService pledgeService;
@Resource(name = "giftDAO")
private GiftDao giftDao;
@Resource(name = "siteDAO")
private SiteDao siteDao;
private ApplicationContext context;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
context = applicationContext;
}
private final static String MAINTAIN_METHOD = "GiftServiceImpl.maintainGift";
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Gift maintainGift(Gift gift) {
boolean reentrant = RulesStack.push(MAINTAIN_METHOD);
try {
if (logger.isTraceEnabled()) {
logger.trace("maintainGift: gift = " + gift);
}
maintainEntityChildren(gift, gift.getPerson());
setDefaultDates(gift);
gift.filterValidDistributionLines();
gift = giftDao.maintainGift(gift);
if (!reentrant) {
paymentHistoryService.addPaymentHistory(createPaymentHistoryForGift(gift));
}
auditService.auditObject(gift, gift.getPerson());
//
// this needs to go last because we need the gift in the database
// in order for rules to work properly.
if (!reentrant) {
routeGift(gift);
}
return gift;
} finally {
RulesStack.pop(MAINTAIN_METHOD);
}
}
private void setDefaultDates(Gift gift) {
if (gift.getId() == null) {
Calendar transCal = Calendar.getInstance();
gift.setTransactionDate(transCal.getTime());
if (gift.getPostmarkDate() == null) {
Calendar postCal = new GregorianCalendar(transCal.get(Calendar.YEAR), transCal.get(Calendar.MONTH), transCal.get(Calendar.DAY_OF_MONTH));
gift.setPostmarkDate(postCal.getTime());
}
}
}
private final static String EDIT_METHOD = "GiftServiceImpl.editGift";
/*
* this is needed for JMS
*/
// @Resource(name = "creditGateway")
// private TangerineCreditGateway creditGateway;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Gift editGift(Gift gift) {
boolean reentrant = RulesStack.push(EDIT_METHOD);
try {
if (logger.isTraceEnabled()) {
logger.trace("editGift: giftId = " + gift.getId());
}
maintainEntityChildren(gift, gift.getPerson());
gift = giftDao.maintainGift(gift);
if (!reentrant) {
routeGift(gift);
}
auditService.auditObject(gift, gift.getPerson());
return gift;
} finally {
RulesStack.pop(EDIT_METHOD);
}
}
private final static String ROUTE_METHOD = "GiftServiceImpl.routeGift";
private void routeGift(Gift gift) {
RulesStack.push(ROUTE_METHOD);
try {
try {
NewGift newGift = (NewGift) context.getBean("newGift");
newGift.routeGift(gift);
}
catch (Exception ex) {
logger.error("RULES_FAILURE: " + ex.getMessage(), ex);
writeRulesFailureLog(ex.getMessage() + "\r\n" + gift);
}
} finally {
RulesStack.pop(ROUTE_METHOD);
}
}
private synchronized void writeRulesFailureLog(String message) {
try {
FileWriter out = new FileWriter("rules-errors.log");
try {
out.write(message);
} finally {
out.close();
}
} catch (Exception e) {
logger.error("Unable to write to rules error log file: "+message);
}
}
// private void processMockTrans(Gift gift) {
// this was a part of our JMS/MOM poc
// creditGateway.sendGiftTransaction(gift);
// }
private PaymentHistory createPaymentHistoryForGift(Gift gift) {
PaymentHistory paymentHistory = new PaymentHistory();
paymentHistory.setAmount(gift.getAmount());
paymentHistory.setCurrencyCode(gift.getCurrencyCode());
paymentHistory.setGift(gift);
paymentHistory.setPerson(gift.getPerson());
paymentHistory.setPaymentHistoryType(PaymentHistoryType.GIFT);
paymentHistory.setPaymentType(gift.getPaymentType());
paymentHistory.setTransactionDate(gift.getTransactionDate());
paymentHistory.setTransactionId("");
String desc = getGiftDescription(gift);
paymentHistory.setDescription(desc);
return paymentHistory;
}
private String getGiftDescription(Gift gift) {
StringBuilder sb = new StringBuilder();
// TODO: localize
if (PaymentSource.ACH.equals(gift.getPaymentType())) {
sb.append("ACH Number: ").append(gift.getSelectedPaymentSource().getAchAccountNumberDisplay());
}
if (PaymentSource.CREDIT_CARD.equals(gift.getPaymentType())) {
sb.append("Credit Card Number: ").append(gift.getSelectedPaymentSource().getCreditCardType()).append(" ").append(gift.getSelectedPaymentSource().getCreditCardNumberDisplay());
sb.append(" ");
sb.append(gift.getSelectedPaymentSource().getCreditCardExpirationMonth());
sb.append(" / ");
sb.append(gift.getSelectedPaymentSource().getCreditCardExpirationYear());
sb.append(" ");
sb.append(gift.getSelectedPaymentSource().getCreditCardHolderName());
}
if (PaymentSource.CHECK.equals(gift.getPaymentType())) {
sb.append("\nCheck Number: ");
sb.append(gift.getCheckNumber());
}
if (FormBeanType.NONE.equals(gift.getAddressType()) == false) {
Address address = gift.getSelectedAddress();
if (address != null) {
sb.append("\nAddress: ");
sb.append(StringUtils.trimToEmpty(address.getAddressLine1()));
sb.append(" ").append(StringUtils.trimToEmpty(address.getAddressLine2()));
sb.append(" ").append(StringUtils.trimToEmpty(address.getAddressLine3()));
sb.append(" ").append(StringUtils.trimToEmpty(address.getCity()));
String state = StringUtils.trimToEmpty(address.getStateProvince());
sb.append((state.length() == 0 ? "" : (", " + state))).append(" ");
sb.append(" ").append(StringUtils.trimToEmpty(address.getCountry()));
sb.append(" ").append(StringUtils.trimToEmpty(address.getPostalCode()));
}
}
if (FormBeanType.NONE.equals(gift.getPhoneType()) == false) {
Phone phone = gift.getSelectedPhone();
if (phone != null) {
sb.append("\nPhone: ");
sb.append(StringUtils.trimToEmpty(phone.getNumber()));
}
}
return sb.toString();
}
@Override
public Gift readGiftById(Long giftId) {
if (logger.isTraceEnabled()) {
logger.trace("readGiftById: giftId = " + giftId);
}
return giftDao.readGiftById(giftId);
}
@Override
public Gift readGiftByIdCreateIfNull(Person constituent, String giftId, String recurringGiftId, String pledgeId) {
if (logger.isTraceEnabled()) {
logger.trace("readGiftByIdCreateIfNull: giftId = " + giftId + " recurringGiftId = " + recurringGiftId +
"pledgeId = " + pledgeId + " constituentId = " + (constituent == null ? null : constituent.getId()));
}
Gift gift = null;
if (giftId == null) {
if (recurringGiftId != null) {
RecurringGift recurringGift = null;
recurringGift = recurringGiftService.readRecurringGiftById(Long.parseLong(recurringGiftId));
if (recurringGift == null) {
logger.error("readGiftByIdCreateIfNull: recurringGift not found for recurringGiftId = " + recurringGiftId);
return gift;
}
gift = this.createGift(recurringGift, GiftType.MONETARY_GIFT, GiftEntryType.MANUAL);
}
else if (pledgeId != null) {
Pledge pledge = null;
pledge = pledgeService.readPledgeById(Long.parseLong(pledgeId));
if (pledge == null) {
logger.error("readGiftByIdCreateIfNull: pledge not found for pledgeId = " + pledgeId);
return gift;
}
gift = this.createGift(pledge, GiftType.MONETARY_GIFT, GiftEntryType.MANUAL);
}
if (gift == null) {
if (constituent != null) {
gift = this.createDefaultGift(constituent);
}
}
}
else {
gift = this.readGiftById(Long.valueOf(giftId));
}
return gift;
}
@Override
public List<Gift> readMonetaryGifts(Person constituent) {
return readMonetaryGifts(constituent.getId());
}
@Override
public List<Gift> readMonetaryGifts(Long constituentId) {
if (logger.isTraceEnabled()) {
logger.trace("readMonetaryGifts: constituentId = " + constituentId);
}
return giftDao.readMonetaryGiftsByConstituentId(constituentId);
}
@Override
public PaginatedResult readPaginatedMonetaryGifts(Long constituentId, SortInfo sortinfo) {
if (logger.isTraceEnabled()) {
logger.trace("readPaginatedMonetaryGifts: constituentId = " + constituentId);
}
return giftDao.readPaginatedMonetaryGiftsByConstituentId(constituentId, sortinfo);
}
@Override
public List<Gift> searchGifts(Map<String, Object> params) {
if (logger.isTraceEnabled()) {
logger.trace("readGifts: params = " + params);
}
return giftDao.searchGifts(params);
}
@Override
public Gift createDefaultGift(Person constituent) {
if (logger.isTraceEnabled()) {
logger.trace("createDefaultGift: constituent = " + (constituent == null ? null : constituent.getId()));
}
// get initial gift with built-in defaults
Gift gift = new Gift();
BeanWrapper giftBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(gift);
List<EntityDefault> entityDefaults = siteDao.readEntityDefaults(Arrays.asList(new EntityType[] { EntityType.gift }));
for (EntityDefault ed : entityDefaults) {
giftBeanWrapper.setPropertyValue(ed.getEntityFieldName(), ed.getDefaultValue());
}
gift.setPerson(constituent);
List<DistributionLine> lines = new ArrayList<DistributionLine>(1);
DistributionLine line = new DistributionLine(constituent);
line.setDefaults();
line.setGiftId(gift.getId());
lines.add(line);
gift.setDistributionLines(lines);
// TODO: consider caching techniques for the default Gift
return gift;
}
@Override
public Gift createGift(Commitment commitment, GiftType giftType, GiftEntryType giftEntryType) {
if (logger.isTraceEnabled()) {
logger.trace("createGift: commitment = " + commitment + " giftType = " + giftType + " giftEntryType = " + giftEntryType);
}
Gift gift = new Gift();
gift.setPerson(commitment.getPerson());
if (commitment instanceof RecurringGift) {
gift.setRecurringGiftId(commitment.getId());
}
else if (commitment instanceof Pledge) {
gift.setPledgeId(commitment.getId());
}
gift.setComments(commitment.getComments());
gift.setAmount(commitment.getAmountPerGift());
gift.setPaymentType(commitment.getPaymentType());
gift.setPaymentSource(commitment.getPaymentSource());
gift.setGiftType(giftType);
gift.setEntryType(giftEntryType);
if (commitment.getDistributionLines() != null) {
List<DistributionLine> list = new ArrayList<DistributionLine>();
for (DistributionLine oldLine : commitment.getDistributionLines()) {
DistributionLine newLine = new DistributionLine(oldLine, gift.getId());
list.add(newLine);
}
gift.setDistributionLines(list);
}
gift.setAddress(commitment.getAddress());
gift.setPhone(commitment.getPhone());
return gift;
}
@Override
public double analyzeMajorDonor(Long constituentId, Date beginDate, Date currentDate) {
if (logger.isTraceEnabled()) {
logger.trace("analyzeMajorDonor: constituentId = " + constituentId + " beginDate = " + beginDate + " currentDate = " + currentDate);
}
return giftDao.analyzeMajorDonor(constituentId, beginDate, currentDate);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void adjustGift(Gift gift) {
if (logger.isDebugEnabled()) {
logger.debug("adjustGift: giftId = " + gift.getId());
}
//TODO - DRAFT functionality. Need to bounce off Karie
try {
// get the original gift to compare against
Gift originalGift = readGiftById(gift.getId());
// clone the incoming gift; we'll use as a template
Gift adjustedGift = (Gift) BeanUtils.cloneBean(gift);
adjustedGift.resetIdToNull();
adjustedGift.setTransactionDate( gift.getRefundGiftTransactionDate());
// clear these from the adjustment, we'll put them on the original
adjustedGift.setRefundGiftId(null);
adjustedGift.setGiftType(GiftType.ADJUSTMENT);
adjustedGift.setDeductibleAmount(adjustedGift.getAmount());
adjustedGift.setOriginalGiftId(originalGift.getId());
adjustedGift.setPaymentStatus(null);
adjustedGift.setPaymentType(null);
adjustedGift.setPostmarkDate(null);
// make sure we really have an adjustment
if(adjustedGift.getAmount().equals(BigDecimal.ZERO) ) {
// if no amout difference, don't save anything
logger.debug("adjustGift: adjustment amout = 0; exiting method");
return;
}
// save our adjustment, which gets us the new ID
adjustedGift = maintainGift(adjustedGift);
+ gift.setId(adjustedGift.getId());
// set the refund (adjustment) details on the original and save it
originalGift.setRefundGiftId(adjustedGift.getId());
originalGift.setRefundGiftTransactionDate(adjustedGift.getTransactionDate());
maintainGift(originalGift);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Gift refundGift(Long giftId) {
if (logger.isTraceEnabled()) {
logger.trace("refundGift: giftId = " + giftId);
}
Gift originalGift = giftDao.readGiftById(giftId);
try {
Gift refundGift = (Gift) BeanUtils.cloneBean(originalGift);
refundGift.resetIdToNull();
refundGift.setTransactionDate(null);
refundGift.getPaymentSource().setCreditCardExpiration(null);
refundGift.setAmount(originalGift.getAmount().negate());
refundGift.setOriginalGiftId(originalGift.getId());
refundGift = maintainGift(refundGift);
originalGift.filterValidDistributionLines();
List<DistributionLine> lines = originalGift.getDistributionLines();
List<DistributionLine> refundLines = new ArrayList<DistributionLine>();
for (DistributionLine line : lines) {
BigDecimal negativeAmount = line.getAmount() == null ? null : line.getAmount().negate();
DistributionLine newLine = new DistributionLine(negativeAmount, line.getPercentage(), line.getProjectCode(), line.getMotivationCode(), line.getOther_motivationCode());
newLine.setGiftId(refundGift.getId());
refundLines.add(newLine);
}
refundGift.setDistributionLines(refundLines);
originalGift.setRefundGiftId(refundGift.getId());
originalGift.setRefundGiftTransactionDate(refundGift.getTransactionDate());
maintainGift(originalGift);
auditService.auditObject(refundGift, refundGift.getPerson());
return refundGift;
} catch (IllegalAccessException e) {
throw new IllegalStateException();
} catch (InstantiationException e) {
throw new IllegalStateException();
} catch (InvocationTargetException e) {
throw new IllegalStateException();
} catch (NoSuchMethodException e) {
throw new IllegalStateException();
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<Gift> readMonetaryGiftsByConstituentId(Long constituentId) {
if (logger.isTraceEnabled()) {
logger.trace("readMonetaryGiftsByConstituentId: constituentId = " + constituentId);
}
return giftDao.readMonetaryGiftsByConstituentId(constituentId);
}
// @Override
// @Transactional(propagation = Propagation.REQUIRED)
// THIS METHOD IS NOT USED ANYWHERE TODO: remove?
// public List<Gift> readAllGifts() {
// return giftDao.readAllGifts();
// }
// THIS METHOD IS NOT USED ANYWHERE TODO: remove?
@Override
public List<Gift> readGiftsByRecurringGiftId(RecurringGift recurringGift) {
if (logger.isTraceEnabled()) {
logger.trace("readGiftsByRecurringGiftId: recurringGiftId = " + recurringGift.getId());
}
return giftDao.readGiftsByRecurringGiftId(recurringGift.getId());
}
// THIS METHOD IS NOT USED ANYWHERE TODO: remove?
@Override
public List<Gift> readGiftsByPledgeId(Pledge pledge) {
if (logger.isTraceEnabled()) {
logger.trace("readGiftsByPledgeId: pledgeId = " + pledge.getId());
}
return giftDao.readGiftsByPledgeId(pledge.getId());
}
@Override
public List<Gift> readAllGiftsByDateRange(Date fromDate, Date toDate) {
if (logger.isTraceEnabled()) {
logger.trace("readAllGiftsByDateRange:");
}
return giftDao.readAllGiftsByDateRange(fromDate, toDate);
}
@Override
public List<Gift> readAllGiftsBySiteName() {
if (logger.isTraceEnabled()) {
logger.trace("readAllGiftsBySiteName:");
}
return giftDao.readAllGiftsBySite();
}
@Override
public List<DistributionLine> combineGiftPledgeDistributionLines(List<DistributionLine> giftDistributionLines, List<DistributionLine> pledgeLines, BigDecimal amount, int numPledges, Person constituent) {
if (logger.isTraceEnabled()) {
logger.trace("combineGiftPledgeDistributionLines: amount = " + amount + " numPledges = " + numPledges);
}
List<DistributionLine> returnLines = new ArrayList<DistributionLine>();
giftDistributionLines = removeDefaultDistributionLine(giftDistributionLines, amount, constituent);
if ((pledgeLines == null || pledgeLines.isEmpty()) && giftDistributionLines != null) {
// NO pledge distribution lines associated with this gift; only add gift distribution lines that have no pledge associations
for (DistributionLine giftLine : giftDistributionLines) {
if (giftLine != null && giftLine.isFieldEntered()) {
if (org.springframework.util.StringUtils.hasText(giftLine.getCustomFieldValue(StringConstants.ASSOCIATED_PLEDGE_ID)) == false) {
returnLines.add(giftLine);
}
}
}
}
else if ((giftDistributionLines == null || giftDistributionLines.isEmpty()) && pledgeLines != null) {
initPledgeDistributionLine(pledgeLines, returnLines, numPledges, amount);
}
else if (pledgeLines != null && giftDistributionLines != null) {
for (DistributionLine aLine : giftDistributionLines) {
if (aLine != null && aLine.isFieldEntered()) {
String associatedPledgeId = aLine.getCustomFieldValue(StringConstants.ASSOCIATED_PLEDGE_ID);
if (org.springframework.util.StringUtils.hasText(associatedPledgeId) == false) {
returnLines.add(aLine); // No associated pledgeIds, so just copy the line
}
else {
for (Iterator<DistributionLine> pledgeLineIter = pledgeLines.iterator(); pledgeLineIter.hasNext();) {
DistributionLine pledgeLine = pledgeLineIter.next();
Long associatedPledgeIdLong = Long.parseLong(associatedPledgeId);
if (associatedPledgeIdLong.equals(pledgeLine.getPledgeId())) {
pledgeLineIter.remove();
returnLines.add(aLine); // Has an existing pledgeId, so copy the line; gift distribution lines with an associated pledgeId that is not in the list of pledgeLines will not be copied
break;
}
}
}
}
}
initPledgeDistributionLine(pledgeLines, returnLines, numPledges, amount);
}
return returnLines;
}
/**
* Check if a default distribution line was created; remove if necessary
* @param giftDistributionLines
*/
public List<DistributionLine> removeDefaultDistributionLine(List<DistributionLine> giftDistributionLines, BigDecimal amount, Person constituent) {
if (logger.isTraceEnabled()) {
logger.trace("removeDefaultDistributionLine: amount = " + amount);
}
int count = 0;
DistributionLine enteredLine = null;
if (giftDistributionLines != null) {
for (DistributionLine aLine : giftDistributionLines) {
if (aLine != null) {
enteredLine = aLine;
count++;
}
}
}
/* If only 1 line is entered, check if it is the default */
if (count == 1) {
DistributionLine defaultLine = new DistributionLine(constituent);
defaultLine.setDefaults();
if (amount.equals(enteredLine.getAmount()) && new BigDecimal("100").equals(enteredLine.getPercentage())) {
if (org.springframework.util.StringUtils.hasText(enteredLine.getProjectCode()) || org.springframework.util.StringUtils.hasText(enteredLine.getMotivationCode()) ||
org.springframework.util.StringUtils.hasText(enteredLine.getOther_motivationCode()) || enteredLine.getAssociatedPledgeId() != null) {
// do nothing
}
else {
boolean isSame = true;
Set<String> keys = enteredLine.getCustomFieldMap().keySet();
for (String aKey : keys) {
// Empty string and null are considered equivalent values for custom fields
if ((enteredLine.getCustomFieldValue(aKey) == null || StringConstants.EMPTY.equals(enteredLine.getCustomFieldValue(aKey)))
&& (defaultLine.getCustomFieldValue(aKey) == null || StringConstants.EMPTY.equals(defaultLine.getCustomFieldValue(aKey)))) {
// do nothing
}
else if (enteredLine.getCustomFieldValue(aKey) != null && enteredLine.getCustomFieldValue(aKey).equals(defaultLine.getCustomFieldValue(aKey))) {
// do nothing
}
else {
isSame = false;
break;
}
}
if (isSame) {
return new ArrayList<DistributionLine>();
}
}
}
}
return giftDistributionLines;
}
private void initPledgeDistributionLine(List<DistributionLine> pledgeLines, List<DistributionLine> returnLines, int numPledges, BigDecimal amount) {
BigDecimal splitPledgeAmount = BigDecimal.ZERO;
if (numPledges > 0) {
splitPledgeAmount = amount.divide(new BigDecimal(numPledges), 10, BigDecimal.ROUND_HALF_EVEN);
}
for (DistributionLine pLine : pledgeLines) {
pLine.addCustomFieldValue(StringConstants.ASSOCIATED_PLEDGE_ID, pLine.getPledgeId().toString());
pLine.setPledgeId(null);
pLine.setAmount(pLine.getPercentage().multiply(splitPledgeAmount).divide(new BigDecimal("100"), 10, BigDecimal.ROUND_HALF_EVEN).setScale(2, BigDecimal.ROUND_HALF_EVEN));
// find the new percentage (line percentage / numPledges)
pLine.setPercentage(pLine.getPercentage().divide(new BigDecimal(numPledges), 2, BigDecimal.ROUND_HALF_EVEN));
}
returnLines.addAll(pledgeLines); // Add the remaining pledge lines; these are the pledge distribution lines not already assigned to the gift
}
@Override
public void checkAssociatedPledgeIds(Gift gift) {
Set<Long> linePledgeIds = new HashSet<Long>();
for (DistributionLine line : gift.getMutableDistributionLines()) {
if (line != null) {
String associatedPledgeId = line.getCustomFieldValue(StringConstants.ASSOCIATED_PLEDGE_ID);
if (NumberUtils.isDigits(associatedPledgeId)) {
Long thisPledgeId = Long.parseLong(associatedPledgeId);
linePledgeIds.add(thisPledgeId);
if (gift.getAssociatedPledgeIds() == null || gift.getAssociatedPledgeIds().contains(thisPledgeId) == false) {
gift.addAssociatedPledgeId(thisPledgeId);
}
}
}
}
if (gift.getAssociatedPledgeIds() != null) {
for (Iterator<Long> iter = gift.getAssociatedPledgeIds().iterator(); iter.hasNext();) {
Long id = iter.next();
if (linePledgeIds.contains(id) == false) {
iter.remove();
}
}
}
}
}
| true | true | public void adjustGift(Gift gift) {
if (logger.isDebugEnabled()) {
logger.debug("adjustGift: giftId = " + gift.getId());
}
//TODO - DRAFT functionality. Need to bounce off Karie
try {
// get the original gift to compare against
Gift originalGift = readGiftById(gift.getId());
// clone the incoming gift; we'll use as a template
Gift adjustedGift = (Gift) BeanUtils.cloneBean(gift);
adjustedGift.resetIdToNull();
adjustedGift.setTransactionDate( gift.getRefundGiftTransactionDate());
// clear these from the adjustment, we'll put them on the original
adjustedGift.setRefundGiftId(null);
adjustedGift.setGiftType(GiftType.ADJUSTMENT);
adjustedGift.setDeductibleAmount(adjustedGift.getAmount());
adjustedGift.setOriginalGiftId(originalGift.getId());
adjustedGift.setPaymentStatus(null);
adjustedGift.setPaymentType(null);
adjustedGift.setPostmarkDate(null);
// make sure we really have an adjustment
if(adjustedGift.getAmount().equals(BigDecimal.ZERO) ) {
// if no amout difference, don't save anything
logger.debug("adjustGift: adjustment amout = 0; exiting method");
return;
}
// save our adjustment, which gets us the new ID
adjustedGift = maintainGift(adjustedGift);
// set the refund (adjustment) details on the original and save it
originalGift.setRefundGiftId(adjustedGift.getId());
originalGift.setRefundGiftTransactionDate(adjustedGift.getTransactionDate());
maintainGift(originalGift);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
| public void adjustGift(Gift gift) {
if (logger.isDebugEnabled()) {
logger.debug("adjustGift: giftId = " + gift.getId());
}
//TODO - DRAFT functionality. Need to bounce off Karie
try {
// get the original gift to compare against
Gift originalGift = readGiftById(gift.getId());
// clone the incoming gift; we'll use as a template
Gift adjustedGift = (Gift) BeanUtils.cloneBean(gift);
adjustedGift.resetIdToNull();
adjustedGift.setTransactionDate( gift.getRefundGiftTransactionDate());
// clear these from the adjustment, we'll put them on the original
adjustedGift.setRefundGiftId(null);
adjustedGift.setGiftType(GiftType.ADJUSTMENT);
adjustedGift.setDeductibleAmount(adjustedGift.getAmount());
adjustedGift.setOriginalGiftId(originalGift.getId());
adjustedGift.setPaymentStatus(null);
adjustedGift.setPaymentType(null);
adjustedGift.setPostmarkDate(null);
// make sure we really have an adjustment
if(adjustedGift.getAmount().equals(BigDecimal.ZERO) ) {
// if no amout difference, don't save anything
logger.debug("adjustGift: adjustment amout = 0; exiting method");
return;
}
// save our adjustment, which gets us the new ID
adjustedGift = maintainGift(adjustedGift);
gift.setId(adjustedGift.getId());
// set the refund (adjustment) details on the original and save it
originalGift.setRefundGiftId(adjustedGift.getId());
originalGift.setRefundGiftTransactionDate(adjustedGift.getTransactionDate());
maintainGift(originalGift);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
|
diff --git a/IpScrum/src/fhdw/ipscrum/client/presenter/PersonRolePresenter.java b/IpScrum/src/fhdw/ipscrum/client/presenter/PersonRolePresenter.java
index 46088c7..a3d5cac 100644
--- a/IpScrum/src/fhdw/ipscrum/client/presenter/PersonRolePresenter.java
+++ b/IpScrum/src/fhdw/ipscrum/client/presenter/PersonRolePresenter.java
@@ -1,210 +1,210 @@
package fhdw.ipscrum.client.presenter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Panel;
import fhdw.ipscrum.client.events.EventArgs;
import fhdw.ipscrum.client.events.EventHandler;
import fhdw.ipscrum.client.events.args.AssociatePersonAndRoleArgs;
import fhdw.ipscrum.client.events.args.MultipleRoleArgs;
import fhdw.ipscrum.client.events.args.PersonArgs;
import fhdw.ipscrum.client.view.PersonRoleView;
import fhdw.ipscrum.client.view.interfaces.IPersonRoleView;
import fhdw.ipscrum.shared.SessionManager;
import fhdw.ipscrum.shared.constants.TextConstants;
import fhdw.ipscrum.shared.exceptions.ConsistencyException;
import fhdw.ipscrum.shared.model.Person;
import fhdw.ipscrum.shared.model.interfaces.IPerson;
import fhdw.ipscrum.shared.model.interfaces.IRole;
/**
* Presenter for PersonRoleView. PRView is intended to be a central management console for persons and roles.
* It provides controls for creating, modifying and deleting persons and roles as well associate roles to persons or remove associations.
*/
public class PersonRolePresenter extends Presenter<IPersonRoleView> {
private IPersonRoleView concreteView;
/**
* Constructor for PersonRolePresenter.
* @param parent Panel
*/
public PersonRolePresenter(Panel parent) {
super(parent);
}
/**
* Method createView.
*
* @return IPersonRoleView
*/
@Override
protected IPersonRoleView createView() {
this.concreteView = new PersonRoleView();
this.updateGuiTables();
this.setupEventHandlers();
return this.concreteView;
}
/**
* This method is called to update or fill the GUI with the model-data.
*/
private void updateGuiTables() {
HashSet<IPerson> personSet = SessionManager.getInstance().getModel().getPersons();
this.concreteView.updatePersonTable(personSet);
Person selPerson = this.concreteView.getSelectedPerson();
if (selPerson != null) {
this.concreteView.updateAssignedRoles(selPerson.getRoles());
} else {
this.concreteView.updateAssignedRoles(new Vector<IRole>());
}
HashSet<IRole> roleSet = SessionManager.getInstance().getModel().getRoles();
this.concreteView.updateAvailRoleList(roleSet);
}
/**
* This method is called to set up the algorithms for each button of the GUI.
*/
private void setupEventHandlers() {
this.concreteView.defineNewPersonEventHandler(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
final DialogBox box = new DialogBox();
final PersonDialogPresenter presenter = new PersonDialogPresenter(box);
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(TextConstants.PERSONDIALOG_TITLE_CREATE);
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
box.center();
}
});
this.concreteView.defineModifyPersonEventHandler(new EventHandler<PersonArgs>() {
@Override
public void onUpdate(Object sender, PersonArgs eventArgs) {
final DialogBox box = new DialogBox();
final PersonDialogPresenter presenter = new PersonDialogPresenter(box, eventArgs.getPerson());
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(eventArgs.getPerson().getFirstname() + " bearbeiten");
box.center();
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
}
});
this.concreteView.defineRemoveRoleFromPersonEventHandler(new EventHandler<AssociatePersonAndRoleArgs>() {
@Override
public void onUpdate(Object sender, AssociatePersonAndRoleArgs eventArgs) {
if (eventArgs != null && eventArgs.getPerson() != null && eventArgs.getRoles().size() > 0) {
try {
eventArgs.getPerson().removeRole(eventArgs.getSingleRole());
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
PersonRolePresenter.this.updateGuiTables();
}
}
});
this.concreteView.defineAddRoleToPersonEventHandler(new EventHandler<AssociatePersonAndRoleArgs>() {
@Override
public void onUpdate(Object sender, AssociatePersonAndRoleArgs eventArgs) {
if (eventArgs != null && eventArgs.getPerson() != null && eventArgs.getRoles().size() > 0) {
Iterator<IRole> i = eventArgs.getRoles().iterator();
while (i.hasNext()) {
IRole current = i.next();
try {
eventArgs.getPerson().addRole(current);
} catch (ConsistencyException e) {
- Window.alert(e.getMessage());
+ // This error is not severe. The user will notice that the role he wants to add is already in posession of the selected user.
}
}
}
PersonRolePresenter.this.updateGuiTables();
}
});
this.concreteView.defineNewRoleEventHandler(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
final DialogBox box = new DialogBox();
final RoleDialogPresenter presenter = new RoleDialogPresenter(box);
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(TextConstants.ROLEDIALOG_TITLE_CREATE);
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
box.center();
}
});
this.concreteView.defineRemoveRoleEventHandler(new EventHandler<MultipleRoleArgs>() {
@Override
public void onUpdate(Object sender, MultipleRoleArgs eventArgs) {
for (IRole role : eventArgs.getRoles()) {
try {
SessionManager.getInstance().getModel().removeRole(role);
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
}
PersonRolePresenter.this.updateGuiTables();
}
});
}
}
| true | true | private void setupEventHandlers() {
this.concreteView.defineNewPersonEventHandler(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
final DialogBox box = new DialogBox();
final PersonDialogPresenter presenter = new PersonDialogPresenter(box);
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(TextConstants.PERSONDIALOG_TITLE_CREATE);
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
box.center();
}
});
this.concreteView.defineModifyPersonEventHandler(new EventHandler<PersonArgs>() {
@Override
public void onUpdate(Object sender, PersonArgs eventArgs) {
final DialogBox box = new DialogBox();
final PersonDialogPresenter presenter = new PersonDialogPresenter(box, eventArgs.getPerson());
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(eventArgs.getPerson().getFirstname() + " bearbeiten");
box.center();
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
}
});
this.concreteView.defineRemoveRoleFromPersonEventHandler(new EventHandler<AssociatePersonAndRoleArgs>() {
@Override
public void onUpdate(Object sender, AssociatePersonAndRoleArgs eventArgs) {
if (eventArgs != null && eventArgs.getPerson() != null && eventArgs.getRoles().size() > 0) {
try {
eventArgs.getPerson().removeRole(eventArgs.getSingleRole());
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
PersonRolePresenter.this.updateGuiTables();
}
}
});
this.concreteView.defineAddRoleToPersonEventHandler(new EventHandler<AssociatePersonAndRoleArgs>() {
@Override
public void onUpdate(Object sender, AssociatePersonAndRoleArgs eventArgs) {
if (eventArgs != null && eventArgs.getPerson() != null && eventArgs.getRoles().size() > 0) {
Iterator<IRole> i = eventArgs.getRoles().iterator();
while (i.hasNext()) {
IRole current = i.next();
try {
eventArgs.getPerson().addRole(current);
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
}
}
PersonRolePresenter.this.updateGuiTables();
}
});
this.concreteView.defineNewRoleEventHandler(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
final DialogBox box = new DialogBox();
final RoleDialogPresenter presenter = new RoleDialogPresenter(box);
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(TextConstants.ROLEDIALOG_TITLE_CREATE);
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
box.center();
}
});
this.concreteView.defineRemoveRoleEventHandler(new EventHandler<MultipleRoleArgs>() {
@Override
public void onUpdate(Object sender, MultipleRoleArgs eventArgs) {
for (IRole role : eventArgs.getRoles()) {
try {
SessionManager.getInstance().getModel().removeRole(role);
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
}
PersonRolePresenter.this.updateGuiTables();
}
});
}
| private void setupEventHandlers() {
this.concreteView.defineNewPersonEventHandler(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
final DialogBox box = new DialogBox();
final PersonDialogPresenter presenter = new PersonDialogPresenter(box);
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(TextConstants.PERSONDIALOG_TITLE_CREATE);
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
box.center();
}
});
this.concreteView.defineModifyPersonEventHandler(new EventHandler<PersonArgs>() {
@Override
public void onUpdate(Object sender, PersonArgs eventArgs) {
final DialogBox box = new DialogBox();
final PersonDialogPresenter presenter = new PersonDialogPresenter(box, eventArgs.getPerson());
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(eventArgs.getPerson().getFirstname() + " bearbeiten");
box.center();
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
}
});
this.concreteView.defineRemoveRoleFromPersonEventHandler(new EventHandler<AssociatePersonAndRoleArgs>() {
@Override
public void onUpdate(Object sender, AssociatePersonAndRoleArgs eventArgs) {
if (eventArgs != null && eventArgs.getPerson() != null && eventArgs.getRoles().size() > 0) {
try {
eventArgs.getPerson().removeRole(eventArgs.getSingleRole());
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
PersonRolePresenter.this.updateGuiTables();
}
}
});
this.concreteView.defineAddRoleToPersonEventHandler(new EventHandler<AssociatePersonAndRoleArgs>() {
@Override
public void onUpdate(Object sender, AssociatePersonAndRoleArgs eventArgs) {
if (eventArgs != null && eventArgs.getPerson() != null && eventArgs.getRoles().size() > 0) {
Iterator<IRole> i = eventArgs.getRoles().iterator();
while (i.hasNext()) {
IRole current = i.next();
try {
eventArgs.getPerson().addRole(current);
} catch (ConsistencyException e) {
// This error is not severe. The user will notice that the role he wants to add is already in posession of the selected user.
}
}
}
PersonRolePresenter.this.updateGuiTables();
}
});
this.concreteView.defineNewRoleEventHandler(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
final DialogBox box = new DialogBox();
final RoleDialogPresenter presenter = new RoleDialogPresenter(box);
box.setAnimationEnabled(true);
box.setAutoHideEnabled(true);
box.setGlassEnabled(true);
box.setText(TextConstants.ROLEDIALOG_TITLE_CREATE);
presenter.getFinished().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
PersonRolePresenter.this.updateGuiTables();
box.hide();
}
});
presenter.getAborted().add(new EventHandler<EventArgs>() {
@Override
public void onUpdate(Object sender, EventArgs eventArgs) {
box.hide();
}
});
box.center();
}
});
this.concreteView.defineRemoveRoleEventHandler(new EventHandler<MultipleRoleArgs>() {
@Override
public void onUpdate(Object sender, MultipleRoleArgs eventArgs) {
for (IRole role : eventArgs.getRoles()) {
try {
SessionManager.getInstance().getModel().removeRole(role);
} catch (ConsistencyException e) {
Window.alert(e.getMessage());
}
}
PersonRolePresenter.this.updateGuiTables();
}
});
}
|
diff --git a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java
index 3bcbe8011..7ee0f2d3b 100644
--- a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java
+++ b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java
@@ -1,2991 +1,2995 @@
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.AddVmFromScratchParameters;
import org.ovirt.engine.core.common.action.AddVmFromTemplateParameters;
import org.ovirt.engine.core.common.action.AddVmTemplateParameters;
import org.ovirt.engine.core.common.action.AttachEntityToTagParameters;
import org.ovirt.engine.core.common.action.ChangeDiskCommandParameters;
import org.ovirt.engine.core.common.action.ChangeVMClusterParameters;
import org.ovirt.engine.core.common.action.HibernateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmToServerParameters;
import org.ovirt.engine.core.common.action.MoveVmParameters;
import org.ovirt.engine.core.common.action.RemoveVmParameters;
import org.ovirt.engine.core.common.action.RunVmOnceParams;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.ShutdownVmParameters;
import org.ovirt.engine.core.common.action.StopVmParameters;
import org.ovirt.engine.core.common.action.StopVmTypeEnum;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VmManagementParametersBase;
import org.ovirt.engine.core.common.action.VmOperationParameterBase;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.MigrationSupport;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.UsbPolicy;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.VmOsType;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VmType;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParamenters;
import org.ovirt.engine.core.common.queries.GetVmByVmIdParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.ObservableCollection;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Cloner;
import org.ovirt.engine.ui.uicommonweb.DataProvider;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.TagsEqualityComparer;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ISupportSystemTreeContext;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.ChangeCDModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.tags.TagListModel;
import org.ovirt.engine.ui.uicommonweb.models.tags.TagModel;
import org.ovirt.engine.ui.uicommonweb.models.userportal.AttachCdModel;
import org.ovirt.engine.ui.uicompat.Assembly;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.ResourceManager;
@SuppressWarnings("unused")
public class VmListModel extends ListWithDetailsModel implements ISupportSystemTreeContext
{
private UICommand privateNewServerCommand;
public UICommand getNewServerCommand()
{
return privateNewServerCommand;
}
private void setNewServerCommand(UICommand value)
{
privateNewServerCommand = value;
}
private UICommand privateNewDesktopCommand;
public UICommand getNewDesktopCommand()
{
return privateNewDesktopCommand;
}
private void setNewDesktopCommand(UICommand value)
{
privateNewDesktopCommand = value;
}
private UICommand privateEditCommand;
public UICommand getEditCommand()
{
return privateEditCommand;
}
private void setEditCommand(UICommand value)
{
privateEditCommand = value;
}
private UICommand privateRemoveCommand;
public UICommand getRemoveCommand()
{
return privateRemoveCommand;
}
private void setRemoveCommand(UICommand value)
{
privateRemoveCommand = value;
}
private UICommand privateRunCommand;
public UICommand getRunCommand()
{
return privateRunCommand;
}
private void setRunCommand(UICommand value)
{
privateRunCommand = value;
}
private UICommand privatePauseCommand;
public UICommand getPauseCommand()
{
return privatePauseCommand;
}
private void setPauseCommand(UICommand value)
{
privatePauseCommand = value;
}
private UICommand privateStopCommand;
public UICommand getStopCommand()
{
return privateStopCommand;
}
private void setStopCommand(UICommand value)
{
privateStopCommand = value;
}
private UICommand privateShutdownCommand;
public UICommand getShutdownCommand()
{
return privateShutdownCommand;
}
private void setShutdownCommand(UICommand value)
{
privateShutdownCommand = value;
}
private UICommand privateCancelMigrateCommand;
public UICommand getCancelMigrateCommand() {
return privateCancelMigrateCommand;
}
private void setCancelMigrateCommand(UICommand value) {
privateCancelMigrateCommand = value;
}
private UICommand privateMigrateCommand;
public UICommand getMigrateCommand()
{
return privateMigrateCommand;
}
private void setMigrateCommand(UICommand value)
{
privateMigrateCommand = value;
}
private UICommand privateNewTemplateCommand;
public UICommand getNewTemplateCommand()
{
return privateNewTemplateCommand;
}
private void setNewTemplateCommand(UICommand value)
{
privateNewTemplateCommand = value;
}
private UICommand privateRunOnceCommand;
public UICommand getRunOnceCommand()
{
return privateRunOnceCommand;
}
private void setRunOnceCommand(UICommand value)
{
privateRunOnceCommand = value;
}
private UICommand privateExportCommand;
public UICommand getExportCommand()
{
return privateExportCommand;
}
private void setExportCommand(UICommand value)
{
privateExportCommand = value;
}
private UICommand privateMoveCommand;
public UICommand getMoveCommand()
{
return privateMoveCommand;
}
private void setMoveCommand(UICommand value)
{
privateMoveCommand = value;
}
private UICommand privateRetrieveIsoImagesCommand;
public UICommand getRetrieveIsoImagesCommand()
{
return privateRetrieveIsoImagesCommand;
}
private void setRetrieveIsoImagesCommand(UICommand value)
{
privateRetrieveIsoImagesCommand = value;
}
private UICommand privateGuideCommand;
public UICommand getGuideCommand()
{
return privateGuideCommand;
}
private void setGuideCommand(UICommand value)
{
privateGuideCommand = value;
}
private UICommand privateChangeCdCommand;
public UICommand getChangeCdCommand()
{
return privateChangeCdCommand;
}
private void setChangeCdCommand(UICommand value)
{
privateChangeCdCommand = value;
}
private UICommand privateAssignTagsCommand;
public UICommand getAssignTagsCommand()
{
return privateAssignTagsCommand;
}
private void setAssignTagsCommand(UICommand value)
{
privateAssignTagsCommand = value;
}
private Model errorWindow;
public Model getErrorWindow()
{
return errorWindow;
}
public void setErrorWindow(Model value)
{
if (errorWindow != value)
{
errorWindow = value;
OnPropertyChanged(new PropertyChangedEventArgs("ErrorWindow"));
}
}
private ConsoleModel defaultConsoleModel;
public ConsoleModel getDefaultConsoleModel()
{
return defaultConsoleModel;
}
public void setDefaultConsoleModel(ConsoleModel value)
{
if (defaultConsoleModel != value)
{
defaultConsoleModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("DefaultConsoleModel"));
}
}
private ConsoleModel additionalConsoleModel;
public ConsoleModel getAdditionalConsoleModel()
{
return additionalConsoleModel;
}
public void setAdditionalConsoleModel(ConsoleModel value)
{
if (additionalConsoleModel != value)
{
additionalConsoleModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("AdditionalConsoleModel"));
}
}
private boolean hasAdditionalConsoleModel;
public boolean getHasAdditionalConsoleModel()
{
return hasAdditionalConsoleModel;
}
public void setHasAdditionalConsoleModel(boolean value)
{
if (hasAdditionalConsoleModel != value)
{
hasAdditionalConsoleModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasAdditionalConsoleModel"));
}
}
public ObservableCollection<ChangeCDModel> isoImages;
public ObservableCollection<ChangeCDModel> getIsoImages()
{
return isoImages;
}
private void setIsoImages(ObservableCollection<ChangeCDModel> value)
{
if ((isoImages == null && value != null) || (isoImages != null && !isoImages.equals(value)))
{
isoImages = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsoImages"));
}
}
// get { return SelectedItems == null ? new object[0] : SelectedItems.Cast<VM>().Select(a =>
// a.vm_guid).Cast<object>().ToArray(); }
protected Object[] getSelectedKeys()
{
if (getSelectedItems() == null)
{
return new Object[0];
}
Object[] keys = new Object[getSelectedItems().size()];
for (int i = 0; i < getSelectedItems().size(); i++)
{
keys[i] = ((VM) getSelectedItems().get(i)).getId();
}
return keys;
}
private Object privateGuideContext;
public Object getGuideContext()
{
return privateGuideContext;
}
public void setGuideContext(Object value)
{
privateGuideContext = value;
}
private VM privatecurrentVm;
public VM getcurrentVm()
{
return privatecurrentVm;
}
public void setcurrentVm(VM value)
{
privatecurrentVm = value;
}
private final java.util.HashMap<Guid, java.util.ArrayList<ConsoleModel>> cachedConsoleModels;
private java.util.ArrayList<String> privateCustomPropertiesKeysList;
private java.util.ArrayList<String> getCustomPropertiesKeysList()
{
return privateCustomPropertiesKeysList;
}
private void setCustomPropertiesKeysList(java.util.ArrayList<String> value)
{
privateCustomPropertiesKeysList = value;
}
public VmListModel()
{
setTitle("Virtual Machines");
setDefaultSearchString("Vms:");
setSearchString(getDefaultSearchString());
cachedConsoleModels = new java.util.HashMap<Guid, java.util.ArrayList<ConsoleModel>>();
setNewServerCommand(new UICommand("NewServer", this));
setNewDesktopCommand(new UICommand("NewDesktop", this));
setEditCommand(new UICommand("Edit", this));
setRemoveCommand(new UICommand("Remove", this));
setRunCommand(new UICommand("Run", this, true));
setPauseCommand(new UICommand("Pause", this));
setStopCommand(new UICommand("Stop", this));
setShutdownCommand(new UICommand("Shutdown", this));
setMigrateCommand(new UICommand("Migrate", this));
setCancelMigrateCommand(new UICommand("CancelMigration", this));
setNewTemplateCommand(new UICommand("NewTemplate", this));
setRunOnceCommand(new UICommand("RunOnce", this));
setExportCommand(new UICommand("Export", this));
setMoveCommand(new UICommand("Move", this));
setGuideCommand(new UICommand("Guide", this));
setRetrieveIsoImagesCommand(new UICommand("RetrieveIsoImages", this));
setChangeCdCommand(new UICommand("ChangeCD", this));
setAssignTagsCommand(new UICommand("AssignTags", this));
setIsoImages(new ObservableCollection<ChangeCDModel>());
ChangeCDModel tempVar = new ChangeCDModel();
tempVar.setTitle("Retrieving CDs...");
getIsoImages().add(tempVar);
UpdateActionAvailability();
getSearchNextPageCommand().setIsAvailable(true);
getSearchPreviousPageCommand().setIsAvailable(true);
AsyncDataProvider.GetCustomPropertiesList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel model = (VmListModel) target;
if (returnValue != null)
{
String[] array = ((String) returnValue).split("[;]", -1);
model.setCustomPropertiesKeysList(new java.util.ArrayList<String>());
for (String s : array)
{
model.getCustomPropertiesKeysList().add(s);
}
}
}
}));
// Call 'IsCommandCompatible' for precaching
AsyncDataProvider.IsCommandCompatible(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
}
}), null, null, null);
}
private void AssignTags()
{
if (getWindow() != null)
{
return;
}
TagListModel model = new TagListModel();
setWindow(model);
model.setTitle("Assign Tags");
model.setHashName("assign_tags_vms");
GetAttachedTagsToSelectedVMs(model);
UICommand tempVar = new UICommand("OnAssignTags", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
public java.util.Map<Guid, Boolean> attachedTagsToEntities;
public java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags> allAttachedTags;
public int selectedItemsCounter;
private void GetAttachedTagsToSelectedVMs(TagListModel model)
{
java.util.ArrayList<Guid> vmIds = new java.util.ArrayList<Guid>();
for (Object item : getSelectedItems())
{
VM vm = (VM) item;
vmIds.add(vm.getId());
}
attachedTagsToEntities = new java.util.HashMap<Guid, Boolean>();
allAttachedTags = new java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags>();
selectedItemsCounter = 0;
for (Guid id : vmIds)
{
AsyncDataProvider.GetAttachedTagsToVm(new AsyncQuery(new Object[] { this, model },
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
VmListModel vmListModel = (VmListModel) array[0];
TagListModel tagListModel = (TagListModel) array[1];
vmListModel.allAttachedTags.addAll((java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags>) returnValue);
vmListModel.selectedItemsCounter++;
if (vmListModel.selectedItemsCounter == vmListModel.getSelectedItems().size())
{
PostGetAttachedTags(vmListModel, tagListModel);
}
}
}),
id);
}
}
private void PostGetAttachedTags(VmListModel vmListModel, TagListModel tagListModel)
{
if (vmListModel.getLastExecutedCommand() == getAssignTagsCommand())
{
// C# TO JAVA CONVERTER TODO TASK: There is no Java equivalent to LINQ queries:
java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags> attachedTags =
Linq.Distinct(vmListModel.allAttachedTags, new TagsEqualityComparer());
for (org.ovirt.engine.core.common.businessentities.tags tag : attachedTags)
{
int count = 0;
for (org.ovirt.engine.core.common.businessentities.tags tag2 : vmListModel.allAttachedTags)
{
if (tag2.gettag_id().equals(tag.gettag_id()))
{
count++;
}
}
vmListModel.attachedTagsToEntities.put(tag.gettag_id(), count == vmListModel.getSelectedItems().size());
}
tagListModel.setAttachedTagsToEntities(vmListModel.attachedTagsToEntities);
}
else if (StringHelper.stringsEqual(vmListModel.getLastExecutedCommand().getName(), "OnAssignTags"))
{
vmListModel.PostOnAssignTags(tagListModel.getAttachedTagsToEntities());
}
}
private void OnAssignTags()
{
TagListModel model = (TagListModel) getWindow();
GetAttachedTagsToSelectedVMs(model);
}
public void PostOnAssignTags(java.util.Map<Guid, Boolean> attachedTags)
{
TagListModel model = (TagListModel) getWindow();
java.util.ArrayList<Guid> vmIds = new java.util.ArrayList<Guid>();
for (Object item : getSelectedItems())
{
VM vm = (VM) item;
vmIds.add(vm.getId());
}
// prepare attach/detach lists
java.util.ArrayList<Guid> tagsToAttach = new java.util.ArrayList<Guid>();
java.util.ArrayList<Guid> tagsToDetach = new java.util.ArrayList<Guid>();
if (model.getItems() != null && ((java.util.ArrayList<TagModel>) model.getItems()).size() > 0)
{
java.util.ArrayList<TagModel> tags = (java.util.ArrayList<TagModel>) model.getItems();
TagModel rootTag = tags.get(0);
TagModel.RecursiveEditAttachDetachLists(rootTag, attachedTags, tagsToAttach, tagsToDetach);
}
java.util.ArrayList<VdcActionParametersBase> parameters = new java.util.ArrayList<VdcActionParametersBase>();
for (Guid a : tagsToAttach)
{
parameters.add(new AttachEntityToTagParameters(a, vmIds));
}
Frontend.RunMultipleAction(VdcActionType.AttachVmsToTag, parameters);
parameters = new java.util.ArrayList<VdcActionParametersBase>();
for (Guid a : tagsToDetach)
{
parameters.add(new AttachEntityToTagParameters(a, vmIds));
}
Frontend.RunMultipleAction(VdcActionType.DetachVmFromTag, parameters);
Cancel();
}
private void Guide()
{
VmGuideModel model = new VmGuideModel();
setWindow(model);
model.setTitle("New Virtual Machine - Guide Me");
model.setHashName("new_virtual_machine_-_guide_me");
if (getGuideContext() == null) {
VM vm = (VM) getSelectedItem();
setGuideContext(vm.getId());
}
AsyncDataProvider.GetVmById(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
VmGuideModel model = (VmGuideModel) vmListModel.getWindow();
model.setEntity((VM) returnValue);
UICommand tempVar = new UICommand("Cancel", vmListModel);
tempVar.setTitle("Configure Later");
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
}), (Guid) getGuideContext());
}
@Override
protected void InitDetailModels()
{
super.InitDetailModels();
ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
list.add(new VmGeneralModel());
list.add(new VmInterfaceListModel());
list.add(new VmDiskListModel());
list.add(new VmSnapshotListModel());
list.add(new VmEventListModel());
list.add(new VmAppListModel());
list.add(new PermissionListModel());
setDetailModels(list);
}
@Override
public boolean IsSearchStringMatch(String searchString)
{
return searchString.trim().toLowerCase().startsWith("vm");
}
@Override
protected void SyncSearch()
{
SearchParameters tempVar = new SearchParameters(getSearchString(), SearchType.VM);
tempVar.setMaxCount(getSearchPageSize());
super.SyncSearch(VdcQueryType.Search, tempVar);
}
@Override
protected void AsyncSearch()
{
super.AsyncSearch();
setAsyncResult(Frontend.RegisterSearch(getSearchString(), SearchType.VM, getSearchPageSize()));
setItems(getAsyncResult().getData());
}
private void UpdateConsoleModels()
{
java.util.List tempVar = getSelectedItems();
java.util.List selectedItems = (tempVar != null) ? tempVar : new java.util.ArrayList();
Object tempVar2 = getSelectedItem();
VM vm = (VM) ((tempVar2 instanceof VM) ? tempVar2 : null);
if (vm == null || selectedItems.size() > 1)
{
setDefaultConsoleModel(null);
setAdditionalConsoleModel(null);
setHasAdditionalConsoleModel(false);
}
else
{
if (!cachedConsoleModels.containsKey(vm.getId()))
{
SpiceConsoleModel spiceConsoleModel = new SpiceConsoleModel();
spiceConsoleModel.getErrorEvent().addListener(this);
VncConsoleModel vncConsoleModel = new VncConsoleModel();
RdpConsoleModel rdpConsoleModel = new RdpConsoleModel();
cachedConsoleModels.put(vm.getId(),
new java.util.ArrayList<ConsoleModel>(java.util.Arrays.asList(new ConsoleModel[] {
spiceConsoleModel, vncConsoleModel, rdpConsoleModel })));
}
java.util.ArrayList<ConsoleModel> cachedModels = cachedConsoleModels.get(vm.getId());
for (ConsoleModel a : cachedModels)
{
a.setEntity(null);
a.setEntity(vm);
}
setDefaultConsoleModel(vm.getdisplay_type() == DisplayType.vnc ? cachedModels.get(1) : cachedModels.get(0));
if (DataProvider.IsWindowsOsType(vm.getvm_os()))
{
for (ConsoleModel a : cachedModels)
{
if (a instanceof RdpConsoleModel)
{
setAdditionalConsoleModel(a);
break;
}
}
setHasAdditionalConsoleModel(true);
}
else
{
setAdditionalConsoleModel(null);
setHasAdditionalConsoleModel(false);
}
}
}
public java.util.ArrayList<ConsoleModel> GetConsoleModelsByVmGuid(Guid vmGuid)
{
if (cachedConsoleModels != null && cachedConsoleModels.containsKey(vmGuid))
{
return cachedConsoleModels.get(vmGuid);
}
return null;
}
private void NewDesktop()
{
NewInternal(VmType.Desktop);
}
private void NewServer()
{
NewInternal(VmType.Server);
}
private void NewInternal(VmType vmType)
{
if (getWindow() != null)
{
return;
}
UnitVmModel model = new UnitVmModel(new NewVmModelBehavior());
model.setTitle(StringFormat.format("New %1$s Virtual Machine", vmType == VmType.Server ? "Server" : "Desktop"));
model.setHashName("new_" + (vmType == VmType.Server ? "server" : "desktop"));
model.setIsNew(true);
model.setVmType(vmType);
model.setCustomPropertiesKeysList(getCustomPropertiesKeysList());
setWindow(model);
model.Initialize(getSystemTreeSelectedItem());
// Ensures that the default provisioning is "Clone" for a new server and "Thin" for a new desktop.
boolean selectValue = model.getVmType() == VmType.Server;
model.getProvisioning().setEntity(selectValue);
UICommand tempVar = new UICommand("OnSave", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void Edit()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
UnitVmModel model = new UnitVmModel(new ExistingVmModelBehavior(vm));
model.setVmType(vm.getvm_type());
setWindow(model);
model.setTitle(StringFormat.format("Edit %1$s Virtual Machine", vm.getvm_type() == VmType.Server ? "Server"
: "Desktop"));
model.setHashName("edit_" + (vm.getvm_type() == VmType.Server ? "server" : "desktop"));
model.setCustomPropertiesKeysList(getCustomPropertiesKeysList());
model.Initialize(this.getSystemTreeSelectedItem());
// TODO:
// VDSGroup cluster = null;
// if (model.Cluster.Items == null)
// {
// model.Commands.Add(
// new UICommand("Cancel", this)
// {
// Title = "Cancel",
// IsCancel = true
// });
// return;
// }
UICommand tempVar = new UICommand("OnSave", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void remove()
{
if (getWindow() != null)
{
return;
}
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle("Remove Virtual Machine(s)");
model.setHashName("remove_virtual_machine");
model.setMessage("Virtual Machine(s)");
// model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name);
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
for (Object selectedItem : getSelectedItems())
{
VM a = (VM) selectedItem;
list.add(a.getvm_name());
}
model.setItems(list);
UICommand tempVar = new UICommand("OnRemove", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void Move()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
MoveDiskModel model = new MoveDiskModel();
setWindow(model);
model.setTitle("Move Virtual Machine");
model.setHashName("move_virtual_machine");
model.setIsSourceStorageDomainNameAvailable(true);
model.setEntity(this);
model.StartProgress(null);
AsyncDataProvider.GetVmDiskList(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
MoveDiskModel moveDiskModel = (MoveDiskModel) vmListModel.getWindow();
LinkedList<DiskImage> disks = (LinkedList<DiskImage>) returnValue;
ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>();
diskImages.addAll(disks);
moveDiskModel.init(diskImages);
}
}), vm.getId(), true);
}
private void Export()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
ExportVmModel model = new ExportVmModel();
setWindow(model);
model.setTitle("Export Virtual Machine");
model.setHashName("export_virtual_machine");
AsyncDataProvider.GetStorageDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
java.util.ArrayList<storage_domains> storageDomains =
(java.util.ArrayList<storage_domains>) returnValue;
java.util.ArrayList<storage_domains> filteredStorageDomains =
new java.util.ArrayList<storage_domains>();
for (storage_domains a : storageDomains)
{
if (a.getstorage_domain_type() == StorageDomainType.ImportExport)
{
filteredStorageDomains.add(a);
}
}
vmListModel.PostExportGetStorageDomainList(filteredStorageDomains);
}
}), vm.getstorage_pool_id());
}
private void PostExportGetStorageDomainList(java.util.ArrayList<storage_domains> storageDomains)
{
ExportVmModel model = (ExportVmModel) getWindow();
model.getStorage().setItems(storageDomains);
model.getStorage().setSelectedItem(Linq.FirstOrDefault(storageDomains));
boolean noActiveStorage = true;
for (storage_domains a : storageDomains)
{
if (a.getstatus() == StorageDomainStatus.Active)
{
noActiveStorage = false;
break;
}
}
if (SelectedVmsOnDifferentDataCenters())
{
model.getCollapseSnapshots().setIsChangable(false);
model.getForceOverride().setIsChangable(false);
model.setMessage("Virtual Machines reside on several Data Centers. Make sure the exported Virtual Machines reside on the same Data Center.");
UICommand tempVar = new UICommand("Cancel", this);
tempVar.setTitle("Close");
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
else if (storageDomains.isEmpty())
{
model.getCollapseSnapshots().setIsChangable(false);
model.getForceOverride().setIsChangable(false);
model.setMessage("There is no Export Domain to Backup the Virtual Machine into. Attach an Export Domain to the Virtual Machine(s) Data Center.");
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Close");
tempVar2.setIsDefault(true);
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
else if (noActiveStorage)
{
model.getCollapseSnapshots().setIsChangable(false);
model.getForceOverride().setIsChangable(false);
model.setMessage("The relevant Export Domain in not active. Please activate it.");
UICommand tempVar3 = new UICommand("Cancel", this);
tempVar3.setTitle("Close");
tempVar3.setIsDefault(true);
tempVar3.setIsCancel(true);
model.getCommands().add(tempVar3);
}
else
{
showWarningOnExistingVms(model);
UICommand tempVar4 = new UICommand("OnExport", this);
tempVar4.setTitle("OK");
tempVar4.setIsDefault(true);
model.getCommands().add(tempVar4);
UICommand tempVar5 = new UICommand("Cancel", this);
tempVar5.setTitle("Cancel");
tempVar5.setIsCancel(true);
model.getCommands().add(tempVar5);
}
}
private void showWarningOnExistingVms(ExportVmModel model)
{
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
AsyncDataProvider.GetDataCentersByStorageDomain(new AsyncQuery(new Object[] { this, model },
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
VmListModel vmListModel = (VmListModel) array[0];
ExportVmModel exportVmModel = (ExportVmModel) array[1];
java.util.ArrayList<storage_pool> storagePools =
(java.util.ArrayList<storage_pool>) returnValue;
vmListModel.PostShowWarningOnExistingVms(exportVmModel, storagePools);
}
}), storageDomainId);
}
private void PostShowWarningOnExistingVms(ExportVmModel exportModel, java.util.List<storage_pool> storagePools)
{
storage_pool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null;
String existingVMs = "";
if (storagePool != null)
{
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object ReturnValue)
{
VmListModel vmListModel = (VmListModel) model;
ExportVmModel exportModel1 = (ExportVmModel) vmListModel.getWindow();
String existingVMs = "";
if (ReturnValue != null)
{
for (Object selectedItem : vmListModel.getSelectedItems())
{
VM vm = (VM) selectedItem;
VM foundVm = null;
VdcQueryReturnValue returnValue = (VdcQueryReturnValue) ReturnValue;
for (VM a : (java.util.ArrayList<VM>) returnValue.getReturnValue())
{
if (a.getId().equals(vm.getId()))
{
foundVm = a;
break;
}
}
if (foundVm != null)
{
existingVMs += "\u2022 " + vm.getvm_name() + "\n";
}
}
}
if (!StringHelper.isNullOrEmpty(existingVMs))
{
exportModel1.setMessage(StringFormat.format("VM(s):\n%1$s already exist on the target Export Domain. If you want to override them, please check the 'Force Override' check-box.",
existingVMs));
}
}
};
Guid storageDomainId = ((storage_domains) exportModel.getStorage().getSelectedItem()).getId();
GetAllFromExportDomainQueryParamenters tempVar =
new GetAllFromExportDomainQueryParamenters(storagePool.getId(), storageDomainId);
tempVar.setGetAll(true);
Frontend.RunQuery(VdcQueryType.GetVmsFromExportDomain, tempVar, _asyncQuery);
}
}
private boolean SelectedVmsOnDifferentDataCenters()
{
java.util.ArrayList<VM> vms = new java.util.ArrayList<VM>();
for (Object selectedItem : getSelectedItems())
{
VM a = (VM) selectedItem;
vms.add(a);
}
java.util.Map<NGuid, java.util.ArrayList<VM>> t = new java.util.HashMap<NGuid, java.util.ArrayList<VM>>();
for (VM a : vms)
{
if (!t.containsKey(a.getstorage_pool_id()))
{
t.put(a.getstorage_pool_id(), new java.util.ArrayList<VM>());
}
java.util.ArrayList<VM> list = t.get(a.getstorage_pool_id());
list.add(a);
}
return t.size() > 1;
}
private void GetTemplatesNotPresentOnExportDomain()
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
AsyncDataProvider.GetDataCentersByStorageDomain(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
java.util.ArrayList<storage_pool> storagePools =
(java.util.ArrayList<storage_pool>) returnValue;
storage_pool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null;
vmListModel.PostGetTemplatesNotPresentOnExportDomain(storagePool);
}
}), storageDomainId);
}
private void PostGetTemplatesNotPresentOnExportDomain(storage_pool storagePool)
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
if (storagePool != null)
{
AsyncDataProvider.GetAllTemplatesFromExportDomain(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
java.util.HashMap<VmTemplate, java.util.ArrayList<DiskImage>> templatesDiskSet =
(java.util.HashMap<VmTemplate, java.util.ArrayList<DiskImage>>) returnValue;
java.util.HashMap<String, java.util.ArrayList<String>> templateDic =
new java.util.HashMap<String, java.util.ArrayList<String>>();
// check if relevant templates are already there
for (Object selectedItem : vmListModel.getSelectedItems())
{
VM vm = (VM) selectedItem;
boolean hasMatch = false;
for (VmTemplate a : templatesDiskSet.keySet())
{
if (vm.getvmt_guid().equals(a.getId()))
{
hasMatch = true;
break;
}
}
if (!vm.getvmt_guid().equals(NGuid.Empty) && !hasMatch)
{
if (!templateDic.containsKey(vm.getvmt_name()))
{
templateDic.put(vm.getvmt_name(), new java.util.ArrayList<String>());
}
templateDic.get(vm.getvmt_name()).add(vm.getvm_name());
}
}
String tempStr;
java.util.ArrayList<String> tempList;
java.util.ArrayList<String> missingTemplates = new java.util.ArrayList<String>();
for (java.util.Map.Entry<String, java.util.ArrayList<String>> keyValuePair : templateDic.entrySet())
{
tempList = keyValuePair.getValue();
tempStr = "Template " + keyValuePair.getKey() + " (for ";
int i;
for (i = 0; i < tempList.size() - 1; i++)
{
tempStr += tempList.get(i) + ", ";
}
tempStr += tempList.get(i) + ")";
missingTemplates.add(tempStr);
}
vmListModel.PostExportGetMissingTemplates(missingTemplates);
}
}),
storagePool.getId(),
storageDomainId);
}
}
private void PostExportGetMissingTemplates(java.util.ArrayList<String> missingTemplatesFromVms)
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
java.util.ArrayList<VdcActionParametersBase> parameters = new java.util.ArrayList<VdcActionParametersBase>();
model.StopProgress();
for (Object a : getSelectedItems())
{
VM vm = (VM) a;
MoveVmParameters parameter = new MoveVmParameters(vm.getId(), storageDomainId);
parameter.setForceOverride((Boolean) model.getForceOverride().getEntity());
parameter.setCopyCollapse((Boolean) model.getCollapseSnapshots().getEntity());
parameter.setTemplateMustExists(true);
parameters.add(parameter);
}
if (!(Boolean) model.getCollapseSnapshots().getEntity())
{
if ((missingTemplatesFromVms == null || missingTemplatesFromVms.size() > 0))
{
ConfirmationModel confirmModel = new ConfirmationModel();
setConfirmWindow(confirmModel);
confirmModel.setTitle("Template(s) not Found on Export Domain");
confirmModel.setHashName("template_not_found_on_export_domain");
confirmModel.setMessage(missingTemplatesFromVms == null ? "Could not read templates from Export Domain"
: "The following templates are missing on the target Export Domain:");
confirmModel.setItems(missingTemplatesFromVms);
UICommand tempVar = new UICommand("OnExportNoTemplates", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
confirmModel.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("CancelConfirmation", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
confirmModel.getCommands().add(tempVar2);
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ExportVm, parameters,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
}
else
{
if (model.getProgress() != null)
{
return;
}
for (VdcActionParametersBase item : parameters)
{
MoveVmParameters parameter = (MoveVmParameters) item;
parameter.setTemplateMustExists(false);
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ExportVm, parameters,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
}
public void OnExport()
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
if (!model.Validate())
{
return;
}
model.StartProgress(null);
GetTemplatesNotPresentOnExportDomain();
}
private void OnExportNoTemplates()
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
if (model.getProgress() != null)
{
return;
}
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
MoveVmParameters parameters = new MoveVmParameters(a.getId(), storageDomainId);
parameters.setForceOverride((Boolean) model.getForceOverride().getEntity());
parameters.setCopyCollapse((Boolean) model.getCollapseSnapshots().getEntity());
parameters.setTemplateMustExists(false);
list.add(parameters);
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ExportVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void RunOnce()
{
VM vm = (VM) getSelectedItem();
RunOnceModel model = new RunOnceModel();
setWindow(model);
model.setTitle("Run Virtual Machine(s)");
model.setHashName("run_virtual_machine");
model.getAttachIso().setEntity(false);
model.getAttachFloppy().setEntity(false);
model.getRunAsStateless().setEntity(vm.getis_stateless());
model.getRunAndPause().setEntity(false);
model.setHwAcceleration(true);
// passing Kernel parameters
model.getKernel_parameters().setEntity(vm.getkernel_params());
model.getKernel_path().setEntity(vm.getkernel_url());
model.getInitrd_path().setEntity(vm.getinitrd_url());
// Custom Properties
model.getCustomProperties().setEntity(vm.getCustomProperties());
model.setCustomPropertiesKeysList(getCustomPropertiesKeysList());
model.setIsLinux_Unassign_UnknownOS(DataProvider.IsLinuxOsType(vm.getvm_os())
|| vm.getvm_os() == VmOsType.Unassigned || vm.getvm_os() == VmOsType.Other);
model.getIsLinuxOptionsAvailable().setEntity(model.getIsLinux_Unassign_UnknownOS());
model.setIsWindowsOS(DataProvider.IsWindowsOsType(vm.getvm_os()));
model.getIsVmFirstRun().setEntity(!vm.getis_initialized());
model.getSysPrepDomainName().setSelectedItem(vm.getvm_domain());
RunOnceUpdateDisplayProtocols(vm);
RunOnceUpdateFloppy(vm, new java.util.ArrayList<String>());
RunOnceUpdateImages(vm);
RunOnceUpdateDomains();
RunOnceUpdateBootSequence(vm);
UICommand tempVar = new UICommand("OnRunOnce", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void RunOnceUpdateDisplayProtocols(VM vm)
{
RunOnceModel model = (RunOnceModel) getWindow();
EntityModel tempVar = new EntityModel();
tempVar.setTitle("VNC");
tempVar.setEntity(DisplayType.vnc);
EntityModel vncProtocol = tempVar;
EntityModel tempVar2 = new EntityModel();
tempVar2.setTitle("Spice");
tempVar2.setEntity(DisplayType.qxl);
EntityModel qxlProtocol = tempVar2;
boolean isVncSelected = vm.getdefault_display_type() == DisplayType.vnc;
model.getDisplayConsole_Vnc_IsSelected().setEntity(isVncSelected);
model.getDisplayConsole_Spice_IsSelected().setEntity(!isVncSelected);
java.util.ArrayList<EntityModel> items = new java.util.ArrayList<EntityModel>();
items.add(vncProtocol);
items.add(qxlProtocol);
model.getDisplayProtocol().setItems(items);
model.getDisplayProtocol().setSelectedItem(isVncSelected ? vncProtocol : qxlProtocol);
}
private void RunOnceUpdateBootSequence(VM vm)
{
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object ReturnValue)
{
VmListModel vmListModel = (VmListModel) model;
RunOnceModel runOnceModel = (RunOnceModel) vmListModel.getWindow();
boolean hasNics =
((java.util.ArrayList<VmNetworkInterface>) ((VdcQueryReturnValue) ReturnValue).getReturnValue()).size() > 0;
if (!hasNics)
{
BootSequenceModel bootSequenceModel = runOnceModel.getBootSequence();
bootSequenceModel.getNetworkOption().setIsChangable(false);
bootSequenceModel.getNetworkOption()
.getChangeProhibitionReasons()
.add("Virtual Machine must have at least one network interface defined to boot from network.");
}
}
};
Frontend.RunQuery(VdcQueryType.GetVmInterfacesByVmId, new GetVmByVmIdParameters(vm.getId()), _asyncQuery);
}
private void RunOnceUpdateDomains()
{
RunOnceModel model = (RunOnceModel) getWindow();
// Update Domain list
AsyncDataProvider.GetDomainList(new AsyncQuery(model,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
RunOnceModel runOnceModel = (RunOnceModel) target;
java.util.List<String> domains = (java.util.List<String>) returnValue;
String oldDomain = (String) runOnceModel.getSysPrepDomainName().getSelectedItem();
if (oldDomain != null && !oldDomain.equals("") && !domains.contains(oldDomain))
{
domains.add(0, oldDomain);
}
runOnceModel.getSysPrepDomainName().setItems(domains);
String selectedDomain = (oldDomain != null) ? oldDomain : Linq.FirstOrDefault(domains);
if (!StringHelper.stringsEqual(selectedDomain, ""))
{
runOnceModel.getSysPrepDomainName().setSelectedItem(selectedDomain);
}
}
}), true);
}
public void RunOnceUpdateFloppy(VM vm, java.util.ArrayList<String> images)
{
RunOnceModel model = (RunOnceModel) getWindow();
if (DataProvider.IsWindowsOsType(vm.getvm_os()))
{
// Add a pseudo floppy disk image used for Windows' sysprep.
if (!vm.getis_initialized())
{
images.add(0, "[sysprep]");
model.getAttachFloppy().setEntity(true);
}
else
{
images.add("[sysprep]");
}
}
model.getFloppyImage().setItems(images);
if (model.getFloppyImage().getIsChangable() && model.getFloppyImage().getSelectedItem() == null)
{
model.getFloppyImage().setSelectedItem(Linq.FirstOrDefault(images));
}
}
private void RunOnceUpdateImages(VM vm)
{
AsyncQuery _asyncQuery0 = new AsyncQuery();
_asyncQuery0.setModel(this);
_asyncQuery0.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model0, Object result0)
{
if (result0 != null)
{
storage_domains isoDomain = (storage_domains) result0;
VmListModel vmListModel = (VmListModel) model0;
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(vmListModel);
_asyncQuery1.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result)
{
VmListModel vmListModel1 = (VmListModel) model1;
RunOnceModel runOnceModel = (RunOnceModel) vmListModel1.getWindow();
java.util.ArrayList<String> images = (java.util.ArrayList<String>) result;
runOnceModel.getIsoImage().setItems(images);
if (runOnceModel.getIsoImage().getIsChangable()
&& runOnceModel.getIsoImage().getSelectedItem() == null)
{
runOnceModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images));
}
}
};
AsyncDataProvider.GetIrsImageList(_asyncQuery1, isoDomain.getId(), false);
AsyncQuery _asyncQuery2 = new AsyncQuery();
_asyncQuery2.setModel(vmListModel);
_asyncQuery2.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model2, Object result)
{
VmListModel vmListModel2 = (VmListModel) model2;
VM selectedVM = (VM) vmListModel2.getSelectedItem();
java.util.ArrayList<String> images = (java.util.ArrayList<String>) result;
vmListModel2.RunOnceUpdateFloppy(selectedVM, images);
}
};
AsyncDataProvider.GetFloppyImageList(_asyncQuery2, isoDomain.getId(), false);
}
}
};
AsyncDataProvider.GetIsoDomainByDataCenterId(_asyncQuery0, vm.getstorage_pool_id());
}
private void OnRunOnce()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
Cancel();
return;
}
RunOnceModel model = (RunOnceModel) getWindow();
if (!model.Validate())
{
return;
}
BootSequenceModel bootSequenceModel = model.getBootSequence();
RunVmOnceParams tempVar = new RunVmOnceParams();
tempVar.setVmId(vm.getId());
tempVar.setBootSequence(bootSequenceModel.getSequence());
tempVar.setDiskPath((Boolean) model.getAttachIso().getEntity() ? (String) model.getIsoImage().getSelectedItem()
: "");
tempVar.setFloppyPath(model.getFloppyImagePath());
tempVar.setKvmEnable(model.getHwAcceleration());
tempVar.setRunAndPause((Boolean) model.getRunAndPause().getEntity());
tempVar.setAcpiEnable(true);
tempVar.setRunAsStateless((Boolean) model.getRunAsStateless().getEntity());
tempVar.setReinitialize(model.getReinitialize());
tempVar.setCustomProperties((String) model.getCustomProperties().getEntity());
RunVmOnceParams param = tempVar;
// kernel params
if (model.getKernel_path().getEntity() != null)
{
param.setkernel_url((String) model.getKernel_path().getEntity());
}
if (model.getKernel_parameters().getEntity() != null)
{
param.setkernel_params((String) model.getKernel_parameters().getEntity());
}
if (model.getInitrd_path().getEntity() != null)
{
param.setinitrd_url((String) model.getInitrd_path().getEntity());
}
// Sysprep params
if (model.getSysPrepDomainName().getSelectedItem() != null)
{
param.setSysPrepDomainName(model.getSysPrepSelectedDomainName().getEntity().equals("") ? (String) model.getSysPrepSelectedDomainName()
.getEntity()
: (String) model.getSysPrepDomainName().getSelectedItem());
}
if (model.getSysPrepUserName().getEntity() != null)
{
param.setSysPrepUserName((String) model.getSysPrepUserName().getEntity());
}
if (model.getSysPrepPassword().getEntity() != null)
{
param.setSysPrepPassword((String) model.getSysPrepPassword().getEntity());
}
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
param.setUseVnc((DisplayType) displayProtocolSelectedItem.getEntity() == DisplayType.vnc);
if ((Boolean) model.getDisplayConsole_Vnc_IsSelected().getEntity()
|| (Boolean) model.getDisplayConsole_Spice_IsSelected().getEntity())
{
param.setUseVnc((Boolean) model.getDisplayConsole_Vnc_IsSelected().getEntity());
}
Frontend.RunAction(VdcActionType.RunVmOnce, param,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
}
}, this);
Cancel();
}
private void NewTemplate()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
UnitVmModel model = new UnitVmModel(new NewTemplateVmModelBehavior(vm));
setWindow(model);
model.setTitle("New Template");
model.setHashName("new_template");
model.setIsNew(true);
model.setVmType(vm.getvm_type());
model.Initialize(getSystemTreeSelectedItem());
UICommand tempVar = new UICommand("OnNewTemplate", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void DisableNewTemplateModel(VmModel model, String errMessage)
{
model.setMessage(errMessage);
model.getName().setIsChangable(false);
model.getDescription().setIsChangable(false);
model.getCluster().setIsChangable(false);
model.getStorageDomain().setIsChangable(false);
model.getIsTemplatePublic().setIsChangable(false);
UICommand tempVar = new UICommand("Cancel", this);
tempVar.setTitle("Close");
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
private void OnNewTemplate()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM vm = (VM) getSelectedItem();
if (vm == null)
{
Cancel();
return;
}
if (model.getProgress() != null)
{
return;
}
if (!model.Validate())
{
model.setIsValid(false);
}
else
{
String name = (String) model.getName().getEntity();
// Check name unicitate.
AsyncDataProvider.IsTemplateNameUnique(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
boolean isNameUnique = (Boolean) returnValue;
if (!isNameUnique)
{
UnitVmModel VmModel = (UnitVmModel) vmListModel.getWindow();
VmModel.getInvalidityReasons().clear();
VmModel.getName().getInvalidityReasons().add("Name must be unique.");
VmModel.getName().setIsValid(false);
VmModel.setIsValid(false);
}
else
{
vmListModel.PostNameUniqueCheck();
}
}
}), name);
}
}
public void PostNameUniqueCheck()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM vm = (VM) getSelectedItem();
VM tempVar = new VM();
tempVar.setId(vm.getId());
tempVar.setvm_type(model.getVmType());
if (model.getQuota().getSelectedItem() != null) {
tempVar.setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId());
}
tempVar.setvm_os((VmOsType) model.getOSType().getSelectedItem());
tempVar.setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem());
tempVar.setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem() : "");
tempVar.setvm_mem_size_mb((Integer) model.getMemSize().getEntity());
tempVar.setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity());
tempVar.setvds_group_id(((VDSGroup) model.getCluster().getSelectedItem()).getId());
tempVar.settime_zone(model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null ? ((java.util.Map.Entry<String, String>) model.getTimeZone()
.getSelectedItem()).getKey()
: "");
tempVar.setnum_of_sockets((Integer) model.getNumOfSockets().getEntity());
tempVar.setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity()
/ (Integer) model.getNumOfSockets().getEntity());
tempVar.setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem());
tempVar.setis_auto_suspend(false);
tempVar.setis_stateless((Boolean) model.getIsStateless().getEntity());
tempVar.setdefault_boot_sequence(model.getBootSequence());
tempVar.setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity());
tempVar.setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem() : "");
tempVar.setinitrd_url(vm.getinitrd_url());
tempVar.setkernel_url(vm.getkernel_url());
tempVar.setkernel_params(vm.getkernel_params());
VM newvm = tempVar;
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
newvm.setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity());
EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem();
newvm.setpriority((Integer) prioritySelectedItem.getEntity());
AddVmTemplateParameters addVmTemplateParameters =
new AddVmTemplateParameters(newvm,
(String) model.getName().getEntity(),
(String) model.getDescription().getEntity());
addVmTemplateParameters.setPublicUse((Boolean) model.getIsTemplatePublic().getEntity());
addVmTemplateParameters.setDiskInfoDestinationMap(
model.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) model.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
model.StartProgress(null);
Frontend.RunAction(VdcActionType.AddVmTemplate, addVmTemplateParameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
private void Migrate()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
MigrateModel model = new MigrateModel();
setWindow(model);
model.setTitle("Migrate Virtual Machine(s)");
model.setHashName("migrate_virtual_machine");
model.setVmsOnSameCluster(true);
model.setIsAutoSelect(true);
model.setVmList(Linq.<VM> Cast(getSelectedItems()));
AsyncDataProvider.GetUpHostListByCluster(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
vmListModel.PostMigrateGetUpHosts((java.util.ArrayList<VDS>) returnValue);
}
}), vm.getvds_group_name());
}
private void CancelMigration()
{
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
list.add(new VmOperationParameterBase(a.getId()));
}
Frontend.RunMultipleAction(VdcActionType.CancelMigrateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(
FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void PostMigrateGetUpHosts(java.util.ArrayList<VDS> hosts)
{
MigrateModel model = (MigrateModel) getWindow();
NGuid run_on_vds = null;
boolean allRunOnSameVds = true;
for (Object item : getSelectedItems())
{
VM a = (VM) item;
if (!a.getvds_group_id().equals(((VM) getSelectedItems().get(0)).getvds_group_id()))
{
model.setVmsOnSameCluster(false);
}
if (run_on_vds == null)
{
run_on_vds = a.getrun_on_vds().getValue();
}
else if (allRunOnSameVds && !run_on_vds.equals(a.getrun_on_vds().getValue()))
{
allRunOnSameVds = false;
}
}
model.setIsHostSelAvailable(model.getVmsOnSameCluster() && hosts.size() > 0);
if (model.getVmsOnSameCluster() && allRunOnSameVds)
{
VDS runOnSameVDS = null;
for (VDS host : hosts)
{
if (host.getId().equals(run_on_vds))
{
runOnSameVDS = host;
}
}
hosts.remove(runOnSameVDS);
}
if (hosts.isEmpty())
{
model.setIsHostSelAvailable(false);
if (allRunOnSameVds)
{
model.setNoSelAvailable(true);
UICommand tempVar = new UICommand("Cancel", this);
tempVar.setTitle("Close");
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
}
else
{
model.getHosts().setItems(hosts);
model.getHosts().setSelectedItem(Linq.FirstOrDefault(hosts));
UICommand tempVar2 = new UICommand("OnMigrate", this);
tempVar2.setTitle("OK");
tempVar2.setIsDefault(true);
model.getCommands().add(tempVar2);
UICommand tempVar3 = new UICommand("Cancel", this);
tempVar3.setTitle("Cancel");
tempVar3.setIsCancel(true);
model.getCommands().add(tempVar3);
}
}
private void OnMigrate()
{
MigrateModel model = (MigrateModel) getWindow();
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
if (model.getIsAutoSelect())
{
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new MigrateVmParameters(true, a.getId()));
}
Frontend.RunMultipleAction(VdcActionType.MigrateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
MigrateModel localModel = (MigrateModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
else
{
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
if (a.getrun_on_vds().getValue().equals(((VDS) model.getHosts().getSelectedItem()).getId()))
{
continue;
}
list.add(new MigrateVmToServerParameters(true, a.getId(), ((VDS) model.getHosts()
.getSelectedItem()).getId()));
}
Frontend.RunMultipleAction(VdcActionType.MigrateVmToServer, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
MigrateModel localModel = (MigrateModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
}
private void Shutdown()
{
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle("Shut down Virtual Machine(s)");
model.setHashName("shut_down_virtual_machine");
model.setMessage("Are you sure you want to Shut down the following Virtual Machines?");
// model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name);
java.util.ArrayList<String> items = new java.util.ArrayList<String>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
items.add(a.getvm_name());
}
model.setItems(items);
UICommand tempVar = new UICommand("OnShutdown", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnShutdown()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new ShutdownVmParameters(a.getId(), true));
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ShutdownVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void stop()
{
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle("Stop Virtual Machine(s)");
model.setHashName("stop_virtual_machine");
model.setMessage("Are you sure you want to Stop the following Virtual Machines?");
// model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name);
java.util.ArrayList<String> items = new java.util.ArrayList<String>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
items.add(a.getvm_name());
}
model.setItems(items);
UICommand tempVar = new UICommand("OnStop", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnStop()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new StopVmParameters(a.getId(), StopVmTypeEnum.NORMAL));
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.StopVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void Pause()
{
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new HibernateVmParameters(a.getId()));
}
Frontend.RunMultipleAction(VdcActionType.HibernateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void Run()
{
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
// use sysprep iff the vm is not initialized and vm has Win OS
boolean reinitialize = !a.getis_initialized() && DataProvider.IsWindowsOsType(a.getvm_os());
RunVmParams tempVar = new RunVmParams(a.getId());
tempVar.setReinitialize(reinitialize);
list.add(tempVar);
}
Frontend.RunMultipleAction(VdcActionType.RunVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void OnRemove()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new RemoveVmParameters(a.getId(), false));
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.RemoveVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void ChangeCD()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
AttachCdModel model = new AttachCdModel();
setWindow(model);
model.setTitle("Change CD");
model.setHashName("change_cd");
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(this);
_asyncQuery1.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
VmListModel vmListModel1 = (VmListModel) model1;
AttachCdModel attachCdModel = (AttachCdModel) vmListModel1.getWindow();
java.util.ArrayList<String> images1 =
new java.util.ArrayList<String>(java.util.Arrays.asList(new String[] { "No CDs" }));
attachCdModel.getIsoImage().setItems(images1);
attachCdModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images1));
if (result1 != null)
{
storage_domains isoDomain = (storage_domains) result1;
AsyncQuery _asyncQuery2 = new AsyncQuery();
_asyncQuery2.setModel(vmListModel1);
_asyncQuery2.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model2, Object result2)
{
VmListModel vmListModel2 = (VmListModel) model2;
AttachCdModel _attachCdModel = (AttachCdModel) vmListModel2.getWindow();
java.util.ArrayList<String> images2 = (java.util.ArrayList<String>) result2;
if (images2.size() > 0)
{
images2.add(0, ConsoleModel.EjectLabel);
_attachCdModel.getIsoImage().setItems(images2);
}
if (_attachCdModel.getIsoImage().getIsChangable())
{
_attachCdModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images2));
}
}
};
AsyncDataProvider.GetIrsImageList(_asyncQuery2, isoDomain.getId(), false);
}
}
};
AsyncDataProvider.GetIsoDomainByDataCenterId(_asyncQuery1, vm.getstorage_pool_id());
UICommand tempVar = new UICommand("OnChangeCD", this);
tempVar.setTitle("OK");
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this);
tempVar2.setTitle("Cancel");
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnChangeCD()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
Cancel();
return;
}
AttachCdModel model = (AttachCdModel) getWindow();
if (model.getProgress() != null)
{
return;
}
String isoName =
(StringHelper.stringsEqual(model.getIsoImage().getSelectedItem().toString(), ConsoleModel.EjectLabel)) ? ""
: model.getIsoImage().getSelectedItem().toString();
model.StartProgress(null);
Frontend.RunAction(VdcActionType.ChangeDisk, new ChangeDiskCommandParameters(vm.getId(), isoName),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
AttachCdModel attachCdModel = (AttachCdModel) result.getState();
attachCdModel.StopProgress();
Cancel();
}
}, model);
}
private void OnSave()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM selectedItem = (VM) getSelectedItem();
if (model.getIsNew() == false && selectedItem == null)
{
Cancel();
return;
}
setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem));
if (!model.Validate())
{
return;
}
String name = (String) model.getName().getEntity();
// Check name unicitate.
if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0)
{
model.getName().setIsValid(false);
model.getName().getInvalidityReasons().add("Name must be unique.");
model.setIsGeneralTabValid(false);
return;
}
// Save changes.
VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem();
getcurrentVm().setvm_type(model.getVmType());
getcurrentVm().setvmt_guid(template.getId());
getcurrentVm().setvm_name(name);
if (model.getQuota().getSelectedItem() != null) {
getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId());
}
getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem());
getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem());
getcurrentVm().setvm_description((String) model.getDescription().getEntity());
getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem()
: "");
getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity());
getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity());
Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId();
getcurrentVm().setvds_group_id(newClusterID);
getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((java.util.Map.Entry<String, String>) model.getTimeZone()
.getSelectedItem()).getKey()
: "");
getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity()
/ (Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem());
getcurrentVm().setis_auto_suspend(false);
getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity());
getcurrentVm().setdefault_boot_sequence(model.getBootSequence());
getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem()
: "");
getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity());
getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity());
getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity());
getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity());
getcurrentVm().setCustomProperties((String) model.getCustomProperties().getEntity());
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity());
EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem();
getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity());
VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem();
if ((Boolean) model.getIsAutoAssign().getEntity())
{
getcurrentVm().setdedicated_vm_for_vds(null);
}
else
{
getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId());
}
getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE);
if ((Boolean) model.getRunVMOnSpecificHost().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST);
}
else if ((Boolean) model.getDontMigrateVM().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE);
}
if (model.getIsNew())
{
if (getcurrentVm().getvmt_guid().equals(NGuid.Empty))
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(),
new java.util.ArrayList<DiskImageBase>(),
NGuid.Empty),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
vmListModel.setGuideContext(returnValueBase.getActionReturnValue());
vmListModel.UpdateActionAvailability();
vmListModel.getGuideCommand().Execute();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
if ((Boolean) model.getProvisioning().getEntity())
{
model.StartProgress(null);
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
VmListModel vmListModel = (VmListModel) model1;
java.util.ArrayList<DiskImage> templateDisks = (java.util.ArrayList<DiskImage>) result1;
UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow();
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap();
ArrayList<storage_domains> activeStorageDomains =
unitVmModel.getDisksAllocationModel().getActiveStorageDomains();
for (DiskImage templateDisk : templateDisks)
{
DiskModel disk = null;
for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks())
{
if (StringHelper.stringsEqual(a.getName(), templateDisk.getinternal_drive_mapping()))
{
disk = a;
break;
}
}
storage_domains storageDomain =
Linq.getStorageById(
imageToDestinationDomainMap.get(templateDisk.getId())
.getstorage_ids()
.get(0), activeStorageDomains);
if (disk != null) {
templateDisk.setvolume_type((VolumeType) disk.getVolumeType().getSelectedItem());
templateDisk.setvolume_format(DataProvider.GetDiskVolumeFormat(
(VolumeType) disk.getVolumeType().getSelectedItem(),
storageDomain.getstorage_type()));
}
}
HashMap<String, DiskImageBase> dict = new HashMap<String, DiskImageBase>();
for (DiskImage a : templateDisks)
{
dict.put(a.getinternal_drive_mapping(), a);
}
storage_domains storageDomain =
(storage_domains) unitVmModel.getDisksAllocationModel()
.getStorageDomain().getSelectedItem();
AddVmFromTemplateParameters parameters =
new AddVmFromTemplateParameters(vmListModel.getcurrentVm(),
dict, storageDomain.getId());
parameters.setDiskInfoDestinationMap(
unitVmModel.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) unitVmModel.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel1 = (VmListModel) result.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
};
AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId());
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
model.getDisksAllocationModel().getImageToDestinationDomainMap();
storage_domains storageDomain =
((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem());
VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm());
- params.setDiskInfoDestinationMap(imageToDestinationDomainMap);
+ params.setDiskInfoDestinationMap(
+ model.getDisksAllocationModel()
+ .getImageToDestinationDomainMap((Boolean) model.getDisksAllocationModel()
+ .getIsSingleStorageDomain()
+ .getEntity()));
Frontend.RunAction(VdcActionType.AddVm, params,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM:
{
if (model.getProgress() != null)
{
return;
}
// runEditVM: should be true if Cluster hasn't changed or if
// Cluster has changed and Editing it in the Backend has succeeded:
Guid oldClusterID = selectedItem.getvds_group_id();
if (oldClusterID.equals(newClusterID) == false)
{
ChangeVMClusterParameters parameters =
new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId());
model.StartProgress(null);
Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
Frontend.RunAction(VdcActionType.UpdateVm,
new VmManagementParametersBase(vmListModel.getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result1) {
VmListModel vmListModel1 = (VmListModel) result1.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase retVal = result1.getReturnValue();
boolean isSucceeded = retVal.getSucceeded();
if (retVal != null && isSucceeded)
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
else
{
vmListModel.getWindow().StopProgress();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
private void RetrieveIsoImages()
{
Object tempVar = getSelectedItem();
VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null);
if (vm == null)
{
return;
}
Guid storagePoolId = vm.getstorage_pool_id();
getIsoImages().clear();
ChangeCDModel tempVar2 = new ChangeCDModel();
tempVar2.setTitle(ConsoleModel.EjectLabel);
ChangeCDModel ejectModel = tempVar2;
ejectModel.getExecutedEvent().addListener(this);
getIsoImages().add(ejectModel);
java.util.ArrayList<String> list = DataProvider.GetIrsImageList(storagePoolId, false);
if (list.size() > 0)
{
for (String iso : list)
{
ChangeCDModel tempVar3 = new ChangeCDModel();
tempVar3.setTitle(iso);
ChangeCDModel model = tempVar3;
// model.Executed += changeCD;
model.getExecutedEvent().addListener(this);
getIsoImages().add(model);
}
}
else
{
ChangeCDModel tempVar4 = new ChangeCDModel();
tempVar4.setTitle("No CDs");
getIsoImages().add(tempVar4);
}
}
private void changeCD(Object sender, EventArgs e)
{
ChangeCDModel model = (ChangeCDModel) sender;
// TODO: Patch!
String isoName = model.getTitle();
if (StringHelper.stringsEqual(isoName, "No CDs"))
{
return;
}
Object tempVar = getSelectedItem();
VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null);
if (vm == null)
{
return;
}
Frontend.RunMultipleAction(VdcActionType.ChangeDisk,
new java.util.ArrayList<VdcActionParametersBase>(java.util.Arrays.asList(new VdcActionParametersBase[] { new ChangeDiskCommandParameters(vm.getId(),
StringHelper.stringsEqual(isoName, ConsoleModel.EjectLabel) ? "" : isoName) })),
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
},
null);
}
public void Cancel()
{
Frontend.Unsubscribe();
CancelConfirmation();
setGuideContext(null);
setWindow(null);
UpdateActionAvailability();
}
private void CancelConfirmation()
{
setConfirmWindow(null);
}
public void CancelError()
{
setErrorWindow(null);
}
@Override
protected void OnSelectedItemChanged()
{
super.OnSelectedItemChanged();
UpdateActionAvailability();
UpdateConsoleModels();
}
@Override
protected void SelectedItemsChanged()
{
super.SelectedItemsChanged();
UpdateActionAvailability();
UpdateConsoleModels();
}
@Override
protected void SelectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
super.SelectedItemPropertyChanged(sender, e);
// C# TO JAVA CONVERTER NOTE: The following 'switch' operated on a string member and was converted to Java
// 'if-else' logic:
// switch (e.PropertyName)
// ORIGINAL LINE: case "status":
if (e.PropertyName.equals("status"))
{
UpdateActionAvailability();
}
// ORIGINAL LINE: case "display_type":
else if (e.PropertyName.equals("display_type"))
{
UpdateConsoleModels();
}
}
private void UpdateActionAvailability()
{
java.util.List items =
getSelectedItems() != null && getSelectedItem() != null ? getSelectedItems()
: new java.util.ArrayList();
getEditCommand().setIsExecutionAllowed(items.size() == 1);
getRemoveCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RemoveVm));
getRunCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RunVm));
getPauseCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.HibernateVm));
getShutdownCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ShutdownVm));
getStopCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.StopVm));
getMigrateCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.MigrateVm));
getCancelMigrateCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.CancelMigrateVm));
getNewTemplateCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.AddVmTemplate));
getRunOnceCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RunVmOnce));
getExportCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ExportVm));
getMoveCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.MoveVm));
getRetrieveIsoImagesCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ChangeDisk));
getChangeCdCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ChangeDisk));
getAssignTagsCommand().setIsExecutionAllowed(items.size() > 0);
getGuideCommand().setIsExecutionAllowed(getGuideContext() != null
|| (getSelectedItem() != null && getSelectedItems() != null && getSelectedItems().size() == 1));
}
@Override
public void eventRaised(Event ev, Object sender, EventArgs args)
{
super.eventRaised(ev, sender, args);
if (ev.equals(ChangeCDModel.ExecutedEventDefinition))
{
changeCD(sender, args);
}
else if (ev.equals(ConsoleModel.ErrorEventDefinition) && sender instanceof SpiceConsoleModel)
{
SpiceConsoleModel_Error(sender, (ErrorCodeEventArgs) args);
}
}
private void SpiceConsoleModel_Error(Object sender, ErrorCodeEventArgs e)
{
ResourceManager rm =
new ResourceManager("UICommon.Resources.RdpErrors.RdpErrors", Assembly.GetExecutingAssembly());
ConfirmationModel model = new ConfirmationModel();
if (getErrorWindow() == null)
{
setErrorWindow(model);
}
model.setTitle("Console Disconnected");
model.setHashName("console_disconnected");
model.setMessage(StringFormat.format("Error connecting to Virtual Machine using Spice:\n%1$s",
rm.GetString("E" + e.getErrorCode())));
rm.ReleaseAllResources();
UICommand tempVar = new UICommand("CancelError", this);
tempVar.setTitle("Close");
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
@Override
public void ExecuteCommand(UICommand command)
{
super.ExecuteCommand(command);
if (command == getNewServerCommand())
{
NewServer();
}
else if (command == getNewDesktopCommand())
{
NewDesktop();
}
else if (command == getEditCommand())
{
Edit();
}
else if (command == getRemoveCommand())
{
remove();
}
else if (command == getRunCommand())
{
Run();
}
else if (command == getPauseCommand())
{
Pause();
}
else if (command == getStopCommand())
{
stop();
}
else if (command == getShutdownCommand())
{
Shutdown();
}
else if (command == getMigrateCommand())
{
Migrate();
}
else if (command == getNewTemplateCommand())
{
NewTemplate();
}
else if (command == getRunOnceCommand())
{
RunOnce();
}
else if (command == getExportCommand())
{
Export();
}
else if (command == getMoveCommand())
{
Move();
}
else if (command == getGuideCommand())
{
Guide();
}
else if (command == getRetrieveIsoImagesCommand())
{
RetrieveIsoImages();
}
else if (command == getChangeCdCommand())
{
ChangeCD();
}
else if (command == getAssignTagsCommand())
{
AssignTags();
}
else if (StringHelper.stringsEqual(command.getName(), "OnAssignTags"))
{
OnAssignTags();
}
else if (StringHelper.stringsEqual(command.getName(), "Cancel"))
{
Cancel();
}
else if (StringHelper.stringsEqual(command.getName(), "OnSave"))
{
OnSave();
}
else if (StringHelper.stringsEqual(command.getName(), "OnRemove"))
{
OnRemove();
}
else if (StringHelper.stringsEqual(command.getName(), "OnExport"))
{
OnExport();
}
else if (StringHelper.stringsEqual(command.getName(), "OnExportNoTemplates"))
{
OnExportNoTemplates();
}
else if (StringHelper.stringsEqual(command.getName(), "CancelConfirmation"))
{
CancelConfirmation();
}
else if (StringHelper.stringsEqual(command.getName(), "CancelError"))
{
CancelError();
}
else if (StringHelper.stringsEqual(command.getName(), "OnRunOnce"))
{
OnRunOnce();
}
else if (StringHelper.stringsEqual(command.getName(), "OnNewTemplate"))
{
OnNewTemplate();
}
else if (StringHelper.stringsEqual(command.getName(), "OnMigrate"))
{
OnMigrate();
}
else if (command == getCancelMigrateCommand())
{
CancelMigration();
}
else if (StringHelper.stringsEqual(command.getName(), "OnShutdown"))
{
OnShutdown();
}
else if (StringHelper.stringsEqual(command.getName(), "OnStop"))
{
OnStop();
}
else if (StringHelper.stringsEqual(command.getName(), "OnChangeCD"))
{
OnChangeCD();
}
}
private SystemTreeItemModel systemTreeSelectedItem;
@Override
public SystemTreeItemModel getSystemTreeSelectedItem()
{
return systemTreeSelectedItem;
}
@Override
public void setSystemTreeSelectedItem(SystemTreeItemModel value)
{
systemTreeSelectedItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("SystemTreeSelectedItem"));
}
@Override
protected String getListName() {
return "VmListModel";
}
}
| true | true | private void OnSave()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM selectedItem = (VM) getSelectedItem();
if (model.getIsNew() == false && selectedItem == null)
{
Cancel();
return;
}
setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem));
if (!model.Validate())
{
return;
}
String name = (String) model.getName().getEntity();
// Check name unicitate.
if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0)
{
model.getName().setIsValid(false);
model.getName().getInvalidityReasons().add("Name must be unique.");
model.setIsGeneralTabValid(false);
return;
}
// Save changes.
VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem();
getcurrentVm().setvm_type(model.getVmType());
getcurrentVm().setvmt_guid(template.getId());
getcurrentVm().setvm_name(name);
if (model.getQuota().getSelectedItem() != null) {
getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId());
}
getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem());
getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem());
getcurrentVm().setvm_description((String) model.getDescription().getEntity());
getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem()
: "");
getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity());
getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity());
Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId();
getcurrentVm().setvds_group_id(newClusterID);
getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((java.util.Map.Entry<String, String>) model.getTimeZone()
.getSelectedItem()).getKey()
: "");
getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity()
/ (Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem());
getcurrentVm().setis_auto_suspend(false);
getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity());
getcurrentVm().setdefault_boot_sequence(model.getBootSequence());
getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem()
: "");
getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity());
getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity());
getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity());
getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity());
getcurrentVm().setCustomProperties((String) model.getCustomProperties().getEntity());
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity());
EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem();
getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity());
VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem();
if ((Boolean) model.getIsAutoAssign().getEntity())
{
getcurrentVm().setdedicated_vm_for_vds(null);
}
else
{
getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId());
}
getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE);
if ((Boolean) model.getRunVMOnSpecificHost().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST);
}
else if ((Boolean) model.getDontMigrateVM().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE);
}
if (model.getIsNew())
{
if (getcurrentVm().getvmt_guid().equals(NGuid.Empty))
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(),
new java.util.ArrayList<DiskImageBase>(),
NGuid.Empty),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
vmListModel.setGuideContext(returnValueBase.getActionReturnValue());
vmListModel.UpdateActionAvailability();
vmListModel.getGuideCommand().Execute();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
if ((Boolean) model.getProvisioning().getEntity())
{
model.StartProgress(null);
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
VmListModel vmListModel = (VmListModel) model1;
java.util.ArrayList<DiskImage> templateDisks = (java.util.ArrayList<DiskImage>) result1;
UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow();
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap();
ArrayList<storage_domains> activeStorageDomains =
unitVmModel.getDisksAllocationModel().getActiveStorageDomains();
for (DiskImage templateDisk : templateDisks)
{
DiskModel disk = null;
for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks())
{
if (StringHelper.stringsEqual(a.getName(), templateDisk.getinternal_drive_mapping()))
{
disk = a;
break;
}
}
storage_domains storageDomain =
Linq.getStorageById(
imageToDestinationDomainMap.get(templateDisk.getId())
.getstorage_ids()
.get(0), activeStorageDomains);
if (disk != null) {
templateDisk.setvolume_type((VolumeType) disk.getVolumeType().getSelectedItem());
templateDisk.setvolume_format(DataProvider.GetDiskVolumeFormat(
(VolumeType) disk.getVolumeType().getSelectedItem(),
storageDomain.getstorage_type()));
}
}
HashMap<String, DiskImageBase> dict = new HashMap<String, DiskImageBase>();
for (DiskImage a : templateDisks)
{
dict.put(a.getinternal_drive_mapping(), a);
}
storage_domains storageDomain =
(storage_domains) unitVmModel.getDisksAllocationModel()
.getStorageDomain().getSelectedItem();
AddVmFromTemplateParameters parameters =
new AddVmFromTemplateParameters(vmListModel.getcurrentVm(),
dict, storageDomain.getId());
parameters.setDiskInfoDestinationMap(
unitVmModel.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) unitVmModel.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel1 = (VmListModel) result.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
};
AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId());
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
model.getDisksAllocationModel().getImageToDestinationDomainMap();
storage_domains storageDomain =
((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem());
VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm());
params.setDiskInfoDestinationMap(imageToDestinationDomainMap);
Frontend.RunAction(VdcActionType.AddVm, params,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM:
{
if (model.getProgress() != null)
{
return;
}
// runEditVM: should be true if Cluster hasn't changed or if
// Cluster has changed and Editing it in the Backend has succeeded:
Guid oldClusterID = selectedItem.getvds_group_id();
if (oldClusterID.equals(newClusterID) == false)
{
ChangeVMClusterParameters parameters =
new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId());
model.StartProgress(null);
Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
Frontend.RunAction(VdcActionType.UpdateVm,
new VmManagementParametersBase(vmListModel.getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result1) {
VmListModel vmListModel1 = (VmListModel) result1.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase retVal = result1.getReturnValue();
boolean isSucceeded = retVal.getSucceeded();
if (retVal != null && isSucceeded)
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
else
{
vmListModel.getWindow().StopProgress();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
| private void OnSave()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM selectedItem = (VM) getSelectedItem();
if (model.getIsNew() == false && selectedItem == null)
{
Cancel();
return;
}
setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem));
if (!model.Validate())
{
return;
}
String name = (String) model.getName().getEntity();
// Check name unicitate.
if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0)
{
model.getName().setIsValid(false);
model.getName().getInvalidityReasons().add("Name must be unique.");
model.setIsGeneralTabValid(false);
return;
}
// Save changes.
VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem();
getcurrentVm().setvm_type(model.getVmType());
getcurrentVm().setvmt_guid(template.getId());
getcurrentVm().setvm_name(name);
if (model.getQuota().getSelectedItem() != null) {
getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId());
}
getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem());
getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem());
getcurrentVm().setvm_description((String) model.getDescription().getEntity());
getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem()
: "");
getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity());
getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity());
Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId();
getcurrentVm().setvds_group_id(newClusterID);
getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((java.util.Map.Entry<String, String>) model.getTimeZone()
.getSelectedItem()).getKey()
: "");
getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity()
/ (Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem());
getcurrentVm().setis_auto_suspend(false);
getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity());
getcurrentVm().setdefault_boot_sequence(model.getBootSequence());
getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem()
: "");
getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity());
getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity());
getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity());
getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity());
getcurrentVm().setCustomProperties((String) model.getCustomProperties().getEntity());
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity());
EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem();
getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity());
VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem();
if ((Boolean) model.getIsAutoAssign().getEntity())
{
getcurrentVm().setdedicated_vm_for_vds(null);
}
else
{
getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId());
}
getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE);
if ((Boolean) model.getRunVMOnSpecificHost().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST);
}
else if ((Boolean) model.getDontMigrateVM().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE);
}
if (model.getIsNew())
{
if (getcurrentVm().getvmt_guid().equals(NGuid.Empty))
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(),
new java.util.ArrayList<DiskImageBase>(),
NGuid.Empty),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
vmListModel.setGuideContext(returnValueBase.getActionReturnValue());
vmListModel.UpdateActionAvailability();
vmListModel.getGuideCommand().Execute();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
if ((Boolean) model.getProvisioning().getEntity())
{
model.StartProgress(null);
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
VmListModel vmListModel = (VmListModel) model1;
java.util.ArrayList<DiskImage> templateDisks = (java.util.ArrayList<DiskImage>) result1;
UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow();
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap();
ArrayList<storage_domains> activeStorageDomains =
unitVmModel.getDisksAllocationModel().getActiveStorageDomains();
for (DiskImage templateDisk : templateDisks)
{
DiskModel disk = null;
for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks())
{
if (StringHelper.stringsEqual(a.getName(), templateDisk.getinternal_drive_mapping()))
{
disk = a;
break;
}
}
storage_domains storageDomain =
Linq.getStorageById(
imageToDestinationDomainMap.get(templateDisk.getId())
.getstorage_ids()
.get(0), activeStorageDomains);
if (disk != null) {
templateDisk.setvolume_type((VolumeType) disk.getVolumeType().getSelectedItem());
templateDisk.setvolume_format(DataProvider.GetDiskVolumeFormat(
(VolumeType) disk.getVolumeType().getSelectedItem(),
storageDomain.getstorage_type()));
}
}
HashMap<String, DiskImageBase> dict = new HashMap<String, DiskImageBase>();
for (DiskImage a : templateDisks)
{
dict.put(a.getinternal_drive_mapping(), a);
}
storage_domains storageDomain =
(storage_domains) unitVmModel.getDisksAllocationModel()
.getStorageDomain().getSelectedItem();
AddVmFromTemplateParameters parameters =
new AddVmFromTemplateParameters(vmListModel.getcurrentVm(),
dict, storageDomain.getId());
parameters.setDiskInfoDestinationMap(
unitVmModel.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) unitVmModel.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel1 = (VmListModel) result.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
};
AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId());
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
model.getDisksAllocationModel().getImageToDestinationDomainMap();
storage_domains storageDomain =
((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem());
VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm());
params.setDiskInfoDestinationMap(
model.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) model.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
Frontend.RunAction(VdcActionType.AddVm, params,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM:
{
if (model.getProgress() != null)
{
return;
}
// runEditVM: should be true if Cluster hasn't changed or if
// Cluster has changed and Editing it in the Backend has succeeded:
Guid oldClusterID = selectedItem.getvds_group_id();
if (oldClusterID.equals(newClusterID) == false)
{
ChangeVMClusterParameters parameters =
new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId());
model.StartProgress(null);
Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
Frontend.RunAction(VdcActionType.UpdateVm,
new VmManagementParametersBase(vmListModel.getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result1) {
VmListModel vmListModel1 = (VmListModel) result1.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase retVal = result1.getReturnValue();
boolean isSucceeded = retVal.getSucceeded();
if (retVal != null && isSucceeded)
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
else
{
vmListModel.getWindow().StopProgress();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
|
diff --git a/modules/plugin/wfs/src/main/java/org/geotools/data/wfs/protocol/http/SimpleHttpProtocol.java b/modules/plugin/wfs/src/main/java/org/geotools/data/wfs/protocol/http/SimpleHttpProtocol.java
index 430d9e87e..1c7ef91f8 100644
--- a/modules/plugin/wfs/src/main/java/org/geotools/data/wfs/protocol/http/SimpleHttpProtocol.java
+++ b/modules/plugin/wfs/src/main/java/org/geotools/data/wfs/protocol/http/SimpleHttpProtocol.java
@@ -1,141 +1,143 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.data.wfs.protocol.http;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import sun.misc.BASE64Encoder;
/**
* An {@link HTTPProtocol} implementation that relies on plain {@link HttpURLConnection}
*
* @author Gabriel Roldan (OpenGeo)
* @since 2.6.x
* @version $Id$
* @source $URL$
*/
@SuppressWarnings("nls")
public class SimpleHttpProtocol extends AbstractHttpProtocol {
private static class SimpleHttpResponse implements HTTPResponse {
private HttpURLConnection conn;
private InputStream inputStream;
public SimpleHttpResponse(HttpURLConnection conn) {
this.conn = conn;
}
public String getContentType() {
return conn.getContentType();
}
public String getResponseCharset() {
// String contentType = getContentType();
return null;
}
public String getResponseHeader(String headerName) {
String headerField = conn.getHeaderField(headerName);
return headerField;
}
public InputStream getResponseStream() throws IOException {
if (this.inputStream == null) {
InputStream responseStream = conn.getInputStream();
responseStream = new BufferedInputStream(responseStream);
final String contentEncoding = conn.getContentEncoding();
if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
responseStream = new GZIPInputStream(responseStream);
}
this.inputStream = responseStream;
}
return this.inputStream;
}
public String getTargetUrl() {
return conn.getURL().toExternalForm();
}
}
public HTTPResponse issueGet(URL baseUrl, Map<String, String> kvp) throws IOException {
URL targetUrl = createUrl(baseUrl, kvp);
HttpURLConnection conn = openConnection(targetUrl, HttpMethod.GET);
HTTPResponse response = new SimpleHttpResponse(conn);
return response;
}
public HTTPResponse issuePost(URL targetUrl, POSTCallBack callback) throws IOException {
HttpURLConnection conn = openConnection(targetUrl, HttpMethod.POST);
long contentLength = callback.getContentLength();
conn.setRequestProperty("Content-Length", String.valueOf(contentLength));
String bodyContentType = callback.getContentType();
conn.setRequestProperty("Content-Type", bodyContentType);
OutputStream bodyOut = conn.getOutputStream();
callback.writeBody(bodyOut);
HTTPResponse response = new SimpleHttpResponse(conn);
return response;
}
private HttpURLConnection openConnection(URL targetUrl, HttpMethod method) throws IOException {
HttpURLConnection conn;
try {
conn = (HttpURLConnection) targetUrl.openConnection();
} catch (ClassCastException wrongUrl) {
throw new IOException("HTTP connection required for " + targetUrl);
}
if (0 < getTimeoutMillis()) {
conn.setConnectTimeout(getTimeoutMillis());
conn.setReadTimeout(getTimeoutMillis());
}
+ // remember to set the Accept-Encoding header before setting the authentication credentials
+ // or an IllegalStateException is thrown
if (isTryGzip()) {
conn.setRequestProperty("Accept-Encoding", "gzip");
}
if (method == HttpMethod.POST) {
conn.setRequestMethod("POST");
// conn.setRequestProperty("Content-type", "text/xml, application/xml");
conn.setDoOutput(true);
} else {
conn.setRequestMethod("GET");
}
conn.setDoInput(true);
if (authUsername != null && authPassword != null) {
String userPassword = authUsername + ":" + authPassword;
byte[] encodedUserPassword = userPassword.getBytes();
BASE64Encoder encoder = new BASE64Encoder();
String base64UserAndPasswd = encoder.encode(encodedUserPassword);
conn.setRequestProperty("Authorization", "Basic " + base64UserAndPasswd);
}
return conn;
}
}
| true | true | private HttpURLConnection openConnection(URL targetUrl, HttpMethod method) throws IOException {
HttpURLConnection conn;
try {
conn = (HttpURLConnection) targetUrl.openConnection();
} catch (ClassCastException wrongUrl) {
throw new IOException("HTTP connection required for " + targetUrl);
}
if (0 < getTimeoutMillis()) {
conn.setConnectTimeout(getTimeoutMillis());
conn.setReadTimeout(getTimeoutMillis());
}
if (isTryGzip()) {
conn.setRequestProperty("Accept-Encoding", "gzip");
}
if (method == HttpMethod.POST) {
conn.setRequestMethod("POST");
// conn.setRequestProperty("Content-type", "text/xml, application/xml");
conn.setDoOutput(true);
} else {
conn.setRequestMethod("GET");
}
conn.setDoInput(true);
if (authUsername != null && authPassword != null) {
String userPassword = authUsername + ":" + authPassword;
byte[] encodedUserPassword = userPassword.getBytes();
BASE64Encoder encoder = new BASE64Encoder();
String base64UserAndPasswd = encoder.encode(encodedUserPassword);
conn.setRequestProperty("Authorization", "Basic " + base64UserAndPasswd);
}
return conn;
}
| private HttpURLConnection openConnection(URL targetUrl, HttpMethod method) throws IOException {
HttpURLConnection conn;
try {
conn = (HttpURLConnection) targetUrl.openConnection();
} catch (ClassCastException wrongUrl) {
throw new IOException("HTTP connection required for " + targetUrl);
}
if (0 < getTimeoutMillis()) {
conn.setConnectTimeout(getTimeoutMillis());
conn.setReadTimeout(getTimeoutMillis());
}
// remember to set the Accept-Encoding header before setting the authentication credentials
// or an IllegalStateException is thrown
if (isTryGzip()) {
conn.setRequestProperty("Accept-Encoding", "gzip");
}
if (method == HttpMethod.POST) {
conn.setRequestMethod("POST");
// conn.setRequestProperty("Content-type", "text/xml, application/xml");
conn.setDoOutput(true);
} else {
conn.setRequestMethod("GET");
}
conn.setDoInput(true);
if (authUsername != null && authPassword != null) {
String userPassword = authUsername + ":" + authPassword;
byte[] encodedUserPassword = userPassword.getBytes();
BASE64Encoder encoder = new BASE64Encoder();
String base64UserAndPasswd = encoder.encode(encodedUserPassword);
conn.setRequestProperty("Authorization", "Basic " + base64UserAndPasswd);
}
return conn;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/TransferTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/TransferTest.java
index b8ff6b22a..73b93f1ec 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/TransferTest.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/TransferTest.java
@@ -1,67 +1,67 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.tests.artifact.repository;
import java.io.*;
import java.net.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.p2.tests.AbstractProvisioningTest;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
public class TransferTest extends AbstractProvisioningTest {
public void testGZFileAreNotUnzipped() throws URISyntaxException {
FileOutputStream fos = null;
File f = null;
try {
f = File.createTempFile("TransferTest", "pack.gz");
fos = new FileOutputStream(f);
Platform.getBundle("org.eclipse.ecf.provider.filetransfer").start();
} catch (IOException e) {
fail("1.0", e);
} catch (BundleException e) {
fail("1.5", e);
}
final URI toDownload = new URI("http://download.eclipse.org/eclipse/updates/3.4/plugins/javax.servlet.jsp_2.0.0.v200806031607.jar.pack.gz");
IStatus s = getTransport().download(toDownload, fos, new NullProgressMonitor());
assertOK("2.0", s);
int httpSize = -1;
URL u;
try {
u = toDownload.toURL();
HttpURLConnection c = (HttpURLConnection) u.openConnection();
httpSize = c.getContentLength();
} catch (MalformedURLException e1) {
httpSize = -1;
} catch (IOException e) {
httpSize = -1;
}
try {
fos.close();
if (f != null) {
- String[] ecfPlugins = new String[] {"org.eclipse.ecf", "org.eclipse.ecf.identity", "org.eclipse.ecf.filetransfer", "org.eclipse.ecf.provider.filetransfer", "org.eclipse.ecf.provider.filetransfer.httpclient"};
+ String[] ecfPlugins = new String[] {"org.eclipse.ecf", "org.eclipse.ecf.identity", "org.eclipse.ecf.filetransfer", "org.eclipse.ecf.provider.filetransfer", "org.eclipse.ecf.provider.filetransfer.httpclient4"};
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < ecfPlugins.length; i++) {
Bundle bundle = Platform.getBundle(ecfPlugins[i]);
buffer.append(bundle.getSymbolicName()).append('-').append(bundle.getVersion()).append('\n');
}
assertTrue("4.0 - length found: " + f.length() + " using ECF bundles: " + buffer.toString(), f.length() < 50000);
assertTrue("5.0", httpSize == -1 ? true : (httpSize == f.length()));
}
} catch (IOException e) {
fail("5.0", e);
} finally {
if (f != null)
f.delete();
}
}
}
| true | true | public void testGZFileAreNotUnzipped() throws URISyntaxException {
FileOutputStream fos = null;
File f = null;
try {
f = File.createTempFile("TransferTest", "pack.gz");
fos = new FileOutputStream(f);
Platform.getBundle("org.eclipse.ecf.provider.filetransfer").start();
} catch (IOException e) {
fail("1.0", e);
} catch (BundleException e) {
fail("1.5", e);
}
final URI toDownload = new URI("http://download.eclipse.org/eclipse/updates/3.4/plugins/javax.servlet.jsp_2.0.0.v200806031607.jar.pack.gz");
IStatus s = getTransport().download(toDownload, fos, new NullProgressMonitor());
assertOK("2.0", s);
int httpSize = -1;
URL u;
try {
u = toDownload.toURL();
HttpURLConnection c = (HttpURLConnection) u.openConnection();
httpSize = c.getContentLength();
} catch (MalformedURLException e1) {
httpSize = -1;
} catch (IOException e) {
httpSize = -1;
}
try {
fos.close();
if (f != null) {
String[] ecfPlugins = new String[] {"org.eclipse.ecf", "org.eclipse.ecf.identity", "org.eclipse.ecf.filetransfer", "org.eclipse.ecf.provider.filetransfer", "org.eclipse.ecf.provider.filetransfer.httpclient"};
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < ecfPlugins.length; i++) {
Bundle bundle = Platform.getBundle(ecfPlugins[i]);
buffer.append(bundle.getSymbolicName()).append('-').append(bundle.getVersion()).append('\n');
}
assertTrue("4.0 - length found: " + f.length() + " using ECF bundles: " + buffer.toString(), f.length() < 50000);
assertTrue("5.0", httpSize == -1 ? true : (httpSize == f.length()));
}
} catch (IOException e) {
fail("5.0", e);
} finally {
if (f != null)
f.delete();
}
}
| public void testGZFileAreNotUnzipped() throws URISyntaxException {
FileOutputStream fos = null;
File f = null;
try {
f = File.createTempFile("TransferTest", "pack.gz");
fos = new FileOutputStream(f);
Platform.getBundle("org.eclipse.ecf.provider.filetransfer").start();
} catch (IOException e) {
fail("1.0", e);
} catch (BundleException e) {
fail("1.5", e);
}
final URI toDownload = new URI("http://download.eclipse.org/eclipse/updates/3.4/plugins/javax.servlet.jsp_2.0.0.v200806031607.jar.pack.gz");
IStatus s = getTransport().download(toDownload, fos, new NullProgressMonitor());
assertOK("2.0", s);
int httpSize = -1;
URL u;
try {
u = toDownload.toURL();
HttpURLConnection c = (HttpURLConnection) u.openConnection();
httpSize = c.getContentLength();
} catch (MalformedURLException e1) {
httpSize = -1;
} catch (IOException e) {
httpSize = -1;
}
try {
fos.close();
if (f != null) {
String[] ecfPlugins = new String[] {"org.eclipse.ecf", "org.eclipse.ecf.identity", "org.eclipse.ecf.filetransfer", "org.eclipse.ecf.provider.filetransfer", "org.eclipse.ecf.provider.filetransfer.httpclient4"};
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < ecfPlugins.length; i++) {
Bundle bundle = Platform.getBundle(ecfPlugins[i]);
buffer.append(bundle.getSymbolicName()).append('-').append(bundle.getVersion()).append('\n');
}
assertTrue("4.0 - length found: " + f.length() + " using ECF bundles: " + buffer.toString(), f.length() < 50000);
assertTrue("5.0", httpSize == -1 ? true : (httpSize == f.length()));
}
} catch (IOException e) {
fail("5.0", e);
} finally {
if (f != null)
f.delete();
}
}
|
diff --git a/src/com/turbonips/troglodytes/systems/LightingSystem.java b/src/com/turbonips/troglodytes/systems/LightingSystem.java
index 17a546e..697d831 100644
--- a/src/com/turbonips/troglodytes/systems/LightingSystem.java
+++ b/src/com/turbonips/troglodytes/systems/LightingSystem.java
@@ -1,76 +1,78 @@
package com.turbonips.troglodytes.systems;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.tiled.TiledMap;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.utils.ImmutableBag;
import com.turbonips.troglodytes.ResourceManager;
import com.turbonips.troglodytes.components.Resource;
import com.turbonips.troglodytes.components.Sliding;
public class LightingSystem extends BaseEntitySystem {
private Image light;
private Graphics graphics;
private GameContainer container;
private ComponentMapper<Sliding> slidingMapper;
private ComponentMapper<Resource> resourceMapper;
public LightingSystem(GameContainer container) {
// TODO For map based lights we could also use Transform.class
this.container = container;
graphics = container.getGraphics();
ResourceManager resourceManager = ResourceManager.getInstance();
light = (Image)resourceManager.getResource("light").getObject();
}
@Override
protected void initialize() {
slidingMapper = new ComponentMapper<Sliding>(Sliding.class, world);
resourceMapper = new ComponentMapper<Resource>(Resource.class, world);
}
@Override
protected void processEntities(ImmutableBag<Entity> entities) {
ImmutableBag<Entity> creatures = world.getGroupManager().getEntities("PLAYER");
ImmutableBag<Entity> layers = world.getGroupManager().getEntities("LAYER");
if (!layers.isEmpty()) {
Resource resource = resourceMapper.get(layers.get(0));
if (resource != null) {
TiledMap tiledMap = (TiledMap)resourceMapper.get(layers.get(0)).getObject();
boolean isDark = Boolean.parseBoolean(tiledMap.getMapProperty("Dark", "false"));
if (isDark) {
for (int i=0; i<creatures.size(); i++) {
Entity entity = creatures.get(i);
Sliding sliding = slidingMapper.get(entity);
int lightSize = 15;
float invSize = 1f / lightSize;
graphics.clearAlphaMap();
//graphics.setColor(new Color(0,0,0,100));
//graphics.fillRect(0, 0, container.getWidth(), container.getHeight());
graphics.scale(lightSize, lightSize);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
- light.drawCentered((container.getWidth()/2 - sliding.getX() + 16) * invSize, (container.getHeight()/2 - sliding.getY() + 16) * invSize);
+ if (sliding != null) {
+ light.drawCentered((container.getWidth()/2 - sliding.getX() + 16) * invSize, (container.getHeight()/2 - sliding.getY() + 16) * invSize);
+ }
graphics.scale(invSize, invSize);
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_DST_ALPHA);
graphics.setColor(new Color(0,0,0,255));
graphics.fillRect(0, 0, container.getWidth(), container.getHeight());
graphics.setDrawMode(Graphics.MODE_NORMAL);
}
}
}
}
}
@Override
protected boolean checkProcessing() {
return true;
}
}
| true | true | protected void processEntities(ImmutableBag<Entity> entities) {
ImmutableBag<Entity> creatures = world.getGroupManager().getEntities("PLAYER");
ImmutableBag<Entity> layers = world.getGroupManager().getEntities("LAYER");
if (!layers.isEmpty()) {
Resource resource = resourceMapper.get(layers.get(0));
if (resource != null) {
TiledMap tiledMap = (TiledMap)resourceMapper.get(layers.get(0)).getObject();
boolean isDark = Boolean.parseBoolean(tiledMap.getMapProperty("Dark", "false"));
if (isDark) {
for (int i=0; i<creatures.size(); i++) {
Entity entity = creatures.get(i);
Sliding sliding = slidingMapper.get(entity);
int lightSize = 15;
float invSize = 1f / lightSize;
graphics.clearAlphaMap();
//graphics.setColor(new Color(0,0,0,100));
//graphics.fillRect(0, 0, container.getWidth(), container.getHeight());
graphics.scale(lightSize, lightSize);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
light.drawCentered((container.getWidth()/2 - sliding.getX() + 16) * invSize, (container.getHeight()/2 - sliding.getY() + 16) * invSize);
graphics.scale(invSize, invSize);
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_DST_ALPHA);
graphics.setColor(new Color(0,0,0,255));
graphics.fillRect(0, 0, container.getWidth(), container.getHeight());
graphics.setDrawMode(Graphics.MODE_NORMAL);
}
}
}
}
}
| protected void processEntities(ImmutableBag<Entity> entities) {
ImmutableBag<Entity> creatures = world.getGroupManager().getEntities("PLAYER");
ImmutableBag<Entity> layers = world.getGroupManager().getEntities("LAYER");
if (!layers.isEmpty()) {
Resource resource = resourceMapper.get(layers.get(0));
if (resource != null) {
TiledMap tiledMap = (TiledMap)resourceMapper.get(layers.get(0)).getObject();
boolean isDark = Boolean.parseBoolean(tiledMap.getMapProperty("Dark", "false"));
if (isDark) {
for (int i=0; i<creatures.size(); i++) {
Entity entity = creatures.get(i);
Sliding sliding = slidingMapper.get(entity);
int lightSize = 15;
float invSize = 1f / lightSize;
graphics.clearAlphaMap();
//graphics.setColor(new Color(0,0,0,100));
//graphics.fillRect(0, 0, container.getWidth(), container.getHeight());
graphics.scale(lightSize, lightSize);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
if (sliding != null) {
light.drawCentered((container.getWidth()/2 - sliding.getX() + 16) * invSize, (container.getHeight()/2 - sliding.getY() + 16) * invSize);
}
graphics.scale(invSize, invSize);
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_DST_ALPHA);
graphics.setColor(new Color(0,0,0,255));
graphics.fillRect(0, 0, container.getWidth(), container.getHeight());
graphics.setDrawMode(Graphics.MODE_NORMAL);
}
}
}
}
}
|
diff --git a/storm-core/src/jvm/backtype/storm/metric/SystemBolt.java b/storm-core/src/jvm/backtype/storm/metric/SystemBolt.java
index f19b4bd7..ea44f678 100644
--- a/storm-core/src/jvm/backtype/storm/metric/SystemBolt.java
+++ b/storm-core/src/jvm/backtype/storm/metric/SystemBolt.java
@@ -1,138 +1,138 @@
package backtype.storm.metric;
import backtype.storm.Config;
import backtype.storm.metric.api.AssignableMetric;
import backtype.storm.metric.api.IMetric;
import backtype.storm.task.IBolt;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Tuple;
import clojure.lang.AFn;
import clojure.lang.IFn;
import clojure.lang.RT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.management.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// There is one task inside one executor for each worker of the topology.
// TaskID is always -1, therefore you can only send-unanchored tuples to co-located SystemBolt.
// This bolt was conceived to export worker stats via metrics api.
public class SystemBolt implements IBolt {
private static Logger LOG = LoggerFactory.getLogger(SystemBolt.class);
private static boolean _prepareWasCalled = false;
private static class MemoryUsageMetric implements IMetric {
IFn _getUsage;
public MemoryUsageMetric(IFn getUsage) {
_getUsage = getUsage;
}
@Override
public Object getValueAndReset() {
MemoryUsage memUsage = (MemoryUsage)_getUsage.invoke();
HashMap m = new HashMap();
m.put("maxBytes", memUsage.getMax());
m.put("committedBytes", memUsage.getCommitted());
m.put("initBytes", memUsage.getInit());
m.put("usedBytes", memUsage.getUsed());
m.put("virtualFreeBytes", memUsage.getMax() - memUsage.getUsed());
m.put("unusedBytes", memUsage.getCommitted() - memUsage.getUsed());
return m;
}
}
// canonically the metrics data exported is time bucketed when doing counts.
// convert the absolute values here into time buckets.
private static class GarbageCollectorMetric implements IMetric {
GarbageCollectorMXBean _gcBean;
Long _collectionCount;
Long _collectionTime;
public GarbageCollectorMetric(GarbageCollectorMXBean gcBean) {
_gcBean = gcBean;
}
@Override
public Object getValueAndReset() {
Long collectionCountP = _gcBean.getCollectionCount();
Long collectionTimeP = _gcBean.getCollectionTime();
Map ret = null;
if(_collectionCount!=null && _collectionTime!=null) {
ret = new HashMap();
ret.put("count", collectionCountP - _collectionCount);
ret.put("timeMs", collectionTimeP - _collectionTime);
}
_collectionCount = collectionCountP;
_collectionTime = collectionTimeP;
return ret;
}
}
@Override
public void prepare(final Map stormConf, TopologyContext context, OutputCollector collector) {
- if(_prepareWasCalled && stormConf.get(Config.STORM_CLUSTER_MODE) != "local") {
+ if(_prepareWasCalled && !"local".equals(stormConf.get(Config.STORM_CLUSTER_MODE))) {
throw new RuntimeException("A single worker should have 1 SystemBolt instance.");
}
_prepareWasCalled = true;
int bucketSize = RT.intCast(stormConf.get(Config.TOPOLOGY_BUILTIN_METRICS_BUCKET_SIZE_SECS));
final RuntimeMXBean jvmRT = ManagementFactory.getRuntimeMXBean();
context.registerMetric("uptimeSecs", new IMetric() {
@Override
public Object getValueAndReset() {
return jvmRT.getUptime()/1000.0;
}
}, bucketSize);
context.registerMetric("startTimeSecs", new IMetric() {
@Override
public Object getValueAndReset() {
return jvmRT.getStartTime()/1000.0;
}
}, bucketSize);
context.registerMetric("newWorkerEvent", new IMetric() {
boolean doEvent = true;
@Override
public Object getValueAndReset() {
if (doEvent) {
doEvent = false;
return 1;
} else return 0;
}
}, bucketSize);
final MemoryMXBean jvmMemRT = ManagementFactory.getMemoryMXBean();
context.registerMetric("memory/heap", new MemoryUsageMetric(new AFn() {
public Object invoke() {
return jvmMemRT.getHeapMemoryUsage();
}
}), bucketSize);
context.registerMetric("memory/nonHeap", new MemoryUsageMetric(new AFn() {
public Object invoke() {
return jvmMemRT.getNonHeapMemoryUsage();
}
}), bucketSize);
for(GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) {
context.registerMetric("GC/" + b.getName().replaceAll("\\W", ""), new GarbageCollectorMetric(b), bucketSize);
}
}
@Override
public void execute(Tuple input) {
throw new RuntimeException("Non-system tuples should never be sent to __system bolt.");
}
@Override
public void cleanup() {
}
}
| true | true | public void prepare(final Map stormConf, TopologyContext context, OutputCollector collector) {
if(_prepareWasCalled && stormConf.get(Config.STORM_CLUSTER_MODE) != "local") {
throw new RuntimeException("A single worker should have 1 SystemBolt instance.");
}
_prepareWasCalled = true;
int bucketSize = RT.intCast(stormConf.get(Config.TOPOLOGY_BUILTIN_METRICS_BUCKET_SIZE_SECS));
final RuntimeMXBean jvmRT = ManagementFactory.getRuntimeMXBean();
context.registerMetric("uptimeSecs", new IMetric() {
@Override
public Object getValueAndReset() {
return jvmRT.getUptime()/1000.0;
}
}, bucketSize);
context.registerMetric("startTimeSecs", new IMetric() {
@Override
public Object getValueAndReset() {
return jvmRT.getStartTime()/1000.0;
}
}, bucketSize);
context.registerMetric("newWorkerEvent", new IMetric() {
boolean doEvent = true;
@Override
public Object getValueAndReset() {
if (doEvent) {
doEvent = false;
return 1;
} else return 0;
}
}, bucketSize);
final MemoryMXBean jvmMemRT = ManagementFactory.getMemoryMXBean();
context.registerMetric("memory/heap", new MemoryUsageMetric(new AFn() {
public Object invoke() {
return jvmMemRT.getHeapMemoryUsage();
}
}), bucketSize);
context.registerMetric("memory/nonHeap", new MemoryUsageMetric(new AFn() {
public Object invoke() {
return jvmMemRT.getNonHeapMemoryUsage();
}
}), bucketSize);
for(GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) {
context.registerMetric("GC/" + b.getName().replaceAll("\\W", ""), new GarbageCollectorMetric(b), bucketSize);
}
}
| public void prepare(final Map stormConf, TopologyContext context, OutputCollector collector) {
if(_prepareWasCalled && !"local".equals(stormConf.get(Config.STORM_CLUSTER_MODE))) {
throw new RuntimeException("A single worker should have 1 SystemBolt instance.");
}
_prepareWasCalled = true;
int bucketSize = RT.intCast(stormConf.get(Config.TOPOLOGY_BUILTIN_METRICS_BUCKET_SIZE_SECS));
final RuntimeMXBean jvmRT = ManagementFactory.getRuntimeMXBean();
context.registerMetric("uptimeSecs", new IMetric() {
@Override
public Object getValueAndReset() {
return jvmRT.getUptime()/1000.0;
}
}, bucketSize);
context.registerMetric("startTimeSecs", new IMetric() {
@Override
public Object getValueAndReset() {
return jvmRT.getStartTime()/1000.0;
}
}, bucketSize);
context.registerMetric("newWorkerEvent", new IMetric() {
boolean doEvent = true;
@Override
public Object getValueAndReset() {
if (doEvent) {
doEvent = false;
return 1;
} else return 0;
}
}, bucketSize);
final MemoryMXBean jvmMemRT = ManagementFactory.getMemoryMXBean();
context.registerMetric("memory/heap", new MemoryUsageMetric(new AFn() {
public Object invoke() {
return jvmMemRT.getHeapMemoryUsage();
}
}), bucketSize);
context.registerMetric("memory/nonHeap", new MemoryUsageMetric(new AFn() {
public Object invoke() {
return jvmMemRT.getNonHeapMemoryUsage();
}
}), bucketSize);
for(GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) {
context.registerMetric("GC/" + b.getName().replaceAll("\\W", ""), new GarbageCollectorMetric(b), bucketSize);
}
}
|
diff --git a/src/etc/jtlv/GROne/GROneGame.java b/src/etc/jtlv/GROne/GROneGame.java
index 7b1df28..3d33841 100644
--- a/src/etc/jtlv/GROne/GROneGame.java
+++ b/src/etc/jtlv/GROne/GROneGame.java
@@ -1,1277 +1,1277 @@
import java.util.Iterator;
import java.util.Stack;
import java.util.Vector;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import net.sf.javabdd.BDD.BDDIterator;
import edu.wis.jtlv.env.Env;
import edu.wis.jtlv.env.module.ModuleWithWeakFairness;
import edu.wis.jtlv.env.module.Module;
import edu.wis.jtlv.lib.FixPoint;
import edu.wis.jtlv.old_lib.games.GameException;
/**
* <p>
* Nir Piterman, Amir Pnueli, and Yaniv Sa’ar. Synthesis of Reactive(1) Designs.
* In VMCAI, pages 364–380, Charleston, SC, Jenuary 2006.
* </p>
* <p>
* To execute, create an object with two Modules, one for the system and the
* other for the environment, and then just extract the strategy through
* {@link edu.wis.jtlv.old_lib.games.GR1Game#printWinningStrategy()}.
* </p>
*
* @version {@value edu.wis.jtlv.env.Env#version}
* @author yaniv sa'ar. (parts modified by Cameron Finucane)
*
*/
public class GROneGame {
private ModuleWithWeakFairness env;
private ModuleWithWeakFairness sys;
int sysJustNum, envJustNum;
private BDD player1_winning;
private BDD player2_winning;
private boolean autBDDTrue;
// p2_winning in GRGAmes are !p1_winning
public GROneGame(ModuleWithWeakFairness env, ModuleWithWeakFairness sys, int sysJustNum, int envJustNum)
throws GameException {
if ((env == null) || (sys == null)) {
throw new GameException(
"cannot instanciate a GR[1] Game with an empty player.");
}
this.env = env;
this.sys = sys;
this.sysJustNum = sysJustNum;
this.envJustNum = envJustNum;
// for now I'm giving max_y 50, at the end I'll cut it (and during, I'll
// extend if needed. (using vectors only makes things more complicate
// since we cannot instantiate vectors with new vectors)
x_mem = new BDD[sysJustNum][envJustNum][50];
y_mem = new BDD[sysJustNum][50];
z_mem = new BDD[sysJustNum];
x2_mem = new BDD[sysJustNum][envJustNum][50][50];
y2_mem = new BDD[sysJustNum][50];
z2_mem = new BDD[50];
this.player2_winning = this.calculate_win();
this.player1_winning = this.calculate_loss();
//this.player1_winning = this.player2_winning.not();
}
public GROneGame(ModuleWithWeakFairness env, ModuleWithWeakFairness sys)
throws GameException {
this(env, sys, sys.justiceNum(), env.justiceNum());
}
public BDD[][][] x_mem;
public BDD[][][][] x2_mem;
public BDD[][] y_mem, y2_mem;
public BDD[] z_mem, z2_mem;
/**
* <p>
* Calculating winning states.
* </p>
*
* @return The winning states for this game.
*/
private BDD calculate_win() {
BDD x, y, z;
FixPoint<BDD> iterZ, iterY, iterX;
int cy = 0;
z = Env.TRUE();
for (iterZ = new FixPoint<BDD>(); iterZ.advance(z);) {
//for (int j = 0; j < sys.justiceNum(); j++) {
for (int j = 0; j < sysJustNum; j++) {
cy = 0;
y = Env.FALSE();
for (iterY = new FixPoint<BDD>(); iterY.advance(y);) {
BDD start = sys.justiceAt(j).and(env.yieldStates(sys, z))
.or(env.yieldStates(sys, y));
y = Env.FALSE();
for (int i = 0; i < envJustNum; i++) {
BDD negp = env.justiceAt(i).not();
x = z.id();
for (iterX = new FixPoint<BDD>(); iterX.advance(x);) {
x = negp.and(env.yieldStates(sys, x)).or(start);
}
x_mem[j][i][cy] = x.id();
//System.out.println("X ["+ j + ", " + i + ", " + cy + "] = " + x_mem[j][i][cy]);
y = y.id().or(x);
}
y_mem[j][cy] = y.id();
//System.out.println("Y ["+ j + "] = " + y_mem[j][cy]);
cy++;
if (cy % 50 == 0) {
x_mem = extend_size(x_mem, cy);
y_mem = extend_size(y_mem, cy);
}
}
z = y.id();
z_mem[j] = z.id();
//System.out.println("Z ["+ j + "] = " + z_mem[j]);
}
}
x_mem = extend_size(x_mem, 0);
y_mem = extend_size(y_mem, 0);
return z.id();
}
private BDD calculate_loss() {
BDD x, y, z;
FixPoint<BDD> iterZ, iterY, iterX;
int c = 0;
int a = 0;
z = Env.FALSE();
x = Env.FALSE();
for (iterZ = new FixPoint<BDD>(); iterZ.advance(z);) {
//for (int j = 0; j < sys.justiceNum(); j++) {
for (int j = 0; j < sysJustNum; j++) {
y = Env.TRUE();
for (iterY = new FixPoint<BDD>(); iterY.advance(y);) {
BDD start = ((sys.justiceAt(j).not()).or((env.yieldStates(sys, z.not())).not()))
//BDD start = ((sys.justiceAt(j).not()).or(sys.yieldStates(sys, z)))
.and((env.yieldStates(sys, y.not())).not());
for (int i = 0; i < envJustNum; i++) {
x = Env.FALSE();
c=0;
for (iterX = new FixPoint<BDD>(); iterX.advance(x);) {
x = x.id().or((env.justiceAt(i).or(((env.yieldStates(sys, x.not())).not()))).and(start));
//x = x.id().or((env.justiceAt(i).or(env.yieldStates(sys, x))).and(start));
x2_mem[j][i][a][c] = x.id();
//System.out.println("X ["+ j + ", " + i + ", " + a + ", " + c + "] = " + x2_mem[j][i][a][c]);
c++;
}
y = y.id().and(x);
}
if (c % 50 == 0) {
x2_mem = extend_size(x2_mem, c);
}
}
y2_mem[j][a] = y.id();
//System.out.println("Y ["+ j + ", " + c + "] = " + y2_mem[j][a]);
z = z.id().or(y);
}
z2_mem[a] = z.id();
//System.out.println("Z ["+ a + "] = " + z2_mem[a]);
a++;
if (a % 50 == 0) {
z2_mem = extend_size(z2_mem, a);
y2_mem = extend_size(y2_mem, a);
}
}
x2_mem = extend_size(x2_mem, 0);
y2_mem = extend_size(y2_mem, 0);
z2_mem = extend_size(z2_mem, 0);
//System.out.println("SAME " + z.id().equals(player2_winning.not()));
return z.id();
}
private BDD[][][][] extend_size(BDD[][][][] in, int extended_size) {
BDD[][][][] res;
if (extended_size > 0) {
res = new BDD[in.length][in[0].length][in[0][0].length + extended_size][in[0][0][0].length
+ extended_size];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
for (int k = 0; k < in[i][j].length; k++) {
for (int m = 0; m < in[i][j][k].length; m++) {
res[i][j][k][m] = in[i][j][k][m];
}
}
}
}
} else {
res = new BDD[in.length][in[0].length][in[0][0].length][];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
for (int k = 0; k < in[i][j].length; k++) {
int real_size = 0;
for (int m = 0; m < in[i][j][k].length; m++) {
if (in[i][j][k][m] != null)
real_size++;
}
res[i][j][k] = new BDD[real_size];
int new_add = 0;
for (int m = 0; m < in[i][j][k].length; m++) {
if (in[i][j][k][m] != null) {
res[i][j][k][new_add] = in[i][j][k][m];
new_add++;
}
}
}
}
}
}
return res;
}
// extended_size<=0 will tight the arrays to be the exact sizes.
private BDD[][][] extend_size(BDD[][][] in, int extended_size) {
BDD[][][] res;
if (extended_size > 0) {
res = new BDD[in.length][in[0].length][in[0][0].length
+ extended_size];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
for (int k = 0; k < in[i][j].length; k++) {
res[i][j][k] = in[i][j][k];
}
}
}
} else {
res = new BDD[in.length][in[0].length][];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
int real_size = 0;
for (int k = 0; k < in[i][j].length; k++) {
if (in[i][j][k] != null)
real_size++;
}
res[i][j] = new BDD[real_size];
int new_add = 0;
for (int k = 0; k < in[i][j].length; k++) {
if (in[i][j][k] != null) {
res[i][j][new_add] = in[i][j][k];
new_add++;
}
}
}
}
}
return res;
}
// extended_size<=0 will tight the arrays to be the exact sizes.
private BDD[][] extend_size(BDD[][] in, int extended_size) {
BDD[][] res;
if (extended_size > 0) {
res = new BDD[in.length][in[0].length + extended_size];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
res[i][j] = in[i][j];
}
}
} else {
res = new BDD[in.length][];
for (int i = 0; i < in.length; i++) {
int real_size = 0;
for (int j = 0; j < in[i].length; j++) {
if (in[i][j] != null)
real_size++;
}
res[i] = new BDD[real_size];
int new_add = 0;
for (int j = 0; j < in[i].length; j++) {
if (in[i][j] != null) {
res[i][new_add] = in[i][j];
new_add++;
}
}
}
}
return res;
}
private BDD[] extend_size(BDD[] in, int extended_size) {
BDD[] res;
if (extended_size > 0) {
res = new BDD[in.length + extended_size];
for (int i = 0; i < in.length; i++) {
res[i] = in[i];
}
} else {
int real_size = 0;
for (int j = 0; j < in.length; j++) {
if (in[j] != null)
real_size++;
}
res = new BDD[real_size];
for (int j = 0; j < real_size; j++) {
res[j] = in[j];
}
}
return res;
}
/**
* <p>
* Extracting an arbitrary implementation from the set of possible
* strategies.
* </p>
*/
public void printWinningStrategy(BDD ini) {
calculate_strategy(3, ini);
// return calculate_strategy(3);
// return calculate_strategy(7);
// return calculate_strategy(11);
// return calculate_strategy(15);
// return calculate_strategy(19);
// return calculate_strategy(23);
}
public void printLosingStrategy(BDD ini) {
calculate_counterstrategy(ini);
// return calculate_strategy(3);
// return calculate_strategy(7);
// return calculate_strategy(11);
// return calculate_strategy(15);
// return calculate_strategy(19);
}
//public void printLosingTrace(BDD ini) {
// calculate_countertrace(ini);
// return calculate_strategy(3);
// return calculate_strategy(7);
// return calculate_strategy(11);
// return calculate_strategy(15);
// return calculate_strategy(19);
// /}
/**
* <p>
* Extracting an implementation from the set of possible strategies with the
* given priority to the next step.
* </p>
* <p>
* Possible priorities are:<br>
* 3 - Z Y X.<br>
* 7 - Z X Y.<br>
* 11 - Y Z X.<br>
* 15 - Y X Z.<br>
* 19 - X Z Y.<br>
* 23 - X Y Z.<br>
* </p>
*
* @param kind
* The priority kind.
*/
public void calculate_strategy(int kind, BDD ini) {
calculate_strategy(kind, ini, true);
}
public boolean calculate_strategy(int kind, BDD ini, boolean det) {
int strategy_kind = kind;
BDD autBDD = sys.trans().and(env.trans());
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawState> aut = new Stack<RawState>();
boolean result = true;
// FDSModule res = new FDSModule("strategy");
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
j_stack.push(new Integer(0)); // TODO: is there a better default j?
//this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int p_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, p_j);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
/* Find Y index of current state */
// find minimal cy and an i
int p_cy = -1;
for (int i = 0; i < y_mem[p_j].length; i++) {
if (!p_st.and(y_mem[p_j][i]).isZero()) {
p_cy = i;
break;
}
}
assert p_cy >= 0 : "Couldn't find p_cy";
/* Find X index of current state */
int p_i = -1;
for (int i = 0; i < envJustNum; i++) {
if (!p_st.and(x_mem[p_j][i][p_cy]).isZero()) {
p_i = i;
break;
}
}
assert p_i >= 0 : "Couldn't find p_i";
// computing the set of env possible successors.
Vector<BDD> succs = new Vector<BDD>();
BDD all_succs = env.succ(p_st);
if (all_succs.isZero()) return true;
for (BDDIterator all_states = all_succs.iterator(env
.moduleUnprimeVars()); all_states.hasNext();) {
BDD sin = (BDD) all_states.next();
succs.add(sin);
}
BDD candidate = Env.FALSE();
// For each env successor, find a strategy successor
for (Iterator<BDD> iter_succ = succs.iterator(); iter_succ
.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.next());
BDD next_op = Env
.unprime(sys.trans().and(p_st).and(primed_cur_succ)
.exist(
env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())));
candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// (rho_1 in Piterman; satisfy current goal and move to next goal)
if ((local_kind == 3) | (local_kind == 7)
| (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
if (!p_st.and(sys.justiceAt(p_j)).isZero()) {
int next_p_j = (p_j + 1) % sysJustNum;
//Look for the next goal and see if you can satisfy it by staying in place. If so, swell.
while (!next_op.and(sys.justiceAt(next_p_j)).isZero() && next_p_j!=p_j)
{
next_p_j = (next_p_j + 1) % sysJustNum;
}
- if (next_p_j!=p_j)
+ if (next_p_j!=p_j || sysJustNum == 1)
{
int look_r = 0;
while ((next_op.and(y_mem[next_p_j][look_r]).isZero())) {
look_r++;
}
BDD opt = next_op.and(y_mem[next_p_j][look_r]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("1");
jcand = next_p_j;
}
- } else if (sysJustNum != 1) {
+ } else {
//There are no unsatisfied goals, so just stay in place, yay.
candidate = next_op;
jcand = p_j;
//System.out.println("All goals satisfied");
}
}
}
// b - second successor option in the strategy.
// (rho_2 in Piterman; move closer to current goal)
if ((local_kind == 2) | (local_kind == 5)
| (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the farest r.
while ((next_op.and(y_mem[p_j][look_r]).isZero())
& (look_r < p_cy)) {
look_r++;
}
BDD opt = next_op.and(y_mem[p_j][look_r]);
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt;
//System.out.println("2");
}
}
}
// c - third successor option in the strategy.
// (rho_3 in Piterman; falsify environment :()
if ((local_kind == 1) | (local_kind == 6)
| (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
if (!p_st.and(env.justiceAt(p_i).not()).isZero()) {
BDD opt = next_op.and(x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("3");
}
}
}
// no successor was found yet.
//assert ((local_kind != 0) & (local_kind != 4)
if (!((local_kind != 0) & (local_kind != 4)
& (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20))) {
//System.out.println("No successor was found");
assert !det : "No successor was found";
if (strategy_kind == 3) result = false;
else candidate = next_op.and(y_mem[p_j][p_cy]);
}
local_kind--;
}
// picking one candidate. In JDD satOne is not take
// env.unprimeVars().union(sys.unprimeVars()) into its
// considerations.
// BDD one_cand = candidate.satOne();
/* BDD one_cand = candidate.satOne(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars()), false);
*/
for (BDDIterator candIter = candidate.iterator(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())); candIter.hasNext();) {
BDD one_cand = (BDD) candIter.next();
RawState gsucc = new RawState(aut.size(), one_cand, jcand);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(one_cand);
j_stack.push(jcand);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
if (det) break; //if we only need one successor, stop here
}
autBDD = autBDD.and((p_st.imp(Env.prime(candidate))));
result = result & (candidate.equals(next_op));
//result = result & (candidate.equals(env.trans().and(sys.trans())));
}
}
}
/* Remove stuttering */
// TODO: Make this more efficient (and less ugly) if possible
/*
int num_removed = 0;
for (RawState state1 : aut) {
int j1 = state1.get_rank();
for (RawState state2 : state1.get_succ()) {
int j2 = state2.get_rank();
if ((j2 == (j1 + 1) % sys.justiceNum()) &&
state1.equals(state2, false)) {
// Find any states pointing to state1
for (RawState state3 : aut) {
if (state3.get_succ().indexOf(state1) != -1) {
// Redirect transitions to state2
state3.del_succ(state1);
state3.add_succ(state2);
// Mark the extra state for deletion
state1.set_rank(-1);
}
}
}
}
if (state1.get_rank() == -1) {
num_removed++;
}
}
System.out.println("Removed " + num_removed + " stutter states.");
*/
/* Print output */
if (det) {
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
System.out.print("\n\n");
}
if (strategy_kind == 3) return result; else return false;
}
public void generate_safety_aut(BDD ini) {
Stack<BDD> st_stack = new Stack<BDD>();
Stack<RawState> aut = new Stack<RawState>();
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, 0);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
BDD next_op = Env.unprime(sys.trans().and(p_st).exist(env.moduleUnprimeVars().union(sys.moduleUnprimeVars())));
BDDIterator next_iterator = next_op.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (next_iterator.hasNext()) {
BDD this_next = (BDD) next_iterator.next();
//this_next.printSet();
RawState gsucc = new RawState(aut.size(), this_next, 0);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(this_next);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
}
//System.out.print("------------\n");
}
}
/* Print output */
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
}
public void calculate_counterstrategy(BDD ini) {
calculate_counterstrategy(ini, true, true);
}
public boolean calculate_counterstrategy(BDD ini, boolean enable_234, boolean det) {
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> i_stack = new Stack<Integer>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawCState> aut = new Stack<RawCState>();
BDD autBDD = sys.trans().and(env.trans());
boolean result = true;
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
int a = 0;
BDD this_ini = (BDD) ini_iterator.next();
int idx = -1;
st_stack.push(this_ini);
i_stack.push(new Integer(0)); // TODO: is there a better default j?
j_stack.push(new Integer(-1)); // TODO: is there a better default j?
this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int rank_i = i_stack.pop().intValue();
int rank_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawCState new_state = new RawCState(aut.size(), p_st, rank_j, rank_i, Env.FALSE());
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
BDD primed_cur_succ = Env.prime(env.succ(p_st));
BDD input = Env.FALSE();
int new_i = 0, new_j = -1;
/* Find Z index of current state */
// find minimal cy and an i
int p_az = -1;
for (int i = 0; i < z2_mem.length; i++) {
if (!p_st.and(z2_mem[i]).isZero()) {
p_az = i;
break;
}
}
assert p_az >= 0 : "Couldn't find p_az";
/* Find Y index of current state */
int p_j = -1;
for (int j = 0; j < sysJustNum; j++) {
if (!p_st.and(y2_mem[j][p_az]).isZero()) {
p_j = j;
break;
}
}
assert p_j >= 0 : "Couldn't find p_j";
/* Find X index of current state */
int p_c = -1;
for (int c = 0; c < x2_mem[p_j][rank_i][p_az].length; c++) {
if (!p_st.and(x2_mem[p_j][rank_i][p_az][c]).isZero()) {
p_c = c;
break;
}
}
assert p_c >= 0 : "Couldn't find p_c";
while(input.isZero()) {
input = p_st.and(z2_mem[0]).and(primed_cur_succ.and(sys.yieldStates(env,Env.FALSE())));
if (!input.isZero()) {
new_i = rank_i;
new_j = -1;
break;
}
//\rho_1 transitions in K\"onighofer et al
for (int az = 1; az < z2_mem.length; az++) {
input = p_st.and(z2_mem[az]).and(z2_mem[az-1].not())
.and((primed_cur_succ.and(sys.yieldStates(env,(Env.unprime(primed_cur_succ).and(z2_mem[az-1]))))));
if (!input.isZero()) {
//System.out.println("RHO 1");
new_i = rank_i;
new_j = -1;
break;
}
}
//if we are only looking for unsatisfiability, we only allow transitions
//into a lower iterate of Z, i.e. \rho_1
if (!enable_234) {
//if (input.isZero()) System.out.println("No successor was found");
result = false;
break;
}
if (!input.isZero()) break;
//\rho_2 transitions
if (rank_j == -1) {
for (int az = 0; az < z2_mem.length; az++) {
for (int j = 0; j < sysJustNum; j++) {
if (az == 0)
input = p_st.and(z2_mem[az])
.and(primed_cur_succ.and(sys.yieldStates(env,(y2_mem[j][az]))))
.and(sys.yieldStates(env,(Env.FALSE())).not());
else
input = p_st.and(z2_mem[az]).and(z2_mem[az-1].not())
.and(primed_cur_succ.and(sys.yieldStates(env,(y2_mem[j][az]))))
.and((sys.yieldStates(env,(z2_mem[az-1]))).not());
if (!input.isZero()) {
//System.out.println("RHO 2");
new_i = rank_i;
new_j = j;
break;
}
}
if (new_j != -1) break;
}
}
if (!input.isZero()) break;
//\rho_3 transitions
if (rank_j != -1 && rank_i != -1 && p_st.and(env.justiceAt(rank_i)).isZero()) {
//System.out.println("RHO 3");
new_i = (rank_i + 1) % env.justiceNum();
new_j = rank_j;
for (int az = 0; az < z2_mem.length; az++) {
if (az == 0)
input = (p_st.and(z2_mem[az])
.and(primed_cur_succ.and(sys.yieldStates(env,y2_mem[rank_j][az])))
.and((sys.yieldStates(env,(Env.FALSE()))).not()));
else
input = (p_st.and(z2_mem[az]).and(z2_mem[az-1].not())
.and(primed_cur_succ.and((sys.yieldStates(env,y2_mem[rank_j][az]))))
.and((sys.yieldStates(env,z2_mem[az-1])).not()));
if (!input.isZero()) break;
}
}
if (!input.isZero()) break;
//\rho_4 transitions
for (int az = 0; az < z2_mem.length; az++) {
if (rank_i != -1 && rank_j != -1) {
for (int c = 1; c < x2_mem[rank_j][rank_i][az].length; c++) {
if (az == 0)
input = ((p_st.and(z2_mem[az])
.and(x2_mem[rank_j][rank_i][az][c])
.and(x2_mem[rank_j][rank_i][az][c-1].not())
.and(primed_cur_succ.and((sys.yieldStates(env,x2_mem[rank_j][rank_i][az][c-1])))
.and(sys.yieldStates(env,Env.FALSE()).not()))));
else
input = ((p_st.and(z2_mem[az])
.and(x2_mem[rank_j][rank_i][az][c])
.and(x2_mem[rank_j][rank_i][az][c-1].not())
.and(primed_cur_succ.and((sys.yieldStates(env,x2_mem[rank_j][rank_i][az][c-1])))
.and((sys.yieldStates(env,z2_mem[az-1])).not()))));
if (!input.isZero()) {
//System.out.println("RHO 4");
new_i = rank_i;
new_j = rank_j;
break;
}
}
}
}
//if (p_az == 0) input = p_st.and(z2_mem[p_az])
// .and(primed_cur_succ.and(sys.yieldStates(env,(y2_mem[p_j][p_az]))));
if (p_az == 0) {
if (p_c > 0)
input = ((p_st.and((primed_cur_succ.and((sys.yieldStates(env,x2_mem[p_j][rank_i][p_az][p_c-1])))))));
else
input = ((p_st.and((primed_cur_succ.and((sys.yieldStates(env,x2_mem[p_j][rank_i][p_az][p_c])))))));
}
assert (!input.isZero()) : "No successor was found";
}
addState(new_state, input, new_i, new_j, aut, st_stack, i_stack, j_stack, det);
autBDD = autBDD.and(p_st.imp(input));
//result is true if for every state, all environment actions take us into a lower iterate of Z
//this means the environment can do anything to prevent the system from achieving some goal.
result = result & (input.equals(p_st));
}
}
if (det) {
String res = "";
for (RawCState state : aut) {
if (state.get_rank_i() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
}
return result;
}
public void addState(RawCState new_state, BDD input, int new_i, int new_j, Stack<RawCState> aut, Stack<BDD> st_stack, Stack<Integer> i_stack, Stack<Integer> j_stack, boolean det) {
//method for adding stated to the aut and state stack, based on whether we want a deterministic or nondet automaton
for (BDDIterator inputIter = input.iterator(env
.modulePrimeVars()); inputIter.hasNext();) {
BDD inputOne = (BDD) inputIter.next();
// computing the set of system possible successors.
Vector<BDD> sys_succs = new Vector<BDD>();
BDD all_sys_succs = sys.succ(new_state.get_state().and(inputOne));
int idx = -1;
if (all_sys_succs.equals(Env.FALSE())) {
RawCState gsucc = new RawCState(aut.size(), Env.unprime(inputOne), new_j, new_i, inputOne);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
continue;
}
for (BDDIterator all_sys_states = all_sys_succs.iterator(sys
.moduleUnprimeVars()); all_sys_states.hasNext();) {
BDD sin = (BDD) all_sys_states.next();
sys_succs.add(sin);
}
// For each system successor, find a strategy successor
for (Iterator<BDD> iter_succ = sys_succs.iterator(); iter_succ
.hasNext();) {
BDD sys_succ = iter_succ.next().and(Env.unprime(inputOne));
RawCState gsucc = new RawCState(aut.size(), sys_succ, new_j, new_i, inputOne);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(sys_succ);
i_stack.push(new_i);
j_stack.push(new_j);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
}
if (det) break;
}
}
@SuppressWarnings("unused")
private class RawState {
private int id;
private int rank;
private BDD state;
private Vector<RawState> succ;
public RawState(int id, BDD state, int rank) {
this.id = id;
this.state = state;
this.rank = rank;
succ = new Vector<RawState>(10);
}
public void add_succ(RawState to_add) {
succ.add(to_add);
}
public void del_succ(RawState to_del) {
succ.remove(to_del);
}
public BDD get_state() {
return this.state;
}
public int get_rank() {
return this.rank;
}
public void set_rank(int rank) {
this.rank = rank;
}
public Vector<RawState> get_succ() {
//RawState[] res = new RawState[this.succ.size()];
//this.succ.toArray(res);
return this.succ;
}
public boolean equals(Object other) {
return this.equals(other, true);
}
public boolean equals(Object other, boolean use_rank) {
if (!(other instanceof RawState))
return false;
RawState other_raw = (RawState) other;
if (other_raw == null)
return false;
if (use_rank) {
return ((this.rank == other_raw.rank) & (this.state
.equals(other_raw.state)));
} else {
return (this.state.equals(other_raw.state));
}
}
public String toString() {
String res = "State " + id + " with rank " + rank + " -> "
+ state.toStringWithDomains(Env.stringer) + "\n";
if (succ.isEmpty()) {
res += "\tWith no successors.";
} else {
RawState[] all_succ = new RawState[succ.size()];
succ.toArray(all_succ);
res += "\tWith successors : " + all_succ[0].id;
for (int i = 1; i < all_succ.length; i++) {
res += ", " + all_succ[i].id;
}
}
return res;
}
}
private class RawCState {
private int id;
private int rank_i;//_old, rank_j_old;
private int rank_j;//i_new, rank_j_new;
private BDD input;
private BDD state;
private Vector<RawCState> succ;
/*public RawCState(int id, BDD state, int rank_i_old, int rank_i_new, int rank_j_old, int rank_j_new, BDD input) {
this.id = id;
this.state = state;
this.rank_i_old = rank_i_old;
this.rank_j_old = rank_j_old;
this.rank_i_new = rank_i_new;
this.rank_j_new = rank_j_new;
this.input = input;
}*/
public RawCState(int id, BDD state, int rank_j, int rank_i, BDD input) {
this.id = id;
this.state = state;
this.rank_i = rank_i;
this.rank_j = rank_j;
this.input = input;
succ = new Vector<RawCState>(10);
}
public void add_succ(RawCState to_add) {
succ.add(to_add);
}
public void del_succ(RawCState to_del) {
succ.remove(to_del);
}
public BDD get_input() {
return this.input;
}
public void set_input(BDD input) {
this.input = input;
}
public BDD get_state() {
return this.state;
}
public int get_rank_i() {
return this.rank_i;
}
public void set_rank_i(int rank) {
this.rank_i = rank;
}
public int get_rank_j() {
return this.rank_j;
}
public void set_rank_j(int rank) {
this.rank_j = rank;
}
/*public int get_rank_i_new() {
return this.rank_i_new;
}
public void set_rank_i_new(int rank) {
this.rank_i_new = rank;
}
public int get_rank_j_new() {
return this.rank_j_new;
}
public void set_rank_j_new(int rank) {
this.rank_j_new = rank;
}*/
public boolean equals(Object other) {
return this.equals(other, true);
}
public boolean equals(Object other, boolean use_rank) {
if (!(other instanceof RawCState))
return false;
RawCState other_raw = (RawCState) other;
if (other_raw == null)
return false;
if (use_rank) {
//return ((this.rank_i_old == other_raw.rank_i_old) & (this.rank_j_old == other_raw.rank_j_old) & (this.rank_i_new == other_raw.rank_i_new) & (this.rank_j_new == other_raw.rank_j_new) &
return ((this.rank_i == other_raw.rank_i) & (this.rank_j == other_raw.rank_j) &
(this.state.equals(other_raw.state)));
} else {
return ((this.state.equals(other_raw.state)));
}
}
/*public String toString() {
String res = "State " + id + " with rank_i " + rank_i + " with rank_j " + rank_j + " -> "
+ state.toStringWithDomains(Env.stringer) + "\n";
if (succ.isEmpty()) {
res += "\tWith no successors.";
} else {
RawCState[] all_succ = new RawCState[succ.size()];
succ.toArray(all_succ);
res += "\tWith successors : " + all_succ[0].id;
for (int i = 1; i < all_succ.length; i++) {
res += ", " + all_succ[i].id;
}
}
res += "\tWith input : " + input.toStringWithDomains(Env.stringer) + "\n";
return res;
}*/
public String toString() {
String res = "State " + id + " with rank (" + rank_i + "," + rank_j + ") -> "
+ state.toStringWithDomains(Env.stringer) + "\n";
if (succ.isEmpty()) {
res += "\tWith no successors.";
} else {
RawCState[] all_succ = new RawCState[succ.size()];
succ.toArray(all_succ);
res += "\tWith successors : " + all_succ[0].id;
for (int i = 1; i < all_succ.length; i++) {
res += ", " + all_succ[i].id;
}
}
return res;
}
}
/**
* <p>
* Getter for the environment player.
* </p>
*
* @return The environment player.
*/
public ModuleWithWeakFairness getEnvPlayer() {
return env;
}
/**
* <p>
* Getter for the system player.
* </p>
*
* @return The system player.
*/
public ModuleWithWeakFairness getSysPlayer() {
return sys;
}
/**
* <p>
* Getter for the environment's winning states.
* </p>
*
* @return The environment's winning states.
*/
public BDD sysWinningStates() {
return player2_winning;
}
/**
* <p>
* Getter for the system's winning states.
* </p>
*
* @return The system's winning states.
*/
public BDD envWinningStates() {
return player2_winning.not();
}
public BDD gameInitials() {
return getSysPlayer().initial().and(getEnvPlayer().initial());
}
public BDD[] playersWinningStates() {
return new BDD[] { envWinningStates(), sysWinningStates() };
}
public BDD firstPlayersWinningStates() {
return envWinningStates();
}
public BDD secondPlayersWinningStates() {
return sysWinningStates();
}
}
| false | true | public boolean calculate_strategy(int kind, BDD ini, boolean det) {
int strategy_kind = kind;
BDD autBDD = sys.trans().and(env.trans());
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawState> aut = new Stack<RawState>();
boolean result = true;
// FDSModule res = new FDSModule("strategy");
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
j_stack.push(new Integer(0)); // TODO: is there a better default j?
//this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int p_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, p_j);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
/* Find Y index of current state */
// find minimal cy and an i
int p_cy = -1;
for (int i = 0; i < y_mem[p_j].length; i++) {
if (!p_st.and(y_mem[p_j][i]).isZero()) {
p_cy = i;
break;
}
}
assert p_cy >= 0 : "Couldn't find p_cy";
/* Find X index of current state */
int p_i = -1;
for (int i = 0; i < envJustNum; i++) {
if (!p_st.and(x_mem[p_j][i][p_cy]).isZero()) {
p_i = i;
break;
}
}
assert p_i >= 0 : "Couldn't find p_i";
// computing the set of env possible successors.
Vector<BDD> succs = new Vector<BDD>();
BDD all_succs = env.succ(p_st);
if (all_succs.isZero()) return true;
for (BDDIterator all_states = all_succs.iterator(env
.moduleUnprimeVars()); all_states.hasNext();) {
BDD sin = (BDD) all_states.next();
succs.add(sin);
}
BDD candidate = Env.FALSE();
// For each env successor, find a strategy successor
for (Iterator<BDD> iter_succ = succs.iterator(); iter_succ
.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.next());
BDD next_op = Env
.unprime(sys.trans().and(p_st).and(primed_cur_succ)
.exist(
env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())));
candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// (rho_1 in Piterman; satisfy current goal and move to next goal)
if ((local_kind == 3) | (local_kind == 7)
| (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
if (!p_st.and(sys.justiceAt(p_j)).isZero()) {
int next_p_j = (p_j + 1) % sysJustNum;
//Look for the next goal and see if you can satisfy it by staying in place. If so, swell.
while (!next_op.and(sys.justiceAt(next_p_j)).isZero() && next_p_j!=p_j)
{
next_p_j = (next_p_j + 1) % sysJustNum;
}
if (next_p_j!=p_j)
{
int look_r = 0;
while ((next_op.and(y_mem[next_p_j][look_r]).isZero())) {
look_r++;
}
BDD opt = next_op.and(y_mem[next_p_j][look_r]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("1");
jcand = next_p_j;
}
} else if (sysJustNum != 1) {
//There are no unsatisfied goals, so just stay in place, yay.
candidate = next_op;
jcand = p_j;
//System.out.println("All goals satisfied");
}
}
}
// b - second successor option in the strategy.
// (rho_2 in Piterman; move closer to current goal)
if ((local_kind == 2) | (local_kind == 5)
| (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the farest r.
while ((next_op.and(y_mem[p_j][look_r]).isZero())
& (look_r < p_cy)) {
look_r++;
}
BDD opt = next_op.and(y_mem[p_j][look_r]);
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt;
//System.out.println("2");
}
}
}
// c - third successor option in the strategy.
// (rho_3 in Piterman; falsify environment :()
if ((local_kind == 1) | (local_kind == 6)
| (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
if (!p_st.and(env.justiceAt(p_i).not()).isZero()) {
BDD opt = next_op.and(x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("3");
}
}
}
// no successor was found yet.
//assert ((local_kind != 0) & (local_kind != 4)
if (!((local_kind != 0) & (local_kind != 4)
& (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20))) {
//System.out.println("No successor was found");
assert !det : "No successor was found";
if (strategy_kind == 3) result = false;
else candidate = next_op.and(y_mem[p_j][p_cy]);
}
local_kind--;
}
// picking one candidate. In JDD satOne is not take
// env.unprimeVars().union(sys.unprimeVars()) into its
// considerations.
// BDD one_cand = candidate.satOne();
/* BDD one_cand = candidate.satOne(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars()), false);
*/
for (BDDIterator candIter = candidate.iterator(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())); candIter.hasNext();) {
BDD one_cand = (BDD) candIter.next();
RawState gsucc = new RawState(aut.size(), one_cand, jcand);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(one_cand);
j_stack.push(jcand);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
if (det) break; //if we only need one successor, stop here
}
autBDD = autBDD.and((p_st.imp(Env.prime(candidate))));
result = result & (candidate.equals(next_op));
//result = result & (candidate.equals(env.trans().and(sys.trans())));
}
}
}
/* Remove stuttering */
// TODO: Make this more efficient (and less ugly) if possible
/*
int num_removed = 0;
for (RawState state1 : aut) {
int j1 = state1.get_rank();
for (RawState state2 : state1.get_succ()) {
int j2 = state2.get_rank();
if ((j2 == (j1 + 1) % sys.justiceNum()) &&
state1.equals(state2, false)) {
// Find any states pointing to state1
for (RawState state3 : aut) {
if (state3.get_succ().indexOf(state1) != -1) {
// Redirect transitions to state2
state3.del_succ(state1);
state3.add_succ(state2);
// Mark the extra state for deletion
state1.set_rank(-1);
}
}
}
}
if (state1.get_rank() == -1) {
num_removed++;
}
}
System.out.println("Removed " + num_removed + " stutter states.");
*/
/* Print output */
if (det) {
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
System.out.print("\n\n");
}
if (strategy_kind == 3) return result; else return false;
}
| public boolean calculate_strategy(int kind, BDD ini, boolean det) {
int strategy_kind = kind;
BDD autBDD = sys.trans().and(env.trans());
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawState> aut = new Stack<RawState>();
boolean result = true;
// FDSModule res = new FDSModule("strategy");
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
j_stack.push(new Integer(0)); // TODO: is there a better default j?
//this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int p_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, p_j);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
/* Find Y index of current state */
// find minimal cy and an i
int p_cy = -1;
for (int i = 0; i < y_mem[p_j].length; i++) {
if (!p_st.and(y_mem[p_j][i]).isZero()) {
p_cy = i;
break;
}
}
assert p_cy >= 0 : "Couldn't find p_cy";
/* Find X index of current state */
int p_i = -1;
for (int i = 0; i < envJustNum; i++) {
if (!p_st.and(x_mem[p_j][i][p_cy]).isZero()) {
p_i = i;
break;
}
}
assert p_i >= 0 : "Couldn't find p_i";
// computing the set of env possible successors.
Vector<BDD> succs = new Vector<BDD>();
BDD all_succs = env.succ(p_st);
if (all_succs.isZero()) return true;
for (BDDIterator all_states = all_succs.iterator(env
.moduleUnprimeVars()); all_states.hasNext();) {
BDD sin = (BDD) all_states.next();
succs.add(sin);
}
BDD candidate = Env.FALSE();
// For each env successor, find a strategy successor
for (Iterator<BDD> iter_succ = succs.iterator(); iter_succ
.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.next());
BDD next_op = Env
.unprime(sys.trans().and(p_st).and(primed_cur_succ)
.exist(
env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())));
candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// (rho_1 in Piterman; satisfy current goal and move to next goal)
if ((local_kind == 3) | (local_kind == 7)
| (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
if (!p_st.and(sys.justiceAt(p_j)).isZero()) {
int next_p_j = (p_j + 1) % sysJustNum;
//Look for the next goal and see if you can satisfy it by staying in place. If so, swell.
while (!next_op.and(sys.justiceAt(next_p_j)).isZero() && next_p_j!=p_j)
{
next_p_j = (next_p_j + 1) % sysJustNum;
}
if (next_p_j!=p_j || sysJustNum == 1)
{
int look_r = 0;
while ((next_op.and(y_mem[next_p_j][look_r]).isZero())) {
look_r++;
}
BDD opt = next_op.and(y_mem[next_p_j][look_r]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("1");
jcand = next_p_j;
}
} else {
//There are no unsatisfied goals, so just stay in place, yay.
candidate = next_op;
jcand = p_j;
//System.out.println("All goals satisfied");
}
}
}
// b - second successor option in the strategy.
// (rho_2 in Piterman; move closer to current goal)
if ((local_kind == 2) | (local_kind == 5)
| (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the farest r.
while ((next_op.and(y_mem[p_j][look_r]).isZero())
& (look_r < p_cy)) {
look_r++;
}
BDD opt = next_op.and(y_mem[p_j][look_r]);
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt;
//System.out.println("2");
}
}
}
// c - third successor option in the strategy.
// (rho_3 in Piterman; falsify environment :()
if ((local_kind == 1) | (local_kind == 6)
| (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
if (!p_st.and(env.justiceAt(p_i).not()).isZero()) {
BDD opt = next_op.and(x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("3");
}
}
}
// no successor was found yet.
//assert ((local_kind != 0) & (local_kind != 4)
if (!((local_kind != 0) & (local_kind != 4)
& (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20))) {
//System.out.println("No successor was found");
assert !det : "No successor was found";
if (strategy_kind == 3) result = false;
else candidate = next_op.and(y_mem[p_j][p_cy]);
}
local_kind--;
}
// picking one candidate. In JDD satOne is not take
// env.unprimeVars().union(sys.unprimeVars()) into its
// considerations.
// BDD one_cand = candidate.satOne();
/* BDD one_cand = candidate.satOne(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars()), false);
*/
for (BDDIterator candIter = candidate.iterator(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())); candIter.hasNext();) {
BDD one_cand = (BDD) candIter.next();
RawState gsucc = new RawState(aut.size(), one_cand, jcand);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(one_cand);
j_stack.push(jcand);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
if (det) break; //if we only need one successor, stop here
}
autBDD = autBDD.and((p_st.imp(Env.prime(candidate))));
result = result & (candidate.equals(next_op));
//result = result & (candidate.equals(env.trans().and(sys.trans())));
}
}
}
/* Remove stuttering */
// TODO: Make this more efficient (and less ugly) if possible
/*
int num_removed = 0;
for (RawState state1 : aut) {
int j1 = state1.get_rank();
for (RawState state2 : state1.get_succ()) {
int j2 = state2.get_rank();
if ((j2 == (j1 + 1) % sys.justiceNum()) &&
state1.equals(state2, false)) {
// Find any states pointing to state1
for (RawState state3 : aut) {
if (state3.get_succ().indexOf(state1) != -1) {
// Redirect transitions to state2
state3.del_succ(state1);
state3.add_succ(state2);
// Mark the extra state for deletion
state1.set_rank(-1);
}
}
}
}
if (state1.get_rank() == -1) {
num_removed++;
}
}
System.out.println("Removed " + num_removed + " stutter states.");
*/
/* Print output */
if (det) {
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
System.out.print("\n\n");
}
if (strategy_kind == 3) return result; else return false;
}
|
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/AppServletModule.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/AppServletModule.java
index cf15c4e4..573e8288 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/AppServletModule.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/AppServletModule.java
@@ -1,60 +1,60 @@
/*
* Copyright 2009-2012 European Molecular Biology Laboratory
*
* 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 impl
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.fg.annotare2.web.server;
import com.google.inject.Scopes;
import com.google.inject.servlet.ServletModule;
import uk.ac.ebi.fg.annotare2.dao.SubmissionDao;
import uk.ac.ebi.fg.annotare2.dao.UserDao;
import uk.ac.ebi.fg.annotare2.dao.dummy.SubmissionDaoDummy;
import uk.ac.ebi.fg.annotare2.dao.dummy.UserDaoDummy;
import uk.ac.ebi.fg.annotare2.web.server.auth.*;
import uk.ac.ebi.fg.annotare2.web.server.rpc.CurrentUserAccountServiceImpl;
import uk.ac.ebi.fg.annotare2.web.server.rpc.SubmissionServiceImpl;
import uk.ac.ebi.fg.annotare2.web.server.services.AccountManager;
import uk.ac.ebi.fg.annotare2.web.server.services.SubmissionManager;
/**
* @author Olga Melnichuk
*/
public class AppServletModule extends ServletModule {
@Override
protected void configureServlets() {
filter("/UserApp/*", "/index.html").through(SecurityFilter.class);
- serve("/login").with(LoginServlet.class);
- serve("/logout").with(LogoutServlet.class);
+ serveRegex("/login(;jsessionid=[A-Z0-9]+)?").with(LoginServlet.class);
+ serveRegex("/logout(;jsessionid=[A-Z0-9]+)?").with(LogoutServlet.class);
bind(SecurityFilter.class).in(Scopes.SINGLETON);
bind(LoginServlet.class).in(Scopes.SINGLETON);
bind(LogoutServlet.class).in(Scopes.SINGLETON);
serve("/UserApp/me").with(CurrentUserAccountServiceImpl.class);
bind(CurrentUserAccountServiceImpl.class).in(Scopes.SINGLETON);
serve("/UserApp/mySubmissions").with(SubmissionServiceImpl.class);
bind(SubmissionServiceImpl.class).in(Scopes.SINGLETON);
bind(UserDao.class).to(UserDaoDummy.class).in(Scopes.SINGLETON);
bind(SubmissionDao.class).to(SubmissionDaoDummy.class).in(Scopes.SINGLETON);
bind(AccountManager.class).in(Scopes.SINGLETON);
bind(SubmissionManager.class).in(Scopes.SINGLETON);
bind(AuthService.class).to(AuthServiceImpl.class).in(Scopes.SINGLETON);
}
}
| true | true | protected void configureServlets() {
filter("/UserApp/*", "/index.html").through(SecurityFilter.class);
serve("/login").with(LoginServlet.class);
serve("/logout").with(LogoutServlet.class);
bind(SecurityFilter.class).in(Scopes.SINGLETON);
bind(LoginServlet.class).in(Scopes.SINGLETON);
bind(LogoutServlet.class).in(Scopes.SINGLETON);
serve("/UserApp/me").with(CurrentUserAccountServiceImpl.class);
bind(CurrentUserAccountServiceImpl.class).in(Scopes.SINGLETON);
serve("/UserApp/mySubmissions").with(SubmissionServiceImpl.class);
bind(SubmissionServiceImpl.class).in(Scopes.SINGLETON);
bind(UserDao.class).to(UserDaoDummy.class).in(Scopes.SINGLETON);
bind(SubmissionDao.class).to(SubmissionDaoDummy.class).in(Scopes.SINGLETON);
bind(AccountManager.class).in(Scopes.SINGLETON);
bind(SubmissionManager.class).in(Scopes.SINGLETON);
bind(AuthService.class).to(AuthServiceImpl.class).in(Scopes.SINGLETON);
}
| protected void configureServlets() {
filter("/UserApp/*", "/index.html").through(SecurityFilter.class);
serveRegex("/login(;jsessionid=[A-Z0-9]+)?").with(LoginServlet.class);
serveRegex("/logout(;jsessionid=[A-Z0-9]+)?").with(LogoutServlet.class);
bind(SecurityFilter.class).in(Scopes.SINGLETON);
bind(LoginServlet.class).in(Scopes.SINGLETON);
bind(LogoutServlet.class).in(Scopes.SINGLETON);
serve("/UserApp/me").with(CurrentUserAccountServiceImpl.class);
bind(CurrentUserAccountServiceImpl.class).in(Scopes.SINGLETON);
serve("/UserApp/mySubmissions").with(SubmissionServiceImpl.class);
bind(SubmissionServiceImpl.class).in(Scopes.SINGLETON);
bind(UserDao.class).to(UserDaoDummy.class).in(Scopes.SINGLETON);
bind(SubmissionDao.class).to(SubmissionDaoDummy.class).in(Scopes.SINGLETON);
bind(AccountManager.class).in(Scopes.SINGLETON);
bind(SubmissionManager.class).in(Scopes.SINGLETON);
bind(AuthService.class).to(AuthServiceImpl.class).in(Scopes.SINGLETON);
}
|
diff --git a/src/worker/GeneSetMerger.java b/src/worker/GeneSetMerger.java
index 55b7931..0ea44bb 100644
--- a/src/worker/GeneSetMerger.java
+++ b/src/worker/GeneSetMerger.java
@@ -1,263 +1,266 @@
package worker;
import java.io.BufferedReader;
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.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import obj.GeneSet;
import obj.ValIdx;
public class GeneSetMerger extends DistributedWorker{
ArrayList<GeneSet> allGeneSets;
public static int mergeCount = 0;
public static int minSize = 0;
public GeneSetMerger(int id, int totalComputers, long jobID){
super(id, totalComputers, jobID);
allGeneSets = new ArrayList<GeneSet>();
}
public void mergeWeightedGeneSets(String path, int numFiles, float precision, boolean finalOutput) throws IOException{
if(!path.endsWith("/")) path = path + "/";
int start = id * numFiles/totalComputers;
int end = (id+1) * numFiles/totalComputers;
BufferedReader br;
ArrayList<float[]> wVecs = new ArrayList<float[]>();
ArrayList<ArrayList<Integer>> basins = new ArrayList<ArrayList<Integer>>();
ArrayList<String> chrs = new ArrayList<String>();
System.out.println("Processing file " + start + " to file " + end );
for(int i = start; i < end; i++){
System.out.println(i);
br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt"));
String line = br.readLine();
// Greedily merge gene set
while(line != null){
String[] tokens = line.split("\t");
String tag = tokens[0];
int nt = tokens.length;
int m = nt-2;
float[] wvec = new float[m];
ArrayList<Integer> basin = new ArrayList<Integer>();
String[] t2 = tokens[1].split(",");
int nt2 = t2.length;
+ if(finalOutput && nt2 < 2){
+ continue;
+ }
for(int j = 0; j < nt2; j++){
basin.add(Integer.parseInt(t2[j]));
}
for(int j = 0; j < m; j++){
wvec[j] = Float.parseFloat(tokens[j+2]);
}
boolean newOne = true;
int foundIdx = -1;
for(int j = 0; j < wVecs.size(); j++){
if(tag.equals(chrs.get(j))){
float[] fs = wVecs.get(j);
float err = Converger.calcMSE(fs, wvec, m);
if(err < precision/m){
foundIdx = j;
newOne = false;
break;
}
}
}
if(newOne){
wVecs.add(wvec);
basins.add(basin);
chrs.add(tag);
}else{
basins.get(foundIdx).addAll(basin);
}
line = br.readLine();
}
br.close();
}
if(finalOutput){
new File("output").mkdir();
new File("output/" + jobID).mkdir();
PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt"));
PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt"));
for(int i = 0; i < wVecs.size(); i++){
ArrayList<Integer> basin = basins.get(i);
if(basin.size() < 2){
continue;
}
String name = "Attractor" + String.format("%05d", i);
pw2.print(name + "\t" + chrs.get(i));
pw.print(name+ "\t" + chrs.get(i));
for(int j : basin){
pw2.print("\t" + j);
}pw2.println();
float[] fs = wVecs.get(i);
for(float f : fs){
pw.print("\t" + f);
}pw.println();
}
pw2.close();
pw.close();
}else{
prepare("merge" + mergeCount);
PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount+ "/caf."+ String.format("%05d", id)+".txt"));
for(int i = 0; i < wVecs.size(); i++){
pw.print(chrs.get(i));
ArrayList<Integer> basin = basins.get(i);
int k = basin.size();
for(int j = 0; j < k; j++){
if(j == 0){
pw.print("\t" + basin.get(j));
}else{
pw.print("," + basin.get(j));
}
}
float[] fs = wVecs.get(i);
for(float f : fs){
pw.print("\t" + f);
}
pw.println();
}
pw.close();
mergeCount++;
}
}
public void mergeGeneSets(String path, int numFiles, boolean finalOutput) throws IOException{
if(!path.endsWith("/")) path = path + "/";
int start = id * numFiles/totalComputers;
int end = (id+1) * numFiles/totalComputers;
BufferedReader br;
System.out.println("Processing file " + start + " to file " + end );
for(int i = start; i < end; i++){
System.out.println(i);
br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt"));
String line = br.readLine();
// Greedily merge gene set
while(line != null){
String[] tokens = line.split("\t");
if(!tokens[2].equals("NA")){
//first token: attractees separated by ","
HashSet<Integer> attr = new HashSet<Integer>();
String[] t2 = tokens[0].split(",");
for(String s: t2){
attr.add(Integer.parseInt(s));
}
int nt = tokens.length;
ValIdx[] geneIdx = new ValIdx[nt-2];
float[] Zs = new float[nt-2];
//int[] gIdx = new int[nt-2];
//float[] wts = new float[nt-2]; // mi with metagene
int numChild = Integer.parseInt(tokens[1]);
for(int j = 2; j < nt; j++){
t2 = tokens[j].split(",");
geneIdx[j-2] = new ValIdx(Integer.parseInt(t2[0]), Float.parseFloat(t2[1]));
Zs[j-2] = t2.length > 2 ? Float.parseFloat(t2[2]) : Float.NaN;
//gIdx[j-2] = Integer.parseInt(t2[0]);
//wts[j-2] = Float.parseFloat(t2[1]);
}
//GeneSet rookie = new GeneSet(attr,gIdx, wts, numChild);
GeneSet rookie = new GeneSet(attr, geneIdx, Zs, numChild);
int origSize = allGeneSets.size();
if(origSize == 0){
allGeneSets.add(rookie);
}else{
boolean mergeable = false;
for(int j = 0; j < origSize; j++){
GeneSet gs = allGeneSets.get(j);
if(gs.equals(rookie)){
mergeable = true;
gs.merge(rookie);
break;
}
/*if(gs.merge(rookie)){
mergeable = true;
break;
// gene set merged
}*/
}
if(!mergeable){
allGeneSets.add(rookie);
}
}
}
line = br.readLine();
}
br.close();
}
if(finalOutput){
new File("output").mkdir();
new File("output/" + jobID).mkdir();
//new File("output/" + jobID + "/lists").mkdir();
PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt"));
PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt"));
//PrintWriter pw3 = new PrintWriter(new FileWriter("output/" + jobID + "/weights.txt"));
int cnt = 0;
for(GeneSet gs : allGeneSets){
//if(gs.size() >= minSize){
String name = "Attractor" + String.format("%03d", cnt);
gs.sort();
//gs.calcWeight();
/*pw3.print(name + "\t" + gs.size() + ":" + gs.getAttracteeSize() + "\t");
pw3.println(gs.getWeight());*/
pw2.print(name + "\t" + gs.size() + ":" + gs.getAttracteeSize() + "\t");
pw2.println(gs.getAttractees());
pw.print(name + "\t" + gs.size() + ":" + gs.getAttracteeSize() + "\t");
if(GeneSet.hasAnnot()){
pw.println(gs.toGenes());
}else{
pw.println(gs.toProbes());
}
/*PrintWriter pw4 = new PrintWriter(new FileWriter("output/" + jobID + "/lists/" + name + ".txt"));
if(GeneSet.hasAnnot()){
pw4.println("Probe\tGene\tWeight");
//int[] indices = gs.getGeneIdx();
for(int i = 0; i < gs.size(); i++){
pw4.println(gs.getOnePair(i));
}
}else{
pw4.println("Gene\tWeight");
for(int i = 0; i < gs.size(); i++){
pw4.println(gs.getOnePair(i));
}
}
pw4.close();*/
cnt++;
//}
}
//pw3.close();
pw2.close();
pw.close();
}else{
prepare("merge" + mergeCount);
PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount + "/caf."+ String.format("%05d", id)+".txt"));
for(GeneSet gs : allGeneSets){
pw.println(gs.toString());
}
pw.close();
mergeCount++;
}
}
public void setMinSize(int minSize){
GeneSetMerger.minSize = minSize;
}
public static void addMergeCount(){
mergeCount++;
}
}
| true | true | public void mergeWeightedGeneSets(String path, int numFiles, float precision, boolean finalOutput) throws IOException{
if(!path.endsWith("/")) path = path + "/";
int start = id * numFiles/totalComputers;
int end = (id+1) * numFiles/totalComputers;
BufferedReader br;
ArrayList<float[]> wVecs = new ArrayList<float[]>();
ArrayList<ArrayList<Integer>> basins = new ArrayList<ArrayList<Integer>>();
ArrayList<String> chrs = new ArrayList<String>();
System.out.println("Processing file " + start + " to file " + end );
for(int i = start; i < end; i++){
System.out.println(i);
br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt"));
String line = br.readLine();
// Greedily merge gene set
while(line != null){
String[] tokens = line.split("\t");
String tag = tokens[0];
int nt = tokens.length;
int m = nt-2;
float[] wvec = new float[m];
ArrayList<Integer> basin = new ArrayList<Integer>();
String[] t2 = tokens[1].split(",");
int nt2 = t2.length;
for(int j = 0; j < nt2; j++){
basin.add(Integer.parseInt(t2[j]));
}
for(int j = 0; j < m; j++){
wvec[j] = Float.parseFloat(tokens[j+2]);
}
boolean newOne = true;
int foundIdx = -1;
for(int j = 0; j < wVecs.size(); j++){
if(tag.equals(chrs.get(j))){
float[] fs = wVecs.get(j);
float err = Converger.calcMSE(fs, wvec, m);
if(err < precision/m){
foundIdx = j;
newOne = false;
break;
}
}
}
if(newOne){
wVecs.add(wvec);
basins.add(basin);
chrs.add(tag);
}else{
basins.get(foundIdx).addAll(basin);
}
line = br.readLine();
}
br.close();
}
if(finalOutput){
new File("output").mkdir();
new File("output/" + jobID).mkdir();
PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt"));
PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt"));
for(int i = 0; i < wVecs.size(); i++){
ArrayList<Integer> basin = basins.get(i);
if(basin.size() < 2){
continue;
}
String name = "Attractor" + String.format("%05d", i);
pw2.print(name + "\t" + chrs.get(i));
pw.print(name+ "\t" + chrs.get(i));
for(int j : basin){
pw2.print("\t" + j);
}pw2.println();
float[] fs = wVecs.get(i);
for(float f : fs){
pw.print("\t" + f);
}pw.println();
}
pw2.close();
pw.close();
}else{
prepare("merge" + mergeCount);
PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount+ "/caf."+ String.format("%05d", id)+".txt"));
for(int i = 0; i < wVecs.size(); i++){
pw.print(chrs.get(i));
ArrayList<Integer> basin = basins.get(i);
int k = basin.size();
for(int j = 0; j < k; j++){
if(j == 0){
pw.print("\t" + basin.get(j));
}else{
pw.print("," + basin.get(j));
}
}
float[] fs = wVecs.get(i);
for(float f : fs){
pw.print("\t" + f);
}
pw.println();
}
pw.close();
mergeCount++;
}
}
| public void mergeWeightedGeneSets(String path, int numFiles, float precision, boolean finalOutput) throws IOException{
if(!path.endsWith("/")) path = path + "/";
int start = id * numFiles/totalComputers;
int end = (id+1) * numFiles/totalComputers;
BufferedReader br;
ArrayList<float[]> wVecs = new ArrayList<float[]>();
ArrayList<ArrayList<Integer>> basins = new ArrayList<ArrayList<Integer>>();
ArrayList<String> chrs = new ArrayList<String>();
System.out.println("Processing file " + start + " to file " + end );
for(int i = start; i < end; i++){
System.out.println(i);
br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt"));
String line = br.readLine();
// Greedily merge gene set
while(line != null){
String[] tokens = line.split("\t");
String tag = tokens[0];
int nt = tokens.length;
int m = nt-2;
float[] wvec = new float[m];
ArrayList<Integer> basin = new ArrayList<Integer>();
String[] t2 = tokens[1].split(",");
int nt2 = t2.length;
if(finalOutput && nt2 < 2){
continue;
}
for(int j = 0; j < nt2; j++){
basin.add(Integer.parseInt(t2[j]));
}
for(int j = 0; j < m; j++){
wvec[j] = Float.parseFloat(tokens[j+2]);
}
boolean newOne = true;
int foundIdx = -1;
for(int j = 0; j < wVecs.size(); j++){
if(tag.equals(chrs.get(j))){
float[] fs = wVecs.get(j);
float err = Converger.calcMSE(fs, wvec, m);
if(err < precision/m){
foundIdx = j;
newOne = false;
break;
}
}
}
if(newOne){
wVecs.add(wvec);
basins.add(basin);
chrs.add(tag);
}else{
basins.get(foundIdx).addAll(basin);
}
line = br.readLine();
}
br.close();
}
if(finalOutput){
new File("output").mkdir();
new File("output/" + jobID).mkdir();
PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt"));
PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt"));
for(int i = 0; i < wVecs.size(); i++){
ArrayList<Integer> basin = basins.get(i);
if(basin.size() < 2){
continue;
}
String name = "Attractor" + String.format("%05d", i);
pw2.print(name + "\t" + chrs.get(i));
pw.print(name+ "\t" + chrs.get(i));
for(int j : basin){
pw2.print("\t" + j);
}pw2.println();
float[] fs = wVecs.get(i);
for(float f : fs){
pw.print("\t" + f);
}pw.println();
}
pw2.close();
pw.close();
}else{
prepare("merge" + mergeCount);
PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount+ "/caf."+ String.format("%05d", id)+".txt"));
for(int i = 0; i < wVecs.size(); i++){
pw.print(chrs.get(i));
ArrayList<Integer> basin = basins.get(i);
int k = basin.size();
for(int j = 0; j < k; j++){
if(j == 0){
pw.print("\t" + basin.get(j));
}else{
pw.print("," + basin.get(j));
}
}
float[] fs = wVecs.get(i);
for(float f : fs){
pw.print("\t" + f);
}
pw.println();
}
pw.close();
mergeCount++;
}
}
|
diff --git a/spf4j-core/src/main/java/org/spf4j/stackmonitor/proto/Converter.java b/spf4j-core/src/main/java/org/spf4j/stackmonitor/proto/Converter.java
index 1142a2178c..e4f4673103 100644
--- a/spf4j-core/src/main/java/org/spf4j/stackmonitor/proto/Converter.java
+++ b/spf4j-core/src/main/java/org/spf4j/stackmonitor/proto/Converter.java
@@ -1,76 +1,77 @@
/*
* Copyright (c) 2001, Zoltan Farkas All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.spf4j.stackmonitor.proto;
import org.spf4j.stackmonitor.Method;
import org.spf4j.stackmonitor.SampleNode;
import org.spf4j.stackmonitor.proto.gen.ProtoSampleNodes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author zoly
*/
public final class Converter {
private Converter() { }
public static ProtoSampleNodes.Method fromMethodToProto(final Method m) {
return ProtoSampleNodes.Method.newBuilder().setMethodName(m.getMethodName())
.setDeclaringClass(m.getDeclaringClass()).build();
}
public static ProtoSampleNodes.SampleNode fromSampleNodeToProto(final SampleNode node) {
ProtoSampleNodes.SampleNode.Builder resultBuilder
= ProtoSampleNodes.SampleNode.newBuilder().setCount(node.getSampleCount());
Map<Method, SampleNode> subNodes = node.getSubNodes();
if (subNodes != null) {
for (Map.Entry<Method, SampleNode> entry : subNodes.entrySet()) {
resultBuilder.addSubNodes(
ProtoSampleNodes.SamplePair.newBuilder().setMethod(fromMethodToProto(entry.getKey())).
setNode(fromSampleNodeToProto(entry.getValue())).build());
}
}
return resultBuilder.build();
}
public static SampleNode fromProtoToSampleNode(final ProtoSampleNodes.SampleNodeOrBuilder node) {
Map<Method, SampleNode> subNodes = null;
List<ProtoSampleNodes.SamplePair> sns = node.getSubNodesList();
if (sns != null) {
subNodes = new HashMap<Method, SampleNode>();
for (ProtoSampleNodes.SamplePair pair : sns) {
- subNodes.put(new Method(pair.getMethod().getMethodName(), pair.getMethod().getDeclaringClass()),
+ final ProtoSampleNodes.Method method = pair.getMethod();
+ subNodes.put(new Method(pair.getMethod().getDeclaringClass(), method.getMethodName()),
fromProtoToSampleNode(pair.getNode()));
}
}
return new SampleNode(node.getCount(), subNodes);
}
}
| true | true | public static SampleNode fromProtoToSampleNode(final ProtoSampleNodes.SampleNodeOrBuilder node) {
Map<Method, SampleNode> subNodes = null;
List<ProtoSampleNodes.SamplePair> sns = node.getSubNodesList();
if (sns != null) {
subNodes = new HashMap<Method, SampleNode>();
for (ProtoSampleNodes.SamplePair pair : sns) {
subNodes.put(new Method(pair.getMethod().getMethodName(), pair.getMethod().getDeclaringClass()),
fromProtoToSampleNode(pair.getNode()));
}
}
return new SampleNode(node.getCount(), subNodes);
}
| public static SampleNode fromProtoToSampleNode(final ProtoSampleNodes.SampleNodeOrBuilder node) {
Map<Method, SampleNode> subNodes = null;
List<ProtoSampleNodes.SamplePair> sns = node.getSubNodesList();
if (sns != null) {
subNodes = new HashMap<Method, SampleNode>();
for (ProtoSampleNodes.SamplePair pair : sns) {
final ProtoSampleNodes.Method method = pair.getMethod();
subNodes.put(new Method(pair.getMethod().getDeclaringClass(), method.getMethodName()),
fromProtoToSampleNode(pair.getNode()));
}
}
return new SampleNode(node.getCount(), subNodes);
}
|
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/helpers/OccurrenceCountHelper.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/helpers/OccurrenceCountHelper.java
index dec76abef..b6dafa47d 100644
--- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/helpers/OccurrenceCountHelper.java
+++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/helpers/OccurrenceCountHelper.java
@@ -1,72 +1,76 @@
package org.emftext.sdk.codegen.resource.generators.helpers;
import org.eclipse.emf.codegen.ecore.genmodel.GenFeature;
import org.emftext.sdk.concretesyntax.Cardinality;
import org.emftext.sdk.concretesyntax.CardinalityDefinition;
import org.emftext.sdk.concretesyntax.Choice;
import org.emftext.sdk.concretesyntax.QUESTIONMARK;
import org.emftext.sdk.concretesyntax.Rule;
import org.emftext.sdk.concretesyntax.STAR;
import org.emftext.sdk.concretesyntax.SyntaxElement;
import org.emftext.sdk.concretesyntax.Terminal;
/**
* A helper class to compute the mandatory occurrences of features in syntax
* rules.
*/
public class OccurrenceCountHelper {
public int getMandatoryOccurencesAfter(SyntaxElement syntaxElement, GenFeature feature) {
Rule rule = syntaxElement.getContainingRule();
int count = getMandatoryOccurencesAfter(rule, syntaxElement, feature, -1, true);
return count < 0 ? 0 : count;
}
private int getMandatoryOccurencesAfter(SyntaxElement syntaxElement, SyntaxElement startAt, GenFeature feature, int count, boolean mandatory) {
+ System.out.println("getMandatoryOccurencesAfter(" + syntaxElement + ") count = " + count);
boolean isMandatory = mandatory && isMandatory(syntaxElement);
if (syntaxElement instanceof Terminal) {
Terminal terminal = (Terminal) syntaxElement;
if (terminal.getFeature() == feature) {
if (count >= 0 && isMandatory) {
+ System.out.println("count++");
count++;
}
}
}
// check children
for (SyntaxElement child : syntaxElement.getChildren()) {
int childCount = getMandatoryOccurencesAfter(child, startAt, feature, count, isMandatory);
if (childCount < 0) {
// feature was not found yet
} else {
if (childCount == 0) {
count = 0;
} else {
if (count < 0) {
count = 0;
}
if (isMandatory) {
+ System.out.println("adding child count (" + childCount + ") to count (" + count + ")");
count += childCount;
}
}
}
if (syntaxElement instanceof Choice) {
break;
}
}
if (startAt == syntaxElement) {
count = 0;
}
+ System.out.println("}");
return count;
}
private boolean isMandatory(SyntaxElement element) {
if (element instanceof CardinalityDefinition) {
CardinalityDefinition cd = (CardinalityDefinition) element;
Cardinality cardinality = cd.getCardinality();
if (cardinality instanceof STAR || cardinality instanceof QUESTIONMARK) {
return false;
}
}
return true;
}
}
| false | true | private int getMandatoryOccurencesAfter(SyntaxElement syntaxElement, SyntaxElement startAt, GenFeature feature, int count, boolean mandatory) {
boolean isMandatory = mandatory && isMandatory(syntaxElement);
if (syntaxElement instanceof Terminal) {
Terminal terminal = (Terminal) syntaxElement;
if (terminal.getFeature() == feature) {
if (count >= 0 && isMandatory) {
count++;
}
}
}
// check children
for (SyntaxElement child : syntaxElement.getChildren()) {
int childCount = getMandatoryOccurencesAfter(child, startAt, feature, count, isMandatory);
if (childCount < 0) {
// feature was not found yet
} else {
if (childCount == 0) {
count = 0;
} else {
if (count < 0) {
count = 0;
}
if (isMandatory) {
count += childCount;
}
}
}
if (syntaxElement instanceof Choice) {
break;
}
}
if (startAt == syntaxElement) {
count = 0;
}
return count;
}
| private int getMandatoryOccurencesAfter(SyntaxElement syntaxElement, SyntaxElement startAt, GenFeature feature, int count, boolean mandatory) {
System.out.println("getMandatoryOccurencesAfter(" + syntaxElement + ") count = " + count);
boolean isMandatory = mandatory && isMandatory(syntaxElement);
if (syntaxElement instanceof Terminal) {
Terminal terminal = (Terminal) syntaxElement;
if (terminal.getFeature() == feature) {
if (count >= 0 && isMandatory) {
System.out.println("count++");
count++;
}
}
}
// check children
for (SyntaxElement child : syntaxElement.getChildren()) {
int childCount = getMandatoryOccurencesAfter(child, startAt, feature, count, isMandatory);
if (childCount < 0) {
// feature was not found yet
} else {
if (childCount == 0) {
count = 0;
} else {
if (count < 0) {
count = 0;
}
if (isMandatory) {
System.out.println("adding child count (" + childCount + ") to count (" + count + ")");
count += childCount;
}
}
}
if (syntaxElement instanceof Choice) {
break;
}
}
if (startAt == syntaxElement) {
count = 0;
}
System.out.println("}");
return count;
}
|
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java
index 1f024c69..cbb24a37 100644
--- a/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java
+++ b/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java
@@ -1,778 +1,783 @@
/*
* Copyright (C) 2009 Jayway AB
* Copyright (C) 2007-2008 JVending Masa
*
* 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.jayway.maven.plugins.android.phase01generatesources;
import com.jayway.maven.plugins.android.AbstractAndroidMojo;
import com.jayway.maven.plugins.android.CommandExecutor;
import com.jayway.maven.plugins.android.ExecutionException;
import com.jayway.maven.plugins.android.common.AetherHelper;
import com.jayway.maven.plugins.android.manifmerger.ManifestMerger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.zip.ZipUnArchiver;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.AbstractScanner;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APK;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APKSOURCES;
/**
* Generates <code>R.java</code> based on resources specified by the <code>resources</code> configuration parameter.
* Generates java files based on aidl files.
*
* @author [email protected]
* @author Manfred Moser <[email protected]>
*
* @goal generate-sources
* @phase generate-sources
* @requiresProject true
* @requiresDependencyResolution compile
*/
public class GenerateSourcesMojo extends AbstractAndroidMojo
{
/**
* <p>
* Override default merging. You must have SDK Tools r20+
* </p>
*
* <p>
* <b>IMPORTANT:</b> The resource plugin needs to be disabled for the
* <code>process-resources</code> phase, so the "default-resources"
* execution must be added. Without this the non-merged manifest will get
* re-copied to the build directory.
* </p>
*
* <p>
* The <code>androidManifestFile</code> should also be configured to pull
* from the build directory so that later phases will pull the merged
* manifest file.
* </p>
* <p>
* Example POM Setup:
* </p>
*
* <pre>
* <build>
* ...
* <plugins>
* ...
* <plugin>
* <artifactId>maven-resources-plugin</artifactId>
* <version>2.6</version>
* <executions>
* <execution>
* <phase>initialize</phase>
* <goals>
* <goal>resources</goal>
* </goals>
* </execution>
* <b><execution>
* <id>default-resources</id>
* <phase>DISABLED</phase>
* </execution></b>
* </executions>
* </plugin>
* <plugin>
* <groupId>com.jayway.maven.plugins.android.generation2</groupId>
* <artifactId>android-maven-plugin</artifactId>
* <configuration>
* <b><androidManifestFile>
* ${project.build.directory}/AndroidManifest.xml
* </androidManifestFile>
* <mergeManifests>true</mergeManifests></b>
* </configuration>
* <extensions>true</extensions>
* </plugin>
* ...
* </plugins>
* ...
* </build>
* </pre>
* <p>
* You can filter the pre-merged APK manifest. One important note about Eclipse, Eclipse will
* replace the merged manifest with a filtered pre-merged version when the project is refreshed.
* If you want to review the filtered merged version then you will need to open it outside Eclipse
* without refreshing the project in Eclipse.
* </p>
* <pre>
* <resources>
* <resource>
* <targetPath>${project.build.directory}</targetPath>
* <filtering>true</filtering>
* <directory>${basedir}</directory>
* <includes>
* <include>AndroidManifest.xml</include>
* </includes>
* </resource>
* </resources>
* </pre>
*
* @parameter expression="${android.mergeManifests}" default-value="false"
*/
protected boolean mergeManifests;
/**
* Override default generated folder containing R.java
*
* @parameter expression="${android.genDirectory}" default-value="${project.build.directory}/generated-sources/r"
*/
protected File genDirectory;
/**
* Override default generated folder containing aidl classes
*
* @parameter expression="${android.genDirectoryAidl}"
* default-value="${project.build.directory}/generated-sources/aidl"
*/
protected File genDirectoryAidl;
public void execute() throws MojoExecutionException, MojoFailureException
{
// If the current POM isn't an Android-related POM, then don't do
// anything. This helps work with multi-module projects.
if ( ! isCurrentProjectAndroid() )
{
return;
}
try
{
extractSourceDependencies();
extractApkLibDependencies();
final String[] relativeAidlFileNames1 = findRelativeAidlFileNames( sourceDirectory );
final String[] relativeAidlFileNames2 = findRelativeAidlFileNames( extractedDependenciesJavaSources );
final Map<String, String[]> relativeApklibAidlFileNames = new HashMap<String, String[]>();
String[] apklibAidlFiles;
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
apklibAidlFiles = findRelativeAidlFileNames(
new File( getLibraryUnpackDirectory( artifact ) + "/src" ) );
relativeApklibAidlFileNames.put( artifact.getArtifactId(), apklibAidlFiles );
}
}
mergeManifests();
generateR();
generateApklibR();
generateBuildConfig();
// When compiling AIDL for this project,
// make sure we compile AIDL for dependencies as well.
// This is so project A, which depends on project B, can
// use AIDL info from project B in its own AIDL
Map<File, String[]> files = new HashMap<File, String[]>();
files.put( sourceDirectory, relativeAidlFileNames1 );
files.put( extractedDependenciesJavaSources, relativeAidlFileNames2 );
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
files.put( new File( getLibraryUnpackDirectory( artifact ) + "/src" ),
relativeApklibAidlFileNames.get( artifact.getArtifactId() ) );
}
}
generateAidlFiles( files );
}
catch ( MojoExecutionException e )
{
getLog().error( "Error when generating sources.", e );
throw e;
}
}
protected void extractSourceDependencies() throws MojoExecutionException
{
for ( Artifact artifact : getRelevantDependencyArtifacts() )
{
String type = artifact.getType();
if ( type.equals( APKSOURCES ) )
{
getLog().debug( "Detected apksources dependency " + artifact + " with file " + artifact.getFile()
+ ". Will resolve and extract..." );
Artifact resolvedArtifact = AetherHelper
.resolveArtifact( artifact, repoSystem, repoSession, projectRepos );
File apksourcesFile = resolvedArtifact.getFile();
// When the artifact is not installed in local repository, but rather part of the current reactor,
// resolve from within the reactor. (i.e. ../someothermodule/target/*)
if ( ! apksourcesFile.exists() )
{
apksourcesFile = resolveArtifactToFile( artifact );
}
// When using maven under eclipse the artifact will by default point to a directory, which isn't
// correct. To work around this we'll first try to get the archive from the local repo, and only if it
// isn't found there we'll do a normal resolve.
if ( apksourcesFile.isDirectory() )
{
apksourcesFile = resolveArtifactToFile( artifact );
}
getLog().debug( "Extracting " + apksourcesFile + "..." );
extractApksources( apksourcesFile );
}
}
projectHelper.addResource( project, extractedDependenciesJavaResources.getAbsolutePath(), null, null );
project.addCompileSourceRoot( extractedDependenciesJavaSources.getAbsolutePath() );
}
private void extractApksources( File apksourcesFile ) throws MojoExecutionException
{
if ( apksourcesFile.isDirectory() )
{
getLog().warn( "The apksources artifact points to '" + apksourcesFile
+ "' which is a directory; skipping unpacking it." );
return;
}
final UnArchiver unArchiver = new ZipUnArchiver( apksourcesFile )
{
@Override
protected Logger getLogger()
{
return new ConsoleLogger( Logger.LEVEL_DEBUG, "dependencies-unarchiver" );
}
};
extractedDependenciesDirectory.mkdirs();
unArchiver.setDestDirectory( extractedDependenciesDirectory );
try
{
unArchiver.extract();
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "ArchiverException while extracting " + apksourcesFile.getAbsolutePath()
+ ". Message: " + e.getLocalizedMessage(), e );
}
}
private void extractApkLibDependencies() throws MojoExecutionException
{
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
String type = artifact.getType();
if ( type.equals( APKLIB ) )
{
getLog().debug( "Extracting apklib " + artifact.getArtifactId() + "..." );
extractApklib( artifact );
}
}
}
private void extractApklib( Artifact apklibArtifact ) throws MojoExecutionException
{
final Artifact resolvedArtifact = AetherHelper
.resolveArtifact( apklibArtifact, repoSystem, repoSession, projectRepos );
File apkLibFile = resolvedArtifact.getFile();
// When the artifact is not installed in local repository, but rather part of the current reactor,
// resolve from within the reactor. (i.e. ../someothermodule/target/*)
if ( ! apkLibFile.exists() )
{
apkLibFile = resolveArtifactToFile( apklibArtifact );
}
//When using maven under eclipse the artifact will by default point to a directory, which isn't correct.
//To work around this we'll first try to get the archive from the local repo, and only if it isn't found there
// we'll do a normal resolve.
if ( apkLibFile.isDirectory() )
{
apkLibFile = resolveArtifactToFile( apklibArtifact );
}
if ( apkLibFile.isDirectory() )
{
getLog().warn(
"The apklib artifact points to '" + apkLibFile + "' which is a directory; skipping unpacking it." );
return;
}
final UnArchiver unArchiver = new ZipUnArchiver( apkLibFile )
{
@Override
protected Logger getLogger()
{
return new ConsoleLogger( Logger.LEVEL_DEBUG, "dependencies-unarchiver" );
}
};
File apklibDirectory = new File( getLibraryUnpackDirectory( apklibArtifact ) );
apklibDirectory.mkdirs();
unArchiver.setDestDirectory( apklibDirectory );
try
{
unArchiver.extract();
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "ArchiverException while extracting " + apklibDirectory.getAbsolutePath()
+ ". Message: " + e.getLocalizedMessage(), e );
}
projectHelper.addResource( project, apklibDirectory.getAbsolutePath() + "/src", null,
Arrays.asList( "**/*.java", "**/*.aidl" ) );
project.addCompileSourceRoot( apklibDirectory.getAbsolutePath() + "/src" );
}
private void generateR() throws MojoExecutionException
{
getLog().debug( "Generating R file for " + project.getPackaging() );
genDirectory.mkdirs();
File[] overlayDirectories = getResourceOverlayDirectories();
if ( extractedDependenciesRes.exists() )
{
try
{
getLog().info( "Copying dependency resource files to combined resource directory." );
if ( ! combinedRes.exists() )
{
if ( ! combinedRes.mkdirs() )
{
throw new MojoExecutionException(
"Could not create directory for combined resources at " + combinedRes
.getAbsolutePath() );
}
}
org.apache.commons.io.FileUtils.copyDirectory( extractedDependenciesRes, combinedRes );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
if ( resourceDirectory.exists() && combinedRes.exists() )
{
try
{
getLog().info( "Copying local resource files to combined resource directory." );
org.apache.commons.io.FileUtils.copyDirectory( resourceDirectory, combinedRes, new FileFilter()
{
/**
* Excludes files matching one of the common file to exclude.
* The default excludes pattern are the ones from
* {org.codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES}
* @see java.io.FileFilter#accept(java.io.File)
*/
public boolean accept( File file )
{
for ( String pattern : AbstractScanner.DEFAULTEXCLUDES )
{
if ( AbstractScanner.match( pattern, file.getAbsolutePath() ) )
{
getLog().debug(
"Excluding " + file.getName() + " from resource copy : matching " + pattern );
return false;
}
}
return true;
}
} );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
commands.add( "package" );
commands.add( "-m" );
commands.add( "-J" );
commands.add( genDirectory.getAbsolutePath() );
commands.add( "-M" );
commands.add( androidManifestFile.getAbsolutePath() );
if ( StringUtils.isNotBlank( customPackage ) )
{
commands.add( "--custom-package" );
commands.add( customPackage );
}
addResourcesDirectories( commands, overlayDirectories );
commands.add( "--auto-add-overlay" );
if ( assetsDirectory.exists() )
{
commands.add( "-A" );
commands.add( assetsDirectory.getAbsolutePath() );
}
if ( extractedDependenciesAssets.exists() )
{
commands.add( "-A" );
commands.add( extractedDependenciesAssets.getAbsolutePath() );
}
commands.add( "-I" );
commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() );
if ( StringUtils.isNotBlank( configurations ) )
{
commands.add( "-c" );
commands.add( configurations );
}
if ( proguardFile != null )
{
+ File parentFolder = proguardFile.getParentFile();
+ if ( parentFolder != null )
+ {
+ parentFolder.mkdirs();
+ }
commands.add( "-G" );
commands.add( proguardFile.getAbsolutePath() );
}
getLog().info( getAndroidSdk().getPathForTool( "aapt" ) + " " + commands.toString() );
try
{
executor.executeCommand( getAndroidSdk().getPathForTool( "aapt" ), commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
private void addResourcesDirectories( List<String> commands, File[] overlayDirectories )
{
for ( File resOverlayDir : overlayDirectories )
{
if ( resOverlayDir != null && resOverlayDir.exists() )
{
commands.add( "-S" );
commands.add( resOverlayDir.getAbsolutePath() );
}
}
if ( combinedRes.exists() )
{
commands.add( "-S" );
commands.add( combinedRes.getAbsolutePath() );
}
else
{
if ( resourceDirectory.exists() )
{
commands.add( "-S" );
commands.add( resourceDirectory.getAbsolutePath() );
}
}
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
String apklibResDirectory = getLibraryUnpackDirectory( artifact ) + "/res";
if ( new File( apklibResDirectory ).exists() )
{
commands.add( "-S" );
commands.add( apklibResDirectory );
}
}
}
}
private void mergeManifests() throws MojoExecutionException
{
getLog().debug( "mergeManifests: " + mergeManifests );
if ( !mergeManifests )
{
getLog().info( "Manifest merging disabled. Using project manifest only" );
return;
}
getLog().info( "Getting manifests of dependent apklibs" );
List<File> libManifests = new ArrayList<File>();
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
File apklibManifeset = new File( getLibraryUnpackDirectory( artifact ), "AndroidManifest.xml" );
if ( !apklibManifeset.exists() )
{
throw new MojoExecutionException( artifact.getArtifactId() + " is missing AndroidManifest.xml" );
}
libManifests.add( apklibManifeset );
}
}
if ( !libManifests.isEmpty() )
{
File mergedManifest = new File( androidManifestFile.getParent(), "AndroidManifest-merged.xml" );
ManifestMerger mm = new ManifestMerger( getLog(), getAndroidSdk().getSdkPath(), getAndroidSdk()
.getSdkMajorVersion() );
getLog().info( "Merging manifests of dependent apklibs" );
if ( mm.process( mergedManifest, androidManifestFile,
libManifests.toArray( new File[libManifests.size()] ) ) )
{
// Replace the original manifest file with the merged one so that
// the rest of the build will pick it up.
androidManifestFile.delete();
mergedManifest.renameTo( androidManifestFile );
getLog().info( "Done Merging Manifests of APKLIBs" );
}
else
{
getLog().error( "Manifests were not merged!" );
throw new MojoExecutionException( "Manifests were not merged!" );
}
}
else
{
getLog().info( "No APKLIB manifests found. Using project manifest only." );
}
}
private void generateApklibR() throws MojoExecutionException
{
getLog().debug( "Generating R file for projects dependent on apklibs" );
genDirectory.mkdirs();
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
generateRForApkLibDependency( artifact );
}
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
private void generateRForApkLibDependency( Artifact apklibArtifact ) throws MojoExecutionException
{
final String unpackDir = getLibraryUnpackDirectory( apklibArtifact );
getLog().debug( "Generating R file for apklibrary: " + apklibArtifact.getGroupId() );
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
commands.add( "package" );
commands.add( "-m" );
commands.add( "-J" );
commands.add( genDirectory.getAbsolutePath() );
commands.add( "--custom-package" );
commands.add( extractPackageNameFromAndroidManifest( new File( unpackDir + "/" + "AndroidManifest.xml" ) ) );
commands.add( "-M" );
commands.add( androidManifestFile.getAbsolutePath() );
if ( resourceDirectory.exists() )
{
commands.add( "-S" );
commands.add( resourceDirectory.getAbsolutePath() );
}
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
final String apkLibResDir = getLibraryUnpackDirectory( artifact ) + "/res";
if ( new File( apkLibResDir ).exists() )
{
commands.add( "-S" );
commands.add( apkLibResDir );
}
}
}
commands.add( "--auto-add-overlay" );
if ( assetsDirectory.exists() )
{
commands.add( "-A" );
commands.add( assetsDirectory.getAbsolutePath() );
}
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
final String apkLibAssetsDir = getLibraryUnpackDirectory( artifact ) + "/assets";
if ( new File( apkLibAssetsDir ).exists() )
{
commands.add( "-A" );
commands.add( apkLibAssetsDir );
}
}
}
commands.add( "-I" );
commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() );
if ( StringUtils.isNotBlank( configurations ) )
{
commands.add( "-c" );
commands.add( configurations );
}
getLog().info( getAndroidSdk().getPathForTool( "aapt" ) + " " + commands.toString() );
try
{
executor.executeCommand( getAndroidSdk().getPathForTool( "aapt" ), commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
}
private void generateBuildConfig() throws MojoExecutionException
{
getLog().debug( "Generating BuildConfig file" );
// Create the BuildConfig for our package.
String packageName = extractPackageNameFromAndroidManifest( androidManifestFile );
if ( StringUtils.isNotBlank( customPackage ) )
{
packageName = customPackage;
}
generateBuildConfigForPackage( packageName, !release );
// Generate the BuildConfig for any apklib dependencies.
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( "apklib" ) )
{
File apklibManifeset = new File( getLibraryUnpackDirectory( artifact ), "AndroidManifest.xml" );
String apklibPackageName = extractPackageNameFromAndroidManifest( apklibManifeset );
generateBuildConfigForPackage( apklibPackageName, !release );
}
}
}
private void generateBuildConfigForPackage( String packageName, boolean debug ) throws MojoExecutionException
{
File outputFolder = new File( genDirectory, packageName.replace( ".", File.separator ) );
outputFolder.mkdirs();
String buildConfig = ""
+ "package " + packageName + ";\n\n"
+ "public final class BuildConfig {\n"
+ " public static final boolean DEBUG = " + Boolean.toString( debug ) + ";\n"
+ "}\n"
;
File outputFile = new File( outputFolder, "BuildConfig.java" );
try
{
FileUtils.writeStringToFile( outputFile, buildConfig );
}
catch ( IOException e )
{
getLog().error( "Error generating BuildConfig ", e );
throw new MojoExecutionException( "Error generating BuildConfig", e );
}
}
/**
* Given a map of source directories to list of AIDL (relative) filenames within each,
* runs the AIDL compiler for each, such that all source directories are available to
* the AIDL compiler.
*
* @param files Map of source directory File instances to the relative paths to all AIDL files within
* @throws MojoExecutionException If the AIDL compiler fails
*/
private void generateAidlFiles( Map<File /*sourceDirectory*/, String[] /*relativeAidlFileNames*/> files )
throws MojoExecutionException
{
List<String> protoCommands = new ArrayList<String>();
protoCommands.add( "-p" + getAndroidSdk().getPathForFrameworkAidl() );
genDirectoryAidl.mkdirs();
project.addCompileSourceRoot( genDirectoryAidl.getPath() );
Set<File> sourceDirs = files.keySet();
for ( File sourceDir : sourceDirs )
{
protoCommands.add( "-I" + sourceDir );
}
for ( File sourceDir : sourceDirs )
{
for ( String relativeAidlFileName : files.get( sourceDir ) )
{
File targetDirectory = new File( genDirectoryAidl, new File( relativeAidlFileName ).getParent() );
targetDirectory.mkdirs();
final String shortAidlFileName = new File( relativeAidlFileName ).getName();
final String shortJavaFileName = shortAidlFileName.substring( 0, shortAidlFileName.lastIndexOf( "." ) )
+ ".java";
final File aidlFileInSourceDirectory = new File( sourceDir, relativeAidlFileName );
List<String> commands = new ArrayList<String>( protoCommands );
commands.add( aidlFileInSourceDirectory.getAbsolutePath() );
commands.add( new File( targetDirectory, shortJavaFileName ).getAbsolutePath() );
try
{
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
executor.executeCommand( getAndroidSdk().getPathForTool( "aidl" ), commands, project.getBasedir(),
false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
}
}
}
private String[] findRelativeAidlFileNames( File sourceDirectory )
{
String[] relativeAidlFileNames = findFilesInDirectory( sourceDirectory, "**/*.aidl" );
getLog().info( "ANDROID-904-002: Found aidl files: Count = " + relativeAidlFileNames.length );
return relativeAidlFileNames;
}
/**
* @return true if the pom type is APK, APKLIB, or APKSOURCES
*/
private boolean isCurrentProjectAndroid()
{
Set<String> androidArtifacts = new HashSet<String>()
{
{
addAll( Arrays.asList( APK, APKLIB, APKSOURCES ) );
}
};
return androidArtifacts.contains( project.getArtifact().getType() );
}
}
| true | true | private void generateR() throws MojoExecutionException
{
getLog().debug( "Generating R file for " + project.getPackaging() );
genDirectory.mkdirs();
File[] overlayDirectories = getResourceOverlayDirectories();
if ( extractedDependenciesRes.exists() )
{
try
{
getLog().info( "Copying dependency resource files to combined resource directory." );
if ( ! combinedRes.exists() )
{
if ( ! combinedRes.mkdirs() )
{
throw new MojoExecutionException(
"Could not create directory for combined resources at " + combinedRes
.getAbsolutePath() );
}
}
org.apache.commons.io.FileUtils.copyDirectory( extractedDependenciesRes, combinedRes );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
if ( resourceDirectory.exists() && combinedRes.exists() )
{
try
{
getLog().info( "Copying local resource files to combined resource directory." );
org.apache.commons.io.FileUtils.copyDirectory( resourceDirectory, combinedRes, new FileFilter()
{
/**
* Excludes files matching one of the common file to exclude.
* The default excludes pattern are the ones from
* {org.codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES}
* @see java.io.FileFilter#accept(java.io.File)
*/
public boolean accept( File file )
{
for ( String pattern : AbstractScanner.DEFAULTEXCLUDES )
{
if ( AbstractScanner.match( pattern, file.getAbsolutePath() ) )
{
getLog().debug(
"Excluding " + file.getName() + " from resource copy : matching " + pattern );
return false;
}
}
return true;
}
} );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
commands.add( "package" );
commands.add( "-m" );
commands.add( "-J" );
commands.add( genDirectory.getAbsolutePath() );
commands.add( "-M" );
commands.add( androidManifestFile.getAbsolutePath() );
if ( StringUtils.isNotBlank( customPackage ) )
{
commands.add( "--custom-package" );
commands.add( customPackage );
}
addResourcesDirectories( commands, overlayDirectories );
commands.add( "--auto-add-overlay" );
if ( assetsDirectory.exists() )
{
commands.add( "-A" );
commands.add( assetsDirectory.getAbsolutePath() );
}
if ( extractedDependenciesAssets.exists() )
{
commands.add( "-A" );
commands.add( extractedDependenciesAssets.getAbsolutePath() );
}
commands.add( "-I" );
commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() );
if ( StringUtils.isNotBlank( configurations ) )
{
commands.add( "-c" );
commands.add( configurations );
}
if ( proguardFile != null )
{
commands.add( "-G" );
commands.add( proguardFile.getAbsolutePath() );
}
getLog().info( getAndroidSdk().getPathForTool( "aapt" ) + " " + commands.toString() );
try
{
executor.executeCommand( getAndroidSdk().getPathForTool( "aapt" ), commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
| private void generateR() throws MojoExecutionException
{
getLog().debug( "Generating R file for " + project.getPackaging() );
genDirectory.mkdirs();
File[] overlayDirectories = getResourceOverlayDirectories();
if ( extractedDependenciesRes.exists() )
{
try
{
getLog().info( "Copying dependency resource files to combined resource directory." );
if ( ! combinedRes.exists() )
{
if ( ! combinedRes.mkdirs() )
{
throw new MojoExecutionException(
"Could not create directory for combined resources at " + combinedRes
.getAbsolutePath() );
}
}
org.apache.commons.io.FileUtils.copyDirectory( extractedDependenciesRes, combinedRes );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
if ( resourceDirectory.exists() && combinedRes.exists() )
{
try
{
getLog().info( "Copying local resource files to combined resource directory." );
org.apache.commons.io.FileUtils.copyDirectory( resourceDirectory, combinedRes, new FileFilter()
{
/**
* Excludes files matching one of the common file to exclude.
* The default excludes pattern are the ones from
* {org.codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES}
* @see java.io.FileFilter#accept(java.io.File)
*/
public boolean accept( File file )
{
for ( String pattern : AbstractScanner.DEFAULTEXCLUDES )
{
if ( AbstractScanner.match( pattern, file.getAbsolutePath() ) )
{
getLog().debug(
"Excluding " + file.getName() + " from resource copy : matching " + pattern );
return false;
}
}
return true;
}
} );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
commands.add( "package" );
commands.add( "-m" );
commands.add( "-J" );
commands.add( genDirectory.getAbsolutePath() );
commands.add( "-M" );
commands.add( androidManifestFile.getAbsolutePath() );
if ( StringUtils.isNotBlank( customPackage ) )
{
commands.add( "--custom-package" );
commands.add( customPackage );
}
addResourcesDirectories( commands, overlayDirectories );
commands.add( "--auto-add-overlay" );
if ( assetsDirectory.exists() )
{
commands.add( "-A" );
commands.add( assetsDirectory.getAbsolutePath() );
}
if ( extractedDependenciesAssets.exists() )
{
commands.add( "-A" );
commands.add( extractedDependenciesAssets.getAbsolutePath() );
}
commands.add( "-I" );
commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() );
if ( StringUtils.isNotBlank( configurations ) )
{
commands.add( "-c" );
commands.add( configurations );
}
if ( proguardFile != null )
{
File parentFolder = proguardFile.getParentFile();
if ( parentFolder != null )
{
parentFolder.mkdirs();
}
commands.add( "-G" );
commands.add( proguardFile.getAbsolutePath() );
}
getLog().info( getAndroidSdk().getPathForTool( "aapt" ) + " " + commands.toString() );
try
{
executor.executeCommand( getAndroidSdk().getPathForTool( "aapt" ), commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
|
diff --git a/src/org/ita/neutrino/astparser/SourceFileParser.java b/src/org/ita/neutrino/astparser/SourceFileParser.java
index 7b9f55c..3182728 100644
--- a/src/org/ita/neutrino/astparser/SourceFileParser.java
+++ b/src/org/ita/neutrino/astparser/SourceFileParser.java
@@ -1,184 +1,184 @@
package org.ita.neutrino.astparser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
import org.eclipse.jdt.core.dom.EnumDeclaration;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.ita.neutrino.codeparser.Type;
class SourceFileParser {
/**
* Localiza as declarações de import e as salva.
*
* @author Rafael Monico
*
*/
private static class ImportVisitor extends ASTVisitor {
private ASTSourceFile sourceFile;
public void setSourceFile(ASTSourceFile sourceFile) {
this.sourceFile = sourceFile;
}
@Override
public boolean visit(ImportDeclaration node) {
ASTImportDeclaration _import = sourceFile.createImportDeclaration();
ASTEnvironment environment = sourceFile.getParent().getParent();
// Nesse caso, node.getName() já devolve o nome qualificado do tipo
// importado
ITypeBinding typeBinding;
- if (node.isStatic()) {
+ if (node.resolveBinding() instanceof IMethodBinding) {
IMethodBinding methodBinding = (IMethodBinding) node.resolveBinding();
typeBinding = methodBinding.getDeclaringClass();
} else {
typeBinding = (ITypeBinding) node.resolveBinding();
}
Type type;
if (typeBinding.isClass()) {
type = environment.getTypeCache().getOrCreateClass(node.getName().getFullyQualifiedName());
} else if (typeBinding.isAnnotation()) {
type = environment.getTypeCache().getOrCreateAnnotation(node.getName().getFullyQualifiedName());
} else {
type = environment.getTypeCache().get(node.getName());
}
_import.setType(type);
_import.setASTObject(node);
ASTSelection selection = environment.getSelection();
if (selection.isOverNode(node)) {
selection.setSelectedElement(_import);
}
// Nunca visita os nós filhos, isso será feito posteriormente
return false;
}
}
/**
* Localiza as declarações de tipo e as lança na lista.
*
* @author Rafael Monico
*
*/
private static class TypeVisitor extends ASTVisitor {
private ASTSourceFile sourceFile;
public void setSourceFile(ASTSourceFile sourceFile) {
this.sourceFile = sourceFile;
}
@Override
public boolean visit(TypeDeclaration node) {
ASTType type = null;
// Nesse caso, só pode ser classe
if (!node.isInterface()) {
type = classFound(node);
} else {
// É interface
type = interfaceFound(node);
}
// Se encontrou alguma coisa, verifica se está dentro da seleção
if (type != null) {
ASTSelection selection = sourceFile.getParent().getParent().getSelection();
if (selection.isOverNode(node.getName())) {
selection.setSelectedElement(type);
}
}
return false;
}
private ASTClass classFound(TypeDeclaration node) {
ASTClass clazz = sourceFile.createClass(node.getName().getIdentifier());
clazz.setASTObject(node);
return clazz;
}
private ASTInterface interfaceFound(TypeDeclaration node) {
ASTInterface _interface = sourceFile.createInterface(node.getName().getIdentifier());
_interface.setASTObject(node);
return _interface;
}
@Override
public boolean visit(AnnotationTypeDeclaration node) {
annotationFound(node);
return false;
}
private void annotationFound(AnnotationTypeDeclaration node) {
// TODO Auto-generated method stub
}
@Override
public boolean visit(EnumDeclaration node) {
enumFound(node);
return false;
}
private void enumFound(EnumDeclaration node) {
// TODO Auto-generated method stub
}
}
private ASTSourceFile sourceFile;
public void setSourceFile(ASTSourceFile sourceFile) {
this.sourceFile = sourceFile;
}
/**
* Faz o parsing do source file, baseado na compilation unit passada como
* parâmetro anteriormente.
*/
public void parse() {
populateImportList();
populateTypeList();
}
private void populateImportList() {
ImportVisitor visitor = new ImportVisitor();
visitor.setSourceFile(sourceFile);
sourceFile.getASTObject().getCompilationUnit().accept(visitor);
}
private void populateTypeList() {
TypeVisitor visitor = new TypeVisitor();
visitor.setSourceFile(sourceFile);
sourceFile.getASTObject().getCompilationUnit().accept(visitor);
}
}
| true | true | public boolean visit(ImportDeclaration node) {
ASTImportDeclaration _import = sourceFile.createImportDeclaration();
ASTEnvironment environment = sourceFile.getParent().getParent();
// Nesse caso, node.getName() já devolve o nome qualificado do tipo
// importado
ITypeBinding typeBinding;
if (node.isStatic()) {
IMethodBinding methodBinding = (IMethodBinding) node.resolveBinding();
typeBinding = methodBinding.getDeclaringClass();
} else {
typeBinding = (ITypeBinding) node.resolveBinding();
}
Type type;
if (typeBinding.isClass()) {
type = environment.getTypeCache().getOrCreateClass(node.getName().getFullyQualifiedName());
} else if (typeBinding.isAnnotation()) {
type = environment.getTypeCache().getOrCreateAnnotation(node.getName().getFullyQualifiedName());
} else {
type = environment.getTypeCache().get(node.getName());
}
_import.setType(type);
_import.setASTObject(node);
ASTSelection selection = environment.getSelection();
if (selection.isOverNode(node)) {
selection.setSelectedElement(_import);
}
// Nunca visita os nós filhos, isso será feito posteriormente
return false;
}
| public boolean visit(ImportDeclaration node) {
ASTImportDeclaration _import = sourceFile.createImportDeclaration();
ASTEnvironment environment = sourceFile.getParent().getParent();
// Nesse caso, node.getName() já devolve o nome qualificado do tipo
// importado
ITypeBinding typeBinding;
if (node.resolveBinding() instanceof IMethodBinding) {
IMethodBinding methodBinding = (IMethodBinding) node.resolveBinding();
typeBinding = methodBinding.getDeclaringClass();
} else {
typeBinding = (ITypeBinding) node.resolveBinding();
}
Type type;
if (typeBinding.isClass()) {
type = environment.getTypeCache().getOrCreateClass(node.getName().getFullyQualifiedName());
} else if (typeBinding.isAnnotation()) {
type = environment.getTypeCache().getOrCreateAnnotation(node.getName().getFullyQualifiedName());
} else {
type = environment.getTypeCache().get(node.getName());
}
_import.setType(type);
_import.setASTObject(node);
ASTSelection selection = environment.getSelection();
if (selection.isOverNode(node)) {
selection.setSelectedElement(_import);
}
// Nunca visita os nós filhos, isso será feito posteriormente
return false;
}
|
diff --git a/ons.solubility.rdf/src/ons/solubility/rdf/ConvertToRDF.java b/ons.solubility.rdf/src/ons/solubility/rdf/ConvertToRDF.java
index 1016815..e887c15 100644
--- a/ons.solubility.rdf/src/ons/solubility/rdf/ConvertToRDF.java
+++ b/ons.solubility.rdf/src/ons/solubility/rdf/ConvertToRDF.java
@@ -1,180 +1,181 @@
/* Copyright (C) 2008 Egon Willighagen <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package ons.solubility.rdf;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import net.sf.jniinchi.INCHI_RET;
import ons.solubility.data.Measurement;
import ons.solubility.data.SolubilityData;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.exception.InvalidSmilesException;
import org.openscience.cdk.inchi.InChIGenerator;
import org.openscience.cdk.inchi.InChIGeneratorFactory;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.nonotify.NoNotificationChemObjectBuilder;
import org.openscience.cdk.smiles.SmilesParser;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.DC_11;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
public class ConvertToRDF {
private SmilesParser smilesParser;
private InChIGeneratorFactory inchiFactory;
private Model model;
private int measurementsProcessed;
private int solutesProcessed;
private int solventsProcessed;
private Map<String,Resource> solvents;
private Map<String,Resource> solutes;
public ConvertToRDF() throws Exception {
model = ModelFactory.createDefaultModel();
measurementsProcessed = 0;
solvents = new HashMap<String,Resource>();
solutes = new HashMap<String,Resource>();
solutesProcessed = 0;
solventsProcessed = 0;
smilesParser = new SmilesParser(NoNotificationChemObjectBuilder.getInstance());
inchiFactory = new InChIGeneratorFactory();
}
public void processData() throws Exception {
Properties userInfo = new Properties();
InputStream input = this.getClass().getClassLoader().getResourceAsStream("userinfo.properties");
userInfo.load(input);
String username = userInfo.getProperty("username");
String password = userInfo.getProperty("password");
SolubilityData data = new SolubilityData(username, password);
data.download();
for (Measurement measurement : data.getData()) {
createResource(measurement);
}
}
private void createResource(Measurement mData) {
// create the resource
String url = ONS.NS;
Resource measurement = model.createResource(url + "measurement" + measurementsProcessed);
// // FIXME: how can I set the rdf:type?? that is, have ons:Measurement??
measurement.addProperty(RDF.type, ONS.Measurement);
measurement.addProperty(ONS.experiment, model.createResource(url + "experiment" + mData.getExperiment()));
measurement.addProperty(ONS.solute, getSoluteResource(mData));
measurement.addProperty(ONS.solvent, getSolventResource(mData));
measurementsProcessed++;
}
private Resource getSolventResource(Measurement mData) {
String solventName = removeQuotes(mData.getSolvent());
Resource solvent = solvents.get(solventName);
if (solvent == null) {
solvent = model.createResource(ONS.NS + "solvent" + solventsProcessed);
solvent.addProperty(RDF.type, ONS.Solvent);
solvent.addProperty(DC_11.title, mData.getSolvent().trim());
solvent.addProperty(BO.smiles, mData.getSolventSMILES().trim());
solvents.put(solventName, solvent);
solventsProcessed++;
}
return solvent;
}
private Resource getSoluteResource(Measurement mData) {
String soluteName = removeQuotes(mData.getSolute());
Resource solute = solutes.get(soluteName);
if (solute == null) {
solute = model.createResource(ONS.NS + "solute" + solutesProcessed);
solute.addProperty(RDF.type, ONS.Solute);
if (mData.getSolute() != null)
solute.addProperty(DC_11.title, mData.getSolute());
String SMILES = mData.getSoluteSMILES();
if (SMILES != null) solute.addProperty(BO.smiles, SMILES);
try {
IAtomContainer container = smilesParser.parseSmiles(SMILES);
InChIGenerator inchiGenerator =
inchiFactory.getInChIGenerator(container);
INCHI_RET ret = inchiGenerator.getReturnStatus();
if (ret == INCHI_RET.WARNING) {
// InChI generated, but with warning message
System.out.println("InChI warning: " + inchiGenerator.getMessage());
} else if (ret != INCHI_RET.OKAY) {
// InChI generation failed
throw new CDKException("InChI failed: " + ret.toString()
+ " [" + inchiGenerator.getMessage() + "]");
}
solute.addProperty(
RDFS.isDefinedBy,
- "http://rdf.openmolecule.net/?" + inchiGenerator.getInchi()
+ model.createResource("http://rdf.openmolecules.net/?" +
+ inchiGenerator.getInchi())
);
} catch ( InvalidSmilesException e ) {
System.out.println("Error in parsing SMILES: " + SMILES);
e.printStackTrace();
} catch ( CDKException e ) {
System.out.println("Error in creating InChI for SMILES: " + SMILES);
e.printStackTrace();
}
solutes.put(soluteName, solute);
solutesProcessed++;
}
return solute;
}
private String removeQuotes(String string) {
if (string == null || string.length() == 0) return string;
String result = string;
if (result.charAt(0) == '"') {
result = result.substring(1);
}
if (result.charAt(result.length()-1) == '"') {
result = result.substring(0, result.length()-1);
}
return result;
}
public void write() {
model.setNsPrefix("ons", ONS.NS);
model.setNsPrefix("chem", BO.NS);
try {
model.write(System.out);
} catch (Exception exception) {
exception.printStackTrace();
}
}
public static void main( String[] args ) throws Exception {
ConvertToRDF convertor = new ConvertToRDF();
convertor.processData();
convertor.write();
}
}
| true | true | private Resource getSoluteResource(Measurement mData) {
String soluteName = removeQuotes(mData.getSolute());
Resource solute = solutes.get(soluteName);
if (solute == null) {
solute = model.createResource(ONS.NS + "solute" + solutesProcessed);
solute.addProperty(RDF.type, ONS.Solute);
if (mData.getSolute() != null)
solute.addProperty(DC_11.title, mData.getSolute());
String SMILES = mData.getSoluteSMILES();
if (SMILES != null) solute.addProperty(BO.smiles, SMILES);
try {
IAtomContainer container = smilesParser.parseSmiles(SMILES);
InChIGenerator inchiGenerator =
inchiFactory.getInChIGenerator(container);
INCHI_RET ret = inchiGenerator.getReturnStatus();
if (ret == INCHI_RET.WARNING) {
// InChI generated, but with warning message
System.out.println("InChI warning: " + inchiGenerator.getMessage());
} else if (ret != INCHI_RET.OKAY) {
// InChI generation failed
throw new CDKException("InChI failed: " + ret.toString()
+ " [" + inchiGenerator.getMessage() + "]");
}
solute.addProperty(
RDFS.isDefinedBy,
"http://rdf.openmolecule.net/?" + inchiGenerator.getInchi()
);
} catch ( InvalidSmilesException e ) {
System.out.println("Error in parsing SMILES: " + SMILES);
e.printStackTrace();
} catch ( CDKException e ) {
System.out.println("Error in creating InChI for SMILES: " + SMILES);
e.printStackTrace();
}
solutes.put(soluteName, solute);
solutesProcessed++;
}
return solute;
}
| private Resource getSoluteResource(Measurement mData) {
String soluteName = removeQuotes(mData.getSolute());
Resource solute = solutes.get(soluteName);
if (solute == null) {
solute = model.createResource(ONS.NS + "solute" + solutesProcessed);
solute.addProperty(RDF.type, ONS.Solute);
if (mData.getSolute() != null)
solute.addProperty(DC_11.title, mData.getSolute());
String SMILES = mData.getSoluteSMILES();
if (SMILES != null) solute.addProperty(BO.smiles, SMILES);
try {
IAtomContainer container = smilesParser.parseSmiles(SMILES);
InChIGenerator inchiGenerator =
inchiFactory.getInChIGenerator(container);
INCHI_RET ret = inchiGenerator.getReturnStatus();
if (ret == INCHI_RET.WARNING) {
// InChI generated, but with warning message
System.out.println("InChI warning: " + inchiGenerator.getMessage());
} else if (ret != INCHI_RET.OKAY) {
// InChI generation failed
throw new CDKException("InChI failed: " + ret.toString()
+ " [" + inchiGenerator.getMessage() + "]");
}
solute.addProperty(
RDFS.isDefinedBy,
model.createResource("http://rdf.openmolecules.net/?" +
inchiGenerator.getInchi())
);
} catch ( InvalidSmilesException e ) {
System.out.println("Error in parsing SMILES: " + SMILES);
e.printStackTrace();
} catch ( CDKException e ) {
System.out.println("Error in creating InChI for SMILES: " + SMILES);
e.printStackTrace();
}
solutes.put(soluteName, solute);
solutesProcessed++;
}
return solute;
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/NEvaluator.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/NEvaluator.java
index eb9fd5610..c9c27b5d0 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/NEvaluator.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/NEvaluator.java
@@ -1,314 +1,315 @@
package org.eclipse.birt.data.engine.script;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.IExecutorHelper;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* The implementation of this class is used to evaluate TopN/BottomN expressions
* @author lzhu
*
*/
public abstract class NEvaluator
{
private static int MAX_N_VALUE = 1000000;
private Object[] valueList;
private int[] rowIdList;
private int firstPassRowNumberCounter = 0;
private int secondPassRowNumberCounter = 0;
private int qualifiedRowCounter = 0;
private IExecutorHelper helper;
//The "N" of topN/bottomN.
private int N = -1;
// whether we are doing N percent
private boolean n_percent = false;
// expression for operand (to be compared)
private IScriptExpression op_expr;
// expression for N
private IScriptExpression n_expr;
private FilterPassController filterPassController;
protected static final String nullValueReplacer = "{NULL_VALUE_!@#$%^&}";
/**
* Create a new instance to evaluate the top/bottom expression
* @param operator
* @param op_expr operand expression
* @param n_expr expression to yield N
* @return
*/
public static NEvaluator newInstance( int operator, IScriptExpression op_expr,
IScriptExpression n_expr, FilterPassController filterPassController, IExecutorHelper helper )
throws DataException
{
NEvaluator instance = null;
switch ( operator )
{
case IConditionalExpression.OP_TOP_N :
instance = new TopNEvaluator();
instance.n_percent = false;
break;
case IConditionalExpression.OP_TOP_PERCENT:
instance = new TopNEvaluator( );
instance.n_percent = true;
break;
case IConditionalExpression.OP_BOTTOM_N:
instance = new BottomNEvaluator( );
instance.n_percent = false;
break;
case IConditionalExpression.OP_BOTTOM_PERCENT:
instance = new BottomNEvaluator( );
instance.n_percent = true;
break;
default:
assert false; // shouldn't get here
return null;
}
instance.op_expr = op_expr;
instance.n_expr = n_expr;
instance.filterPassController = filterPassController;
instance.helper = helper;
return instance;
}
/**
* Evaluate the given value
* @param value
* @param n
* @return
* @throws DataException
*/
public boolean evaluate( Context cx, Scriptable scope ) throws DataException
{
if( filterPassController.getForceReset() )
{
doReset();
filterPassController.setForceReset( false );
}
if ( N == -1 )
{
// Create a new evaluator
// Evaluate N (which is operand1) at this time
Object n_object = null;
if( helper != null )
{
try
{
n_object = helper.evaluate( n_expr );
}
catch ( BirtException e1 )
{
throw new DataException( e1.getLocalizedMessage( ) );
}
}
else
ScriptEvalUtil.evalExpr( n_expr, cx, scope, "Filter", 0 );
double n_value = -1;
try
{
n_value = DataTypeUtil.toDouble( n_object ).doubleValue();
}
catch ( BirtException e )
{
// conversion error
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_ARGUMENT, e);
}
// First time; calculate N based on updated row count
if( n_percent )
{
if( n_value < 0 || n_value > 100)
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_PERCENT_ARGUMENT);
N = (int)Math.round( n_value / 100 * filterPassController.getRowCount() );
}
else
{
if( n_value < 0 )
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_N_ARGUMENT);
N = (int)n_value;
}
if ( N > MAX_N_VALUE )
- throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_N + MAX_N_VALUE);
+ throw new DataException( ResourceConstants.INVALID_TOP_BOTTOM_N,
+ new Integer( MAX_N_VALUE ) );
}
// Evaluate operand expression
Object value = ScriptEvalUtil.evalExpr( op_expr, cx, scope, "Filter", 0 );
if ( filterPassController.getPassLevel( ) == FilterPassController.FIRST_PASS )
{
return doFirstPass( value );
}
else if ( filterPassController.getPassLevel( ) == FilterPassController.SECOND_PASS )
{
return doSecondPass( );
}
return false;
}
/**
* Do the first pass. In the first pass we maintain a value list and a row id list that will
* host all top/bottom N values/rowIds so that in pass 2 we can use them to filter rows out.
* @param value
* @return
* @throws DataException
*/
private boolean doFirstPass( Object value ) throws DataException
{
firstPassRowNumberCounter++;
if ( valueList == null )
{
valueList = new Object[N];
rowIdList = new int[N];
}
populateValueListAndRowIdList( value, N );
return true;
}
/**
* @param value
* @param N
* @throws DataException
*/
private void populateValueListAndRowIdList( Object value, int N ) throws DataException
{
assert N>=0;
for( int i = 0; i < N; i++ )
{
if( value == null )
value = nullValueReplacer;
if( valueList[i] == null )
{
valueList[i] = value;
rowIdList[i] = firstPassRowNumberCounter;
break;
}
else
{
Object result;
if( value.equals(nullValueReplacer) )
result = this.doCompare( null, valueList[i]);
else if ( valueList[i].equals(nullValueReplacer))
result = this.doCompare( value, null );
else
result = this.doCompare( value, valueList[i] );
try
{
// filter in
if ( DataTypeUtil.toBoolean( result ).booleanValue( ) == true )
{
for( int j = N - 1; j > i; j--)
{
valueList[j] = valueList[j-1];
rowIdList[j] = rowIdList[j-1];
}
valueList[i] = value;
rowIdList[i] = firstPassRowNumberCounter;
break;
}
}
catch ( BirtException e )
{
throw DataException.wrap(e);
}
}
}
}
/**
* Do the second pass
* @param N
* @return
*/
private boolean doSecondPass( )
{
secondPassRowNumberCounter++;
if( secondPassRowNumberCounter > this.filterPassController.getSecondPassRowCount() )
this.filterPassController.setSecondPassRowCount( secondPassRowNumberCounter );
else
this.secondPassRowNumberCounter = this.filterPassController.getSecondPassRowCount();
if ( qualifiedRowCounter < N )
{
for ( int i = 0; i < N; i++ )
{
if ( rowIdList[i] == secondPassRowNumberCounter )
{
qualifiedRowCounter++;
reset( );
return true;
}
}
return false;
}
else
{
reset( );
return false;
}
}
/**
* Reset all the member data to their default value.
*/
private void reset( )
{
if ( firstPassRowNumberCounter == secondPassRowNumberCounter )
{
doReset();
}
}
/**
*
*
*/
private void doReset()
{
firstPassRowNumberCounter = 0;
secondPassRowNumberCounter = 0;
qualifiedRowCounter = 0;
rowIdList = null;
valueList = null;
N = -1;
}
protected abstract Object doCompare( Object value1, Object value2 ) throws DataException;
}
/**
* The class that provides "Top N" calculation service
*
*/
class TopNEvaluator extends NEvaluator
{
protected Object doCompare( Object value1, Object value2 ) throws DataException
{
return ScriptEvalUtil.evalConditionalExpr( value1, IConditionalExpression.OP_GT, value2, null);
}
}
/**
* The class that provides "Bottom N" calculation service
*
*/
class BottomNEvaluator extends NEvaluator
{
protected Object doCompare( Object value1, Object value2 ) throws DataException
{
return ScriptEvalUtil.evalConditionalExpr( value1, IConditionalExpression.OP_LT, value2, null);
}
}
| true | true | public boolean evaluate( Context cx, Scriptable scope ) throws DataException
{
if( filterPassController.getForceReset() )
{
doReset();
filterPassController.setForceReset( false );
}
if ( N == -1 )
{
// Create a new evaluator
// Evaluate N (which is operand1) at this time
Object n_object = null;
if( helper != null )
{
try
{
n_object = helper.evaluate( n_expr );
}
catch ( BirtException e1 )
{
throw new DataException( e1.getLocalizedMessage( ) );
}
}
else
ScriptEvalUtil.evalExpr( n_expr, cx, scope, "Filter", 0 );
double n_value = -1;
try
{
n_value = DataTypeUtil.toDouble( n_object ).doubleValue();
}
catch ( BirtException e )
{
// conversion error
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_ARGUMENT, e);
}
// First time; calculate N based on updated row count
if( n_percent )
{
if( n_value < 0 || n_value > 100)
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_PERCENT_ARGUMENT);
N = (int)Math.round( n_value / 100 * filterPassController.getRowCount() );
}
else
{
if( n_value < 0 )
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_N_ARGUMENT);
N = (int)n_value;
}
if ( N > MAX_N_VALUE )
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_N + MAX_N_VALUE);
}
// Evaluate operand expression
Object value = ScriptEvalUtil.evalExpr( op_expr, cx, scope, "Filter", 0 );
if ( filterPassController.getPassLevel( ) == FilterPassController.FIRST_PASS )
{
return doFirstPass( value );
}
else if ( filterPassController.getPassLevel( ) == FilterPassController.SECOND_PASS )
{
return doSecondPass( );
}
return false;
}
| public boolean evaluate( Context cx, Scriptable scope ) throws DataException
{
if( filterPassController.getForceReset() )
{
doReset();
filterPassController.setForceReset( false );
}
if ( N == -1 )
{
// Create a new evaluator
// Evaluate N (which is operand1) at this time
Object n_object = null;
if( helper != null )
{
try
{
n_object = helper.evaluate( n_expr );
}
catch ( BirtException e1 )
{
throw new DataException( e1.getLocalizedMessage( ) );
}
}
else
ScriptEvalUtil.evalExpr( n_expr, cx, scope, "Filter", 0 );
double n_value = -1;
try
{
n_value = DataTypeUtil.toDouble( n_object ).doubleValue();
}
catch ( BirtException e )
{
// conversion error
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_ARGUMENT, e);
}
// First time; calculate N based on updated row count
if( n_percent )
{
if( n_value < 0 || n_value > 100)
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_PERCENT_ARGUMENT);
N = (int)Math.round( n_value / 100 * filterPassController.getRowCount() );
}
else
{
if( n_value < 0 )
throw new DataException(ResourceConstants.INVALID_TOP_BOTTOM_N_ARGUMENT);
N = (int)n_value;
}
if ( N > MAX_N_VALUE )
throw new DataException( ResourceConstants.INVALID_TOP_BOTTOM_N,
new Integer( MAX_N_VALUE ) );
}
// Evaluate operand expression
Object value = ScriptEvalUtil.evalExpr( op_expr, cx, scope, "Filter", 0 );
if ( filterPassController.getPassLevel( ) == FilterPassController.FIRST_PASS )
{
return doFirstPass( value );
}
else if ( filterPassController.getPassLevel( ) == FilterPassController.SECOND_PASS )
{
return doSecondPass( );
}
return false;
}
|
diff --git a/src/com/android/contacts/calllog/ContactInfoHelper.java b/src/com/android/contacts/calllog/ContactInfoHelper.java
index b4e4cf7d3..90d5e8b0b 100644
--- a/src/com/android/contacts/calllog/ContactInfoHelper.java
+++ b/src/com/android/contacts/calllog/ContactInfoHelper.java
@@ -1,214 +1,215 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.calllog;
import com.android.contacts.util.UriUtils;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
/**
* Utility class to look up the contact information for a given number.
*/
public class ContactInfoHelper {
private final Context mContext;
private final String mCurrentCountryIso;
public ContactInfoHelper(Context context, String currentCountryIso) {
mContext = context;
mCurrentCountryIso = currentCountryIso;
}
/**
* Returns the contact information for the given number.
* <p>
* If the number does not match any contact, returns a contact info containing only the number
* and the formatted number.
* <p>
* If an error occurs during the lookup, it returns null.
*
* @param number the number to look up
* @param countryIso the country associated with this number
*/
public ContactInfo lookupNumber(String number, String countryIso) {
final ContactInfo info;
// Determine the contact info.
if (PhoneNumberUtils.isUriNumber(number)) {
// This "number" is really a SIP address.
ContactInfo sipInfo = queryContactInfoForSipAddress(number);
if (sipInfo == null || sipInfo == ContactInfo.EMPTY) {
- // Check whether the username is actually a phone number of contact.
- String username = number.substring(0, number.indexOf('@'));
+ // Check whether the "username" part of the SIP address is
+ // actually the phone number of a contact.
+ String username = PhoneNumberUtils.getUsernameFromUriNumber(number);
if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
sipInfo = queryContactInfoForPhoneNumber(username, countryIso);
}
}
info = sipInfo;
} else {
// Look for a contact that has the given phone number.
ContactInfo phoneInfo = queryContactInfoForPhoneNumber(number, countryIso);
if (phoneInfo == null || phoneInfo == ContactInfo.EMPTY) {
// Check whether the phone number has been saved as an "Internet call" number.
phoneInfo = queryContactInfoForSipAddress(number);
}
info = phoneInfo;
}
final ContactInfo updatedInfo;
if (info == null) {
// The lookup failed.
updatedInfo = null;
} else {
// If we did not find a matching contact, generate an empty contact info for the number.
if (info == ContactInfo.EMPTY) {
// Did not find a matching contact.
updatedInfo = new ContactInfo();
updatedInfo.number = number;
updatedInfo.formattedNumber = formatPhoneNumber(number, null, countryIso);
} else {
updatedInfo = info;
}
}
return updatedInfo;
}
/**
* Looks up a contact using the given URI.
* <p>
* It returns null if an error occurs, {@link ContactInfo#EMPTY} if no matching contact is
* found, or the {@link ContactInfo} for the given contact.
* <p>
* The {@link ContactInfo#formattedNumber} field is always set to {@code null} in the returned
* value.
*/
private ContactInfo lookupContactFromUri(Uri uri) {
final ContactInfo info;
Cursor phonesCursor =
mContext.getContentResolver().query(
uri, PhoneQuery._PROJECTION, null, null, null);
if (phonesCursor != null) {
try {
if (phonesCursor.moveToFirst()) {
info = new ContactInfo();
long contactId = phonesCursor.getLong(PhoneQuery.PERSON_ID);
String lookupKey = phonesCursor.getString(PhoneQuery.LOOKUP_KEY);
info.lookupUri = Contacts.getLookupUri(contactId, lookupKey);
info.name = phonesCursor.getString(PhoneQuery.NAME);
info.type = phonesCursor.getInt(PhoneQuery.PHONE_TYPE);
info.label = phonesCursor.getString(PhoneQuery.LABEL);
info.number = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
info.normalizedNumber = phonesCursor.getString(PhoneQuery.NORMALIZED_NUMBER);
info.photoId = phonesCursor.getLong(PhoneQuery.PHOTO_ID);
info.photoUri =
UriUtils.parseUriOrNull(phonesCursor.getString(PhoneQuery.PHOTO_URI));
info.formattedNumber = null;
} else {
info = ContactInfo.EMPTY;
}
} finally {
phonesCursor.close();
}
} else {
// Failed to fetch the data, ignore this request.
info = null;
}
return info;
}
/**
* Determines the contact information for the given SIP address.
* <p>
* It returns the contact info if found.
* <p>
* If no contact corresponds to the given SIP address, returns {@link ContactInfo#EMPTY}.
* <p>
* If the lookup fails for some other reason, it returns null.
*/
private ContactInfo queryContactInfoForSipAddress(String sipAddress) {
final ContactInfo info;
// "contactNumber" is a SIP address, so use the PhoneLookup table with the SIP parameter.
Uri.Builder uriBuilder = PhoneLookup.CONTENT_FILTER_URI.buildUpon();
uriBuilder.appendPath(Uri.encode(sipAddress));
uriBuilder.appendQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, "1");
return lookupContactFromUri(uriBuilder.build());
}
/**
* Determines the contact information for the given phone number.
* <p>
* It returns the contact info if found.
* <p>
* If no contact corresponds to the given phone number, returns {@link ContactInfo#EMPTY}.
* <p>
* If the lookup fails for some other reason, it returns null.
*/
private ContactInfo queryContactInfoForPhoneNumber(String number, String countryIso) {
String contactNumber = number;
if (!TextUtils.isEmpty(countryIso)) {
// Normalize the number: this is needed because the PhoneLookup query below does not
// accept a country code as an input.
String numberE164 = PhoneNumberUtils.formatNumberToE164(number, countryIso);
if (!TextUtils.isEmpty(numberE164)) {
// Only use it if the number could be formatted to E164.
contactNumber = numberE164;
}
}
// The "contactNumber" is a regular phone number, so use the PhoneLookup table.
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(contactNumber));
ContactInfo info = lookupContactFromUri(uri);
if (info != null && info != ContactInfo.EMPTY) {
info.formattedNumber = formatPhoneNumber(number, null, countryIso);
}
return info;
}
/**
* Format the given phone number
*
* @param number the number to be formatted.
* @param normalizedNumber the normalized number of the given number.
* @param countryIso the ISO 3166-1 two letters country code, the country's
* convention will be used to format the number if the normalized
* phone is null.
*
* @return the formatted number, or the given number if it was formatted.
*/
private String formatPhoneNumber(String number, String normalizedNumber,
String countryIso) {
if (TextUtils.isEmpty(number)) {
return "";
}
// If "number" is really a SIP address, don't try to do any formatting at all.
if (PhoneNumberUtils.isUriNumber(number)) {
return number;
}
if (TextUtils.isEmpty(countryIso)) {
countryIso = mCurrentCountryIso;
}
return PhoneNumberUtils.formatNumber(number, normalizedNumber, countryIso);
}
}
| true | true | public ContactInfo lookupNumber(String number, String countryIso) {
final ContactInfo info;
// Determine the contact info.
if (PhoneNumberUtils.isUriNumber(number)) {
// This "number" is really a SIP address.
ContactInfo sipInfo = queryContactInfoForSipAddress(number);
if (sipInfo == null || sipInfo == ContactInfo.EMPTY) {
// Check whether the username is actually a phone number of contact.
String username = number.substring(0, number.indexOf('@'));
if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
sipInfo = queryContactInfoForPhoneNumber(username, countryIso);
}
}
info = sipInfo;
} else {
// Look for a contact that has the given phone number.
ContactInfo phoneInfo = queryContactInfoForPhoneNumber(number, countryIso);
if (phoneInfo == null || phoneInfo == ContactInfo.EMPTY) {
// Check whether the phone number has been saved as an "Internet call" number.
phoneInfo = queryContactInfoForSipAddress(number);
}
info = phoneInfo;
}
final ContactInfo updatedInfo;
if (info == null) {
// The lookup failed.
updatedInfo = null;
} else {
// If we did not find a matching contact, generate an empty contact info for the number.
if (info == ContactInfo.EMPTY) {
// Did not find a matching contact.
updatedInfo = new ContactInfo();
updatedInfo.number = number;
updatedInfo.formattedNumber = formatPhoneNumber(number, null, countryIso);
} else {
updatedInfo = info;
}
}
return updatedInfo;
}
| public ContactInfo lookupNumber(String number, String countryIso) {
final ContactInfo info;
// Determine the contact info.
if (PhoneNumberUtils.isUriNumber(number)) {
// This "number" is really a SIP address.
ContactInfo sipInfo = queryContactInfoForSipAddress(number);
if (sipInfo == null || sipInfo == ContactInfo.EMPTY) {
// Check whether the "username" part of the SIP address is
// actually the phone number of a contact.
String username = PhoneNumberUtils.getUsernameFromUriNumber(number);
if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
sipInfo = queryContactInfoForPhoneNumber(username, countryIso);
}
}
info = sipInfo;
} else {
// Look for a contact that has the given phone number.
ContactInfo phoneInfo = queryContactInfoForPhoneNumber(number, countryIso);
if (phoneInfo == null || phoneInfo == ContactInfo.EMPTY) {
// Check whether the phone number has been saved as an "Internet call" number.
phoneInfo = queryContactInfoForSipAddress(number);
}
info = phoneInfo;
}
final ContactInfo updatedInfo;
if (info == null) {
// The lookup failed.
updatedInfo = null;
} else {
// If we did not find a matching contact, generate an empty contact info for the number.
if (info == ContactInfo.EMPTY) {
// Did not find a matching contact.
updatedInfo = new ContactInfo();
updatedInfo.number = number;
updatedInfo.formattedNumber = formatPhoneNumber(number, null, countryIso);
} else {
updatedInfo = info;
}
}
return updatedInfo;
}
|
diff --git a/src/sql/DB.java b/src/sql/DB.java
index d29d576..55777a4 100644
--- a/src/sql/DB.java
+++ b/src/sql/DB.java
@@ -1,187 +1,188 @@
package sql;
/*hi*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import javax.servlet.RequestDispatcher;
import frontend.Challenge;
import frontend.FriendRequest;
import frontend.History;
import frontend.Message;
import frontend.Result;
public class DB {
private static final String MYSQL_USERNAME = "ccs108kolyyu22";
private static final String MYSQL_PASSWORD = "shooneon";
private static final String MYSQL_DATABASE_SERVER = "mysql-user.stanford.edu";
private static final String MYSQL_DATABASE_NAME = "c_cs108_kolyyu22";
private static Connection con;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" + MYSQL_DATABASE_SERVER + "/" + MYSQL_DATABASE_NAME;
con = DriverManager.getConnection(url, MYSQL_USERNAME, MYSQL_PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
System.err.println("CS108 student: Update the MySQL constants to correct values!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.err.println("CS108 student: Add the MySQL jar file to your build path!");
}
}
public static Connection getConnection() {
return con;
}
public static void close() {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addUser(String user, String hash, boolean isAdmin){
String query = "INSERT INTO users VALUES('" + user + "', " + "'" + hash + "', " + isAdmin + ");";
System.out.println(query);
sqlUpdate(query);
}
private ResultSet getResult(String query){
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void sqlUpdate(String query){
Statement stmt;
try {
stmt = con.createStatement();
stmt.executeUpdate(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<String> getFriends(String userId){
String query = "SELECT id2 FROM friends WHERE id1 = '" + userId + "';";
System.out.println(query);
ArrayList<String> list = new ArrayList<String>();
try {
ResultSet rs = getResult(query);
rs.beforeFirst();
while (rs.next()){
list.add(rs.getString("id2"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public ArrayList<Message> getMessages(String userId){
ArrayList<Message> returnList = new ArrayList<Message>();
String query = "select * from notes where dest = '" + userId + "'";
ResultSet rs = getResult(query);
try {
while(rs.next()){
returnList.add(new Message(rs.getString("src"), rs.getString("dest"), rs.getString("body"), rs.getString("time")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ArrayList<Message>();
}
public History getHistory(String userId){
return null;
}
public ArrayList<String> getAchievements(String userId){
return null;
}
public boolean getIsAdmin(String userId){
return false;
}
public void addAchievement(String userId, String achievement){
}
public ArrayList<Challenge> getChallenges(String userId){
return null;
}
public void addFriend(String user1, String user2){
String query = "INSERT INTO friends VALUES('" + user1 + "', '" + user2 + "');";
sqlUpdate(query);
System.out.println(query);
}
public void removeFriend(String id, String id2) {
String query = "DELETE FROM friends WHERE id1 = '" + id + "' AND id2 = '" + id2 + "';";
sqlUpdate(query);
System.out.println(query);
}
public ArrayList<FriendRequest> getFriendRequests(String id) {
String query = "SELECT * FROM requests WHERE dest = '" + id + "' and isConfirmed = false;";
System.out.println(query);
ArrayList<FriendRequest> list = new ArrayList<FriendRequest>();
try {
ResultSet rs = getResult(query);
rs.beforeFirst();
while (rs.next()){
String source = rs.getString("source");
boolean isConfirmed = rs.getBoolean("isConfirmed");
String time = rs.getString("time");
- FriendRequest fr = new FriendRequest(source, id, source + " has added you as a friend!", isConfirmed);
+ String body = source + " has added you as a friend!";
+ FriendRequest fr = new FriendRequest(source, id, body, isConfirmed, time);
list.add(fr);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public void addResult(String id, Result result) {
// TODO Auto-generated method stub
}
public void setAdminStatus(String id, boolean status) {
// TODO Auto-generated method stub
}
public void sendMessage(Message message) {
// TODO Auto-generated method stub
}
}
| true | true | public ArrayList<FriendRequest> getFriendRequests(String id) {
String query = "SELECT * FROM requests WHERE dest = '" + id + "' and isConfirmed = false;";
System.out.println(query);
ArrayList<FriendRequest> list = new ArrayList<FriendRequest>();
try {
ResultSet rs = getResult(query);
rs.beforeFirst();
while (rs.next()){
String source = rs.getString("source");
boolean isConfirmed = rs.getBoolean("isConfirmed");
String time = rs.getString("time");
FriendRequest fr = new FriendRequest(source, id, source + " has added you as a friend!", isConfirmed);
list.add(fr);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
| public ArrayList<FriendRequest> getFriendRequests(String id) {
String query = "SELECT * FROM requests WHERE dest = '" + id + "' and isConfirmed = false;";
System.out.println(query);
ArrayList<FriendRequest> list = new ArrayList<FriendRequest>();
try {
ResultSet rs = getResult(query);
rs.beforeFirst();
while (rs.next()){
String source = rs.getString("source");
boolean isConfirmed = rs.getBoolean("isConfirmed");
String time = rs.getString("time");
String body = source + " has added you as a friend!";
FriendRequest fr = new FriendRequest(source, id, body, isConfirmed, time);
list.add(fr);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
|
diff --git a/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyLintVisitor.java b/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyLintVisitor.java
index d2007114..3f5bce0c 100644
--- a/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyLintVisitor.java
+++ b/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyLintVisitor.java
@@ -1,141 +1,141 @@
package org.rubypeople.rdt.internal.core.parser;
import java.util.HashSet;
import java.util.Set;
import org.jruby.ast.BlockNode;
import org.jruby.ast.CallNode;
import org.jruby.ast.ConstDeclNode;
import org.jruby.ast.DefnNode;
import org.jruby.ast.DefsNode;
import org.jruby.ast.FCallNode;
import org.jruby.ast.FalseNode;
import org.jruby.ast.IfNode;
import org.jruby.ast.IterNode;
import org.jruby.ast.NilNode;
import org.jruby.ast.Node;
import org.jruby.ast.ScopeNode;
import org.jruby.ast.TrueNode;
import org.jruby.ast.WhenNode;
import org.jruby.evaluator.Instruction;
import org.jruby.lexer.yacc.ISourcePosition;
import org.rubypeople.rdt.core.IProblemRequestor;
import org.rubypeople.rdt.core.RubyCore;
import org.rubypeople.rdt.core.parser.IProblem;
public class RubyLintVisitor extends InOrderVisitor {
private IProblemRequestor problemRequestor;
private Set assignedConstants;
private Set methodsCalled;
private String contents;
public RubyLintVisitor(String contents, IProblemRequestor problemRequestor) {
this.problemRequestor = problemRequestor;
assignedConstants = new HashSet();
methodsCalled = new HashSet();
this.contents = contents;
}
public Instruction visitFCallNode(FCallNode iVisited) {
methodsCalled.add(iVisited.getName());
return super.visitFCallNode(iVisited);
}
public Instruction visitCallNode(CallNode iVisited) {
methodsCalled.add(iVisited.getName());
return super.visitCallNode(iVisited);
}
public Instruction visitIfNode(IfNode iVisited) {
Node condition = iVisited.getCondition();
if (condition instanceof TrueNode) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Condition is always true"));
} else if ((condition instanceof FalseNode) || (condition instanceof NilNode)) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Condition is always false"));
}
String source = NodeUtil.getSource(contents, iVisited);
- if (iVisited.getThenBody() == null && !source.contains("unless")) {
+ if (iVisited.getThenBody() == null && source.indexOf("unless") == -1) {
IProblem problem = createProblem(
RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty Conditional Body");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitIfNode(iVisited);
}
public Instruction visitWhenNode(WhenNode iVisited) {
if (iVisited.getBodyNode() == null) {
IProblem problem = createProblem(RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty When Body");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitWhenNode(iVisited);
}
public Instruction visitBlockNode(BlockNode iVisited) {
return super.visitBlockNode(iVisited);
}
public Instruction visitIterNode(IterNode iVisited) {
if (iVisited.getBodyNode() == null) {
IProblem problem = createProblem(RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty Block");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitIterNode(iVisited);
}
public Instruction visitDefnNode(DefnNode iVisited) {
// TODO Analyze method visibility. Create warning for uncalled private
// methods
ScopeNode scope = iVisited.getBodyNode();
if (scope.getBodyNode() == null) {
IProblem problem = createProblem(RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty Method Definition");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitDefnNode(iVisited);
}
public Instruction visitDefsNode(DefsNode iVisited) {
ScopeNode scope = iVisited.getBodyNode();
if (scope.getBodyNode() == null) {
IProblem problem = createProblem(RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty Method Definition");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitDefsNode(iVisited);
}
protected Instruction handleNode(Node visited) {
// System.out.println(visited.toString() + ", position -> "
// + visited.getPosition());
return super.handleNode(visited);
}
public Instruction visitConstDeclNode(ConstDeclNode iVisited) {
String name = iVisited.getName();
if (assignedConstants.contains(name)) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Reassignment of a constant"));
} else
assignedConstants.add(name);
return super.visitConstDeclNode(iVisited);
}
private IProblem createProblem(String compilerOption, ISourcePosition position, String message) {
String value = RubyCore.getOption(compilerOption);
if (value == null)
return new Error(position, message);
if (value.equals(RubyCore.WARNING))
return new Warning(position, message);
if (value.equals(RubyCore.ERROR))
return new Error(position, message);
return null;
}
}
| true | true | public Instruction visitIfNode(IfNode iVisited) {
Node condition = iVisited.getCondition();
if (condition instanceof TrueNode) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Condition is always true"));
} else if ((condition instanceof FalseNode) || (condition instanceof NilNode)) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Condition is always false"));
}
String source = NodeUtil.getSource(contents, iVisited);
if (iVisited.getThenBody() == null && !source.contains("unless")) {
IProblem problem = createProblem(
RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty Conditional Body");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitIfNode(iVisited);
}
| public Instruction visitIfNode(IfNode iVisited) {
Node condition = iVisited.getCondition();
if (condition instanceof TrueNode) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Condition is always true"));
} else if ((condition instanceof FalseNode) || (condition instanceof NilNode)) {
problemRequestor.acceptProblem(new Warning(iVisited.getPosition(), "Condition is always false"));
}
String source = NodeUtil.getSource(contents, iVisited);
if (iVisited.getThenBody() == null && source.indexOf("unless") == -1) {
IProblem problem = createProblem(
RubyCore.COMPILER_PB_EMPTY_STATEMENT, iVisited.getPosition(), "Empty Conditional Body");
if (problem != null)
problemRequestor.acceptProblem(problem);
}
return super.visitIfNode(iVisited);
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java b/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
index f6d572cc6..020ae4a11 100644
--- a/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
+++ b/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
@@ -1,299 +1,299 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.metaclass;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest;
import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletResponse;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since 0.2
*
* Created: Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private static final String ARGUMENT_TO = "to";
private static final int BUFFER_SIZE = 8192;
public RenderDynamicMethod() {
super(METHOD_PATTERN);
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
try {
- out.flush();
+ if(!renderView) out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
}
| true | true | public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
try {
out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
| public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
try {
if(!renderView) out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
|
diff --git a/src/chameleon/test/provider/BasicDescendantProvider.java b/src/chameleon/test/provider/BasicDescendantProvider.java
index f12518a3..01fcaa59 100644
--- a/src/chameleon/test/provider/BasicDescendantProvider.java
+++ b/src/chameleon/test/provider/BasicDescendantProvider.java
@@ -1,54 +1,55 @@
package chameleon.test.provider;
import java.util.ArrayList;
import java.util.Collection;
import chameleon.core.element.Element;
import chameleon.core.language.Language;
/**
* A class for searching elements of type E in the elements provided by a provider to the ancestor
* elements.
*
* @author Marko van Dooren
*
* @param <E>
*/
public class BasicDescendantProvider<E extends Element> extends AbstractDescendantProvider<E> {
/**
* Create a new basic descendant provider with the given ancestor provider, and the class
* object representing the type of the elements that must be provided.
*/
/*@
@ public behavior
@
@ pre ancestorProvider != null;
@ pre cls != null;
@
@ post ancestorProvider() == ancestorProvider;
@ post selectedType() == cls;
@*/
public BasicDescendantProvider(ElementProvider<? extends Element> ancestorProvider, Class<E> cls) {
super(ancestorProvider, cls);
}
/**
* Return a collection containing all descendants of type E of all elements
* provided by the ancestor provider.
*/
/*@
@ public behavior
@
@ post (\forall Element ancestor; ancestorProvider().elements().contains(ancestor);
@ \result.containsAll(ancestor.descendants(selectedType())));
*/
public Collection<E> elements(Language language) {
Collection<E> result = new ArrayList<E>();
Class<E> cls = elementType();
- for(Element<?> element: ancestorProvider().elements(language)) {
+ Collection<? extends Element> elements = ancestorProvider().elements(language);
+ for(Element<?> element: elements) {
result.addAll(element.descendants(cls));
}
return result;
}
}
| true | true | public Collection<E> elements(Language language) {
Collection<E> result = new ArrayList<E>();
Class<E> cls = elementType();
for(Element<?> element: ancestorProvider().elements(language)) {
result.addAll(element.descendants(cls));
}
return result;
}
| public Collection<E> elements(Language language) {
Collection<E> result = new ArrayList<E>();
Class<E> cls = elementType();
Collection<? extends Element> elements = ancestorProvider().elements(language);
for(Element<?> element: elements) {
result.addAll(element.descendants(cls));
}
return result;
}
|
diff --git a/src/main/java/org/stwerff/msl/InitListener.java b/src/main/java/org/stwerff/msl/InitListener.java
index 0f8c990..eaba2ba 100644
--- a/src/main/java/org/stwerff/msl/InitListener.java
+++ b/src/main/java/org/stwerff/msl/InitListener.java
@@ -1,56 +1,55 @@
package org.stwerff.msl;
import java.io.InputStream;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.stwerff.mslagents.ClockAgent;
import com.almende.eve.agent.AgentFactory;
import com.almende.eve.config.Config;
import com.almende.eve.rpc.jsonrpc.JSONRequest;
import com.almende.eve.rpc.jsonrpc.jackson.JOM;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class InitListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent arg0) {
}
public void contextInitialized(ServletContextEvent ctx) {
InputStream is = ctx.getServletContext().getResourceAsStream(
"/WEB-INF/eve.yaml");
Config config = new Config(is);
try {
AgentFactory factory = new AgentFactory(config);
if (!factory.hasAgent("clock")) {
factory.createAgent(ClockAgent.class, "clock");
}
ClockAgent clock = (ClockAgent) factory.getAgent("clock");
- /*
- * for (String taskId : clock.getScheduler().getTasks()){
- * clock.getScheduler().cancelTask(taskId); }
- */
+ for (String taskId : clock.getScheduler().getTasks()) {
+ clock.getScheduler().cancelTask(taskId);
+ }
ObjectNode params = JOM.createObjectNode();
JSONRequest request = new JSONRequest("updateHeads", params);
long delay = 12000; // milliseconds
clock.getScheduler().createTask(request, delay);
request = new JSONRequest("updateSpice", params);
clock.getScheduler().createTask(request, delay);
params.put("reload", new Boolean(false));
delay = 2000;
request = new JSONRequest("updateSols", params);
clock.getScheduler().createTask(request, delay);
} catch (Exception e) {
System.err.println("ERROR initializing agents");
e.printStackTrace();
}
}
}
| true | true | public void contextInitialized(ServletContextEvent ctx) {
InputStream is = ctx.getServletContext().getResourceAsStream(
"/WEB-INF/eve.yaml");
Config config = new Config(is);
try {
AgentFactory factory = new AgentFactory(config);
if (!factory.hasAgent("clock")) {
factory.createAgent(ClockAgent.class, "clock");
}
ClockAgent clock = (ClockAgent) factory.getAgent("clock");
/*
* for (String taskId : clock.getScheduler().getTasks()){
* clock.getScheduler().cancelTask(taskId); }
*/
ObjectNode params = JOM.createObjectNode();
JSONRequest request = new JSONRequest("updateHeads", params);
long delay = 12000; // milliseconds
clock.getScheduler().createTask(request, delay);
request = new JSONRequest("updateSpice", params);
clock.getScheduler().createTask(request, delay);
params.put("reload", new Boolean(false));
delay = 2000;
request = new JSONRequest("updateSols", params);
clock.getScheduler().createTask(request, delay);
} catch (Exception e) {
System.err.println("ERROR initializing agents");
e.printStackTrace();
}
}
| public void contextInitialized(ServletContextEvent ctx) {
InputStream is = ctx.getServletContext().getResourceAsStream(
"/WEB-INF/eve.yaml");
Config config = new Config(is);
try {
AgentFactory factory = new AgentFactory(config);
if (!factory.hasAgent("clock")) {
factory.createAgent(ClockAgent.class, "clock");
}
ClockAgent clock = (ClockAgent) factory.getAgent("clock");
for (String taskId : clock.getScheduler().getTasks()) {
clock.getScheduler().cancelTask(taskId);
}
ObjectNode params = JOM.createObjectNode();
JSONRequest request = new JSONRequest("updateHeads", params);
long delay = 12000; // milliseconds
clock.getScheduler().createTask(request, delay);
request = new JSONRequest("updateSpice", params);
clock.getScheduler().createTask(request, delay);
params.put("reload", new Boolean(false));
delay = 2000;
request = new JSONRequest("updateSols", params);
clock.getScheduler().createTask(request, delay);
} catch (Exception e) {
System.err.println("ERROR initializing agents");
e.printStackTrace();
}
}
|
diff --git a/src/org/bouncycastle/crypto/prng/DigestRandomGenerator.java b/src/org/bouncycastle/crypto/prng/DigestRandomGenerator.java
index 6852af78..a0ba1080 100644
--- a/src/org/bouncycastle/crypto/prng/DigestRandomGenerator.java
+++ b/src/org/bouncycastle/crypto/prng/DigestRandomGenerator.java
@@ -1,96 +1,97 @@
package org.bouncycastle.crypto.prng;
import org.bouncycastle.crypto.Digest;
/**
* Random generation based on the digest with counter. Calling addSeedMaterial will
* always increase the entropy of the hash.
* <p>
* Internal access to the digest is syncrhonized so a single one of these can be shared.
* </p>
*/
public class DigestRandomGenerator
implements RandomGenerator
{
private long counter;
private Digest digest;
private byte[] state;
// public constructors
public DigestRandomGenerator(
Digest digest)
{
this.digest = digest;
this.state = new byte[digest.getDigestSize()];
this.counter = 1;
}
public void addSeedMaterial(byte[] inSeed)
{
synchronized (this)
{
digestUpdate(inSeed);
}
}
public void addSeedMaterial(long rSeed)
{
synchronized (this)
{
for (int i = 0; i != 8; i++)
{
digestUpdate((byte)rSeed);
rSeed >>>= 8;
}
}
}
public void nextBytes(byte[] bytes)
{
nextBytes(bytes, 0, bytes.length);
}
public void nextBytes(byte[] bytes, int start, int len)
{
synchronized (this)
{
int stateOff = 0;
digestDoFinal(state);
- for (int i = start; i != len; i++)
+ int end = start + len;
+ for (int i = start; i != end; i++)
{
if (stateOff == state.length)
{
digestUpdate(counter++);
digestUpdate(state);
digestDoFinal(state);
stateOff = 0;
}
bytes[i] = state[stateOff++];
}
digestUpdate(counter++);
digestUpdate(state);
}
}
private void digestUpdate(long seed)
{
for (int i = 0; i != 8; i++)
{
digest.update((byte)seed);
seed >>>= 8;
}
}
private void digestUpdate(byte[] inSeed)
{
digest.update(inSeed, 0, inSeed.length);
}
private void digestDoFinal(byte[] result)
{
digest.doFinal(result, 0);
}
}
| true | true | public void nextBytes(byte[] bytes, int start, int len)
{
synchronized (this)
{
int stateOff = 0;
digestDoFinal(state);
for (int i = start; i != len; i++)
{
if (stateOff == state.length)
{
digestUpdate(counter++);
digestUpdate(state);
digestDoFinal(state);
stateOff = 0;
}
bytes[i] = state[stateOff++];
}
digestUpdate(counter++);
digestUpdate(state);
}
}
| public void nextBytes(byte[] bytes, int start, int len)
{
synchronized (this)
{
int stateOff = 0;
digestDoFinal(state);
int end = start + len;
for (int i = start; i != end; i++)
{
if (stateOff == state.length)
{
digestUpdate(counter++);
digestUpdate(state);
digestDoFinal(state);
stateOff = 0;
}
bytes[i] = state[stateOff++];
}
digestUpdate(counter++);
digestUpdate(state);
}
}
|
diff --git a/src/main/java/biomesoplenty/common/eventhandler/entity/TemptEventHandler.java b/src/main/java/biomesoplenty/common/eventhandler/entity/TemptEventHandler.java
index 55f204858..0cd11b988 100644
--- a/src/main/java/biomesoplenty/common/eventhandler/entity/TemptEventHandler.java
+++ b/src/main/java/biomesoplenty/common/eventhandler/entity/TemptEventHandler.java
@@ -1,51 +1,51 @@
package biomesoplenty.common.eventhandler.entity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.ai.EntityAITasks;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import biomesoplenty.api.BOPItemHelper;
import biomesoplenty.common.entities.ai.EntityAITemptArmor;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class TemptEventHandler
{
@SubscribeEvent
public void onEntitySpawn(EntityJoinWorldEvent event)
{
Entity entity = event.entity;
if (!(entity instanceof EntityLiving))
return;
- //TODO: FEATURE Remove Reflection
- EntityAITasks tasks = ObfuscationReflectionHelper.getPrivateValue(EntityLiving.class, ((EntityLiving)entity), new String[] { "tasks" });
+ //TODO: FEATURE Remove Reflection tasks
+ EntityAITasks tasks = ObfuscationReflectionHelper.getPrivateValue(EntityLiving.class, ((EntityLiving)entity), new String[] { "field_75732_c" });
if (entity instanceof EntityChicken)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 0, false));
}
if (entity instanceof EntitySheep)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 1, false));
}
if (entity instanceof EntityPig)
{
tasks.addTask(4, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 2, false));
}
if (entity instanceof EntityCow)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 3, false));
}
}
}
| true | true | public void onEntitySpawn(EntityJoinWorldEvent event)
{
Entity entity = event.entity;
if (!(entity instanceof EntityLiving))
return;
//TODO: FEATURE Remove Reflection
EntityAITasks tasks = ObfuscationReflectionHelper.getPrivateValue(EntityLiving.class, ((EntityLiving)entity), new String[] { "tasks" });
if (entity instanceof EntityChicken)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 0, false));
}
if (entity instanceof EntitySheep)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 1, false));
}
if (entity instanceof EntityPig)
{
tasks.addTask(4, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 2, false));
}
if (entity instanceof EntityCow)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 3, false));
}
}
| public void onEntitySpawn(EntityJoinWorldEvent event)
{
Entity entity = event.entity;
if (!(entity instanceof EntityLiving))
return;
//TODO: FEATURE Remove Reflection tasks
EntityAITasks tasks = ObfuscationReflectionHelper.getPrivateValue(EntityLiving.class, ((EntityLiving)entity), new String[] { "field_75732_c" });
if (entity instanceof EntityChicken)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 0, false));
}
if (entity instanceof EntitySheep)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 1, false));
}
if (entity instanceof EntityPig)
{
tasks.addTask(4, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 2, false));
}
if (entity instanceof EntityCow)
{
tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 3, false));
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IView.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IView.java
index 221adbfa1..891d4f930 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IView.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IView.java
@@ -1,455 +1,458 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowCloseListener;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.ui.HasFocus;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.BrowserInfo;
import com.itmill.toolkit.terminal.gwt.client.Container;
import com.itmill.toolkit.terminal.gwt.client.Focusable;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.RenderSpace;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
/**
*
*/
public class IView extends SimplePanel implements Container,
WindowResizeListener, WindowCloseListener {
private static final String CLASSNAME = "i-view";
private String theme;
private Paintable layout;
private final HashSet subWindows = new HashSet();
private String id;
private ShortcutActionHandler actionHandler;
/** stored width for IE resize optimization */
private int width;
/** stored height for IE resize optimization */
private int height;
private ApplicationConnection connection;
/**
* We are postponing resize process with IE. IE bugs with scrollbars in some
* situations, that causes false onWindowResized calls. With Timer we will
* give IE some time to decide if it really wants to keep current size
* (scrollbars).
*/
private Timer resizeTimer;
public IView(String elementId) {
super();
setStyleName(CLASSNAME);
DOM.sinkEvents(getElement(), Event.ONKEYDOWN);
// iview is focused when created so element needs tabIndex
// 1 due 0 is at the end of natural tabbing order
DOM.setElementProperty(getElement(), "tabIndex", "1");
RootPanel.get(elementId).add(this);
RootPanel.get(elementId).removeStyleName("i-app-loading");
// set focus to iview element by default to listen possible keyboard
// shortcuts
if (BrowserInfo.get().isOpera() || BrowserInfo.get().isSafari()
&& BrowserInfo.get().getWebkitVersion() < 526) {
// old webkits don't support focusing div elements
Element fElem = DOM.createInputCheck();
DOM.setStyleAttribute(fElem, "margin", "0");
DOM.setStyleAttribute(fElem, "padding", "0");
DOM.setStyleAttribute(fElem, "border", "0");
DOM.setStyleAttribute(fElem, "outline", "0");
DOM.setStyleAttribute(fElem, "width", "1px");
DOM.setStyleAttribute(fElem, "height", "1px");
DOM.setStyleAttribute(fElem, "position", "absolute");
DOM.setStyleAttribute(fElem, "opacity", "0.1");
DOM.appendChild(getElement(), fElem);
focus(fElem);
} else {
focus(getElement());
}
}
private static native void focus(Element el)
/*-{
try {
el.focus();
} catch (e) {
}
}-*/;
public String getTheme() {
return theme;
}
/**
* Used to reload host page on theme changes.
*/
private static native void reloadHostPage()
/*-{
$wnd.location.reload();
}-*/;
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
boolean firstPaint = connection == null;
connection = client;
String newTheme = uidl.getStringAttribute("theme");
if (theme != null && !newTheme.equals(theme)) {
// Complete page refresh is needed due css can affect layout
// calculations etc
reloadHostPage();
} else {
theme = newTheme;
}
if (uidl.hasAttribute("style")) {
addStyleName(uidl.getStringAttribute("style"));
}
if (uidl.hasAttribute("name")) {
client.setWindowName(uidl.getStringAttribute("name"));
}
com.google.gwt.user.client.Window.setTitle(uidl
.getStringAttribute("caption"));
// Process children
int childIndex = 0;
// Open URL:s
boolean isClosed = false; // was this window closed?
while (childIndex < uidl.getChildCount()
&& "open".equals(uidl.getChildUIDL(childIndex).getTag())) {
final UIDL open = uidl.getChildUIDL(childIndex);
final String url = open.getStringAttribute("src");
final String target = open.getStringAttribute("name");
if (target == null) {
// This window is closing. Send close event before
// going to the new url
isClosed = true;
onWindowClosed();
goTo(url);
} else {
// TODO width & height
Window.open(url, target != null ? target : null, "");
}
childIndex++;
}
if (isClosed) {
// don't render the content
return;
}
// Draw this application level window
UIDL childUidl = uidl.getChildUIDL(childIndex);
final Paintable lo = client.getPaintable(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
// add new
setWidget((Widget) lo);
layout = lo;
}
} else {
setWidget((Widget) lo);
layout = lo;
}
layout.updateFromUIDL(childUidl, client);
// Update subwindows
final HashSet removedSubWindows = new HashSet(subWindows);
// Open new windows
while ((childUidl = uidl.getChildUIDL(childIndex++)) != null) {
if ("window".equals(childUidl.getTag())) {
final Paintable w = client.getPaintable(childUidl);
if (subWindows.contains(w)) {
removedSubWindows.remove(w);
} else {
subWindows.add(w);
}
w.updateFromUIDL(childUidl, client);
} else if ("actions".equals(childUidl.getTag())) {
if (actionHandler == null) {
actionHandler = new ShortcutActionHandler(id, client);
}
actionHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
for (final Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
final UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("icon")) {
final String parsedUri = client
.translateToolkitUri(notification
.getStringAttribute("icon"));
html += "<IMG src=\"" + parsedUri + "\" />";
}
if (notification.hasAttribute("caption")) {
html += "<H1>"
+ notification.getStringAttribute("caption")
+ "</H1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification.getStringAttribute("message")
+ "</p>";
}
final String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
final int position = notification
.getIntAttribute("position");
final int delay = notification.getIntAttribute("delay");
new INotification(delay).show(html, position, style);
}
}
}
// Close old windows
for (final Iterator rem = removedSubWindows.iterator(); rem.hasNext();) {
final IWindow w = (IWindow) rem.next();
client.unregisterPaintable(w);
subWindows.remove(w);
w.hide();
}
if (uidl.hasAttribute("focused")) {
final String focusPid = uidl.getStringAttribute("focused");
// set focused component when render phase is finished
DeferredCommand.addCommand(new Command() {
public void execute() {
final Paintable toBeFocused = connection
.getPaintable(focusPid);
/*
* Two types of Widgets can be focused, either implementing
* GWT HasFocus of a thinner Toolkit specific Focusable
* interface.
*/
if (toBeFocused instanceof HasFocus) {
final HasFocus toBeFocusedWidget = (HasFocus) toBeFocused;
toBeFocusedWidget.setFocus(true);
} else if (toBeFocused instanceof Focusable) {
((Focusable) toBeFocused).focus();
} else {
ApplicationConnection.getConsole().log(
"Could not focus component");
}
}
});
}
// Add window listeners on first paint, to prevent premature
// variablechanges
if (firstPaint) {
Window.addWindowCloseListener(this);
Window.addWindowResizeListener(this);
}
onWindowResized(Window.getClientWidth(), Window.getClientHeight());
// IE somehow fails some layout on first run, force layout
// functions
// client.runDescendentsLayout(this);
+ if (BrowserInfo.get().isSafari()) {
+ Util.runWebkitOverflowAutoFix(getElement());
+ }
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (DOM.eventGetType(event) == Event.ONKEYDOWN && actionHandler != null) {
actionHandler.handleKeyboardEvent(event);
return;
}
}
public void onWindowResized(int width, int height) {
if (Util.isIE()) {
/*
* IE will give us some false resized events due bugs with
* scrollbars. Postponing layout phase to see if size was really
* changed.
*/
if (resizeTimer == null) {
resizeTimer = new Timer() {
@Override
public void run() {
boolean changed = false;
if (IView.this.width != getOffsetWidth()) {
IView.this.width = getOffsetWidth();
changed = true;
ApplicationConnection.getConsole().log(
"window w" + IView.this.width);
}
if (IView.this.height != getOffsetHeight()) {
IView.this.height = getOffsetHeight();
changed = true;
ApplicationConnection.getConsole().log(
"window h" + IView.this.height);
}
if (changed) {
ApplicationConnection
.getConsole()
.log(
"Running layout functions due window resize");
connection.runDescendentsLayout(IView.this);
}
}
};
} else {
resizeTimer.cancel();
}
resizeTimer.schedule(200);
} else {
if (width == IView.this.width && height == IView.this.height) {
// No point in doing resize operations if window size has not
// changed
return;
}
IView.this.width = Window.getClientWidth();
IView.this.height = Window.getClientHeight();
// temporary set overflow hidden, not to let scrollbars disturb
// layout functions
final String overflow = DOM.getStyleAttribute(getElement(),
"overflow");
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
ApplicationConnection.getConsole().log(
"Running layout functions due window resize");
connection.runDescendentsLayout(this);
DOM.setStyleAttribute(getElement(), "overflow", overflow);
}
}
public native static void goTo(String url)
/*-{
$wnd.location = url;
}-*/;
public void onWindowClosed() {
// Change focus on this window in order to ensure that all state is
// collected from textfields
ITextField.flushChangesFromFocusedTextField();
// Send the closing state to server
connection.updateVariable(id, "close", true, false);
connection.sendPendingVariableChangesSync();
}
public String onWindowClosing() {
return null;
}
private final RenderSpace myRenderSpace = new RenderSpace() {
private int excessHeight = -1;
private int excessWidth = -1;
@Override
public int getHeight() {
return getElement().getOffsetHeight() - getExcessHeight();
}
private int getExcessHeight() {
if (excessHeight < 0) {
detectExcessSize();
}
return excessHeight;
}
private void detectExcessSize() {
final String overflow = getElement().getStyle().getProperty(
"overflow");
getElement().getStyle().setProperty("overflow", "hidden");
excessHeight = getElement().getOffsetHeight()
- getElement().getPropertyInt("clientHeight");
excessWidth = getElement().getOffsetWidth()
- getElement().getPropertyInt("clientWidth");
getElement().getStyle().setProperty("overflow", overflow);
}
@Override
public int getWidth() {
return getElement().getOffsetWidth() - getExcessWidth();
}
private int getExcessWidth() {
if (excessWidth < 0) {
detectExcessSize();
}
return excessWidth;
}
@Override
public int getScrollbarSize() {
return Util.getNativeScrollbarSize();
}
};
public RenderSpace getAllocatedSpace(Widget child) {
return myRenderSpace;
}
public boolean hasChildComponent(Widget component) {
return (component != null && component == layout);
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
// TODO Auto-generated method stub
}
public boolean requestLayout(Set<Paintable> child) {
/*
* Can never propagate further and we do not want need to re-layout the
* layout which has caused this request.
*/
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// TODO Auto-generated method stub
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
boolean firstPaint = connection == null;
connection = client;
String newTheme = uidl.getStringAttribute("theme");
if (theme != null && !newTheme.equals(theme)) {
// Complete page refresh is needed due css can affect layout
// calculations etc
reloadHostPage();
} else {
theme = newTheme;
}
if (uidl.hasAttribute("style")) {
addStyleName(uidl.getStringAttribute("style"));
}
if (uidl.hasAttribute("name")) {
client.setWindowName(uidl.getStringAttribute("name"));
}
com.google.gwt.user.client.Window.setTitle(uidl
.getStringAttribute("caption"));
// Process children
int childIndex = 0;
// Open URL:s
boolean isClosed = false; // was this window closed?
while (childIndex < uidl.getChildCount()
&& "open".equals(uidl.getChildUIDL(childIndex).getTag())) {
final UIDL open = uidl.getChildUIDL(childIndex);
final String url = open.getStringAttribute("src");
final String target = open.getStringAttribute("name");
if (target == null) {
// This window is closing. Send close event before
// going to the new url
isClosed = true;
onWindowClosed();
goTo(url);
} else {
// TODO width & height
Window.open(url, target != null ? target : null, "");
}
childIndex++;
}
if (isClosed) {
// don't render the content
return;
}
// Draw this application level window
UIDL childUidl = uidl.getChildUIDL(childIndex);
final Paintable lo = client.getPaintable(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
// add new
setWidget((Widget) lo);
layout = lo;
}
} else {
setWidget((Widget) lo);
layout = lo;
}
layout.updateFromUIDL(childUidl, client);
// Update subwindows
final HashSet removedSubWindows = new HashSet(subWindows);
// Open new windows
while ((childUidl = uidl.getChildUIDL(childIndex++)) != null) {
if ("window".equals(childUidl.getTag())) {
final Paintable w = client.getPaintable(childUidl);
if (subWindows.contains(w)) {
removedSubWindows.remove(w);
} else {
subWindows.add(w);
}
w.updateFromUIDL(childUidl, client);
} else if ("actions".equals(childUidl.getTag())) {
if (actionHandler == null) {
actionHandler = new ShortcutActionHandler(id, client);
}
actionHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
for (final Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
final UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("icon")) {
final String parsedUri = client
.translateToolkitUri(notification
.getStringAttribute("icon"));
html += "<IMG src=\"" + parsedUri + "\" />";
}
if (notification.hasAttribute("caption")) {
html += "<H1>"
+ notification.getStringAttribute("caption")
+ "</H1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification.getStringAttribute("message")
+ "</p>";
}
final String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
final int position = notification
.getIntAttribute("position");
final int delay = notification.getIntAttribute("delay");
new INotification(delay).show(html, position, style);
}
}
}
// Close old windows
for (final Iterator rem = removedSubWindows.iterator(); rem.hasNext();) {
final IWindow w = (IWindow) rem.next();
client.unregisterPaintable(w);
subWindows.remove(w);
w.hide();
}
if (uidl.hasAttribute("focused")) {
final String focusPid = uidl.getStringAttribute("focused");
// set focused component when render phase is finished
DeferredCommand.addCommand(new Command() {
public void execute() {
final Paintable toBeFocused = connection
.getPaintable(focusPid);
/*
* Two types of Widgets can be focused, either implementing
* GWT HasFocus of a thinner Toolkit specific Focusable
* interface.
*/
if (toBeFocused instanceof HasFocus) {
final HasFocus toBeFocusedWidget = (HasFocus) toBeFocused;
toBeFocusedWidget.setFocus(true);
} else if (toBeFocused instanceof Focusable) {
((Focusable) toBeFocused).focus();
} else {
ApplicationConnection.getConsole().log(
"Could not focus component");
}
}
});
}
// Add window listeners on first paint, to prevent premature
// variablechanges
if (firstPaint) {
Window.addWindowCloseListener(this);
Window.addWindowResizeListener(this);
}
onWindowResized(Window.getClientWidth(), Window.getClientHeight());
// IE somehow fails some layout on first run, force layout
// functions
// client.runDescendentsLayout(this);
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
boolean firstPaint = connection == null;
connection = client;
String newTheme = uidl.getStringAttribute("theme");
if (theme != null && !newTheme.equals(theme)) {
// Complete page refresh is needed due css can affect layout
// calculations etc
reloadHostPage();
} else {
theme = newTheme;
}
if (uidl.hasAttribute("style")) {
addStyleName(uidl.getStringAttribute("style"));
}
if (uidl.hasAttribute("name")) {
client.setWindowName(uidl.getStringAttribute("name"));
}
com.google.gwt.user.client.Window.setTitle(uidl
.getStringAttribute("caption"));
// Process children
int childIndex = 0;
// Open URL:s
boolean isClosed = false; // was this window closed?
while (childIndex < uidl.getChildCount()
&& "open".equals(uidl.getChildUIDL(childIndex).getTag())) {
final UIDL open = uidl.getChildUIDL(childIndex);
final String url = open.getStringAttribute("src");
final String target = open.getStringAttribute("name");
if (target == null) {
// This window is closing. Send close event before
// going to the new url
isClosed = true;
onWindowClosed();
goTo(url);
} else {
// TODO width & height
Window.open(url, target != null ? target : null, "");
}
childIndex++;
}
if (isClosed) {
// don't render the content
return;
}
// Draw this application level window
UIDL childUidl = uidl.getChildUIDL(childIndex);
final Paintable lo = client.getPaintable(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
// add new
setWidget((Widget) lo);
layout = lo;
}
} else {
setWidget((Widget) lo);
layout = lo;
}
layout.updateFromUIDL(childUidl, client);
// Update subwindows
final HashSet removedSubWindows = new HashSet(subWindows);
// Open new windows
while ((childUidl = uidl.getChildUIDL(childIndex++)) != null) {
if ("window".equals(childUidl.getTag())) {
final Paintable w = client.getPaintable(childUidl);
if (subWindows.contains(w)) {
removedSubWindows.remove(w);
} else {
subWindows.add(w);
}
w.updateFromUIDL(childUidl, client);
} else if ("actions".equals(childUidl.getTag())) {
if (actionHandler == null) {
actionHandler = new ShortcutActionHandler(id, client);
}
actionHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
for (final Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
final UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("icon")) {
final String parsedUri = client
.translateToolkitUri(notification
.getStringAttribute("icon"));
html += "<IMG src=\"" + parsedUri + "\" />";
}
if (notification.hasAttribute("caption")) {
html += "<H1>"
+ notification.getStringAttribute("caption")
+ "</H1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification.getStringAttribute("message")
+ "</p>";
}
final String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
final int position = notification
.getIntAttribute("position");
final int delay = notification.getIntAttribute("delay");
new INotification(delay).show(html, position, style);
}
}
}
// Close old windows
for (final Iterator rem = removedSubWindows.iterator(); rem.hasNext();) {
final IWindow w = (IWindow) rem.next();
client.unregisterPaintable(w);
subWindows.remove(w);
w.hide();
}
if (uidl.hasAttribute("focused")) {
final String focusPid = uidl.getStringAttribute("focused");
// set focused component when render phase is finished
DeferredCommand.addCommand(new Command() {
public void execute() {
final Paintable toBeFocused = connection
.getPaintable(focusPid);
/*
* Two types of Widgets can be focused, either implementing
* GWT HasFocus of a thinner Toolkit specific Focusable
* interface.
*/
if (toBeFocused instanceof HasFocus) {
final HasFocus toBeFocusedWidget = (HasFocus) toBeFocused;
toBeFocusedWidget.setFocus(true);
} else if (toBeFocused instanceof Focusable) {
((Focusable) toBeFocused).focus();
} else {
ApplicationConnection.getConsole().log(
"Could not focus component");
}
}
});
}
// Add window listeners on first paint, to prevent premature
// variablechanges
if (firstPaint) {
Window.addWindowCloseListener(this);
Window.addWindowResizeListener(this);
}
onWindowResized(Window.getClientWidth(), Window.getClientHeight());
// IE somehow fails some layout on first run, force layout
// functions
// client.runDescendentsLayout(this);
if (BrowserInfo.get().isSafari()) {
Util.runWebkitOverflowAutoFix(getElement());
}
}
|
diff --git a/lib/src/java/org/j2free/jsp/tags/cache/ResultHTMLCacheTag.java b/lib/src/java/org/j2free/jsp/tags/cache/ResultHTMLCacheTag.java
index cc9f6dd..212289e 100644
--- a/lib/src/java/org/j2free/jsp/tags/cache/ResultHTMLCacheTag.java
+++ b/lib/src/java/org/j2free/jsp/tags/cache/ResultHTMLCacheTag.java
@@ -1,193 +1,196 @@
/*
* ResultHTMLCacheTag.java
*
* Created on September 30, 2008, 9:12 AM
*/
package org.j2free.jsp.tags.cache;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.j2free.etc.ServletUtils.*;
/**
* Generated tag handler class.
* @author ryan
* @version
*/
public class ResultHTMLCacheTag extends BodyTagSupport {
private static final Log log = LogFactory.getLog(ResultHTMLCacheTag.class);
private static final String ATTRIBUTE_DISABLE_GLOBALLY = "disable-html-cache";
private static final String ATTRIBUTE_DISABLE_ONCE = "nocache";
private static HashMap<String,String> cache;
private static HashMap<String,Long> cacheTimestamps;
private static HashMap<String,String> cacheConditions;
/**
* @TODO implement cron expression based expiration to allow for easy definition
* of expiration times in absolute terms
*/
// Cache Timeout
// -1 will force expiration and the result will not be cached
private long timeout;
// Cache Key
private String key;
// Cache Condition, used to specify a value to monitor for a change
private String condition;
private boolean disable;
static {
cache = new HashMap<String,String>(200);
cacheTimestamps = new HashMap<String,Long>(200);
cacheConditions = new HashMap<String,String>(200);
}
public ResultHTMLCacheTag() {
super();
disable = false;
}
public void setKey(String key) {
this.key = key;
}
public void setCondition(String condition) {
this.condition = condition;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public void setDisable(boolean disable) {
this.disable = disable;
}
@Override
public int doStartTag() throws JspException {
String globalDisableFlag = (String)pageContext.getServletContext().getAttribute(ATTRIBUTE_DISABLE_GLOBALLY);
if (globalDisableFlag != null && !disable) {
log.trace("globalDisableFlag = " + globalDisableFlag);
try {
disable = Boolean.parseBoolean(globalDisableFlag);
} catch (Exception e) {
log.warn("Invalid value for " + ATTRIBUTE_DISABLE_GLOBALLY + " context-param: " + globalDisableFlag + ", expected [true|false]");
disable = false;
}
}
/**
* Reasons to evaluate the body:
* 1. Nothing is cached under the key
* 2. The nocache attribute is set
* 3. the disable attribute is set
*/
if (!cache.containsKey(key) || pageContext.getAttribute(ATTRIBUTE_DISABLE_ONCE) != null || disable) {
if (log.isTraceEnabled()) {
log.trace("Evaluating body: [key=" + key + ",containsKey=" + cache.containsKey(key) + ",nocache=" + (pageContext.getAttribute(ATTRIBUTE_DISABLE_ONCE) != null) + ",disable=" + disable + "]");
}
log.debug("Evaluating body for key: " + key);
return EVAL_BODY_BUFFERED;
}
long now = System.currentTimeMillis();
long exp = 0;
- if (cacheTimestamps != null && !cacheTimestamps.isEmpty()) {
- exp = (Long)cacheTimestamps.get(key) + timeout;
+ if (cacheTimestamps != null && !cacheTimestamps.isEmpty() && key != null) {
+ Long temp = (Long)cacheTimestamps.get(key) + timeout;
+ if (temp != null) {
+ exp = temp;
+ }
}
/**
* Reasons to evaluate the body:
* 1. The cache timeout has occurred
* 2. There is a cacheCondition saved, the condition attribute is set, and the condition attribute does not match the saved condition
*/
if (exp <= now || (cacheConditions.containsKey(key) && !empty(condition) && !cacheConditions.get(key).equals(condition))) {
if (log.isTraceEnabled()) {
log.trace("Evaluating body: [key=" + key + ",exp=" + exp + ",now=" + now + ",cacheCondition.containsKey=" + cacheConditions.containsKey(key) + ",!empty(condition)=" + !empty(condition) + "]");
if (cacheConditions.containsKey(key) && !empty(condition)) {
log.trace("cacheConditions.get(" + key + ").equals(" + condition + ") = " + cacheConditions.get(key).equals(condition));
}
}
log.debug("Evaluating body for key: " + key);
return EVAL_BODY_BUFFERED;
}
try {
log.debug("Writing cached body for key: " + key);
pageContext.getOut().print(cache.get(key));
} catch (IOException ex) {
throw new JspException(ex);
}
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
@Override
public int doAfterBody() throws JspException {
// Get the BodyContent object
BodyContent bc = getBodyContent();
try {
// Write the output to the page
bc.writeOut(bc.getEnclosingWriter());
} catch (IOException ex) {
throw new JspException(ex);
}
if (disable)
return SKIP_BODY;
if (timeout == -1) {
// Clear any cached value
cache.remove(key);
cacheTimestamps.remove(key);
cacheConditions.remove(key);
log.debug("Clearing cached body for key: " + key);
} else {
// Cache the result
cache.put(key,bc.getString());
cacheTimestamps.put(key,System.currentTimeMillis());
if (!empty(condition)) {
if (log.isTraceEnabled()) {
log.trace("Cache condition exists, adding to map [key=" + key + ",condition=" + condition + "]");
}
log.debug("Caching body for key: " + key);
cacheConditions.put(key,condition);
}
}
return SKIP_BODY;
}
}
| true | true | public int doStartTag() throws JspException {
String globalDisableFlag = (String)pageContext.getServletContext().getAttribute(ATTRIBUTE_DISABLE_GLOBALLY);
if (globalDisableFlag != null && !disable) {
log.trace("globalDisableFlag = " + globalDisableFlag);
try {
disable = Boolean.parseBoolean(globalDisableFlag);
} catch (Exception e) {
log.warn("Invalid value for " + ATTRIBUTE_DISABLE_GLOBALLY + " context-param: " + globalDisableFlag + ", expected [true|false]");
disable = false;
}
}
/**
* Reasons to evaluate the body:
* 1. Nothing is cached under the key
* 2. The nocache attribute is set
* 3. the disable attribute is set
*/
if (!cache.containsKey(key) || pageContext.getAttribute(ATTRIBUTE_DISABLE_ONCE) != null || disable) {
if (log.isTraceEnabled()) {
log.trace("Evaluating body: [key=" + key + ",containsKey=" + cache.containsKey(key) + ",nocache=" + (pageContext.getAttribute(ATTRIBUTE_DISABLE_ONCE) != null) + ",disable=" + disable + "]");
}
log.debug("Evaluating body for key: " + key);
return EVAL_BODY_BUFFERED;
}
long now = System.currentTimeMillis();
long exp = 0;
if (cacheTimestamps != null && !cacheTimestamps.isEmpty()) {
exp = (Long)cacheTimestamps.get(key) + timeout;
}
/**
* Reasons to evaluate the body:
* 1. The cache timeout has occurred
* 2. There is a cacheCondition saved, the condition attribute is set, and the condition attribute does not match the saved condition
*/
if (exp <= now || (cacheConditions.containsKey(key) && !empty(condition) && !cacheConditions.get(key).equals(condition))) {
if (log.isTraceEnabled()) {
log.trace("Evaluating body: [key=" + key + ",exp=" + exp + ",now=" + now + ",cacheCondition.containsKey=" + cacheConditions.containsKey(key) + ",!empty(condition)=" + !empty(condition) + "]");
if (cacheConditions.containsKey(key) && !empty(condition)) {
log.trace("cacheConditions.get(" + key + ").equals(" + condition + ") = " + cacheConditions.get(key).equals(condition));
}
}
log.debug("Evaluating body for key: " + key);
return EVAL_BODY_BUFFERED;
}
try {
log.debug("Writing cached body for key: " + key);
pageContext.getOut().print(cache.get(key));
} catch (IOException ex) {
throw new JspException(ex);
}
return SKIP_BODY;
}
| public int doStartTag() throws JspException {
String globalDisableFlag = (String)pageContext.getServletContext().getAttribute(ATTRIBUTE_DISABLE_GLOBALLY);
if (globalDisableFlag != null && !disable) {
log.trace("globalDisableFlag = " + globalDisableFlag);
try {
disable = Boolean.parseBoolean(globalDisableFlag);
} catch (Exception e) {
log.warn("Invalid value for " + ATTRIBUTE_DISABLE_GLOBALLY + " context-param: " + globalDisableFlag + ", expected [true|false]");
disable = false;
}
}
/**
* Reasons to evaluate the body:
* 1. Nothing is cached under the key
* 2. The nocache attribute is set
* 3. the disable attribute is set
*/
if (!cache.containsKey(key) || pageContext.getAttribute(ATTRIBUTE_DISABLE_ONCE) != null || disable) {
if (log.isTraceEnabled()) {
log.trace("Evaluating body: [key=" + key + ",containsKey=" + cache.containsKey(key) + ",nocache=" + (pageContext.getAttribute(ATTRIBUTE_DISABLE_ONCE) != null) + ",disable=" + disable + "]");
}
log.debug("Evaluating body for key: " + key);
return EVAL_BODY_BUFFERED;
}
long now = System.currentTimeMillis();
long exp = 0;
if (cacheTimestamps != null && !cacheTimestamps.isEmpty() && key != null) {
Long temp = (Long)cacheTimestamps.get(key) + timeout;
if (temp != null) {
exp = temp;
}
}
/**
* Reasons to evaluate the body:
* 1. The cache timeout has occurred
* 2. There is a cacheCondition saved, the condition attribute is set, and the condition attribute does not match the saved condition
*/
if (exp <= now || (cacheConditions.containsKey(key) && !empty(condition) && !cacheConditions.get(key).equals(condition))) {
if (log.isTraceEnabled()) {
log.trace("Evaluating body: [key=" + key + ",exp=" + exp + ",now=" + now + ",cacheCondition.containsKey=" + cacheConditions.containsKey(key) + ",!empty(condition)=" + !empty(condition) + "]");
if (cacheConditions.containsKey(key) && !empty(condition)) {
log.trace("cacheConditions.get(" + key + ").equals(" + condition + ") = " + cacheConditions.get(key).equals(condition));
}
}
log.debug("Evaluating body for key: " + key);
return EVAL_BODY_BUFFERED;
}
try {
log.debug("Writing cached body for key: " + key);
pageContext.getOut().print(cache.get(key));
} catch (IOException ex) {
throw new JspException(ex);
}
return SKIP_BODY;
}
|
diff --git a/src/test/java/org/dita/dost/platform/FileGeneratorTest.java b/src/test/java/org/dita/dost/platform/FileGeneratorTest.java
index a765ed083..b3b6b97a8 100644
--- a/src/test/java/org/dita/dost/platform/FileGeneratorTest.java
+++ b/src/test/java/org/dita/dost/platform/FileGeneratorTest.java
@@ -1,127 +1,128 @@
/*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
package org.dita.dost.platform;
import static org.junit.Assert.assertEquals;
import org.dita.dost.TestUtils;
import org.dita.dost.log.DITAOTLogger;
import org.dita.dost.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.helpers.AttributesImpl;
public class FileGeneratorTest {
final File resourceDir = TestUtils.getResourceDir(FileGeneratorTest.class);
private File tempDir;
private static File tempFile;
private final static Hashtable<String, String> features = new Hashtable<String, String>();
static {
features.put("element", "foo,bar,baz");
features.put("attribute", "foo,bar,baz");
}
private final static Map<String, Features> plugins = new HashMap<String, Features>();
static {
final Features a = new Features(null, null);
final AttributesImpl aAtts = new AttributesImpl();
aAtts.addAttribute("", "value", "value", "CDATA", "foo,bar,baz");
aAtts.addAttribute("", "type", "type", "CDATA", "text");
a.addFeature("element", aAtts);
plugins.put("a", a);
final Features b = new Features(null, null);
final AttributesImpl bAtts = new AttributesImpl();
bAtts.addAttribute("", "value", "value", "CDATA", "foo,bar,baz");
bAtts.addAttribute("", "type", "type", "CDATA", "text");
b.addFeature("attribute", bAtts);
plugins.put("b", b);
}
@Before
public void setUp() throws Exception {
tempDir = TestUtils.createTempDir(getClass());
tempFile = new File(tempDir, "dummy_template.xml");
FileUtils.copyFile(new File(resourceDir, "src" + File.separator + "dummy_template.xml"),
tempFile);
}
@Test
public void testGenerate() throws IOException {
final FileGenerator f = new FileGenerator(features, plugins);
f.generate(tempFile);
assertEquals(TestUtils.readFileToString(new File(resourceDir, "exp" + File.separator + "dummy.xml")),
TestUtils.readFileToString(new File(tempDir, "dummy.xml")));
}
@After
public void tearDown() throws IOException {
TestUtils.forceDelete(tempDir);
}
private static abstract class AbstractAction implements IAction {
protected List<String> inputs = new ArrayList<String>();
protected Map<String, String> params = new HashMap<String, String>();
protected Map<String, Features> features;
public void setInput(final String input) {
final StringTokenizer inputTokenizer = new StringTokenizer(input, Integrator.FEAT_VALUE_SEPARATOR);
while(inputTokenizer.hasMoreElements()){
inputs.add(inputTokenizer.nextToken());
}
}
public void addParam(final String name, final String value) {
params.put(name, value);
}
public void setFeatures(final Map<String, Features> features) {
this.features = features;
}
public abstract String getResult();
public void setLogger(final DITAOTLogger logger) {
// NOOP
}
}
public static class ElementAction extends AbstractAction {
@Override
public String getResult() {
final Map<String, String> paramsExp = new HashMap<String, String>();
paramsExp.put(FileGenerator.PARAM_TEMPLATE, tempFile.getAbsolutePath());
- paramsExp.put("extension", "element");
+ paramsExp.put("id", "element");
+ paramsExp.put("behavior", this.getClass().getName());
assertEquals(paramsExp, params);
final List<String> inputExp = Arrays.asList(new String[] {"foo", "bar", "baz"});
assertEquals(inputExp, inputs);
assertEquals(FileGeneratorTest.plugins, features);
return "<foo bar='baz'>quz</foo>";
}
}
public static class AttributeAction extends AbstractAction {
@Override
public String getResult() {
final Map<String, String> paramsExp = new HashMap<String, String>();
paramsExp.put(FileGenerator.PARAM_TEMPLATE, tempFile.getAbsolutePath());
paramsExp.put(FileGenerator.PARAM_LOCALNAME, "foo");
assertEquals(paramsExp, params);
final List<String> inputExp = Arrays.asList(new String[] {"attribute"});
assertEquals(inputExp, inputs);
assertEquals(FileGeneratorTest.plugins, features);
return " foo='bar'";
}
}
}
| true | true | public String getResult() {
final Map<String, String> paramsExp = new HashMap<String, String>();
paramsExp.put(FileGenerator.PARAM_TEMPLATE, tempFile.getAbsolutePath());
paramsExp.put("extension", "element");
assertEquals(paramsExp, params);
final List<String> inputExp = Arrays.asList(new String[] {"foo", "bar", "baz"});
assertEquals(inputExp, inputs);
assertEquals(FileGeneratorTest.plugins, features);
return "<foo bar='baz'>quz</foo>";
}
| public String getResult() {
final Map<String, String> paramsExp = new HashMap<String, String>();
paramsExp.put(FileGenerator.PARAM_TEMPLATE, tempFile.getAbsolutePath());
paramsExp.put("id", "element");
paramsExp.put("behavior", this.getClass().getName());
assertEquals(paramsExp, params);
final List<String> inputExp = Arrays.asList(new String[] {"foo", "bar", "baz"});
assertEquals(inputExp, inputs);
assertEquals(FileGeneratorTest.plugins, features);
return "<foo bar='baz'>quz</foo>";
}
|
diff --git a/weaver/src/org/aspectj/weaver/AsmAdaptor.java b/weaver/src/org/aspectj/weaver/AsmAdaptor.java
index ba84390f9..15e94274e 100644
--- a/weaver/src/org/aspectj/weaver/AsmAdaptor.java
+++ b/weaver/src/org/aspectj/weaver/AsmAdaptor.java
@@ -1,199 +1,202 @@
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 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:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.Iterator;
import org.aspectj.asm.AdviceAssociation;
import org.aspectj.asm.LinkNode;
import org.aspectj.asm.ProgramElementNode;
import org.aspectj.asm.Relation;
import org.aspectj.asm.RelationNode;
import org.aspectj.asm.StructureModel;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
public class AsmAdaptor {
public static void noteMunger(StructureModel model, Shadow shadow, ShadowMunger munger) {
if (munger instanceof Advice) {
Advice a = (Advice)munger;
if (a.getKind().isPerEntry() || a.getKind().isCflow()) {
// ??? might want to show these in the future
return;
}
// System.out.println("--------------------------");
ProgramElementNode targetNode = getNode(model, shadow);
ProgramElementNode adviceNode = getNode(model, a);
Relation relation;
if (shadow.getKind().equals(Shadow.FieldGet) || shadow.getKind().equals(Shadow.FieldSet)) {
relation = AdviceAssociation.FIELD_ACCESS_RELATION;
} else if (shadow.getKind().equals(Shadow.Initialization) || shadow.getKind().equals(Shadow.StaticInitialization)) {
relation = AdviceAssociation.INITIALIZER_RELATION;
} else if (shadow.getKind().equals(Shadow.ExceptionHandler)) {
relation = AdviceAssociation.HANDLER_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodCall)) {
relation = AdviceAssociation.METHOD_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorCall)) {
relation = AdviceAssociation.CONSTRUCTOR_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodExecution) || shadow.getKind().equals(Shadow.AdviceExecution)) {
relation = AdviceAssociation.METHOD_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorExecution)) {
relation = AdviceAssociation.CONSTRUCTOR_RELATION;
+ } else if (shadow.getKind().equals(Shadow.PreInitialization)) {
+ // TODO: someone should check that this behaves reasonably in the IDEs
+ relation = AdviceAssociation.INITIALIZER_RELATION;
} else {
System.err.println("> unmatched relation: " + shadow.getKind());
relation = AdviceAssociation.METHOD_RELATION;
}
// System.out.println("> target: " + targetNode + ", advice: " + adviceNode);
createAppropriateLinks(targetNode, adviceNode, relation);
}
}
private static void createAppropriateLinks(
ProgramElementNode target,
ProgramElementNode advice,
Relation relation)
{
if (target == null || advice == null) return;
addLink(target, new LinkNode(advice), relation, true);
addLink(advice, new LinkNode(target), relation, false);
// System.out.println(">> added target: " + target.getProgramElementKind() + ", advice: " + advice);
// System.out.println(">> target: " + target + ", advice: " + target.getSourceLocation());
}
private static void addLink(
ProgramElementNode onNode,
LinkNode linkNode,
Relation relation,
boolean isBack)
{
RelationNode node = null;
String relationName = isBack ? relation.getBackNavigationName() : relation.getForwardNavigationName();
//System.err.println("on: " + onNode + " relationName: " + relationName + " existin: " + onNode.getRelations());
for (Iterator i = onNode.getRelations().iterator(); i.hasNext();) {
RelationNode relationNode = (RelationNode) i.next();
if (relationName.equals(relationNode.getName())) {
node = relationNode;
break;
}
}
if (node == null) {
node = new RelationNode(relation, relationName, new ArrayList());
onNode.getRelations().add(node);
}
node.getChildren().add(linkNode);
}
private static ProgramElementNode getNode(StructureModel model, Advice a) {
//ResolvedTypeX inAspect = a.getConcreteAspect();
Member member = a.getSignature();
if (a.getSignature() == null) return null;
return lookupMember(model, member);
}
private static ProgramElementNode getNode(StructureModel model, Shadow shadow) {
Member enclosingMember = shadow.getEnclosingCodeSignature();
ProgramElementNode enclosingNode = lookupMember(model, enclosingMember);
if (enclosingNode == null) {
Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure;
if (err.isEnabled()) {
err.signal(shadow.toString(), shadow.getSourceLocation());
}
return null;
}
Member shadowSig = shadow.getSignature();
if (!shadowSig.equals(enclosingMember)) {
ProgramElementNode bodyNode = findOrCreateBodyNode(enclosingNode, shadowSig, shadow);
return bodyNode;
} else {
return enclosingNode;
}
}
private static ProgramElementNode findOrCreateBodyNode(
ProgramElementNode enclosingNode,
Member shadowSig, Shadow shadow)
{
for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode node = (ProgramElementNode)it.next();
if (shadowSig.getName().equals(node.getBytecodeName()) &&
shadowSig.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
ISourceLocation sl = shadow.getSourceLocation();
ProgramElementNode peNode = new ProgramElementNode(
shadow.toString(),
ProgramElementNode.Kind.CODE,
//XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()),
new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()),
// enclosingNode.getSourceLocation(),
0,
"",
new ArrayList());
//System.err.println(peNode.getSourceLocation());
peNode.setBytecodeName(shadowSig.getName());
peNode.setBytecodeSignature(shadowSig.getSignature());
enclosingNode.addChild(peNode);
return peNode;
}
public static ProgramElementNode lookupMember(StructureModel model, Member member) {
TypeX declaringType = member.getDeclaringType();
ProgramElementNode classNode =
model.findNodeForClass(declaringType.getPackageName(), declaringType.getClassName());
return findMemberInClass(classNode, member);
}
private static ProgramElementNode findMemberInClass(
ProgramElementNode classNode,
Member member)
{
if (classNode == null) return null; // XXX remove this check
for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode node = (ProgramElementNode)it.next();
//System.err.println("checking: " + member.getName() + " with " + node.getBytecodeName() + ", " + node.getBytecodeSignature());
if (member.getName().equals(node.getBytecodeName()) &&
member.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
// if we can't find the member, we'll just put it in the class
return classNode;
}
}
| true | true | public static void noteMunger(StructureModel model, Shadow shadow, ShadowMunger munger) {
if (munger instanceof Advice) {
Advice a = (Advice)munger;
if (a.getKind().isPerEntry() || a.getKind().isCflow()) {
// ??? might want to show these in the future
return;
}
// System.out.println("--------------------------");
ProgramElementNode targetNode = getNode(model, shadow);
ProgramElementNode adviceNode = getNode(model, a);
Relation relation;
if (shadow.getKind().equals(Shadow.FieldGet) || shadow.getKind().equals(Shadow.FieldSet)) {
relation = AdviceAssociation.FIELD_ACCESS_RELATION;
} else if (shadow.getKind().equals(Shadow.Initialization) || shadow.getKind().equals(Shadow.StaticInitialization)) {
relation = AdviceAssociation.INITIALIZER_RELATION;
} else if (shadow.getKind().equals(Shadow.ExceptionHandler)) {
relation = AdviceAssociation.HANDLER_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodCall)) {
relation = AdviceAssociation.METHOD_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorCall)) {
relation = AdviceAssociation.CONSTRUCTOR_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodExecution) || shadow.getKind().equals(Shadow.AdviceExecution)) {
relation = AdviceAssociation.METHOD_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorExecution)) {
relation = AdviceAssociation.CONSTRUCTOR_RELATION;
} else {
System.err.println("> unmatched relation: " + shadow.getKind());
relation = AdviceAssociation.METHOD_RELATION;
}
// System.out.println("> target: " + targetNode + ", advice: " + adviceNode);
createAppropriateLinks(targetNode, adviceNode, relation);
}
}
| public static void noteMunger(StructureModel model, Shadow shadow, ShadowMunger munger) {
if (munger instanceof Advice) {
Advice a = (Advice)munger;
if (a.getKind().isPerEntry() || a.getKind().isCflow()) {
// ??? might want to show these in the future
return;
}
// System.out.println("--------------------------");
ProgramElementNode targetNode = getNode(model, shadow);
ProgramElementNode adviceNode = getNode(model, a);
Relation relation;
if (shadow.getKind().equals(Shadow.FieldGet) || shadow.getKind().equals(Shadow.FieldSet)) {
relation = AdviceAssociation.FIELD_ACCESS_RELATION;
} else if (shadow.getKind().equals(Shadow.Initialization) || shadow.getKind().equals(Shadow.StaticInitialization)) {
relation = AdviceAssociation.INITIALIZER_RELATION;
} else if (shadow.getKind().equals(Shadow.ExceptionHandler)) {
relation = AdviceAssociation.HANDLER_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodCall)) {
relation = AdviceAssociation.METHOD_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorCall)) {
relation = AdviceAssociation.CONSTRUCTOR_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodExecution) || shadow.getKind().equals(Shadow.AdviceExecution)) {
relation = AdviceAssociation.METHOD_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorExecution)) {
relation = AdviceAssociation.CONSTRUCTOR_RELATION;
} else if (shadow.getKind().equals(Shadow.PreInitialization)) {
// TODO: someone should check that this behaves reasonably in the IDEs
relation = AdviceAssociation.INITIALIZER_RELATION;
} else {
System.err.println("> unmatched relation: " + shadow.getKind());
relation = AdviceAssociation.METHOD_RELATION;
}
// System.out.println("> target: " + targetNode + ", advice: " + adviceNode);
createAppropriateLinks(targetNode, adviceNode, relation);
}
}
|
diff --git a/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/LdapGroupSearchQueryTest.java b/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/LdapGroupSearchQueryTest.java
index 5ad86231b..98443a20f 100644
--- a/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/LdapGroupSearchQueryTest.java
+++ b/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/LdapGroupSearchQueryTest.java
@@ -1,46 +1,46 @@
package org.ovirt.engine.core.bll;
import java.util.Arrays;
import java.util.Collection;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.ovirt.engine.core.bll.adbroker.AdActionType;
import org.ovirt.engine.core.bll.adbroker.LdapQueryType;
import org.ovirt.engine.core.common.businessentities.ad_groups;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.AdGroupsSearchParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.compat.Guid;
@RunWith(Parameterized.class)
public class LdapGroupSearchQueryTest extends LdapSearchQueryTestBase {
public LdapGroupSearchQueryTest(Class<? extends SearchQuery<? extends SearchParameters>> queryType,
SearchParameters queryParamters) {
super(queryType, queryParamters);
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]
{ { SearchQuery.class, new SearchParameters("AdGroup: name=" + NAME_TO_SEARCH, SearchType.AdGroup) },
- { AdGroupsSearchQuery.class, new AdGroupsSearchParameters(NAME_TO_SEARCH) } });
+ { AdGroupsSearchQuery.class, new AdGroupsSearchParameters("name=" + NAME_TO_SEARCH) } });
}
@Override
protected ad_groups getExpectedResult() {
return new ad_groups(Guid.NewGuid(), NAME_TO_SEARCH, DOMAIN);
}
@Override
protected AdActionType getAdActionType() {
return AdActionType.SearchGroupsByQuery;
}
@Override
protected LdapQueryType getLdapActionType() {
return LdapQueryType.searchGroups;
}
}
| true | true | public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]
{ { SearchQuery.class, new SearchParameters("AdGroup: name=" + NAME_TO_SEARCH, SearchType.AdGroup) },
{ AdGroupsSearchQuery.class, new AdGroupsSearchParameters(NAME_TO_SEARCH) } });
}
| public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]
{ { SearchQuery.class, new SearchParameters("AdGroup: name=" + NAME_TO_SEARCH, SearchType.AdGroup) },
{ AdGroupsSearchQuery.class, new AdGroupsSearchParameters("name=" + NAME_TO_SEARCH) } });
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java
index 2e1fe1f1..04f50b58 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java
@@ -1,461 +1,461 @@
/*
* Copyright (C) 2011-2012 asksven
*
* 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.asksven.betterbatterystats.adapters;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.asksven.android.common.privateapiproxies.NativeKernelWakelock;
import com.asksven.android.common.kernelutils.State;
import com.asksven.android.common.nameutils.UidNameResolver;
import com.asksven.android.common.privateapiproxies.Alarm;
import com.asksven.android.common.privateapiproxies.AlarmItem;
import com.asksven.android.common.privateapiproxies.Misc;
import com.asksven.android.common.privateapiproxies.Process;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.asksven.betterbatterystats.data.GoogleAnalytics;
import com.asksven.betterbatterystats.data.KbData;
import com.asksven.betterbatterystats.data.KbEntry;
import com.asksven.betterbatterystats.data.KbReader;
import com.asksven.betterbatterystats.widgets.GraphableBars;
import com.asksven.betterbatterystats.widgets.GraphablePie;
import com.asksven.betterbatterystats.HelpActivity;
import com.asksven.betterbatterystats.PackageInfoTabsPager;
import com.asksven.betterbatterystats.R;
public class StatsAdapter extends BaseAdapter
{
private Context m_context;
private List<StatElement> m_listData;
private static final String TAG = "StatsAdapter";
private double m_maxValue = 0;
public StatsAdapter(Context context, List<StatElement> listData)
{
this.m_context = context;
this.m_listData = listData;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bKbEnabled = sharedPrefs.getBoolean("enable_kb", true);
if (m_listData != null)
{
for (int i = 0; i < m_listData.size(); i++)
{
StatElement g = m_listData.get(i);
// @todo refactor Misc instead. For now the change is here as I don't want to break the deserialization
if (g instanceof Misc)
{
m_maxValue = ((Misc)g).getTimeRunning();
}
else if (!((g instanceof Process) || (g instanceof Alarm)))
{
m_maxValue = g.getTotal();
}
else
{
double[] values = g.getValues();
m_maxValue = Math.max(m_maxValue, values[values.length - 1]);
m_maxValue = Math.max(m_maxValue, g.getMaxValue());
}
}
}
}
public int getCount()
{
if (m_listData != null)
{
return m_listData.size();
}
else
{
return 0;
}
}
public Object getItem(int position)
{
return m_listData.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup)
{
StatElement entry = m_listData.get(position);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bShowBars = sharedPrefs.getBoolean("show_gauge", false);
Log.i(TAG, "Values: " +entry.getVals());
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) m_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// depending on settings show new pie gauge or old bar gauge
if (!bShowBars)
{
convertView = inflater.inflate(R.layout.stat_row, null);
}
else
{
convertView = inflater.inflate(R.layout.stat_row_gauge, null);
}
}
TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName);
tvName.setText(entry.getName());
KbData kb = KbReader.getInstance().read(m_context);
KbEntry kbentry = null;
if (kb != null)
{
kbentry = kb.findByStatElement(entry.getName(), entry.getFqn(UidNameResolver.getInstance(m_context)));
}
boolean bShowKb = sharedPrefs.getBoolean("enable_kb", true);
ImageView iconKb = (ImageView) convertView.findViewById(R.id.imageKB);
if ( (bShowKb) && (kbentry != null))
{
iconKb.setVisibility(View.VISIBLE);
}
else
{
iconKb.setVisibility(View.INVISIBLE);
}
TextView tvFqn = (TextView) convertView.findViewById(R.id.TextViewFqn);
tvFqn.setText(entry.getFqn(UidNameResolver.getInstance(m_context)));
TextView tvData = (TextView) convertView.findViewById(R.id.TextViewData);
tvData.setText(entry.getData());
//LinearLayout myLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutBar);
LinearLayout myFqnLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutFqn);
LinearLayout myRow = (LinearLayout) convertView.findViewById(R.id.LinearLayoutEntry);
// long press for "copy to clipboard"
- //myRow.setOnLongClickListener(new OnItemLongClickListener(position));
+ convertView.setOnLongClickListener(new OnItemLongClickListener(position));
if (!bShowBars)
{
GraphablePie gauge = (GraphablePie) convertView.findViewById(R.id.Gauge);
if (entry instanceof Misc)
{
gauge.setValue(entry.getValues()[0], ((Misc) entry).getTimeRunning());
}
else
{
gauge.setValue(entry.getValues()[0], m_maxValue);
}
}
else
{
GraphableBars buttonBar = (GraphableBars) convertView.findViewById(R.id.ButtonBar);
int iHeight = 10;
try
{
iHeight = Integer.valueOf(sharedPrefs.getString("graph_bar_height", "10"));
}
catch (Exception e)
{
iHeight = 10;
}
if (iHeight == 0)
{
iHeight = 10;
}
buttonBar.setMinimumHeight(iHeight);
buttonBar.setName(entry.getName());
buttonBar.setValues(entry.getValues(), m_maxValue);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
// add on click listener for the icon only if KB is enabled
if (bShowKb)
{
// set a click listener for the list
iconKb.setOnClickListener(new OnIconClickListener(position));
}
// show / hide fqn text
if ((entry instanceof Process) || (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
myFqnLayout.setVisibility(View.GONE);
}
else
{
myFqnLayout.setVisibility(View.VISIBLE);
}
// show / hide package icons
if ((entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
iconView.setVisibility(View.GONE);
}
else
{
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(entry.getIcon(UidNameResolver.getInstance(m_context)));
// set a click listener for the list
iconView.setOnClickListener(new OnPackageClickListener(position));
}
// add on click listener for the list entry if details are availble
if ( (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) )
{
convertView.setOnClickListener(new OnItemClickListener(position));
}
// // show / hide set dividers
// ListView myList = (ListView) convertView.getListView(); //findViewById(R.id.id.list);
// myList.setDivider(new ColorDrawable(0x99F10529));
// myList.setDividerHeight(1);
return convertView;
}
/**
* Handler for on click of the KB icon
* @author sven
*
*/
private class OnIconClickListener implements OnClickListener
{
private int m_iPosition;
OnIconClickListener(int position)
{
m_iPosition = position;
}
@Override
public void onClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
KbData kb = KbReader.getInstance().read(m_context);
// the timing may lead to m_kb not being initialized yet, it must be checked
if (kb == null)
{
return;
}
KbEntry kbentry = kb.findByStatElement(entry.getName(), entry.getFqn(UidNameResolver.getInstance(StatsAdapter.this.m_context)));
if (kbentry != null)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(StatsAdapter.this.m_context);
String url = kbentry.getUrl();
if (sharedPrefs.getBoolean("kb_ext_browser", true))
{
Intent intent = new Intent("android.intent.action.VIEW",
Uri.parse(url));
StatsAdapter.this.m_context.startActivity(intent);
}
else
{
Intent intentKB = new Intent(StatsAdapter.this.m_context,
HelpActivity.class);
intentKB.putExtra("url", url);
StatsAdapter.this.m_context.startActivity(intentKB);
}
}
}
}
/**
* Handler for on click of the KB icon
* @author sven
*
*/
private class OnPackageClickListener implements OnClickListener
{
private int m_iPosition;
OnPackageClickListener(int position)
{
m_iPosition = position;
}
@Override
public void onClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
Context ctx = arg0.getContext();
if (entry.getIcon(UidNameResolver.getInstance(m_context)) == null)
{
return;
}
// ctx.startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS));
String packageName = entry.getPackageName();
showInstalledPackageDetails(ctx, packageName);
}
}
/**
* Handler for the on click of the list item
* @author sven
*
*/
private class OnItemClickListener implements OnClickListener
{
private int m_iPosition;
OnItemClickListener(int position)
{
m_iPosition = position;
}
@Override
public void onClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
if (entry instanceof Alarm)
{
Alarm alarmEntry = (Alarm) getItem(m_iPosition);
Dialog dialog = new Dialog(m_context);
dialog.setContentView(R.layout.alarms_dialog);
dialog.setTitle(entry.getName());
TextView title = (TextView) dialog.findViewById(R.id.title);
// TextView subtitle = (TextView) dialog.findViewById(R.id.subtitle);
TextView text = (TextView) dialog.findViewById(R.id.text);
title.setText(entry.getData());
String strText = "";
ArrayList<AlarmItem> myItems = alarmEntry.getItems();
if (myItems != null)
{
for (int i=0; i<myItems.size(); i++)
{
if (myItems.get(i).getCount() > 0)
{
strText = strText + myItems.get(i).getData() + "\n\n";
}
}
}
text.setText(strText);
dialog.show();
}
if (entry instanceof NativeKernelWakelock)
{
NativeKernelWakelock kernelWakelockEntry = (NativeKernelWakelock) getItem(m_iPosition);
Dialog dialog = new Dialog(m_context);
dialog.setContentView(R.layout.alarms_dialog);
dialog.setTitle(kernelWakelockEntry.getName());
TextView title = (TextView) dialog.findViewById(R.id.title);
// TextView subtitle = (TextView) dialog.findViewById(R.id.subtitle);
TextView text = (TextView) dialog.findViewById(R.id.text);
title.setText(kernelWakelockEntry.getData());
String strText = "";
strText += "Count: " + kernelWakelockEntry.getCount() + "\n";
strText += "Expire Count: " + kernelWakelockEntry.getExpireCount() + "\n";
strText += "Wake Count: " + kernelWakelockEntry.getWakeCount() + "\n";
strText += "Total Time: "+ kernelWakelockEntry.getTtlTime() + "\n";
strText += "Sleep Time: " + kernelWakelockEntry.getSleepTime() + "\n";
strText += "Max Time: " + kernelWakelockEntry.getMaxTime() + "\n";
text.setText(strText);
dialog.show();
}
}
}
/**
* Handler for the on click of the list item
* @author sven
*
*/
private class OnItemLongClickListener implements OnLongClickListener
{
private int m_iPosition;
OnItemLongClickListener(int position)
{
m_iPosition = position;
}
@SuppressLint("NewApi")
@Override
public boolean onLongClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
{
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) m_context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(entry.getName());
}
else
{
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) m_context.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", entry.getName());
clipboard.setPrimaryClip(clip);
}
Toast.makeText(m_context, entry.getName() + " was copied to the clipboard", Toast.LENGTH_LONG).show();
return true;
}
}
public static void showInstalledPackageDetails(Context context, String packageName)
{
Intent intentPerms = new Intent(context, PackageInfoTabsPager.class); //Activity.class);
intentPerms.putExtra("package", packageName);
GoogleAnalytics.getInstance(context).trackPage(GoogleAnalytics.ACTIVITY_PERMS);
context.startActivity(intentPerms);
}
}
| true | true | public View getView(int position, View convertView, ViewGroup viewGroup)
{
StatElement entry = m_listData.get(position);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bShowBars = sharedPrefs.getBoolean("show_gauge", false);
Log.i(TAG, "Values: " +entry.getVals());
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) m_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// depending on settings show new pie gauge or old bar gauge
if (!bShowBars)
{
convertView = inflater.inflate(R.layout.stat_row, null);
}
else
{
convertView = inflater.inflate(R.layout.stat_row_gauge, null);
}
}
TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName);
tvName.setText(entry.getName());
KbData kb = KbReader.getInstance().read(m_context);
KbEntry kbentry = null;
if (kb != null)
{
kbentry = kb.findByStatElement(entry.getName(), entry.getFqn(UidNameResolver.getInstance(m_context)));
}
boolean bShowKb = sharedPrefs.getBoolean("enable_kb", true);
ImageView iconKb = (ImageView) convertView.findViewById(R.id.imageKB);
if ( (bShowKb) && (kbentry != null))
{
iconKb.setVisibility(View.VISIBLE);
}
else
{
iconKb.setVisibility(View.INVISIBLE);
}
TextView tvFqn = (TextView) convertView.findViewById(R.id.TextViewFqn);
tvFqn.setText(entry.getFqn(UidNameResolver.getInstance(m_context)));
TextView tvData = (TextView) convertView.findViewById(R.id.TextViewData);
tvData.setText(entry.getData());
//LinearLayout myLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutBar);
LinearLayout myFqnLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutFqn);
LinearLayout myRow = (LinearLayout) convertView.findViewById(R.id.LinearLayoutEntry);
// long press for "copy to clipboard"
//myRow.setOnLongClickListener(new OnItemLongClickListener(position));
if (!bShowBars)
{
GraphablePie gauge = (GraphablePie) convertView.findViewById(R.id.Gauge);
if (entry instanceof Misc)
{
gauge.setValue(entry.getValues()[0], ((Misc) entry).getTimeRunning());
}
else
{
gauge.setValue(entry.getValues()[0], m_maxValue);
}
}
else
{
GraphableBars buttonBar = (GraphableBars) convertView.findViewById(R.id.ButtonBar);
int iHeight = 10;
try
{
iHeight = Integer.valueOf(sharedPrefs.getString("graph_bar_height", "10"));
}
catch (Exception e)
{
iHeight = 10;
}
if (iHeight == 0)
{
iHeight = 10;
}
buttonBar.setMinimumHeight(iHeight);
buttonBar.setName(entry.getName());
buttonBar.setValues(entry.getValues(), m_maxValue);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
// add on click listener for the icon only if KB is enabled
if (bShowKb)
{
// set a click listener for the list
iconKb.setOnClickListener(new OnIconClickListener(position));
}
// show / hide fqn text
if ((entry instanceof Process) || (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
myFqnLayout.setVisibility(View.GONE);
}
else
{
myFqnLayout.setVisibility(View.VISIBLE);
}
// show / hide package icons
if ((entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
iconView.setVisibility(View.GONE);
}
else
{
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(entry.getIcon(UidNameResolver.getInstance(m_context)));
// set a click listener for the list
iconView.setOnClickListener(new OnPackageClickListener(position));
}
// add on click listener for the list entry if details are availble
if ( (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) )
{
convertView.setOnClickListener(new OnItemClickListener(position));
}
// // show / hide set dividers
// ListView myList = (ListView) convertView.getListView(); //findViewById(R.id.id.list);
// myList.setDivider(new ColorDrawable(0x99F10529));
// myList.setDividerHeight(1);
return convertView;
}
| public View getView(int position, View convertView, ViewGroup viewGroup)
{
StatElement entry = m_listData.get(position);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bShowBars = sharedPrefs.getBoolean("show_gauge", false);
Log.i(TAG, "Values: " +entry.getVals());
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) m_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// depending on settings show new pie gauge or old bar gauge
if (!bShowBars)
{
convertView = inflater.inflate(R.layout.stat_row, null);
}
else
{
convertView = inflater.inflate(R.layout.stat_row_gauge, null);
}
}
TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName);
tvName.setText(entry.getName());
KbData kb = KbReader.getInstance().read(m_context);
KbEntry kbentry = null;
if (kb != null)
{
kbentry = kb.findByStatElement(entry.getName(), entry.getFqn(UidNameResolver.getInstance(m_context)));
}
boolean bShowKb = sharedPrefs.getBoolean("enable_kb", true);
ImageView iconKb = (ImageView) convertView.findViewById(R.id.imageKB);
if ( (bShowKb) && (kbentry != null))
{
iconKb.setVisibility(View.VISIBLE);
}
else
{
iconKb.setVisibility(View.INVISIBLE);
}
TextView tvFqn = (TextView) convertView.findViewById(R.id.TextViewFqn);
tvFqn.setText(entry.getFqn(UidNameResolver.getInstance(m_context)));
TextView tvData = (TextView) convertView.findViewById(R.id.TextViewData);
tvData.setText(entry.getData());
//LinearLayout myLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutBar);
LinearLayout myFqnLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutFqn);
LinearLayout myRow = (LinearLayout) convertView.findViewById(R.id.LinearLayoutEntry);
// long press for "copy to clipboard"
convertView.setOnLongClickListener(new OnItemLongClickListener(position));
if (!bShowBars)
{
GraphablePie gauge = (GraphablePie) convertView.findViewById(R.id.Gauge);
if (entry instanceof Misc)
{
gauge.setValue(entry.getValues()[0], ((Misc) entry).getTimeRunning());
}
else
{
gauge.setValue(entry.getValues()[0], m_maxValue);
}
}
else
{
GraphableBars buttonBar = (GraphableBars) convertView.findViewById(R.id.ButtonBar);
int iHeight = 10;
try
{
iHeight = Integer.valueOf(sharedPrefs.getString("graph_bar_height", "10"));
}
catch (Exception e)
{
iHeight = 10;
}
if (iHeight == 0)
{
iHeight = 10;
}
buttonBar.setMinimumHeight(iHeight);
buttonBar.setName(entry.getName());
buttonBar.setValues(entry.getValues(), m_maxValue);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
// add on click listener for the icon only if KB is enabled
if (bShowKb)
{
// set a click listener for the list
iconKb.setOnClickListener(new OnIconClickListener(position));
}
// show / hide fqn text
if ((entry instanceof Process) || (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
myFqnLayout.setVisibility(View.GONE);
}
else
{
myFqnLayout.setVisibility(View.VISIBLE);
}
// show / hide package icons
if ((entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
iconView.setVisibility(View.GONE);
}
else
{
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(entry.getIcon(UidNameResolver.getInstance(m_context)));
// set a click listener for the list
iconView.setOnClickListener(new OnPackageClickListener(position));
}
// add on click listener for the list entry if details are availble
if ( (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) )
{
convertView.setOnClickListener(new OnItemClickListener(position));
}
// // show / hide set dividers
// ListView myList = (ListView) convertView.getListView(); //findViewById(R.id.id.list);
// myList.setDivider(new ColorDrawable(0x99F10529));
// myList.setDividerHeight(1);
return convertView;
}
|
diff --git a/src/SetIterator.java b/src/SetIterator.java
index 5c61cf9..f6ff948 100644
--- a/src/SetIterator.java
+++ b/src/SetIterator.java
@@ -1,124 +1,128 @@
import java.util.Iterator;
/**
* This class implements an Iterator for Sets
*
* @author OOP Gruppe 187
*/
public class SetIterator<T> implements Iterator<T> {
private Integer lastIndexReturned;
private Set<T> cursor;
private Set<T> entries;
/**
* Default constructor
*/
public SetIterator() {
this.lastIndexReturned = -1;
this.cursor = null;
this.entries = null;
}
/**
* Constructor with one parameter
*
* @param start
* The Set were the iterator is used
*/
public SetIterator(Set<T> start) {
this.cursor = start;
this.entries = start;
this.lastIndexReturned = -1;
}
/**
* @return true if the iteration has more elements, false otherwise
*/
@Override
public boolean hasNext() {
return this.cursor != null && cursor.getValue() != null;
}
/**
* @return the next element of the iteration.
*/
@Override
public T next() {
if (this.hasNext()) {
T result = this.cursor.getValue();
this.lastIndexReturned++;
this.cursor = this.cursor.getNext();
return result;
} else {
return null;
}
}
/**
* Removes the last element returned by the iterator
*/
@Override
public void remove() {
if(this.lastIndexReturned == -1) {
throw new RuntimeException("SetIterator: next() was never called");
} else if(this.lastIndexReturned == 0 && hasNext()) {
// there is a next element and we remove the 1st element
this.entries.setValue(this.entries.getNext().getValue());
this.entries.setNext(this.entries.getNext().getNext());
} else if(this.lastIndexReturned == 0 && !hasNext()) {
// there is no next element and we remove the 1st element
this.entries.setValue(null);
this.entries.setNext(null);
} else {
Set<T> previous = null;
Set<T> current = entries;
for(int i = 0; i < this.lastIndexReturned; i++) {
if(i == this.lastIndexReturned - 1) {
previous = current;
}
- current = current.getNext();
+ if(current != null) {
+ current = current.getNext();
+ } else {
+ this.lastIndexReturned = -1;
+ }
}
- if(current.getNext() != null) {
+ if(current != null && current.getNext() != null) {
previous.setNext(current.getNext());
- } else {
+ } else if(lastIndexReturned != -1){
previous.setNext(null);
}
}
}
/**
* getter for the set behind the iterator
* @return set behind the iterator
*/
public Set<T> getEntries() {
return entries;
}
/**
* setter for the set the iterator points to; used by InMapIterator
* @param entries
*/
protected void setEntries(Set<T> entries) {
this.entries = entries;
}
/**
* getter for the current element the iterator points to; similar to peek()
* @return the current posiiton of the iterator
*/
public Set<T> getCursor() {
return cursor;
}
public Integer getLastIndexReturned() {
return lastIndexReturned;
}
public void setCursor(Set<T> cursor) {
this.cursor = cursor;
}
}
| false | true | public void remove() {
if(this.lastIndexReturned == -1) {
throw new RuntimeException("SetIterator: next() was never called");
} else if(this.lastIndexReturned == 0 && hasNext()) {
// there is a next element and we remove the 1st element
this.entries.setValue(this.entries.getNext().getValue());
this.entries.setNext(this.entries.getNext().getNext());
} else if(this.lastIndexReturned == 0 && !hasNext()) {
// there is no next element and we remove the 1st element
this.entries.setValue(null);
this.entries.setNext(null);
} else {
Set<T> previous = null;
Set<T> current = entries;
for(int i = 0; i < this.lastIndexReturned; i++) {
if(i == this.lastIndexReturned - 1) {
previous = current;
}
current = current.getNext();
}
if(current.getNext() != null) {
previous.setNext(current.getNext());
} else {
previous.setNext(null);
}
}
}
| public void remove() {
if(this.lastIndexReturned == -1) {
throw new RuntimeException("SetIterator: next() was never called");
} else if(this.lastIndexReturned == 0 && hasNext()) {
// there is a next element and we remove the 1st element
this.entries.setValue(this.entries.getNext().getValue());
this.entries.setNext(this.entries.getNext().getNext());
} else if(this.lastIndexReturned == 0 && !hasNext()) {
// there is no next element and we remove the 1st element
this.entries.setValue(null);
this.entries.setNext(null);
} else {
Set<T> previous = null;
Set<T> current = entries;
for(int i = 0; i < this.lastIndexReturned; i++) {
if(i == this.lastIndexReturned - 1) {
previous = current;
}
if(current != null) {
current = current.getNext();
} else {
this.lastIndexReturned = -1;
}
}
if(current != null && current.getNext() != null) {
previous.setNext(current.getNext());
} else if(lastIndexReturned != -1){
previous.setNext(null);
}
}
}
|
diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java
index d8527cf23..21f914a75 100644
--- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java
+++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java
@@ -1,378 +1,378 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.RuntimeBeanNameReference;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Helper class for use in bean factory implementations,
* resolving values contained in bean definition objects
* into the actual values applied to the target bean instance.
*
* <p>Operates on an {@link AbstractBeanFactory} and a plain
* {@link org.springframework.beans.factory.config.BeanDefinition} object.
* Used by {@link AbstractAutowireCapableBeanFactory}.
*
* @author Juergen Hoeller
* @since 1.2
* @see AbstractAutowireCapableBeanFactory
*/
class BeanDefinitionValueResolver {
private final AbstractBeanFactory beanFactory;
private final String beanName;
private final BeanDefinition beanDefinition;
private final TypeConverter typeConverter;
/**
* Create a BeanDefinitionValueResolver for the given BeanFactory and BeanDefinition.
* @param beanFactory the BeanFactory to resolve against
* @param beanName the name of the bean that we work on
* @param beanDefinition the BeanDefinition of the bean that we work on
* @param typeConverter the TypeConverter to use for resolving TypedStringValues
*/
public BeanDefinitionValueResolver(
AbstractBeanFactory beanFactory, String beanName, BeanDefinition beanDefinition, TypeConverter typeConverter) {
this.beanFactory = beanFactory;
this.beanName = beanName;
this.beanDefinition = beanDefinition;
this.typeConverter = typeConverter;
}
/**
* Given a PropertyValue, return a value, resolving any references to other
* beans in the factory if necessary. The value could be:
* <li>A BeanDefinition, which leads to the creation of a corresponding
* new bean instance. Singleton flags and names of such "inner beans"
* are always ignored: Inner beans are anonymous prototypes.
* <li>A RuntimeBeanReference, which must be resolved.
* <li>A ManagedList. This is a special collection that may contain
* RuntimeBeanReferences or Collections that will need to be resolved.
* <li>A ManagedSet. May also contain RuntimeBeanReferences or
* Collections that will need to be resolved.
* <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
* or Collection that will need to be resolved.
* <li>An ordinary object or <code>null</code>, in which case it's left alone.
* @param argName the name of the argument that the value is defined for
* @param value the value object to resolve
* @return the resolved object
*/
public Object resolveValueIfNecessary(Object argName, Object value) {
// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) {
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(evaluate(refName));
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
else if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) {
// Resolve plain BeanDefinition, without contained name: use dummy name.
BeanDefinition bd = (BeanDefinition) value;
return resolveInnerBean(argName, "(inner bean)", bd);
}
else if (value instanceof ManagedArray) {
// May need to resolve contained runtime references.
ManagedArray array = (ManagedArray) value;
Class elementType = array.resolvedElementType;
if (elementType == null) {
String elementTypeName = array.getElementTypeName();
if (StringUtils.hasText(elementTypeName)) {
try {
elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
array.resolvedElementType = elementType;
}
catch (Throwable ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error resolving array type for " + argName, ex);
}
}
else {
elementType = Object.class;
}
}
return resolveManagedArray(argName, (List<?>) value, elementType);
}
else if (value instanceof ManagedList) {
// May need to resolve contained runtime references.
return resolveManagedList(argName, (List<?>) value);
}
else if (value instanceof ManagedSet) {
// May need to resolve contained runtime references.
return resolveManagedSet(argName, (Set<?>) value);
}
else if (value instanceof ManagedMap) {
// May need to resolve contained runtime references.
return resolveManagedMap(argName, (Map<?, ?>) value);
}
else if (value instanceof ManagedProperties) {
Properties original = (Properties) value;
Properties copy = new Properties();
for (Map.Entry propEntry : original.entrySet()) {
Object propKey = propEntry.getKey();
Object propValue = propEntry.getValue();
if (propKey instanceof TypedStringValue) {
- propKey = ((TypedStringValue) propKey).getValue();
+ propKey = evaluate(((TypedStringValue) propKey).getValue());
}
if (propValue instanceof TypedStringValue) {
- propValue = ((TypedStringValue) propValue).getValue();
+ propValue = evaluate(((TypedStringValue) propValue).getValue());
}
copy.put(propKey, propValue);
}
return copy;
}
else if (value instanceof TypedStringValue) {
// Convert value to target type here.
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue.getValue());
try {
Class resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) {
return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
else {
return valueObject;
}
}
catch (Throwable ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting typed String value for " + argName, ex);
}
}
else {
return evaluate(value);
}
}
/**
* Evaluate the given value as an expression, if necessary.
* @param value the candidate value (may be an expression)
* @return the resolved value
*/
protected Object evaluate(Object value) {
if (value instanceof String) {
return this.beanFactory.evaluateBeanDefinitionString((String) value, this.beanDefinition);
}
else {
return value;
}
}
/**
* Resolve the target type in the given TypedStringValue.
* @param value the TypedStringValue to resolve
* @return the resolved target type (or <code>null</code> if none specified)
* @throws ClassNotFoundException if the specified type cannot be resolved
* @see TypedStringValue#resolveTargetType
*/
protected Class resolveTargetType(TypedStringValue value) throws ClassNotFoundException {
if (value.hasTargetType()) {
return value.getTargetType();
}
return value.resolveTargetType(this.beanFactory.getBeanClassLoader());
}
/**
* Resolve an inner bean definition.
* @param argName the name of the argument that the inner bean is defined for
* @param innerBeanName the name of the inner bean
* @param innerBd the bean definition for the inner bean
* @return the resolved inner bean instance
*/
private Object resolveInnerBean(Object argName, String innerBeanName, BeanDefinition innerBd) {
RootBeanDefinition mbd = null;
try {
mbd = this.beanFactory.getMergedBeanDefinition(innerBeanName, innerBd, this.beanDefinition);
// Check given bean name whether it is unique. If not already unique,
// add counter - increasing the counter until the name is unique.
String actualInnerBeanName = innerBeanName;
if (mbd.isSingleton()) {
actualInnerBeanName = adaptInnerBeanName(innerBeanName);
}
// Guarantee initialization of beans that the inner bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
this.beanFactory.getBean(dependsOnBean);
this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName);
}
}
Object innerBean = this.beanFactory.createBean(actualInnerBeanName, mbd, null);
this.beanFactory.registerContainedBean(actualInnerBeanName, this.beanName);
if (innerBean instanceof FactoryBean) {
boolean synthetic = (mbd != null && mbd.isSynthetic());
return this.beanFactory.getObjectFromFactoryBean((FactoryBean) innerBean, actualInnerBeanName, !synthetic);
}
else {
return innerBean;
}
}
catch (BeansException ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Cannot create inner bean '" + innerBeanName + "' " +
(mbd != null && mbd.getBeanClassName() != null ? "of type [" + mbd.getBeanClassName() + "] " : "") +
"while setting " + argName, ex);
}
}
/**
* Checks the given bean name whether it is unique. If not already unique,
* a counter is added, increasing the counter until the name is unique.
* @param innerBeanName the original name for the inner bean
* @return the adapted name for the inner bean
*/
private String adaptInnerBeanName(String innerBeanName) {
String actualInnerBeanName = innerBeanName;
int counter = 0;
while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) {
counter++;
actualInnerBeanName = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter;
}
return actualInnerBeanName;
}
/**
* Resolve a reference to another bean in the factory.
*/
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
String refName = ref.getBeanName();
refName = String.valueOf(evaluate(refName));
if (ref.isToParent()) {
if (this.beanFactory.getParentBeanFactory() == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Can't resolve reference to bean '" + refName +
"' in parent factory: no parent factory available");
}
return this.beanFactory.getParentBeanFactory().getBean(refName);
}
else {
Object bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
return bean;
}
}
catch (BeansException ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
}
}
/**
* For each element in the managed array, resolve reference if necessary.
*/
private Object resolveManagedArray(Object argName, List<?> ml, Class elementType) {
Object resolved = Array.newInstance(elementType, ml.size());
for (int i = 0; i < ml.size(); i++) {
Array.set(resolved, i,
resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
ml.get(i)));
}
return resolved;
}
/**
* For each element in the managed list, resolve reference if necessary.
*/
private List resolveManagedList(Object argName, List<?> ml) {
List<Object> resolved = new ArrayList<Object>(ml.size());
for (int i = 0; i < ml.size(); i++) {
resolved.add(
resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
ml.get(i)));
}
return resolved;
}
/**
* For each element in the managed set, resolve reference if necessary.
*/
private Set resolveManagedSet(Object argName, Set<?> ms) {
Set<Object> resolved = new LinkedHashSet<Object>(ms.size());
int i = 0;
for (Object m : ms) {
resolved.add(resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX, m));
i++;
}
return resolved;
}
/**
* For each element in the managed map, resolve reference if necessary.
*/
private Map resolveManagedMap(Object argName, Map<?, ?> mm) {
Map<Object, Object> resolved = new LinkedHashMap<Object, Object>(mm.size());
for (Map.Entry entry : mm.entrySet()) {
Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey());
Object resolvedValue = resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + entry.getKey() +
BeanWrapper.PROPERTY_KEY_SUFFIX, entry.getValue());
resolved.put(resolvedKey, resolvedValue);
}
return resolved;
}
}
| false | true | public Object resolveValueIfNecessary(Object argName, Object value) {
// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) {
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(evaluate(refName));
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
else if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) {
// Resolve plain BeanDefinition, without contained name: use dummy name.
BeanDefinition bd = (BeanDefinition) value;
return resolveInnerBean(argName, "(inner bean)", bd);
}
else if (value instanceof ManagedArray) {
// May need to resolve contained runtime references.
ManagedArray array = (ManagedArray) value;
Class elementType = array.resolvedElementType;
if (elementType == null) {
String elementTypeName = array.getElementTypeName();
if (StringUtils.hasText(elementTypeName)) {
try {
elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
array.resolvedElementType = elementType;
}
catch (Throwable ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error resolving array type for " + argName, ex);
}
}
else {
elementType = Object.class;
}
}
return resolveManagedArray(argName, (List<?>) value, elementType);
}
else if (value instanceof ManagedList) {
// May need to resolve contained runtime references.
return resolveManagedList(argName, (List<?>) value);
}
else if (value instanceof ManagedSet) {
// May need to resolve contained runtime references.
return resolveManagedSet(argName, (Set<?>) value);
}
else if (value instanceof ManagedMap) {
// May need to resolve contained runtime references.
return resolveManagedMap(argName, (Map<?, ?>) value);
}
else if (value instanceof ManagedProperties) {
Properties original = (Properties) value;
Properties copy = new Properties();
for (Map.Entry propEntry : original.entrySet()) {
Object propKey = propEntry.getKey();
Object propValue = propEntry.getValue();
if (propKey instanceof TypedStringValue) {
propKey = ((TypedStringValue) propKey).getValue();
}
if (propValue instanceof TypedStringValue) {
propValue = ((TypedStringValue) propValue).getValue();
}
copy.put(propKey, propValue);
}
return copy;
}
else if (value instanceof TypedStringValue) {
// Convert value to target type here.
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue.getValue());
try {
Class resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) {
return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
else {
return valueObject;
}
}
catch (Throwable ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting typed String value for " + argName, ex);
}
}
else {
return evaluate(value);
}
}
| public Object resolveValueIfNecessary(Object argName, Object value) {
// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) {
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(evaluate(refName));
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
else if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) {
// Resolve plain BeanDefinition, without contained name: use dummy name.
BeanDefinition bd = (BeanDefinition) value;
return resolveInnerBean(argName, "(inner bean)", bd);
}
else if (value instanceof ManagedArray) {
// May need to resolve contained runtime references.
ManagedArray array = (ManagedArray) value;
Class elementType = array.resolvedElementType;
if (elementType == null) {
String elementTypeName = array.getElementTypeName();
if (StringUtils.hasText(elementTypeName)) {
try {
elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
array.resolvedElementType = elementType;
}
catch (Throwable ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error resolving array type for " + argName, ex);
}
}
else {
elementType = Object.class;
}
}
return resolveManagedArray(argName, (List<?>) value, elementType);
}
else if (value instanceof ManagedList) {
// May need to resolve contained runtime references.
return resolveManagedList(argName, (List<?>) value);
}
else if (value instanceof ManagedSet) {
// May need to resolve contained runtime references.
return resolveManagedSet(argName, (Set<?>) value);
}
else if (value instanceof ManagedMap) {
// May need to resolve contained runtime references.
return resolveManagedMap(argName, (Map<?, ?>) value);
}
else if (value instanceof ManagedProperties) {
Properties original = (Properties) value;
Properties copy = new Properties();
for (Map.Entry propEntry : original.entrySet()) {
Object propKey = propEntry.getKey();
Object propValue = propEntry.getValue();
if (propKey instanceof TypedStringValue) {
propKey = evaluate(((TypedStringValue) propKey).getValue());
}
if (propValue instanceof TypedStringValue) {
propValue = evaluate(((TypedStringValue) propValue).getValue());
}
copy.put(propKey, propValue);
}
return copy;
}
else if (value instanceof TypedStringValue) {
// Convert value to target type here.
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue.getValue());
try {
Class resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) {
return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
else {
return valueObject;
}
}
catch (Throwable ex) {
// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting typed String value for " + argName, ex);
}
}
else {
return evaluate(value);
}
}
|
diff --git a/src/net/sourcewalker/garanbot/data/GaranbotDBHelper.java b/src/net/sourcewalker/garanbot/data/GaranbotDBHelper.java
index a1de29d..62ef434 100644
--- a/src/net/sourcewalker/garanbot/data/GaranbotDBHelper.java
+++ b/src/net/sourcewalker/garanbot/data/GaranbotDBHelper.java
@@ -1,37 +1,37 @@
package net.sourcewalker.garanbot.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class GaranbotDBHelper extends SQLiteOpenHelper {
private final String TAG = "GaranbotDBHelper";
private static final String DATABASE_NAME = "garanbot.sql";
private static final int DATABASE_VERSION = 2;
public GaranbotDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(GaranbotDBMetaData.SCHEMA);
// create dummy entry
db
.execSQL("INSERT INTO "
+ GaranbotDBMetaData.TABLE_NAME
+ " (name,manufacturer,itemtype,vendor,location,notes,haspicture,purchasedate,endofwarranty) "
- + "VALUES ('dummyEntry','matchbox','toy','schinacher','fn','green car', 0,'2002-12-24','2004-12-24')");
+ + "VALUES ('dummyEntry','matchbox','toy','schinacher','fn','green car', 0,'2002-12-24T00:00:00+00:00','2004-12-24T00:00:00+00:00')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
Log.w(TAG, "Upgrading database, which will destroy all old data.");
db.execSQL("DROP TABLE IF EXISTS " + GaranbotDBMetaData.TABLE_NAME);
onCreate(db);
}
}
| true | true | public void onCreate(SQLiteDatabase db) {
db.execSQL(GaranbotDBMetaData.SCHEMA);
// create dummy entry
db
.execSQL("INSERT INTO "
+ GaranbotDBMetaData.TABLE_NAME
+ " (name,manufacturer,itemtype,vendor,location,notes,haspicture,purchasedate,endofwarranty) "
+ "VALUES ('dummyEntry','matchbox','toy','schinacher','fn','green car', 0,'2002-12-24','2004-12-24')");
}
| public void onCreate(SQLiteDatabase db) {
db.execSQL(GaranbotDBMetaData.SCHEMA);
// create dummy entry
db
.execSQL("INSERT INTO "
+ GaranbotDBMetaData.TABLE_NAME
+ " (name,manufacturer,itemtype,vendor,location,notes,haspicture,purchasedate,endofwarranty) "
+ "VALUES ('dummyEntry','matchbox','toy','schinacher','fn','green car', 0,'2002-12-24T00:00:00+00:00','2004-12-24T00:00:00+00:00')");
}
|
diff --git a/src/application/TimeTableManager.java b/src/application/TimeTableManager.java
index 22526bd..b036f48 100644
--- a/src/application/TimeTableManager.java
+++ b/src/application/TimeTableManager.java
@@ -1,197 +1,198 @@
package application;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import data.Database;
import exceptions.ParserException;
public class TimeTableManager {
private Controller controller;
private Parser parser;
private Database database;
private List<Transport> timeTable;
public TimeTableManager(Controller controller) throws SQLException {
this.controller = controller;
this.parser = controller.getParser();
this.database = controller.getDatabase();
if (this.controller.getConfiguration().isOffline()) {
this.controller.getDisplay().setOfflineMode(true);
this.loadNewOfflineTimeTable();
} else {
try {
this.loadNewTimeTable();
this.controller.getDisplay().setOfflineMode(false);
} catch (ParserException e) {
this.controller.getDisplay().setOfflineMode(true);
this.loadNewOfflineTimeTable();
}
}
}
private void loadNewTimeTable() throws ParserException {
List<Transport> parsedTimeTable = this.parser.loadTimeTable();
List<Transport> newTimeTable = new LinkedList<Transport>();
for (Transport transport : parsedTimeTable) {
Long etc = transport.calcEtcSec();
if (
!"S Potsdam Hbf".equals(transport.getDestination())
&& !"Potsdam, Lange Brücke".equals(transport.getPlatform())
&& !"S Potsdam Hbf Nord".equals(transport.getPlatform())
&& !"Potsdam, Hbf/H.-Mann-Allee".equals(transport.getPlatform())
&& !"Potsdam, Hauptbahnhof/Hafen".equals(transport.getPlatform())
&& etc > 0
&& etc < 82800
) {
newTimeTable.add(transport);
}
}
this.timeTable = newTimeTable;
}
public List<Transport> getCurrentTimeTable() throws SQLException {
List<Transport> newTimeTable = new LinkedList<Transport>();
List<Transport> currentTimeTable = new LinkedList<Transport>();
for (Transport transport : this.timeTable) {
int minTime = this.controller.getConfiguration().getMinTime();
if (transport.calcEtcSec() > minTime) newTimeTable.add(transport);
}
this.timeTable = newTimeTable;
int displayTransports = this.controller.getConfiguration().getDisplayTransports();
if (this.timeTable.size() < displayTransports) {
try {
this.loadNewTimeTable();
this.controller.getDisplay().setOfflineMode(false);
} catch (ParserException e) {
this.controller.getDisplay().setOfflineMode(true);
this.loadNewOfflineTimeTable();
}
newTimeTable = this.timeTable;
}
for (Transport transport : newTimeTable) {
if (currentTimeTable.size() < displayTransports) {
currentTimeTable.add(transport);
} else {
break;
}
}
return currentTimeTable;
}
private void loadNewOfflineTimeTable() throws SQLException {
this.database.connect();
this.loadNewOfflineTimeTable(new Date(), this.controller.getConfiguration().getLoadTransports());
this.database.disconnect();
}
private void loadNewOfflineTimeTable(Date date, int nOfTransports) throws SQLException {
List<Transport> transportDayList = this.database.loadDayList();
Date queryDate = this.calcSimilarDate(transportDayList, date);
Date queryDateTime = Transport.mergeDate(queryDate, date);
this.timeTable = this.database.loadSpecificTransportList(queryDateTime, nOfTransports);
for (Transport transport : this.timeTable) {
transport.setDeparture(Transport.mergeDate(date, transport.getDeparture()));
}
if (this.timeTable.size() < nOfTransports) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
queryDateTime.setTime(cal.getTimeInMillis());
queryDate = this.calcSimilarDate(transportDayList, date);
queryDateTime = Transport.mergeDate(queryDate, "00:00");
List<Transport> listDayAfter = this.database.loadSpecificTransportList(queryDateTime, nOfTransports - this.timeTable.size());
for (Transport transport : listDayAfter) {
transport.setDeparture(Transport.mergeDate(date, transport.getDeparture()));
}
this.timeTable.addAll(listDayAfter);
}
}
private Date calcSimilarDate(List<Transport> transportList, Date searchDate) {
List<Transport> rightDow = new LinkedList<Transport>();
SimpleDateFormat dowFormat = new SimpleDateFormat("E");
String searchDow = dowFormat.format(searchDate);
for (Transport transport : transportList) {
String transportDow = dowFormat.format(transport.getDeparture());
if (
searchDow.equals(transportDow)
|| (
searchDow.equals("Mon")
|| searchDow.equals("Tue")
|| searchDow.equals("Wed")
|| searchDow.equals("Thu")
|| searchDow.equals("Fri")
) && (
transportDow.equals("Mon")
|| transportDow.equals("Tue")
|| transportDow.equals("Wed")
|| transportDow.equals("Thu")
|| transportDow.equals("Fri")
)
) {
rightDow.add(transport);
}
}
if (rightDow.size() == 0) return null;
Date closestInPast = null;
for (Transport transport : rightDow) {
if (
(
(closestInPast == null)
&& !transport.getDeparture().after(searchDate)
) || (
closestInPast != null
&& closestInPast.before(transport.getDeparture())
&& !transport.getDeparture().after(searchDate)
)
) {
closestInPast = transport.getDeparture();
}
}
if (closestInPast != null) return closestInPast;
Date closestInFuture = null;
for (Transport transport : rightDow) {
if (
(
(closestInFuture == null)
&& transport.getDeparture().after(searchDate)
- ) || (
- closestInFuture.after(transport.getDeparture())
+ ) || (
+ closestInFuture != null
+ && closestInFuture.after(transport.getDeparture())
&& transport.getDeparture().after(searchDate)
)
) {
closestInFuture = transport.getDeparture();
}
}
return closestInFuture;
}
}
| true | true | private Date calcSimilarDate(List<Transport> transportList, Date searchDate) {
List<Transport> rightDow = new LinkedList<Transport>();
SimpleDateFormat dowFormat = new SimpleDateFormat("E");
String searchDow = dowFormat.format(searchDate);
for (Transport transport : transportList) {
String transportDow = dowFormat.format(transport.getDeparture());
if (
searchDow.equals(transportDow)
|| (
searchDow.equals("Mon")
|| searchDow.equals("Tue")
|| searchDow.equals("Wed")
|| searchDow.equals("Thu")
|| searchDow.equals("Fri")
) && (
transportDow.equals("Mon")
|| transportDow.equals("Tue")
|| transportDow.equals("Wed")
|| transportDow.equals("Thu")
|| transportDow.equals("Fri")
)
) {
rightDow.add(transport);
}
}
if (rightDow.size() == 0) return null;
Date closestInPast = null;
for (Transport transport : rightDow) {
if (
(
(closestInPast == null)
&& !transport.getDeparture().after(searchDate)
) || (
closestInPast != null
&& closestInPast.before(transport.getDeparture())
&& !transport.getDeparture().after(searchDate)
)
) {
closestInPast = transport.getDeparture();
}
}
if (closestInPast != null) return closestInPast;
Date closestInFuture = null;
for (Transport transport : rightDow) {
if (
(
(closestInFuture == null)
&& transport.getDeparture().after(searchDate)
) || (
closestInFuture.after(transport.getDeparture())
&& transport.getDeparture().after(searchDate)
)
) {
closestInFuture = transport.getDeparture();
}
}
return closestInFuture;
}
| private Date calcSimilarDate(List<Transport> transportList, Date searchDate) {
List<Transport> rightDow = new LinkedList<Transport>();
SimpleDateFormat dowFormat = new SimpleDateFormat("E");
String searchDow = dowFormat.format(searchDate);
for (Transport transport : transportList) {
String transportDow = dowFormat.format(transport.getDeparture());
if (
searchDow.equals(transportDow)
|| (
searchDow.equals("Mon")
|| searchDow.equals("Tue")
|| searchDow.equals("Wed")
|| searchDow.equals("Thu")
|| searchDow.equals("Fri")
) && (
transportDow.equals("Mon")
|| transportDow.equals("Tue")
|| transportDow.equals("Wed")
|| transportDow.equals("Thu")
|| transportDow.equals("Fri")
)
) {
rightDow.add(transport);
}
}
if (rightDow.size() == 0) return null;
Date closestInPast = null;
for (Transport transport : rightDow) {
if (
(
(closestInPast == null)
&& !transport.getDeparture().after(searchDate)
) || (
closestInPast != null
&& closestInPast.before(transport.getDeparture())
&& !transport.getDeparture().after(searchDate)
)
) {
closestInPast = transport.getDeparture();
}
}
if (closestInPast != null) return closestInPast;
Date closestInFuture = null;
for (Transport transport : rightDow) {
if (
(
(closestInFuture == null)
&& transport.getDeparture().after(searchDate)
) || (
closestInFuture != null
&& closestInFuture.after(transport.getDeparture())
&& transport.getDeparture().after(searchDate)
)
) {
closestInFuture = transport.getDeparture();
}
}
return closestInFuture;
}
|
diff --git a/projects/tests/src/test/java/org/jboss/forge/addon/projects/shell/NewProjectShellTest.java b/projects/tests/src/test/java/org/jboss/forge/addon/projects/shell/NewProjectShellTest.java
index ec35311d2..ea4395790 100644
--- a/projects/tests/src/test/java/org/jboss/forge/addon/projects/shell/NewProjectShellTest.java
+++ b/projects/tests/src/test/java/org/jboss/forge/addon/projects/shell/NewProjectShellTest.java
@@ -1,138 +1,139 @@
package org.jboss.forge.addon.projects.shell;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import static org.hamcrest.CoreMatchers.*;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.shell.test.ShellTest;
import org.jboss.forge.addon.ui.result.Failed;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.forge.furnace.util.OperatingSystemUtils;
import org.jboss.forge.furnace.util.Streams;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
@RunWith(Arquillian.class)
public class NewProjectShellTest
{
@Deployment
@Dependencies({
@AddonDependency(name = "org.jboss.forge.addon:shell-test-harness"),
@AddonDependency(name = "org.jboss.forge.addon:maven"),
@AddonDependency(name = "org.jboss.forge.addon:addons"),
@AddonDependency(name = "org.jboss.forge.addon:parser-java"),
@AddonDependency(name = "org.jboss.forge.addon:projects")
})
public static ForgeArchive getDeployment()
{
ForgeArchive archive = ShrinkWrap
.create(ForgeArchive.class)
.addBeansXML()
.addAsAddonDependencies(
AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi"),
AddonDependencyEntry.create("org.jboss.forge.addon:projects"),
AddonDependencyEntry.create("org.jboss.forge.addon:shell-test-harness")
);
return archive;
}
@Inject
private ShellTest test;
@After
public void after() throws IOException
{
test.clearScreen();
}
@Test
public void testWizardCommandExecution() throws Exception
{
File target = OperatingSystemUtils.createTempDir();
Result result = test.execute(("new-project " +
"--named lincoln " +
"--topLevelPackage org.lincoln " +
"--targetLocation " + target.getAbsolutePath() + " " +
"--type \"Maven - Java\" " +
"--overwrite " +
"--version 1.0.0-SNAPSHOT"), 10, TimeUnit.SECONDS);
Assert.assertFalse(result instanceof Failed);
Assert.assertTrue(target.exists());
Assert.assertTrue(target.isDirectory());
File projectDir = new File(target, "lincoln");
Assert.assertTrue(projectDir.exists());
Assert.assertTrue(new File(projectDir, "pom.xml").exists());
}
@Test
public void testTopLevelPackageOptional() throws Exception
{
File target = OperatingSystemUtils.createTempDir();
Result result = test.execute(("new-project " +
"--named lincoln-three " +
"--targetLocation " + target.getAbsolutePath() + " " +
"--type \"Maven - Resources\" " +
"--version 1.0.0-SNAPSHOT"), 10, TimeUnit.SECONDS);
Assert.assertFalse(result instanceof Failed);
Assert.assertTrue(target.exists());
Assert.assertTrue(target.isDirectory());
File projectDir = new File(target, "lincoln-three");
Assert.assertTrue(projectDir.exists());
File pomFile = new File(projectDir, "pom.xml");
Assert.assertTrue(pomFile.exists());
String pomContents = Streams.toString(new BufferedInputStream(
new FileInputStream(pomFile)));
Assert.assertTrue(pomContents.contains("org.lincoln.three"));
}
@Test
public void testCompletionFlow() throws Exception
{
test.waitForCompletion("new-project ", "new-pr", 5, TimeUnit.SECONDS);
test.waitForCompletion("new-project --", "", 5, TimeUnit.SECONDS);
String stdout = test.waitForCompletion(5, TimeUnit.SECONDS);
Assert.assertThat(stdout, containsString("--named"));
Assert.assertThat(stdout, containsString("--topLevelPackage"));
Assert.assertThat(stdout, containsString("--targetLocation"));
Assert.assertThat(stdout, containsString("--overwrite"));
Assert.assertThat(stdout, containsString("--type"));
Assert.assertThat(stdout, containsString("--version"));
Assert.assertThat(stdout, not(containsString("--addons")));
- stdout = test.waitForCompletion("new-project --named", "named lincoln --type \"Maven - Java\" --",
+ stdout = test.waitForCompletion("new-project --named lincoln --type \"Maven - Java\" --",
+ "named lincoln --type \"Maven - Java\" --",
5, TimeUnit.SECONDS);
Assert.assertThat(stdout, containsString("--topLevelPackage"));
Assert.assertThat(stdout, containsString("--targetLocation"));
Assert.assertThat(stdout, containsString("--overwrite"));
Assert.assertThat(stdout, containsString("--type"));
Assert.assertThat(stdout, containsString("--version"));
Assert.assertThat(stdout, not(containsString("--addons")));
}
}
| true | true | public void testCompletionFlow() throws Exception
{
test.waitForCompletion("new-project ", "new-pr", 5, TimeUnit.SECONDS);
test.waitForCompletion("new-project --", "", 5, TimeUnit.SECONDS);
String stdout = test.waitForCompletion(5, TimeUnit.SECONDS);
Assert.assertThat(stdout, containsString("--named"));
Assert.assertThat(stdout, containsString("--topLevelPackage"));
Assert.assertThat(stdout, containsString("--targetLocation"));
Assert.assertThat(stdout, containsString("--overwrite"));
Assert.assertThat(stdout, containsString("--type"));
Assert.assertThat(stdout, containsString("--version"));
Assert.assertThat(stdout, not(containsString("--addons")));
stdout = test.waitForCompletion("new-project --named", "named lincoln --type \"Maven - Java\" --",
5, TimeUnit.SECONDS);
Assert.assertThat(stdout, containsString("--topLevelPackage"));
Assert.assertThat(stdout, containsString("--targetLocation"));
Assert.assertThat(stdout, containsString("--overwrite"));
Assert.assertThat(stdout, containsString("--type"));
Assert.assertThat(stdout, containsString("--version"));
Assert.assertThat(stdout, not(containsString("--addons")));
}
| public void testCompletionFlow() throws Exception
{
test.waitForCompletion("new-project ", "new-pr", 5, TimeUnit.SECONDS);
test.waitForCompletion("new-project --", "", 5, TimeUnit.SECONDS);
String stdout = test.waitForCompletion(5, TimeUnit.SECONDS);
Assert.assertThat(stdout, containsString("--named"));
Assert.assertThat(stdout, containsString("--topLevelPackage"));
Assert.assertThat(stdout, containsString("--targetLocation"));
Assert.assertThat(stdout, containsString("--overwrite"));
Assert.assertThat(stdout, containsString("--type"));
Assert.assertThat(stdout, containsString("--version"));
Assert.assertThat(stdout, not(containsString("--addons")));
stdout = test.waitForCompletion("new-project --named lincoln --type \"Maven - Java\" --",
"named lincoln --type \"Maven - Java\" --",
5, TimeUnit.SECONDS);
Assert.assertThat(stdout, containsString("--topLevelPackage"));
Assert.assertThat(stdout, containsString("--targetLocation"));
Assert.assertThat(stdout, containsString("--overwrite"));
Assert.assertThat(stdout, containsString("--type"));
Assert.assertThat(stdout, containsString("--version"));
Assert.assertThat(stdout, not(containsString("--addons")));
}
|
diff --git a/testsrc/com/gtosoft/libvoyager/test/DtcLookupTest.java b/testsrc/com/gtosoft/libvoyager/test/DtcLookupTest.java
index bf3e546..01ec701 100644
--- a/testsrc/com/gtosoft/libvoyager/test/DtcLookupTest.java
+++ b/testsrc/com/gtosoft/libvoyager/test/DtcLookupTest.java
@@ -1,32 +1,32 @@
package com.gtosoft.libvoyager.test;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.gtosoft.libvoyager.net.NetDTCInfo;
public class DtcLookupTest {
@Test
public void testNetDTCLookup() throws Exception {
String testdtcs [] = {
"P0021",
"P070F",
"P0819"};
String dtcDescriptions [] = {
"Camshaft Position Timing Over-Advanced or System Performance Bank 2",
"Transmission Fluid Level Too Low",
"Up and Down Shift Switch to Transmission Range Correlation"};
NetDTCInfo ndi = new NetDTCInfo("unitTest");
String thisDescr = "";
for (int i=0;i<testdtcs.length;i++) {
thisDescr = ndi.getDTCDescription(testdtcs[i]);
- assertEquals (thisDescr,dtcDescriptions[i]);
+ assertEquals (dtcDescriptions[i], thisDescr);
}
}// end of testNetDTCLookup.
}
| true | true | public void testNetDTCLookup() throws Exception {
String testdtcs [] = {
"P0021",
"P070F",
"P0819"};
String dtcDescriptions [] = {
"Camshaft Position Timing Over-Advanced or System Performance Bank 2",
"Transmission Fluid Level Too Low",
"Up and Down Shift Switch to Transmission Range Correlation"};
NetDTCInfo ndi = new NetDTCInfo("unitTest");
String thisDescr = "";
for (int i=0;i<testdtcs.length;i++) {
thisDescr = ndi.getDTCDescription(testdtcs[i]);
assertEquals (thisDescr,dtcDescriptions[i]);
}
}// end of testNetDTCLookup.
| public void testNetDTCLookup() throws Exception {
String testdtcs [] = {
"P0021",
"P070F",
"P0819"};
String dtcDescriptions [] = {
"Camshaft Position Timing Over-Advanced or System Performance Bank 2",
"Transmission Fluid Level Too Low",
"Up and Down Shift Switch to Transmission Range Correlation"};
NetDTCInfo ndi = new NetDTCInfo("unitTest");
String thisDescr = "";
for (int i=0;i<testdtcs.length;i++) {
thisDescr = ndi.getDTCDescription(testdtcs[i]);
assertEquals (dtcDescriptions[i], thisDescr);
}
}// end of testNetDTCLookup.
|
diff --git a/src/main/java/org/bioinfo/gcsa/ws/AnalysisWSServer.java b/src/main/java/org/bioinfo/gcsa/ws/AnalysisWSServer.java
index 43c1814..a271bd6 100644
--- a/src/main/java/org/bioinfo/gcsa/ws/AnalysisWSServer.java
+++ b/src/main/java/org/bioinfo/gcsa/ws/AnalysisWSServer.java
@@ -1,300 +1,300 @@
package org.bioinfo.gcsa.ws;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.bioinfo.commons.utils.StringUtils;
import org.bioinfo.gcsa.lib.GcsaUtils;
import org.bioinfo.gcsa.lib.analysis.AnalysisExecutionException;
import org.bioinfo.gcsa.lib.analysis.AnalysisJobExecuter;
import org.bioinfo.gcsa.lib.analysis.beans.Analysis;
import org.bioinfo.gcsa.lib.analysis.beans.Execution;
import org.bioinfo.gcsa.lib.analysis.beans.InputParam;
import org.bioinfo.gcsa.lib.account.beans.ObjectItem;
import org.bioinfo.gcsa.lib.account.beans.Plugin;
import org.bioinfo.gcsa.lib.account.db.AccountManagementException;
@Path("/analysis")
public class AnalysisWSServer extends GenericWSServer {
AnalysisJobExecuter aje;
String baseUrl;
public AnalysisWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest)
throws IOException {
super(uriInfo, httpServletRequest);
baseUrl = uriInfo.getBaseUri().toString();
}
@GET
@Path("/{analysis}")
public Response help1(@DefaultValue("") @PathParam("analysis") String analysis) {
try {
aje = new AnalysisJobExecuter(analysis);
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
return createOkResponse(aje.help(baseUrl));
}
@GET
@Path("/{analysis}/help")
public Response help2(@DefaultValue("") @PathParam("analysis") String analysis) {
try {
aje = new AnalysisJobExecuter(analysis);
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
return createOkResponse(aje.help(baseUrl));
}
@GET
@Path("/{analysis}/params")
public Response showParams(@DefaultValue("") @PathParam("analysis") String analysis) {
try {
aje = new AnalysisJobExecuter(analysis);
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
return createOkResponse(aje.params());
}
@GET
@Path("/{analysis}/test")
public Response test(@DefaultValue("") @PathParam("analysis") String analysis) {
try {
aje = new AnalysisJobExecuter(analysis);
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
// Create job
String jobId = cloudSessionManager.createJob("", null, "", "", new ArrayList<String>(), "", sessionId);
String jobFolder = "/tmp/";
return createOkResponse(aje.test(jobId, jobFolder));
}
@GET
@Path("/{analysis}/status")
public Response status(@DefaultValue("") @PathParam("analysis") String analysis,
@DefaultValue("") @QueryParam("jobid") String jobId) {
try {
aje = new AnalysisJobExecuter(analysis);
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
return createOkResponse(aje.status(jobId));
}
@GET
@Path("/{analysis}/run")
public Response analysisGet(@DefaultValue("") @PathParam("analysis") String analysis) {
// MultivaluedMap<String, String> params =
// this.uriInfo.getQueryParameters();
System.out.println("**GET executed***");
System.out.println("get params: " + params);
return this.analysis(analysis, params);
}
@POST
@Path("/{analysis}/run")
@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_FORM_URLENCODED })
public Response analysisPost(@DefaultValue("") @PathParam("analysis") String analysis,
MultivaluedMap<String, String> postParams) {
System.out.println("**POST executed***");
System.out.println("post params: " + postParams);
return this.analysis(analysis, postParams);
}
private Response analysis(String analysisStr, MultivaluedMap<String, String> params) {
// TODO Comprobar mas cosas antes de crear el analysis job executer
// (permisos, etc..)
if (params.containsKey("sessionid")) {
sessionId = params.get("sessionid").get(0);
params.remove("sessionid");
} else {
return createErrorResponse("ERROR: Session is not initialized yet.");
}
String accountId = null;
if (params.containsKey("accountid")) {
accountId = params.get("accountid").get(0);
params.remove("accountid");
} else {
return createErrorResponse("ERROR: Session is not initialized yet.");
}
String bucket = null;
if (params.containsKey("jobdestinationbucket")) {
bucket = params.get("jobdestinationbucket").get(0);
params.remove("jobdestinationbucket");
} else {
return createErrorResponse("ERROR: unspecified destination bucket.");
}
// Jquery put this parameter and it is sent to the tool
if (params.containsKey("_")) {
params.remove("_");
}
String analysisName = analysisStr;
if (analysisStr.contains(".")) {
analysisName = analysisStr.split("\\.")[0];
}
String analysisOwner = "system";
try {
List<Plugin> userAnalysis = cloudSessionManager.getUserAnalysis(sessionId);
for (Plugin a : userAnalysis) {
if (a.getName().equals(analysisName)) {
analysisOwner = a.getOwnerId();
break;
}
}
} catch (AccountManagementException e1) {
e1.printStackTrace();
return createErrorResponse("ERROR: invalid session id.");
}
Analysis analysis = null;
try {
aje = new AnalysisJobExecuter(analysisStr, analysisOwner);
analysis = aje.getAnalysis();
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
Execution execution = null;
try {
execution = aje.getExecution();
} catch (AnalysisExecutionException e) {
e.printStackTrace();
return createErrorResponse("ERROR: Executable not found.");
}
String jobName = "";
if (params.containsKey("jobname")) {
jobName = params.get("jobname").get(0);
params.remove("jobname");
}
String jobFolder = null;
if (params.containsKey("outdir")) {
jobFolder = params.get("outdir").get(0);
params.remove("outdir");
}
boolean example = false;
if (params.containsKey("example")) {
example = Boolean.parseBoolean(params.get("example").get(0));
params.remove("example");
}
String toolName = analysis.getId();
// Set input param
for (InputParam inputParam : execution.getInputParams()) {
if (params.containsKey(inputParam.getName())) {
List<String> dataIds = Arrays.asList(params.get(inputParam.getName()).get(0).split(","));
List<String> dataPaths = new ArrayList<String>();
for (String dataId : dataIds) {
String dataPath = null;
if(example) {
dataPath = aje.getExamplePath(dataId);
}
else {
//TODO
/*TEMPORAL, PENSAR OTRA FORMA DE CREAR LOS FICHEROS CON LA LISTA DE NODOS*/
/*DE MOMENTO SE CREAN EN TMP*/
if(dataId.contains("\n")) {
FileWriter fileWriter = null;
try {
String content = dataId;
- dataPath = "/tmp/" + StringUtils.randomString(8) + "/";
+ dataPath = "/tmp/" + StringUtils.randomString(8);
fileWriter = new FileWriter(new File(dataPath));
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**/
else { // is a dataId
dataPath = cloudSessionManager.getDataPath(accountId, null, dataId);
}
}
if (dataPath.contains("ERROR")) {
return createErrorResponse(dataPath);
} else {
dataPaths.add(dataPath);
}
}
params.put(inputParam.getName(), dataPaths);
}
}
// Create commmand line
String commandLine = null;
try {
commandLine = aje.createCommandLine(execution.getExecutable(), params);
} catch (AccountManagementException e) {
e.printStackTrace();
return createErrorResponse(e.getMessage());
}
String jobId = cloudSessionManager.createJob(jobName, jobFolder, bucket, toolName, new ArrayList<String>(),
commandLine, sessionId);
if (jobFolder == null) {
jobFolder = cloudSessionManager.getJobFolder(bucket, jobId, sessionId);
}
// String jobId = execute("SW","HPG.SW", dataIds, params, "-d");
String resp;
try {
resp = aje.execute(jobId, jobFolder, params);
} catch (AccountManagementException e) {
e.printStackTrace();
return createErrorResponse("ERROR: Execution failed.");
}
return createOkResponse(resp);
}
}
| true | true | private Response analysis(String analysisStr, MultivaluedMap<String, String> params) {
// TODO Comprobar mas cosas antes de crear el analysis job executer
// (permisos, etc..)
if (params.containsKey("sessionid")) {
sessionId = params.get("sessionid").get(0);
params.remove("sessionid");
} else {
return createErrorResponse("ERROR: Session is not initialized yet.");
}
String accountId = null;
if (params.containsKey("accountid")) {
accountId = params.get("accountid").get(0);
params.remove("accountid");
} else {
return createErrorResponse("ERROR: Session is not initialized yet.");
}
String bucket = null;
if (params.containsKey("jobdestinationbucket")) {
bucket = params.get("jobdestinationbucket").get(0);
params.remove("jobdestinationbucket");
} else {
return createErrorResponse("ERROR: unspecified destination bucket.");
}
// Jquery put this parameter and it is sent to the tool
if (params.containsKey("_")) {
params.remove("_");
}
String analysisName = analysisStr;
if (analysisStr.contains(".")) {
analysisName = analysisStr.split("\\.")[0];
}
String analysisOwner = "system";
try {
List<Plugin> userAnalysis = cloudSessionManager.getUserAnalysis(sessionId);
for (Plugin a : userAnalysis) {
if (a.getName().equals(analysisName)) {
analysisOwner = a.getOwnerId();
break;
}
}
} catch (AccountManagementException e1) {
e1.printStackTrace();
return createErrorResponse("ERROR: invalid session id.");
}
Analysis analysis = null;
try {
aje = new AnalysisJobExecuter(analysisStr, analysisOwner);
analysis = aje.getAnalysis();
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
Execution execution = null;
try {
execution = aje.getExecution();
} catch (AnalysisExecutionException e) {
e.printStackTrace();
return createErrorResponse("ERROR: Executable not found.");
}
String jobName = "";
if (params.containsKey("jobname")) {
jobName = params.get("jobname").get(0);
params.remove("jobname");
}
String jobFolder = null;
if (params.containsKey("outdir")) {
jobFolder = params.get("outdir").get(0);
params.remove("outdir");
}
boolean example = false;
if (params.containsKey("example")) {
example = Boolean.parseBoolean(params.get("example").get(0));
params.remove("example");
}
String toolName = analysis.getId();
// Set input param
for (InputParam inputParam : execution.getInputParams()) {
if (params.containsKey(inputParam.getName())) {
List<String> dataIds = Arrays.asList(params.get(inputParam.getName()).get(0).split(","));
List<String> dataPaths = new ArrayList<String>();
for (String dataId : dataIds) {
String dataPath = null;
if(example) {
dataPath = aje.getExamplePath(dataId);
}
else {
//TODO
/*TEMPORAL, PENSAR OTRA FORMA DE CREAR LOS FICHEROS CON LA LISTA DE NODOS*/
/*DE MOMENTO SE CREAN EN TMP*/
if(dataId.contains("\n")) {
FileWriter fileWriter = null;
try {
String content = dataId;
dataPath = "/tmp/" + StringUtils.randomString(8) + "/";
fileWriter = new FileWriter(new File(dataPath));
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**/
else { // is a dataId
dataPath = cloudSessionManager.getDataPath(accountId, null, dataId);
}
}
if (dataPath.contains("ERROR")) {
return createErrorResponse(dataPath);
} else {
dataPaths.add(dataPath);
}
}
params.put(inputParam.getName(), dataPaths);
}
}
// Create commmand line
String commandLine = null;
try {
commandLine = aje.createCommandLine(execution.getExecutable(), params);
} catch (AccountManagementException e) {
e.printStackTrace();
return createErrorResponse(e.getMessage());
}
String jobId = cloudSessionManager.createJob(jobName, jobFolder, bucket, toolName, new ArrayList<String>(),
commandLine, sessionId);
if (jobFolder == null) {
jobFolder = cloudSessionManager.getJobFolder(bucket, jobId, sessionId);
}
// String jobId = execute("SW","HPG.SW", dataIds, params, "-d");
String resp;
try {
resp = aje.execute(jobId, jobFolder, params);
} catch (AccountManagementException e) {
e.printStackTrace();
return createErrorResponse("ERROR: Execution failed.");
}
return createOkResponse(resp);
}
| private Response analysis(String analysisStr, MultivaluedMap<String, String> params) {
// TODO Comprobar mas cosas antes de crear el analysis job executer
// (permisos, etc..)
if (params.containsKey("sessionid")) {
sessionId = params.get("sessionid").get(0);
params.remove("sessionid");
} else {
return createErrorResponse("ERROR: Session is not initialized yet.");
}
String accountId = null;
if (params.containsKey("accountid")) {
accountId = params.get("accountid").get(0);
params.remove("accountid");
} else {
return createErrorResponse("ERROR: Session is not initialized yet.");
}
String bucket = null;
if (params.containsKey("jobdestinationbucket")) {
bucket = params.get("jobdestinationbucket").get(0);
params.remove("jobdestinationbucket");
} else {
return createErrorResponse("ERROR: unspecified destination bucket.");
}
// Jquery put this parameter and it is sent to the tool
if (params.containsKey("_")) {
params.remove("_");
}
String analysisName = analysisStr;
if (analysisStr.contains(".")) {
analysisName = analysisStr.split("\\.")[0];
}
String analysisOwner = "system";
try {
List<Plugin> userAnalysis = cloudSessionManager.getUserAnalysis(sessionId);
for (Plugin a : userAnalysis) {
if (a.getName().equals(analysisName)) {
analysisOwner = a.getOwnerId();
break;
}
}
} catch (AccountManagementException e1) {
e1.printStackTrace();
return createErrorResponse("ERROR: invalid session id.");
}
Analysis analysis = null;
try {
aje = new AnalysisJobExecuter(analysisStr, analysisOwner);
analysis = aje.getAnalysis();
} catch (Exception e) {
e.printStackTrace();
return createErrorResponse("ERROR: Analysis not found.");
}
Execution execution = null;
try {
execution = aje.getExecution();
} catch (AnalysisExecutionException e) {
e.printStackTrace();
return createErrorResponse("ERROR: Executable not found.");
}
String jobName = "";
if (params.containsKey("jobname")) {
jobName = params.get("jobname").get(0);
params.remove("jobname");
}
String jobFolder = null;
if (params.containsKey("outdir")) {
jobFolder = params.get("outdir").get(0);
params.remove("outdir");
}
boolean example = false;
if (params.containsKey("example")) {
example = Boolean.parseBoolean(params.get("example").get(0));
params.remove("example");
}
String toolName = analysis.getId();
// Set input param
for (InputParam inputParam : execution.getInputParams()) {
if (params.containsKey(inputParam.getName())) {
List<String> dataIds = Arrays.asList(params.get(inputParam.getName()).get(0).split(","));
List<String> dataPaths = new ArrayList<String>();
for (String dataId : dataIds) {
String dataPath = null;
if(example) {
dataPath = aje.getExamplePath(dataId);
}
else {
//TODO
/*TEMPORAL, PENSAR OTRA FORMA DE CREAR LOS FICHEROS CON LA LISTA DE NODOS*/
/*DE MOMENTO SE CREAN EN TMP*/
if(dataId.contains("\n")) {
FileWriter fileWriter = null;
try {
String content = dataId;
dataPath = "/tmp/" + StringUtils.randomString(8);
fileWriter = new FileWriter(new File(dataPath));
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**/
else { // is a dataId
dataPath = cloudSessionManager.getDataPath(accountId, null, dataId);
}
}
if (dataPath.contains("ERROR")) {
return createErrorResponse(dataPath);
} else {
dataPaths.add(dataPath);
}
}
params.put(inputParam.getName(), dataPaths);
}
}
// Create commmand line
String commandLine = null;
try {
commandLine = aje.createCommandLine(execution.getExecutable(), params);
} catch (AccountManagementException e) {
e.printStackTrace();
return createErrorResponse(e.getMessage());
}
String jobId = cloudSessionManager.createJob(jobName, jobFolder, bucket, toolName, new ArrayList<String>(),
commandLine, sessionId);
if (jobFolder == null) {
jobFolder = cloudSessionManager.getJobFolder(bucket, jobId, sessionId);
}
// String jobId = execute("SW","HPG.SW", dataIds, params, "-d");
String resp;
try {
resp = aje.execute(jobId, jobFolder, params);
} catch (AccountManagementException e) {
e.printStackTrace();
return createErrorResponse("ERROR: Execution failed.");
}
return createOkResponse(resp);
}
|
diff --git a/src/test/java/org/noisemap/core/TestSoundPropagationValidation.java b/src/test/java/org/noisemap/core/TestSoundPropagationValidation.java
index edfa203..9a2deef 100644
--- a/src/test/java/org/noisemap/core/TestSoundPropagationValidation.java
+++ b/src/test/java/org/noisemap/core/TestSoundPropagationValidation.java
@@ -1,273 +1,273 @@
/**
* NoiseMap is a scientific computation plugin for OrbisGIS developed in order to
* evaluate the noise impact on urban mobility plans. This model is
* based on the French standard method NMPB2008. It includes traffic-to-noise
* sources evaluation and sound propagation processing.
*
* This version is developed at French IRSTV Institute and at IFSTTAR
* (http://www.ifsttar.fr/) as part of the Eval-PDU project, funded by the
* French Agence Nationale de la Recherche (ANR) under contract ANR-08-VILL-0005-01.
*
* Noisemap is distributed under GPL 3 license. Its reference contact is Judicaël
* Picaut <[email protected]>. It is maintained by Nicolas Fortin
* as part of the "Atelier SIG" team of the IRSTV Institute <http://www.irstv.fr/>.
*
* Copyright (C) 2011 IFSTTAR
* Copyright (C) 2011-2012 IRSTV (FR CNRS 2488)
*
* Noisemap 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.
*
* Noisemap 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
* Noisemap. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.noisemap.core;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Polygon;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import junit.framework.TestCase;
public class TestSoundPropagationValidation extends TestCase {
public static double splEpsilon=0.05;
private double splCompute(PropagationProcess propManager,Coordinate receiverPosition) {
double energeticSum[]={0.};
propManager.computeSoundLevelAtPosition(receiverPosition, energeticSum);
return PropagationProcess.wToDba(energeticSum[0]);
}
public static boolean isSameDbValues(double dba,double dba2) {
return Math.abs(dba-dba2)<splEpsilon || (Double.isInfinite(dba) && Double.isInfinite(dba2));
}
public static boolean isSameDbValues(double dba,double dba2,double externalEpsilon) {
return Math.abs(dba-dba2)<externalEpsilon || (Double.isInfinite(dba) && Double.isInfinite(dba2));
}
private void splCompare(double dba,String testName,double goodSpl) {
System.out.println(testName+" "+dba+" dB(A)");
assertTrue(goodSpl+"!="+dba+" (right ref)Sound level computation error @ "+testName,isSameDbValues(dba,goodSpl));
}
public void testScene1() throws LayerDelaunayError {
System.out.println("________________________________________________");
System.out.println("Scene 1 :");
long startMakeScene=System.currentTimeMillis();
////////////////////////////////////////////////////////////////////////////
//Build Scene with One Building
GeometryFactory factory = new GeometryFactory();
Coordinate[] building1Coords = { new Coordinate(15., 5.,0.),
new Coordinate(30., 5.,0.), new Coordinate(30., 30.,0.),
new Coordinate(15., 30.,0.), new Coordinate(15., 5.,0.) };
Polygon building1 = factory.createPolygon(
factory.createLinearRing(building1Coords), null);
////////////////////////////////////////////////////////////////////////////
//Add road source as one point
List<Geometry> srclst=new ArrayList<Geometry>();
srclst.add(factory.createPoint(new Coordinate(40,15,0)));
//Scene dimension
Envelope cellEnvelope=new Envelope(new Coordinate(-170., -170.,0.),new Coordinate(170, 170,0.));
//Add source sound level
List<ArrayList<Double>> srcSpectrum=new ArrayList<ArrayList<Double>>();
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
List<Integer> freqLvl=new ArrayList<Integer>();
freqLvl.add(125);
//Build query structure for sources
QueryGeometryStructure sourcesIndex = new QueryGridIndex(
cellEnvelope, 8, 8);
int idsrc=0;
for(Geometry src : srclst) {
sourcesIndex.appendGeometry(src, idsrc);
idsrc++;
}
System.out.println("Construction scene in "+(System.currentTimeMillis()-startMakeScene)+"ms");
long startObstructionTest=System.currentTimeMillis();
//Create obstruction test object
FastObstructionTest manager = new FastObstructionTest();
manager.addGeometry(building1);
manager.finishPolygonFeeding(cellEnvelope);
//Retrieve Delaunay triangulation of scene
List<Triangle> tri=manager.getTriangles();
List<Coordinate> vert=manager.getVertices();
Stack<PropagationResultTriRecord> dataStack=new Stack<PropagationResultTriRecord>();
PropagationProcessData propData=new PropagationProcessData(vert,null, tri, manager, sourcesIndex, srclst, srcSpectrum, freqLvl, 0, 2, 80.,50., 1., 0., 0, null, null);
PropagationProcessOut propDataOut=new PropagationProcessOut(dataStack,null);
PropagationProcess propManager=new PropagationProcess(propData, propDataOut);
propManager.initStructures();
System.out.println("Propagation initialisation in "+(System.currentTimeMillis()-startObstructionTest)+"ms");
long startSimulation=System.currentTimeMillis();
//Run test
/////////////////////////////////////////////////////////////////////////
// Single diffraction test
propData.diffractionOrder=1;
propData.reflexionOrder=0;
splCompare(splCompute(propManager, new Coordinate(15,40,0)), "Scene 1 R4_S1", 46.81);
/////////////////////////////////////////////////////////////////////////
// Dual diffraction test
propData.diffractionOrder=2;
propData.reflexionOrder=0;
- splCompare(splCompute(propManager, new Coordinate(5,15,0)), "Scene 1 R1_S1", 34.97);
+ splCompare(splCompute(propManager, new Coordinate(5,15,0)), "Scene 1 R1_S1", 37.096);
/////////////////////////////////////////////////////////////////////////
// Geometric dispersion test
//Get reference spl value at 5m
propData.reflexionOrder=0;
propData.diffractionOrder=0;
double dbaRef=splCompute(propManager, new Coordinate(40,20,0));
//spl value at 10m
double dbaReduced=splCompute(propManager, new Coordinate(40,25,0));
splCompare(dbaReduced, "Scene 1 R2_S1", dbaRef-6.); //Double distance, then loss 6 dB. Atmospheric attenuation is not significant at 125Hz and 5 m distance
/////////////////////////////////////////////////////////////////////////
// First reflection test
dbaRef=splCompute(propManager, new Coordinate(35,15,0)); //Ref, at 5m of src, at 5m of wall
double dbaRef2=splCompute(propManager, new Coordinate(40,15+15,0));//Ref2, at 15m of src (Src->Receiver->Wall->Receiver : 5+5+5)
propData.reflexionOrder=1;
propData.wallAlpha=0.2;
double dbaReflection=splCompute(propManager, new Coordinate(35,15,0)); //dbaReflection must be equal to the energetic sum of Ref&Ref2, with Ref2 attenuated by wall alpha.
splCompare(dbaReflection, "Scene 1 R3_S1",PropagationProcess.wToDba( PropagationProcess.dbaToW(dbaRef)+PropagationProcess.dbaToW(dbaRef2)*(1-propData.wallAlpha)));
/////////////////////////////////////////////////////////////////////////
// Energetic sum of source test
// The same source duplicated at the same position must be equal to a single point source with an energetic sum of SPL.
// Get reference spl value
propData.reflexionOrder=0;
propData.diffractionOrder=0;
srcSpectrum.get(0).set(0,PropagationProcess.dbaToW(100.)+PropagationProcess.dbaToW(100.));
double dbaSingleSource=splCompute(propManager, new Coordinate(40,20,0));
//spl value
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).set(0,PropagationProcess.dbaToW(100.));
srcSpectrum.get(1).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
srclst.add(factory.createPoint(new Coordinate(40,15,0)));
sourcesIndex.appendGeometry(srclst.get(1), idsrc);
idsrc++;
double dbaDupp=splCompute(propManager, new Coordinate(40,20,0));
splCompare(dbaSingleSource, "Scene 1 R3_S2",dbaDupp);
System.out.println("Simulation done in "+(System.currentTimeMillis()-startSimulation)+"ms");
System.out.println(manager.getNbObstructionTest()+" obstruction test has been done..");
System.out.println("testScene1 done in "+(System.currentTimeMillis()-startMakeScene)+"ms");
}
/**
* Build a scene with two line source at the same position
* @throws LayerDelaunayError
*/
public void testMergeSources() throws LayerDelaunayError {
System.out.println("________________________________________________");
System.out.println("Scene 2 :");
long startMakeScene=System.currentTimeMillis();
////////////////////////////////////////////////////////////////////////////
//Build Scene with Three Building
GeometryFactory factory = new GeometryFactory();
Coordinate[] building1Coords = { new Coordinate(6., 2.,0.),
new Coordinate(18., 2.,0.),new Coordinate(18., 6.,0.),
new Coordinate(6., 6.,0.),new Coordinate(6., 2.,0.)};
Polygon building1 = factory.createPolygon(
factory.createLinearRing(building1Coords), null);
Coordinate[] building2Coords = { new Coordinate(24., 2.,0.),
new Coordinate(28., 2.,0.),new Coordinate(28., 6.,0.),
new Coordinate(24., 6.,0.),new Coordinate(24., 2.,0.)};
Polygon building2 = factory.createPolygon(
factory.createLinearRing(building2Coords), null);
Coordinate[] building3Coords = { new Coordinate(6., 10.,0.),
new Coordinate(24., 10.,0.),new Coordinate(24.,18.,0.),
new Coordinate(6., 18.,0.),new Coordinate(6., 10.,0.)};
Polygon building3 = factory.createPolygon(
factory.createLinearRing(building3Coords), null);
////////////////////////////////////////////////////////////////////////////
//Add road source as one point
List<Geometry> srclst=new ArrayList<Geometry>();
Coordinate[] way1={new Coordinate(2,8,0),new Coordinate(24,8,0),new Coordinate(30,14,0)};
LineString road1=factory.createLineString(way1);
srclst.add(road1);
srclst.add(road1);
//Scene dimension
Envelope cellEnvelope=new Envelope(new Coordinate(-500., -500.,0.),new Coordinate(500, 500,0.));
//Add source sound level
List<ArrayList<Double>> srcSpectrum=new ArrayList<ArrayList<Double>>();
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
srcSpectrum.get(1).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
List<Integer> freqLvl=new ArrayList<Integer>();
freqLvl.add(125);
//Build query structure for sources
QueryGeometryStructure sourcesIndex = new QueryGridIndex(
cellEnvelope, 8, 8);
int idsrc=0;
for(Geometry src : srclst) {
sourcesIndex.appendGeometry(src, idsrc);
idsrc++;
}
System.out.println("Construction scene in "+(System.currentTimeMillis()-startMakeScene)+"ms");
long startObstructionTest=System.currentTimeMillis();
//Create obstruction test object
FastObstructionTest manager = new FastObstructionTest();
manager.addGeometry(building1);
manager.addGeometry(building2);
manager.addGeometry(building3);
manager.finishPolygonFeeding(cellEnvelope);
//Retrieve Delaunay triangulation of scene
List<Triangle> tri=manager.getTriangles();
List<Coordinate> vert=manager.getVertices();
Stack<PropagationResultTriRecord> dataStack=new Stack<PropagationResultTriRecord>();
PropagationProcessData propData=new PropagationProcessData(vert,null, tri, manager, sourcesIndex, srclst, srcSpectrum, freqLvl, 0, 2, 80.,50., 1., 0., 0, null, null);
PropagationProcessOut propDataOut=new PropagationProcessOut(dataStack,null);
PropagationProcess propManager=new PropagationProcess(propData, propDataOut);
propManager.initStructures();
System.out.println("Propagation initialisation in "+(System.currentTimeMillis()-startObstructionTest)+"ms");
long startSimulation=System.currentTimeMillis();
//Run test
//System.out.println(manager.getDelaunayGeoms());
/////////////////////////////////////////////////////////////////////////
// Geometric dispersion test
propData.reflexionOrder=3;
propData.diffractionOrder=0;
double dbaRef=splCompute(propManager, new Coordinate(20,4,0));
//Receiver in the buildings
propData.reflexionOrder=2;
propData.diffractionOrder=1;
double dbaInBuilding=splCompute(propManager, new Coordinate(26,4,0));
splCompare(Double.NEGATIVE_INFINITY, "in building",dbaInBuilding);
dbaInBuilding=splCompute(propManager, new Coordinate(8,12,0));
splCompare(Double.NEGATIVE_INFINITY, "in building",dbaInBuilding);
dbaInBuilding=splCompute(propManager, new Coordinate(20,12,0));
splCompare(Double.NEGATIVE_INFINITY, "in building",dbaInBuilding);
dbaInBuilding=splCompute(propManager, new Coordinate(12,4,0));
splCompare(Double.NEGATIVE_INFINITY, "in building",dbaInBuilding);
System.out.println("Simulation done in "+(System.currentTimeMillis()-startSimulation)+"ms");
System.out.println(manager.getNbObstructionTest()+" obstruction test has been done..");
System.out.println(propDataOut.getNb_couple_receiver_src()+" point source created..");
System.out.println(propDataOut.getNb_image_receiver()+" receiver image found..");
System.out.println(propDataOut.getNb_reflexion_path()+" reflection path found..");
splCompare(dbaRef, "Scene 2 (20,4)",91.916);
System.out.println("testScene1 done in "+(System.currentTimeMillis()-startMakeScene)+"ms");
}
}
| true | true | public void testScene1() throws LayerDelaunayError {
System.out.println("________________________________________________");
System.out.println("Scene 1 :");
long startMakeScene=System.currentTimeMillis();
////////////////////////////////////////////////////////////////////////////
//Build Scene with One Building
GeometryFactory factory = new GeometryFactory();
Coordinate[] building1Coords = { new Coordinate(15., 5.,0.),
new Coordinate(30., 5.,0.), new Coordinate(30., 30.,0.),
new Coordinate(15., 30.,0.), new Coordinate(15., 5.,0.) };
Polygon building1 = factory.createPolygon(
factory.createLinearRing(building1Coords), null);
////////////////////////////////////////////////////////////////////////////
//Add road source as one point
List<Geometry> srclst=new ArrayList<Geometry>();
srclst.add(factory.createPoint(new Coordinate(40,15,0)));
//Scene dimension
Envelope cellEnvelope=new Envelope(new Coordinate(-170., -170.,0.),new Coordinate(170, 170,0.));
//Add source sound level
List<ArrayList<Double>> srcSpectrum=new ArrayList<ArrayList<Double>>();
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
List<Integer> freqLvl=new ArrayList<Integer>();
freqLvl.add(125);
//Build query structure for sources
QueryGeometryStructure sourcesIndex = new QueryGridIndex(
cellEnvelope, 8, 8);
int idsrc=0;
for(Geometry src : srclst) {
sourcesIndex.appendGeometry(src, idsrc);
idsrc++;
}
System.out.println("Construction scene in "+(System.currentTimeMillis()-startMakeScene)+"ms");
long startObstructionTest=System.currentTimeMillis();
//Create obstruction test object
FastObstructionTest manager = new FastObstructionTest();
manager.addGeometry(building1);
manager.finishPolygonFeeding(cellEnvelope);
//Retrieve Delaunay triangulation of scene
List<Triangle> tri=manager.getTriangles();
List<Coordinate> vert=manager.getVertices();
Stack<PropagationResultTriRecord> dataStack=new Stack<PropagationResultTriRecord>();
PropagationProcessData propData=new PropagationProcessData(vert,null, tri, manager, sourcesIndex, srclst, srcSpectrum, freqLvl, 0, 2, 80.,50., 1., 0., 0, null, null);
PropagationProcessOut propDataOut=new PropagationProcessOut(dataStack,null);
PropagationProcess propManager=new PropagationProcess(propData, propDataOut);
propManager.initStructures();
System.out.println("Propagation initialisation in "+(System.currentTimeMillis()-startObstructionTest)+"ms");
long startSimulation=System.currentTimeMillis();
//Run test
/////////////////////////////////////////////////////////////////////////
// Single diffraction test
propData.diffractionOrder=1;
propData.reflexionOrder=0;
splCompare(splCompute(propManager, new Coordinate(15,40,0)), "Scene 1 R4_S1", 46.81);
/////////////////////////////////////////////////////////////////////////
// Dual diffraction test
propData.diffractionOrder=2;
propData.reflexionOrder=0;
splCompare(splCompute(propManager, new Coordinate(5,15,0)), "Scene 1 R1_S1", 34.97);
/////////////////////////////////////////////////////////////////////////
// Geometric dispersion test
//Get reference spl value at 5m
propData.reflexionOrder=0;
propData.diffractionOrder=0;
double dbaRef=splCompute(propManager, new Coordinate(40,20,0));
//spl value at 10m
double dbaReduced=splCompute(propManager, new Coordinate(40,25,0));
splCompare(dbaReduced, "Scene 1 R2_S1", dbaRef-6.); //Double distance, then loss 6 dB. Atmospheric attenuation is not significant at 125Hz and 5 m distance
/////////////////////////////////////////////////////////////////////////
// First reflection test
dbaRef=splCompute(propManager, new Coordinate(35,15,0)); //Ref, at 5m of src, at 5m of wall
double dbaRef2=splCompute(propManager, new Coordinate(40,15+15,0));//Ref2, at 15m of src (Src->Receiver->Wall->Receiver : 5+5+5)
propData.reflexionOrder=1;
propData.wallAlpha=0.2;
double dbaReflection=splCompute(propManager, new Coordinate(35,15,0)); //dbaReflection must be equal to the energetic sum of Ref&Ref2, with Ref2 attenuated by wall alpha.
splCompare(dbaReflection, "Scene 1 R3_S1",PropagationProcess.wToDba( PropagationProcess.dbaToW(dbaRef)+PropagationProcess.dbaToW(dbaRef2)*(1-propData.wallAlpha)));
/////////////////////////////////////////////////////////////////////////
// Energetic sum of source test
// The same source duplicated at the same position must be equal to a single point source with an energetic sum of SPL.
// Get reference spl value
propData.reflexionOrder=0;
propData.diffractionOrder=0;
srcSpectrum.get(0).set(0,PropagationProcess.dbaToW(100.)+PropagationProcess.dbaToW(100.));
double dbaSingleSource=splCompute(propManager, new Coordinate(40,20,0));
//spl value
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).set(0,PropagationProcess.dbaToW(100.));
srcSpectrum.get(1).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
srclst.add(factory.createPoint(new Coordinate(40,15,0)));
sourcesIndex.appendGeometry(srclst.get(1), idsrc);
idsrc++;
double dbaDupp=splCompute(propManager, new Coordinate(40,20,0));
splCompare(dbaSingleSource, "Scene 1 R3_S2",dbaDupp);
System.out.println("Simulation done in "+(System.currentTimeMillis()-startSimulation)+"ms");
System.out.println(manager.getNbObstructionTest()+" obstruction test has been done..");
System.out.println("testScene1 done in "+(System.currentTimeMillis()-startMakeScene)+"ms");
}
| public void testScene1() throws LayerDelaunayError {
System.out.println("________________________________________________");
System.out.println("Scene 1 :");
long startMakeScene=System.currentTimeMillis();
////////////////////////////////////////////////////////////////////////////
//Build Scene with One Building
GeometryFactory factory = new GeometryFactory();
Coordinate[] building1Coords = { new Coordinate(15., 5.,0.),
new Coordinate(30., 5.,0.), new Coordinate(30., 30.,0.),
new Coordinate(15., 30.,0.), new Coordinate(15., 5.,0.) };
Polygon building1 = factory.createPolygon(
factory.createLinearRing(building1Coords), null);
////////////////////////////////////////////////////////////////////////////
//Add road source as one point
List<Geometry> srclst=new ArrayList<Geometry>();
srclst.add(factory.createPoint(new Coordinate(40,15,0)));
//Scene dimension
Envelope cellEnvelope=new Envelope(new Coordinate(-170., -170.,0.),new Coordinate(170, 170,0.));
//Add source sound level
List<ArrayList<Double>> srcSpectrum=new ArrayList<ArrayList<Double>>();
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
List<Integer> freqLvl=new ArrayList<Integer>();
freqLvl.add(125);
//Build query structure for sources
QueryGeometryStructure sourcesIndex = new QueryGridIndex(
cellEnvelope, 8, 8);
int idsrc=0;
for(Geometry src : srclst) {
sourcesIndex.appendGeometry(src, idsrc);
idsrc++;
}
System.out.println("Construction scene in "+(System.currentTimeMillis()-startMakeScene)+"ms");
long startObstructionTest=System.currentTimeMillis();
//Create obstruction test object
FastObstructionTest manager = new FastObstructionTest();
manager.addGeometry(building1);
manager.finishPolygonFeeding(cellEnvelope);
//Retrieve Delaunay triangulation of scene
List<Triangle> tri=manager.getTriangles();
List<Coordinate> vert=manager.getVertices();
Stack<PropagationResultTriRecord> dataStack=new Stack<PropagationResultTriRecord>();
PropagationProcessData propData=new PropagationProcessData(vert,null, tri, manager, sourcesIndex, srclst, srcSpectrum, freqLvl, 0, 2, 80.,50., 1., 0., 0, null, null);
PropagationProcessOut propDataOut=new PropagationProcessOut(dataStack,null);
PropagationProcess propManager=new PropagationProcess(propData, propDataOut);
propManager.initStructures();
System.out.println("Propagation initialisation in "+(System.currentTimeMillis()-startObstructionTest)+"ms");
long startSimulation=System.currentTimeMillis();
//Run test
/////////////////////////////////////////////////////////////////////////
// Single diffraction test
propData.diffractionOrder=1;
propData.reflexionOrder=0;
splCompare(splCompute(propManager, new Coordinate(15,40,0)), "Scene 1 R4_S1", 46.81);
/////////////////////////////////////////////////////////////////////////
// Dual diffraction test
propData.diffractionOrder=2;
propData.reflexionOrder=0;
splCompare(splCompute(propManager, new Coordinate(5,15,0)), "Scene 1 R1_S1", 37.096);
/////////////////////////////////////////////////////////////////////////
// Geometric dispersion test
//Get reference spl value at 5m
propData.reflexionOrder=0;
propData.diffractionOrder=0;
double dbaRef=splCompute(propManager, new Coordinate(40,20,0));
//spl value at 10m
double dbaReduced=splCompute(propManager, new Coordinate(40,25,0));
splCompare(dbaReduced, "Scene 1 R2_S1", dbaRef-6.); //Double distance, then loss 6 dB. Atmospheric attenuation is not significant at 125Hz and 5 m distance
/////////////////////////////////////////////////////////////////////////
// First reflection test
dbaRef=splCompute(propManager, new Coordinate(35,15,0)); //Ref, at 5m of src, at 5m of wall
double dbaRef2=splCompute(propManager, new Coordinate(40,15+15,0));//Ref2, at 15m of src (Src->Receiver->Wall->Receiver : 5+5+5)
propData.reflexionOrder=1;
propData.wallAlpha=0.2;
double dbaReflection=splCompute(propManager, new Coordinate(35,15,0)); //dbaReflection must be equal to the energetic sum of Ref&Ref2, with Ref2 attenuated by wall alpha.
splCompare(dbaReflection, "Scene 1 R3_S1",PropagationProcess.wToDba( PropagationProcess.dbaToW(dbaRef)+PropagationProcess.dbaToW(dbaRef2)*(1-propData.wallAlpha)));
/////////////////////////////////////////////////////////////////////////
// Energetic sum of source test
// The same source duplicated at the same position must be equal to a single point source with an energetic sum of SPL.
// Get reference spl value
propData.reflexionOrder=0;
propData.diffractionOrder=0;
srcSpectrum.get(0).set(0,PropagationProcess.dbaToW(100.)+PropagationProcess.dbaToW(100.));
double dbaSingleSource=splCompute(propManager, new Coordinate(40,20,0));
//spl value
srcSpectrum.add(new ArrayList<Double>());
srcSpectrum.get(0).set(0,PropagationProcess.dbaToW(100.));
srcSpectrum.get(1).add(PropagationProcess.dbaToW(100.)); // 100 dB(A) @ 125 Hz
srclst.add(factory.createPoint(new Coordinate(40,15,0)));
sourcesIndex.appendGeometry(srclst.get(1), idsrc);
idsrc++;
double dbaDupp=splCompute(propManager, new Coordinate(40,20,0));
splCompare(dbaSingleSource, "Scene 1 R3_S2",dbaDupp);
System.out.println("Simulation done in "+(System.currentTimeMillis()-startSimulation)+"ms");
System.out.println(manager.getNbObstructionTest()+" obstruction test has been done..");
System.out.println("testScene1 done in "+(System.currentTimeMillis()-startMakeScene)+"ms");
}
|
diff --git a/src/tux2/MonsterBox/MonsterBoxBlockListener.java b/src/tux2/MonsterBox/MonsterBoxBlockListener.java
index 5548194..22d6404 100644
--- a/src/tux2/MonsterBox/MonsterBoxBlockListener.java
+++ b/src/tux2/MonsterBox/MonsterBoxBlockListener.java
@@ -1,126 +1,134 @@
package tux2.MonsterBox;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.inventory.ItemStack;
public class MonsterBoxBlockListener implements Listener {
MonsterBox plugin;
public ConcurrentHashMap<Integer, String> intmobs = new ConcurrentHashMap<Integer, String>();
public ConcurrentHashMap<String, Integer> stringmobs = new ConcurrentHashMap<String, Integer>();
public MonsterBoxBlockListener(MonsterBox plugin) {
this.plugin = plugin;
CreatureTypes[] mobs = CreatureTypes.values();
for(CreatureTypes mob : mobs) {
intmobs.put(new Integer(mob.id), mob.toString());
stringmobs.put(mob.toString(), new Integer(mob.id));
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockBreak(BlockBreakEvent event) {
event.getPlayer().getItemInHand();
if(!event.isCancelled() && event.getBlock().getType() == Material.MOB_SPAWNER) {
ItemStack is = event.getPlayer().getItemInHand();
//Check to see if the tool needs to be enchanted.
boolean nodrops = false;
if(plugin.disabledspawnerlocs.containsKey(plugin.locationBuilder(event.getBlock().getLocation()))) {
plugin.removeDisabledSpawner(event.getBlock());
nodrops = true;
}
if(plugin.needssilktouch && !itemHasSilkTouch(is)) {
return;
}
try {
CreatureSpawner theSpawner = (CreatureSpawner) event.getBlock().getState();
String monster = intmobs.get(new Integer(theSpawner.getSpawnedType().getTypeId()));
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.drops") || plugin.hasPermissions(event.getPlayer(), "monsterbox.dropegg")) {
if(nodrops) {
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just broke an " + ChatColor.RED + "unset" + ChatColor.DARK_GREEN + " spawner.");
}else {
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just broke a " + ChatColor.RED + monster.toLowerCase() + ChatColor.DARK_GREEN + " spawner.");
}
}
+ //fix the beserk thingy that some players have been reporting.
+ boolean mcmmofix = false;
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.drops")) {
ItemStack mobstack = new ItemStack(Material.MOB_SPAWNER, 1);
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), mobstack);
+ mcmmofix = true;
}
if(!nodrops && stringmobs.containsKey(monster) && plugin.hasPermissions(event.getPlayer(), "monsterbox.dropegg." + monster.toLowerCase())) {
ItemStack eggstack = new ItemStack(383, 1, theSpawner.getSpawnedType().getTypeId());
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), eggstack);
+ mcmmofix = true;
+ }
+ //If we dropped something, let's break the spawner
+ if(mcmmofix) {
+ event.getBlock().setType(Material.AIR);
}
}catch (Exception e) {
}
}
}
private boolean itemHasSilkTouch(ItemStack is) {
if(is != null && is.containsEnchantment(Enchantment.SILK_TOUCH)) {
return true;
}
return false;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
if(!event.isCancelled() && event.getBlockPlaced().getType() == Material.MOB_SPAWNER) {
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.place")) {
plugin.addDisabledSpawner(event.getBlockPlaced());
//This code doesn't work from 1.0.1 on, so why include it...
/*
String type = intmobs.get(plugin.playermonsterspawner.get(event.getPlayer().getName()));
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just placed a " + ChatColor.RED + type.toLowerCase() + ChatColor.DARK_GREEN + " spawner.");
CreatureSpawner theSpawner = (CreatureSpawner) event.getBlockPlaced().getState();
CreatureType ct = CreatureType.fromName(type);
if (ct == null) {
return;
}
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SetSpawner(theSpawner, ct));*/
}else {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.DARK_RED + "You don't have permission to place a monster spawner.");
}
}
}
//Make sure we remove mob spawners that get exploded
@EventHandler(priority = EventPriority.MONITOR)
public void explosion(EntityExplodeEvent event) {
if(event.isCancelled()) {
return;
}
for(Block block : event.blockList()) {
if(block.getType() == Material.MOB_SPAWNER) {
if(plugin.disabledspawnerlocs.containsKey(plugin.locationBuilder(block.getLocation()))) {
plugin.removeDisabledSpawner(block);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void mobSpawn(CreatureSpawnEvent event) {
if(!event.isCancelled()) {
if(event.getSpawnReason() == SpawnReason.SPAWNER) {
if(!plugin.canSpawnMob(event.getLocation(), event.getEntityType())) {
event.setCancelled(true);
}
}
}
}
}
| false | true | public void onBlockBreak(BlockBreakEvent event) {
event.getPlayer().getItemInHand();
if(!event.isCancelled() && event.getBlock().getType() == Material.MOB_SPAWNER) {
ItemStack is = event.getPlayer().getItemInHand();
//Check to see if the tool needs to be enchanted.
boolean nodrops = false;
if(plugin.disabledspawnerlocs.containsKey(plugin.locationBuilder(event.getBlock().getLocation()))) {
plugin.removeDisabledSpawner(event.getBlock());
nodrops = true;
}
if(plugin.needssilktouch && !itemHasSilkTouch(is)) {
return;
}
try {
CreatureSpawner theSpawner = (CreatureSpawner) event.getBlock().getState();
String monster = intmobs.get(new Integer(theSpawner.getSpawnedType().getTypeId()));
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.drops") || plugin.hasPermissions(event.getPlayer(), "monsterbox.dropegg")) {
if(nodrops) {
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just broke an " + ChatColor.RED + "unset" + ChatColor.DARK_GREEN + " spawner.");
}else {
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just broke a " + ChatColor.RED + monster.toLowerCase() + ChatColor.DARK_GREEN + " spawner.");
}
}
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.drops")) {
ItemStack mobstack = new ItemStack(Material.MOB_SPAWNER, 1);
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), mobstack);
}
if(!nodrops && stringmobs.containsKey(monster) && plugin.hasPermissions(event.getPlayer(), "monsterbox.dropegg." + monster.toLowerCase())) {
ItemStack eggstack = new ItemStack(383, 1, theSpawner.getSpawnedType().getTypeId());
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), eggstack);
}
}catch (Exception e) {
}
}
}
| public void onBlockBreak(BlockBreakEvent event) {
event.getPlayer().getItemInHand();
if(!event.isCancelled() && event.getBlock().getType() == Material.MOB_SPAWNER) {
ItemStack is = event.getPlayer().getItemInHand();
//Check to see if the tool needs to be enchanted.
boolean nodrops = false;
if(plugin.disabledspawnerlocs.containsKey(plugin.locationBuilder(event.getBlock().getLocation()))) {
plugin.removeDisabledSpawner(event.getBlock());
nodrops = true;
}
if(plugin.needssilktouch && !itemHasSilkTouch(is)) {
return;
}
try {
CreatureSpawner theSpawner = (CreatureSpawner) event.getBlock().getState();
String monster = intmobs.get(new Integer(theSpawner.getSpawnedType().getTypeId()));
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.drops") || plugin.hasPermissions(event.getPlayer(), "monsterbox.dropegg")) {
if(nodrops) {
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just broke an " + ChatColor.RED + "unset" + ChatColor.DARK_GREEN + " spawner.");
}else {
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + "You just broke a " + ChatColor.RED + monster.toLowerCase() + ChatColor.DARK_GREEN + " spawner.");
}
}
//fix the beserk thingy that some players have been reporting.
boolean mcmmofix = false;
if(plugin.hasPermissions(event.getPlayer(), "monsterbox.drops")) {
ItemStack mobstack = new ItemStack(Material.MOB_SPAWNER, 1);
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), mobstack);
mcmmofix = true;
}
if(!nodrops && stringmobs.containsKey(monster) && plugin.hasPermissions(event.getPlayer(), "monsterbox.dropegg." + monster.toLowerCase())) {
ItemStack eggstack = new ItemStack(383, 1, theSpawner.getSpawnedType().getTypeId());
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), eggstack);
mcmmofix = true;
}
//If we dropped something, let's break the spawner
if(mcmmofix) {
event.getBlock().setType(Material.AIR);
}
}catch (Exception e) {
}
}
}
|
diff --git a/App/src/com/dozuki/ifixit/ui/guide/create/StepEditActivity.java b/App/src/com/dozuki/ifixit/ui/guide/create/StepEditActivity.java
index 3ee0d277..06e02195 100644
--- a/App/src/com/dozuki/ifixit/ui/guide/create/StepEditActivity.java
+++ b/App/src/com/dozuki/ifixit/ui/guide/create/StepEditActivity.java
@@ -1,873 +1,874 @@
package com.dozuki.ifixit.ui.guide.create;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.dozuki.ifixit.MainApplication;
import com.dozuki.ifixit.R;
import com.dozuki.ifixit.model.Image;
import com.dozuki.ifixit.model.guide.Guide;
import com.dozuki.ifixit.model.guide.GuideStep;
import com.dozuki.ifixit.model.guide.StepLine;
import com.dozuki.ifixit.ui.BaseActivity;
import com.dozuki.ifixit.ui.gallery.GalleryActivity;
import com.dozuki.ifixit.ui.guide.view.GuideViewActivity;
import com.dozuki.ifixit.util.APIError;
import com.dozuki.ifixit.util.APIEvent;
import com.dozuki.ifixit.util.APIService;
import com.squareup.otto.Subscribe;
import com.viewpagerindicator.TitlePageIndicator;
import java.util.ArrayList;
import java.util.Iterator;
public class StepEditActivity extends BaseActivity implements OnClickListener {
public static final int MENU_VIEW_GUIDE = 12;
private static final int STEP_VIEW = 1;
private static final int FOR_RESULT = 2;
private static final int HOME_UP = 3;
public static final int GALLERY_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 1888;
public static final String TEMP_FILE_NAME_KEY = "TEMP_FILE_NAME_KEY";
public static final String EXIT_CODE = "EXIT_CODE_KEY";
public static final String GUIDE_PUBLIC_KEY = "GUIDE_PUBLIC_KEY";
public static String GUIDE_STEP_NUM_KEY = "GUIDE_STEP_NUM_KEY";
public static String DELETE_GUIDE_DIALOG_KEY = "DeleteGuideDialog";
public static final String GUIDE_ID_KEY = "GUIDE_ID_KEY";
public static final String GUIDE_STEP_ID = "GUIDE_STEP_ID";
public static final String PARENT_GUIDE_ID_KEY = "PARENT_GUIDE_ID_KEY";
public static final int NO_PARENT_GUIDE = -1;
private static final String SHOWING_HELP = "SHOWING_HELP";
private static final String IS_GUIDE_DIRTY_KEY = "IS_GUIDE_DIRTY_KEY";
private static final String SHOWING_SAVE = "SHOWING_SAVE";
private static final String LOCK_SAVE = "LOCK_SAVE";
private Guide mGuide;
private StepEditFragment mCurStepFragment;
private ImageButton mAddStepButton;
private Button mSaveStep;
private ImageButton mDeleteStepButton;
private StepAdapter mStepAdapter;
private LockableViewPager mPager;
private TitlePageIndicator titleIndicator;
private int mPagePosition = 0;
private int mSavePosition;
// Necessary for editing prerequisite guides from the view interface in order to navigate back to the parent guide.
private int mParentGuideId = NO_PARENT_GUIDE;
// Used to navigate to the correct step when coming from GuideViewActivity.
private int mInboundStepId;
private boolean mConfirmDelete = false;
private boolean mIsStepDirty;
private boolean mShowingHelp;
private boolean mShowingSave;
private boolean mIsLoading;
// Flag to prevent saving a guide while we're waiting for an image to upload and return
private boolean mLockSave;
private int mExitCode;
private static int mLoadingContainer = R.id.step_edit_loading_screen;
/////////////////////////////////////////////////////
// LIFECYCLE
/////////////////////////////////////////////////////
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* lock screen for small sizes to portrait.
* Courtesy:
* http://stackoverflow.com/questions/10491531/android-restrict-activity-orientation-based-on-screen-size
**/
if (MainApplication.get().isScreenLarge()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
extractExtras(getIntent().getExtras());
if (savedInstanceState != null) {
mGuide = (Guide) savedInstanceState.getSerializable(StepsActivity.GUIDE_KEY);
mPagePosition = savedInstanceState.getInt(GUIDE_STEP_NUM_KEY);
mConfirmDelete = savedInstanceState.getBoolean(DELETE_GUIDE_DIALOG_KEY);
mIsStepDirty = savedInstanceState.getBoolean(IS_GUIDE_DIRTY_KEY);
mShowingHelp = savedInstanceState.getBoolean(SHOWING_HELP);
mShowingSave = savedInstanceState.getBoolean(SHOWING_SAVE);
mLockSave = savedInstanceState.getBoolean(LOCK_SAVE);
mIsLoading = savedInstanceState.getBoolean(LOADING);
mExitCode = savedInstanceState.getInt(EXIT_CODE);
if (mShowingHelp) {
createHelpDialog().show();
}
if (mShowingSave) {
createExitWarningDialog(mExitCode).show();
}
}
setContentView(R.layout.guide_create_step_edit);
mSaveStep = (Button) findViewById(R.id.step_edit_save);
toggleSave(mIsStepDirty);
if (mGuide != null) {
initPage(mPagePosition);
}
}
private void initPage(int startPage) {
getSupportActionBar().setTitle(mGuide.getTitle());
mAddStepButton = (ImageButton) findViewById(R.id.step_edit_add_step);
mDeleteStepButton = (ImageButton) findViewById(R.id.step_edit_delete_step);
mPager = (LockableViewPager) findViewById(R.id.guide_edit_body_pager);
initPager();
mPager.setCurrentItem(startPage);
titleIndicator = (TitlePageIndicator) findViewById(R.id.step_edit_top_bar);
titleIndicator.setViewPager(mPager);
mSaveStep.setOnClickListener(this);
mAddStepButton.setOnClickListener(this);
mDeleteStepButton.setOnClickListener(this);
if (mConfirmDelete) {
createDeleteDialog(this).show();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (mIsLoading) {
mPager.setVisibility(View.GONE);
}
}
private void initPager() {
mStepAdapter = new StepAdapter(this.getSupportFragmentManager());
mPager.setAdapter(mStepAdapter);
}
private void extractExtras(Bundle extras) {
if (extras != null) {
mGuide = (Guide) extras.getSerializable(GuideCreateActivity.GUIDE_KEY);
mPagePosition = extras.getInt(GUIDE_STEP_NUM_KEY, 0);
if (mGuide == null) {
mParentGuideId = extras.getInt(PARENT_GUIDE_ID_KEY, NO_PARENT_GUIDE);
mInboundStepId = extras.getInt(GUIDE_STEP_ID);
showLoading(mLoadingContainer);
APIService.call(StepEditActivity.this,
APIService.getGuideForEditAPICall(extras.getInt(GUIDE_ID_KEY)));
}
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mGuide = null;
mPagePosition = 0;
extractExtras(intent.getExtras());
if (mGuide != null) {
initPage(mPagePosition);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
- //MainApplication.getBus().register(this);
+ MainApplication.getBus().register(this);
super.onActivityResult(requestCode, resultCode, data);
if (mCurStepFragment != null) {
Image newThumb;
switch (requestCode) {
case GALLERY_REQUEST_CODE:
if (data != null) {
newThumb = (Image) data.getSerializableExtra(GalleryActivity.MEDIA_RETURN_KEY);
mGuide.getStep(mPagePosition).addImage(newThumb);
mCurStepFragment.setImages(mGuide.getStep(mPagePosition).getImages());
+ MainApplication.getBus().post(new StepChangedEvent());
} else {
Log.e("StepEditActivity", "Error data is null!");
return;
}
break;
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
SharedPreferences prefs = getSharedPreferences("com.dozuki.ifixit", Context.MODE_PRIVATE);
String tempFileName = prefs.getString(TEMP_FILE_NAME_KEY, null);
if (tempFileName == null) {
Log.e("StepEditActivity", "Error cameraTempFile is null!");
return;
}
// Prevent a save from being called until the image uploads and returns with the imageid
lockSave();
newThumb = new Image();
newThumb.setLocalImage(tempFileName);
mGuide.getStep(mPagePosition).addImage(newThumb);
mCurStepFragment.setImages(mGuide.getStep(mPagePosition).getImages());
APIService.call(this, APIService.getUploadImageToStepAPICall(tempFileName));
}
break;
}
} else {
if (resultCode == RESULT_OK) {
// we dont have a reference the the fragment managing the media, so we make the changes to the step manually
Image image = (Image) data.getSerializableExtra(GalleryActivity.MEDIA_RETURN_KEY);
ArrayList<Image> list = mGuide.getStep(mPagePosition).getImages();
if (list.size() > 0) {
list.set(0, image);
} else {
list.add(image);
}
mGuide.getStep(mPagePosition).setImages(list);
toggleSave(true);
// recreate pager with updated step:
initPager();
mPager.invalidate();
titleIndicator.invalidate();
mPager.setCurrentItem(mPagePosition, false);
}
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putSerializable(StepsActivity.GUIDE_KEY, mGuide);
savedInstanceState.putBoolean(DELETE_GUIDE_DIALOG_KEY, mConfirmDelete);
savedInstanceState.putInt(StepEditActivity.GUIDE_STEP_NUM_KEY, mPagePosition);
savedInstanceState.putBoolean(IS_GUIDE_DIRTY_KEY, mIsStepDirty);
savedInstanceState.putBoolean(SHOWING_HELP, mShowingHelp);
savedInstanceState.putBoolean(SHOWING_SAVE, mShowingSave);
savedInstanceState.putBoolean(LOADING, mIsLoading);
savedInstanceState.putBoolean(LOCK_SAVE, mLockSave);
savedInstanceState.putInt(EXIT_CODE, mExitCode);
}
public void navigateBack() {
Intent returnIntent = new Intent();
returnIntent.putExtra(GuideCreateActivity.GUIDE_KEY, mGuide);
setResult(RESULT_OK, returnIntent);
finish();
}
@Override
public boolean finishActivityIfLoggedOut() {
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(1, MENU_VIEW_GUIDE, 0, R.string.view_guide)
.setIcon(R.drawable.ic_action_book)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
/////////////////////////////////////////////////////
// NOTIFICATION LISTENERS
/////////////////////////////////////////////////////
@Subscribe
public void onGuideGet(APIEvent.GuideForEdit event) {
hideLoading();
if (!event.hasError()) {
int startPagePosition = 0;
mGuide = event.getResult();
for (int i = 0; i < mGuide.getSteps().size(); i++) {
if (mGuide.getStep(i).getStepid() == mInboundStepId) {
startPagePosition = i;
break;
}
}
initPage(startPagePosition);
} else {
event.setError(APIError.getFatalError(this));
APIService.getErrorDialog(StepEditActivity.this, event.getError(), null).show();
}
}
@Subscribe
public void onStepSave(APIEvent.StepSave event) {
hideLoading();
if (!event.hasError()) {
GuideStep step = event.getResult();
mGuide.getSteps().set(mSavePosition, step);
} else {
mIsStepDirty = true;
toggleSave(mIsStepDirty);
event.setError(APIError.getFatalError(this));
APIService.getErrorDialog(StepEditActivity.this, event.getError(), null).show();
}
}
@Subscribe
public void onUploadStepImage(APIEvent.UploadStepImage event) {
if (!event.hasError()) {
Image newThumb = event.getResult();
// Find the temporarily stored image object to update the filename to the image path and imageid
if (newThumb != null) {
ArrayList<Image> images = new ArrayList<Image>(mGuide.getStep(mPagePosition).getImages());
for (Image image : images) {
if (image.isLocal()) {
images.set(images.indexOf(image), newThumb);
break;
}
}
mCurStepFragment.setImages(images);
mGuide.getStep(mPagePosition).setImages(images);
}
if (!mGuide.getStep(mPagePosition).hasLocalImages()) {
unlockSave();
// Set guide dirty after the image is uploaded so the user can't save the guide before we have the imageid
MainApplication.getBus().post(new StepChangedEvent());
}
} else {
Log.e("Upload Image Error", event.getError().mMessage);
event.setError(APIError.getFatalError(this));
APIService.getErrorDialog(this, event.getError(), null).show();
}
}
@Subscribe
public void onStepImageDelete(StepImageDeleteEvent event) {
mGuide.getStep(mPagePosition).getImages().remove(event.image);
}
@Subscribe
public void onStepAdd(APIEvent.StepAdd event) {
hideLoading();
if (!event.hasError()) {
mGuide = event.getResult();
mStepAdapter.notifyDataSetChanged();
mPager.setCurrentItem(mPagePosition);
} else {
mIsStepDirty = true;
toggleSave(mIsStepDirty);
event.setError(APIError.getFatalError(this));
APIService.getErrorDialog(StepEditActivity.this, event.getError(), null).show();
}
}
@Subscribe
public void onGuideStepDeleted(APIEvent.StepRemove event) {
hideLoading();
if (!event.hasError()) {
mGuide.setRevisionid(event.getResult().getRevisionid());
deleteStep(false);
} else {
event.setError(APIError.getFatalError(this));
APIService.getErrorDialog(StepEditActivity.this, event.getError(), null).show();
}
}
@Subscribe
public void onImageCopy(APIEvent.CopyImage event) {
if (!event.hasError()) {
Toast.makeText(this, getString(R.string.image_saved_to_media_manager_toast),
Toast.LENGTH_LONG).show();
} else {
event.setError(APIError.getFatalError(this));
APIService.getErrorDialog(StepEditActivity.this, event.getError(), null).show();
}
}
@Subscribe
public void onGuideChanged(StepChangedEvent event) {
mIsStepDirty = true;
toggleSave(mIsStepDirty);
}
/////////////////////////////////////////////////////
// UI EVENT LISTENERS
/////////////////////////////////////////////////////
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.step_edit_delete_step:
if (!mGuide.getSteps().isEmpty()) {
createDeleteDialog(StepEditActivity.this).show();
}
break;
case R.id.step_edit_save:
save(mPagePosition);
break;
case R.id.step_edit_add_step:
int newPosition = mPagePosition + 1;
// If the step has changes, save it first.
if (mIsStepDirty) {
save(mPagePosition);
} else if (!stepHasLineContent(mGuide.getStep(mPagePosition))) {
Toast.makeText(this, getResources().getString(R.string.guide_create_edit_step_media_cannot_add_step),
Toast.LENGTH_SHORT).show();
return;
} else {
GuideStep item = new GuideStep(StepPortalFragment.STEP_ID++);
item.setTitle(StepPortalFragment.DEFAULT_TITLE);
item.addLine(new StepLine());
item.setStepNum(newPosition);
mGuide.addStep(item, newPosition);
for (int i = 1; i < mGuide.getSteps().size(); i++) {
mGuide.getStep(i).setStepNum(i);
}
// The view pager does not recreate the item in the current position unless we force it
initPager();
mPager.invalidate();
titleIndicator.invalidate();
mPager.setCurrentItem(newPosition, false);
}
break;
}
}
@Override
public void onBackPressed() {
finishEdit(HOME_UP);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_VIEW_GUIDE:
finishEdit(STEP_VIEW);
}
return (super.onOptionsItemSelected(item));
}
/////////////////////////////////////////////////////
// ADAPTERS and PRIVATE CLASSES
/////////////////////////////////////////////////////
public class StepAdapter extends FragmentStatePagerAdapter {
public StepAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return mGuide.getSteps().size();
}
@Override
public CharSequence getPageTitle(int position) {
return getString(R.string.step_number, position + 1);
}
@Override
public Fragment getItem(int position) {
return StepEditFragment.newInstance(mGuide.getStep(position));
}
/**
* When you call notifyDataSetChanged(), if it's set to POSITION_NONE, the view pager will remove all views and
* reload them all.
*/
@Override
public int getItemPosition(Object object) {
/*StepEditFragment page = (StepEditFragment)object;
GuideStep step = page.getStepObject();
int position = mGuide.getSteps().indexOf(step);
if (position >= 0) {
return position;
} else {*/
return POSITION_NONE;
// }
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
mPagePosition = position;
mCurStepFragment = (StepEditFragment) object;
}
}
/////////////////////////////////////////////////////
// DIALOGS
/////////////////////////////////////////////////////
protected AlertDialog createDeleteDialog(final Context context) {
mConfirmDelete = true;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setTitle(context.getString(R.string.step_edit_confirm_delete_title))
.setMessage(context.getString(R.string.step_edit_confirm_delete_message, mPagePosition + 1))
.setPositiveButton(context.getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
mConfirmDelete = false;
mIsStepDirty = false;
//step is at end of list
if (mPagePosition >= mGuide.getSteps().size()
// or it's a new step
|| mGuide.getStep(mPagePosition).getRevisionid() == null) {
deleteStep(mIsStepDirty);
} else {
showLoading(mLoadingContainer, getString(R.string.deleting));
APIService.call(StepEditActivity.this, APIService.getRemoveStepAPICall(
mGuide.getGuideid(), mGuide.getSteps().get(mPagePosition)));
}
dialog.cancel();
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mConfirmDelete = false;
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mConfirmDelete = false;
}
});
return dialog;
}
protected AlertDialog createHelpDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.media_help_title))
.setMessage(getString(R.string.guide_create_edit_steps_help))
.setPositiveButton(getString(R.string.media_help_confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
return builder.create();
}
protected AlertDialog createExitWarningDialog(final int exitCode) {
mShowingSave = true;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle(getString(R.string.guide_create_confirm_leave_without_save_title))
.setMessage(getString(R.string.guide_create_confirm_leave_without_save_body))
.setNegativeButton(getString(R.string.save),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mIsStepDirty = true;
save(mPagePosition);
dialog.dismiss();
if (mExitCode == STEP_VIEW) {
navigateToStepView();
} else {
navigateBack();
}
}
})
.setPositiveButton(R.string.guide_create_confirm_leave_without_save_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mIsStepDirty = false;
dialog.dismiss();
finishEdit(exitCode);
}
});
AlertDialog dialog = builder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mShowingSave = false;
}
});
return dialog;
}
/////////////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////////////
protected void save(int savePosition) {
GuideStep obj = mGuide.getStep(savePosition);
obj.setLines(mCurStepFragment.getLines());
obj.setTitle(mCurStepFragment.getTitle());
mGuide.getSteps().set(savePosition, obj);
if (!stepHasLineContent(obj)) {
Toast.makeText(this, getResources().getString(R.string.guide_create_edit_must_add_line_content),
Toast.LENGTH_SHORT).show();
return;
}
if (!mIsStepDirty || mLockSave) {
return;
}
mSavePosition = savePosition;
mIsStepDirty = false;
showLoading(mLoadingContainer, getString(R.string.saving));
toggleSave(mIsStepDirty);
if (obj.getRevisionid() != null) {
APIService.call(this, APIService.getEditStepAPICall(obj, mGuide.getGuideid()));
} else {
APIService.call(this, APIService.getAddStepAPICall(obj, mGuide.getGuideid(),
mPagePosition + 1, mGuide.getRevisionid()));
}
}
private boolean stepHasLineContent(GuideStep obj) {
if (obj.getLines().size() == 0) {
return false;
}
for (StepLine l : obj.getLines()) {
if (l.getTextRaw().length() == 0) {
return false;
}
}
return true;
}
@Override
public void showLoading(int container) {
if (mPager != null) {
mPager.setVisibility(View.GONE);
}
mIsLoading = true;
super.showLoading(container);
}
@Override
public void showLoading(int container, String message) {
if (mPager != null) {
mPager.setVisibility(View.GONE);
}
mIsLoading = true;
super.showLoading(container, message);
}
@Override
public void hideLoading() {
if (mPager != null) {
mPager.setVisibility(View.VISIBLE);
}
getSupportFragmentManager().popBackStack(LOADING, FragmentManager.POP_BACK_STACK_INCLUSIVE);
mIsLoading = false;
}
protected void navigateToStepView() {
Intent intent = new Intent(this, GuideViewActivity.class);
if (mParentGuideId != NO_PARENT_GUIDE) {
intent.putExtra(GuideViewActivity.GUIDEID, mParentGuideId);
} else {
intent.putExtra(GuideViewActivity.GUIDEID, mGuide.getGuideid());
}
intent.putExtra(GuideViewActivity.CURRENT_PAGE, mPagePosition + 1);
intent.putExtra(GuideViewActivity.INBOUND_STEP_ID, mGuide.getStep(mPagePosition).getStepid());
intent.putExtra(StepEditActivity.GUIDE_PUBLIC_KEY, mGuide.isPublic());
intent.putExtra(GuideViewActivity.FROM_EDIT, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
protected void finishEdit(int exitCode) {
mExitCode = exitCode;
if (mIsStepDirty || mLockSave) {
createExitWarningDialog(exitCode).show();
} else {
// Clean out unsaved, new steps.
for (Iterator<GuideStep> it = mGuide.getSteps().iterator(); it.hasNext(); ) {
if (it.next().getRevisionid() == null) {
it.remove();
}
}
int guideSize = mGuide.getSteps().size();
// Make sure the step numbers are correct after removing steps.
for (int i = 1; i <= guideSize; i++) {
mGuide.getStep(i - 1).setStepNum(i);
}
// If the current position is equal to or greater than the number of steps in the guide,
// there was a new step at the end of the guide and that position no longer exists. Set the page position
// to the new last step.
if (mPagePosition >= guideSize) {
mPagePosition = guideSize - 1;
}
Intent data;
switch (exitCode) {
case HOME_UP:
data = new Intent(this, StepsActivity.class);
data.putExtra(StepsActivity.GUIDE_ID_KEY, mGuide.getGuideid());
data.putExtra(GuideCreateActivity.GUIDE_KEY, mGuide);
data.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(data);
break;
case FOR_RESULT:
data = new Intent();
data.putExtra(GuideCreateActivity.GUIDE_KEY, mGuide);
if (getParent() == null) {
setResult(Activity.RESULT_OK, data);
} else {
getParent().setResult(Activity.RESULT_OK, data);
}
finish();
break;
case STEP_VIEW:
navigateToStepView();
break;
}
}
}
protected void deleteStep(boolean unsaved) {
// Delete the step if it hasn't been saved yet.
if (mPagePosition < mGuide.getSteps().size() && !unsaved) {
mGuide.getSteps().remove(mPagePosition);
}
// If it's the last step in the guide, finish the activity.
if (mGuide.getSteps().size() == 0) {
finish();
return;
}
int guideSize = mGuide.getSteps().size();
for (int i = 0; i < guideSize; i++) {
mGuide.getStep(i).setStepNum(i);
}
// The view pager does not recreate the item in the current position unless we force it to:
initPager();
mPager.setCurrentItem(mPagePosition);
mPager.invalidate();
titleIndicator.invalidate();
}
public void toggleSave(boolean toggle) {
if (!mLockSave) {
int buttonBackgroundColor = toggle ? R.color.fireswing_blue : R.color.fireswing_dark_grey;
int buttonTextColor = toggle ? R.color.white : R.color.fireswing_grey;
mSaveStep.setBackgroundColor(getResources().getColor(buttonBackgroundColor));
mSaveStep.setTextColor(getResources().getColor(buttonTextColor));
mSaveStep.setText(R.string.save);
mSaveStep.setEnabled(toggle);
// Lock the pager if save is enabled
enableViewPager(!toggle);
}
}
protected void enableViewPager(boolean unlocked) {
if (mPager != null) {
mPager.setPagingEnabled(unlocked);
}
}
public void lockSave() {
mLockSave = true;
mSaveStep.setText(getString(R.string.loading_image));
mSaveStep.setBackgroundColor(getResources().getColor(R.color.fireswing_dark_grey));
mSaveStep.setTextColor(getResources().getColor(R.color.fireswing_grey));
enableViewPager(false);
}
public void unlockSave() {
mLockSave = false;
enableViewPager(true);
}
}
| false | true | public void onActivityResult(int requestCode, int resultCode, Intent data) {
//MainApplication.getBus().register(this);
super.onActivityResult(requestCode, resultCode, data);
if (mCurStepFragment != null) {
Image newThumb;
switch (requestCode) {
case GALLERY_REQUEST_CODE:
if (data != null) {
newThumb = (Image) data.getSerializableExtra(GalleryActivity.MEDIA_RETURN_KEY);
mGuide.getStep(mPagePosition).addImage(newThumb);
mCurStepFragment.setImages(mGuide.getStep(mPagePosition).getImages());
} else {
Log.e("StepEditActivity", "Error data is null!");
return;
}
break;
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
SharedPreferences prefs = getSharedPreferences("com.dozuki.ifixit", Context.MODE_PRIVATE);
String tempFileName = prefs.getString(TEMP_FILE_NAME_KEY, null);
if (tempFileName == null) {
Log.e("StepEditActivity", "Error cameraTempFile is null!");
return;
}
// Prevent a save from being called until the image uploads and returns with the imageid
lockSave();
newThumb = new Image();
newThumb.setLocalImage(tempFileName);
mGuide.getStep(mPagePosition).addImage(newThumb);
mCurStepFragment.setImages(mGuide.getStep(mPagePosition).getImages());
APIService.call(this, APIService.getUploadImageToStepAPICall(tempFileName));
}
break;
}
} else {
if (resultCode == RESULT_OK) {
// we dont have a reference the the fragment managing the media, so we make the changes to the step manually
Image image = (Image) data.getSerializableExtra(GalleryActivity.MEDIA_RETURN_KEY);
ArrayList<Image> list = mGuide.getStep(mPagePosition).getImages();
if (list.size() > 0) {
list.set(0, image);
} else {
list.add(image);
}
mGuide.getStep(mPagePosition).setImages(list);
toggleSave(true);
// recreate pager with updated step:
initPager();
mPager.invalidate();
titleIndicator.invalidate();
mPager.setCurrentItem(mPagePosition, false);
}
}
}
| public void onActivityResult(int requestCode, int resultCode, Intent data) {
MainApplication.getBus().register(this);
super.onActivityResult(requestCode, resultCode, data);
if (mCurStepFragment != null) {
Image newThumb;
switch (requestCode) {
case GALLERY_REQUEST_CODE:
if (data != null) {
newThumb = (Image) data.getSerializableExtra(GalleryActivity.MEDIA_RETURN_KEY);
mGuide.getStep(mPagePosition).addImage(newThumb);
mCurStepFragment.setImages(mGuide.getStep(mPagePosition).getImages());
MainApplication.getBus().post(new StepChangedEvent());
} else {
Log.e("StepEditActivity", "Error data is null!");
return;
}
break;
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
SharedPreferences prefs = getSharedPreferences("com.dozuki.ifixit", Context.MODE_PRIVATE);
String tempFileName = prefs.getString(TEMP_FILE_NAME_KEY, null);
if (tempFileName == null) {
Log.e("StepEditActivity", "Error cameraTempFile is null!");
return;
}
// Prevent a save from being called until the image uploads and returns with the imageid
lockSave();
newThumb = new Image();
newThumb.setLocalImage(tempFileName);
mGuide.getStep(mPagePosition).addImage(newThumb);
mCurStepFragment.setImages(mGuide.getStep(mPagePosition).getImages());
APIService.call(this, APIService.getUploadImageToStepAPICall(tempFileName));
}
break;
}
} else {
if (resultCode == RESULT_OK) {
// we dont have a reference the the fragment managing the media, so we make the changes to the step manually
Image image = (Image) data.getSerializableExtra(GalleryActivity.MEDIA_RETURN_KEY);
ArrayList<Image> list = mGuide.getStep(mPagePosition).getImages();
if (list.size() > 0) {
list.set(0, image);
} else {
list.add(image);
}
mGuide.getStep(mPagePosition).setImages(list);
toggleSave(true);
// recreate pager with updated step:
initPager();
mPager.invalidate();
titleIndicator.invalidate();
mPager.setCurrentItem(mPagePosition, false);
}
}
}
|
diff --git a/holmes-rome-modules/src/main/java/com/sun/syndication/feed/module/mediarss/io/MediaModuleParser.java b/holmes-rome-modules/src/main/java/com/sun/syndication/feed/module/mediarss/io/MediaModuleParser.java
index 9977325a..72eff7db 100644
--- a/holmes-rome-modules/src/main/java/com/sun/syndication/feed/module/mediarss/io/MediaModuleParser.java
+++ b/holmes-rome-modules/src/main/java/com/sun/syndication/feed/module/mediarss/io/MediaModuleParser.java
@@ -1,437 +1,438 @@
/*
* Copyright 2006 Nathanial X. Freitas, openvision.tv
*
* This code is currently released under the Mozilla Public License.
* http://www.mozilla.org/MPL/
*
* Alternately you may apply the terms of the Apache Software License
*
* 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.sun.syndication.feed.module.mediarss.io;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Element;
import org.jdom.Namespace;
import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.module.mediarss.MediaEntryModuleImpl;
import com.sun.syndication.feed.module.mediarss.MediaModule;
import com.sun.syndication.feed.module.mediarss.MediaModuleImpl;
import com.sun.syndication.feed.module.mediarss.types.Category;
import com.sun.syndication.feed.module.mediarss.types.Credit;
import com.sun.syndication.feed.module.mediarss.types.Expression;
import com.sun.syndication.feed.module.mediarss.types.Hash;
import com.sun.syndication.feed.module.mediarss.types.MediaContent;
import com.sun.syndication.feed.module.mediarss.types.MediaGroup;
import com.sun.syndication.feed.module.mediarss.types.Metadata;
import com.sun.syndication.feed.module.mediarss.types.PlayerReference;
import com.sun.syndication.feed.module.mediarss.types.Rating;
import com.sun.syndication.feed.module.mediarss.types.Restriction;
import com.sun.syndication.feed.module.mediarss.types.Text;
import com.sun.syndication.feed.module.mediarss.types.Thumbnail;
import com.sun.syndication.feed.module.mediarss.types.Time;
import com.sun.syndication.feed.module.mediarss.types.UrlReference;
import com.sun.syndication.io.ModuleParser;
import com.sun.syndication.io.impl.NumberParser;
/**
* @author Nathanial X. Freitas
*
*/
public class MediaModuleParser implements ModuleParser {
private static final Logger logger = Logger.getLogger(MediaModuleParser.class.getName());
/*
* Namespace instance for this URI.
*/
private static final Namespace NS = Namespace.getNamespace(MediaModule.URI);
/* (non-Javadoc)
* @see com.sun.syndication.io.ModuleParser#getNamespaceUri()
*/
@Override
public String getNamespaceUri() {
return MediaModule.URI;
}
/* (non-Javadoc)
* @see com.sun.syndication.io.ModuleParser#parse(org.jdom.Element)
*/
@Override
public Module parse(Element mmRoot) {
MediaModuleImpl mod = null;
if (mmRoot.getName().equals("channel") || mmRoot.getName().equals("feed")) {
mod = new MediaModuleImpl();
} else {
mod = new MediaEntryModuleImpl();
}
mod.setMetadata(parseMetadata(mmRoot));
mod.setPlayer(parsePlayer(mmRoot));
if (mod instanceof MediaEntryModuleImpl) {
MediaEntryModuleImpl m = (MediaEntryModuleImpl) mod;
m.setMediaContents(parseContent(mmRoot));
m.setMediaGroups(parseGroup(mmRoot));
}
return mod;
}
private MediaContent[] parseContent(Element e) {
List<?> contents = e.getChildren("content", getNS());
ArrayList<MediaContent> values = new ArrayList<MediaContent>();
try {
for (int i = 0; (contents != null) && (i < contents.size()); i++) {
Element content = (Element) contents.get(i);
MediaContent mc = null;
if (content.getAttributeValue("url") != null) {
try {
mc = new MediaContent(new UrlReference(new URI(content.getAttributeValue("url"))));
mc.setPlayer(parsePlayer(content));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
} else {
mc = new MediaContent(parsePlayer(content));
}
if (mc != null) {
values.add(mc);
try {
mc.setAudioChannels((content.getAttributeValue("channels") == null) ? null : new Integer(content.getAttributeValue("channels")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
try {
mc.setBitrate((content.getAttributeValue("bitrate") == null) ? null : new Float(content.getAttributeValue("bitrate")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
try {
mc.setDuration((content.getAttributeValue("duration") == null) ? null : new Long(content.getAttributeValue("duration")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
String expression = content.getAttributeValue("expression");
if (expression != null) {
if (expression.equalsIgnoreCase("full")) {
mc.setExpression(Expression.FULL);
} else if (expression.equalsIgnoreCase("sample")) {
mc.setExpression(Expression.SAMPLE);
} else if (expression.equalsIgnoreCase("nonstop")) {
mc.setExpression(Expression.NONSTOP);
}
}
try {
mc.setFileSize((content.getAttributeValue("fileSize") == null) ? null : NumberParser.parseLong(content.getAttributeValue("fileSize")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
try {
mc.setFramerate((content.getAttributeValue("framerate") == null) ? null : NumberParser.parseFloat(content
.getAttributeValue("framerate")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
try {
mc.setHeight((content.getAttributeValue("height") == null) ? null : NumberParser.parseInt(content.getAttributeValue("height")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
mc.setLanguage(content.getAttributeValue("lang"));
mc.setMetadata(parseMetadata(content));
try {
mc.setSamplingrate((content.getAttributeValue("samplingrate") == null) ? null : NumberParser.parseFloat(content
.getAttributeValue("samplingrate")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
mc.setType(content.getAttributeValue("type"));
try {
mc.setWidth((content.getAttributeValue("width") == null) ? null : NumberParser.parseInt(content.getAttributeValue("width")));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
mc.setDefaultContent((content.getAttributeValue("isDefault") == null) ? false : Boolean.getBoolean(content.getAttributeValue("isDefault")));
} else {
logger.log(Level.WARNING, "Could not find MediaContent.");
}
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing content tag.", ex);
}
return values.toArray(new MediaContent[values.size()]);
}
private MediaGroup[] parseGroup(Element e) {
List<?> groups = e.getChildren("group", getNS());
ArrayList<MediaGroup> values = new ArrayList<MediaGroup>();
for (int i = 0; (groups != null) && (i < groups.size()); i++) {
Element group = (Element) groups.get(i);
MediaGroup g = new MediaGroup(parseContent(group));
for (int j = 0; j < g.getContents().length; j++) {
if (g.getContents()[j].isDefaultContent()) {
g.setDefaultContentIndex(new Integer(j));
break;
}
}
g.setMetadata(parseMetadata(group));
values.add(g);
}
return values.toArray(new MediaGroup[values.size()]);
}
private Metadata parseMetadata(Element e) {
Metadata md = new Metadata();
// categories
{
List<?> categories = e.getChildren("category", getNS());
ArrayList<Category> values = new ArrayList<Category>();
for (int i = 0; (categories != null) && (i < categories.size()); i++) {
try {
Element cat = (Element) categories.get(i);
values.add(new Category(cat.getAttributeValue("scheme"), cat.getAttributeValue("label"), cat.getText()));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing category tag.", ex);
}
}
md.setCategories(values.toArray(new Category[values.size()]));
}
// copyright
try {
Element copy = e.getChild("copyright", getNS());
if (copy != null) {
md.setCopyright(copy.getText());
md.setCopyrightUrl((copy.getAttributeValue("url") != null) ? new URI(copy.getAttributeValue("url")) : null);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing copyright tag.", ex);
}
// credits
{
List<?> credits = e.getChildren("credit", getNS());
ArrayList<Credit> values = new ArrayList<Credit>();
for (int i = 0; (credits != null) && (i < credits.size()); i++) {
try {
Element cred = (Element) credits.get(i);
values.add(new Credit(cred.getAttributeValue("scheme"), cred.getAttributeValue("role"), cred.getText()));
md.setCredits(values.toArray(new Credit[values.size()]));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing credit tag.", ex);
}
}
}
// description
try {
Element description = e.getChild("description", getNS());
if (description != null) {
md.setDescription(description.getText());
md.setDescriptionType(description.getAttributeValue("type"));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing description tag.", ex);
}
// hash
try {
Element hash = e.getChild("hash", getNS());
if (hash != null) {
md.setHash(new Hash(hash.getAttributeValue("algo"), hash.getText()));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing hash tag.", ex);
}
// keywords
{
Element keywords = e.getChild("keywords", getNS());
if (keywords != null) {
StringTokenizer tok = new StringTokenizer(keywords.getText(), ",");
String[] value = new String[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
value[i] = tok.nextToken().trim();
}
md.setKeywords(value);
}
}
// ratings
{
List<?> ratings = e.getChildren("rating", getNS());
ArrayList<Rating> values = new ArrayList<Rating>();
for (int i = 0; (ratings != null) && (i < ratings.size()); i++) {
try {
Element rat = (Element) ratings.get(i);
- values.add(new Rating(rat.getAttributeValue("scheme"), rat.getText()));
+ if (rat.getText() != null && rat.getAttributeValue("scheme") != null)
+ values.add(new Rating(rat.getAttributeValue("scheme"), rat.getText()));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing rating tag.", ex);
}
}
md.setRatings(values.toArray(new Rating[values.size()]));
}
// text
{
List<?> texts = e.getChildren("text", getNS());
ArrayList<Text> values = new ArrayList<Text>();
for (int i = 0; (texts != null) && (i < texts.size()); i++) {
try {
Element text = (Element) texts.get(i);
Time start = (text.getAttributeValue("start") == null) ? null : new Time(text.getAttributeValue("start"));
Time end = (text.getAttributeValue("end") == null) ? null : new Time(text.getAttributeValue("end"));
values.add(new Text(text.getAttributeValue("type"), text.getTextTrim(), start, end));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing text tag.", ex);
}
}
md.setText(values.toArray(new Text[values.size()]));
}
// thumbnails
{
List<?> thumbnails = e.getChildren("thumbnail", getNS());
ArrayList<Thumbnail> values = new ArrayList<Thumbnail>();
for (int i = 0; (thumbnails != null) && (i < thumbnails.size()); i++) {
try {
Element thumb = (Element) thumbnails.get(i);
if (thumb.getValue().startsWith("http")) {
values.add(new Thumbnail(new URI(thumb.getValue()), null, null, null));
} else {
Time t = (thumb.getAttributeValue("time") == null) ? null : new Time(thumb.getAttributeValue("time"));
Integer width = (thumb.getAttributeValue("width") == null) ? null : new Integer(thumb.getAttributeValue("width"));
Integer height = (thumb.getAttributeValue("height") == null) ? null : new Integer(thumb.getAttributeValue("height"));
values.add(new Thumbnail(new URI(thumb.getAttributeValue("url")), width, height, t));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing thumbnail tag.", ex);
}
}
md.setThumbnail(values.toArray(new Thumbnail[values.size()]));
}
// title
{
Element title = e.getChild("title", getNS());
if (title != null) {
md.setTitle(title.getText());
md.setTitleType(title.getAttributeValue("type"));
}
}
// restrictions
{
List<?> restrictions = e.getChildren("restriction", getNS());
ArrayList<Restriction> values = new ArrayList<Restriction>();
for (int i = 0; i < restrictions.size(); i++) {
Element r = (Element) restrictions.get(i);
Restriction.Type type = null;
if (r.getAttributeValue("type").equalsIgnoreCase("uri")) {
type = Restriction.Type.URI;
} else if (r.getAttributeValue("type").equalsIgnoreCase("country")) {
type = Restriction.Type.COUNTRY;
}
Restriction.Relationship relationship = null;
if (r.getAttributeValue("relationship").equalsIgnoreCase("allow")) {
relationship = Restriction.Relationship.ALLOW;
} else if (r.getAttributeValue("relationship").equalsIgnoreCase("deny")) {
relationship = Restriction.Relationship.DENY;
}
Restriction value = new Restriction(relationship, type, r.getTextTrim());
values.add(value);
}
md.setRestrictions(values.toArray(new Restriction[values.size()]));
}
// handle adult
{
Element adult = e.getChild("adult", getNS());
if ((adult != null) && (md.getRatings().length == 0)) {
Rating[] r = new Rating[1];
if (adult.getTextTrim().equals("true")) {
r[0] = new Rating("urn:simple", "adult");
} else {
r[0] = new Rating("urn:simple", "nonadult");
}
md.setRatings(r);
}
}
return md;
}
private PlayerReference parsePlayer(Element e) {
Element player = e.getChild("player", getNS());
PlayerReference p = null;
if (player != null) {
Integer width = (player.getAttributeValue("width") == null) ? null : new Integer(player.getAttributeValue("width"));
Integer height = (player.getAttributeValue("height") == null) ? null : new Integer(player.getAttributeValue("height"));
try {
p = new PlayerReference(new URI(player.getAttributeValue("url")), width, height);
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing player tag.", ex);
}
}
return p;
}
public Namespace getNS() {
return NS;
}
}
| true | true | private Metadata parseMetadata(Element e) {
Metadata md = new Metadata();
// categories
{
List<?> categories = e.getChildren("category", getNS());
ArrayList<Category> values = new ArrayList<Category>();
for (int i = 0; (categories != null) && (i < categories.size()); i++) {
try {
Element cat = (Element) categories.get(i);
values.add(new Category(cat.getAttributeValue("scheme"), cat.getAttributeValue("label"), cat.getText()));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing category tag.", ex);
}
}
md.setCategories(values.toArray(new Category[values.size()]));
}
// copyright
try {
Element copy = e.getChild("copyright", getNS());
if (copy != null) {
md.setCopyright(copy.getText());
md.setCopyrightUrl((copy.getAttributeValue("url") != null) ? new URI(copy.getAttributeValue("url")) : null);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing copyright tag.", ex);
}
// credits
{
List<?> credits = e.getChildren("credit", getNS());
ArrayList<Credit> values = new ArrayList<Credit>();
for (int i = 0; (credits != null) && (i < credits.size()); i++) {
try {
Element cred = (Element) credits.get(i);
values.add(new Credit(cred.getAttributeValue("scheme"), cred.getAttributeValue("role"), cred.getText()));
md.setCredits(values.toArray(new Credit[values.size()]));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing credit tag.", ex);
}
}
}
// description
try {
Element description = e.getChild("description", getNS());
if (description != null) {
md.setDescription(description.getText());
md.setDescriptionType(description.getAttributeValue("type"));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing description tag.", ex);
}
// hash
try {
Element hash = e.getChild("hash", getNS());
if (hash != null) {
md.setHash(new Hash(hash.getAttributeValue("algo"), hash.getText()));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing hash tag.", ex);
}
// keywords
{
Element keywords = e.getChild("keywords", getNS());
if (keywords != null) {
StringTokenizer tok = new StringTokenizer(keywords.getText(), ",");
String[] value = new String[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
value[i] = tok.nextToken().trim();
}
md.setKeywords(value);
}
}
// ratings
{
List<?> ratings = e.getChildren("rating", getNS());
ArrayList<Rating> values = new ArrayList<Rating>();
for (int i = 0; (ratings != null) && (i < ratings.size()); i++) {
try {
Element rat = (Element) ratings.get(i);
values.add(new Rating(rat.getAttributeValue("scheme"), rat.getText()));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing rating tag.", ex);
}
}
md.setRatings(values.toArray(new Rating[values.size()]));
}
// text
{
List<?> texts = e.getChildren("text", getNS());
ArrayList<Text> values = new ArrayList<Text>();
for (int i = 0; (texts != null) && (i < texts.size()); i++) {
try {
Element text = (Element) texts.get(i);
Time start = (text.getAttributeValue("start") == null) ? null : new Time(text.getAttributeValue("start"));
Time end = (text.getAttributeValue("end") == null) ? null : new Time(text.getAttributeValue("end"));
values.add(new Text(text.getAttributeValue("type"), text.getTextTrim(), start, end));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing text tag.", ex);
}
}
md.setText(values.toArray(new Text[values.size()]));
}
// thumbnails
{
List<?> thumbnails = e.getChildren("thumbnail", getNS());
ArrayList<Thumbnail> values = new ArrayList<Thumbnail>();
for (int i = 0; (thumbnails != null) && (i < thumbnails.size()); i++) {
try {
Element thumb = (Element) thumbnails.get(i);
if (thumb.getValue().startsWith("http")) {
values.add(new Thumbnail(new URI(thumb.getValue()), null, null, null));
} else {
Time t = (thumb.getAttributeValue("time") == null) ? null : new Time(thumb.getAttributeValue("time"));
Integer width = (thumb.getAttributeValue("width") == null) ? null : new Integer(thumb.getAttributeValue("width"));
Integer height = (thumb.getAttributeValue("height") == null) ? null : new Integer(thumb.getAttributeValue("height"));
values.add(new Thumbnail(new URI(thumb.getAttributeValue("url")), width, height, t));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing thumbnail tag.", ex);
}
}
md.setThumbnail(values.toArray(new Thumbnail[values.size()]));
}
// title
{
Element title = e.getChild("title", getNS());
if (title != null) {
md.setTitle(title.getText());
md.setTitleType(title.getAttributeValue("type"));
}
}
// restrictions
{
List<?> restrictions = e.getChildren("restriction", getNS());
ArrayList<Restriction> values = new ArrayList<Restriction>();
for (int i = 0; i < restrictions.size(); i++) {
Element r = (Element) restrictions.get(i);
Restriction.Type type = null;
if (r.getAttributeValue("type").equalsIgnoreCase("uri")) {
type = Restriction.Type.URI;
} else if (r.getAttributeValue("type").equalsIgnoreCase("country")) {
type = Restriction.Type.COUNTRY;
}
Restriction.Relationship relationship = null;
if (r.getAttributeValue("relationship").equalsIgnoreCase("allow")) {
relationship = Restriction.Relationship.ALLOW;
} else if (r.getAttributeValue("relationship").equalsIgnoreCase("deny")) {
relationship = Restriction.Relationship.DENY;
}
Restriction value = new Restriction(relationship, type, r.getTextTrim());
values.add(value);
}
md.setRestrictions(values.toArray(new Restriction[values.size()]));
}
// handle adult
{
Element adult = e.getChild("adult", getNS());
if ((adult != null) && (md.getRatings().length == 0)) {
Rating[] r = new Rating[1];
if (adult.getTextTrim().equals("true")) {
r[0] = new Rating("urn:simple", "adult");
} else {
r[0] = new Rating("urn:simple", "nonadult");
}
md.setRatings(r);
}
}
return md;
}
| private Metadata parseMetadata(Element e) {
Metadata md = new Metadata();
// categories
{
List<?> categories = e.getChildren("category", getNS());
ArrayList<Category> values = new ArrayList<Category>();
for (int i = 0; (categories != null) && (i < categories.size()); i++) {
try {
Element cat = (Element) categories.get(i);
values.add(new Category(cat.getAttributeValue("scheme"), cat.getAttributeValue("label"), cat.getText()));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing category tag.", ex);
}
}
md.setCategories(values.toArray(new Category[values.size()]));
}
// copyright
try {
Element copy = e.getChild("copyright", getNS());
if (copy != null) {
md.setCopyright(copy.getText());
md.setCopyrightUrl((copy.getAttributeValue("url") != null) ? new URI(copy.getAttributeValue("url")) : null);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing copyright tag.", ex);
}
// credits
{
List<?> credits = e.getChildren("credit", getNS());
ArrayList<Credit> values = new ArrayList<Credit>();
for (int i = 0; (credits != null) && (i < credits.size()); i++) {
try {
Element cred = (Element) credits.get(i);
values.add(new Credit(cred.getAttributeValue("scheme"), cred.getAttributeValue("role"), cred.getText()));
md.setCredits(values.toArray(new Credit[values.size()]));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing credit tag.", ex);
}
}
}
// description
try {
Element description = e.getChild("description", getNS());
if (description != null) {
md.setDescription(description.getText());
md.setDescriptionType(description.getAttributeValue("type"));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing description tag.", ex);
}
// hash
try {
Element hash = e.getChild("hash", getNS());
if (hash != null) {
md.setHash(new Hash(hash.getAttributeValue("algo"), hash.getText()));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing hash tag.", ex);
}
// keywords
{
Element keywords = e.getChild("keywords", getNS());
if (keywords != null) {
StringTokenizer tok = new StringTokenizer(keywords.getText(), ",");
String[] value = new String[tok.countTokens()];
for (int i = 0; tok.hasMoreTokens(); i++) {
value[i] = tok.nextToken().trim();
}
md.setKeywords(value);
}
}
// ratings
{
List<?> ratings = e.getChildren("rating", getNS());
ArrayList<Rating> values = new ArrayList<Rating>();
for (int i = 0; (ratings != null) && (i < ratings.size()); i++) {
try {
Element rat = (Element) ratings.get(i);
if (rat.getText() != null && rat.getAttributeValue("scheme") != null)
values.add(new Rating(rat.getAttributeValue("scheme"), rat.getText()));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing rating tag.", ex);
}
}
md.setRatings(values.toArray(new Rating[values.size()]));
}
// text
{
List<?> texts = e.getChildren("text", getNS());
ArrayList<Text> values = new ArrayList<Text>();
for (int i = 0; (texts != null) && (i < texts.size()); i++) {
try {
Element text = (Element) texts.get(i);
Time start = (text.getAttributeValue("start") == null) ? null : new Time(text.getAttributeValue("start"));
Time end = (text.getAttributeValue("end") == null) ? null : new Time(text.getAttributeValue("end"));
values.add(new Text(text.getAttributeValue("type"), text.getTextTrim(), start, end));
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing text tag.", ex);
}
}
md.setText(values.toArray(new Text[values.size()]));
}
// thumbnails
{
List<?> thumbnails = e.getChildren("thumbnail", getNS());
ArrayList<Thumbnail> values = new ArrayList<Thumbnail>();
for (int i = 0; (thumbnails != null) && (i < thumbnails.size()); i++) {
try {
Element thumb = (Element) thumbnails.get(i);
if (thumb.getValue().startsWith("http")) {
values.add(new Thumbnail(new URI(thumb.getValue()), null, null, null));
} else {
Time t = (thumb.getAttributeValue("time") == null) ? null : new Time(thumb.getAttributeValue("time"));
Integer width = (thumb.getAttributeValue("width") == null) ? null : new Integer(thumb.getAttributeValue("width"));
Integer height = (thumb.getAttributeValue("height") == null) ? null : new Integer(thumb.getAttributeValue("height"));
values.add(new Thumbnail(new URI(thumb.getAttributeValue("url")), width, height, t));
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Exception parsing thumbnail tag.", ex);
}
}
md.setThumbnail(values.toArray(new Thumbnail[values.size()]));
}
// title
{
Element title = e.getChild("title", getNS());
if (title != null) {
md.setTitle(title.getText());
md.setTitleType(title.getAttributeValue("type"));
}
}
// restrictions
{
List<?> restrictions = e.getChildren("restriction", getNS());
ArrayList<Restriction> values = new ArrayList<Restriction>();
for (int i = 0; i < restrictions.size(); i++) {
Element r = (Element) restrictions.get(i);
Restriction.Type type = null;
if (r.getAttributeValue("type").equalsIgnoreCase("uri")) {
type = Restriction.Type.URI;
} else if (r.getAttributeValue("type").equalsIgnoreCase("country")) {
type = Restriction.Type.COUNTRY;
}
Restriction.Relationship relationship = null;
if (r.getAttributeValue("relationship").equalsIgnoreCase("allow")) {
relationship = Restriction.Relationship.ALLOW;
} else if (r.getAttributeValue("relationship").equalsIgnoreCase("deny")) {
relationship = Restriction.Relationship.DENY;
}
Restriction value = new Restriction(relationship, type, r.getTextTrim());
values.add(value);
}
md.setRestrictions(values.toArray(new Restriction[values.size()]));
}
// handle adult
{
Element adult = e.getChild("adult", getNS());
if ((adult != null) && (md.getRatings().length == 0)) {
Rating[] r = new Rating[1];
if (adult.getTextTrim().equals("true")) {
r[0] = new Rating("urn:simple", "adult");
} else {
r[0] = new Rating("urn:simple", "nonadult");
}
md.setRatings(r);
}
}
return md;
}
|
diff --git a/editor/src/main/java/kkckkc/jsourcepad/http/HttpServerFactoryBean.java b/editor/src/main/java/kkckkc/jsourcepad/http/HttpServerFactoryBean.java
index 452d691..b36bb34 100644
--- a/editor/src/main/java/kkckkc/jsourcepad/http/HttpServerFactoryBean.java
+++ b/editor/src/main/java/kkckkc/jsourcepad/http/HttpServerFactoryBean.java
@@ -1,32 +1,32 @@
package kkckkc.jsourcepad.http;
import com.sun.net.httpserver.HttpServer;
import kkckkc.jsourcepad.util.Config;
import org.springframework.beans.factory.FactoryBean;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class HttpServerFactoryBean implements FactoryBean<HttpServer> {
@Override
public HttpServer getObject() throws Exception {
- InetSocketAddress addr = new InetSocketAddress(Config.getHttpPort());
+ InetSocketAddress addr = new InetSocketAddress("localhost", Config.getHttpPort());
HttpServer server = HttpServer.create(addr, 0);
server.setExecutor(Executors.newCachedThreadPool());
server.start();
return server;
}
@Override
public Class<?> getObjectType() {
return HttpServer.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
| true | true | public HttpServer getObject() throws Exception {
InetSocketAddress addr = new InetSocketAddress(Config.getHttpPort());
HttpServer server = HttpServer.create(addr, 0);
server.setExecutor(Executors.newCachedThreadPool());
server.start();
return server;
}
| public HttpServer getObject() throws Exception {
InetSocketAddress addr = new InetSocketAddress("localhost", Config.getHttpPort());
HttpServer server = HttpServer.create(addr, 0);
server.setExecutor(Executors.newCachedThreadPool());
server.start();
return server;
}
|
diff --git a/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/study/StudyFileUI.java b/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/study/StudyFileUI.java
index b457ad258..de3f0f69d 100644
--- a/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/study/StudyFileUI.java
+++ b/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/study/StudyFileUI.java
@@ -1,215 +1,215 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* 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
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* StudyFileUI.java
*
* Created on January 25, 2007, 2:10 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.hmdc.vdcnet.web.study;
import edu.harvard.hmdc.vdcnet.admin.UserGroup;
import edu.harvard.hmdc.vdcnet.admin.VDCUser;
import edu.harvard.hmdc.vdcnet.study.DataFileFormatType;
import edu.harvard.hmdc.vdcnet.study.StudyFile;
import edu.harvard.hmdc.vdcnet.study.StudyServiceLocal;
import edu.harvard.hmdc.vdcnet.util.FileUtil;
import edu.harvard.hmdc.vdcnet.util.StringUtil;
import edu.harvard.hmdc.vdcnet.util.WebStatisticsSupport;
import edu.harvard.hmdc.vdcnet.vdc.VDC;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Ellen Kraffmiller
*/
public class StudyFileUI implements java.io.Serializable {
/** Creates a new instance of StudyFileUI */
public StudyFileUI() {
}
public StudyFileUI(StudyFile studyFile, VDC vdc, VDCUser user, UserGroup ipUserGroup) {
this.studyFile = studyFile;
this.restrictedForUser = studyFile.isFileRestrictedForUser(user, vdc, ipUserGroup);
this.vdcId = vdc != null ? vdc.getId() : null;
}
/**
* Holds value of property studyFile.
*/
private StudyFile studyFile;
/**
* Getter for property studyFile.
* @return Value of property studyFile.
*/
public StudyFile getStudyFile() {
return this.studyFile;
}
/**
* Setter for property studyFile.
* @param studyFile New value of property studyFile.
*/
public void setStudyFile(StudyFile studyFile) {
this.studyFile = studyFile;
}
/**
* Holds value of property restrictedForUser.
*/
private boolean restrictedForUser;
/**
* Getter for property restrictedForUser.
* @return Value of property restrictedForUser.
*/
public boolean isRestrictedForUser() {
return this.restrictedForUser;
}
/**
* Setter for property restrictedForUser.
* @param restrictedForUser New value of property restrictedForUser.
*/
public void setRestrictedForUser(boolean restrictedForUser) {
this.restrictedForUser = restrictedForUser;
}
// variables used in download
private Long vdcId;
public Long getVdcId() {
return vdcId;
}
public void setVdcId(Long vdcId) {
this.vdcId = vdcId;
}
private String format;
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public boolean isImage() {
if (studyFile.getFileType() != null && studyFile.getFileType().length() >= 6 &&
studyFile.getFileType().substring(0, 6).equalsIgnoreCase("image/")) {
return true;
} else {
return false;
}
}
public String getUserFriendlyFileType() {
return FileUtil.getUserFriendlyFileType(studyFile);
}
public String fileDownload_action() {
try {
//get the xff arg used for web stats text report
WebStatisticsSupport webstatistics = new WebStatisticsSupport();
int headerValue = webstatistics.getParameterFromHeader("X-Forwarded-For");
String xff = webstatistics.getQSArgument("xff", headerValue);
String fileDownloadURL = "/dvn/FileDownload/" + "?fileId=" + this.studyFile.getId() + xff;
if (!StringUtil.isEmpty(format)) {
if (format.equals(DataFileFormatType.ORIGINAL_FILE_DATA_FILE_FORMAT)) {
fileDownloadURL += "&downloadOriginalFormat=true";
} else {
fileDownloadURL += "&format=" + this.format;
}
}
if (vdcId != null) {
fileDownloadURL += "&vdcId=" + this.vdcId;
}
FacesContext fc = javax.faces.context.FacesContext.getCurrentInstance();
HttpServletResponse response = (javax.servlet.http.HttpServletResponse) fc.getExternalContext().getResponse();
response.sendRedirect(fileDownloadURL);
fc.responseComplete();
} catch (IOException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
}
return null;
}
- public List getDataFileFormatTypes(boolean includeOriginalFile, boolean FixedFieldFile) {
+ public List getDataFileFormatTypes() {
List dataFileFormatTypes = new ArrayList();
String tabDelimitedValue = "";
// first check for fixed field
if ("text/x-fixed-field".equals(studyFile.getFileType())) {
DataFileFormatType fixedFileType = new DataFileFormatType();
fixedFileType.setName("Fixed-Field");
fixedFileType.setValue("");
dataFileFormatTypes.add(fixedFileType);
tabDelimitedValue = "D00";
}
// now add tab delimited
DataFileFormatType tabDelimitedType = new DataFileFormatType();
- tabDelimitedType.setName("Tab delimited");
+ tabDelimitedType.setName("Tab Delimited");
tabDelimitedType.setValue(tabDelimitedValue);
dataFileFormatTypes.add(tabDelimitedType);
// and original file
if ( !StringUtil.isEmpty( studyFile.getOriginalFileType() ) ) {
DataFileFormatType originalFileType = new DataFileFormatType();
originalFileType.setName("Original File");
originalFileType.setValue(DataFileFormatType.ORIGINAL_FILE_DATA_FILE_FORMAT);
dataFileFormatTypes.add(originalFileType);
}
// finally, add types from db
StudyServiceLocal studyService = null;
try {
studyService = (StudyServiceLocal) new InitialContext().lookup("java:comp/env/studyService");
} catch (Exception e) {
e.printStackTrace();
}
- dataFileFormatTypes = studyService.getDataFileFormatTypes();
+ dataFileFormatTypes.addAll(studyService.getDataFileFormatTypes());
return dataFileFormatTypes;
}
}
| false | true | public List getDataFileFormatTypes(boolean includeOriginalFile, boolean FixedFieldFile) {
List dataFileFormatTypes = new ArrayList();
String tabDelimitedValue = "";
// first check for fixed field
if ("text/x-fixed-field".equals(studyFile.getFileType())) {
DataFileFormatType fixedFileType = new DataFileFormatType();
fixedFileType.setName("Fixed-Field");
fixedFileType.setValue("");
dataFileFormatTypes.add(fixedFileType);
tabDelimitedValue = "D00";
}
// now add tab delimited
DataFileFormatType tabDelimitedType = new DataFileFormatType();
tabDelimitedType.setName("Tab delimited");
tabDelimitedType.setValue(tabDelimitedValue);
dataFileFormatTypes.add(tabDelimitedType);
// and original file
if ( !StringUtil.isEmpty( studyFile.getOriginalFileType() ) ) {
DataFileFormatType originalFileType = new DataFileFormatType();
originalFileType.setName("Original File");
originalFileType.setValue(DataFileFormatType.ORIGINAL_FILE_DATA_FILE_FORMAT);
dataFileFormatTypes.add(originalFileType);
}
// finally, add types from db
StudyServiceLocal studyService = null;
try {
studyService = (StudyServiceLocal) new InitialContext().lookup("java:comp/env/studyService");
} catch (Exception e) {
e.printStackTrace();
}
dataFileFormatTypes = studyService.getDataFileFormatTypes();
return dataFileFormatTypes;
}
| public List getDataFileFormatTypes() {
List dataFileFormatTypes = new ArrayList();
String tabDelimitedValue = "";
// first check for fixed field
if ("text/x-fixed-field".equals(studyFile.getFileType())) {
DataFileFormatType fixedFileType = new DataFileFormatType();
fixedFileType.setName("Fixed-Field");
fixedFileType.setValue("");
dataFileFormatTypes.add(fixedFileType);
tabDelimitedValue = "D00";
}
// now add tab delimited
DataFileFormatType tabDelimitedType = new DataFileFormatType();
tabDelimitedType.setName("Tab Delimited");
tabDelimitedType.setValue(tabDelimitedValue);
dataFileFormatTypes.add(tabDelimitedType);
// and original file
if ( !StringUtil.isEmpty( studyFile.getOriginalFileType() ) ) {
DataFileFormatType originalFileType = new DataFileFormatType();
originalFileType.setName("Original File");
originalFileType.setValue(DataFileFormatType.ORIGINAL_FILE_DATA_FILE_FORMAT);
dataFileFormatTypes.add(originalFileType);
}
// finally, add types from db
StudyServiceLocal studyService = null;
try {
studyService = (StudyServiceLocal) new InitialContext().lookup("java:comp/env/studyService");
} catch (Exception e) {
e.printStackTrace();
}
dataFileFormatTypes.addAll(studyService.getDataFileFormatTypes());
return dataFileFormatTypes;
}
|
diff --git a/src/com/fsck/k9/mail/filter/PeekableInputStream.java b/src/com/fsck/k9/mail/filter/PeekableInputStream.java
index a6e4868d..0175bc4d 100644
--- a/src/com/fsck/k9/mail/filter/PeekableInputStream.java
+++ b/src/com/fsck/k9/mail/filter/PeekableInputStream.java
@@ -1,65 +1,65 @@
package com.fsck.k9.mail.filter;
import java.io.IOException;
import java.io.InputStream;
/**
* A filtering InputStream that allows single byte "peeks" without consuming the byte. The
* client of this stream can call peek() to see the next available byte in the stream
* and a subsequent read will still return the peeked byte.
*/
public class PeekableInputStream extends InputStream {
private InputStream mIn;
private boolean mPeeked;
private int mPeekedByte;
public PeekableInputStream(InputStream in) {
this.mIn = in;
}
@Override
public int read() throws IOException {
if (!mPeeked) {
return mIn.read();
} else {
mPeeked = false;
return mPeekedByte;
}
}
public int peek() throws IOException {
if (!mPeeked) {
mPeekedByte = mIn.read();
mPeeked = true;
}
return mPeekedByte;
}
@Override
public int read(byte[] b, int offset, int length) throws IOException {
if (!mPeeked) {
return mIn.read(b, offset, length);
} else {
- b[0] = (byte)mPeekedByte;
+ b[offset] = (byte)mPeekedByte;
mPeeked = false;
int r = mIn.read(b, offset + 1, length - 1);
if (r == -1) {
return 1;
} else {
return r + 1;
}
}
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public String toString() {
return String.format("PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)",
mIn.toString(), mPeeked, mPeekedByte);
}
}
| true | true | public int read(byte[] b, int offset, int length) throws IOException {
if (!mPeeked) {
return mIn.read(b, offset, length);
} else {
b[0] = (byte)mPeekedByte;
mPeeked = false;
int r = mIn.read(b, offset + 1, length - 1);
if (r == -1) {
return 1;
} else {
return r + 1;
}
}
}
| public int read(byte[] b, int offset, int length) throws IOException {
if (!mPeeked) {
return mIn.read(b, offset, length);
} else {
b[offset] = (byte)mPeekedByte;
mPeeked = false;
int r = mIn.read(b, offset + 1, length - 1);
if (r == -1) {
return 1;
} else {
return r + 1;
}
}
}
|
diff --git a/src/main/java/water/ValueArray.java b/src/main/java/water/ValueArray.java
index 7b7ffa96e..ce3382760 100644
--- a/src/main/java/water/ValueArray.java
+++ b/src/main/java/water/ValueArray.java
@@ -1,433 +1,433 @@
package water;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import water.H2O.H2OCountedCompleter;
/**
* Large Arrays & Arraylets
*
* Large arrays are broken into 1Meg chunks (except the last chunk which may be
* from 1 to 2Megs). Large arrays have a metadata section in this ValueArray.
*
* @author <a href="mailto:[email protected]"></a>
* @version 1.0
*/
public class ValueArray extends Iced implements Cloneable {
public static final int LOG_CHK = 20; // Chunks are 1<<20, or 1Meg
public static final long CHUNK_SZ = 1L << LOG_CHK;
// --------------------------------------------------------
// Large datasets need metadata. :-)
//
// We describe datasets as either being "raw" ascii or unformatted binary
// data, or as being "structured binary" data - i.e., binary, floats, or
// ints. Structured data is efficient for doing math & matrix manipulation.
//
// Structured data is limited to being 2-D, a collection of rows and columns.
// The count of columns is expected to be small - from 1 to 1000. The count
// of rows is unlimited and could be more than 2^32. We expect data in
// columns to be highly compressable within a column, as data with a dynamic
// range of less than 1 byte is common (or equivalently, floating point data
// with only 2 or 3 digits of accuracy). Because data volumes matter (when
// you have billions of rows!), we want to compress the data while leaving it
// in an efficient-to-use format.
//
// The primary compression is to use 1-byte, 2-byte, or 4-byte columns, with
// an optional offset & scale factor. These are described in the meta-data.
public transient Key _key; // Main Array Key
public final Column[] _cols; // The array of column descriptors; the X dimension
public long[] _rpc; // Row# for start of each chunk
public long _numrows; // Number of rows; the Y dimension. Can be >>2^32
public final int _rowsize; // Size in bytes for an entire row
public ValueArray(Key key, long numrows, int rowsize, Column[] cols ) {
// Always some kind of rowsize. For plain unstructured data use a single
// byte column format.
assert rowsize > 0;
_numrows = numrows;
_rowsize = rowsize;
_cols = cols;
init(key);
}
// Plain unstructured data wrapper. Just a vast byte array
public ValueArray(Key key, long len ) { this(key,len,1,new Column[]{new Column(len)}); }
// Variable-sized chunks. Pass in the number of whole rows in each chunk.
public ValueArray(Key key, int[] rows, int rowsize, Column[] cols ) {
assert rowsize > 0;
_rowsize = rowsize;
_cols = cols;
_key = key;
// Roll-up summary the number rows in each chunk, to the starting row# per chunk.
_rpc = new long[rows.length+1];
long sum = 0;
for( int i=0; i<rows.length; i++ ) { // Variable-sized chunks
int r = rows[i]; // Rows in chunk# i
assert r*rowsize < (CHUNK_SZ*4); // Keep them reasonably sized please
_rpc[i] = sum; // Starting row# for chunk i
sum += r;
}
_rpc[_rpc.length-1] = _numrows = sum;
assert rpc(0) == rows[0]; // Some quicky sanity checks
assert rpc(chunks()-1) == rows[(int)(chunks()-1)];
}
public int [] getColumnIds(String [] colNames){
HashMap<String,Integer> colMap = new HashMap<String,Integer>();
for(int i = 0; i < colNames.length; ++i)colMap.put(colNames[i],i);
int [] res = new int [colNames.length];
Arrays.fill(res, -1);
Integer idx = null;
for(int i = 0; i < _cols.length; ++i)
if((idx = colMap.get(_cols[i]._name)) != null)
res[idx] = i;
return res;
}
@Override public ValueArray clone() {
try { return (ValueArray)super.clone(); }
catch( CloneNotSupportedException cne ) { throw H2O.unimpl(); }
}
// Init of transient fields from deserialization calls
@Override public final ValueArray init( Key key ) {
_key = key;
return this;
}
/** Pretty print! */
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("VA[").append(_numrows).append("][").append(_cols.length).append("]{");
sb.append("bpr=").append(_rowsize).append(", rpc=").append(_rpc).append(", ");
sb.append("chunks=").append(chunks()).append(", key=").append(_key);
sb.append("}");
return sb.toString();
}
/** An array of column names */
public final String[] colNames() {
String[] names = new String[_cols.length];
for( int i=0; i<names.length; i++ )
names[i] = _cols[i]._name;
return names;
}
/**Returns the width of a row.*/
public int rowSize() { return _rowsize; }
public long numRows() { return _numrows; }
public int numCols() { return _cols.length; }
public long length() { return _numrows*_rowsize; }
public boolean hasInvalidRows(int colnum) { return _cols[colnum]._n != _numrows; }
/** Rows in this chunk */
public int rpc(long chunknum) {
if( (long)(int)chunknum!=chunknum ) throw H2O.unimpl(); // more than 2^31 chunks?
if( _rpc != null ) return (int)(_rpc[(int)chunknum+1]-_rpc[(int)chunknum]);
int rpc = (int)(CHUNK_SZ/_rowsize);
long chunks = Math.max(1,_numrows/rpc);
assert chunknum < chunks;
if( chunknum < chunks-1 ) // Not last chunk?
return rpc; // Rows per chunk
return (int)(_numrows - (chunks-1)*rpc);
}
/** Row number at the start of this chunk */
public long startRow( long chunknum) {
if( (long)(int)chunknum!=chunknum ) throw H2O.unimpl(); // more than 2^31 chunks?
if( _rpc != null ) return _rpc[(int)chunknum];
int rpc = (int)(CHUNK_SZ/_rowsize); // Rows per chunk
return rpc*chunknum;
}
// Which row in the chunk?
public int rowInChunk( long chknum, long rownum ) {
return (int)(rownum - startRow(chknum));
}
/** Number of chunks */
public long chunks() {
if( _rpc != null ) return _rpc.length-1; // one row# per chunk
// Else uniform-size chunks
int rpc = (int)(CHUNK_SZ/_rowsize); // Rows per chunk
return Math.max(1,_numrows/rpc);
}
/** Chunk number containing a row */
private long chknum( long rownum ) {
if( _rpc == null ) {
int rpc = (int)(CHUNK_SZ/_rowsize);
return Math.min(rownum/rpc,Math.max(1,_numrows/rpc)-1);
}
int bs = Arrays.binarySearch(_rpc,rownum);
if( bs < 0 ) bs = -bs-2;
while( _rpc[bs+1]==rownum ) bs++;
return bs;
}
// internal convience class for building structured ValueArrays
static public class Column extends Iced implements Cloneable {
public String _name;
// Domain of the column - all the strings which represents the column's
// domain. The order of the strings corresponds to numbering utilized in
// dataset. Null for numeric columns.
public String[] _domain;
public double _min, _max, _mean; // Min/Max/mean/var per column; requires a 1st pass
public double _sigma; // Requires a 2nd pass
// Number of valid values; different than the rows for the entire ValueArray in some rows
// have bad data
public long _n;
public int _base; // Base
public char _scale; // Actual value is (((double)(stored_value+base))/scale); 1,10,100,1000
public char _off; // Offset within a row
public byte _size; // Size is 1,2,4 or 8 bytes, or -4,-8 for float/double data
public Column() { _min = Double.MAX_VALUE; _max = -Double.MAX_VALUE; _scale = 1; }
// Plain unstructured byte array; min/max/mean/sigma are all bogus.
// No 'NA' options, e.g. 255 is a valid datum.
public Column(long len) {
_min=0; _max=255; _mean=128; _n = len; _scale=1; _size=1;
}
public final boolean isFloat() { return _size < 0 || _scale != 1; }
public final boolean isScaled() { return _scale != 1; }
/** Compute size of numeric integer domain */
public final long numDomainSize() { return (long) ((_max - _min)+1); }
@Override public Column clone() {
try { return (Column)super.clone(); }
catch( CloneNotSupportedException cne ) { throw H2O.unimpl(); }
}
private static boolean eq(double x, double y, double precision){
return (Math.abs(x-y) < precision);
}
@Override
public boolean equals(Object other){
if(!(other instanceof Column)) return false;
Column c = (Column)other;
return
_base == c._base &&
_scale == c._scale &&
_max == c._max &&
_min == c._min &&
(eq(_mean,c._mean,1e-5) || Double.isNaN(_mean) && Double.isNaN(c._mean)) &&
(eq(_sigma,c._sigma,1e-5)|| Double.isNaN(_sigma)&& Double.isNaN(c._sigma)) &&
_n == c._n &&
_size == c._size &&
(_name == null && c._name == null || _name != null && c._name != null && _name.equals(c._name));
}
}
// Get a usable pile-o-bits
public AutoBuffer getChunk( long chknum ) { return getChunk(getChunkKey(chknum)); }
public AutoBuffer getChunk( Key key ) {
byte[] b = DKV.get(key).getBytes();
assert b.length == rpc(getChunkIndex(key))*_rowsize : "actual="+b.length+" expected="+rpc(getChunkIndex(key))*_rowsize;
return new AutoBuffer(b);
}
// Value extracted, then scaled & based - the double version. Note that this
// is not terrible efficient, and that 99% of this code I expect to be loop-
// invariant when run inside real numeric loops... but that the compiler will
// probably need help pulling out the loop invariants.
public double datad(long rownum, int colnum) {
long chknum = chknum(rownum);
return datad(getChunk(chknum),rowInChunk(chknum,rownum),colnum);
}
// This is a version where the colnum data is not yet pulled out.
public double datad(AutoBuffer ab, int row_in_chunk, int colnum) {
return datad(ab,row_in_chunk,_cols[colnum]);
}
// This is a version where all the loop-invariants are hoisted already.
public double datad(AutoBuffer ab, int row_in_chunk, Column col) {
int off = (row_in_chunk * _rowsize) + col._off;
double res=0;
switch( col._size ) {
case 1: res = ab.get1 (off); break;
case 2: res = ab.get2 (off); break;
case 4: res = ab.get4 (off); break;
case 8:return ab.get8 (off); // No scale/offset for long data
case -4:return ab.get4f(off); // No scale/offset for float data
case -8:return ab.get8d(off); // No scale/offset for double data
}
// Apply scale & base for the smaller numbers
return (res+col._base)/col._scale;
}
// Value extracted, then scaled & based - the integer version.
public long data(long rownum, int colnum) {
long chknum = chknum(rownum);
return data(getChunk(chknum),rowInChunk(chknum,rownum),colnum);
}
public long data(AutoBuffer ab, int row_in_chunk, int colnum) {
return data(ab,row_in_chunk,_cols[colnum]);
}
// This is a version where all the loop-invariants are hoisted already.
public long data(AutoBuffer ab, int row_in_chunk, Column col) {
int off = (row_in_chunk * _rowsize) + col._off;
long res=0;
switch( col._size ) {
case 1: res = ab.get1 (off); break;
case 2: res = ab.get2 (off); break;
case 4: res = ab.get4 (off); break;
case 8:return ab.get8 (off); // No scale/offset for long data
case -4:return (long)ab.get4f(off); // No scale/offset for float data
case -8:return (long)ab.get8d(off); // No scale/offset for double data
}
// Apply scale & base for the smaller numbers
assert col._scale==1;
return (res + col._base);
}
// Test if the value is valid, or was missing in the orginal dataset
public boolean isNA(long rownum, int colnum) {
long chknum = chknum(rownum);
return isNA(getChunk(chknum),rowInChunk(chknum,rownum),colnum);
}
public boolean isNA(AutoBuffer ab, int row_in_chunk, int colnum ) {
return isNA(ab,row_in_chunk,_cols[colnum]);
}
// Test if the value is valid, or was missing in the orginal dataset
// This is a version where all the loop-invariants are hoisted already.
public boolean isNA(AutoBuffer ab, int row_in_chunk, Column col ) {
int off = (row_in_chunk * _rowsize) + col._off;
switch( col._size ) {
case 1: return ab.get1(off) == 255;
case 2: return ab.get2(off) == 65535;
case 4: return ab.get4(off) == Integer.MIN_VALUE;
case 8: return ab.get8(off) == Long.MIN_VALUE;
case -4: return Float.isNaN(ab.get4f(off));
case -8: return Double.isNaN(ab.get8d(off));
}
return true;
}
// Get the proper Key for a given chunk number
public Key getChunkKey( long chknum ) {
assert 0 <= chknum && chknum < chunks() : "AIOOB "+chknum+" < "+chunks();
return getChunkKey(chknum,_key);
}
public static Key getChunkKey( long chknum, Key arrayKey ) {
byte[] buf = new AutoBuffer().put1(Key.ARRAYLET_CHUNK).put1(0)
.put8(chknum<<LOG_CHK).putA1(arrayKey._kb,arrayKey._kb.length).buf();
return Key.make(buf,(byte)arrayKey.desired());
}
// Get the root array Key from a random arraylet sub-key
public static Key getArrayKey( Key k ) { return Key.make(getArrayKeyBytes(k)); }
public static byte[] getArrayKeyBytes( Key k ) {
assert k._kb[0] == Key.ARRAYLET_CHUNK;
return Arrays.copyOfRange(k._kb,2+8,k._kb.length);
}
// Get the chunk-index from a random arraylet sub-key
public static long getChunkIndex(Key k) {
assert k._kb[0] == Key.ARRAYLET_CHUNK;
return UDP.get8(k._kb, 2) >> LOG_CHK;
}
public static long getChunkOffset(Key k) { return getChunkIndex(k)<<LOG_CHK; }
// ---
// Read a (possibly VERY large file) and put it in the K/V store and return a
// Value for it. Files larger than 2Meg are broken into arraylets of 1Meg each.
static public Key readPut(String keyname, InputStream is) throws IOException {
return readPut(Key.make(keyname), is);
}
static public Key readPut(Key k, InputStream is) throws IOException {
return readPut(k, is, null);
}
static public Key readPut(Key k, InputStream is, Job job) throws IOException {
readPut(k,is,job,new Futures()).blockForPending();
return k;
}
static private Futures readPut(Key key, InputStream is, Job job, final Futures fs) throws IOException {
UKV.remove(key);
byte[] oldbuf, buf = null;
int off = 0, sz = 0;
long szl = off;
long cidx = 0;
Futures dkv_fs = new Futures();
while( true ) {
oldbuf = buf;
buf = MemoryManager.malloc1((int)CHUNK_SZ);
off=0;
while( off<CHUNK_SZ && (sz = is.read(buf,off,(int)(CHUNK_SZ-off))) != -1 )
off+=sz;
szl += off;
if( off<CHUNK_SZ ) break;
if( job != null && job.cancelled() ) break;
final Key ckey = getChunkKey(cidx++,key);
final Value val = new Value(ckey,buf);
// Do the 'DKV.put' in a F/J task. For multi-JVM setups, this step often
// means network I/O pushing the Value to a new Node. Putting it in a
// subtask allows the I/O to overlap with the read from the InputStream.
// Especially if the InputStream is a (g)unzip, its useful to overlap the
// write with read.
H2OCountedCompleter subtask = new H2OCountedCompleter() {
@Override public void compute2() {
- DKV.put(ckey,val,fs); // The only exciting thing in this innerclass!
+ DKV.put(val._key,val,fs); // The only exciting thing in this innerclass!
tryComplete();
}
};
H2O.submitTask(subtask);
// Also add the DKV task to the blocking list (not just the TaskPutKey
// buried inside the DKV!)
dkv_fs.add(subtask);
}
assert is.read(new byte[1]) == -1 || job.cancelled();
// Block for all pending DKV puts, which will in turn add blocking requests
// to the passed-in Future list 'fs'. Also block for the last DKV to
// happen, because we're overwriting the last one with final size bits.
dkv_fs.blockForPending();
// Last chunk is short, read it; combine buffers and make the last chunk larger
if( cidx > 0 ) {
Key ckey = getChunkKey(cidx-1,key); // Get last chunk written out
assert DKV.get(ckey).memOrLoad()==oldbuf; // Maybe false-alarms under high-memory-pressure?
byte[] newbuf = Arrays.copyOf(oldbuf,(int)(off+CHUNK_SZ));
System.arraycopy(buf,0,newbuf,(int)CHUNK_SZ,off);
DKV.put(ckey,new Value(ckey,newbuf),fs); // Overwrite the old too-small Value
} else {
Key ckey = getChunkKey(cidx,key);
DKV.put(ckey,new Value(ckey,Arrays.copyOf(buf,off)),fs);
}
UKV.put(key,new ValueArray(key,szl),fs);
return fs;
}
// Wrap a InputStream over this ValueArray
public InputStream openStream() {
return new InputStream() {
private AutoBuffer _ab;
private long _chkidx;
@Override public int available() throws IOException {
if( _ab==null || _ab.remaining()==0 ) {
if( _chkidx >= chunks() ) return 0;
_ab = getChunk(_chkidx++);
}
return _ab.remaining();
}
@Override public void close() { _chkidx = chunks(); _ab = null; }
@Override public int read() throws IOException {
return available() == 0 ? -1 : _ab.get1();
}
@Override public int read(byte[] b, int off, int len) throws IOException {
return available() == 0 ? -1 : _ab.read(b,off,len);
}
};
}
}
| true | true | static private Futures readPut(Key key, InputStream is, Job job, final Futures fs) throws IOException {
UKV.remove(key);
byte[] oldbuf, buf = null;
int off = 0, sz = 0;
long szl = off;
long cidx = 0;
Futures dkv_fs = new Futures();
while( true ) {
oldbuf = buf;
buf = MemoryManager.malloc1((int)CHUNK_SZ);
off=0;
while( off<CHUNK_SZ && (sz = is.read(buf,off,(int)(CHUNK_SZ-off))) != -1 )
off+=sz;
szl += off;
if( off<CHUNK_SZ ) break;
if( job != null && job.cancelled() ) break;
final Key ckey = getChunkKey(cidx++,key);
final Value val = new Value(ckey,buf);
// Do the 'DKV.put' in a F/J task. For multi-JVM setups, this step often
// means network I/O pushing the Value to a new Node. Putting it in a
// subtask allows the I/O to overlap with the read from the InputStream.
// Especially if the InputStream is a (g)unzip, its useful to overlap the
// write with read.
H2OCountedCompleter subtask = new H2OCountedCompleter() {
@Override public void compute2() {
DKV.put(ckey,val,fs); // The only exciting thing in this innerclass!
tryComplete();
}
};
H2O.submitTask(subtask);
// Also add the DKV task to the blocking list (not just the TaskPutKey
// buried inside the DKV!)
dkv_fs.add(subtask);
}
assert is.read(new byte[1]) == -1 || job.cancelled();
// Block for all pending DKV puts, which will in turn add blocking requests
// to the passed-in Future list 'fs'. Also block for the last DKV to
// happen, because we're overwriting the last one with final size bits.
dkv_fs.blockForPending();
// Last chunk is short, read it; combine buffers and make the last chunk larger
if( cidx > 0 ) {
Key ckey = getChunkKey(cidx-1,key); // Get last chunk written out
assert DKV.get(ckey).memOrLoad()==oldbuf; // Maybe false-alarms under high-memory-pressure?
byte[] newbuf = Arrays.copyOf(oldbuf,(int)(off+CHUNK_SZ));
System.arraycopy(buf,0,newbuf,(int)CHUNK_SZ,off);
DKV.put(ckey,new Value(ckey,newbuf),fs); // Overwrite the old too-small Value
} else {
Key ckey = getChunkKey(cidx,key);
DKV.put(ckey,new Value(ckey,Arrays.copyOf(buf,off)),fs);
}
UKV.put(key,new ValueArray(key,szl),fs);
return fs;
}
| static private Futures readPut(Key key, InputStream is, Job job, final Futures fs) throws IOException {
UKV.remove(key);
byte[] oldbuf, buf = null;
int off = 0, sz = 0;
long szl = off;
long cidx = 0;
Futures dkv_fs = new Futures();
while( true ) {
oldbuf = buf;
buf = MemoryManager.malloc1((int)CHUNK_SZ);
off=0;
while( off<CHUNK_SZ && (sz = is.read(buf,off,(int)(CHUNK_SZ-off))) != -1 )
off+=sz;
szl += off;
if( off<CHUNK_SZ ) break;
if( job != null && job.cancelled() ) break;
final Key ckey = getChunkKey(cidx++,key);
final Value val = new Value(ckey,buf);
// Do the 'DKV.put' in a F/J task. For multi-JVM setups, this step often
// means network I/O pushing the Value to a new Node. Putting it in a
// subtask allows the I/O to overlap with the read from the InputStream.
// Especially if the InputStream is a (g)unzip, its useful to overlap the
// write with read.
H2OCountedCompleter subtask = new H2OCountedCompleter() {
@Override public void compute2() {
DKV.put(val._key,val,fs); // The only exciting thing in this innerclass!
tryComplete();
}
};
H2O.submitTask(subtask);
// Also add the DKV task to the blocking list (not just the TaskPutKey
// buried inside the DKV!)
dkv_fs.add(subtask);
}
assert is.read(new byte[1]) == -1 || job.cancelled();
// Block for all pending DKV puts, which will in turn add blocking requests
// to the passed-in Future list 'fs'. Also block for the last DKV to
// happen, because we're overwriting the last one with final size bits.
dkv_fs.blockForPending();
// Last chunk is short, read it; combine buffers and make the last chunk larger
if( cidx > 0 ) {
Key ckey = getChunkKey(cidx-1,key); // Get last chunk written out
assert DKV.get(ckey).memOrLoad()==oldbuf; // Maybe false-alarms under high-memory-pressure?
byte[] newbuf = Arrays.copyOf(oldbuf,(int)(off+CHUNK_SZ));
System.arraycopy(buf,0,newbuf,(int)CHUNK_SZ,off);
DKV.put(ckey,new Value(ckey,newbuf),fs); // Overwrite the old too-small Value
} else {
Key ckey = getChunkKey(cidx,key);
DKV.put(ckey,new Value(ckey,Arrays.copyOf(buf,off)),fs);
}
UKV.put(key,new ValueArray(key,szl),fs);
return fs;
}
|
diff --git a/src/main/java/edu/umd/cs/linqs/WeightLearner.java b/src/main/java/edu/umd/cs/linqs/WeightLearner.java
index b077adc..d298e96 100644
--- a/src/main/java/edu/umd/cs/linqs/WeightLearner.java
+++ b/src/main/java/edu/umd/cs/linqs/WeightLearner.java
@@ -1,67 +1,70 @@
package edu.umd.cs.linqs;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import com.google.common.collect.Iterables;
import edu.umd.cs.psl.application.learning.weight.maxlikelihood.MaxLikelihoodMPE;
import edu.umd.cs.psl.application.learning.weight.maxlikelihood.MaxPseudoLikelihood;
import edu.umd.cs.psl.application.learning.weight.maxmargin.MaxMargin;
import edu.umd.cs.psl.application.learning.weight.random.FirstOrderMetropolisRandOM;
import edu.umd.cs.psl.application.learning.weight.random.HardEMRandOM;
import edu.umd.cs.psl.config.ConfigBundle;
import edu.umd.cs.psl.database.Database;
import edu.umd.cs.psl.model.Model;
import edu.umd.cs.psl.model.kernel.CompatibilityKernel;
import edu.umd.cs.psl.model.parameters.PositiveWeight;
import edu.umd.cs.psl.model.parameters.Weight;
public class WeightLearner {
public static void learn(String method, Model m, Database db, Database labelsDB, Map<CompatibilityKernel,Weight> initWeights, ConfigBundle config, Logger log)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
/* init weights */
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(initWeights.get(k));
/* learn/set the weights */
if (method.equals("MLE")) {
MaxLikelihoodMPE mle = new MaxLikelihoodMPE(m, db, labelsDB, config);
mle.learn();
+ mle.close();
}
else if (method.equals("MPLE")) {
MaxPseudoLikelihood mple = new MaxPseudoLikelihood(m, db, labelsDB, config);
mple.learn();
+ mple.close();
}
else if (method.equals("MM")) {
MaxMargin mm = new MaxMargin(m, db, labelsDB, config);
mm.learn();
+ mm.close();
}
// else if (method.equals("HEMRandOM")) {
// HardEMRandOM hardRandOM = new HardEMRandOM(m, db, labelsDB, config);
// hardRandOM.setSlackPenalty(10000);
// hardRandOM.learn();
// }
// else if (method.equals("RandOM")) {
// FirstOrderMetropolisRandOM randOM = new FirstOrderMetropolisRandOM(m, db, labelsDB, config);
// randOM.learn();
// }
else if (method.equals("SET_TO_ONE")) {
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(new PositiveWeight(1.0));
}
else if (method.equals("RAND")) {
Random rand = new Random();
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(new PositiveWeight(rand.nextDouble()));
}
else if (method.equals("NONE"))
;
else {
log.error("Invalid method ");
throw new ClassNotFoundException("Weight learning method " + method + " not found");
}
}
}
| false | true | public static void learn(String method, Model m, Database db, Database labelsDB, Map<CompatibilityKernel,Weight> initWeights, ConfigBundle config, Logger log)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
/* init weights */
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(initWeights.get(k));
/* learn/set the weights */
if (method.equals("MLE")) {
MaxLikelihoodMPE mle = new MaxLikelihoodMPE(m, db, labelsDB, config);
mle.learn();
}
else if (method.equals("MPLE")) {
MaxPseudoLikelihood mple = new MaxPseudoLikelihood(m, db, labelsDB, config);
mple.learn();
}
else if (method.equals("MM")) {
MaxMargin mm = new MaxMargin(m, db, labelsDB, config);
mm.learn();
}
// else if (method.equals("HEMRandOM")) {
// HardEMRandOM hardRandOM = new HardEMRandOM(m, db, labelsDB, config);
// hardRandOM.setSlackPenalty(10000);
// hardRandOM.learn();
// }
// else if (method.equals("RandOM")) {
// FirstOrderMetropolisRandOM randOM = new FirstOrderMetropolisRandOM(m, db, labelsDB, config);
// randOM.learn();
// }
else if (method.equals("SET_TO_ONE")) {
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(new PositiveWeight(1.0));
}
else if (method.equals("RAND")) {
Random rand = new Random();
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(new PositiveWeight(rand.nextDouble()));
}
else if (method.equals("NONE"))
;
else {
log.error("Invalid method ");
throw new ClassNotFoundException("Weight learning method " + method + " not found");
}
}
| public static void learn(String method, Model m, Database db, Database labelsDB, Map<CompatibilityKernel,Weight> initWeights, ConfigBundle config, Logger log)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
/* init weights */
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(initWeights.get(k));
/* learn/set the weights */
if (method.equals("MLE")) {
MaxLikelihoodMPE mle = new MaxLikelihoodMPE(m, db, labelsDB, config);
mle.learn();
mle.close();
}
else if (method.equals("MPLE")) {
MaxPseudoLikelihood mple = new MaxPseudoLikelihood(m, db, labelsDB, config);
mple.learn();
mple.close();
}
else if (method.equals("MM")) {
MaxMargin mm = new MaxMargin(m, db, labelsDB, config);
mm.learn();
mm.close();
}
// else if (method.equals("HEMRandOM")) {
// HardEMRandOM hardRandOM = new HardEMRandOM(m, db, labelsDB, config);
// hardRandOM.setSlackPenalty(10000);
// hardRandOM.learn();
// }
// else if (method.equals("RandOM")) {
// FirstOrderMetropolisRandOM randOM = new FirstOrderMetropolisRandOM(m, db, labelsDB, config);
// randOM.learn();
// }
else if (method.equals("SET_TO_ONE")) {
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(new PositiveWeight(1.0));
}
else if (method.equals("RAND")) {
Random rand = new Random();
for (CompatibilityKernel k : Iterables.filter(m.getKernels(), CompatibilityKernel.class))
k.setWeight(new PositiveWeight(rand.nextDouble()));
}
else if (method.equals("NONE"))
;
else {
log.error("Invalid method ");
throw new ClassNotFoundException("Weight learning method " + method + " not found");
}
}
|
diff --git a/blojsom/src/org/ignition/blojsom/servlet/BlojsomServlet.java b/blojsom/src/org/ignition/blojsom/servlet/BlojsomServlet.java
index ba1fb278c..8623d718c 100644
--- a/blojsom/src/org/ignition/blojsom/servlet/BlojsomServlet.java
+++ b/blojsom/src/org/ignition/blojsom/servlet/BlojsomServlet.java
@@ -1,329 +1,332 @@
/**
* Copyright (c) 2003, David A. Czarnecki
* 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 "David A. Czarnecki" 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
* 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.ignition.blojsom.servlet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ignition.blojsom.blog.Blog;
import org.ignition.blojsom.blog.BlogCategory;
import org.ignition.blojsom.blog.BlogEntry;
import org.ignition.blojsom.blog.BlojsomConfigurationException;
import org.ignition.blojsom.dispatcher.GenericDispatcher;
import org.ignition.blojsom.util.BlojsomConstants;
import org.ignition.blojsom.util.BlojsomUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* BlojsomServlet
*
* @author David Czarnecki
* @author Mark Lussier
*/
public class BlojsomServlet extends HttpServlet implements BlojsomConstants {
// BlojsomServlet initialization properties from web.xml
private final static String BLOG_FLAVOR_CONFIGURATION_IP = "blog-flavor-configuration";
private final static String BLOG_DISPATCHER_MAP_CONFIGURATION_IP = "dispatcher-map-configuration";
private final static String BLOG_CONFIGURATION_IP = "blog-configuration";
private Blog _blog;
private Map _flavorToTemplateMap;
private Map _flavorToContentTypeMap;
private Map _flavors;
private Map _templateDispatchers;
private Log _logger = LogFactory.getLog(BlojsomServlet.class);
/**
* Create a new blojsom servlet instance
*/
public BlojsomServlet() {
}
/**
* Called when removing the servlet from the servlet container
*/
public void destroy() {
super.destroy();
}
/**
* Configure the blog
*
* @param servletConfig Servlet configuration information
*/
private void configureBlog(ServletConfig servletConfig) throws ServletException {
String blojsomConfiguration = servletConfig.getInitParameter(BLOG_CONFIGURATION_IP);
Properties configurationProperties = new Properties();
InputStream is = servletConfig.getServletContext().getResourceAsStream(blojsomConfiguration);
try {
configurationProperties.load(is);
_blog = new Blog(configurationProperties);
} catch (IOException e) {
_logger.error(e);
} catch (BlojsomConfigurationException e) {
_logger.error(e);
throw new ServletException(e);
}
}
/**
* Configure the flavors for the blog which map flavor values like "html" and "rss" to
* the proper template and content type
*
* @param servletConfig Servlet configuration information
*/
private void configureFlavors(ServletConfig servletConfig) {
_flavors = new HashMap();
_flavorToTemplateMap = new HashMap();
_flavorToContentTypeMap = new HashMap();
String flavorConfiguration = servletConfig.getInitParameter(BLOG_FLAVOR_CONFIGURATION_IP);
Properties flavorProperties = new Properties();
InputStream is = servletConfig.getServletContext().getResourceAsStream(flavorConfiguration);
try {
flavorProperties.load(is);
Iterator flavorIterator = flavorProperties.keySet().iterator();
while (flavorIterator.hasNext()) {
String flavor = (String) flavorIterator.next();
String[] flavorMapping = BlojsomUtils.parseCommaList(flavorProperties.getProperty(flavor));
_flavors.put(flavor, flavor);
_flavorToTemplateMap.put(flavor, flavorMapping[0]);
_flavorToContentTypeMap.put(flavor, flavorMapping[1]);
}
} catch (IOException e) {
_logger.error(e);
}
}
/**
* Configure the dispatchers that blojsom will use when passing a request/response on to a
* particular template
*
* @param servletConfig Servlet configuration information
*/
private void configureDispatchers(ServletConfig servletConfig) {
String templateConfiguration = servletConfig.getInitParameter(BLOG_DISPATCHER_MAP_CONFIGURATION_IP);
_templateDispatchers = new HashMap();
Properties templateMapProperties = new Properties();
InputStream is = servletConfig.getServletContext().getResourceAsStream(templateConfiguration);
try {
templateMapProperties.load(is);
Iterator templateIterator = templateMapProperties.keySet().iterator();
while (templateIterator.hasNext()) {
String templateExtension = (String) templateIterator.next();
String templateDispatcherClass = templateMapProperties.getProperty(templateExtension);
Class dispatcherClass = Class.forName(templateDispatcherClass);
GenericDispatcher dispatcher = (GenericDispatcher) dispatcherClass.newInstance();
dispatcher.init(servletConfig);
_templateDispatchers.put(templateExtension, dispatcher);
_logger.debug("Added template dispatcher: " + templateDispatcherClass);
}
} catch (InstantiationException e) {
_logger.error(e);
} catch (IllegalAccessException e) {
_logger.error(e);
} catch (ClassNotFoundException e) {
_logger.error(e);
} catch (IOException e) {
_logger.error(e);
}
}
/**
* Initialize blojsom: configure blog, configure flavors, configure dispatchers
*
* @param servletConfig Servlet configuration information
* @throws ServletException If there is an error initializing blojsom
*/
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
configureBlog(servletConfig);
configureFlavors(servletConfig);
configureDispatchers(servletConfig);
_logger.info("blojsom home: " + _blog.getBlogHome());
}
/**
* Service a request to blojsom
*
* @param httpServletRequest Request
* @param httpServletResponse Response
* @throws ServletException If there is an error processing the request
* @throws IOException If there is an error in IO
*/
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
String blogSiteURL = BlojsomUtils.getBlogSiteURL(httpServletRequest.getRequestURL().toString(), httpServletRequest.getServletPath());
+ if (blogSiteURL.endsWith("/")) {
+ blogSiteURL = blogSiteURL.substring(0, blogSiteURL.length()-1);
+ }
_logger.debug("blojsom servlet path: " + httpServletRequest.getServletPath());
_logger.debug("blojsom request URI: " + httpServletRequest.getRequestURI());
_logger.debug("blojsom request URL: " + httpServletRequest.getRequestURL().toString());
_logger.debug("blojsom URL: " + blogSiteURL);
// Make sure that we have a request URI ending with a / otherwise we need to
// redirect so that the browser can handle relative link generation
if (!httpServletRequest.getRequestURI().endsWith("/")) {
StringBuffer redirectURL = new StringBuffer();
redirectURL.append(httpServletRequest.getRequestURI());
redirectURL.append("/");
if (httpServletRequest.getParameterMap().size() > 0) {
redirectURL.append("?");
redirectURL.append(BlojsomUtils.convertRequestParams(httpServletRequest));
}
_logger.debug("Redirecting the user to: " + redirectURL.toString());
httpServletResponse.sendRedirect(redirectURL.toString());
return;
}
// Determine the user requested category
String requestedCategory = httpServletRequest.getPathInfo();
_logger.debug("blojsom path info: " + requestedCategory);
if (requestedCategory == null) {
requestedCategory = "/";
} else if (!requestedCategory.endsWith("/")) {
requestedCategory += "/";
}
_logger.debug("User requested category: " + requestedCategory);
BlogCategory category = new BlogCategory(requestedCategory, _blog.getBlogURL() + BlojsomUtils.removeInitialSlash(requestedCategory));
category.loadMetaData(_blog.getBlogHome(), _blog.getBlogPropertiesExtensions());
// Determine if a permalink has been requested
String permalink = httpServletRequest.getParameter(PERMALINK_PARAM);
if (permalink != null) {
_logger.debug("Permalink request for: " + permalink);
}
// Determine a calendar-based request
String year = null;
String month = null;
String day = null;
year = httpServletRequest.getParameter(YEAR_PARAM);
if (year != null) {
// Must be a 4 digit year
if (year.length() != 4) {
year = null;
} else {
month = httpServletRequest.getParameter(MONTH_PARAM);
if (month == null) {
month = "";
}
day = httpServletRequest.getParameter(DAY_PARAM);
if (day == null) {
day = "";
}
}
_logger.debug("Calendar-based request for: " + requestedCategory + year + month + day);
}
// Determine the requested flavor
String flavor = httpServletRequest.getParameter(FLAVOR_PARAM);
if (flavor == null) {
flavor = DEFAULT_FLAVOR_HTML;
} else {
if (_flavors.get(flavor) == null) {
flavor = DEFAULT_FLAVOR_HTML;
}
}
BlogEntry[] entries;
// Check for a permalink entry request
if (permalink != null) {
entries = _blog.getPermalinkEntry(category, permalink);
} else {
// Check to see if we have requested entries by calendar
if (year != null) {
entries = _blog.getEntriesForDate(category, year, month, day);
// Check for the default category
} else if (requestedCategory.equals("/")) {
entries = _blog.getEntriesAllCategories();
// Check for the requested category
} else {
entries = _blog.getEntriesForCategory(category);
}
}
String _blogdate;
// If we have entries, construct a last modified on the most recent
// Additional set the blog date
if (entries != null && entries.length > 0) {
httpServletResponse.addDateHeader(HTTP_LASTMODIFIED, entries[0].getLastModified());
_blogdate = entries[0].getISO8601Date();
} else {
_blogdate = BlojsomUtils.getRFC822Date(new Date());
}
// Setup the context for the dispatcher
HashMap context = new HashMap();
context.put(BLOJSOM_BLOG, _blog);
context.put(BLOJSOM_SITE_URL, blogSiteURL);
context.put(BLOJSOM_ENTRIES, entries);
context.put(BLOJSOM_DATE, _blogdate);
if (requestedCategory.equals("/")) {
context.put(BLOJSOM_CATEGORIES, _blog.getBlogCategories());
} else {
context.put(BLOJSOM_CATEGORIES, _blog.getBlogCategoryHierarchy(category));
}
context.put(BLOJSOM_REQUESTED_CATEGORY, category);
// Forward the request on to the template for the requested flavor
String flavorTemplate;
if (_flavorToTemplateMap.get(flavor) == null) {
flavorTemplate = (String) _flavorToTemplateMap.get(DEFAULT_FLAVOR_HTML);
} else {
flavorTemplate = (String) _flavorToTemplateMap.get(flavor);
}
// Get the content type for the requested flavor
String flavorContentType = (String) _flavorToContentTypeMap.get(flavor);
String templateExtension = BlojsomUtils.getFileExtension(flavorTemplate);
_logger.debug("Template extension: " + templateExtension);
// Retrieve the appropriate dispatcher for the template
GenericDispatcher dispatcher = (GenericDispatcher) _templateDispatchers.get(templateExtension);
dispatcher.dispatch(httpServletRequest, httpServletResponse, context, flavorTemplate, flavorContentType);
}
}
| true | true | public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
String blogSiteURL = BlojsomUtils.getBlogSiteURL(httpServletRequest.getRequestURL().toString(), httpServletRequest.getServletPath());
_logger.debug("blojsom servlet path: " + httpServletRequest.getServletPath());
_logger.debug("blojsom request URI: " + httpServletRequest.getRequestURI());
_logger.debug("blojsom request URL: " + httpServletRequest.getRequestURL().toString());
_logger.debug("blojsom URL: " + blogSiteURL);
// Make sure that we have a request URI ending with a / otherwise we need to
// redirect so that the browser can handle relative link generation
if (!httpServletRequest.getRequestURI().endsWith("/")) {
StringBuffer redirectURL = new StringBuffer();
redirectURL.append(httpServletRequest.getRequestURI());
redirectURL.append("/");
if (httpServletRequest.getParameterMap().size() > 0) {
redirectURL.append("?");
redirectURL.append(BlojsomUtils.convertRequestParams(httpServletRequest));
}
_logger.debug("Redirecting the user to: " + redirectURL.toString());
httpServletResponse.sendRedirect(redirectURL.toString());
return;
}
// Determine the user requested category
String requestedCategory = httpServletRequest.getPathInfo();
_logger.debug("blojsom path info: " + requestedCategory);
if (requestedCategory == null) {
requestedCategory = "/";
} else if (!requestedCategory.endsWith("/")) {
requestedCategory += "/";
}
_logger.debug("User requested category: " + requestedCategory);
BlogCategory category = new BlogCategory(requestedCategory, _blog.getBlogURL() + BlojsomUtils.removeInitialSlash(requestedCategory));
category.loadMetaData(_blog.getBlogHome(), _blog.getBlogPropertiesExtensions());
// Determine if a permalink has been requested
String permalink = httpServletRequest.getParameter(PERMALINK_PARAM);
if (permalink != null) {
_logger.debug("Permalink request for: " + permalink);
}
// Determine a calendar-based request
String year = null;
String month = null;
String day = null;
year = httpServletRequest.getParameter(YEAR_PARAM);
if (year != null) {
// Must be a 4 digit year
if (year.length() != 4) {
year = null;
} else {
month = httpServletRequest.getParameter(MONTH_PARAM);
if (month == null) {
month = "";
}
day = httpServletRequest.getParameter(DAY_PARAM);
if (day == null) {
day = "";
}
}
_logger.debug("Calendar-based request for: " + requestedCategory + year + month + day);
}
// Determine the requested flavor
String flavor = httpServletRequest.getParameter(FLAVOR_PARAM);
if (flavor == null) {
flavor = DEFAULT_FLAVOR_HTML;
} else {
if (_flavors.get(flavor) == null) {
flavor = DEFAULT_FLAVOR_HTML;
}
}
BlogEntry[] entries;
// Check for a permalink entry request
if (permalink != null) {
entries = _blog.getPermalinkEntry(category, permalink);
} else {
// Check to see if we have requested entries by calendar
if (year != null) {
entries = _blog.getEntriesForDate(category, year, month, day);
// Check for the default category
} else if (requestedCategory.equals("/")) {
entries = _blog.getEntriesAllCategories();
// Check for the requested category
} else {
entries = _blog.getEntriesForCategory(category);
}
}
String _blogdate;
// If we have entries, construct a last modified on the most recent
// Additional set the blog date
if (entries != null && entries.length > 0) {
httpServletResponse.addDateHeader(HTTP_LASTMODIFIED, entries[0].getLastModified());
_blogdate = entries[0].getISO8601Date();
} else {
_blogdate = BlojsomUtils.getRFC822Date(new Date());
}
// Setup the context for the dispatcher
HashMap context = new HashMap();
context.put(BLOJSOM_BLOG, _blog);
context.put(BLOJSOM_SITE_URL, blogSiteURL);
context.put(BLOJSOM_ENTRIES, entries);
context.put(BLOJSOM_DATE, _blogdate);
if (requestedCategory.equals("/")) {
context.put(BLOJSOM_CATEGORIES, _blog.getBlogCategories());
} else {
context.put(BLOJSOM_CATEGORIES, _blog.getBlogCategoryHierarchy(category));
}
context.put(BLOJSOM_REQUESTED_CATEGORY, category);
// Forward the request on to the template for the requested flavor
String flavorTemplate;
if (_flavorToTemplateMap.get(flavor) == null) {
flavorTemplate = (String) _flavorToTemplateMap.get(DEFAULT_FLAVOR_HTML);
} else {
flavorTemplate = (String) _flavorToTemplateMap.get(flavor);
}
// Get the content type for the requested flavor
String flavorContentType = (String) _flavorToContentTypeMap.get(flavor);
String templateExtension = BlojsomUtils.getFileExtension(flavorTemplate);
_logger.debug("Template extension: " + templateExtension);
// Retrieve the appropriate dispatcher for the template
GenericDispatcher dispatcher = (GenericDispatcher) _templateDispatchers.get(templateExtension);
dispatcher.dispatch(httpServletRequest, httpServletResponse, context, flavorTemplate, flavorContentType);
}
| public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
String blogSiteURL = BlojsomUtils.getBlogSiteURL(httpServletRequest.getRequestURL().toString(), httpServletRequest.getServletPath());
if (blogSiteURL.endsWith("/")) {
blogSiteURL = blogSiteURL.substring(0, blogSiteURL.length()-1);
}
_logger.debug("blojsom servlet path: " + httpServletRequest.getServletPath());
_logger.debug("blojsom request URI: " + httpServletRequest.getRequestURI());
_logger.debug("blojsom request URL: " + httpServletRequest.getRequestURL().toString());
_logger.debug("blojsom URL: " + blogSiteURL);
// Make sure that we have a request URI ending with a / otherwise we need to
// redirect so that the browser can handle relative link generation
if (!httpServletRequest.getRequestURI().endsWith("/")) {
StringBuffer redirectURL = new StringBuffer();
redirectURL.append(httpServletRequest.getRequestURI());
redirectURL.append("/");
if (httpServletRequest.getParameterMap().size() > 0) {
redirectURL.append("?");
redirectURL.append(BlojsomUtils.convertRequestParams(httpServletRequest));
}
_logger.debug("Redirecting the user to: " + redirectURL.toString());
httpServletResponse.sendRedirect(redirectURL.toString());
return;
}
// Determine the user requested category
String requestedCategory = httpServletRequest.getPathInfo();
_logger.debug("blojsom path info: " + requestedCategory);
if (requestedCategory == null) {
requestedCategory = "/";
} else if (!requestedCategory.endsWith("/")) {
requestedCategory += "/";
}
_logger.debug("User requested category: " + requestedCategory);
BlogCategory category = new BlogCategory(requestedCategory, _blog.getBlogURL() + BlojsomUtils.removeInitialSlash(requestedCategory));
category.loadMetaData(_blog.getBlogHome(), _blog.getBlogPropertiesExtensions());
// Determine if a permalink has been requested
String permalink = httpServletRequest.getParameter(PERMALINK_PARAM);
if (permalink != null) {
_logger.debug("Permalink request for: " + permalink);
}
// Determine a calendar-based request
String year = null;
String month = null;
String day = null;
year = httpServletRequest.getParameter(YEAR_PARAM);
if (year != null) {
// Must be a 4 digit year
if (year.length() != 4) {
year = null;
} else {
month = httpServletRequest.getParameter(MONTH_PARAM);
if (month == null) {
month = "";
}
day = httpServletRequest.getParameter(DAY_PARAM);
if (day == null) {
day = "";
}
}
_logger.debug("Calendar-based request for: " + requestedCategory + year + month + day);
}
// Determine the requested flavor
String flavor = httpServletRequest.getParameter(FLAVOR_PARAM);
if (flavor == null) {
flavor = DEFAULT_FLAVOR_HTML;
} else {
if (_flavors.get(flavor) == null) {
flavor = DEFAULT_FLAVOR_HTML;
}
}
BlogEntry[] entries;
// Check for a permalink entry request
if (permalink != null) {
entries = _blog.getPermalinkEntry(category, permalink);
} else {
// Check to see if we have requested entries by calendar
if (year != null) {
entries = _blog.getEntriesForDate(category, year, month, day);
// Check for the default category
} else if (requestedCategory.equals("/")) {
entries = _blog.getEntriesAllCategories();
// Check for the requested category
} else {
entries = _blog.getEntriesForCategory(category);
}
}
String _blogdate;
// If we have entries, construct a last modified on the most recent
// Additional set the blog date
if (entries != null && entries.length > 0) {
httpServletResponse.addDateHeader(HTTP_LASTMODIFIED, entries[0].getLastModified());
_blogdate = entries[0].getISO8601Date();
} else {
_blogdate = BlojsomUtils.getRFC822Date(new Date());
}
// Setup the context for the dispatcher
HashMap context = new HashMap();
context.put(BLOJSOM_BLOG, _blog);
context.put(BLOJSOM_SITE_URL, blogSiteURL);
context.put(BLOJSOM_ENTRIES, entries);
context.put(BLOJSOM_DATE, _blogdate);
if (requestedCategory.equals("/")) {
context.put(BLOJSOM_CATEGORIES, _blog.getBlogCategories());
} else {
context.put(BLOJSOM_CATEGORIES, _blog.getBlogCategoryHierarchy(category));
}
context.put(BLOJSOM_REQUESTED_CATEGORY, category);
// Forward the request on to the template for the requested flavor
String flavorTemplate;
if (_flavorToTemplateMap.get(flavor) == null) {
flavorTemplate = (String) _flavorToTemplateMap.get(DEFAULT_FLAVOR_HTML);
} else {
flavorTemplate = (String) _flavorToTemplateMap.get(flavor);
}
// Get the content type for the requested flavor
String flavorContentType = (String) _flavorToContentTypeMap.get(flavor);
String templateExtension = BlojsomUtils.getFileExtension(flavorTemplate);
_logger.debug("Template extension: " + templateExtension);
// Retrieve the appropriate dispatcher for the template
GenericDispatcher dispatcher = (GenericDispatcher) _templateDispatchers.get(templateExtension);
dispatcher.dispatch(httpServletRequest, httpServletResponse, context, flavorTemplate, flavorContentType);
}
|
diff --git a/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/LauncherApplication.java b/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/LauncherApplication.java
index aa0ebd73a..799e74c3f 100644
--- a/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/LauncherApplication.java
+++ b/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/LauncherApplication.java
@@ -1,129 +1,130 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.xd.dirt.server;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.event.SourceFilteringListener;
import org.springframework.integration.monitor.IntegrationMBeanExporter;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.xd.dirt.container.ContainerStartedEvent;
import org.springframework.xd.dirt.container.XDContainer;
import org.springframework.xd.dirt.server.options.CommandLinePropertySourceOverridingInitializer;
import org.springframework.xd.dirt.server.options.ContainerOptions;
import org.springframework.xd.dirt.server.options.XDPropertyKeys;
import org.springframework.xd.dirt.util.BannerUtils;
import org.springframework.xd.dirt.util.XdConfigLoggingInitializer;
@Configuration
@EnableAutoConfiguration
@ImportResource({
"classpath:" + XDContainer.XD_INTERNAL_CONFIG_ROOT + "launcher.xml",
"classpath:" + XDContainer.XD_INTERNAL_CONFIG_ROOT + "container.xml",
"classpath*:" + XDContainer.XD_CONFIG_ROOT + "plugins/*.xml" })
public class LauncherApplication {
public static final String NODE_PROFILE = "node";
private ConfigurableApplicationContext context;
public static void main(String[] args) {
new LauncherApplication().run(args);
}
public ConfigurableApplicationContext getContext() {
return this.context;
}
public LauncherApplication run(String... args) {
System.out.println(BannerUtils.displayBanner(getClass().getSimpleName(), null));
CommandLinePropertySourceOverridingInitializer<ContainerOptions> commandLineInitializer = new CommandLinePropertySourceOverridingInitializer<ContainerOptions>(
new ContainerOptions());
try {
this.context = new SpringApplicationBuilder(ContainerOptions.class, ParentConfiguration.class)
.profiles(NODE_PROFILE)
+ .initializers(commandLineInitializer)
.child(LauncherApplication.class)
.initializers(commandLineInitializer)
.run(args);
}
catch (Exception e) {
handleErrors(e);
}
publishContainerStarted(context);
return this;
}
private void handleErrors(Exception e) {
if (e.getCause() instanceof BindException) {
BindException be = (BindException) e.getCause();
for (FieldError error : be.getFieldErrors()) {
System.err.println(String.format("the value '%s' is not allowed for property '%s'",
error.getRejectedValue(),
error.getField()));
if (XDPropertyKeys.XD_CONTROL_TRANSPORT.equals(error.getField())) {
System.err.println(
String.format(
"If not explicitly provided, the default value of '%s' assumes the value provided for '%s'",
XDPropertyKeys.XD_CONTROL_TRANSPORT, XDPropertyKeys.XD_TRANSPORT));
}
}
}
else {
e.printStackTrace();
}
System.exit(1);
}
public static void publishContainerStarted(ConfigurableApplicationContext context) {
XDContainer container = new XDContainer();
context.setId(container.getId());
container.setContext(context);
context.publishEvent(new ContainerStartedEvent(container));
}
@Bean
public ApplicationListener<?> xdInitializer(ApplicationContext context) {
XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true);
delegate.setEnvironment(context.getEnvironment());
return new SourceFilteringListener(context, delegate);
}
@ConditionalOnExpression("${XD_JMX_ENABLED:false}")
@EnableMBeanExport(defaultDomain = "xd.container")
protected static class JmxConfiguration {
@Bean
public IntegrationMBeanExporter integrationMBeanExporter() {
IntegrationMBeanExporter exporter = new IntegrationMBeanExporter();
exporter.setDefaultDomain("xd.container");
return exporter;
}
}
}
| true | true | public LauncherApplication run(String... args) {
System.out.println(BannerUtils.displayBanner(getClass().getSimpleName(), null));
CommandLinePropertySourceOverridingInitializer<ContainerOptions> commandLineInitializer = new CommandLinePropertySourceOverridingInitializer<ContainerOptions>(
new ContainerOptions());
try {
this.context = new SpringApplicationBuilder(ContainerOptions.class, ParentConfiguration.class)
.profiles(NODE_PROFILE)
.child(LauncherApplication.class)
.initializers(commandLineInitializer)
.run(args);
}
catch (Exception e) {
handleErrors(e);
}
publishContainerStarted(context);
return this;
}
| public LauncherApplication run(String... args) {
System.out.println(BannerUtils.displayBanner(getClass().getSimpleName(), null));
CommandLinePropertySourceOverridingInitializer<ContainerOptions> commandLineInitializer = new CommandLinePropertySourceOverridingInitializer<ContainerOptions>(
new ContainerOptions());
try {
this.context = new SpringApplicationBuilder(ContainerOptions.class, ParentConfiguration.class)
.profiles(NODE_PROFILE)
.initializers(commandLineInitializer)
.child(LauncherApplication.class)
.initializers(commandLineInitializer)
.run(args);
}
catch (Exception e) {
handleErrors(e);
}
publishContainerStarted(context);
return this;
}
|
diff --git a/src/main/java/com/zaxxer/hikari/HikariPool.java b/src/main/java/com/zaxxer/hikari/HikariPool.java
index f6262323..361d4fb2 100644
--- a/src/main/java/com/zaxxer/hikari/HikariPool.java
+++ b/src/main/java/com/zaxxer/hikari/HikariPool.java
@@ -1,548 +1,554 @@
/*
* Copyright (C) 2013,2014 Brett Wooldridge
*
* 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.zaxxer.hikari;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zaxxer.hikari.proxy.IHikariConnectionProxy;
import com.zaxxer.hikari.proxy.ProxyFactory;
import com.zaxxer.hikari.util.ConcurrentBag;
import com.zaxxer.hikari.util.ConcurrentBag.IBagStateListener;
import com.zaxxer.hikari.util.PropertyBeanSetter;
/**
* This is the primary connection pool class that provides the basic
* pooling behavior for HikariCP.
*
* @author Brett Wooldridge
*/
public final class HikariPool implements HikariPoolMBean, IBagStateListener
{
private static final Logger LOGGER = LoggerFactory.getLogger(HikariPool.class);
final DataSource dataSource;
private final IConnectionCustomizer connectionCustomizer;
private final HikariConfig configuration;
private final ConcurrentBag<IHikariConnectionProxy> idleConnectionBag;
private final Timer houseKeepingTimer;
private final long leakDetectionThreshold;
private final AtomicInteger totalConnections;
private final boolean isAutoCommit;
private final boolean jdbc4ConnectionTest;
private final boolean isRegisteredMbeans;
private final String catalog;
private int transactionIsolation;
private volatile boolean shutdown;
private boolean debug;
/**
* Construct a HikariPool with the specified configuration.
*
* @param configuration a HikariConfig instance
*/
HikariPool(HikariConfig configuration)
{
configuration.validate();
this.configuration = configuration;
this.totalConnections = new AtomicInteger();
this.idleConnectionBag = new ConcurrentBag<IHikariConnectionProxy>();
this.idleConnectionBag.addBagStateListener(this);
this.jdbc4ConnectionTest = configuration.isJdbc4ConnectionTest();
this.leakDetectionThreshold = configuration.getLeakDetectionThreshold();
this.isAutoCommit = configuration.isAutoCommit();
this.isRegisteredMbeans = configuration.isRegisterMbeans();
this.transactionIsolation = configuration.getTransactionIsolation();
this.catalog = configuration.getCatalog();
this.debug = LOGGER.isDebugEnabled();
if (configuration.getDataSource() == null)
{
String dsClassName = configuration.getDataSourceClassName();
try
{
Class<?> clazz = this.getClass().getClassLoader().loadClass(dsClassName);
this.dataSource = (DataSource) clazz.newInstance();
PropertyBeanSetter.setTargetFromProperties(dataSource, configuration.getDataSourceProperties());
}
catch (Exception e)
{
throw new RuntimeException("Could not create datasource instance: " + dsClassName, e);
}
}
else
{
this.dataSource = configuration.getDataSource();
}
if (configuration.getConnectionCustomizerClassName() != null)
{
try
{
Class<?> clazz = this.getClass().getClassLoader().loadClass(configuration.getConnectionCustomizerClassName());
this.connectionCustomizer = (IConnectionCustomizer) clazz.newInstance();
}
catch (Exception e)
{
throw new RuntimeException("Could not load connection customization class", e);
}
}
else
{
this.connectionCustomizer = null;
}
if (isRegisteredMbeans)
{
HikariMBeanElf.registerMBeans(configuration, this);
}
houseKeepingTimer = new Timer("Hikari Housekeeping Timer", true);
fillPool();
long idleTimeout = configuration.getIdleTimeout();
if (idleTimeout > 0 || configuration.getMaxLifetime() > 0)
{
long delayPeriod = Long.getLong("com.zaxxer.hikari.housekeeping.period", TimeUnit.SECONDS.toMillis(30));
houseKeepingTimer.scheduleAtFixedRate(new HouseKeeper(), delayPeriod, delayPeriod);
}
}
/**
* Get a connection from the pool, or timeout trying.
*
* @return a java.sql.Connection instance
* @throws SQLException thrown if a timeout occurs trying to obtain a connection
*/
Connection getConnection() throws SQLException
{
if (shutdown)
{
throw new SQLException("Pool has been shutdown");
}
try
{
long timeout = configuration.getConnectionTimeout();
final long start = System.currentTimeMillis();
do
{
IHikariConnectionProxy connectionProxy = idleConnectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (connectionProxy == null)
{
// We timed out... break and throw exception
break;
}
connectionProxy.unclose();
if (System.currentTimeMillis() - connectionProxy.getLastAccess() > 1000 && !isConnectionAlive(connectionProxy, timeout))
{
// Throw away the dead connection, try again
closeConnection(connectionProxy);
timeout -= (System.currentTimeMillis() - start);
continue;
}
if (leakDetectionThreshold > 0)
{
connectionProxy.captureStack(leakDetectionThreshold, houseKeepingTimer);
}
return connectionProxy;
} while (timeout > 0);
logPoolState();
String msg = String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout());
LOGGER.error(msg);
logPoolState("Timeout failure ");
throw new SQLException(msg);
}
catch (InterruptedException e)
{
return null;
}
}
/**
* Release a connection back to the pool, or permanently close it if it
* is broken.
*
* @param connectionProxy the connection to release back to the pool
*/
public void releaseConnection(IHikariConnectionProxy connectionProxy)
{
if (!connectionProxy.isBrokenConnection() && !shutdown)
{
idleConnectionBag.requite(connectionProxy);
}
else
{
LOGGER.debug("Connection returned to pool is broken, or the pool is shutting down. Closing connection.");
closeConnection(connectionProxy);
}
}
@Override
public String toString()
{
return configuration.getPoolName();
}
void shutdown()
{
LOGGER.info("HikariCP pool " + configuration.getPoolName() + " is being shutdown.");
shutdown = true;
houseKeepingTimer.cancel();
closeIdleConnections();
if (isRegisteredMbeans)
{
HikariMBeanElf.unregisterMBeans(configuration, this);
}
}
// ***********************************************************************
// IBagStateListener methods
// ***********************************************************************
@Override
public void bagIsEmpty()
{
addConnections(AddConnectionStrategy.ONLY_IF_EMPTY);
}
// ***********************************************************************
// HikariPoolMBean methods
// ***********************************************************************
/** {@inheritDoc} */
public int getActiveConnections()
{
return Math.min(configuration.getMaximumPoolSize(), totalConnections.get() - getIdleConnections());
}
/** {@inheritDoc} */
public int getIdleConnections()
{
return idleConnectionBag.values(ConcurrentBag.STATE_NOT_IN_USE).size();
}
/** {@inheritDoc} */
public int getTotalConnections()
{
return totalConnections.get();
}
/** {@inheritDoc} */
public int getThreadsAwaitingConnection()
{
return idleConnectionBag.getPendingQueue();
}
/** {@inheritDoc} */
public void closeIdleConnections()
{
List<IHikariConnectionProxy> list = idleConnectionBag.values(ConcurrentBag.STATE_NOT_IN_USE);
for (IHikariConnectionProxy connectionProxy : list)
{
if (!idleConnectionBag.reserve(connectionProxy))
{
continue;
}
closeConnection(connectionProxy);
}
}
// ***********************************************************************
// Private methods
// ***********************************************************************
/**
* Fill the pool up to the minimum size.
*/
private void fillPool()
{
// maxIters avoids an infinite loop filling the pool if no connections can be acquired
int maxIters = configuration.getMinimumPoolSize() * configuration.getAcquireRetries();
while (totalConnections.get() < configuration.getMinimumPoolSize() && maxIters-- > 0)
{
int beforeCount = totalConnections.get();
addConnection();
if (configuration.isInitializationFailFast() && beforeCount == totalConnections.get())
{
throw new RuntimeException("Fail-fast during pool initialization");
}
}
logPoolState("Initial fill ");
}
/**
* Add connections to the pool, not exceeding the maximum allowed.
*/
private void addConnections(AddConnectionStrategy strategy)
{
switch (strategy)
{
case ONLY_IF_EMPTY:
{
final int max = configuration.getMaximumPoolSize();
final int increment = configuration.getAcquireIncrement();
for (int i = 0; i < increment && totalConnections.get() < max; i++)
{
addConnection();
}
}
break;
case MAINTAIN_MINIMUM:
final int min = configuration.getMinimumPoolSize();
final int max = configuration.getMaximumPoolSize();
final int increment = configuration.getAcquireIncrement();
for (int i = 0; totalConnections.get() < min && i < increment && totalConnections.get() < max; i++)
{
addConnection();
}
break;
}
}
/**
* Create and add a single connection to the pool.
*/
private void addConnection()
{
int retries = 0;
while (true)
{
try
{
Connection connection = dataSource.getConnection();
if (transactionIsolation < 0)
{
transactionIsolation = connection.getTransactionIsolation();
}
if (connectionCustomizer != null)
{
connectionCustomizer.customize(connection);
}
IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, transactionIsolation, isAutoCommit, catalog);
String initSql = configuration.getConnectionInitSql();
if (initSql != null && initSql.length() > 0)
{
connection.setAutoCommit(true);
Statement statement = connection.createStatement();
try
{
statement.execute(initSql);
}
finally
{
statement.close();
}
}
if (!shutdown)
{
- proxyConnection.resetConnectionState();
- totalConnections.incrementAndGet();
- idleConnectionBag.add(proxyConnection);
+ if (totalConnections.getAndIncrement() < configuration.getMaximumPoolSize())
+ {
+ proxyConnection.resetConnectionState();
+ idleConnectionBag.add(proxyConnection);
+ }
+ else
+ {
+ proxyConnection.realClose();
+ }
}
break;
}
catch (Exception e)
{
if (retries++ > configuration.getAcquireRetries())
{
if (debug)
{
LOGGER.error("Maximum connection creation retries exceeded: {}", e.getMessage(), e);
}
else
{
LOGGER.error("Maximum connection creation retries exceeded: {}", e.getMessage());
}
break;
}
try
{
Thread.sleep(configuration.getAcquireRetryDelay());
}
catch (InterruptedException e1)
{
break;
}
}
}
}
/**
* Check whether the connection is alive or not.
*
* @param connection the connection to test
* @param timeoutMs the timeout before we consider the test a failure
* @return true if the connection is alive, false if it is not alive or we timed out
*/
private boolean isConnectionAlive(final IHikariConnectionProxy connection, long timeoutMs)
{
try
{
try
{
if (timeoutMs < 1000)
{
timeoutMs = 1000;
}
if (jdbc4ConnectionTest)
{
return connection.isValid((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs));
}
Statement statement = connection.createStatement();
try
{
statement.setQueryTimeout((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs));
statement.executeQuery(configuration.getConnectionTestQuery());
}
finally
{
statement.close();
}
}
finally
{
if (!isAutoCommit)
{
connection.commit();
}
}
return true;
}
catch (SQLException e)
{
LOGGER.warn("Exception during keep alive check, that means the connection must be dead.", e);
return false;
}
}
/**
* Permanently close a connection.
*
* @param connectionProxy the connection to actually close
*/
private void closeConnection(IHikariConnectionProxy connectionProxy)
{
try
{
totalConnections.decrementAndGet();
connectionProxy.realClose();
}
catch (SQLException e)
{
return;
}
finally
{
idleConnectionBag.remove(connectionProxy);
}
}
private void logPoolState(String... prefix)
{
int total = totalConnections.get();
int idle = getIdleConnections();
LOGGER.debug("{}Pool stats (total={}, inUse={}, avail={}, waiting={})",
(prefix.length > 0 ? prefix[0] : ""), total, total - idle, idle, (isRegisteredMbeans ? getThreadsAwaitingConnection() : "n/a"));
}
/**
* The house keeping task to retire idle and maxAge connections.
*/
private class HouseKeeper extends TimerTask
{
public void run()
{
debug = LOGGER.isDebugEnabled();
houseKeepingTimer.purge();
logPoolState("Before pool cleanup ");
final long now = System.currentTimeMillis();
final long idleTimeout = configuration.getIdleTimeout();
final long maxLifetime = configuration.getMaxLifetime();
for (IHikariConnectionProxy connectionProxy : idleConnectionBag.values(ConcurrentBag.STATE_NOT_IN_USE))
{
if (!idleConnectionBag.reserve(connectionProxy))
{
continue;
}
if ((idleTimeout > 0 && now > connectionProxy.getLastAccess() + idleTimeout)
||
(maxLifetime > 0 && now > connectionProxy.getCreationTime() + maxLifetime))
{
closeConnection(connectionProxy);
}
else
{
idleConnectionBag.unreserve(connectionProxy);
}
}
addConnections(AddConnectionStrategy.MAINTAIN_MINIMUM);
logPoolState("After pool cleanup ");
}
}
private static enum AddConnectionStrategy
{
ONLY_IF_EMPTY,
MAINTAIN_MINIMUM
}
}
| true | true | private void addConnection()
{
int retries = 0;
while (true)
{
try
{
Connection connection = dataSource.getConnection();
if (transactionIsolation < 0)
{
transactionIsolation = connection.getTransactionIsolation();
}
if (connectionCustomizer != null)
{
connectionCustomizer.customize(connection);
}
IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, transactionIsolation, isAutoCommit, catalog);
String initSql = configuration.getConnectionInitSql();
if (initSql != null && initSql.length() > 0)
{
connection.setAutoCommit(true);
Statement statement = connection.createStatement();
try
{
statement.execute(initSql);
}
finally
{
statement.close();
}
}
if (!shutdown)
{
proxyConnection.resetConnectionState();
totalConnections.incrementAndGet();
idleConnectionBag.add(proxyConnection);
}
break;
}
catch (Exception e)
{
if (retries++ > configuration.getAcquireRetries())
{
if (debug)
{
LOGGER.error("Maximum connection creation retries exceeded: {}", e.getMessage(), e);
}
else
{
LOGGER.error("Maximum connection creation retries exceeded: {}", e.getMessage());
}
break;
}
try
{
Thread.sleep(configuration.getAcquireRetryDelay());
}
catch (InterruptedException e1)
{
break;
}
}
}
}
| private void addConnection()
{
int retries = 0;
while (true)
{
try
{
Connection connection = dataSource.getConnection();
if (transactionIsolation < 0)
{
transactionIsolation = connection.getTransactionIsolation();
}
if (connectionCustomizer != null)
{
connectionCustomizer.customize(connection);
}
IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, transactionIsolation, isAutoCommit, catalog);
String initSql = configuration.getConnectionInitSql();
if (initSql != null && initSql.length() > 0)
{
connection.setAutoCommit(true);
Statement statement = connection.createStatement();
try
{
statement.execute(initSql);
}
finally
{
statement.close();
}
}
if (!shutdown)
{
if (totalConnections.getAndIncrement() < configuration.getMaximumPoolSize())
{
proxyConnection.resetConnectionState();
idleConnectionBag.add(proxyConnection);
}
else
{
proxyConnection.realClose();
}
}
break;
}
catch (Exception e)
{
if (retries++ > configuration.getAcquireRetries())
{
if (debug)
{
LOGGER.error("Maximum connection creation retries exceeded: {}", e.getMessage(), e);
}
else
{
LOGGER.error("Maximum connection creation retries exceeded: {}", e.getMessage());
}
break;
}
try
{
Thread.sleep(configuration.getAcquireRetryDelay());
}
catch (InterruptedException e1)
{
break;
}
}
}
}
|
diff --git a/tool/src/java/org/sakaiproject/profile2/tool/components/TextareaTinyMceSettings.java b/tool/src/java/org/sakaiproject/profile2/tool/components/TextareaTinyMceSettings.java
index 9ef0a641..537fc256 100644
--- a/tool/src/java/org/sakaiproject/profile2/tool/components/TextareaTinyMceSettings.java
+++ b/tool/src/java/org/sakaiproject/profile2/tool/components/TextareaTinyMceSettings.java
@@ -1,101 +1,102 @@
/**
* Copyright (c) 2008-2012 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.profile2.tool.components;
import java.util.ArrayList;
import java.util.List;
import wicket.contrib.tinymce.settings.Button;
import wicket.contrib.tinymce.settings.TinyMCESettings;
/**
* A configuration class for the TinyMCE Wicket component, used by textareas.
* If more are required for different purposes, create a new class.
*/
public class TextareaTinyMceSettings extends TinyMCESettings {
private static final long serialVersionUID = 1L;
public TextareaTinyMceSettings(TinyMCESettings.Align toolbarAlign) {
super(TinyMCESettings.Theme.advanced);
/*
add(Button.bullist, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
add(Button.numlist, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
disableButton(Button.styleselect);
disableButton(Button.sub);
disableButton(Button.sup);
disableButton(Button.charmap);
disableButton(Button.image);
disableButton(Button.anchor);
disableButton(Button.help);
disableButton(Button.code);
disableButton(Button.link);
disableButton(Button.unlink);
disableButton(Button.formatselect);
disableButton(Button.indent);
disableButton(Button.outdent);
disableButton(Button.undo);
disableButton(Button.redo);
disableButton(Button.cleanup);
disableButton(Button.hr);
disableButton(Button.visualaid);
disableButton(Button.separator);
disableButton(Button.formatselect);
disableButton(Button.removeformat);
*/
List<Button> firstRowButtons = new ArrayList<Button>();
firstRowButtons.add(Button.bold);
firstRowButtons.add(Button.italic);
firstRowButtons.add(Button.underline);
firstRowButtons.add(Button.strikethrough);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.sub);
firstRowButtons.add(Button.sup);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.link);
firstRowButtons.add(Button.unlink);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.bullist);
firstRowButtons.add(Button.numlist);
- firstRowButtons.add(Button.separator);
- firstRowButtons.add(Button.code);
+ //PRFL-803 remove HTML button, gives an access restriction error
+ //firstRowButtons.add(Button.separator);
+ //firstRowButtons.add(Button.code);
//set first toolbar
setToolbarButtons(TinyMCESettings.Toolbar.first, firstRowButtons);
//remove the second and third toolbars
setToolbarButtons(TinyMCESettings.Toolbar.second, new ArrayList<Button>());
setToolbarButtons(TinyMCESettings.Toolbar.third, new ArrayList<Button>());
setToolbarButtons(TinyMCESettings.Toolbar.fourth, new ArrayList<Button>());
setToolbarAlign(toolbarAlign);
setToolbarLocation(TinyMCESettings.Location.top);
setStatusbarLocation(null);
setResizing(true);
setHorizontalResizing(true);
//remove leading and trailing p tags, PRFL-387
addCustomSetting("forced_root_block : false");
}
public TextareaTinyMceSettings () {
this(TinyMCESettings.Align.center);
}
}
| true | true | public TextareaTinyMceSettings(TinyMCESettings.Align toolbarAlign) {
super(TinyMCESettings.Theme.advanced);
/*
add(Button.bullist, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
add(Button.numlist, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
disableButton(Button.styleselect);
disableButton(Button.sub);
disableButton(Button.sup);
disableButton(Button.charmap);
disableButton(Button.image);
disableButton(Button.anchor);
disableButton(Button.help);
disableButton(Button.code);
disableButton(Button.link);
disableButton(Button.unlink);
disableButton(Button.formatselect);
disableButton(Button.indent);
disableButton(Button.outdent);
disableButton(Button.undo);
disableButton(Button.redo);
disableButton(Button.cleanup);
disableButton(Button.hr);
disableButton(Button.visualaid);
disableButton(Button.separator);
disableButton(Button.formatselect);
disableButton(Button.removeformat);
*/
List<Button> firstRowButtons = new ArrayList<Button>();
firstRowButtons.add(Button.bold);
firstRowButtons.add(Button.italic);
firstRowButtons.add(Button.underline);
firstRowButtons.add(Button.strikethrough);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.sub);
firstRowButtons.add(Button.sup);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.link);
firstRowButtons.add(Button.unlink);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.bullist);
firstRowButtons.add(Button.numlist);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.code);
//set first toolbar
setToolbarButtons(TinyMCESettings.Toolbar.first, firstRowButtons);
//remove the second and third toolbars
setToolbarButtons(TinyMCESettings.Toolbar.second, new ArrayList<Button>());
setToolbarButtons(TinyMCESettings.Toolbar.third, new ArrayList<Button>());
setToolbarButtons(TinyMCESettings.Toolbar.fourth, new ArrayList<Button>());
setToolbarAlign(toolbarAlign);
setToolbarLocation(TinyMCESettings.Location.top);
setStatusbarLocation(null);
setResizing(true);
setHorizontalResizing(true);
//remove leading and trailing p tags, PRFL-387
addCustomSetting("forced_root_block : false");
}
| public TextareaTinyMceSettings(TinyMCESettings.Align toolbarAlign) {
super(TinyMCESettings.Theme.advanced);
/*
add(Button.bullist, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
add(Button.numlist, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
disableButton(Button.styleselect);
disableButton(Button.sub);
disableButton(Button.sup);
disableButton(Button.charmap);
disableButton(Button.image);
disableButton(Button.anchor);
disableButton(Button.help);
disableButton(Button.code);
disableButton(Button.link);
disableButton(Button.unlink);
disableButton(Button.formatselect);
disableButton(Button.indent);
disableButton(Button.outdent);
disableButton(Button.undo);
disableButton(Button.redo);
disableButton(Button.cleanup);
disableButton(Button.hr);
disableButton(Button.visualaid);
disableButton(Button.separator);
disableButton(Button.formatselect);
disableButton(Button.removeformat);
*/
List<Button> firstRowButtons = new ArrayList<Button>();
firstRowButtons.add(Button.bold);
firstRowButtons.add(Button.italic);
firstRowButtons.add(Button.underline);
firstRowButtons.add(Button.strikethrough);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.sub);
firstRowButtons.add(Button.sup);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.link);
firstRowButtons.add(Button.unlink);
firstRowButtons.add(Button.separator);
firstRowButtons.add(Button.bullist);
firstRowButtons.add(Button.numlist);
//PRFL-803 remove HTML button, gives an access restriction error
//firstRowButtons.add(Button.separator);
//firstRowButtons.add(Button.code);
//set first toolbar
setToolbarButtons(TinyMCESettings.Toolbar.first, firstRowButtons);
//remove the second and third toolbars
setToolbarButtons(TinyMCESettings.Toolbar.second, new ArrayList<Button>());
setToolbarButtons(TinyMCESettings.Toolbar.third, new ArrayList<Button>());
setToolbarButtons(TinyMCESettings.Toolbar.fourth, new ArrayList<Button>());
setToolbarAlign(toolbarAlign);
setToolbarLocation(TinyMCESettings.Location.top);
setStatusbarLocation(null);
setResizing(true);
setHorizontalResizing(true);
//remove leading and trailing p tags, PRFL-387
addCustomSetting("forced_root_block : false");
}
|
diff --git a/src/com/detourgames/raw/LevelLoader.java b/src/com/detourgames/raw/LevelLoader.java
index e23d8b9..96690f7 100644
--- a/src/com/detourgames/raw/LevelLoader.java
+++ b/src/com/detourgames/raw/LevelLoader.java
@@ -1,151 +1,151 @@
package com.detourgames.raw;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonWriter.OutputType;
import com.badlogic.gdx.utils.OrderedMap;
public class LevelLoader {
/*
* A class for accessing level files, parsing them, loading them, and
* returning the contents of a level to the GameManager.
*
* It should only need a few methods: createLevel(levelnumber), //should
* possibly be called in the constructor getLevel(), and getLevelItem()
* (like getTiles() or getEnemies()).
*/
Level mLevel;
SpriteFactory mSpriteFactory;
SpriteSheet mSpriteSheet;
int levelWidth = 0;
int levelHeight = 0;
public LevelLoader(Level level) {
mLevel = level;
Texture texture = new Texture(Gdx.files.internal("sprite_tiles.png"));
mSpriteSheet = new SpriteSheet(texture, 3, new int[]{3,1,5}, new int[]{8,8,4,0,7,16,16,16,16}, new int[]{128,1024,64}, new int[]{128,320,64});
mLevel.setSpriteSheet(mSpriteSheet);
mSpriteFactory = new SpriteFactory(mLevel);
// if(lvln==0){
// createRandomTileMap(); TODO
// }else{
// createLevelFromFile(lvln, level);
// mSpriteFactory.createHero(2, 3);
// }
// sprites += HUD.HUD_SPRITES;
}
public void createLevelFromFile(int ln) {
FileHandle jsonId = getFileHandle(ln);
JsonReader reader=new JsonReader();
String jsonString=jsonId.readString();
Object o=reader.parse(jsonString);
CreateLevelFromJsonObject((OrderedMap<String, Object>)o);
}
private FileHandle getFileHandle(int ln) {
FileHandle levelID = null;
if (ln == 1) {
levelID = Gdx.files.internal("levels/RAWtest2.json");
}
return levelID;
}
@SuppressWarnings("unchecked")
private void CreateLevelFromJsonObject(OrderedMap<String,Object> map){
levelWidth = ((Float)map.get("width")).intValue();
levelHeight = ((Float)map.get("height")).intValue();
Array<?> tileSetO=(Array<?>)map.get("tilesets");
OrderedMap<String, ?> tileSetProperties=(OrderedMap<String, ?>)tileSetO.items[0];
OrderedMap<String, ?> tileProperties=(OrderedMap<String, ?>)tileSetProperties.get("tileproperties");
Array<?> layers = (Array<?>) map.get("layers");
OrderedMap<String, ?> foregroundLayer = null;
OrderedMap<String, ?> terrainLayer = null;
OrderedMap<String, ?> actorsObjectsLayer = null;
OrderedMap<String, ?> eventsLayer = null;
OrderedMap<String, ?> background1Layer = null;
OrderedMap<String, ?> background2Layer = null;
OrderedMap<String, ?> background3Layer = null;
Array<?> foregroundData = null;
Array<?> terrainData = null;
- Array<?> actorsObjectsObjects = null;
- Array<?> eventsData = null;
+ Array<?> actorsObjectsData = null;
+ Array<?> eventsObjects = null;
Array<?> background1Data = null;
Array<?> background2Data = null;
Array<?> background3Data = null;
OrderedMap<String, ?> tileLayer;
String name;
for(int i=0;i<layers.size;i++){
tileLayer = (OrderedMap<String, ?>)layers.items[i];
name = (String)tileLayer.get("name");
if(name.equalsIgnoreCase("Foreground")){
foregroundLayer = (OrderedMap<String, ?>)layers.items[i];
foregroundData = (Array<?>)foregroundLayer.get("data");
}else if(name.equalsIgnoreCase("Terrain")){
terrainLayer = (OrderedMap<String, ?>)layers.items[i];
terrainData = (Array<?>)terrainLayer.get("data");
}else if(name.equalsIgnoreCase("Actors and Objects")){
actorsObjectsLayer = (OrderedMap<String, ?>)layers.items[i];
- actorsObjectsObjects = (Array<?>)actorsObjectsLayer.get("objects");
+ actorsObjectsData = (Array<?>)actorsObjectsLayer.get("data");
}else if(name.equalsIgnoreCase("Events")){
eventsLayer = (OrderedMap<String, ?>)layers.items[i];
- eventsData = (Array<?>)eventsLayer.get("data");
+ eventsObjects = (Array<?>)eventsLayer.get("objects");
}else if(name.equalsIgnoreCase("Background")){
background1Layer = (OrderedMap<String, ?>)layers.items[i];
background1Data = (Array<?>)background1Layer.get("data");
}else if(name.equalsIgnoreCase("Background2")){
background2Layer = (OrderedMap<String, ?>)layers.items[i];
background2Data = (Array<?>)background2Layer.get("data");
}else if(name.equalsIgnoreCase("Background3")){
background3Layer = (OrderedMap<String, ?>)layers.items[i];
background3Data = (Array<?>)background3Layer.get("data");
}
}
int[] tiles = new int[terrainData.size];
for(int i=0;i<tiles.length;i++){
tiles[i] = ((Float)terrainData.get(i)).intValue();
}
int i = 0;
for(int y=levelHeight-1;y>-1;y--){
for(int x=0;x<levelWidth;x++){
if(tiles[i]!=0){
int tileNum = tiles[i]-1;//-1 because of apparent flaw in Tiled?
if(!tileProperties.containsKey(""+tileNum))
{
i++;
continue;
}
OrderedMap<String, ?> tileTypeOM = (OrderedMap<String, ?>)tileProperties.get(""+tileNum);
int tileType = Integer.parseInt((String)tileTypeOM.get("TileType"));
mSpriteFactory.createTile((float)x/2f, (float)y/2f, 0, tileType);
}
i++;
}
}
//TODO parse other layers
mSpriteFactory.createHero(2, 2);
}
}
| false | true | private void CreateLevelFromJsonObject(OrderedMap<String,Object> map){
levelWidth = ((Float)map.get("width")).intValue();
levelHeight = ((Float)map.get("height")).intValue();
Array<?> tileSetO=(Array<?>)map.get("tilesets");
OrderedMap<String, ?> tileSetProperties=(OrderedMap<String, ?>)tileSetO.items[0];
OrderedMap<String, ?> tileProperties=(OrderedMap<String, ?>)tileSetProperties.get("tileproperties");
Array<?> layers = (Array<?>) map.get("layers");
OrderedMap<String, ?> foregroundLayer = null;
OrderedMap<String, ?> terrainLayer = null;
OrderedMap<String, ?> actorsObjectsLayer = null;
OrderedMap<String, ?> eventsLayer = null;
OrderedMap<String, ?> background1Layer = null;
OrderedMap<String, ?> background2Layer = null;
OrderedMap<String, ?> background3Layer = null;
Array<?> foregroundData = null;
Array<?> terrainData = null;
Array<?> actorsObjectsObjects = null;
Array<?> eventsData = null;
Array<?> background1Data = null;
Array<?> background2Data = null;
Array<?> background3Data = null;
OrderedMap<String, ?> tileLayer;
String name;
for(int i=0;i<layers.size;i++){
tileLayer = (OrderedMap<String, ?>)layers.items[i];
name = (String)tileLayer.get("name");
if(name.equalsIgnoreCase("Foreground")){
foregroundLayer = (OrderedMap<String, ?>)layers.items[i];
foregroundData = (Array<?>)foregroundLayer.get("data");
}else if(name.equalsIgnoreCase("Terrain")){
terrainLayer = (OrderedMap<String, ?>)layers.items[i];
terrainData = (Array<?>)terrainLayer.get("data");
}else if(name.equalsIgnoreCase("Actors and Objects")){
actorsObjectsLayer = (OrderedMap<String, ?>)layers.items[i];
actorsObjectsObjects = (Array<?>)actorsObjectsLayer.get("objects");
}else if(name.equalsIgnoreCase("Events")){
eventsLayer = (OrderedMap<String, ?>)layers.items[i];
eventsData = (Array<?>)eventsLayer.get("data");
}else if(name.equalsIgnoreCase("Background")){
background1Layer = (OrderedMap<String, ?>)layers.items[i];
background1Data = (Array<?>)background1Layer.get("data");
}else if(name.equalsIgnoreCase("Background2")){
background2Layer = (OrderedMap<String, ?>)layers.items[i];
background2Data = (Array<?>)background2Layer.get("data");
}else if(name.equalsIgnoreCase("Background3")){
background3Layer = (OrderedMap<String, ?>)layers.items[i];
background3Data = (Array<?>)background3Layer.get("data");
}
}
int[] tiles = new int[terrainData.size];
for(int i=0;i<tiles.length;i++){
tiles[i] = ((Float)terrainData.get(i)).intValue();
}
int i = 0;
for(int y=levelHeight-1;y>-1;y--){
for(int x=0;x<levelWidth;x++){
if(tiles[i]!=0){
int tileNum = tiles[i]-1;//-1 because of apparent flaw in Tiled?
if(!tileProperties.containsKey(""+tileNum))
{
i++;
continue;
}
OrderedMap<String, ?> tileTypeOM = (OrderedMap<String, ?>)tileProperties.get(""+tileNum);
int tileType = Integer.parseInt((String)tileTypeOM.get("TileType"));
mSpriteFactory.createTile((float)x/2f, (float)y/2f, 0, tileType);
}
i++;
}
}
//TODO parse other layers
mSpriteFactory.createHero(2, 2);
}
| private void CreateLevelFromJsonObject(OrderedMap<String,Object> map){
levelWidth = ((Float)map.get("width")).intValue();
levelHeight = ((Float)map.get("height")).intValue();
Array<?> tileSetO=(Array<?>)map.get("tilesets");
OrderedMap<String, ?> tileSetProperties=(OrderedMap<String, ?>)tileSetO.items[0];
OrderedMap<String, ?> tileProperties=(OrderedMap<String, ?>)tileSetProperties.get("tileproperties");
Array<?> layers = (Array<?>) map.get("layers");
OrderedMap<String, ?> foregroundLayer = null;
OrderedMap<String, ?> terrainLayer = null;
OrderedMap<String, ?> actorsObjectsLayer = null;
OrderedMap<String, ?> eventsLayer = null;
OrderedMap<String, ?> background1Layer = null;
OrderedMap<String, ?> background2Layer = null;
OrderedMap<String, ?> background3Layer = null;
Array<?> foregroundData = null;
Array<?> terrainData = null;
Array<?> actorsObjectsData = null;
Array<?> eventsObjects = null;
Array<?> background1Data = null;
Array<?> background2Data = null;
Array<?> background3Data = null;
OrderedMap<String, ?> tileLayer;
String name;
for(int i=0;i<layers.size;i++){
tileLayer = (OrderedMap<String, ?>)layers.items[i];
name = (String)tileLayer.get("name");
if(name.equalsIgnoreCase("Foreground")){
foregroundLayer = (OrderedMap<String, ?>)layers.items[i];
foregroundData = (Array<?>)foregroundLayer.get("data");
}else if(name.equalsIgnoreCase("Terrain")){
terrainLayer = (OrderedMap<String, ?>)layers.items[i];
terrainData = (Array<?>)terrainLayer.get("data");
}else if(name.equalsIgnoreCase("Actors and Objects")){
actorsObjectsLayer = (OrderedMap<String, ?>)layers.items[i];
actorsObjectsData = (Array<?>)actorsObjectsLayer.get("data");
}else if(name.equalsIgnoreCase("Events")){
eventsLayer = (OrderedMap<String, ?>)layers.items[i];
eventsObjects = (Array<?>)eventsLayer.get("objects");
}else if(name.equalsIgnoreCase("Background")){
background1Layer = (OrderedMap<String, ?>)layers.items[i];
background1Data = (Array<?>)background1Layer.get("data");
}else if(name.equalsIgnoreCase("Background2")){
background2Layer = (OrderedMap<String, ?>)layers.items[i];
background2Data = (Array<?>)background2Layer.get("data");
}else if(name.equalsIgnoreCase("Background3")){
background3Layer = (OrderedMap<String, ?>)layers.items[i];
background3Data = (Array<?>)background3Layer.get("data");
}
}
int[] tiles = new int[terrainData.size];
for(int i=0;i<tiles.length;i++){
tiles[i] = ((Float)terrainData.get(i)).intValue();
}
int i = 0;
for(int y=levelHeight-1;y>-1;y--){
for(int x=0;x<levelWidth;x++){
if(tiles[i]!=0){
int tileNum = tiles[i]-1;//-1 because of apparent flaw in Tiled?
if(!tileProperties.containsKey(""+tileNum))
{
i++;
continue;
}
OrderedMap<String, ?> tileTypeOM = (OrderedMap<String, ?>)tileProperties.get(""+tileNum);
int tileType = Integer.parseInt((String)tileTypeOM.get("TileType"));
mSpriteFactory.createTile((float)x/2f, (float)y/2f, 0, tileType);
}
i++;
}
}
//TODO parse other layers
mSpriteFactory.createHero(2, 2);
}
|
diff --git a/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/parser/antlr/TreeTestLanguageParser.java b/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/parser/antlr/TreeTestLanguageParser.java
index 492bcefc6..2e63ac07c 100644
--- a/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/parser/antlr/TreeTestLanguageParser.java
+++ b/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/parser/antlr/TreeTestLanguageParser.java
@@ -1,54 +1,55 @@
/*
* generated by Xtext
*/
package org.eclipse.xtext.xtend.parser.antlr;
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.TokenSource;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.parser.ParseException;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import com.google.inject.Inject;
import org.eclipse.xtext.xtend.services.TreeTestLanguageGrammarAccess;
public class TreeTestLanguageParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private TreeTestLanguageGrammarAccess grammarAccess;
@Override
protected IParseResult parse(String ruleName, ANTLRInputStream in) {
TokenSource tokenSource = createLexer(in);
XtextTokenStream tokenStream = createTokenStream(tokenSource);
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
org.eclipse.xtext.xtend.parser.antlr.internal.InternalTreeTestLanguageParser parser = createParser(tokenStream);
parser.setTokenTypeMap(getTokenDefProvider().getTokenDefMap());
+ parser.setSyntaxErrorProvider(getSyntaxErrorProvider());
try {
if(ruleName != null)
return parser.parse(ruleName);
return parser.parse();
} catch (Exception re) {
throw new ParseException(re.getMessage(),re);
}
}
protected org.eclipse.xtext.xtend.parser.antlr.internal.InternalTreeTestLanguageParser createParser(XtextTokenStream stream) {
return new org.eclipse.xtext.xtend.parser.antlr.internal.InternalTreeTestLanguageParser(stream, getElementFactory(), getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "Model";
}
public TreeTestLanguageGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(TreeTestLanguageGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
| true | true | protected IParseResult parse(String ruleName, ANTLRInputStream in) {
TokenSource tokenSource = createLexer(in);
XtextTokenStream tokenStream = createTokenStream(tokenSource);
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
org.eclipse.xtext.xtend.parser.antlr.internal.InternalTreeTestLanguageParser parser = createParser(tokenStream);
parser.setTokenTypeMap(getTokenDefProvider().getTokenDefMap());
try {
if(ruleName != null)
return parser.parse(ruleName);
return parser.parse();
} catch (Exception re) {
throw new ParseException(re.getMessage(),re);
}
}
| protected IParseResult parse(String ruleName, ANTLRInputStream in) {
TokenSource tokenSource = createLexer(in);
XtextTokenStream tokenStream = createTokenStream(tokenSource);
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
org.eclipse.xtext.xtend.parser.antlr.internal.InternalTreeTestLanguageParser parser = createParser(tokenStream);
parser.setTokenTypeMap(getTokenDefProvider().getTokenDefMap());
parser.setSyntaxErrorProvider(getSyntaxErrorProvider());
try {
if(ruleName != null)
return parser.parse(ruleName);
return parser.parse();
} catch (Exception re) {
throw new ParseException(re.getMessage(),re);
}
}
|
diff --git a/AndroidAsync/src/com/koushikdutta/async/PushParser.java b/AndroidAsync/src/com/koushikdutta/async/PushParser.java
index 267081f..22a0e24 100644
--- a/AndroidAsync/src/com/koushikdutta/async/PushParser.java
+++ b/AndroidAsync/src/com/koushikdutta/async/PushParser.java
@@ -1,275 +1,277 @@
package com.koushikdutta.async;
import com.koushikdutta.async.callback.DataCallback;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
public class PushParser {
private LinkedList<Object> mWaiting = new LinkedList<Object>();
static class BufferWaiter {
int length;
}
static class StringWaiter extends BufferWaiter {
}
static class UntilWaiter {
byte value;
DataCallback callback;
}
int mNeeded = 0;
public PushParser readInt() {
mNeeded += 4;
mWaiting.add(int.class);
return this;
}
public PushParser readByte() {
mNeeded += 1;
mWaiting.add(byte.class);
return this;
}
public PushParser readShort() {
mNeeded += 2;
mWaiting.add(short.class);
return this;
}
public PushParser readLong() {
mNeeded += 8;
mWaiting.add(long.class);
return this;
}
public PushParser readBuffer(int length) {
if (length != -1)
mNeeded += length;
BufferWaiter bw = new BufferWaiter();
bw.length = length;
mWaiting.add(bw);
return this;
}
public PushParser readLenBuffer() {
readInt();
BufferWaiter bw = new BufferWaiter();
bw.length = -1;
mWaiting.add(bw);
return this;
}
public PushParser readString() {
readInt();
StringWaiter bw = new StringWaiter();
bw.length = -1;
mWaiting.add(bw);
return this;
}
public PushParser until(byte b, DataCallback callback) {
UntilWaiter waiter = new UntilWaiter();
waiter.value = b;
waiter.callback = callback;
mWaiting.add(waiter);
mNeeded++;
return this;
}
public PushParser noop() {
mWaiting.add(Object.class);
return this;
}
DataEmitterReader mReader;
DataEmitter mEmitter;
public PushParser(DataEmitter s) {
mEmitter = s;
mReader = new DataEmitterReader();
mEmitter.setDataCallback(mReader);
}
private ArrayList<Object> mArgs = new ArrayList<Object>();
private TapCallback mCallback;
Exception stack() {
try {
throw new Exception();
}
catch (Exception e) {
return e;
}
}
ByteOrder order = ByteOrder.BIG_ENDIAN;
public ByteOrder order() {
return order;
}
public PushParser order(ByteOrder order) {
this.order = order;
return this;
}
public void tap(TapCallback callback) {
assert mCallback == null;
assert mWaiting.size() > 0;
mCallback = callback;
new DataCallback() {
{
onDataAvailable(mEmitter, null);
}
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
try {
if (bb != null)
bb.order(order);
while (mWaiting.size() > 0) {
Object waiting = mWaiting.peek();
if (waiting == null)
break;
// System.out.println("Remaining: " + bb.remaining());
if (waiting == int.class) {
mArgs.add(bb.getInt());
mNeeded -= 4;
}
else if (waiting == short.class) {
mArgs.add(bb.getShort());
mNeeded -= 2;
}
else if (waiting == byte.class) {
mArgs.add(bb.get());
mNeeded -= 1;
}
else if (waiting == long.class) {
mArgs.add(bb.getLong());
mNeeded -= 8;
}
else if (waiting == Object.class) {
mArgs.add(null);
}
else if (waiting instanceof UntilWaiter) {
UntilWaiter uw = (UntilWaiter)waiting;
boolean different = true;
ByteBufferList cb = new ByteBufferList();
while (bb.size() > 0) {
ByteBuffer b = bb.remove();
b.mark();
int index = 0;
while (b.remaining() > 0 && (different = (b.get() != uw.value))) {
index++;
}
b.reset();
if (!different) {
bb.addFirst(b);
bb.get(cb, index);
+ // eat the one we're waiting on
+ bb.get();
break;
}
else {
cb.add(b);
}
}
if (uw.callback != null)
uw.callback.onDataAvailable(emitter, cb);
if (!different) {
mNeeded--;
}
else {
throw new Exception();
}
}
else if (waiting instanceof BufferWaiter || waiting instanceof StringWaiter) {
BufferWaiter bw = (BufferWaiter)waiting;
int length = bw.length;
if (length == -1) {
length = (Integer)mArgs.get(mArgs.size() - 1);
mArgs.remove(mArgs.size() - 1);
bw.length = length;
mNeeded += length;
}
if (bb.remaining() < length) {
// System.out.print("imminient feilure detected");
throw new Exception();
}
// e.printStackTrace();
// System.out.println("Buffer length: " + length);
byte[] bytes = null;
if (length > 0) {
bytes = new byte[length];
bb.get(bytes);
}
mNeeded -= length;
if (waiting instanceof StringWaiter)
mArgs.add(new String(bytes));
else
mArgs.add(bytes);
}
else {
assert false;
}
// System.out.println("Parsed: " + mArgs.get(0));
mWaiting.remove();
}
}
catch (Exception ex) {
assert mNeeded != 0;
// ex.printStackTrace();
mReader.read(mNeeded, this);
return;
}
try {
Object[] args = mArgs.toArray();
mArgs.clear();
TapCallback callback = mCallback;
mCallback = null;
Method method = getTap(callback);
method.invoke(callback, args);
}
catch (Exception ex) {
assert false;
ex.printStackTrace();
}
}
};
}
static Hashtable<Class, Method> mTable = new Hashtable<Class, Method>();
static Method getTap(TapCallback callback) {
Method found = mTable.get(callback.getClass());
if (found != null)
return found;
// try the proguard friendly route, take the first/only method
// in case "tap" has been renamed
Method[] candidates = callback.getClass().getDeclaredMethods();
if (candidates.length == 1)
return candidates[0];
for (Method method : callback.getClass().getMethods()) {
if ("tap".equals(method.getName())) {
mTable.put(callback.getClass(), method);
return method;
}
}
String fail =
"-keep class * extends com.koushikdutta.async.TapCallback {\n" +
" *;\n" +
"}\n";
//null != "AndroidAsync: tap callback could not be found. Proguard? Use this in your proguard config:\n" + fail;
assert false;
return null;
}
}
| true | true | public void tap(TapCallback callback) {
assert mCallback == null;
assert mWaiting.size() > 0;
mCallback = callback;
new DataCallback() {
{
onDataAvailable(mEmitter, null);
}
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
try {
if (bb != null)
bb.order(order);
while (mWaiting.size() > 0) {
Object waiting = mWaiting.peek();
if (waiting == null)
break;
// System.out.println("Remaining: " + bb.remaining());
if (waiting == int.class) {
mArgs.add(bb.getInt());
mNeeded -= 4;
}
else if (waiting == short.class) {
mArgs.add(bb.getShort());
mNeeded -= 2;
}
else if (waiting == byte.class) {
mArgs.add(bb.get());
mNeeded -= 1;
}
else if (waiting == long.class) {
mArgs.add(bb.getLong());
mNeeded -= 8;
}
else if (waiting == Object.class) {
mArgs.add(null);
}
else if (waiting instanceof UntilWaiter) {
UntilWaiter uw = (UntilWaiter)waiting;
boolean different = true;
ByteBufferList cb = new ByteBufferList();
while (bb.size() > 0) {
ByteBuffer b = bb.remove();
b.mark();
int index = 0;
while (b.remaining() > 0 && (different = (b.get() != uw.value))) {
index++;
}
b.reset();
if (!different) {
bb.addFirst(b);
bb.get(cb, index);
break;
}
else {
cb.add(b);
}
}
if (uw.callback != null)
uw.callback.onDataAvailable(emitter, cb);
if (!different) {
mNeeded--;
}
else {
throw new Exception();
}
}
else if (waiting instanceof BufferWaiter || waiting instanceof StringWaiter) {
BufferWaiter bw = (BufferWaiter)waiting;
int length = bw.length;
if (length == -1) {
length = (Integer)mArgs.get(mArgs.size() - 1);
mArgs.remove(mArgs.size() - 1);
bw.length = length;
mNeeded += length;
}
if (bb.remaining() < length) {
// System.out.print("imminient feilure detected");
throw new Exception();
}
// e.printStackTrace();
// System.out.println("Buffer length: " + length);
byte[] bytes = null;
if (length > 0) {
bytes = new byte[length];
bb.get(bytes);
}
mNeeded -= length;
if (waiting instanceof StringWaiter)
mArgs.add(new String(bytes));
else
mArgs.add(bytes);
}
else {
assert false;
}
// System.out.println("Parsed: " + mArgs.get(0));
mWaiting.remove();
}
}
catch (Exception ex) {
assert mNeeded != 0;
// ex.printStackTrace();
mReader.read(mNeeded, this);
return;
}
try {
Object[] args = mArgs.toArray();
mArgs.clear();
TapCallback callback = mCallback;
mCallback = null;
Method method = getTap(callback);
method.invoke(callback, args);
}
catch (Exception ex) {
assert false;
ex.printStackTrace();
}
}
};
}
| public void tap(TapCallback callback) {
assert mCallback == null;
assert mWaiting.size() > 0;
mCallback = callback;
new DataCallback() {
{
onDataAvailable(mEmitter, null);
}
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
try {
if (bb != null)
bb.order(order);
while (mWaiting.size() > 0) {
Object waiting = mWaiting.peek();
if (waiting == null)
break;
// System.out.println("Remaining: " + bb.remaining());
if (waiting == int.class) {
mArgs.add(bb.getInt());
mNeeded -= 4;
}
else if (waiting == short.class) {
mArgs.add(bb.getShort());
mNeeded -= 2;
}
else if (waiting == byte.class) {
mArgs.add(bb.get());
mNeeded -= 1;
}
else if (waiting == long.class) {
mArgs.add(bb.getLong());
mNeeded -= 8;
}
else if (waiting == Object.class) {
mArgs.add(null);
}
else if (waiting instanceof UntilWaiter) {
UntilWaiter uw = (UntilWaiter)waiting;
boolean different = true;
ByteBufferList cb = new ByteBufferList();
while (bb.size() > 0) {
ByteBuffer b = bb.remove();
b.mark();
int index = 0;
while (b.remaining() > 0 && (different = (b.get() != uw.value))) {
index++;
}
b.reset();
if (!different) {
bb.addFirst(b);
bb.get(cb, index);
// eat the one we're waiting on
bb.get();
break;
}
else {
cb.add(b);
}
}
if (uw.callback != null)
uw.callback.onDataAvailable(emitter, cb);
if (!different) {
mNeeded--;
}
else {
throw new Exception();
}
}
else if (waiting instanceof BufferWaiter || waiting instanceof StringWaiter) {
BufferWaiter bw = (BufferWaiter)waiting;
int length = bw.length;
if (length == -1) {
length = (Integer)mArgs.get(mArgs.size() - 1);
mArgs.remove(mArgs.size() - 1);
bw.length = length;
mNeeded += length;
}
if (bb.remaining() < length) {
// System.out.print("imminient feilure detected");
throw new Exception();
}
// e.printStackTrace();
// System.out.println("Buffer length: " + length);
byte[] bytes = null;
if (length > 0) {
bytes = new byte[length];
bb.get(bytes);
}
mNeeded -= length;
if (waiting instanceof StringWaiter)
mArgs.add(new String(bytes));
else
mArgs.add(bytes);
}
else {
assert false;
}
// System.out.println("Parsed: " + mArgs.get(0));
mWaiting.remove();
}
}
catch (Exception ex) {
assert mNeeded != 0;
// ex.printStackTrace();
mReader.read(mNeeded, this);
return;
}
try {
Object[] args = mArgs.toArray();
mArgs.clear();
TapCallback callback = mCallback;
mCallback = null;
Method method = getTap(callback);
method.invoke(callback, args);
}
catch (Exception ex) {
assert false;
ex.printStackTrace();
}
}
};
}
|
diff --git a/activemq-broker/src/main/java/org/apache/activemq/network/DurableConduitBridge.java b/activemq-broker/src/main/java/org/apache/activemq/network/DurableConduitBridge.java
index d2d9a79f5..621972c54 100644
--- a/activemq-broker/src/main/java/org/apache/activemq/network/DurableConduitBridge.java
+++ b/activemq-broker/src/main/java/org/apache/activemq/network/DurableConduitBridge.java
@@ -1,109 +1,110 @@
/**
* 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.network;
import java.io.IOException;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.filter.DestinationFilter;
import org.apache.activemq.transport.Transport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Consolidates subscriptions
*/
public class DurableConduitBridge extends ConduitBridge {
private static final Logger LOG = LoggerFactory.getLogger(DurableConduitBridge.class);
public String toString() {
return "DurableConduitBridge:" + configuration.getBrokerName() + "->" + getRemoteBrokerName();
}
/**
* Constructor
*
* @param configuration
*
* @param localBroker
* @param remoteBroker
*/
public DurableConduitBridge(NetworkBridgeConfiguration configuration, Transport localBroker,
Transport remoteBroker) {
super(configuration, localBroker, remoteBroker);
}
/**
* Subscriptions for these destinations are always created
*
*/
protected void setupStaticDestinations() {
super.setupStaticDestinations();
ActiveMQDestination[] dests = configuration.isDynamicOnly() ? null : durableDestinations;
if (dests != null) {
for (ActiveMQDestination dest : dests) {
if (isPermissableDestination(dest) && !doesConsumerExist(dest)) {
DemandSubscription sub = createDemandSubscription(dest);
+ sub.setStaticallyIncluded(true);
if (dest.isTopic()) {
sub.getLocalInfo().setSubscriptionName(getSubscriberName(dest));
}
try {
addSubscription(sub);
} catch (IOException e) {
LOG.error("Failed to add static destination {}", dest, e);
}
LOG.trace("Forwarding messages for durable destination: {}", dest);
}
}
}
}
protected DemandSubscription createDemandSubscription(ConsumerInfo info) throws IOException {
if (addToAlreadyInterestedConsumers(info)) {
return null; // don't want this subscription added
}
//add our original id to ourselves
info.addNetworkConsumerId(info.getConsumerId());
if (info.isDurable()) {
// set the subscriber name to something reproducible
info.setSubscriptionName(getSubscriberName(info.getDestination()));
// and override the consumerId with something unique so that it won't
// be removed if the durable subscriber (at the other end) goes away
info.setConsumerId(new ConsumerId(localSessionInfo.getSessionId(),
consumerIdGenerator.getNextSequenceId()));
}
info.setSelector(null);
return doCreateDemandSubscription(info);
}
protected String getSubscriberName(ActiveMQDestination dest) {
String subscriberName = DURABLE_SUB_PREFIX + configuration.getBrokerName() + "_" + dest.getPhysicalName();
return subscriberName;
}
protected boolean doesConsumerExist(ActiveMQDestination dest) {
DestinationFilter filter = DestinationFilter.parseFilter(dest);
for (DemandSubscription ds : subscriptionMapByLocalId.values()) {
if (filter.matches(ds.getLocalInfo().getDestination())) {
return true;
}
}
return false;
}
}
| true | true | protected void setupStaticDestinations() {
super.setupStaticDestinations();
ActiveMQDestination[] dests = configuration.isDynamicOnly() ? null : durableDestinations;
if (dests != null) {
for (ActiveMQDestination dest : dests) {
if (isPermissableDestination(dest) && !doesConsumerExist(dest)) {
DemandSubscription sub = createDemandSubscription(dest);
if (dest.isTopic()) {
sub.getLocalInfo().setSubscriptionName(getSubscriberName(dest));
}
try {
addSubscription(sub);
} catch (IOException e) {
LOG.error("Failed to add static destination {}", dest, e);
}
LOG.trace("Forwarding messages for durable destination: {}", dest);
}
}
}
}
| protected void setupStaticDestinations() {
super.setupStaticDestinations();
ActiveMQDestination[] dests = configuration.isDynamicOnly() ? null : durableDestinations;
if (dests != null) {
for (ActiveMQDestination dest : dests) {
if (isPermissableDestination(dest) && !doesConsumerExist(dest)) {
DemandSubscription sub = createDemandSubscription(dest);
sub.setStaticallyIncluded(true);
if (dest.isTopic()) {
sub.getLocalInfo().setSubscriptionName(getSubscriberName(dest));
}
try {
addSubscription(sub);
} catch (IOException e) {
LOG.error("Failed to add static destination {}", dest, e);
}
LOG.trace("Forwarding messages for durable destination: {}", dest);
}
}
}
}
|
diff --git a/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java b/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java
index 834e3518..6ad8e9f5 100644
--- a/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java
+++ b/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java
@@ -1,621 +1,622 @@
package com.pace.ext.funcs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.pace.base.PafErrSeverity;
import com.pace.base.PafException;
import com.pace.base.SortOrder;
import com.pace.base.data.EvalUtil;
import com.pace.base.data.IPafDataCache;
import com.pace.base.data.Intersection;
import com.pace.base.funcs.AbstractFunction;
import com.pace.base.mdb.PafDimMember;
import com.pace.base.mdb.PafDimTree;
import com.pace.base.state.IPafEvalState;
/**
* "Allocation" Custom Function -
*
* The calling signature of this function is '@ALLOC(msrToAllocate, [msrsToExclude*] )'.
* This function allocates the initial measure into the hierarchical children of the measure
* specified. A list of measures to be excluded can be optionally passed in.
* @version 2.8.2.0
* @author JWatkins
*
*/
public class AllocFunc extends AbstractFunction {
protected static int MEASURE_ARGS = 1; //, MAX_ARGS = 4;
protected static int REQUIRED_ARGS = 1;
protected String msrToAlloc = null;
protected List<String> targetMsrs = new ArrayList<String>(), validTargetMsrs = new ArrayList<String>();
protected Set<String> aggMsrs = new HashSet<String>();
protected List<Intersection> unlockIntersections = new ArrayList<Intersection>();
protected List<String> excludedMsrs = new ArrayList<String>();
protected Set<Intersection> userAllocFloorCells = new HashSet<Intersection>(); // Exploded measures
protected Set<Intersection> userLockFloorCells = new HashSet<Intersection>(); // Original measures
protected List<Intersection> sourceIsTargetCells = new ArrayList<Intersection>();
private static Logger logger = Logger.getLogger(AllocFunc.class);
public double calculate(Intersection sourceIs, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
// This method use allocation logic cloned from the Evaluation package. Simulating the
// "real" allocation logic, any locked target intersections will be allocated first
// from bottom to top. Lastly, the current intersection, containing the "msrToAllocate",
// is allocated.
// Convenience variables
String msrDim = dataCache.getMeasureDim();
String[] axisSortSeq = evalState.getAxisSortPriority();
HashSet<Intersection> allocIntersections = new HashSet<Intersection>();
HashSet<Intersection> allocMsrIntersections = new HashSet<Intersection>();
PafDimTree measureTree = evalState.getClientState().getUowTrees().getTree(msrDim);
List<Intersection> allocCellList = new ArrayList<Intersection>();
// Validate function parameters
validateParms(evalState);
// targets holds all intersections to allocate into.
// The lists have been processed by validateParms
// Get the list of the source intersection target intersections. (TTN-1743)
sourceIsTargetCells.clear();
sourceIsTargetCells.addAll(EvalUtil.buildFloorIntersections(sourceIs, evalState, true));
// Get the list of intersections to allocate. This would include the current
// intersection as well as any locked descendants along the measure hierarchy.
// (TTN-1743)
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
String measure = lockedCell.getCoordinate(msrDim);
if (this.aggMsrs.contains(measure)) {
if (!measure.equals(msrToAlloc)) {
allocIntersections.add(lockedCell);
} else {
allocMsrIntersections.add(lockedCell);
}
}
}
// Sort intersections in ascending order. (TTN-1743)
Intersection[] allocCells = EvalUtil.sortIntersectionsByAxis(allocIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
Intersection[] allocMsrCells = EvalUtil.sortIntersectionsByAxis(allocMsrIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
// Allocate selected intersections in for top allocation measure, followed by remaining
// measures to allocate, in ascending order along the measure hierarchy. (TTN-1743)
allocCellList.addAll(Arrays.asList(allocMsrCells));
allocCellList.addAll(Arrays.asList(allocCells));
for (Intersection allocCell : allocCellList) {
// Find the targets of the cell to allocate
Set<Intersection> allocTargets = new HashSet<Intersection>();
String allocMeasure = allocCell.getCoordinate(msrDim);
List<String> descMeasures = measureTree.getLowestMemberNames(allocMeasure);
descMeasures.retainAll(this.targetMsrs);
for (String targetMeasure : descMeasures) {
Intersection targetCell = allocCell.clone();
targetCell.setCoordinate(msrDim, targetMeasure);
allocTargets.addAll(EvalUtil.buildFloorIntersections(targetCell, evalState));
}
// gather the user lock floor intersections. These are user locks "only" and
// don't include elapsed period locks. (TTN-1743)
userAllocFloorCells.clear();
userLockFloorCells.clear();
for (Intersection origLockedCell : evalState.getOrigLockedCells()) {
String measure = origLockedCell.getCoordinate(msrDim);
if (aggMsrs.contains(measure)) {
if (!EvalUtil.isElapsedIs(origLockedCell, evalState)) {
userAllocFloorCells.addAll(EvalUtil.buildFloorIntersections(origLockedCell, evalState, true));
if (allocTargets.contains(origLockedCell)) {
userLockFloorCells.addAll(EvalUtil.buildFloorIntersections(origLockedCell, evalState));
}
}
}
}
for (Intersection origChangedCell : evalState.getOrigChangedCells()) {
String measure = origChangedCell.getCoordinate(msrDim);
if (aggMsrs.contains(measure)) {
userAllocFloorCells.addAll(EvalUtil.buildFloorIntersections(origChangedCell, evalState, true));
if (allocTargets.contains(origChangedCell)) {
userLockFloorCells.addAll(EvalUtil.buildFloorIntersections(origChangedCell, evalState));
}
}
}
// Allocate cell
allocateChange(allocCell, allocTargets, evalState, dataCache);
}
// indicate additional aggregations required by this operation
evalState.getTriggeredAggMsrs().addAll(this.targetMsrs);
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
/**
* Parse and validate function parameters
*
* @param evalState Evaluation state object
* @throws PafException
*/
protected void validateParms(IPafEvalState evalState) throws PafException {
int parmIndex = 0;
// quick check to get out if it looks like these have been validated already
// if (this.isValidated) return;
String errMsg = "Error in [" + this.getClass().getName() + "] - ";
String measureDim = evalState.getAppDef().getMdbDef().getMeasureDim();
// Check for existence of arguments
if (parms == null) {
errMsg += "[" + REQUIRED_ARGS + "] arguments are required, but none were provided.";
logger.error(errMsg);
throw new PafException(errMsg, PafErrSeverity.Error);
}
// Check for the correct number of arguments
if (parms.length < REQUIRED_ARGS) {
errMsg += "[" + REQUIRED_ARGS + "] arguments are required, but [" + parms.length + "] were provided.";
logger.error(errMsg);
throw new PafException(errMsg, PafErrSeverity.Error);
}
// Check validity of all arguments for existence in measures dimension
PafDimTree measureTree = evalState.getEvaluationTree(measureDim);
for (parmIndex = 0; parmIndex < parms.length; parmIndex++) {
String member = parms[parmIndex];
if (!measureTree.hasMember(member)){
errMsg += "[" + member + "] is not a valid member of the [" + measureDim + "] dimension.";
logger.error(errMsg);
throw new PafException(errMsg, PafErrSeverity.Error);
}
}
// Get required arguments
msrToAlloc = this.measureName;
// Check for optional parameters - if any other parameters
// then they represent children to be filtered out of the default children
int index = 1;
targetMsrs.clear();
// initialize with descendant floor measures
targetMsrs.addAll(measureTree.getLowestMemberNames(msrToAlloc));
// remove any measures specified as well as their descendants
if (parms.length > 1) {
// build excluded measures list
List<PafDimMember> desc = measureTree.getLowestMembers(parms[index]);
while (index<parms.length) {
if (desc == null || desc.size() == 0) {
excludedMsrs.add(parms[index]);
} else {
for (PafDimMember msrMbr : desc) {
excludedMsrs.add(msrMbr.getKey());
}
}
index++;
}
// now remove them from the list
// for (String excludedMsr : excludedMsrs) {
// targetMsrs.remove(excludedMsr);
// }
}
// create a set of members to aggregate after the allocation takes place. this should be the
// entire measure branch being allocated.
aggMsrs = new HashSet<String>(PafDimTree.getMemberNames(measureTree.getIDescendants(msrToAlloc)));
// create a set of members to aggregate after the allocation takes place. this should be the
// entire measure branch being allocated (TTN-1473)
validTargetMsrs.clear();
validTargetMsrs.addAll(targetMsrs);
validTargetMsrs.removeAll(excludedMsrs);
this.isValidated = true;
}
/* (non-Javadoc)
* @see com.pace.base.funcs.AbstractFunction#getTriggerIntersections(com.pace.base.state.IPafEvalState)
*/
public Set<Intersection> getTriggerIntersections(IPafEvalState evalState) throws PafException {
/*
* The trigger intersections for the @ALLOC function are:
*
* 1. Any changed intersection containing the alloc measure
*
*/
Set<Intersection> triggerIntersections = null; // = new HashSet<Intersection>(0);
Map<String, Set<Intersection>> changedCellsByMsr = evalState.getChangedCellsByMsr();
// Parse function parameters
validateParms(evalState);
// Add in alloc measure
Set<Intersection> allocIsxs = changedCellsByMsr.get(msrToAlloc);
if (allocIsxs == null) {
triggerIntersections = new HashSet<Intersection>(0);
}
else {
triggerIntersections = new HashSet<Intersection>( 2 * allocIsxs.size() );
triggerIntersections.addAll(allocIsxs);
}
return triggerIntersections;
}
/* (non-Javadoc)
* @see com.pace.base.funcs.AbstractFunction#changeTriggersFormula(com.pace.base.data.Intersection, com.pace.base.state.IPafEvalState)
*/
public boolean changeTriggersFormula(Intersection is, IPafEvalState evalState) {
/*
* A change to the allocation measure triggers this formula
*
*/
String measureDim = evalState.getAppDef().getMdbDef().getMeasureDim();
String measure = is.getCoordinate(measureDim);
if (measure.equals(msrToAlloc))
return true;
else
return false;
}
/* (non-Javadoc)
* @see com.pace.base.funcs.AbstractFunction#getMemberDependencyMap(com.pace.base.state.IPafEvalState)
*/
public Map<String, Set<String>> getMemberDependencyMap(IPafEvalState evalState) throws PafException {
Map<String, Set<String>> dependencyMap = new HashMap<String, Set<String>>();
String measureDim = evalState.getMsrDim();
// validate function parameters
validateParms(evalState);
// Add all parameters
Set<String> memberList = new HashSet<String>();
memberList.add(msrToAlloc);
memberList.addAll(targetMsrs);
dependencyMap.put(measureDim, memberList);
// Return member dependency map
return dependencyMap;
}
/**
* This takes an arbitrary intersection and allocates it across a potential pool of intersections. No restrictions are initially
* placed on the validity of this pool as it's used to do measure to measure allocations. The math however won't work if the parent
* doesn't total the children as thats assumed the base condition for allocation.
*
*
* @param intersection Intersection to allocate
* @param targetPoolIsxs Set of intersections that should total the parent intersection
* @param evalState State variable for current point in evaluation process
* @param dataCache Access to the data for updating values as a result of the allocation
* @return
* @throws PafException
*/
public IPafDataCache allocateChange(Intersection allocSrcIsx, Set<Intersection> targets, IPafEvalState evalState, IPafDataCache dataCache) throws PafException {
double allocTotal = dataCache.getCellValue(allocSrcIsx);
// if (logger.isDebugEnabled()) logger.debug("Allocating change for :" + intersection.toString() + " = " + allocTotal);
// convenience variables
// String timeDim = evalState.getAppDef().getMdbDef().getTimeDim();
// String currentYear = evalState.getAppDef().getCurrentYear();
// String yearDim = evalState.getAppDef().getMdbDef().getYearDim();
String msrDim = evalState.getAppDef().getMdbDef().getMeasureDim();
String allocMeasure = allocSrcIsx.getCoordinate(msrDim);
long stepTime = System.currentTimeMillis();
// initial check, don't allocate any intersection that is "elapsed" during forward plannable sessions
// if current plan is forward plannable, also don't allow
// allocation into any intersections containing protected time periods
if (EvalUtil.isElapsedIs(allocSrcIsx, evalState)) return dataCache;
// total locked cells under intersection
stepTime = System.currentTimeMillis();
double lockedTotal = 0;
Set<Intersection> lockedTargets = new HashSet<Intersection>(evalState.getLoadFactor());
Set<Intersection> currentLockedCells = new HashSet<Intersection>(evalState.getLoadFactor());
// Set<String> lockedTimePeriods = evalState.getClientState().getLockedPeriods();
// if (lockedTimePeriods == null) lockedTimePeriods = new HashSet<String>(0);
// add up all locked cell values, this must include floors intersections of excluded measures
// currentLockedCells.addAll(evalState.getCurrentLockedCells());
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
currentLockedCells.addAll(EvalUtil.buildFloorIntersections(lockedCell, evalState));
}
// consider protected cells as locked
// if (allocMeasure.equals(msrToAlloc)) {
// for (Intersection protectedCell : evalState.getCurrentProtectedCells()) {
// currentLockedCells.addAll(EvalUtil.buildFloorIntersections(protectedCell, evalState));
// }
// }
// currentLockedCells.addAll(evalState.getCurrentProtectedCells());
// currentLockedCells.addAll(evalState.getAllocationsByMsr(allocMeasure));
for (Intersection target : targets) {
if (currentLockedCells.contains(target) ||
// (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear)) ||
(EvalUtil.isElapsedIs(target, evalState)) || // TTN-1595
excludedMsrs.contains(target.getCoordinate(msrDim))
) {
lockedTotal += dataCache.getCellValue(target);
lockedTargets.add(target);
}
}
int alan = 2;
double allocAvailable = 0;
// normal routine, remove locked intersections from available allocation targets
if (targets.size() != lockedTargets.size() || evalState.isRoundingResourcePass() ) {
targets.removeAll(lockedTargets);
allocAvailable = allocTotal - lockedTotal;
}
else { // all targets locked so special case
// if some of the locks are original user changes
ArrayList<Intersection> userLockedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
if (allocMeasure.equals(msrToAlloc)) {
userLockedTargets.addAll(userLockFloorCells);
} else {
userLockedTargets.addAll(userAllocFloorCells);
}
userLockedTargets.retainAll(targets);
ArrayList<Intersection> elapsedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
- double userLockedTotal = 0;
double elapsedTotal = 0;
for (Intersection target : targets) {
// total elapsed period locks and add them to a specific collection
// if (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear) ) {
if (EvalUtil.isElapsedIs(target, evalState)) { // TTN-1595
elapsedTotal += dataCache.getCellValue(target);
elapsedTargets.add(target);
}
// total user lock floor intersections that intersect with allocation
// targets and don't include elapsed period locks. (TTN-1743)
// if (
// (evalState.getOrigLockedCells().contains(target) || evalState.getOrigChangedCells().contains(target)) // user change true
// &&
// (!elapsedTargets.contains(target)) // not already counted as an elapsed period
// ) {
// userLockedTotal += dataCache.getCellValue(target);
// userLockedTargets.add(target);
// }
}
// always remove elapsed periods from the allocation
targets.removeAll(elapsedTargets);
allocAvailable = allocTotal - elapsedTotal;
+ userLockedTargets.removeAll(elapsedTargets);
// ensure that potential targets of the top allocation measure are preserved (TTN-1743)
+ Set<Intersection> msrToAllocTargets = null;
+ double msrToAllocTargetTotal = 0;
if (!allocMeasure.equals(msrToAlloc)) {
- Set<Intersection> msrToAllocTargets = new HashSet<Intersection>(evalState.getLoadFactor());
- double msrToAllocTargetTotal = 0;
+ msrToAllocTargets = new HashSet<Intersection>(evalState.getLoadFactor());
for (Intersection target : targets) {
if (sourceIsTargetCells.contains(target)) {
msrToAllocTargets.add(target);
msrToAllocTargetTotal += dataCache.getCellValue(target);
}
}
targets.removeAll(msrToAllocTargets);
allocAvailable -= msrToAllocTargetTotal;
userLockedTargets.removeAll(msrToAllocTargets);
}
if (targets.size() != userLockedTargets.size()) {
// some targets are user locks so remove them and allocate into rest
for (Intersection userLockedTarget : userLockedTargets) {
if (targets.contains(userLockedTarget)) {
targets.remove(userLockedTarget);
allocAvailable -= dataCache.getCellValue(userLockedTarget);
}
}
}
// else { // all potential targets are user locks, so allocate evenly into them
// allocAvailable = allocAvailable;
// }
}
// if no quantity to allocate, dump out.
// if (allocAvailable == 0) return dataCache;
double origTargetSum = 0;
for (Intersection target : targets ) {
origTargetSum += dataCache.getCellValue(target);
}
// begin timing allocation step
stepTime = System.currentTimeMillis();
// logger.info("Allocating intersection: " + intersection);
// logger.info("Allocating into " + targets.size() + " targets" );
if (origTargetSum == 0 &&
evalState.getRule().getBaseAllocateMeasure() != null
&& !evalState.getRule().getBaseAllocateMeasure().equals("")) {
// in this case, perform the exact same logic as the normal allocation step, however, use the "shape"
// from base measure to determine the allocation percentages.
allocateToTargets(targets, evalState.getRule().getBaseAllocateMeasure(), allocAvailable, dataCache, evalState);
} else {
// normal allocation to open targets
allocateToTargets(targets, allocAvailable, origTargetSum, dataCache, evalState);
}
// logger.info(LogUtil.timedStep("Allocation completed ", stepTime));
// evalState.addAllAllocations(targets);
return dataCache;
}
protected void allocateToTargets(Set<Intersection> targets, double allocAvailable, double origTargetSum, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
double origValue = 0;
double allocValue = 0;
int places = 0;
long stepTime = System.currentTimeMillis();
for (Intersection target : targets ) {
origValue = dataCache.getCellValue(target);
if (origTargetSum == 0) {
allocValue = allocAvailable / targets.size();
}
else {
allocValue = ((origValue / origTargetSum) * (allocAvailable));
}
if (evalState.getAppDef().getAppSettings() != null && evalState.getAppDef().getAppSettings().isEnableRounding())
{
String currentMeasure = target.getCoordinate(evalState.getAppDef().getMdbDef().getMeasureDim());
if (evalState.getRoundingRules().containsKey(currentMeasure)){
places = evalState.getRoundingRules().get(currentMeasure).getDigits();
allocValue = EvalUtil.Round(allocValue, places);
evalState.getAllocatedLockedCells().add(target);
}
}
dataCache.setCellValue(target, allocValue);
// if (logger.isDebugEnabled()) logger.debug("Allocating " + target.toString() + " new value: " + allocValue);
// add cells to locks
evalState.getCurrentLockedCells().add(target);
// add to changed cell list
evalState.addChangedCell(target);
}
// // default is to lock the results of allocation, but can be overriden,
// // however unlocking can only occur at the end of the overall allocation pass
// if (!evalState.getRule().isLockAllocation())
// unlockIntersections.addAll(targets);
}
protected void allocateToTargets(Set<Intersection> targets, String baseMeasure, double allocAvailable, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
double baseValue = 0;
double allocValue = 0;
double baseTargetSum = 0;
int places = 0;
String msrDim = evalState.getAppDef().getMdbDef().getMeasureDim();
// find index of measure dimension in axis
int msrIndex = dataCache.getAxisIndex(msrDim);
String[] baseCoords;
String targetMsr;
// save off original measure from 1st target
if (targets.size() > 0)
targetMsr = targets.iterator().next().getCoordinate(msrDim);
else //just return if no targets, no work to do
return;
// recalculate origTargetSum over base measure intersections
for (Intersection target : targets ) {
baseCoords = target.getCoordinates();
baseCoords[msrIndex] = baseMeasure;
baseTargetSum += dataCache.getCellValue(target);
}
// if (logger.isDebugEnabled()) logger.debug("Original total of unlocked base measure targets: " + baseTargetSum);
// allocate into each target intersection, using the shape of the
for (Intersection target : targets ) {
// target coordinates have already been shifted by the
// addition operation above.
baseValue = dataCache.getCellValue(target);
if (baseTargetSum == 0) {
allocValue = allocAvailable / targets.size();
}
else {
allocValue = ((baseValue / baseTargetSum) * (allocAvailable));
}
if (evalState.getAppDef().getAppSettings() != null && evalState.getAppDef().getAppSettings().isEnableRounding())
{
if (evalState.getRoundingRules().containsKey(targetMsr)){
places = evalState.getRoundingRules().get(targetMsr).getDigits();
allocValue = EvalUtil.Round(allocValue, places);
evalState.getAllocatedLockedCells().add(target);
}
}
// put target msr coordinate back to original measure for assignment
target.setCoordinate(msrDim, targetMsr);
dataCache.setCellValue(target, allocValue);
// if (logger.isDebugEnabled()) logger.debug("Allocating " + target.toString() + " new value: " + allocValue);
// add cells to locks
evalState.getCurrentLockedCells().add(target);
// add to changed cell list
evalState.addChangedCell(target);
}
// // default is to lock the results of allocation, but can be overriden,
// // however unlocking can only occur at the end of the overall allocation pass
// if (!evalState.getRule().isLockAllocation())
// unlockIntersections.addAll(targets);
}
}
| false | true | public IPafDataCache allocateChange(Intersection allocSrcIsx, Set<Intersection> targets, IPafEvalState evalState, IPafDataCache dataCache) throws PafException {
double allocTotal = dataCache.getCellValue(allocSrcIsx);
// if (logger.isDebugEnabled()) logger.debug("Allocating change for :" + intersection.toString() + " = " + allocTotal);
// convenience variables
// String timeDim = evalState.getAppDef().getMdbDef().getTimeDim();
// String currentYear = evalState.getAppDef().getCurrentYear();
// String yearDim = evalState.getAppDef().getMdbDef().getYearDim();
String msrDim = evalState.getAppDef().getMdbDef().getMeasureDim();
String allocMeasure = allocSrcIsx.getCoordinate(msrDim);
long stepTime = System.currentTimeMillis();
// initial check, don't allocate any intersection that is "elapsed" during forward plannable sessions
// if current plan is forward plannable, also don't allow
// allocation into any intersections containing protected time periods
if (EvalUtil.isElapsedIs(allocSrcIsx, evalState)) return dataCache;
// total locked cells under intersection
stepTime = System.currentTimeMillis();
double lockedTotal = 0;
Set<Intersection> lockedTargets = new HashSet<Intersection>(evalState.getLoadFactor());
Set<Intersection> currentLockedCells = new HashSet<Intersection>(evalState.getLoadFactor());
// Set<String> lockedTimePeriods = evalState.getClientState().getLockedPeriods();
// if (lockedTimePeriods == null) lockedTimePeriods = new HashSet<String>(0);
// add up all locked cell values, this must include floors intersections of excluded measures
// currentLockedCells.addAll(evalState.getCurrentLockedCells());
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
currentLockedCells.addAll(EvalUtil.buildFloorIntersections(lockedCell, evalState));
}
// consider protected cells as locked
// if (allocMeasure.equals(msrToAlloc)) {
// for (Intersection protectedCell : evalState.getCurrentProtectedCells()) {
// currentLockedCells.addAll(EvalUtil.buildFloorIntersections(protectedCell, evalState));
// }
// }
// currentLockedCells.addAll(evalState.getCurrentProtectedCells());
// currentLockedCells.addAll(evalState.getAllocationsByMsr(allocMeasure));
for (Intersection target : targets) {
if (currentLockedCells.contains(target) ||
// (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear)) ||
(EvalUtil.isElapsedIs(target, evalState)) || // TTN-1595
excludedMsrs.contains(target.getCoordinate(msrDim))
) {
lockedTotal += dataCache.getCellValue(target);
lockedTargets.add(target);
}
}
int alan = 2;
double allocAvailable = 0;
// normal routine, remove locked intersections from available allocation targets
if (targets.size() != lockedTargets.size() || evalState.isRoundingResourcePass() ) {
targets.removeAll(lockedTargets);
allocAvailable = allocTotal - lockedTotal;
}
else { // all targets locked so special case
// if some of the locks are original user changes
ArrayList<Intersection> userLockedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
if (allocMeasure.equals(msrToAlloc)) {
userLockedTargets.addAll(userLockFloorCells);
} else {
userLockedTargets.addAll(userAllocFloorCells);
}
userLockedTargets.retainAll(targets);
ArrayList<Intersection> elapsedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
double userLockedTotal = 0;
double elapsedTotal = 0;
for (Intersection target : targets) {
// total elapsed period locks and add them to a specific collection
// if (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear) ) {
if (EvalUtil.isElapsedIs(target, evalState)) { // TTN-1595
elapsedTotal += dataCache.getCellValue(target);
elapsedTargets.add(target);
}
// total user lock floor intersections that intersect with allocation
// targets and don't include elapsed period locks. (TTN-1743)
// if (
// (evalState.getOrigLockedCells().contains(target) || evalState.getOrigChangedCells().contains(target)) // user change true
// &&
// (!elapsedTargets.contains(target)) // not already counted as an elapsed period
// ) {
// userLockedTotal += dataCache.getCellValue(target);
// userLockedTargets.add(target);
// }
}
// always remove elapsed periods from the allocation
targets.removeAll(elapsedTargets);
allocAvailable = allocTotal - elapsedTotal;
// ensure that potential targets of the top allocation measure are preserved (TTN-1743)
if (!allocMeasure.equals(msrToAlloc)) {
Set<Intersection> msrToAllocTargets = new HashSet<Intersection>(evalState.getLoadFactor());
double msrToAllocTargetTotal = 0;
for (Intersection target : targets) {
if (sourceIsTargetCells.contains(target)) {
msrToAllocTargets.add(target);
msrToAllocTargetTotal += dataCache.getCellValue(target);
}
}
targets.removeAll(msrToAllocTargets);
allocAvailable -= msrToAllocTargetTotal;
userLockedTargets.removeAll(msrToAllocTargets);
}
if (targets.size() != userLockedTargets.size()) {
// some targets are user locks so remove them and allocate into rest
for (Intersection userLockedTarget : userLockedTargets) {
if (targets.contains(userLockedTarget)) {
targets.remove(userLockedTarget);
allocAvailable -= dataCache.getCellValue(userLockedTarget);
}
}
}
// else { // all potential targets are user locks, so allocate evenly into them
// allocAvailable = allocAvailable;
// }
}
// if no quantity to allocate, dump out.
// if (allocAvailable == 0) return dataCache;
double origTargetSum = 0;
for (Intersection target : targets ) {
origTargetSum += dataCache.getCellValue(target);
}
// begin timing allocation step
stepTime = System.currentTimeMillis();
// logger.info("Allocating intersection: " + intersection);
// logger.info("Allocating into " + targets.size() + " targets" );
if (origTargetSum == 0 &&
evalState.getRule().getBaseAllocateMeasure() != null
&& !evalState.getRule().getBaseAllocateMeasure().equals("")) {
// in this case, perform the exact same logic as the normal allocation step, however, use the "shape"
// from base measure to determine the allocation percentages.
allocateToTargets(targets, evalState.getRule().getBaseAllocateMeasure(), allocAvailable, dataCache, evalState);
} else {
// normal allocation to open targets
allocateToTargets(targets, allocAvailable, origTargetSum, dataCache, evalState);
}
// logger.info(LogUtil.timedStep("Allocation completed ", stepTime));
// evalState.addAllAllocations(targets);
return dataCache;
}
| public IPafDataCache allocateChange(Intersection allocSrcIsx, Set<Intersection> targets, IPafEvalState evalState, IPafDataCache dataCache) throws PafException {
double allocTotal = dataCache.getCellValue(allocSrcIsx);
// if (logger.isDebugEnabled()) logger.debug("Allocating change for :" + intersection.toString() + " = " + allocTotal);
// convenience variables
// String timeDim = evalState.getAppDef().getMdbDef().getTimeDim();
// String currentYear = evalState.getAppDef().getCurrentYear();
// String yearDim = evalState.getAppDef().getMdbDef().getYearDim();
String msrDim = evalState.getAppDef().getMdbDef().getMeasureDim();
String allocMeasure = allocSrcIsx.getCoordinate(msrDim);
long stepTime = System.currentTimeMillis();
// initial check, don't allocate any intersection that is "elapsed" during forward plannable sessions
// if current plan is forward plannable, also don't allow
// allocation into any intersections containing protected time periods
if (EvalUtil.isElapsedIs(allocSrcIsx, evalState)) return dataCache;
// total locked cells under intersection
stepTime = System.currentTimeMillis();
double lockedTotal = 0;
Set<Intersection> lockedTargets = new HashSet<Intersection>(evalState.getLoadFactor());
Set<Intersection> currentLockedCells = new HashSet<Intersection>(evalState.getLoadFactor());
// Set<String> lockedTimePeriods = evalState.getClientState().getLockedPeriods();
// if (lockedTimePeriods == null) lockedTimePeriods = new HashSet<String>(0);
// add up all locked cell values, this must include floors intersections of excluded measures
// currentLockedCells.addAll(evalState.getCurrentLockedCells());
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
currentLockedCells.addAll(EvalUtil.buildFloorIntersections(lockedCell, evalState));
}
// consider protected cells as locked
// if (allocMeasure.equals(msrToAlloc)) {
// for (Intersection protectedCell : evalState.getCurrentProtectedCells()) {
// currentLockedCells.addAll(EvalUtil.buildFloorIntersections(protectedCell, evalState));
// }
// }
// currentLockedCells.addAll(evalState.getCurrentProtectedCells());
// currentLockedCells.addAll(evalState.getAllocationsByMsr(allocMeasure));
for (Intersection target : targets) {
if (currentLockedCells.contains(target) ||
// (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear)) ||
(EvalUtil.isElapsedIs(target, evalState)) || // TTN-1595
excludedMsrs.contains(target.getCoordinate(msrDim))
) {
lockedTotal += dataCache.getCellValue(target);
lockedTargets.add(target);
}
}
int alan = 2;
double allocAvailable = 0;
// normal routine, remove locked intersections from available allocation targets
if (targets.size() != lockedTargets.size() || evalState.isRoundingResourcePass() ) {
targets.removeAll(lockedTargets);
allocAvailable = allocTotal - lockedTotal;
}
else { // all targets locked so special case
// if some of the locks are original user changes
ArrayList<Intersection> userLockedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
if (allocMeasure.equals(msrToAlloc)) {
userLockedTargets.addAll(userLockFloorCells);
} else {
userLockedTargets.addAll(userAllocFloorCells);
}
userLockedTargets.retainAll(targets);
ArrayList<Intersection> elapsedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
double elapsedTotal = 0;
for (Intersection target : targets) {
// total elapsed period locks and add them to a specific collection
// if (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear) ) {
if (EvalUtil.isElapsedIs(target, evalState)) { // TTN-1595
elapsedTotal += dataCache.getCellValue(target);
elapsedTargets.add(target);
}
// total user lock floor intersections that intersect with allocation
// targets and don't include elapsed period locks. (TTN-1743)
// if (
// (evalState.getOrigLockedCells().contains(target) || evalState.getOrigChangedCells().contains(target)) // user change true
// &&
// (!elapsedTargets.contains(target)) // not already counted as an elapsed period
// ) {
// userLockedTotal += dataCache.getCellValue(target);
// userLockedTargets.add(target);
// }
}
// always remove elapsed periods from the allocation
targets.removeAll(elapsedTargets);
allocAvailable = allocTotal - elapsedTotal;
userLockedTargets.removeAll(elapsedTargets);
// ensure that potential targets of the top allocation measure are preserved (TTN-1743)
Set<Intersection> msrToAllocTargets = null;
double msrToAllocTargetTotal = 0;
if (!allocMeasure.equals(msrToAlloc)) {
msrToAllocTargets = new HashSet<Intersection>(evalState.getLoadFactor());
for (Intersection target : targets) {
if (sourceIsTargetCells.contains(target)) {
msrToAllocTargets.add(target);
msrToAllocTargetTotal += dataCache.getCellValue(target);
}
}
targets.removeAll(msrToAllocTargets);
allocAvailable -= msrToAllocTargetTotal;
userLockedTargets.removeAll(msrToAllocTargets);
}
if (targets.size() != userLockedTargets.size()) {
// some targets are user locks so remove them and allocate into rest
for (Intersection userLockedTarget : userLockedTargets) {
if (targets.contains(userLockedTarget)) {
targets.remove(userLockedTarget);
allocAvailable -= dataCache.getCellValue(userLockedTarget);
}
}
}
// else { // all potential targets are user locks, so allocate evenly into them
// allocAvailable = allocAvailable;
// }
}
// if no quantity to allocate, dump out.
// if (allocAvailable == 0) return dataCache;
double origTargetSum = 0;
for (Intersection target : targets ) {
origTargetSum += dataCache.getCellValue(target);
}
// begin timing allocation step
stepTime = System.currentTimeMillis();
// logger.info("Allocating intersection: " + intersection);
// logger.info("Allocating into " + targets.size() + " targets" );
if (origTargetSum == 0 &&
evalState.getRule().getBaseAllocateMeasure() != null
&& !evalState.getRule().getBaseAllocateMeasure().equals("")) {
// in this case, perform the exact same logic as the normal allocation step, however, use the "shape"
// from base measure to determine the allocation percentages.
allocateToTargets(targets, evalState.getRule().getBaseAllocateMeasure(), allocAvailable, dataCache, evalState);
} else {
// normal allocation to open targets
allocateToTargets(targets, allocAvailable, origTargetSum, dataCache, evalState);
}
// logger.info(LogUtil.timedStep("Allocation completed ", stepTime));
// evalState.addAllAllocations(targets);
return dataCache;
}
|
diff --git a/src/org/seed419/PrintColors.java b/src/org/seed419/PrintColors.java
index 045da6b..aeffe07 100644
--- a/src/org/seed419/PrintColors.java
+++ b/src/org/seed419/PrintColors.java
@@ -1,35 +1,35 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.seed419;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
/**
*
* @author seed419
*/
public class PrintColors {
public void printcolors(CommandSender sender){
- sender.sendMessage(ChatColor.DARK_GREEN + "====================" + ChatColor.DARK_RED + " C"
+ sender.sendMessage(ChatColor.GOLD + "====================" + ChatColor.DARK_RED + " C"
+ ChatColor.RED + "h" + ChatColor.GOLD + "a" + ChatColor.YELLOW + "t" + ChatColor.GREEN + " C"
+ ChatColor.DARK_GREEN + "o" + ChatColor.AQUA + "l" + ChatColor.DARK_AQUA + "o" + ChatColor.BLUE
- + "r" + ChatColor.LIGHT_PURPLE + "s " + ChatColor.DARK_PURPLE + ChatColor.DARK_GREEN + "====================");
- sender.sendMessage(ChatColor.DARK_GREEN + "Syntax for iChat Colors is an ampersand '&', followed by");
+ + "r" + ChatColor.LIGHT_PURPLE + "s " + ChatColor.DARK_PURPLE + ChatColor.GOLD + "====================");
+ sender.sendMessage(ChatColor.DARK_GREEN + "Syntax for Chat Colors is an ampersand '&', followed by");
sender.sendMessage(ChatColor.DARK_GREEN + "either a number or character as follows:");
sender.sendMessage("");
sender.sendMessage(ChatColor.GRAY + "Dark Colors:");
sender.sendMessage(ChatColor.DARK_BLUE + "1 Dark Blue"+ ChatColor.DARK_GREEN
+" 2 Dark Green" + ChatColor.DARK_AQUA +" 3 Dark Aqua" + ChatColor.DARK_RED + " 4 Dark Red");
sender.sendMessage(ChatColor.DARK_PURPLE + "5 Dark Purple" + ChatColor.GOLD + " 6 Gold" + ChatColor.GRAY
- + " 7 Gray" + ChatColor.DARK_GRAY + " 8 Dark Gray" + ChatColor.BLUE + " 9 Blue" + ChatColor.BLACK +"0 Black");
+ + " 7 Gray" + ChatColor.DARK_GRAY + " 8 Dark Gray" + ChatColor.BLUE + " 9 Blue" + ChatColor.BLACK +" 0 Black");
sender.sendMessage("");
sender.sendMessage(ChatColor.GRAY + "Bright Colors:");
sender.sendMessage(ChatColor.GREEN + "a Green" + ChatColor.AQUA + " b Aqua" + ChatColor.RED + " c Red"
+ ChatColor.LIGHT_PURPLE + " d Pink" + ChatColor.YELLOW + " e Yellow"+ChatColor.WHITE + " f White");
}
}
| false | true | public void printcolors(CommandSender sender){
sender.sendMessage(ChatColor.DARK_GREEN + "====================" + ChatColor.DARK_RED + " C"
+ ChatColor.RED + "h" + ChatColor.GOLD + "a" + ChatColor.YELLOW + "t" + ChatColor.GREEN + " C"
+ ChatColor.DARK_GREEN + "o" + ChatColor.AQUA + "l" + ChatColor.DARK_AQUA + "o" + ChatColor.BLUE
+ "r" + ChatColor.LIGHT_PURPLE + "s " + ChatColor.DARK_PURPLE + ChatColor.DARK_GREEN + "====================");
sender.sendMessage(ChatColor.DARK_GREEN + "Syntax for iChat Colors is an ampersand '&', followed by");
sender.sendMessage(ChatColor.DARK_GREEN + "either a number or character as follows:");
sender.sendMessage("");
sender.sendMessage(ChatColor.GRAY + "Dark Colors:");
sender.sendMessage(ChatColor.DARK_BLUE + "1 Dark Blue"+ ChatColor.DARK_GREEN
+" 2 Dark Green" + ChatColor.DARK_AQUA +" 3 Dark Aqua" + ChatColor.DARK_RED + " 4 Dark Red");
sender.sendMessage(ChatColor.DARK_PURPLE + "5 Dark Purple" + ChatColor.GOLD + " 6 Gold" + ChatColor.GRAY
+ " 7 Gray" + ChatColor.DARK_GRAY + " 8 Dark Gray" + ChatColor.BLUE + " 9 Blue" + ChatColor.BLACK +"0 Black");
sender.sendMessage("");
sender.sendMessage(ChatColor.GRAY + "Bright Colors:");
sender.sendMessage(ChatColor.GREEN + "a Green" + ChatColor.AQUA + " b Aqua" + ChatColor.RED + " c Red"
+ ChatColor.LIGHT_PURPLE + " d Pink" + ChatColor.YELLOW + " e Yellow"+ChatColor.WHITE + " f White");
}
| public void printcolors(CommandSender sender){
sender.sendMessage(ChatColor.GOLD + "====================" + ChatColor.DARK_RED + " C"
+ ChatColor.RED + "h" + ChatColor.GOLD + "a" + ChatColor.YELLOW + "t" + ChatColor.GREEN + " C"
+ ChatColor.DARK_GREEN + "o" + ChatColor.AQUA + "l" + ChatColor.DARK_AQUA + "o" + ChatColor.BLUE
+ "r" + ChatColor.LIGHT_PURPLE + "s " + ChatColor.DARK_PURPLE + ChatColor.GOLD + "====================");
sender.sendMessage(ChatColor.DARK_GREEN + "Syntax for Chat Colors is an ampersand '&', followed by");
sender.sendMessage(ChatColor.DARK_GREEN + "either a number or character as follows:");
sender.sendMessage("");
sender.sendMessage(ChatColor.GRAY + "Dark Colors:");
sender.sendMessage(ChatColor.DARK_BLUE + "1 Dark Blue"+ ChatColor.DARK_GREEN
+" 2 Dark Green" + ChatColor.DARK_AQUA +" 3 Dark Aqua" + ChatColor.DARK_RED + " 4 Dark Red");
sender.sendMessage(ChatColor.DARK_PURPLE + "5 Dark Purple" + ChatColor.GOLD + " 6 Gold" + ChatColor.GRAY
+ " 7 Gray" + ChatColor.DARK_GRAY + " 8 Dark Gray" + ChatColor.BLUE + " 9 Blue" + ChatColor.BLACK +" 0 Black");
sender.sendMessage("");
sender.sendMessage(ChatColor.GRAY + "Bright Colors:");
sender.sendMessage(ChatColor.GREEN + "a Green" + ChatColor.AQUA + " b Aqua" + ChatColor.RED + " c Red"
+ ChatColor.LIGHT_PURPLE + " d Pink" + ChatColor.YELLOW + " e Yellow"+ChatColor.WHITE + " f White");
}
|
diff --git a/src/main/java/org/lightmare/jpa/datasource/PoolConfig.java b/src/main/java/org/lightmare/jpa/datasource/PoolConfig.java
index c980725e1..7305dd4b0 100644
--- a/src/main/java/org/lightmare/jpa/datasource/PoolConfig.java
+++ b/src/main/java/org/lightmare/jpa/datasource/PoolConfig.java
@@ -1,222 +1,221 @@
package org.lightmare.jpa.datasource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Configuration with default parameters for c3p0 connection pooling
*
* @author levan
*
*/
public class PoolConfig {
public static final String MAX_POOL_SIZE = "maxPoolSize";
public static final String INITIAL_POOL_SIZE = "initialPoolSize";
public static final String MIN_POOL_SIZE = "minPoolSize";
public static final String MAX_IDLE_TIMEOUT = "maxIdleTime";
public static final String MAX_STATEMENTS = "maxStatements";
public static final String AQUIRE_INCREMENT = "acquireIncrement";
public static final String MAX_IDLE_TIME_EXCESS_CONN = "maxIdleTimeExcessConnections";
public static final String STAT_CACHE_NUM_DEFF_THREADS = "statementCacheNumDeferredCloseThreads";
public static final String MAX_POOL_SIZE_DEF_VALUE = "15";
public static final String INITIAL_POOL_SIZE_DEF_VALUE = "5";
public static final String MIN_POOL_SIZE_DEF_VALUE = "5";
public static final String MAX_IDLE_TIMEOUT_DEF_VALUE = "0";
public static final String MAX_STATEMENTS_DEF_VALUE = "50";
public static final String AQUIRE_INCREMENT_DEF_VALUE = "50";
public static final String MAX_IDLE_TIME_EXCESS_CONN_DEF_VALUE = "0";
public static final String STAT_CACHE_NUM_DEFF_THREADS_DEF_VALUE = "1";
private static final String DEFAULT_POOL_PATH = "META-INF/pool.properties";
public static String poolPath;
public static Map<Object, Object> poolProperties;
/**
* Enumeration to choose which type connection pool should be in use
*
* @author levan
*
*/
public static enum PoolProviderType {
C3P0, TOMCAT;
}
public static PoolProviderType poolProviderType = PoolProviderType.C3P0;
/**
* Sets default connection pooling properties
*
* @return
*/
public static Map<Object, Object> getDefaultPooling() {
Map<Object, Object> c3p0Properties = new HashMap<Object, Object>();
c3p0Properties.put(PoolConfig.MAX_POOL_SIZE,
PoolConfig.MAX_POOL_SIZE_DEF_VALUE);
c3p0Properties.put(PoolConfig.INITIAL_POOL_SIZE,
PoolConfig.INITIAL_POOL_SIZE_DEF_VALUE);
c3p0Properties.put(PoolConfig.MIN_POOL_SIZE,
PoolConfig.MIN_POOL_SIZE_DEF_VALUE);
c3p0Properties.put(PoolConfig.MAX_IDLE_TIMEOUT,
PoolConfig.MAX_IDLE_TIMEOUT_DEF_VALUE);
c3p0Properties.put(PoolConfig.MAX_STATEMENTS,
PoolConfig.MAX_STATEMENTS_DEF_VALUE);
c3p0Properties.put(PoolConfig.AQUIRE_INCREMENT,
PoolConfig.AQUIRE_INCREMENT_DEF_VALUE);
c3p0Properties.put(STAT_CACHE_NUM_DEFF_THREADS,
STAT_CACHE_NUM_DEFF_THREADS_DEF_VALUE);
return c3p0Properties;
}
private static boolean checkModifiers(Field field) {
return Modifier.isStatic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())
&& field.getType().equals(String.class);
}
private static Set<Object> unsopportedKeys() throws IOException {
Set<Object> keys = new HashSet<Object>();
Field[] fields = DataSourceInitializer.class.getDeclaredFields();
Object key;
String apprEnd = "_PROPERTY";
String name;
for (Field field : fields) {
name = field.getName();
if (checkModifiers(field) && name.endsWith(apprEnd)) {
key = MetaUtils.getFieldValue(field);
keys.add(key);
}
}
return keys;
}
/**
* Add initialized properties to defaults
*
* @param defaults
* @param initial
*/
private static void fillDefaults(Map<Object, Object> defaults,
Map<Object, Object> initial) {
defaults.putAll(initial);
}
/**
* Generates pooling configuration properties
*
* @param initial
* @return {@link Map}<Object, Object>
* @throws IOException
*/
private static Map<Object, Object> configProperties(
Map<Object, Object> initial) throws IOException {
Map<Object, Object> propertiesMap = getDefaultPooling();
fillDefaults(propertiesMap, initial);
Set<Object> keys = unsopportedKeys();
for (Object key : keys) {
propertiesMap.remove(key);
}
return propertiesMap;
}
public static int asInt(Map<Object, Object> properties, Object key) {
Object property = properties.get(key);
Integer propertyInt;
if (property == null) {
propertyInt = null;
} else if (property instanceof Integer) {
propertyInt = (Integer) property;
} else if (property instanceof String) {
propertyInt = Integer.valueOf((String) property);
} else {
propertyInt = null;
}
return propertyInt;
}
/**
* Loads {@link Properties} from specific path
*
* @param path
* @return {@link Properties}
* @throws IOException
*/
public static Map<Object, Object> load() throws IOException {
InputStream stream;
if (ObjectUtils.notAvailable(poolPath)) {
- poolPath = DEFAULT_POOL_PATH;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
- stream = loader.getResourceAsStream(poolPath);
+ stream = loader.getResourceAsStream(DEFAULT_POOL_PATH);
} else {
File file = new File(poolPath);
stream = new FileInputStream(file);
}
try {
Map<Object, Object> properties;
Properties propertiesToLoad;
if (ObjectUtils.notNull(stream)) {
propertiesToLoad = new Properties();
propertiesToLoad.load(stream);
properties = new HashMap<Object, Object>();
properties.putAll(propertiesToLoad);
} else {
properties = null;
}
return properties;
} finally {
if (ObjectUtils.notNull(stream)) {
stream.close();
}
}
}
/**
* Merges passed properties, startup time passed properties and properties
* loaded from file
*
* @param properties
* @return {@link Map}<Object, Object> merged properties map
* @throws IOException
*/
public static Map<Object, Object> merge(Map<Object, Object> properties)
throws IOException {
Map<Object, Object> configMap = configProperties(properties);
Map<Object, Object> loaded = load();
if (ObjectUtils.notNull(loaded)) {
fillDefaults(configMap, loaded);
}
if (ObjectUtils.notNull(poolProperties)) {
fillDefaults(configMap, poolProperties);
}
return configMap;
}
}
| false | true | public static Map<Object, Object> load() throws IOException {
InputStream stream;
if (ObjectUtils.notAvailable(poolPath)) {
poolPath = DEFAULT_POOL_PATH;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
stream = loader.getResourceAsStream(poolPath);
} else {
File file = new File(poolPath);
stream = new FileInputStream(file);
}
try {
Map<Object, Object> properties;
Properties propertiesToLoad;
if (ObjectUtils.notNull(stream)) {
propertiesToLoad = new Properties();
propertiesToLoad.load(stream);
properties = new HashMap<Object, Object>();
properties.putAll(propertiesToLoad);
} else {
properties = null;
}
return properties;
} finally {
if (ObjectUtils.notNull(stream)) {
stream.close();
}
}
}
| public static Map<Object, Object> load() throws IOException {
InputStream stream;
if (ObjectUtils.notAvailable(poolPath)) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
stream = loader.getResourceAsStream(DEFAULT_POOL_PATH);
} else {
File file = new File(poolPath);
stream = new FileInputStream(file);
}
try {
Map<Object, Object> properties;
Properties propertiesToLoad;
if (ObjectUtils.notNull(stream)) {
propertiesToLoad = new Properties();
propertiesToLoad.load(stream);
properties = new HashMap<Object, Object>();
properties.putAll(propertiesToLoad);
} else {
properties = null;
}
return properties;
} finally {
if (ObjectUtils.notNull(stream)) {
stream.close();
}
}
}
|
diff --git a/gshell/gshell-admin/src/test/java/org/apache/servicemix/jpm/ProcessTest.java b/gshell/gshell-admin/src/test/java/org/apache/servicemix/jpm/ProcessTest.java
index 5f436ae1..88440632 100644
--- a/gshell/gshell-admin/src/test/java/org/apache/servicemix/jpm/ProcessTest.java
+++ b/gshell/gshell-admin/src/test/java/org/apache/servicemix/jpm/ProcessTest.java
@@ -1,64 +1,65 @@
/*
* 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.servicemix.jpm;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ProcessTest {
@Test
public void testCreate() throws Exception {
StringBuilder command = new StringBuilder();
command.append("java -classpath ");
String clRes = getClass().getName().replace('.', '/') + ".class";
String str = getClass().getClassLoader().getResource(clRes).toString();
str = str.substring("file:".length(), str.indexOf(clRes));
command.append(str);
command.append(" ");
command.append(MainTest.class.getName());
command.append(" ");
command.append(60000);
System.err.println("Executing: " + command.toString());
ProcessBuilder builder = ProcessBuilderFactory.newInstance().newBuilder();
Process p = builder.command(command.toString()).start();
assertNotNull(p);
System.err.println("Process: " + p.getPid());
assertNotNull(p.getPid());
Thread.currentThread().sleep(1000);
System.err.println("Running: " + p.isRunning());
assertTrue(p.isRunning());
System.err.println("Destroying");
p.destroy();
+ Thread.currentThread().sleep(1000);
System.err.println("Running: " + p.isRunning());
assertFalse(p.isRunning());
}
/*
@Test
@Ignore("When the process creation fails, no error is reported by the script")
public void testFailure() throws Exception {
ProcessBuilder builder = ProcessBuilderFactory.newInstance().newBuilder();
Process p = builder.command("ec").start();
fail("An exception should have been thrown");
}
*/
}
| true | true | public void testCreate() throws Exception {
StringBuilder command = new StringBuilder();
command.append("java -classpath ");
String clRes = getClass().getName().replace('.', '/') + ".class";
String str = getClass().getClassLoader().getResource(clRes).toString();
str = str.substring("file:".length(), str.indexOf(clRes));
command.append(str);
command.append(" ");
command.append(MainTest.class.getName());
command.append(" ");
command.append(60000);
System.err.println("Executing: " + command.toString());
ProcessBuilder builder = ProcessBuilderFactory.newInstance().newBuilder();
Process p = builder.command(command.toString()).start();
assertNotNull(p);
System.err.println("Process: " + p.getPid());
assertNotNull(p.getPid());
Thread.currentThread().sleep(1000);
System.err.println("Running: " + p.isRunning());
assertTrue(p.isRunning());
System.err.println("Destroying");
p.destroy();
System.err.println("Running: " + p.isRunning());
assertFalse(p.isRunning());
}
| public void testCreate() throws Exception {
StringBuilder command = new StringBuilder();
command.append("java -classpath ");
String clRes = getClass().getName().replace('.', '/') + ".class";
String str = getClass().getClassLoader().getResource(clRes).toString();
str = str.substring("file:".length(), str.indexOf(clRes));
command.append(str);
command.append(" ");
command.append(MainTest.class.getName());
command.append(" ");
command.append(60000);
System.err.println("Executing: " + command.toString());
ProcessBuilder builder = ProcessBuilderFactory.newInstance().newBuilder();
Process p = builder.command(command.toString()).start();
assertNotNull(p);
System.err.println("Process: " + p.getPid());
assertNotNull(p.getPid());
Thread.currentThread().sleep(1000);
System.err.println("Running: " + p.isRunning());
assertTrue(p.isRunning());
System.err.println("Destroying");
p.destroy();
Thread.currentThread().sleep(1000);
System.err.println("Running: " + p.isRunning());
assertFalse(p.isRunning());
}
|
diff --git a/src/JFlex/Emitter.java b/src/JFlex/Emitter.java
index 8b9a9fc..a5619a5 100644
--- a/src/JFlex/Emitter.java
+++ b/src/JFlex/Emitter.java
@@ -1,1574 +1,1576 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* JFlex 1.4 *
* Copyright (C) 1998-2004 Gerwin Klein <[email protected]> *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License. See the file *
* COPYRIGHT for more information. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package JFlex;
import java.io.*;
import java.util.*;
import java.text.*;
/**
* This class manages the actual code generation, putting
* the scanner together, filling in skeleton sections etc.
*
* Table compression, String packing etc. is also done here.
*
* @author Gerwin Klein
* @version JFlex 1.4, $Revision$, $Date$
*/
final public class Emitter {
// bit masks for state attributes
static final private int FINAL = 1;
static final private int PUSHBACK = 2;
static final private int LOOKEND = 4;
static final private int NOLOOK = 8;
static final private String date = (new SimpleDateFormat()).format(new Date());
private File inputFile;
private PrintWriter out;
private Skeleton skel;
private LexScan scanner;
private LexParse parser;
private DFA dfa;
// for switch statement:
// table[i][j] is the set of input characters that leads from state i to state j
private CharSet table[][];
private boolean isTransition[];
// noTarget[i] is the set of input characters that have no target state in state i
private CharSet noTarget[];
// for row killing:
private int numRows;
private int [] rowMap;
private boolean [] rowKilled;
// for col killing:
private int numCols;
private int [] colMap;
private boolean [] colKilled;
/** maps actions to their switch label */
private Hashtable actionTable = new Hashtable();
private CharClassInterval [] intervalls;
private String visibility = "public";
public Emitter(File inputFile, LexParse parser, DFA dfa) throws IOException {
String name = parser.scanner.className+".java";
File outputFile = normalize(name, inputFile);
Out.println("Writing code to \""+outputFile+"\"");
this.out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
this.parser = parser;
this.scanner = parser.scanner;
this.visibility = scanner.visibility;
this.inputFile = inputFile;
this.dfa = dfa;
this.skel = new Skeleton(out);
}
/**
* Constructs a file in Options.getDir() or in the same directory as
* another file. Makes a backup if the file already exists.
*
* @param name the name (without path) of the file
* @param path the path where to construct the file
* @param input fallback location if path = <tt>null</tt>
* (expected to be a file in the directory to write to)
*/
public static File normalize(String name, File input) {
File outputFile;
if ( Options.getDir() == null )
if ( input == null || input.getParent() == null )
outputFile = new File(name);
else
outputFile = new File(input.getParent(), name);
else
outputFile = new File(Options.getDir(), name);
if ( outputFile.exists() && !Options.no_backup ) {
File backup = new File( outputFile.toString()+"~" );
if ( backup.exists() ) backup.delete();
if ( outputFile.renameTo( backup ) )
Out.println("Old file \""+outputFile+"\" saved as \""+backup+"\"");
else
Out.println("Couldn't save old file \""+outputFile+"\", overwriting!");
}
return outputFile;
}
private void println() {
out.println();
}
private void println(String line) {
out.println(line);
}
private void println(int i) {
out.println(i);
}
private void print(String line) {
out.print(line);
}
private void print(int i) {
out.print(i);
}
private void print(int i, int tab) {
int exp;
if (i < 0)
exp = 1;
else
exp = 10;
while (tab-- > 1) {
if (Math.abs(i) < exp) print(" ");
exp*= 10;
}
print(i);
}
private void emitScanError() {
print(" private void zzScanError(int errorCode)");
if (scanner.scanErrorException != null)
print(" throws "+scanner.scanErrorException);
println(" {");
skel.emitNext();
if (scanner.scanErrorException == null)
println(" throw new Error(message);");
else
println(" throw new "+scanner.scanErrorException+"(message);");
skel.emitNext();
print(" "+visibility+" void yypushback(int number) ");
if (scanner.scanErrorException == null)
println(" {");
else
println(" throws "+scanner.scanErrorException+" {");
}
private void emitMain() {
if ( !(scanner.standalone || scanner.debugOption || scanner.cupDebug) ) return;
if ( scanner.cupDebug ) {
println(" /**");
println(" * Converts an int token code into the name of the");
println(" * token by reflection on the cup symbol class/interface "+scanner.cupSymbol);
println(" *");
println(" * This code was contributed by Karl Meissner <[email protected]>");
println(" */");
println(" private String getTokenName(int token) {");
println(" try {");
println(" java.lang.reflect.Field [] classFields = " + scanner.cupSymbol + ".class.getFields();");
println(" for (int i = 0; i < classFields.length; i++) {");
println(" if (classFields[i].getInt(null) == token) {");
println(" return classFields[i].getName();");
println(" }");
println(" }");
println(" } catch (Exception e) {");
println(" e.printStackTrace(System.err);");
println(" }");
println("");
println(" return \"UNKNOWN TOKEN\";");
println(" }");
println("");
println(" /**");
println(" * Same as "+scanner.functionName+" but also prints the token to standard out");
println(" * for debugging.");
println(" *");
println(" * This code was contributed by Karl Meissner <[email protected]>");
println(" */");
print(" "+visibility+" ");
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" debug_");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
println(" java_cup.runtime.Symbol s = "+scanner.functionName+"();");
print(" System.out.println( ");
if (scanner.lineCount) print("\"line:\" + (yyline+1) + ");
if (scanner.columnCount) print("\" col:\" + (yycolumn+1) + ");
println("\" --\"+ yytext() + \"--\" + getTokenName(s.sym) + \"--\");");
println(" return s;");
println(" }");
println("");
}
if ( scanner.standalone ) {
println(" /**");
println(" * Runs the scanner on input files.");
println(" *");
println(" * This is a standalone scanner, it will print any unmatched");
println(" * text to System.out unchanged.");
println(" *");
println(" * @param argv the command line, contains the filenames to run");
println(" * the scanner on.");
println(" */");
}
else {
println(" /**");
println(" * Runs the scanner on input files.");
println(" *");
println(" * This main method is the debugging routine for the scanner.");
println(" * It prints debugging information about each returned token to");
println(" * System.out until the end of file is reached, or an error occured.");
println(" *");
println(" * @param argv the command line, contains the filenames to run");
println(" * the scanner on.");
println(" */");
}
println(" public static void main(String argv[]) {");
println(" if (argv.length == 0) {");
println(" System.out.println(\"Usage : java "+scanner.className+" <inputfile>\");");
println(" }");
println(" else {");
println(" for (int i = 0; i < argv.length; i++) {");
println(" "+scanner.className+" scanner = null;");
println(" try {");
println(" scanner = new "+scanner.className+"( new java.io.FileReader(argv[i]) );");
if ( scanner.standalone ) {
println(" while ( !scanner.zzAtEOF ) scanner."+scanner.functionName+"();");
}
else if (scanner.cupDebug ) {
println(" while ( !scanner.zzAtEOF ) scanner.debug_"+scanner.functionName+"();");
}
else {
println(" do {");
println(" System.out.println(scanner."+scanner.functionName+"());");
println(" } while (!scanner.zzAtEOF);");
println("");
}
println(" }");
println(" catch (java.io.FileNotFoundException e) {");
println(" System.out.println(\"File not found : \\\"\"+argv[i]+\"\\\"\");");
println(" }");
println(" catch (java.io.IOException e) {");
println(" System.out.println(\"IO error scanning file \\\"\"+argv[i]+\"\\\"\");");
println(" System.out.println(e);");
println(" }");
println(" catch (Exception e) {");
println(" System.out.println(\"Unexpected exception:\");");
println(" e.printStackTrace();");
println(" }");
println(" }");
println(" }");
println(" }");
println("");
}
private void emitNoMatch() {
println(" zzScanError(ZZ_NO_MATCH);");
}
private void emitNextInput() {
println(" if (zzCurrentPosL < zzEndReadL)");
println(" zzInput = zzBufferL[zzCurrentPosL++];");
println(" else if (zzAtEOF) {");
println(" zzInput = YYEOF;");
println(" break zzForAction;");
println(" }");
println(" else {");
println(" // store back cached positions");
println(" zzCurrentPos = zzCurrentPosL;");
println(" zzMarkedPos = zzMarkedPosL;");
if ( scanner.lookAheadUsed )
println(" zzPushbackPos = zzPushbackPosL;");
println(" boolean eof = zzRefill();");
println(" // get translated positions and possibly new buffer");
println(" zzCurrentPosL = zzCurrentPos;");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" zzEndReadL = zzEndRead;");
if ( scanner.lookAheadUsed )
println(" zzPushbackPosL = zzPushbackPos;");
println(" if (eof) {");
println(" zzInput = YYEOF;");
println(" break zzForAction;");
println(" }");
println(" else {");
println(" zzInput = zzBufferL[zzCurrentPosL++];");
println(" }");
println(" }");
}
private void emitHeader() {
println("/* The following code was generated by JFlex "+Main.version+" on "+date+" */");
println("");
}
private void emitUserCode() {
if ( scanner.userCode.length() > 0 )
println(scanner.userCode.toString());
}
private void emitClassName() {
if (!endsWithJavadoc(scanner.userCode)) {
String path = inputFile.toString();
// slashify path (avoid backslash u sequence = unicode escape)
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
println("/**");
println(" * This class is a scanner generated by ");
println(" * <a href=\"http://www.jflex.de/\">JFlex</a> "+Main.version);
println(" * on "+date+" from the specification file");
println(" * <tt>"+path+"</tt>");
println(" */");
}
if ( scanner.isPublic ) print("public ");
if ( scanner.isAbstract) print("abstract ");
if ( scanner.isFinal ) print("final ");
print("class ");
print(scanner.className);
if ( scanner.isExtending != null ) {
print(" extends ");
print(scanner.isExtending);
}
if ( scanner.isImplementing != null ) {
print(" implements ");
print(scanner.isImplementing);
}
println(" {");
}
/**
* Try to find out if user code ends with a javadoc comment
*
* @param buffer the user code
* @return true if it ends with a javadoc comment
*/
public static boolean endsWithJavadoc(StringBuffer usercode) {
String s = usercode.toString().trim();
if (!s.endsWith("*/")) return false;
// find beginning of javadoc comment
int i = s.lastIndexOf("/**");
if (i < 0) return false;
// javadoc comment shouldn't contain a comment end
return s.substring(i,s.length()-2).indexOf("*/") < 0;
}
private void emitLexicalStates() {
Enumeration stateNames = scanner.states.names();
while ( stateNames.hasMoreElements() ) {
String name = (String) stateNames.nextElement();
int num = scanner.states.getNumber(name).intValue();
if (scanner.bolUsed)
println(" "+visibility+" static final int "+name+" = "+2*num+";");
else
println(" "+visibility+" static final int "+name+" = "+dfa.lexState[2*num]+";");
}
if (scanner.bolUsed) {
println("");
println(" /**");
println(" * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l");
println(" * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l");
println(" * at the beginning of a line");
println(" * l is of the form l = 2*k, k a non negative integer");
println(" */");
println(" private static final int ZZ_LEXSTATE[] = { ");
int i, j = 0;
print(" ");
for (i = 0; i < dfa.lexState.length-1; i++) {
print( dfa.lexState[i], 2 );
print(", ");
if (++j >= 16) {
println();
print(" ");
j = 0;
}
}
println( dfa.lexState[i] );
println(" };");
}
}
private void emitDynamicInit() {
int count = 0;
int value = dfa.table[0][0];
println(" /** ");
println(" * The transition table of the DFA");
println(" */");
CountEmitter e = new CountEmitter("Trans");
e.setValTranslation(+1); // allow vals in [-1, 0xFFFE]
e.emitInit();
for (int i = 0; i < dfa.numStates; i++) {
if ( !rowKilled[i] ) {
for (int c = 0; c < dfa.numInput; c++) {
if ( !colKilled[c] ) {
if (dfa.table[i][c] == value) {
count++;
}
else {
e.emit(count, value);
count = 1;
value = dfa.table[i][c];
}
}
}
}
}
e.emit(count, value);
e.emitUnpack();
println(e.toString());
}
private void emitCharMapInitFunction() {
CharClasses cl = parser.getCharClasses();
if ( cl.getMaxCharCode() < 256 ) return;
println("");
println(" /** ");
println(" * Unpacks the compressed character translation table.");
println(" *");
println(" * @param packed the packed character translation table");
println(" * @return the unpacked character translation table");
println(" */");
println(" private static char [] zzUnpackCMap(String packed) {");
println(" char [] map = new char[0x10000];");
println(" int i = 0; /* index in packed string */");
println(" int j = 0; /* index in unpacked array */");
println(" while (i < "+2*intervalls.length+") {");
println(" int count = packed.charAt(i++);");
println(" char value = packed.charAt(i++);");
println(" do map[j++] = value; while (--count > 0);");
println(" }");
println(" return map;");
println(" }");
}
private void emitZZTrans() {
int i,c;
int n = 0;
println(" /** ");
println(" * The transition table of the DFA");
println(" */");
println(" private static final int ZZ_TRANS [] = {"); //XXX
print(" ");
for (i = 0; i < dfa.numStates; i++) {
if ( !rowKilled[i] ) {
for (c = 0; c < dfa.numInput; c++) {
if ( !colKilled[c] ) {
if (n >= 10) {
println();
print(" ");
n = 0;
}
print( dfa.table[i][c] );
if (i != dfa.numStates-1 || c != dfa.numInput-1)
print( ", ");
n++;
}
}
}
}
println();
println(" };");
}
private void emitCharMapArrayUnPacked() {
CharClasses cl = parser.getCharClasses();
intervalls = cl.getIntervalls();
println("");
println(" /** ");
println(" * Translates characters to character classes");
println(" */");
println(" private static final char [] ZZ_CMAP = {");
int n = 0; // numbers of entries in current line
print(" ");
int max = cl.getMaxCharCode();
int i = 0;
while ( i < intervalls.length && intervalls[i].start <= max ) {
int end = Math.min(intervalls[i].end, max);
for (int c = intervalls[i].start; c <= end; c++) {
print(colMap[intervalls[i].charClass], 2);
if (c < max) {
print(", ");
if ( ++n >= 16 ) {
println();
print(" ");
n = 0;
}
}
}
i++;
}
println();
println(" };");
println();
}
private void emitCharMapArray() {
CharClasses cl = parser.getCharClasses();
if ( cl.getMaxCharCode() < 256 ) {
emitCharMapArrayUnPacked();
return;
}
// ignores cl.getMaxCharCode(), emits all intervalls instead
intervalls = cl.getIntervalls();
println("");
println(" /** ");
println(" * Translates characters to character classes");
println(" */");
println(" private static final String ZZ_CMAP_PACKED = ");
int n = 0; // numbers of entries in current line
print(" \"");
int i = 0;
while ( i < intervalls.length-1 ) {
int count = intervalls[i].end-intervalls[i].start+1;
int value = colMap[intervalls[i].charClass];
printUC(count);
printUC(value);
if ( ++n >= 10 ) {
println("\"+");
print(" \"");
n = 0;
}
i++;
}
printUC(intervalls[i].end-intervalls[i].start+1);
printUC(colMap[intervalls[i].charClass]);
println("\";");
println();
println(" /** ");
println(" * Translates characters to character classes");
println(" */");
println(" private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);");
println();
}
/**
* Print number as octal/unicode escaped string character.
*
* @param c the value to print
* @prec 0 <= c <= 0xFFFF
*/
private void printUC(int c) {
if (c > 255) {
out.print("\\u");
if (c < 0x1000) out.print("0");
out.print(Integer.toHexString(c));
}
else {
out.print("\\");
out.print(Integer.toOctalString(c));
}
}
private void emitRowMapArray() {
println("");
println(" /** ");
println(" * Translates a state to a row index in the transition table");
println(" */");
HiLowEmitter e = new HiLowEmitter("RowMap");
e.emitInit();
for (int i = 0; i < dfa.numStates; i++) {
e.emit(rowMap[i]*numCols);
}
e.emitUnpack();
println(e.toString());
}
private void emitAttributes() {
println(" /**");
println(" * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>");
println(" */");
CountEmitter e = new CountEmitter("Attribute");
e.emitInit();
int count = 1;
int value = 0;
if ( dfa.isFinal[0] ) value = FINAL;
if ( dfa.isPushback[0] ) value|= PUSHBACK;
if ( dfa.isLookEnd[0] ) value|= LOOKEND;
if ( !isTransition[0] ) value|= NOLOOK;
for (int i = 1; i < dfa.numStates; i++) {
int attribute = 0;
if ( dfa.isFinal[i] ) attribute = FINAL;
if ( dfa.isPushback[i] ) attribute|= PUSHBACK;
if ( dfa.isLookEnd[i] ) attribute|= LOOKEND;
if ( !isTransition[i] ) attribute|= NOLOOK;
if (value == attribute) {
count++;
}
else {
e.emit(count, value);
count = 1;
value = attribute;
}
}
e.emit(count, value);
e.emitUnpack();
println(e.toString());
}
private void emitClassCode() {
if ( scanner.eofCode != null ) {
println(" /** denotes if the user-EOF-code has already been executed */");
println(" private boolean zzEOFDone;");
println("");
}
if ( scanner.classCode != null ) {
println(" /* user code: */");
println(scanner.classCode);
}
}
private void emitConstructorDecl() {
print(" ");
if ( scanner.isPublic ) print("public ");
print( scanner.className );
print("(java.io.Reader in)");
if ( scanner.initThrow != null ) {
print(" throws ");
print( scanner.initThrow );
}
println(" {");
if ( scanner.initCode != null ) {
print(" ");
print( scanner.initCode );
}
println(" this.zzReader = in;");
println(" }");
println();
println(" /**");
println(" * Creates a new scanner.");
println(" * There is also java.io.Reader version of this constructor.");
println(" *");
println(" * @param in the java.io.Inputstream to read input from.");
println(" */");
print(" ");
if ( scanner.isPublic ) print("public ");
print( scanner.className );
print("(java.io.InputStream in)");
if ( scanner.initThrow != null ) {
print(" throws ");
print( scanner.initThrow );
}
println(" {");
println(" this(new java.io.InputStreamReader(in));");
println(" }");
}
private void emitDoEOF() {
if ( scanner.eofCode == null ) return;
println(" /**");
println(" * Contains user EOF-code, which will be executed exactly once,");
println(" * when the end of file is reached");
println(" */");
print(" private void zzDoEOF()");
if ( scanner.eofThrow != null ) {
print(" throws ");
print(scanner.eofThrow);
}
println(" {");
println(" if (!zzEOFDone) {");
println(" zzEOFDone = true;");
println(" "+scanner.eofCode );
println(" }");
println(" }");
println("");
println("");
}
private void emitLexFunctHeader() {
if (scanner.cupCompatible) {
// force public, because we have to implement java_cup.runtime.Symbol
print(" public ");
}
else {
print(" "+visibility+" ");
}
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" ");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
skel.emitNext();
if ( scanner.useRowMap ) {
println(" int [] zzTransL = ZZ_TRANS;");
println(" int [] zzRowMapL = ZZ_ROWMAP;");
println(" int [] zzAttrL = ZZ_ATTRIBUTE;");
}
if ( scanner.lookAheadUsed ) {
println(" int zzPushbackPosL = zzPushbackPos = -1;");
println(" boolean zzWasPushback;");
}
skel.emitNext();
if ( scanner.charCount ) {
println(" yychar+= zzMarkedPosL-zzStartRead;");
println("");
}
if ( scanner.lineCount || scanner.columnCount ) {
println(" boolean zzR = false;");
println(" for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;");
println(" zzCurrentPosL++) {");
println(" switch (zzBufferL[zzCurrentPosL]) {");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = false;");
println(" break;");
println(" case '\\r':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = true;");
println(" break;");
println(" case '\\n':");
println(" if (zzR)");
println(" zzR = false;");
println(" else {");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" }");
println(" break;");
println(" default:");
println(" zzR = false;");
if ( scanner.columnCount )
println(" yycolumn++;");
println(" }");
println(" }");
println();
if ( scanner.lineCount ) {
println(" if (zzR) {");
println(" // peek one character ahead if it is \\n (if we have counted one line too much)");
println(" boolean zzPeek;");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" else if (zzAtEOF)");
println(" zzPeek = false;");
println(" else {");
println(" boolean eof = zzRefill();");
+ println(" zzEndReadL = zzEndRead;");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzPeek = false;");
println(" else ");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" }");
println(" if (zzPeek) yyline--;");
println(" }");
}
}
if ( scanner.bolUsed ) {
// zzMarkedPos > zzStartRead <=> last match was not empty
// if match was empty, last value of zzAtBOL can be used
// zzStartRead is always >= 0
println(" if (zzMarkedPosL > zzStartRead) {");
println(" switch (zzBufferL[zzMarkedPosL-1]) {");
println(" case '\\n':");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
println(" zzAtBOL = true;");
println(" break;");
println(" case '\\r': ");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" else if (zzAtEOF)");
println(" zzAtBOL = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
+ println(" zzEndReadL = zzEndRead;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzAtBOL = false;");
println(" else ");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" }");
println(" break;");
println(" default:");
println(" zzAtBOL = false;");
println(" }");
println(" }");
}
skel.emitNext();
if (scanner.bolUsed) {
println(" if (zzAtBOL)");
println(" zzState = ZZ_LEXSTATE[zzLexicalState+1];");
println(" else");
println(" zzState = ZZ_LEXSTATE[zzLexicalState];");
println();
}
else {
println(" zzState = zzLexicalState;");
println();
}
if (scanner.lookAheadUsed)
println(" zzWasPushback = false;");
skel.emitNext();
}
private void emitGetRowMapNext() {
println(" int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];");
println(" if (zzNext == "+DFA.NO_TARGET+") break zzForAction;");
println(" zzState = zzNext;");
println();
println(" int zzAttributes = zzAttrL[zzState];");
if ( scanner.lookAheadUsed ) {
println(" if ( (zzAttributes & "+PUSHBACK+") == "+PUSHBACK+" )");
println(" zzPushbackPosL = zzCurrentPosL;");
println();
}
println(" if ( (zzAttributes & "+FINAL+") == "+FINAL+" ) {");
if ( scanner.lookAheadUsed )
println(" zzWasPushback = (zzAttributes & "+LOOKEND+") == "+LOOKEND+";");
skel.emitNext();
println(" if ( (zzAttributes & "+NOLOOK+") == "+NOLOOK+" ) break zzForAction;");
skel.emitNext();
}
private void emitTransitionTable() {
transformTransitionTable();
println(" zzInput = zzCMapL[zzInput];");
println();
if ( scanner.lookAheadUsed )
println(" boolean zzPushback = false;");
println(" boolean zzIsFinal = false;");
println(" boolean zzNoLookAhead = false;");
println();
println(" zzForNext: { switch (zzState) {");
for (int state = 0; state < dfa.numStates; state++)
if (isTransition[state]) emitState(state);
println(" default:");
println(" // if this is ever reached, there is a serious bug in JFlex");
println(" zzScanError(ZZ_UNKNOWN_ERROR);");
println(" break;");
println(" } }");
println();
println(" if ( zzIsFinal ) {");
if ( scanner.lookAheadUsed )
println(" zzWasPushback = zzPushback;");
skel.emitNext();
println(" if ( zzNoLookAhead ) break zzForAction;");
skel.emitNext();
}
/**
* Escapes all " ' \ tabs and newlines
*/
private String escapify(String s) {
StringBuffer result = new StringBuffer(s.length()*2);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\'': result.append("\\\'"); break;
case '\"': result.append("\\\""); break;
case '\\': result.append("\\\\"); break;
case '\t': result.append("\\t"); break;
case '\r': if (i+1 == s.length() || s.charAt(i+1) != '\n') result.append("\"+ZZ_NL+\"");
break;
case '\n': result.append("\"+ZZ_NL+\""); break;
default: result.append(c);
}
}
return result.toString();
}
public void emitActionTable() {
int lastAction = 1;
int count = 0;
int value = 0;
println(" /** ");
println(" * Translates DFA states to action switch labels.");
println(" */");
CountEmitter e = new CountEmitter("Action");
e.emitInit();
for (int i = 0; i < dfa.numStates; i++) {
int newVal;
if ( dfa.isFinal[i] ) {
Action action = dfa.action[i];
Integer stored = (Integer) actionTable.get(action);
if ( stored == null ) {
stored = new Integer(lastAction++);
actionTable.put(action, stored);
}
newVal = stored.intValue();
}
else {
newVal = 0;
}
if (value == newVal) {
count++;
}
else {
if (count > 0) e.emit(count,value);
count = 1;
value = newVal;
}
}
if (count > 0) e.emit(count,value);
e.emitUnpack();
println(e.toString());
}
private void emitActions() {
println(" switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {");
int i = actionTable.size()+1;
Enumeration actions = actionTable.keys();
while ( actions.hasMoreElements() ) {
Action action = (Action) actions.nextElement();
int label = ((Integer) actionTable.get(action)).intValue();
println(" case "+label+": ");
if ( scanner.debugOption ) {
print(" System.out.println(");
if ( scanner.lineCount )
print("\"line: \"+(yyline+1)+\" \"+");
if ( scanner.columnCount )
print("\"col: \"+(yycolumn+1)+\" \"+");
println("\"match: --\"+yytext()+\"--\");");
print(" System.out.println(\"action ["+action.priority+"] { ");
print(escapify(action.content));
println(" }\");");
}
println(" { "+action.content);
println(" }");
println(" case "+(i++)+": break;");
}
}
private void emitEOFVal() {
EOFActions eofActions = parser.getEOFActions();
if ( scanner.eofCode != null )
println(" zzDoEOF();");
if ( eofActions.numActions() > 0 ) {
println(" switch (zzLexicalState) {");
Enumeration stateNames = scanner.states.names();
// record lex states already emitted:
Hashtable used = new Hashtable();
// pick a start value for break case labels.
// must be larger than any value of a lex state:
int last = dfa.numStates;
while ( stateNames.hasMoreElements() ) {
String name = (String) stateNames.nextElement();
int num = scanner.states.getNumber(name).intValue();
Action action = eofActions.getAction(num);
// only emit code if the lex state is not redundant, so
// that case labels don't overlap
// (redundant = points to the same dfa state as another one).
// applies only to scanners that don't use BOL, because
// in BOL scanners lex states get mapped at runtime, so
// case labels will always be unique.
boolean unused = true;
if (!scanner.bolUsed) {
Integer key = new Integer(dfa.lexState[2*num]);
unused = used.get(key) == null;
if (!unused)
Out.warning("Lexical states <"+name+"> and <"+used.get(key)+"> are equivalent.");
else
used.put(key,name);
}
if (action != null && unused) {
println(" case "+name+":");
println(" { "+action.content+" }");
println(" case "+(++last)+": break;");
}
}
println(" default:");
}
if (eofActions.getDefault() != null)
println(" { " + eofActions.getDefault().content + " }");
else if ( scanner.eofVal != null )
println(" { " + scanner.eofVal + " }");
else if ( scanner.isInteger )
println(" return YYEOF;");
else
println(" return null;");
if (eofActions.numActions() > 0)
println(" }");
}
private void emitState(int state) {
println(" case "+state+":");
println(" switch (zzInput) {");
int defaultTransition = getDefaultTransition(state);
for (int next = 0; next < dfa.numStates; next++) {
if ( next != defaultTransition && table[state][next] != null ) {
emitTransition(state, next);
}
}
if ( defaultTransition != DFA.NO_TARGET && noTarget[state] != null ) {
emitTransition(state, DFA.NO_TARGET);
}
emitDefaultTransition(state, defaultTransition);
println(" }");
println("");
}
private void emitTransition(int state, int nextState) {
CharSetEnumerator chars;
if (nextState != DFA.NO_TARGET)
chars = table[state][nextState].characters();
else
chars = noTarget[state].characters();
print(" case ");
print((int)chars.nextElement());
print(": ");
while ( chars.hasMoreElements() ) {
println();
print(" case ");
print((int)chars.nextElement());
print(": ");
}
if ( nextState != DFA.NO_TARGET ) {
if ( dfa.isFinal[nextState] )
print("zzIsFinal = true; ");
if ( dfa.isPushback[nextState] )
print("zzPushbackPosL = zzCurrentPosL; ");
if ( dfa.isLookEnd[nextState] )
print("zzPushback = true; ");
if ( !isTransition[nextState] )
print("zzNoLookAhead = true; ");
if ( nextState == state )
println("break zzForNext;");
else
println("zzState = "+nextState+"; break zzForNext;");
}
else
println("break zzForAction;");
}
private void emitDefaultTransition(int state, int nextState) {
print(" default: ");
if ( nextState != DFA.NO_TARGET ) {
if ( dfa.isFinal[nextState] )
print("zzIsFinal = true; ");
if ( dfa.isPushback[nextState] )
print("zzPushbackPosL = zzCurrentPosL; ");
if ( dfa.isLookEnd[nextState] )
print("zzPushback = true; ");
if ( !isTransition[nextState] )
print("zzNoLookAhead = true; ");
if ( nextState == state )
println("break zzForNext;");
else
println("zzState = "+nextState+"; break zzForNext;");
}
else
println( "break zzForAction;" );
}
private void emitPushback() {
println(" if (zzWasPushback)");
println(" zzMarkedPos = zzPushbackPosL;");
}
private int getDefaultTransition(int state) {
int max = 0;
for (int i = 0; i < dfa.numStates; i++) {
if ( table[state][max] == null )
max = i;
else
if ( table[state][i] != null && table[state][max].size() < table[state][i].size() )
max = i;
}
if ( table[state][max] == null ) return DFA.NO_TARGET;
if ( noTarget[state] == null ) return max;
if ( table[state][max].size() < noTarget[state].size() )
max = DFA.NO_TARGET;
return max;
}
// for switch statement:
private void transformTransitionTable() {
int numInput = parser.getCharClasses().getNumClasses()+1;
int i;
char j;
table = new CharSet[dfa.numStates][dfa.numStates];
noTarget = new CharSet[dfa.numStates];
for (i = 0; i < dfa.numStates; i++)
for (j = 0; j < dfa.numInput; j++) {
int nextState = dfa.table[i][j];
if ( nextState == DFA.NO_TARGET ) {
if ( noTarget[i] == null )
noTarget[i] = new CharSet(numInput, colMap[j]);
else
noTarget[i].add(colMap[j]);
}
else {
if ( table[i][nextState] == null )
table[i][nextState] = new CharSet(numInput, colMap[j]);
else
table[i][nextState].add(colMap[j]);
}
}
}
private void findActionStates() {
isTransition = new boolean [dfa.numStates];
for (int i = 0; i < dfa.numStates; i++) {
char j = 0;
while ( !isTransition[i] && j < dfa.numInput )
isTransition[i] = dfa.table[i][j++] != DFA.NO_TARGET;
}
}
private void reduceColumns() {
colMap = new int [dfa.numInput];
colKilled = new boolean [dfa.numInput];
int i,j,k;
int translate = 0;
boolean equal;
numCols = dfa.numInput;
for (i = 0; i < dfa.numInput; i++) {
colMap[i] = i-translate;
for (j = 0; j < i; j++) {
// test for equality:
k = -1;
equal = true;
while (equal && ++k < dfa.numStates)
equal = dfa.table[k][i] == dfa.table[k][j];
if (equal) {
translate++;
colMap[i] = colMap[j];
colKilled[i] = true;
numCols--;
break;
} // if
} // for j
} // for i
}
private void reduceRows() {
rowMap = new int [dfa.numStates];
rowKilled = new boolean [dfa.numStates];
int i,j,k;
int translate = 0;
boolean equal;
numRows = dfa.numStates;
// i is the state to add to the new table
for (i = 0; i < dfa.numStates; i++) {
rowMap[i] = i-translate;
// check if state i can be removed (i.e. already
// exists in entries 0..i-1)
for (j = 0; j < i; j++) {
// test for equality:
k = -1;
equal = true;
while (equal && ++k < dfa.numInput)
equal = dfa.table[i][k] == dfa.table[j][k];
if (equal) {
translate++;
rowMap[i] = rowMap[j];
rowKilled[i] = true;
numRows--;
break;
} // if
} // for j
} // for i
}
/**
* Set up EOF code sectioin according to scanner.eofcode
*/
private void setupEOFCode() {
if (scanner.eofclose) {
scanner.eofCode = LexScan.conc(scanner.eofCode, " yyclose();");
scanner.eofThrow = LexScan.concExc(scanner.eofThrow, "java.io.IOException");
}
}
/**
* Main Emitter method.
*/
public void emit() {
setupEOFCode();
if (scanner.functionName == null)
scanner.functionName = "yylex";
reduceColumns();
findActionStates();
emitHeader();
emitUserCode();
emitClassName();
skel.emitNext();
println(" private static final int ZZ_BUFFERSIZE = "+scanner.bufferSize+";");
if (scanner.debugOption) {
println(" private static final String ZZ_NL = System.getProperty(\"line.separator\");");
}
skel.emitNext();
emitLexicalStates();
emitCharMapArray();
emitActionTable();
if (scanner.useRowMap) {
reduceRows();
emitRowMapArray();
if (scanner.packed)
emitDynamicInit();
else
emitZZTrans();
}
skel.emitNext();
if (scanner.useRowMap)
emitAttributes();
skel.emitNext();
emitClassCode();
skel.emitNext();
emitConstructorDecl();
emitCharMapInitFunction();
skel.emitNext();
emitScanError();
skel.emitNext();
emitDoEOF();
skel.emitNext();
emitLexFunctHeader();
emitNextInput();
if (scanner.useRowMap)
emitGetRowMapNext();
else
emitTransitionTable();
if (scanner.lookAheadUsed)
emitPushback();
skel.emitNext();
emitActions();
skel.emitNext();
emitEOFVal();
skel.emitNext();
emitNoMatch();
skel.emitNext();
emitMain();
skel.emitNext();
out.close();
}
}
| false | true | private void emitLexFunctHeader() {
if (scanner.cupCompatible) {
// force public, because we have to implement java_cup.runtime.Symbol
print(" public ");
}
else {
print(" "+visibility+" ");
}
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" ");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
skel.emitNext();
if ( scanner.useRowMap ) {
println(" int [] zzTransL = ZZ_TRANS;");
println(" int [] zzRowMapL = ZZ_ROWMAP;");
println(" int [] zzAttrL = ZZ_ATTRIBUTE;");
}
if ( scanner.lookAheadUsed ) {
println(" int zzPushbackPosL = zzPushbackPos = -1;");
println(" boolean zzWasPushback;");
}
skel.emitNext();
if ( scanner.charCount ) {
println(" yychar+= zzMarkedPosL-zzStartRead;");
println("");
}
if ( scanner.lineCount || scanner.columnCount ) {
println(" boolean zzR = false;");
println(" for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;");
println(" zzCurrentPosL++) {");
println(" switch (zzBufferL[zzCurrentPosL]) {");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = false;");
println(" break;");
println(" case '\\r':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = true;");
println(" break;");
println(" case '\\n':");
println(" if (zzR)");
println(" zzR = false;");
println(" else {");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" }");
println(" break;");
println(" default:");
println(" zzR = false;");
if ( scanner.columnCount )
println(" yycolumn++;");
println(" }");
println(" }");
println();
if ( scanner.lineCount ) {
println(" if (zzR) {");
println(" // peek one character ahead if it is \\n (if we have counted one line too much)");
println(" boolean zzPeek;");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" else if (zzAtEOF)");
println(" zzPeek = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzPeek = false;");
println(" else ");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" }");
println(" if (zzPeek) yyline--;");
println(" }");
}
}
if ( scanner.bolUsed ) {
// zzMarkedPos > zzStartRead <=> last match was not empty
// if match was empty, last value of zzAtBOL can be used
// zzStartRead is always >= 0
println(" if (zzMarkedPosL > zzStartRead) {");
println(" switch (zzBufferL[zzMarkedPosL-1]) {");
println(" case '\\n':");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
println(" zzAtBOL = true;");
println(" break;");
println(" case '\\r': ");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" else if (zzAtEOF)");
println(" zzAtBOL = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzAtBOL = false;");
println(" else ");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" }");
println(" break;");
println(" default:");
println(" zzAtBOL = false;");
println(" }");
println(" }");
}
skel.emitNext();
if (scanner.bolUsed) {
println(" if (zzAtBOL)");
println(" zzState = ZZ_LEXSTATE[zzLexicalState+1];");
println(" else");
println(" zzState = ZZ_LEXSTATE[zzLexicalState];");
println();
}
else {
println(" zzState = zzLexicalState;");
println();
}
if (scanner.lookAheadUsed)
println(" zzWasPushback = false;");
skel.emitNext();
}
| private void emitLexFunctHeader() {
if (scanner.cupCompatible) {
// force public, because we have to implement java_cup.runtime.Symbol
print(" public ");
}
else {
print(" "+visibility+" ");
}
if ( scanner.tokenType == null ) {
if ( scanner.isInteger )
print( "int" );
else
if ( scanner.isIntWrap )
print( "Integer" );
else
print( "Yytoken" );
}
else
print( scanner.tokenType );
print(" ");
print(scanner.functionName);
print("() throws java.io.IOException");
if ( scanner.lexThrow != null ) {
print(", ");
print(scanner.lexThrow);
}
if ( scanner.scanErrorException != null ) {
print(", ");
print(scanner.scanErrorException);
}
println(" {");
skel.emitNext();
if ( scanner.useRowMap ) {
println(" int [] zzTransL = ZZ_TRANS;");
println(" int [] zzRowMapL = ZZ_ROWMAP;");
println(" int [] zzAttrL = ZZ_ATTRIBUTE;");
}
if ( scanner.lookAheadUsed ) {
println(" int zzPushbackPosL = zzPushbackPos = -1;");
println(" boolean zzWasPushback;");
}
skel.emitNext();
if ( scanner.charCount ) {
println(" yychar+= zzMarkedPosL-zzStartRead;");
println("");
}
if ( scanner.lineCount || scanner.columnCount ) {
println(" boolean zzR = false;");
println(" for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;");
println(" zzCurrentPosL++) {");
println(" switch (zzBufferL[zzCurrentPosL]) {");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = false;");
println(" break;");
println(" case '\\r':");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" zzR = true;");
println(" break;");
println(" case '\\n':");
println(" if (zzR)");
println(" zzR = false;");
println(" else {");
if ( scanner.lineCount )
println(" yyline++;");
if ( scanner.columnCount )
println(" yycolumn = 0;");
println(" }");
println(" break;");
println(" default:");
println(" zzR = false;");
if ( scanner.columnCount )
println(" yycolumn++;");
println(" }");
println(" }");
println();
if ( scanner.lineCount ) {
println(" if (zzR) {");
println(" // peek one character ahead if it is \\n (if we have counted one line too much)");
println(" boolean zzPeek;");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" else if (zzAtEOF)");
println(" zzPeek = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzEndReadL = zzEndRead;");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzPeek = false;");
println(" else ");
println(" zzPeek = zzBufferL[zzMarkedPosL] == '\\n';");
println(" }");
println(" if (zzPeek) yyline--;");
println(" }");
}
}
if ( scanner.bolUsed ) {
// zzMarkedPos > zzStartRead <=> last match was not empty
// if match was empty, last value of zzAtBOL can be used
// zzStartRead is always >= 0
println(" if (zzMarkedPosL > zzStartRead) {");
println(" switch (zzBufferL[zzMarkedPosL-1]) {");
println(" case '\\n':");
println(" case '\\u000B':");
println(" case '\\u000C':");
println(" case '\\u0085':");
println(" case '\\u2028':");
println(" case '\\u2029':");
println(" zzAtBOL = true;");
println(" break;");
println(" case '\\r': ");
println(" if (zzMarkedPosL < zzEndReadL)");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" else if (zzAtEOF)");
println(" zzAtBOL = false;");
println(" else {");
println(" boolean eof = zzRefill();");
println(" zzMarkedPosL = zzMarkedPos;");
println(" zzEndReadL = zzEndRead;");
println(" zzBufferL = zzBuffer;");
println(" if (eof) ");
println(" zzAtBOL = false;");
println(" else ");
println(" zzAtBOL = zzBufferL[zzMarkedPosL] != '\\n';");
println(" }");
println(" break;");
println(" default:");
println(" zzAtBOL = false;");
println(" }");
println(" }");
}
skel.emitNext();
if (scanner.bolUsed) {
println(" if (zzAtBOL)");
println(" zzState = ZZ_LEXSTATE[zzLexicalState+1];");
println(" else");
println(" zzState = ZZ_LEXSTATE[zzLexicalState];");
println();
}
else {
println(" zzState = zzLexicalState;");
println();
}
if (scanner.lookAheadUsed)
println(" zzWasPushback = false;");
skel.emitNext();
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java
index 0337aac12..c8be361ee 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java
@@ -1,361 +1,361 @@
package org.tmatesoft.svn.core.internal.wc2.ng;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.util.SVNDate;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.util.SVNSkel;
import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNEventFactory;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager;
import org.tmatesoft.svn.core.internal.wc17.SVNCommitMediator17;
import org.tmatesoft.svn.core.internal.wc17.SVNCommitter17;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext;
import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbKind;
import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbStatus;
import org.tmatesoft.svn.core.internal.wc17.db.Structure;
import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.NodeInfo;
import org.tmatesoft.svn.core.internal.wc2.ISvnCommitRunner;
import org.tmatesoft.svn.core.internal.wc2.ng.SvnNgCommitUtil.ISvnUrlKindCallback;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc2.SvnChecksum;
import org.tmatesoft.svn.core.wc2.SvnCommit;
import org.tmatesoft.svn.core.wc2.SvnCommitItem;
import org.tmatesoft.svn.core.wc2.SvnCommitPacket;
import org.tmatesoft.svn.core.wc2.SvnTarget;
import org.tmatesoft.svn.util.SVNLogType;
public class SvnNgCommit extends SvnNgOperationRunner<SVNCommitInfo, SvnCommit> implements ISvnCommitRunner, ISvnUrlKindCallback {
public SvnCommitPacket collectCommitItems(SvnCommit operation) throws SVNException {
setOperation(operation);
SvnCommitPacket packet = new SvnCommitPacket();
Collection<String> targets = new ArrayList<String>();
String[] validatedPaths = new String[getOperation().getTargets().size()];
int i = 0;
for(SvnTarget target : getOperation().getTargets()) {
validatedPaths[i] = target.getFile().getAbsolutePath();
validatedPaths[i] = validatedPaths[i].replace(File.separatorChar, '/');
i++;
}
String rootPath = SVNPathUtil.condencePaths(validatedPaths, targets, false);
if (rootPath == null) {
return packet;
}
File baseDir = new File(rootPath).getAbsoluteFile();
if (targets.isEmpty()) {
targets.add("");
}
Collection<File> lockTargets = determineLockTargets(baseDir, targets);
Collection<File> lockedRoots = new HashSet<File>();
try {
for (File lockTarget : lockTargets) {
File lockRoot = getWcContext().acquireWriteLock(lockTarget, false, true);
lockedRoots.add(lockRoot);
}
packet.setLockingContext(this, lockedRoots);
Map<SVNURL, String> lockTokens = new HashMap<SVNURL, String>();
SvnNgCommitUtil.harversCommittables(getWcContext(), packet, lockTokens,
baseDir, targets, getOperation().getDepth(),
!getOperation().isKeepLocks(), getOperation().getApplicableChangelists(),
this, getOperation().getCommitParameters(), null);
packet.setLockTokens(lockTokens);
if (packet.getRepositoryRoots().size() > 1) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Commit can only commit to a single repository at a time.\n" +
"Are all targets part of the same working copy?");
SVNErrorManager.error(err, SVNLogType.WC);
}
if (!packet.isEmpty()) {
return packet;
} else {
packet.dispose();
return new SvnCommitPacket();
}
} catch (SVNException e) {
packet.dispose();
throw e;
}
}
@Override
protected SVNCommitInfo run(SVNWCContext context) throws SVNException {
SVNCommitInfo info = doRun(context);
if (info != null) {
getOperation().receive(getOperation().getFirstTarget(), info);
}
return info;
}
protected SVNCommitInfo doRun(SVNWCContext context) throws SVNException {
SvnCommitPacket packet = getOperation().collectCommitItems();
if (packet == null || packet.isEmpty()) {
return null;
}
SVNProperties revisionProperties = getOperation().getRevisionProperties();
SVNPropertiesManager.validateRevisionProperties(revisionProperties);
String commitMessage = getOperation().getCommitMessage();
- if (getOperation().getCommitMessage() != null) {
+ if (getOperation().getCommitHandler() != null) {
Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>();
for (SVNURL rootUrl : packet.getRepositoryRoots()) {
items.addAll(packet.getItems(rootUrl));
}
commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage,
items.toArray(new SvnCommitItem[items.size()]));
}
boolean keepLocks = getOperation().isKeepLocks();
SVNException bumpError = null;
SVNCommitInfo info = null;
try {
SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next();
if (packet.isEmpty(repositoryRootUrl)) {
return SVNCommitInfo.NULL;
}
Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>();
Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>();
Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>();
SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables);
Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL);
SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next();
SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath());
SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables);
ISVNEditor commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator);
try {
SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums);
SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1);
committer.sendTextDeltas(commitEditor);
info = commitEditor.closeEdit();
commitEditor = null;
if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) {
// do some post processing, make sure not to unlock wc (to dipose packet) in case there
// is an error on post processing.
SvnCommittedQueue queue = new SvnCommittedQueue();
try {
for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) {
postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath()));
}
processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor());
deleteDeleteFiles(committer, getOperation().getCommitParameters());
} catch (SVNException e) {
// this is bump error.
bumpError = e;
throw e;
} finally {
sleepForTimestamp();
}
}
handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED,
SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1));
} catch (SVNException e) {
if (e instanceof SVNCancelException) {
throw e;
}
SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):");
info = new SVNCommitInfo(-1, null, null, err);
handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN);
if (packet.getRepositoryRoots().size() == 1) {
SVNErrorManager.error(err, SVNLogType.WC);
}
} finally {
if (commitEditor != null) {
commitEditor.abortEdit();
}
for (File tmpFile : mediator.getTmpFiles()) {
SVNFileUtil.deleteFile(tmpFile);
}
}
} finally {
if (bumpError == null) {
packet.dispose();
}
}
return info;
}
private void postProcessCommitItem(SvnCommittedQueue queue, SvnCommitItem item, boolean keepChangelists, boolean keepLocks, SvnChecksum sha1Checksum) {
boolean removeLock = !keepLocks && item.hasFlag(SvnCommitItem.LOCK);
queueCommitted(queue, item.getPath(), false, null /*item.getIncomingProperties()*/, removeLock, !keepChangelists, sha1Checksum);
}
public SVNNodeKind getUrlKind(SVNURL url, long revision) throws SVNException {
return getRepositoryAccess().createRepository(url, null).checkPath("", revision);
}
private Collection<File> determineLockTargets(File baseDirectory, Collection<String> targets) throws SVNException {
Map<File, Collection<File>> wcItems = new HashMap<File, Collection<File>>();
for (String t: targets) {
File target = SVNFileUtil.createFilePath(baseDirectory, t);
File wcRoot = null;
try {
wcRoot = getWcContext().getDb().getWCRoot(target);
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_PATH_NOT_FOUND) {
continue;
}
throw e;
}
Collection<File> wcTargets = wcItems.get(wcRoot);
if (wcTargets == null) {
wcTargets = new HashSet<File>();
wcItems.put(wcRoot, wcTargets);
}
wcTargets.add(target);
}
Collection<File> lockTargets = new HashSet<File>();
for (File wcRoot : wcItems.keySet()) {
Collection<File> wcTargets = wcItems.get(wcRoot);
if (wcTargets.size() == 1) {
if (wcRoot.equals(wcTargets.iterator().next())) {
lockTargets.add(wcRoot);
} else {
lockTargets.add(SVNFileUtil.getParentFile(wcTargets.iterator().next()));
}
} else if (wcTargets.size() > 1) {
lockTargets.add(wcRoot);
}
}
return lockTargets;
}
public void disposeCommitPacket(Object lockingContext) throws SVNException {
if (!(lockingContext instanceof Collection)) {
return;
}
@SuppressWarnings("unchecked")
Collection<File> lockedPaths = (Collection<File>) lockingContext;
for (File lockedPath : lockedPaths) {
try {
getWcContext().releaseWriteLock(lockedPath);
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_LOCKED) {
throw e;
}
}
}
getWcContext().close();
}
private void queueCommitted(SvnCommittedQueue queue, File localAbsPath, boolean recurse, SVNProperties wcPropChanges, boolean removeLock, boolean removeChangelist,
SvnChecksum sha1Checksum) {
SvnCommittedQueueItem cqi = new SvnCommittedQueueItem();
cqi.localAbspath = localAbsPath;
cqi.recurse = recurse;
cqi.noUnlock = !removeLock;
cqi.keepChangelist = !removeChangelist;
cqi.sha1Checksum = sha1Checksum;
cqi.newDavCache = wcPropChanges;
queue.queue.put(localAbsPath, cqi);
}
private void processCommittedQueue(SvnCommittedQueue queue, long newRevision, Date revDate, String revAuthor) throws SVNException {
Collection<File> roots = new HashSet<File>();
for (SvnCommittedQueueItem cqi : queue.queue.values()) {
processCommittedInternal(cqi.localAbspath, cqi.recurse, true, newRevision, new SVNDate(revDate.getTime(), 0), revAuthor, cqi.newDavCache, cqi.noUnlock, cqi.keepChangelist, cqi.sha1Checksum, queue);
File root = getWcContext().getDb().getWCRoot(cqi.localAbspath);
roots.add(root);
}
for (File root : roots) {
getWcContext().wqRun(root);
}
queue.queue.clear();
}
private void processCommittedInternal(File localAbspath, boolean recurse, boolean topOfRecurse, long newRevision, SVNDate revDate, String revAuthor, SVNProperties newDavCache, boolean noUnlock,
boolean keepChangelist, SvnChecksum sha1Checksum, SvnCommittedQueue queue) throws SVNException {
processCommittedLeaf(localAbspath, !topOfRecurse, newRevision, revDate, revAuthor, newDavCache, noUnlock, keepChangelist, sha1Checksum);
}
private void processCommittedLeaf(File localAbspath, boolean viaRecurse, long newRevnum, SVNDate newChangedDate, String newChangedAuthor, SVNProperties newDavCache, boolean noUnlock,
boolean keepChangelist, SvnChecksum checksum) throws SVNException {
long newChangedRev = newRevnum;
assert (SVNFileUtil.isAbsolute(localAbspath));
Structure<NodeInfo> nodeInfo = getWcContext().getDb().readInfo(localAbspath,
NodeInfo.status, NodeInfo.kind, NodeInfo.checksum, NodeInfo.hadProps, NodeInfo.propsMod, NodeInfo.haveBase, NodeInfo.haveWork);
File admAbspath;
if (nodeInfo.get(NodeInfo.kind) == SVNWCDbKind.Dir) {
admAbspath = localAbspath;
} else {
admAbspath = SVNFileUtil.getFileDir(localAbspath);
}
getWcContext().writeCheck(admAbspath);
if (nodeInfo.get(NodeInfo.status) == SVNWCDbStatus.Deleted) {
getWcContext().getDb().opRemoveNode(localAbspath,
nodeInfo.is(NodeInfo.haveBase) && !viaRecurse ? newRevnum : -1,
nodeInfo.<SVNWCDbKind>get(NodeInfo.kind));
nodeInfo.release();
return;
} else if (nodeInfo.get(NodeInfo.status) == SVNWCDbStatus.NotPresent) {
nodeInfo.release();
return;
}
SVNSkel workItem = null;
SVNWCDbKind kind = nodeInfo.get(NodeInfo.kind);
if (kind != SVNWCDbKind.Dir) {
if (checksum == null) {
checksum = nodeInfo.get(NodeInfo.checksum);
if (viaRecurse && !nodeInfo.is(NodeInfo.propsMod)) {
Structure<NodeInfo> moreInfo = getWcContext().getDb().
readInfo(localAbspath, NodeInfo.changedRev, NodeInfo.changedDate, NodeInfo.changedAuthor);
newChangedRev = moreInfo.lng(NodeInfo.changedRev);
newChangedDate = moreInfo.get(NodeInfo.changedDate);
newChangedAuthor = moreInfo.get(NodeInfo.changedAuthor);
moreInfo.release();
}
}
workItem = getWcContext().wqBuildFileCommit(localAbspath, nodeInfo.is(NodeInfo.propsMod));
}
getWcContext().getDb().globalCommit(localAbspath, newRevnum, newChangedRev, newChangedDate, newChangedAuthor, checksum, null, newDavCache, keepChangelist, noUnlock, workItem);
}
private static class SvnCommittedQueue {
@SuppressWarnings("unchecked")
public Map<File, SvnCommittedQueueItem> queue = new TreeMap<File, SvnCommittedQueueItem>(SVNCommitUtil.FILE_COMPARATOR);
};
private static class SvnCommittedQueueItem {
public File localAbspath;
public boolean recurse;
public boolean noUnlock;
public boolean keepChangelist;
public SvnChecksum sha1Checksum;
public SVNProperties newDavCache;
};
}
| true | true | protected SVNCommitInfo doRun(SVNWCContext context) throws SVNException {
SvnCommitPacket packet = getOperation().collectCommitItems();
if (packet == null || packet.isEmpty()) {
return null;
}
SVNProperties revisionProperties = getOperation().getRevisionProperties();
SVNPropertiesManager.validateRevisionProperties(revisionProperties);
String commitMessage = getOperation().getCommitMessage();
if (getOperation().getCommitMessage() != null) {
Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>();
for (SVNURL rootUrl : packet.getRepositoryRoots()) {
items.addAll(packet.getItems(rootUrl));
}
commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage,
items.toArray(new SvnCommitItem[items.size()]));
}
boolean keepLocks = getOperation().isKeepLocks();
SVNException bumpError = null;
SVNCommitInfo info = null;
try {
SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next();
if (packet.isEmpty(repositoryRootUrl)) {
return SVNCommitInfo.NULL;
}
Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>();
Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>();
Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>();
SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables);
Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL);
SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next();
SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath());
SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables);
ISVNEditor commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator);
try {
SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums);
SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1);
committer.sendTextDeltas(commitEditor);
info = commitEditor.closeEdit();
commitEditor = null;
if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) {
// do some post processing, make sure not to unlock wc (to dipose packet) in case there
// is an error on post processing.
SvnCommittedQueue queue = new SvnCommittedQueue();
try {
for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) {
postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath()));
}
processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor());
deleteDeleteFiles(committer, getOperation().getCommitParameters());
} catch (SVNException e) {
// this is bump error.
bumpError = e;
throw e;
} finally {
sleepForTimestamp();
}
}
handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED,
SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1));
} catch (SVNException e) {
if (e instanceof SVNCancelException) {
throw e;
}
SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):");
info = new SVNCommitInfo(-1, null, null, err);
handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN);
if (packet.getRepositoryRoots().size() == 1) {
SVNErrorManager.error(err, SVNLogType.WC);
}
} finally {
if (commitEditor != null) {
commitEditor.abortEdit();
}
for (File tmpFile : mediator.getTmpFiles()) {
SVNFileUtil.deleteFile(tmpFile);
}
}
} finally {
if (bumpError == null) {
packet.dispose();
}
}
return info;
}
| protected SVNCommitInfo doRun(SVNWCContext context) throws SVNException {
SvnCommitPacket packet = getOperation().collectCommitItems();
if (packet == null || packet.isEmpty()) {
return null;
}
SVNProperties revisionProperties = getOperation().getRevisionProperties();
SVNPropertiesManager.validateRevisionProperties(revisionProperties);
String commitMessage = getOperation().getCommitMessage();
if (getOperation().getCommitHandler() != null) {
Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>();
for (SVNURL rootUrl : packet.getRepositoryRoots()) {
items.addAll(packet.getItems(rootUrl));
}
commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage,
items.toArray(new SvnCommitItem[items.size()]));
}
boolean keepLocks = getOperation().isKeepLocks();
SVNException bumpError = null;
SVNCommitInfo info = null;
try {
SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next();
if (packet.isEmpty(repositoryRootUrl)) {
return SVNCommitInfo.NULL;
}
Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>();
Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>();
Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>();
SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables);
Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL);
SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next();
SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath());
SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables);
ISVNEditor commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator);
try {
SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums);
SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1);
committer.sendTextDeltas(commitEditor);
info = commitEditor.closeEdit();
commitEditor = null;
if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) {
// do some post processing, make sure not to unlock wc (to dipose packet) in case there
// is an error on post processing.
SvnCommittedQueue queue = new SvnCommittedQueue();
try {
for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) {
postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath()));
}
processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor());
deleteDeleteFiles(committer, getOperation().getCommitParameters());
} catch (SVNException e) {
// this is bump error.
bumpError = e;
throw e;
} finally {
sleepForTimestamp();
}
}
handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED,
SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1));
} catch (SVNException e) {
if (e instanceof SVNCancelException) {
throw e;
}
SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):");
info = new SVNCommitInfo(-1, null, null, err);
handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN);
if (packet.getRepositoryRoots().size() == 1) {
SVNErrorManager.error(err, SVNLogType.WC);
}
} finally {
if (commitEditor != null) {
commitEditor.abortEdit();
}
for (File tmpFile : mediator.getTmpFiles()) {
SVNFileUtil.deleteFile(tmpFile);
}
}
} finally {
if (bumpError == null) {
packet.dispose();
}
}
return info;
}
|
diff --git a/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java b/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java
index 0fbcf85..b9e3abc 100644
--- a/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java
+++ b/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java
@@ -1,592 +1,585 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony.cdma;
import com.android.internal.telephony.TelephonyProperties;
import com.android.internal.telephony.MccTable;
import com.android.internal.telephony.EventLogTags;
import com.android.internal.telephony.uicc.RuimRecords;
import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState;
import android.telephony.CellInfo;
import android.telephony.CellInfoLte;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellIdentityLte;
import android.telephony.SignalStrength;
import android.telephony.ServiceState;
import android.telephony.cdma.CdmaCellLocation;
import android.text.TextUtils;
import android.os.AsyncResult;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.telephony.Rlog;
import android.util.EventLog;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class CdmaLteServiceStateTracker extends CdmaServiceStateTracker {
private CDMALTEPhone mCdmaLtePhone;
private final CellInfoLte mCellInfoLte;
private CellIdentityLte mNewCellIdentityLte = new CellIdentityLte();
private CellIdentityLte mLasteCellIdentityLte = new CellIdentityLte();
public CdmaLteServiceStateTracker(CDMALTEPhone phone) {
super(phone, new CellInfoLte());
mCdmaLtePhone = phone;
mCellInfoLte = (CellInfoLte) mCellInfo;
((CellInfoLte)mCellInfo).setCellSignalStrength(new CellSignalStrengthLte());
((CellInfoLte)mCellInfo).setCellIdentity(new CellIdentityLte());
if (DBG) log("CdmaLteServiceStateTracker Constructors");
}
@Override
public void handleMessage(Message msg) {
AsyncResult ar;
int[] ints;
String[] strings;
if (!mPhone.mIsTheCurrentActivePhone) {
loge("Received message " + msg + "[" + msg.what + "]" +
" while being destroyed. Ignoring.");
return;
}
switch (msg.what) {
case EVENT_POLL_STATE_GPRS:
if (DBG) log("handleMessage EVENT_POLL_STATE_GPRS");
ar = (AsyncResult)msg.obj;
handlePollStateResult(msg.what, ar);
break;
case EVENT_RUIM_RECORDS_LOADED:
RuimRecords ruim = (RuimRecords)mIccRecords;
if ((ruim != null) && ruim.isProvisioned()) {
mMdn = ruim.getMdn();
mMin = ruim.getMin();
parseSidNid(ruim.getSid(), ruim.getNid());
mPrlVersion = ruim.getPrlVersion();
mIsMinInfoReady = true;
updateOtaspState();
}
// SID/NID/PRL is loaded. Poll service state
// again to update to the roaming state with
// the latest variables.
pollState();
break;
default:
super.handleMessage(msg);
}
}
/**
* Handle the result of one of the pollState()-related requests
*/
@Override
protected void handlePollStateResultMessage(int what, AsyncResult ar) {
if (what == EVENT_POLL_STATE_GPRS) {
String states[] = (String[])ar.result;
if (DBG) {
log("handlePollStateResultMessage: EVENT_POLL_STATE_GPRS states.length=" +
states.length + " states=" + states);
}
int type = 0;
int regState = -1;
if (states.length > 0) {
try {
regState = Integer.parseInt(states[0]);
// states[3] (if present) is the current radio technology
if (states.length >= 4 && states[3] != null) {
type = Integer.parseInt(states[3]);
}
} catch (NumberFormatException ex) {
loge("handlePollStateResultMessage: error parsing GprsRegistrationState: "
+ ex);
}
if (states.length >= 10) {
int mcc;
int mnc;
int tac;
int pci;
int eci;
int csgid;
String operatorNumeric = null;
try {
operatorNumeric = mNewSS.getOperatorNumeric();
mcc = Integer.parseInt(operatorNumeric.substring(0,3));
} catch (Exception e) {
try {
operatorNumeric = mSS.getOperatorNumeric();
mcc = Integer.parseInt(operatorNumeric.substring(0,3));
} catch (Exception ex) {
loge("handlePollStateResultMessage: bad mcc operatorNumeric=" +
operatorNumeric + " ex=" + ex);
operatorNumeric = "";
mcc = Integer.MAX_VALUE;
}
}
try {
mnc = Integer.parseInt(operatorNumeric.substring(3));
} catch (Exception e) {
loge("handlePollStateResultMessage: bad mnc operatorNumeric=" +
operatorNumeric + " e=" + e);
mnc = Integer.MAX_VALUE;
}
// Use Integer#decode to be generous in what we receive and allow
// decimal, hex or octal values.
try {
tac = Integer.decode(states[6]);
} catch (Exception e) {
loge("handlePollStateResultMessage: bad tac states[6]=" +
states[6] + " e=" + e);
tac = Integer.MAX_VALUE;
}
try {
pci = Integer.decode(states[7]);
} catch (Exception e) {
loge("handlePollStateResultMessage: bad pci states[7]=" +
states[7] + " e=" + e);
pci = Integer.MAX_VALUE;
}
try {
eci = Integer.decode(states[8]);
} catch (Exception e) {
loge("handlePollStateResultMessage: bad eci states[8]=" +
states[8] + " e=" + e);
eci = Integer.MAX_VALUE;
}
try {
csgid = Integer.decode(states[9]);
} catch (Exception e) {
// FIX: Always bad so don't pollute the logs
// loge("handlePollStateResultMessage: bad csgid states[9]=" +
// states[9] + " e=" + e);
csgid = Integer.MAX_VALUE;
}
mNewCellIdentityLte = new CellIdentityLte(mcc, mnc, eci, pci, tac);
if (DBG) {
log("handlePollStateResultMessage: mNewLteCellIdentity=" +
mNewCellIdentityLte);
}
}
}
mNewSS.setRilDataRadioTechnology(type);
int dataRegState = regCodeToServiceState(regState);
mNewSS.setDataRegState(dataRegState);
if (DBG) {
log("handlPollStateResultMessage: CdmaLteSST setDataRegState=" + dataRegState
+ " regState=" + regState
+ " dataRadioTechnology=" + type);
}
mDataRoaming = regCodeIsRoaming(regState);
if (mDataRoaming) mNewSS.setRoaming(true);
} else {
super.handlePollStateResultMessage(what, ar);
}
}
@Override
protected void pollState() {
mPollingContext = new int[1];
mPollingContext[0] = 0;
switch (mCi.getRadioState()) {
case RADIO_UNAVAILABLE:
mNewSS.setStateOutOfService();
mNewCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
pollStateDone();
break;
case RADIO_OFF:
mNewSS.setStateOff();
mNewCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
pollStateDone();
break;
default:
// Issue all poll-related commands at once, then count
// down the responses which are allowed to arrive
// out-of-order.
mPollingContext[0]++;
// RIL_REQUEST_OPERATOR is necessary for CDMA
mCi.getOperator(obtainMessage(EVENT_POLL_STATE_OPERATOR_CDMA, mPollingContext));
mPollingContext[0]++;
// RIL_REQUEST_VOICE_REGISTRATION_STATE is necessary for CDMA
mCi.getVoiceRegistrationState(obtainMessage(EVENT_POLL_STATE_REGISTRATION_CDMA,
mPollingContext));
mPollingContext[0]++;
// RIL_REQUEST_DATA_REGISTRATION_STATE
mCi.getDataRegistrationState(obtainMessage(EVENT_POLL_STATE_GPRS,
mPollingContext));
break;
}
}
@Override
protected void pollStateDone() {
log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]");
useDataRegStateForDataOnlyDevices();
boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionAttached =
mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionDetached =
mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionChanged =
mSS.getDataRegState() != mNewSS.getDataRegState();
boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology()
!= mNewSS.getRilVoiceRadioTechnology();
boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology()
!= mNewSS.getRilDataRadioTechnology();
boolean hasChanged = !mNewSS.equals(mSS);
boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming();
boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming();
boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc);
boolean has4gHandoff =
mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE &&
(((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) ||
((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE)));
boolean hasMultiApnSupport =
(((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) ||
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) &&
((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)));
boolean hasLostMultiApnSupport =
((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) &&
(mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A));
if (DBG) {
log("pollStateDone:"
+ " hasRegistered=" + hasRegistered
+ " hasDeegistered=" + hasDeregistered
+ " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached
+ " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached
+ " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged
+ " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged
+ " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged
+ " hasChanged=" + hasChanged
+ " hasRoamingOn=" + hasRoamingOn
+ " hasRoamingOff=" + hasRoamingOff
+ " hasLocationChanged=" + hasLocationChanged
+ " has4gHandoff = " + has4gHandoff
+ " hasMultiApnSupport=" + hasMultiApnSupport
+ " hasLostMultiApnSupport=" + hasLostMultiApnSupport);
}
// Add an event log when connection state changes
if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState()
|| mSS.getDataRegState() != mNewSS.getDataRegState()) {
EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(),
mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState());
}
ServiceState tss;
tss = mSS;
mSS = mNewSS;
mNewSS = tss;
// clean slate for next time
mNewSS.setStateOutOfService();
CdmaCellLocation tcl = mCellLoc;
mCellLoc = mNewCellLoc;
mNewCellLoc = tcl;
mNewSS.setStateOutOfService(); // clean slate for next time
if (hasDataRadioTechnologyChanged) {
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology()));
// Query Signalstrength when there is a change in PS RAT.
sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
}
if (hasChanged) {
- if (mPhone.isEriFileLoaded()) {
+ if ((mCi.getRadioState().isOn()) && (mPhone.isEriFileLoaded())) {
String eriText;
// Now the CDMAPhone sees the new ServiceState so it can get the
// new ERI text
if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE ||
(mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE)) {
eriText = mPhone.getCdmaEriText();
- } else if (mSS.getVoiceRegState() == ServiceState.STATE_POWER_OFF) {
- eriText = (mIccRecords != null) ? mIccRecords.getServiceProviderName() : null;
- if (TextUtils.isEmpty(eriText)) {
- // Sets operator alpha property by retrieving from
- // build-time system property
- eriText = SystemProperties.get("ro.cdma.home.operator.alpha");
- }
} else {
// Note that ServiceState.STATE_OUT_OF_SERVICE is valid used
// for mRegistrationState 0,2,3 and 4
eriText = mPhone.getContext()
.getText(com.android.internal.R.string.roamingTextSearching).toString();
}
mSS.setOperatorAlphaLong(eriText);
}
if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY &&
mIccRecords != null) {
// SIM is found on the device. If ERI roaming is OFF, and SID/NID matches
// one configured in SIM, use operator name from CSIM record.
boolean showSpn =
((RuimRecords)mIccRecords).getCsimSpnDisplayCondition();
int iconIndex = mSS.getCdmaEriIconIndex();
if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) &&
isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) &&
mIccRecords != null) {
mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName());
}
}
String operatorNumeric;
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
mSS.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = mSS.getOperatorNumeric();
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
} else {
String isoCountryCode = "";
String mcc = operatorNumeric.substring(0, 3);
try {
isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric
.substring(0, 3)));
} catch (NumberFormatException ex) {
loge("countryCodeForMcc error" + ex);
} catch (StringIndexOutOfBoundsException ex) {
loge("countryCodeForMcc error" + ex);
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY,
isoCountryCode);
mGotCountryCode = true;
if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric,
mNeedFixZone)) {
fixTimeZone(isoCountryCode);
}
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
mSS.getRoaming() ? "true" : "false");
updateSpnDisplay();
mPhone.notifyServiceStateChanged(mSS);
}
if (hasCdmaDataConnectionAttached || has4gHandoff) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasCdmaDataConnectionDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) {
log("pollStateDone: call notifyDataConnection");
mPhone.notifyDataConnection(null);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
mPhone.notifyLocationChanged();
}
ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>();
synchronized(mCellInfo) {
CellInfoLte cil = (CellInfoLte)mCellInfo;
boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte);
if (hasRegistered || hasDeregistered || cidChanged) {
// TODO: Handle the absence of LteCellIdentity
long timeStamp = SystemClock.elapsedRealtime() * 1000;
boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
mLasteCellIdentityLte = mNewCellIdentityLte;
cil.setRegisterd(registered);
cil.setCellIdentity(mLasteCellIdentityLte);
if (DBG) {
log("pollStateDone: hasRegistered=" + hasRegistered +
" hasDeregistered=" + hasDeregistered +
" cidChanged=" + cidChanged +
" mCellInfo=" + mCellInfo);
}
arrayCi.add(mCellInfo);
}
mPhoneBase.notifyCellInfo(arrayCi);
}
}
@Override
protected boolean onSignalStrengthResult(AsyncResult ar, boolean isGsm) {
if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) {
isGsm = true;
}
boolean ssChanged = super.onSignalStrengthResult(ar, isGsm);
synchronized (mCellInfo) {
if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) {
mCellInfoLte.setTimeStamp(SystemClock.elapsedRealtime() * 1000);
mCellInfoLte.setTimeStampType(CellInfo.TIMESTAMP_TYPE_JAVA_RIL);
mCellInfoLte.getCellSignalStrength()
.initialize(mSignalStrength,SignalStrength.INVALID);
}
if (mCellInfoLte.getCellIdentity() != null) {
ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>();
arrayCi.add(mCellInfoLte);
mPhoneBase.notifyCellInfo(arrayCi);
}
}
return ssChanged;
}
@Override
public boolean isConcurrentVoiceAndDataAllowed() {
// For non-LTE, look at the CSS indicator to check on Concurrent V & D capability
if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) {
return true;
} else {
return mSS.getCssIndicator() == 1;
}
}
/**
* Check whether the specified SID and NID pair appears in the HOME SID/NID list
* read from NV or SIM.
*
* @return true if provided sid/nid pair belongs to operator's home network.
*/
private boolean isInHomeSidNid(int sid, int nid) {
// if SID/NID is not available, assume this is home network.
if (isSidsAllZeros()) return true;
// length of SID/NID shold be same
if (mHomeSystemId.length != mHomeNetworkId.length) return true;
if (sid == 0) return true;
for (int i = 0; i < mHomeSystemId.length; i++) {
// Use SID only if NID is a reserved value.
// SID 0 and NID 0 and 65535 are reserved. (C.0005 2.6.5.2)
if ((mHomeSystemId[i] == sid) &&
((mHomeNetworkId[i] == 0) || (mHomeNetworkId[i] == 65535) ||
(nid == 0) || (nid == 65535) || (mHomeNetworkId[i] == nid))) {
return true;
}
}
// SID/NID are not in the list. So device is not in home network
return false;
}
/**
* TODO: Remove when we get new ril/modem for Galaxy Nexus.
*
* @return all available cell information, the returned List maybe empty but never null.
*/
@Override
public List<CellInfo> getAllCellInfo() {
if (mCi.getRilVersion() >= 8) {
return super.getAllCellInfo();
} else {
ArrayList<CellInfo> arrayList = new ArrayList<CellInfo>();
CellInfo ci;
synchronized(mCellInfo) {
arrayList.add(mCellInfoLte);
}
if (DBG) log ("getAllCellInfo: arrayList=" + arrayList);
return arrayList;
}
}
@Override
protected void log(String s) {
Rlog.d(LOG_TAG, "[CdmaLteSST] " + s);
}
@Override
protected void loge(String s) {
Rlog.e(LOG_TAG, "[CdmaLteSST] " + s);
}
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("CdmaLteServiceStateTracker extends:");
super.dump(fd, pw, args);
pw.println(" mCdmaLtePhone=" + mCdmaLtePhone);
}
}
| false | true | protected void pollStateDone() {
log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]");
useDataRegStateForDataOnlyDevices();
boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionAttached =
mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionDetached =
mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionChanged =
mSS.getDataRegState() != mNewSS.getDataRegState();
boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology()
!= mNewSS.getRilVoiceRadioTechnology();
boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology()
!= mNewSS.getRilDataRadioTechnology();
boolean hasChanged = !mNewSS.equals(mSS);
boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming();
boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming();
boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc);
boolean has4gHandoff =
mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE &&
(((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) ||
((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE)));
boolean hasMultiApnSupport =
(((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) ||
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) &&
((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)));
boolean hasLostMultiApnSupport =
((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) &&
(mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A));
if (DBG) {
log("pollStateDone:"
+ " hasRegistered=" + hasRegistered
+ " hasDeegistered=" + hasDeregistered
+ " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached
+ " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached
+ " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged
+ " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged
+ " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged
+ " hasChanged=" + hasChanged
+ " hasRoamingOn=" + hasRoamingOn
+ " hasRoamingOff=" + hasRoamingOff
+ " hasLocationChanged=" + hasLocationChanged
+ " has4gHandoff = " + has4gHandoff
+ " hasMultiApnSupport=" + hasMultiApnSupport
+ " hasLostMultiApnSupport=" + hasLostMultiApnSupport);
}
// Add an event log when connection state changes
if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState()
|| mSS.getDataRegState() != mNewSS.getDataRegState()) {
EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(),
mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState());
}
ServiceState tss;
tss = mSS;
mSS = mNewSS;
mNewSS = tss;
// clean slate for next time
mNewSS.setStateOutOfService();
CdmaCellLocation tcl = mCellLoc;
mCellLoc = mNewCellLoc;
mNewCellLoc = tcl;
mNewSS.setStateOutOfService(); // clean slate for next time
if (hasDataRadioTechnologyChanged) {
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology()));
// Query Signalstrength when there is a change in PS RAT.
sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
}
if (hasChanged) {
if (mPhone.isEriFileLoaded()) {
String eriText;
// Now the CDMAPhone sees the new ServiceState so it can get the
// new ERI text
if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE ||
(mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE)) {
eriText = mPhone.getCdmaEriText();
} else if (mSS.getVoiceRegState() == ServiceState.STATE_POWER_OFF) {
eriText = (mIccRecords != null) ? mIccRecords.getServiceProviderName() : null;
if (TextUtils.isEmpty(eriText)) {
// Sets operator alpha property by retrieving from
// build-time system property
eriText = SystemProperties.get("ro.cdma.home.operator.alpha");
}
} else {
// Note that ServiceState.STATE_OUT_OF_SERVICE is valid used
// for mRegistrationState 0,2,3 and 4
eriText = mPhone.getContext()
.getText(com.android.internal.R.string.roamingTextSearching).toString();
}
mSS.setOperatorAlphaLong(eriText);
}
if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY &&
mIccRecords != null) {
// SIM is found on the device. If ERI roaming is OFF, and SID/NID matches
// one configured in SIM, use operator name from CSIM record.
boolean showSpn =
((RuimRecords)mIccRecords).getCsimSpnDisplayCondition();
int iconIndex = mSS.getCdmaEriIconIndex();
if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) &&
isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) &&
mIccRecords != null) {
mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName());
}
}
String operatorNumeric;
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
mSS.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = mSS.getOperatorNumeric();
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
} else {
String isoCountryCode = "";
String mcc = operatorNumeric.substring(0, 3);
try {
isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric
.substring(0, 3)));
} catch (NumberFormatException ex) {
loge("countryCodeForMcc error" + ex);
} catch (StringIndexOutOfBoundsException ex) {
loge("countryCodeForMcc error" + ex);
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY,
isoCountryCode);
mGotCountryCode = true;
if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric,
mNeedFixZone)) {
fixTimeZone(isoCountryCode);
}
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
mSS.getRoaming() ? "true" : "false");
updateSpnDisplay();
mPhone.notifyServiceStateChanged(mSS);
}
if (hasCdmaDataConnectionAttached || has4gHandoff) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasCdmaDataConnectionDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) {
log("pollStateDone: call notifyDataConnection");
mPhone.notifyDataConnection(null);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
mPhone.notifyLocationChanged();
}
ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>();
synchronized(mCellInfo) {
CellInfoLte cil = (CellInfoLte)mCellInfo;
boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte);
if (hasRegistered || hasDeregistered || cidChanged) {
// TODO: Handle the absence of LteCellIdentity
long timeStamp = SystemClock.elapsedRealtime() * 1000;
boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
mLasteCellIdentityLte = mNewCellIdentityLte;
cil.setRegisterd(registered);
cil.setCellIdentity(mLasteCellIdentityLte);
if (DBG) {
log("pollStateDone: hasRegistered=" + hasRegistered +
" hasDeregistered=" + hasDeregistered +
" cidChanged=" + cidChanged +
" mCellInfo=" + mCellInfo);
}
arrayCi.add(mCellInfo);
}
mPhoneBase.notifyCellInfo(arrayCi);
}
}
| protected void pollStateDone() {
log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]");
useDataRegStateForDataOnlyDevices();
boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionAttached =
mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionDetached =
mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionChanged =
mSS.getDataRegState() != mNewSS.getDataRegState();
boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology()
!= mNewSS.getRilVoiceRadioTechnology();
boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology()
!= mNewSS.getRilDataRadioTechnology();
boolean hasChanged = !mNewSS.equals(mSS);
boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming();
boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming();
boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc);
boolean has4gHandoff =
mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE &&
(((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) ||
((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE)));
boolean hasMultiApnSupport =
(((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) ||
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) &&
((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)));
boolean hasLostMultiApnSupport =
((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) &&
(mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A));
if (DBG) {
log("pollStateDone:"
+ " hasRegistered=" + hasRegistered
+ " hasDeegistered=" + hasDeregistered
+ " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached
+ " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached
+ " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged
+ " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged
+ " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged
+ " hasChanged=" + hasChanged
+ " hasRoamingOn=" + hasRoamingOn
+ " hasRoamingOff=" + hasRoamingOff
+ " hasLocationChanged=" + hasLocationChanged
+ " has4gHandoff = " + has4gHandoff
+ " hasMultiApnSupport=" + hasMultiApnSupport
+ " hasLostMultiApnSupport=" + hasLostMultiApnSupport);
}
// Add an event log when connection state changes
if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState()
|| mSS.getDataRegState() != mNewSS.getDataRegState()) {
EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(),
mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState());
}
ServiceState tss;
tss = mSS;
mSS = mNewSS;
mNewSS = tss;
// clean slate for next time
mNewSS.setStateOutOfService();
CdmaCellLocation tcl = mCellLoc;
mCellLoc = mNewCellLoc;
mNewCellLoc = tcl;
mNewSS.setStateOutOfService(); // clean slate for next time
if (hasDataRadioTechnologyChanged) {
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology()));
// Query Signalstrength when there is a change in PS RAT.
sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
}
if (hasChanged) {
if ((mCi.getRadioState().isOn()) && (mPhone.isEriFileLoaded())) {
String eriText;
// Now the CDMAPhone sees the new ServiceState so it can get the
// new ERI text
if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE ||
(mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE)) {
eriText = mPhone.getCdmaEriText();
} else {
// Note that ServiceState.STATE_OUT_OF_SERVICE is valid used
// for mRegistrationState 0,2,3 and 4
eriText = mPhone.getContext()
.getText(com.android.internal.R.string.roamingTextSearching).toString();
}
mSS.setOperatorAlphaLong(eriText);
}
if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY &&
mIccRecords != null) {
// SIM is found on the device. If ERI roaming is OFF, and SID/NID matches
// one configured in SIM, use operator name from CSIM record.
boolean showSpn =
((RuimRecords)mIccRecords).getCsimSpnDisplayCondition();
int iconIndex = mSS.getCdmaEriIconIndex();
if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) &&
isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) &&
mIccRecords != null) {
mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName());
}
}
String operatorNumeric;
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
mSS.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = mSS.getOperatorNumeric();
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
} else {
String isoCountryCode = "";
String mcc = operatorNumeric.substring(0, 3);
try {
isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric
.substring(0, 3)));
} catch (NumberFormatException ex) {
loge("countryCodeForMcc error" + ex);
} catch (StringIndexOutOfBoundsException ex) {
loge("countryCodeForMcc error" + ex);
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY,
isoCountryCode);
mGotCountryCode = true;
if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric,
mNeedFixZone)) {
fixTimeZone(isoCountryCode);
}
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
mSS.getRoaming() ? "true" : "false");
updateSpnDisplay();
mPhone.notifyServiceStateChanged(mSS);
}
if (hasCdmaDataConnectionAttached || has4gHandoff) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasCdmaDataConnectionDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) {
log("pollStateDone: call notifyDataConnection");
mPhone.notifyDataConnection(null);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
mPhone.notifyLocationChanged();
}
ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>();
synchronized(mCellInfo) {
CellInfoLte cil = (CellInfoLte)mCellInfo;
boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte);
if (hasRegistered || hasDeregistered || cidChanged) {
// TODO: Handle the absence of LteCellIdentity
long timeStamp = SystemClock.elapsedRealtime() * 1000;
boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
mLasteCellIdentityLte = mNewCellIdentityLte;
cil.setRegisterd(registered);
cil.setCellIdentity(mLasteCellIdentityLte);
if (DBG) {
log("pollStateDone: hasRegistered=" + hasRegistered +
" hasDeregistered=" + hasDeregistered +
" cidChanged=" + cidChanged +
" mCellInfo=" + mCellInfo);
}
arrayCi.add(mCellInfo);
}
mPhoneBase.notifyCellInfo(arrayCi);
}
}
|
diff --git a/goobi1.9/WEB-INF/src/org/goobi/production/flow/helper/JobCreation.java b/goobi1.9/WEB-INF/src/org/goobi/production/flow/helper/JobCreation.java
index 082ca0dce..ae9efd8a1 100644
--- a/goobi1.9/WEB-INF/src/org/goobi/production/flow/helper/JobCreation.java
+++ b/goobi1.9/WEB-INF/src/org/goobi/production/flow/helper/JobCreation.java
@@ -1,258 +1,261 @@
package org.goobi.production.flow.helper;
/**
* This file is part of the Goobi Application - a Workflow tool for the support of mass digitization.
*
* Visit the websites for more information.
* - http://digiverso.com
* - http://www.intranda.com
*
* Copyright 2012, intranda GmbH, Göttingen
*
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions
* of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to
* link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you are not obliged to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.goobi.production.Import.ImportObject;
import org.goobi.production.cli.helper.CopyProcess;
import ugh.exceptions.PreferencesException;
import ugh.exceptions.ReadException;
import ugh.exceptions.WriteException;
import de.sub.goobi.Beans.Prozess;
import de.sub.goobi.Persistence.ProzessDAO;
import de.sub.goobi.config.ConfigMain;
import de.sub.goobi.helper.Helper;
import de.sub.goobi.helper.exceptions.DAOException;
import de.sub.goobi.helper.exceptions.SwapException;
public class JobCreation {
private static final Logger logger = Logger.getLogger(JobCreation.class);
@SuppressWarnings("static-access")
public static Prozess generateProcess(ImportObject io, Prozess vorlage) {
String processTitle = io.getProcessTitle();
logger.trace("processtitle is " + processTitle);
String metsfilename = io.getMetsFilename();
logger.trace("mets filename is " + metsfilename);
String basepath = metsfilename.substring(0, metsfilename.length() - 4);
logger.trace("basepath is " + basepath);
File metsfile = new File(metsfilename);
Prozess p = null;
if (!testTitle(processTitle)) {
logger.trace("wrong title");
// removing all data
File imagesFolder = new File(basepath);
if (imagesFolder.exists() && imagesFolder.isDirectory()) {
deleteDirectory(imagesFolder);
} else {
imagesFolder = new File(basepath + "_" + vorlage.DIRECTORY_SUFFIX);
if (imagesFolder.exists() && imagesFolder.isDirectory()) {
deleteDirectory(imagesFolder);
}
}
try {
FileUtils.forceDelete(metsfile);
} catch (Exception e) {
logger.error("Can not delete file " + processTitle, e);
return null;
}
File anchor = new File(basepath + "_anchor.xml");
if (anchor.exists()) {
FileUtils.deleteQuietly(anchor);
}
return null;
}
CopyProcess cp = new CopyProcess();
cp.setProzessVorlage(vorlage);
cp.metadataFile = metsfilename;
cp.Prepare(io);
cp.getProzessKopie().setTitel(processTitle);
logger.trace("testing title");
if (cp.testTitle()) {
logger.trace("title is valid");
cp.OpacAuswerten();
try {
p = cp.createProcess(io);
moveFiles(metsfile, basepath, p);
} catch (ReadException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
} catch (PreferencesException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
} catch (SwapException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
} catch (DAOException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
} catch (WriteException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
} catch (IOException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
} catch (InterruptedException e) {
Helper.setFehlerMeldung(e);
logger.error(e);
}
} else {
logger.trace("title is invalid");
}
return p;
}
public static boolean testTitle(String titel) {
if (titel != null) {
long anzahl = 0;
try {
anzahl = new ProzessDAO().count("from Prozess where titel='" + titel + "'");
} catch (DAOException e) {
return false;
}
if (anzahl > 0) {
Helper.setFehlerMeldung("processTitleAllreadyInUse");
return false;
}
} else {
return false;
}
return true;
}
@SuppressWarnings("static-access")
public static void moveFiles(File metsfile, String basepath, Prozess p) throws SwapException, DAOException, IOException, InterruptedException {
if (ConfigMain.getBooleanParameter("importUseOldConfiguration", false)) {
File imagesFolder = new File(basepath);
if (!imagesFolder.exists()) {
imagesFolder = new File(basepath + "_" + p.DIRECTORY_SUFFIX);
}
if (imagesFolder.exists() && imagesFolder.isDirectory()) {
List<String> imageDir = new ArrayList<String>();
String[] files = imagesFolder.list();
for (int i = 0; i < files.length; i++) {
imageDir.add(files[i]);
}
for (String file : imageDir) {
File image = new File(imagesFolder, file);
File dest = new File(p.getImagesOrigDirectory() + image.getName());
FileUtils.moveFile(image, dest);
}
deleteDirectory(imagesFolder);
}
// copy pdf files
File pdfs = new File(basepath + "_pdf" + File.separator);
if (pdfs.isDirectory()) {
FileUtils.moveDirectory(pdfs, new File(p.getPdfDirectory()));
}
// copy fulltext files
File fulltext = new File(basepath + "_txt");
if (fulltext.isDirectory()) {
FileUtils.moveDirectory(fulltext, new File(p.getTxtDirectory()));
}
// copy source files
File sourceDir = new File(basepath + "_src" + File.separator);
if (sourceDir.isDirectory()) {
FileUtils.moveDirectory(sourceDir, new File(p.getImportDirectory()));
}
try {
FileUtils.forceDelete(metsfile);
} catch (Exception e) {
logger.error("Can not delete file " + metsfile.getName() + " after importing " + p.getTitel() + " into goobi", e);
}
File anchor = new File(basepath + "_anchor.xml");
if (anchor.exists()) {
FileUtils.deleteQuietly(anchor);
}
}
else {
// new folder structure for process imports
File importFolder = new File(basepath);
if (importFolder.exists() && importFolder.isDirectory()) {
File[] folderList = importFolder.listFiles();
for (File directory : folderList) {
if (directory.getName().contains("images")) {
File[] imageList = directory.listFiles();
for (File imagedir : imageList) {
if (imagedir.isDirectory()) {
- FileUtils.moveDirectory(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
+ for (File file : imagedir.listFiles()) {
+ FileUtils.moveFile(file, new File(p.getImagesDirectory() + imagedir.getName(), file.getName()));
+ }
+// FileUtils.moveDirectory(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
} else {
FileUtils.moveFile(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
}
}
} else if (directory.getName().contains("ocr")) {
File ocr = new File(p.getOcrDirectory());
if (!ocr.exists()) {
ocr.mkdir();
}
File[] ocrList = directory.listFiles();
for (File ocrdir : ocrList) {
if (ocrdir.isDirectory()) {
FileUtils.moveDirectory(ocrdir, new File(ocr, ocrdir.getName()));
} else {
FileUtils.moveFile(ocrdir, new File(ocr, ocrdir.getName()));
}
}
} else {
File i = new File(p.getImportDirectory());
if (!i.exists()) {
i.mkdir();
}
File[] importList = directory.listFiles();
for (File importdir : importList) {
if (importdir.isDirectory()) {
FileUtils.moveDirectory(importdir, new File(i, importdir.getName()));
} else {
FileUtils.moveFile(importdir, new File(i, importdir.getName()));
}
}
}
}
}
}
}
private static void deleteDirectory(File directory) {
try {
FileUtils.deleteDirectory(directory);
} catch (IOException e) {
logger.error(e);
}
}
}
| true | true | public static void moveFiles(File metsfile, String basepath, Prozess p) throws SwapException, DAOException, IOException, InterruptedException {
if (ConfigMain.getBooleanParameter("importUseOldConfiguration", false)) {
File imagesFolder = new File(basepath);
if (!imagesFolder.exists()) {
imagesFolder = new File(basepath + "_" + p.DIRECTORY_SUFFIX);
}
if (imagesFolder.exists() && imagesFolder.isDirectory()) {
List<String> imageDir = new ArrayList<String>();
String[] files = imagesFolder.list();
for (int i = 0; i < files.length; i++) {
imageDir.add(files[i]);
}
for (String file : imageDir) {
File image = new File(imagesFolder, file);
File dest = new File(p.getImagesOrigDirectory() + image.getName());
FileUtils.moveFile(image, dest);
}
deleteDirectory(imagesFolder);
}
// copy pdf files
File pdfs = new File(basepath + "_pdf" + File.separator);
if (pdfs.isDirectory()) {
FileUtils.moveDirectory(pdfs, new File(p.getPdfDirectory()));
}
// copy fulltext files
File fulltext = new File(basepath + "_txt");
if (fulltext.isDirectory()) {
FileUtils.moveDirectory(fulltext, new File(p.getTxtDirectory()));
}
// copy source files
File sourceDir = new File(basepath + "_src" + File.separator);
if (sourceDir.isDirectory()) {
FileUtils.moveDirectory(sourceDir, new File(p.getImportDirectory()));
}
try {
FileUtils.forceDelete(metsfile);
} catch (Exception e) {
logger.error("Can not delete file " + metsfile.getName() + " after importing " + p.getTitel() + " into goobi", e);
}
File anchor = new File(basepath + "_anchor.xml");
if (anchor.exists()) {
FileUtils.deleteQuietly(anchor);
}
}
else {
// new folder structure for process imports
File importFolder = new File(basepath);
if (importFolder.exists() && importFolder.isDirectory()) {
File[] folderList = importFolder.listFiles();
for (File directory : folderList) {
if (directory.getName().contains("images")) {
File[] imageList = directory.listFiles();
for (File imagedir : imageList) {
if (imagedir.isDirectory()) {
FileUtils.moveDirectory(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
} else {
FileUtils.moveFile(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
}
}
} else if (directory.getName().contains("ocr")) {
File ocr = new File(p.getOcrDirectory());
if (!ocr.exists()) {
ocr.mkdir();
}
File[] ocrList = directory.listFiles();
for (File ocrdir : ocrList) {
if (ocrdir.isDirectory()) {
FileUtils.moveDirectory(ocrdir, new File(ocr, ocrdir.getName()));
} else {
FileUtils.moveFile(ocrdir, new File(ocr, ocrdir.getName()));
}
}
} else {
File i = new File(p.getImportDirectory());
if (!i.exists()) {
i.mkdir();
}
File[] importList = directory.listFiles();
for (File importdir : importList) {
if (importdir.isDirectory()) {
FileUtils.moveDirectory(importdir, new File(i, importdir.getName()));
} else {
FileUtils.moveFile(importdir, new File(i, importdir.getName()));
}
}
}
}
}
}
}
| public static void moveFiles(File metsfile, String basepath, Prozess p) throws SwapException, DAOException, IOException, InterruptedException {
if (ConfigMain.getBooleanParameter("importUseOldConfiguration", false)) {
File imagesFolder = new File(basepath);
if (!imagesFolder.exists()) {
imagesFolder = new File(basepath + "_" + p.DIRECTORY_SUFFIX);
}
if (imagesFolder.exists() && imagesFolder.isDirectory()) {
List<String> imageDir = new ArrayList<String>();
String[] files = imagesFolder.list();
for (int i = 0; i < files.length; i++) {
imageDir.add(files[i]);
}
for (String file : imageDir) {
File image = new File(imagesFolder, file);
File dest = new File(p.getImagesOrigDirectory() + image.getName());
FileUtils.moveFile(image, dest);
}
deleteDirectory(imagesFolder);
}
// copy pdf files
File pdfs = new File(basepath + "_pdf" + File.separator);
if (pdfs.isDirectory()) {
FileUtils.moveDirectory(pdfs, new File(p.getPdfDirectory()));
}
// copy fulltext files
File fulltext = new File(basepath + "_txt");
if (fulltext.isDirectory()) {
FileUtils.moveDirectory(fulltext, new File(p.getTxtDirectory()));
}
// copy source files
File sourceDir = new File(basepath + "_src" + File.separator);
if (sourceDir.isDirectory()) {
FileUtils.moveDirectory(sourceDir, new File(p.getImportDirectory()));
}
try {
FileUtils.forceDelete(metsfile);
} catch (Exception e) {
logger.error("Can not delete file " + metsfile.getName() + " after importing " + p.getTitel() + " into goobi", e);
}
File anchor = new File(basepath + "_anchor.xml");
if (anchor.exists()) {
FileUtils.deleteQuietly(anchor);
}
}
else {
// new folder structure for process imports
File importFolder = new File(basepath);
if (importFolder.exists() && importFolder.isDirectory()) {
File[] folderList = importFolder.listFiles();
for (File directory : folderList) {
if (directory.getName().contains("images")) {
File[] imageList = directory.listFiles();
for (File imagedir : imageList) {
if (imagedir.isDirectory()) {
for (File file : imagedir.listFiles()) {
FileUtils.moveFile(file, new File(p.getImagesDirectory() + imagedir.getName(), file.getName()));
}
// FileUtils.moveDirectory(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
} else {
FileUtils.moveFile(imagedir, new File(p.getImagesDirectory(), imagedir.getName()));
}
}
} else if (directory.getName().contains("ocr")) {
File ocr = new File(p.getOcrDirectory());
if (!ocr.exists()) {
ocr.mkdir();
}
File[] ocrList = directory.listFiles();
for (File ocrdir : ocrList) {
if (ocrdir.isDirectory()) {
FileUtils.moveDirectory(ocrdir, new File(ocr, ocrdir.getName()));
} else {
FileUtils.moveFile(ocrdir, new File(ocr, ocrdir.getName()));
}
}
} else {
File i = new File(p.getImportDirectory());
if (!i.exists()) {
i.mkdir();
}
File[] importList = directory.listFiles();
for (File importdir : importList) {
if (importdir.isDirectory()) {
FileUtils.moveDirectory(importdir, new File(i, importdir.getName()));
} else {
FileUtils.moveFile(importdir, new File(i, importdir.getName()));
}
}
}
}
}
}
}
|
diff --git a/source/RMG/jing/rxnSys/JDAS.java b/source/RMG/jing/rxnSys/JDAS.java
index b6b8f33c..bac24678 100644
--- a/source/RMG/jing/rxnSys/JDAS.java
+++ b/source/RMG/jing/rxnSys/JDAS.java
@@ -1,1205 +1,1208 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.rxnSys;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import jing.chem.Species;
import jing.chem.SpeciesDictionary;
import jing.param.Global;
import jing.param.ParameterInfor;
import jing.param.Pressure;
import jing.param.Temperature;
import jing.rxn.LindemannReaction;
import jing.rxn.NegativeRateException;
import jing.rxn.PDepNetwork;
import jing.rxn.PDepReaction;
import jing.rxn.Reaction;
import jing.rxn.TROEReaction;
import jing.rxn.TemplateReaction;
import jing.rxn.ThirdBodyReaction;
import java.io.BufferedWriter;
/**
* Common base class for the DASSL and DASPK solvers, which share a lot of
* code.
*/
public abstract class JDAS implements DAESolver {
protected LinkedHashMap IDTranslator = new LinkedHashMap(); //## attribute IDTranslator
protected double atol; //## attribute atol
protected int parameterInfor;//svp
protected ParameterInfor [] parameterInforArray = null; //## attribute parameterInfor
protected double rtol; //## attribute rtol
protected InitialStatus initialStatus;//svp
protected int nState = 3 ;
protected int neq = 3;
protected int nParameter =0;
protected double [] y;
protected double [] yprime;
protected int [] info = new int[30];
protected LinkedList rList ;
protected LinkedList duplicates ;
protected LinkedList thirdBodyList ;
protected LinkedList troeList ;
protected LinkedList lindemannList;
//protected StringBuilder outputString ;
protected BufferedWriter bw;
protected FileWriter fw;
protected StringBuilder rString ;
protected StringBuilder tbrString;
protected StringBuilder troeString;
protected StringBuilder lindemannString;
protected int index; //11/1/07 gmagoon: adding index to allow appropriate naming of RWORK, IWORK****may need to make similar modification for DASPK?
protected ValidityTester validityTester; //5/5/08 gmagoon: adding validityTester and autoflag as attributes needed for "automatic" time stepping
protected static boolean autoflag;
protected double [] reactionFlux;
protected double [] conversionSet;
protected double endTime;
protected StringBuilder thermoString = new StringBuilder();
protected static HashMap edgeID;
protected double [] maxEdgeFluxRatio;
protected boolean [] prunableSpecies;
protected double termTol;
protected double coreTol;
protected static boolean nonnegative = false;
protected boolean targetReached;
protected JDAS() {
}
public JDAS(double p_rtol, double p_atol, int p_parameterInfor,
InitialStatus p_initialStatus, int p_index, ValidityTester p_vt,
boolean p_autoflag, Double p_termTol, Double p_coreTol) {
rtol = p_rtol;
atol = p_atol;
index = p_index;
validityTester = p_vt;
autoflag = p_autoflag;
termTol = p_termTol;
coreTol = p_coreTol;
parameterInfor = p_parameterInfor;
initialStatus = p_initialStatus;
}
public void addSA(){
if (parameterInfor == 0) {
parameterInfor = 1;
}
}
public void addConversion(double [] p_conversions, int numConversion) {
conversionSet = new double[numConversion];
for (int i=0; i< numConversion; i++)
conversionSet[i] = p_conversions[i];
}
public double[] getConversion(){
return conversionSet;
}
public StringBuilder generatePDepODEReactionList(ReactionModel p_reactionModel,
SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) {
StringBuilder rString = new StringBuilder();
StringBuilder arrayString = new StringBuilder();
StringBuilder rateString = new StringBuilder();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)p_reactionModel;
rList = new LinkedList();
duplicates = new LinkedList();
LinkedList nonPDepList = new LinkedList();
LinkedList pDepList = new LinkedList();
generatePDepReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure, nonPDepList, pDepList);
int size = nonPDepList.size() + pDepList.size() + duplicates.size();
for (Iterator iter = nonPDepList.iterator(); iter.hasNext(); ) {
Reaction r = (Reaction)iter.next();
if (!(r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)){
rList.add(r);
ODEReaction or = transferReaction(r, p_beginStatus, p_temperature, p_pressure);
arrayString.append(or.rNum+" "+or.pNum+" ");
for (int i=0;i<3;i++){
if (i<or.rNum)
arrayString.append(or.rID[i]+" ");
else
arrayString.append(0+" ");
}
for (int i=0;i<3;i++){
if (i<or.pNum)
arrayString.append(or.pID[i]+" ");
else
arrayString.append(0+" ");
}
// Original DASSL has these lines uncommented, while DASPK is as given (should they be different?)
if (r.hasReverseReaction())
arrayString.append(1 + " ");
else
arrayString.append(0 + " ");
rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " ");
}
}
for (Iterator iter = pDepList.iterator(); iter.hasNext(); ) {
Reaction r = (Reaction)iter.next();
if (r instanceof PDepReaction) {
rList.add(r);
ODEReaction or = transferReaction(r, p_beginStatus, p_temperature, p_pressure);
arrayString.append(or.rNum+" "+or.pNum+" ");
for (int i=0;i<3;i++){
if (i<or.rNum)
arrayString.append(or.rID[i]+" ");
else
arrayString.append(0+" ");
}
for (int i=0;i<3;i++){
if (i<or.pNum)
arrayString.append(or.pID[i]+" ");
else
arrayString.append(0+" ");
}
arrayString.append(1 + " ");
rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+" ");
}
}
for (Iterator iter = duplicates.iterator(); iter.hasNext(); ) {
Reaction r = (Reaction)iter.next();
//if (!(r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)){
if (r instanceof PDepReaction) {
rList.add(r);
ODEReaction or = transferReaction(r, p_beginStatus, p_temperature, p_pressure);
arrayString.append(or.rNum+" "+or.pNum+" ");
for (int i=0;i<3;i++){
if (i<or.rNum)
arrayString.append(or.rID[i]+" ");
else
arrayString.append(0+" ");
}
for (int i=0;i<3;i++){
if (i<or.pNum)
arrayString.append(or.pID[i]+" ");
else
arrayString.append(0+" ");
}
//if (r.hasReverseReaction())
arrayString.append(1 + " ");
//else
//arrayString.append(0 + " ");
rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " ");
}
}
rString.append(arrayString.toString()+"\n"+rateString.toString());
return rString;
}
public void generatePDepReactionList(ReactionModel p_reactionModel,
SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure,
LinkedList nonPDepList, LinkedList pDepList) {
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)p_reactionModel;
for (Iterator iter = PDepNetwork.getCoreReactions(cerm).iterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
if (cerm.categorizeReaction(rxn) != 1) continue;
//check if this reaction is not already in the list and also check if this reaction has a reverse reaction
// which is already present in the list.
if (rxn.getReverseReaction() == null)
rxn.generateReverseReaction();
if (!rxn.reactantEqualsProduct() && !troeList.contains(rxn) && !troeList.contains(rxn.getReverseReaction()) && !thirdBodyList.contains(rxn) && !thirdBodyList.contains(rxn.getReverseReaction()) && !lindemannList.contains(rxn) && !lindemannList.contains(rxn.getReverseReaction())) {
if (!pDepList.contains(rxn) && !pDepList.contains(rxn.getReverseReaction())){
pDepList.add(rxn);
}
else if (pDepList.contains(rxn) && !pDepList.contains(rxn.getReverseReaction()))
continue;
else if (!pDepList.contains(rxn) && pDepList.contains(rxn.getReverseReaction())){
Temperature T = new Temperature(298, "K");
if (rxn.calculateKeq(T)>0.999) {
pDepList.remove(rxn.getReverseReaction());
pDepList.add(rxn);
}
}
}
}
for (Iterator iter = p_reactionModel.getReactionSet().iterator(); iter.hasNext(); ) {
Reaction r = (Reaction)iter.next();
if (r.isForward() && !(r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction))
nonPDepList.add(r);
}
duplicates.clear();
}
protected LinkedHashMap generateSpeciesStatus(ReactionModel p_reactionModel,
double [] p_y, double [] p_yprime, int p_paraNum) {
int neq = p_reactionModel.getSpeciesNumber()*(p_paraNum+1);
if (p_y.length != neq) throw new DynamicSimulatorException();
if (p_yprime.length != neq) throw new DynamicSimulatorException();
LinkedHashMap speStatus = new LinkedHashMap();
System.out.println("Sp.#\tName \tConcentration \tFlux");
for (Iterator iter = p_reactionModel.getSpecies(); iter.hasNext(); ) {
Species spe = (Species)iter.next();
int id = getRealID(spe);
if (id>p_y.length) throw new UnknownReactedSpeciesException(spe.getName());
double conc = p_y[id-1];
double flux = p_yprime[id-1];
System.out.println(String.format("%1$4d\t%2$-13s\t%3$ 6E \t%4$ 6E", spe.getID(), spe.getName(), conc, flux));
if (conc < 0) {
double aTol = ReactionModelGenerator.getAtol();
//if (Math.abs(conc) < aTol) conc = 0;
//else throw new NegativeConcentrationException("Species " + spe.getName() + " has negative conc: " + String.valueOf(conc));
if (conc < -100.0 * aTol)
throw new NegativeConcentrationException("Species " + spe.getName() + " has negative concentration: " + String.valueOf(conc));
}
SpeciesStatus ss = new SpeciesStatus(spe, 1, conc, flux);
speStatus.put(spe,ss);
}
return speStatus;
}
public StringBuilder generateThirdBodyReactionList(ReactionModel p_reactionModel,
SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) {
int size = p_reactionModel.getReactionSet().size();
StringBuilder arrayString = new StringBuilder();
StringBuilder rateString = new StringBuilder();
StringBuilder tbrString = new StringBuilder();
Iterator iter = p_reactionModel.getReactionSet().iterator();
thirdBodyList = new LinkedList();
while (iter.hasNext()) {
Reaction r = (Reaction)iter.next();
if ((r.isForward()) && (r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)) {
ThirdBodyODEReaction or = (ThirdBodyODEReaction)transferReaction(r, p_beginStatus, p_temperature, p_pressure);
thirdBodyList.add((ThirdBodyReaction)r);
arrayString.append(or.rNum+" "+or.pNum+" ");
for (int i=0;i<3;i++){
if (i<or.rNum)
arrayString.append(or.rID[i]+" ");
else
arrayString.append(0+" ");
}
for (int i=0;i<3;i++){
if (i<or.pNum)
arrayString.append(or.pID[i]+" ");
else
arrayString.append(0+" ");
}
if (r.hasReverseReaction())
arrayString.append(1 + " ");
else
arrayString.append(0 + " ");
arrayString.append(or.numCollider+" ");
for (int i=0; i<10; i++){
if (i < or.numCollider)
arrayString.append(or.colliders[i] + " ");
else
arrayString.append(0 + " ");
}
rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " " +or.inertColliderEfficiency+" ");
for (int i=0; i<10; i++){
if (i < or.numCollider)
rateString.append(or.efficiency[i] + " ");
else
rateString.append(0 + " ");
}
}
}
tbrString.append(arrayString.toString()+"\n"+rateString.toString());
return tbrString;
}
protected StringBuilder generateTROEReactionList(ReactionModel p_reactionModel,
SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) {
int size = p_reactionModel.getReactionSet().size();
StringBuilder arrayString = new StringBuilder();
StringBuilder rateString = new StringBuilder();
StringBuilder troeString = new StringBuilder();
Iterator iter = p_reactionModel.getReactionSet().iterator();
troeList = new LinkedList();
while (iter.hasNext()) {
Reaction r = (Reaction)iter.next();
if (r.isForward() && r instanceof TROEReaction) {
TROEODEReaction or = (TROEODEReaction)transferReaction(r, p_beginStatus, p_temperature, p_pressure);
troeList.add((TROEReaction)r);
arrayString.append(or.rNum+" "+or.pNum+" ");
for (int i=0;i<3;i++){
if (i<or.rNum)
arrayString.append(or.rID[i]+" ");
else
arrayString.append(0+" ");
}
for (int i=0;i<3;i++){
if (i<or.pNum)
arrayString.append(or.pID[i]+" ");
else
arrayString.append(0+" ");
}
if (r.hasReverseReaction())
arrayString.append(1 + " ");
else
arrayString.append(0 + " ");
arrayString.append(or.numCollider+" ");
for (int i=0; i<10; i++){
if (i < or.numCollider)
arrayString.append(or.colliders[i] + " ");
else
arrayString.append(0 + " ");
}
if (or.troe7)
arrayString.append(0 + " ");
else
arrayString.append(1 + " ");
rateString.append(or.highRate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " "+or.inertColliderEfficiency+" ");
for (int i=0; i<10; i++){
if (i < or.numCollider)
rateString.append(or.efficiency[i] + " ");
else
rateString.append(0 + " ");
}
rateString.append(or.a + " " + or.Tstar + " " + or.T2star + " " + or.T3star + " " + or.lowRate+ " ");
}
}
troeString.append(arrayString.toString()+"\n"+rateString.toString());
return troeString;
}
protected StringBuilder generateLindemannReactionList(ReactionModel p_reactionModel,
SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) {
int size = p_reactionModel.getReactionSet().size();
StringBuilder arrayString = new StringBuilder();
StringBuilder rateString = new StringBuilder();
StringBuilder lindemannString = new StringBuilder();
Iterator iter = p_reactionModel.getReactionSet().iterator();
lindemannList = new LinkedList();
while (iter.hasNext()) {
Reaction r = (Reaction)iter.next();
if (r.isForward() && r instanceof LindemannReaction) {
LindemannODEReaction or = (LindemannODEReaction)transferReaction(r, p_beginStatus, p_temperature, p_pressure);
lindemannList.add((LindemannReaction)r);
arrayString.append(or.rNum+" "+or.pNum+" ");
for (int i=0;i<3;i++){
if (i<or.rNum)
arrayString.append(or.rID[i]+" ");
else
arrayString.append(0+" ");
}
for (int i=0;i<3;i++){
if (i<or.pNum)
arrayString.append(or.pID[i]+" ");
else
arrayString.append(0+" ");
}
if (r.hasReverseReaction())
arrayString.append(1 + " ");
else
arrayString.append(0 + " ");
arrayString.append(or.numCollider+" ");
for (int i=0; i<10; i++){
if (i < or.numCollider)
arrayString.append(or.colliders[i] + " ");
else
arrayString.append(0 + " ");
}
rateString.append(or.highRate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " "+or.inertColliderEfficiency+" ");
for (int i=0; i<10; i++){
if (i < or.numCollider)
rateString.append(or.efficiency[i] + " ");
else
rateString.append(0 + " ");
}
rateString.append(or.lowRate+ " ");
}
}
lindemannString.append(arrayString.toString()+"\n"+rateString.toString());
return lindemannString;
}
public int getRealID(Species p_species) {
Integer id = (Integer)IDTranslator.get(p_species);
if (id == null) {
id = new Integer(IDTranslator.size()+1);
IDTranslator.put(p_species, id);
thermoString.append(p_species.calculateG(initialStatus.getTemperature()) + " ");//10/26/07 gmagoon: changed to avoid use of Global.temperature;****ideally, current temperature would be used, but initial temperature is simplest to pass in current implementation
}
return id.intValue();
}
public boolean IDTranslatorContainsQ(Species p_species){
Integer id = (Integer)IDTranslator.get(p_species);
if (id == null) return false;
else return true;
}
protected void initializeWorkSpace() {
for (int i=0; i<30; i++)
info[i] = 0;
info[2] = 1; //print out the time steps
if (nonnegative) info[9]=1; // don't allow negative values
}
protected void initializeConcentrations(SystemSnapshot p_beginStatus,
ReactionModel p_reactionModel, ReactionTime p_beginTime,
ReactionTime p_endTime, LinkedList initialSpecies) {
y = new double[neq];
yprime = new double[neq];
for (Iterator iter = p_beginStatus.getSpeciesStatus(); iter.hasNext(); ) {
SpeciesStatus ss = (SpeciesStatus)iter.next();
double conc = ss.getConcentration();
double flux = ss.getFlux();
if (ss.isReactedSpecies()) {
Species spe = ss.getSpecies();
int id = getRealID(spe);
//System.out.println(String.valueOf(spe.getID()) + '\t' + spe.getName() + '\t' + String.valueOf(conc) + '\t' + String.valueOf(flux));
y[id-1] = conc;
yprime[id-1] = flux;
}
}
}
public ODEReaction transferReaction(Reaction p_reaction, SystemSnapshot p_beginStatus,
Temperature p_temperature, Pressure p_pressure) {
//System.out.println(p_reaction.getStructure().toString()+"\t"+p_reaction.calculateTotalRate(Global.temperature));
double startTime = System.currentTimeMillis();
double dT = 1;
Temperature Tup = new Temperature(p_temperature.getStandard()+dT, Temperature.getStandardUnit());
Temperature Tlow = new Temperature(p_temperature.getStandard()-dT, Temperature.getStandardUnit());
int rnum = p_reaction.getReactantNumber();
int pnum = p_reaction.getProductNumber();
int [] rid = new int[rnum];
int index = 0;
for (Iterator r_iter = p_reaction.getReactants(); r_iter.hasNext(); ) {
Species s = (Species)r_iter.next();
rid[index] = getRealID(s);
index++;
}
int [] pid = new int[pnum];
index = 0;
for (Iterator p_iter = p_reaction.getProducts(); p_iter.hasNext(); ) {
Species s = (Species)p_iter.next();
pid[index] = getRealID(s);
index++;
}
//Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60;
//ODEReaction or;
if (p_reaction instanceof PDepReaction) {
double rate = ((PDepReaction)p_reaction).calculateRate(p_temperature, p_pressure);
if (String.valueOf(rate).equals("NaN")){
System.err.println(p_reaction.toChemkinString(p_temperature) + "Has bad rate probably due to Ea<DH");
rate = 0;
}
ODEReaction or = new ODEReaction(rnum, pnum, rid, pid, rate);
//Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60;
return or;
}
else {
double rate = 0;
if (p_reaction instanceof TemplateReaction) {
//startTime = System.currentTimeMillis();
//rate = ((TemplateReaction)p_reaction).getRateConstant();
rate = ((TemplateReaction)p_reaction).calculateTotalRate(p_beginStatus.temperature);
ODEReaction or = new ODEReaction(rnum, pnum, rid, pid, rate);
//Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60;
return or;
}
else if (p_reaction instanceof TROEReaction){//svp
startTime = System.currentTimeMillis();
HashMap weightMap = ((ThirdBodyReaction)p_reaction).getWeightMap();
int weightMapSize = weightMap.size();
int [] colliders = new int[weightMapSize];
double [] efficiency = new double[weightMapSize];
Iterator colliderIter = weightMap.keySet().iterator();
int numCollider =0;
for (int i=0; i<weightMapSize; i++){
String name = (String)colliderIter.next();
Species spe = SpeciesDictionary.getInstance().getSpeciesFromName(name);
if (spe != null && IDTranslatorContainsQ(spe)){//gmagoon 02/17/10: added check to make sure the collider is in the IDTranslator as well (i.e. it is in the core); without this check, edge species can pass this test, causing them to be added to the IDTranslator when getRealID is called below; 02/18/10 UPDATE: IDTranslator will not contain inert species like Ar, N2 (in any case, they are not tracked explicitly in the ODESolver); BUT, even in original case (before yesterday's change), they would not be found in SpeciesDictionary either ; Bottom line: collider parameters for Ar/N2 will never be used, and as far as I can tell, never have been
colliders[numCollider] = getRealID(spe);
efficiency[numCollider] = ((Double)weightMap.get(name)).doubleValue();
numCollider++;
}
}
Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60;
double T2star, T3star, Tstar, a;
T2star = ((TROEReaction)p_reaction).getT2star();
T3star = ((TROEReaction)p_reaction).getT3star();
Tstar = ((TROEReaction)p_reaction).getTstar();
a = ((TROEReaction)p_reaction).getA();
int direction = p_reaction.getDirection();
double Keq = p_reaction.calculateKeq(p_temperature);
double lowRate = ((TROEReaction)p_reaction).getLow().calculateRate(p_temperature, -1);
double highRate = 0.0;
for (int numKinetics=0; numKinetics<((TROEReaction)p_reaction).getKinetics().length; ++numKinetics) {
highRate += ((TROEReaction)p_reaction).getKinetics()[numKinetics].calculateRate(p_temperature, -1);
}
double inertColliderEfficiency = ((ThirdBodyReaction)p_reaction).calculateThirdBodyCoefficientForInerts(p_beginStatus);
boolean troe7 = ((TROEReaction)p_reaction).getTroe7();
TROEODEReaction or = new TROEODEReaction(rnum, pnum, rid, pid, direction, Keq, colliders, efficiency, numCollider, inertColliderEfficiency, T2star, T3star, Tstar, a, highRate, lowRate, troe7);
return or;
}
else if (p_reaction instanceof LindemannReaction){
HashMap weightMap = ((ThirdBodyReaction)p_reaction).getWeightMap();
int weightMapSize = weightMap.size();
int [] colliders = new int[weightMapSize];
double [] efficiency = new double[weightMapSize];
Iterator colliderIter = weightMap.keySet().iterator();
int numCollider =0;
for (int i=0; i<weightMapSize; i++){
String name = (String)colliderIter.next();
Species spe = SpeciesDictionary.getInstance().getSpeciesFromName(name);
if (spe != null && IDTranslatorContainsQ(spe)){//gmagoon 2/17/10: added check to make sure the collider is in the ID translator as well (i.e. it is in the core); without this check, edge species can pass this test, causing them to be added to the IDTranslator when getRealID is called below; 02/18/10 UPDATE: IDTranslator will not contain inert species like Ar, N2 (in any case, they are not tracked explicitly in the ODESolver); BUT, even in original case (before yesterday's change), they would not be found in SpeciesDictionary either ; Bottom line: collider parameters for Ar/N2 will never be used, and as far as I can tell, never have been
colliders[numCollider] = getRealID(spe);
efficiency[numCollider] = ((Double)weightMap.get(name)).doubleValue();
numCollider++;
}
}
int direction = p_reaction.getDirection();
double Keq = p_reaction.calculateKeq(p_temperature);
double lowRate = ((LindemannReaction)p_reaction).getLow().calculateRate(p_temperature, -1);
double highRate = 0.0;
for (int numKinetics=0; numKinetics<((LindemannReaction)p_reaction).getKinetics().length; ++numKinetics) {
highRate += ((LindemannReaction)p_reaction).getKinetics()[0].calculateRate(p_temperature, -1);
}
double inertColliderEfficiency = ((ThirdBodyReaction)p_reaction).calculateThirdBodyCoefficientForInerts(p_beginStatus);
LindemannODEReaction or = new LindemannODEReaction(rnum, pnum, rid, pid, direction, Keq, colliders, efficiency, numCollider, inertColliderEfficiency, highRate, lowRate);
return or;
}
else if (p_reaction instanceof ThirdBodyReaction){//svp
startTime = System.currentTimeMillis();
HashMap weightMap = ((ThirdBodyReaction)p_reaction).getWeightMap();
int weightMapSize = weightMap.size();
int [] colliders = new int[weightMapSize];
double [] efficiency = new double[weightMapSize];
Iterator colliderIter = weightMap.keySet().iterator();
int numCollider =0;
for (int i=0; i<weightMapSize; i++){
String name = (String)colliderIter.next();
Species spe = SpeciesDictionary.getInstance().getSpeciesFromName(name);
if (spe != null && IDTranslatorContainsQ(spe)){//gmagoon 2/17/10: added check to make sure the collider is in the ID translator as well (i.e. it is in the core); without this check, edge species can pass this test, causing them to be added to the IDTranslator when getRealID is called below; 02/18/10 UPDATE: IDTranslator will not contain inert species like Ar, N2 (in any case, they are not tracked explicitly in the ODESolver); BUT, even in original case (before yesterday's change), they would not be found in SpeciesDictionary either ; Bottom line: collider parameters for Ar/N2 will never be used, and as far as I can tell, never have been
colliders[numCollider] = getRealID(spe);
efficiency[numCollider] = ((Double)weightMap.get(name)).doubleValue();
numCollider++;
}
}
Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60;
rate = p_reaction.calculateTotalRate(p_beginStatus.temperature);
double inertColliderEfficiency = ((ThirdBodyReaction)p_reaction).calculateThirdBodyCoefficientForInerts(p_beginStatus);
//rate = p_reaction.getRateConstant();
ThirdBodyODEReaction or = new ThirdBodyODEReaction(rnum, pnum, rid, pid, rate, colliders, efficiency,numCollider, inertColliderEfficiency);
return or;
}
else{
rate = p_reaction.calculateTotalRate(p_beginStatus.temperature);
//startTime = System.currentTimeMillis();
//rate = p_reaction.getRateConstant();
ODEReaction or = new ODEReaction(rnum, pnum, rid, pid, rate);
//Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60;
return or;
}
}
}
public double getAtol() {
return atol;
}
public int getReactionSize(){
return rList.size()+troeList.size()+thirdBodyList.size()+lindemannList.size();
}
public int getMaxSpeciesNumber() {
return IDTranslator.size() - 1;
}
public double getRtol() {
return rtol;
}
public String getEdgeReactionString(CoreEdgeReactionModel model, HashMap edgeID,
Reaction r, Temperature temperature, Pressure pressure) {
int edgeSpeciesCounter = edgeID.size();
// Find the rate coefficient
double k;
if (r instanceof TemplateReaction)
k = ((TemplateReaction) r).getRateConstant(temperature, pressure);
else if (r instanceof PDepReaction)
k = ((PDepReaction) r).calculateRate(temperature, pressure);
else
k = r.getRateConstant(temperature);
if (k > 0) {
int reacCount = 0;
int prodCount = 0;
int[] tempReacArray = {0, 0, 0};
int[] tempProdArray = {0, 0, 0};
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (Iterator rIter = r.getReactants(); rIter.hasNext();) {
reacCount++;
Species spe = (Species) rIter.next();
tempReacArray[reacCount - 1] = getRealID(spe);
}
//iterate over the products, selecting products which are not already in the core, counting and storing ID's (created sequentially in a HashMap, similar to getRealID) in tempProdArray, up to a maximum of 3
for (Iterator pIter = r.getProducts(); pIter.hasNext();) {
Species spe = (Species) pIter.next();
if (model.containsAsUnreactedSpecies(spe)) {
prodCount++;
Integer id = (Integer) edgeID.get(spe);
if (id == null) {
edgeSpeciesCounter++;
id = new Integer(edgeSpeciesCounter);
edgeID.put(spe, id);
}
tempProdArray[prodCount - 1] = id;
}
}
//update the output string with info for one reaction
String str = reacCount + " " + prodCount + " " + tempReacArray[0] + " " + tempReacArray[1] + " " + tempReacArray[2] + " " + tempProdArray[0] + " " + tempProdArray[1] + " " + tempProdArray[2] + " " + k;
return str;
} else {
throw new NegativeRateException(r.toChemkinString(temperature) + ": " + String.valueOf(k));
}
}
public void getAutoEdgeReactionInfo(CoreEdgeReactionModel model, Temperature p_temperature,
Pressure p_pressure) {
//updated 10/22/09 by gmagoon to use BufferedReader; this isn't exactly the most elegant solution (as I have effectively copied code and made this loop through twice in order to correctly count the number of edge species and reactions), but it should save on memory
//IMPORTANT: this code should pass the information needed to perform the same checks as done by the validity testing in the Java code
//much of code below is taken or based off of code from appendUnreactedSpeciesStatus in ReactionSystem.java
//StringBuilder edgeReacInfoString = new StringBuilder();
int edgeReactionCounter = 0;
int edgeSpeciesCounter = 0;
// First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME
edgeID = new HashMap();
LinkedHashSet ur = model.getUnreactedReactionSet();
for (Iterator iur = ur.iterator(); iur.hasNext();) {
edgeReactionCounter++;
Reaction r = (Reaction) iur.next();
String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure);//this line is needed even when not writing to file because it will update edgeID
// edgeReacInfoString.append("\n" + str);
}
edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation)
// For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions
if (validityTester instanceof RateBasedPDepVT) {
//first consider NetReactions (formerly known as PDepNetReactionList)
for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) {
PDepNetwork pdn = (PDepNetwork) iter0.next();
for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
// boolean allCoreReac=true; //flag to check whether all the reactants are in the core;
boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species)
boolean edgeReaction=false;//flag to track whether this is an edge reaction
//first determine the direction that gives unreacted products; this will set the forward flag
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = false; //use the reverse reaction
edgeReaction = true;
}
}
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = true; //use the forward reaction
edgeReaction = true;
}
}
//check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere)
if (edgeReaction){
if(forwardFlag){
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
else{
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
}
//write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species))
if(edgeReaction){
edgeReactionCounter++;
if(forwardFlag){
String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction
// edgeReacInfoString.append("\n" + str);
}
else{
String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction
// edgeReacInfoString.append("\n" + str);
}
}
}
}
//second, consider kLeak of each reaction network so that the validity of each reaction network may be tested
//in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network
//with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants
edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context
for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) {
PDepNetwork pdn = (PDepNetwork)iter1.next();
//account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap
int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product
int[] tempProdArray = {0, 0, 0};
edgeSpeciesCounter++;
tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code
double k = 0.0;
boolean allCoreReac=false;
// double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak
// if (!pdn.isActive() && pdn.getIsChemAct()) {
// k = pdn.getEntryReaction().calculateTotalRate(p_temperature);
// }
if(pdn.getPathReactions().size() == 1 && pdn.getNonincludedReactions().size() == 1 && pdn.getNetReactions().size() == 0){//// If there is only one path reaction (and thus only one nonincluded reaction), use the high-pressure limit rate as the flux rather than the k(T,P) value (cf. PDepNetwork.getLeakFlux())
PDepReaction rxn = pdn.getPathReactions().get(0);
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (!rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else{
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
+ if(allCoreReac){//only consider cases where all reactants are in the core
+ edgeReactionCounter++;
+ }
}
else{
for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork
PDepReaction rxn = iter.next();
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
+ if(allCoreReac){//only consider cases where all reactants are in the core
+ edgeReactionCounter++;
+ }
}
}
- if(allCoreReac){//only consider cases where all reactants are in the core
- edgeReactionCounter++;
- }
}
}
//write the counter (and tolerance) info and go through a second time, this time writing to the buffered writer
try{
//edgeSpeciesCounter = edgeID.size();
bw.write("\n" + termTol + " " + coreTol + "\n" + edgeSpeciesCounter + " " + edgeReactionCounter);
//bw.flush();
// bw.write(edgeReacInfoString);
edgeReactionCounter = 0;
edgeSpeciesCounter = 0;
// First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME
edgeID = new HashMap();
ur = model.getUnreactedReactionSet();
for (Iterator iur = ur.iterator(); iur.hasNext();) {
edgeReactionCounter++;
Reaction r = (Reaction) iur.next();
String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure);
bw.write("\n" + str);
}
edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation)
// For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions
if (validityTester instanceof RateBasedPDepVT) {
//first consider NetReactions (formerly known as PDepNetReactionList)
for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) {
PDepNetwork pdn = (PDepNetwork) iter0.next();
for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
// boolean allCoreReac=true; //flag to check whether all the reactants are in the core;
boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species)
boolean edgeReaction=false;//flag to track whether this is an edge reaction
//first determine the direction that gives unreacted products; this will set the forward flag
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = false; //use the reverse reaction
edgeReaction = true;
}
}
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = true; //use the forward reaction
edgeReaction = true;
}
}
//check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere)
if (edgeReaction){
if(forwardFlag){
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
else{
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
}
//write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species))
if(edgeReaction){
edgeReactionCounter++;
if(forwardFlag){
String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction
bw.write("\n" + str);
}
else{
String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction
bw.write("\n" + str);
}
}
}
}
//6/19/09 gmagoon: original code below; with new P-dep implementation, it would only take into account forward reactions
//if (rxn.isEdgeReaction(model)) {
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
//}
//a potentially simpler approach based on the original approach (however, it seems like isEdgeReaction may return false even if there are some core products along with edge products):
// PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
// if (rxn.isEdgeReaction(model)) {
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
// }
// else if (rxnReverse.isEdgeReaction(model)){
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
// }
//second, consider kLeak of each reaction network so that the validity of each reaction network may be tested
//in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network
//with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants
edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context
for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) {
PDepNetwork pdn = (PDepNetwork)iter1.next();
//account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap
int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product
int[] tempProdArray = {0, 0, 0};
edgeSpeciesCounter++;
tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code
double k = 0.0;
// double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak
// if (!pdn.isActive() && pdn.getIsChemAct()) {
// k = pdn.getEntryReaction().calculateTotalRate(p_temperature);
// }
for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork
PDepReaction rxn = iter.next();
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
boolean allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
if(allCoreReac){//only consider cases where all reactants are in the core
edgeReactionCounter++;
//update the output string with info for kLeak for one PDepNetwork
bw.write("\n" + reacCount + " " + prodCount + " " + tempReacArray[0] + " " + tempReacArray[1] + " " + tempReacArray[2] + " " + tempProdArray[0] + " " + tempProdArray[1] + " " + tempProdArray[2] + " " + k);
}
}
}
}
}
catch(IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
}
public void getConcentrationFlags(ReactionModel p_reactionModel) {
try{
// Add list of flags for constantConcentration
// one for each species, and a final one for the volume
// if 1: DASSL will not change the number of moles of that species (or the volume)
// if 0: DASSL will integrate the ODE as normal
// eg. liquid phase calculations with a constant concentration of O2 (the solubility limit - replenished from the gas phase)
// for normal use, this will be a sequence of '0 's
bw.write("\n");
// This portion of code was commented out by MRH on 21-Jul-2009.
// The indexing of the species in p_reactionModel did not match up with the
// indexing of the species in the SpeciesStatus. When constructing an input
// file for a "ConstantConcentration" ODESolver call, the species whose flux
// was being set to zero was not necessarily the desired species
// for (Iterator iter = p_reactionModel.getSpecies(); iter.hasNext(); ) {
// Species spe = (Species)iter.next();
// if (spe.isConstantConcentration())
// outputString.append("1 ");
// else
// outputString.append("0 ");
// }
// Define boolean variable setVolumeConstant: if any species in the condition.txt
// file has been defined with "ConstantConcentration", set this variable to true.
// This variable will determine if the ODESolver assumes constant volume or not.
boolean setVolumeConstant = false;
int[] tempVector = new int[p_reactionModel.getSpeciesNumber()];
// System.out.println("Debugging line: p_reactionModel.getSpeciesNumber(): "+p_reactionModel.getSpeciesNumber());
// System.out.println("Debugging line: IDTranslator.size(): "+IDTranslator.size());
// Iterator j = IDTranslator.keySet().iterator();
// while (j.hasNext()){
// Species spec = (Species)j.next();
// Integer id = (Integer)IDTranslator.get(j);
// System.out.println("Debugging line: " + spec + " " + id);
// }
for (Iterator iter = p_reactionModel.getSpecies(); iter.hasNext(); ) {
Species spe = (Species)iter.next();
int id = getRealID(spe);
// Previous line is due to species order in p_reactionModel not necessarily being
// sequential. We read in the species RealID (which is what is read in during
// the other functions when writing the ODESolver input file) and associate a +1
// with a "ConstantConcentration" species and a 0 for all others
if (spe.isConstantConcentration()) {
tempVector[id-1] = 1;
setVolumeConstant = true;
} else {
tempVector[id-1] = 0;
}
}
// Append the constant concentration flags to the outputString
for (int i=0; i<tempVector.length; i++) {
bw.write(tempVector[i] + " ");
}
if (setVolumeConstant) bw.write("1 \n");
else bw.write("0 \n"); // for liquid EOS or constant volume this should be 1
}
catch (IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
}
//6/24/09 gmagoon: this totals the first n-state elements of y (i.e. the non-inert concentrations)
public double totalNonInertConcentrations(){
double totalNonInertConc=0;
for(int i=0; i< nState ; i++){
totalNonInertConc+=y[i];
}
return totalNonInertConc;
}
// set up the input file
public void setupInputFile(){
File SolverInput = new File("ODESolver/SolverInput.dat");
try {
fw = new FileWriter(SolverInput);
bw = new BufferedWriter(fw);
// fw.write(outputString.toString());
// fw.close();
} catch (IOException e) {
System.err.println("Problem creating Solver Input File!");
e.printStackTrace();
}
}
}
| false | true | public void getAutoEdgeReactionInfo(CoreEdgeReactionModel model, Temperature p_temperature,
Pressure p_pressure) {
//updated 10/22/09 by gmagoon to use BufferedReader; this isn't exactly the most elegant solution (as I have effectively copied code and made this loop through twice in order to correctly count the number of edge species and reactions), but it should save on memory
//IMPORTANT: this code should pass the information needed to perform the same checks as done by the validity testing in the Java code
//much of code below is taken or based off of code from appendUnreactedSpeciesStatus in ReactionSystem.java
//StringBuilder edgeReacInfoString = new StringBuilder();
int edgeReactionCounter = 0;
int edgeSpeciesCounter = 0;
// First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME
edgeID = new HashMap();
LinkedHashSet ur = model.getUnreactedReactionSet();
for (Iterator iur = ur.iterator(); iur.hasNext();) {
edgeReactionCounter++;
Reaction r = (Reaction) iur.next();
String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure);//this line is needed even when not writing to file because it will update edgeID
// edgeReacInfoString.append("\n" + str);
}
edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation)
// For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions
if (validityTester instanceof RateBasedPDepVT) {
//first consider NetReactions (formerly known as PDepNetReactionList)
for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) {
PDepNetwork pdn = (PDepNetwork) iter0.next();
for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
// boolean allCoreReac=true; //flag to check whether all the reactants are in the core;
boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species)
boolean edgeReaction=false;//flag to track whether this is an edge reaction
//first determine the direction that gives unreacted products; this will set the forward flag
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = false; //use the reverse reaction
edgeReaction = true;
}
}
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = true; //use the forward reaction
edgeReaction = true;
}
}
//check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere)
if (edgeReaction){
if(forwardFlag){
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
else{
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
}
//write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species))
if(edgeReaction){
edgeReactionCounter++;
if(forwardFlag){
String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction
// edgeReacInfoString.append("\n" + str);
}
else{
String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction
// edgeReacInfoString.append("\n" + str);
}
}
}
}
//second, consider kLeak of each reaction network so that the validity of each reaction network may be tested
//in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network
//with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants
edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context
for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) {
PDepNetwork pdn = (PDepNetwork)iter1.next();
//account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap
int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product
int[] tempProdArray = {0, 0, 0};
edgeSpeciesCounter++;
tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code
double k = 0.0;
boolean allCoreReac=false;
// double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak
// if (!pdn.isActive() && pdn.getIsChemAct()) {
// k = pdn.getEntryReaction().calculateTotalRate(p_temperature);
// }
if(pdn.getPathReactions().size() == 1 && pdn.getNonincludedReactions().size() == 1 && pdn.getNetReactions().size() == 0){//// If there is only one path reaction (and thus only one nonincluded reaction), use the high-pressure limit rate as the flux rather than the k(T,P) value (cf. PDepNetwork.getLeakFlux())
PDepReaction rxn = pdn.getPathReactions().get(0);
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (!rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else{
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
}
else{
for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork
PDepReaction rxn = iter.next();
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
}
}
if(allCoreReac){//only consider cases where all reactants are in the core
edgeReactionCounter++;
}
}
}
//write the counter (and tolerance) info and go through a second time, this time writing to the buffered writer
try{
//edgeSpeciesCounter = edgeID.size();
bw.write("\n" + termTol + " " + coreTol + "\n" + edgeSpeciesCounter + " " + edgeReactionCounter);
//bw.flush();
// bw.write(edgeReacInfoString);
edgeReactionCounter = 0;
edgeSpeciesCounter = 0;
// First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME
edgeID = new HashMap();
ur = model.getUnreactedReactionSet();
for (Iterator iur = ur.iterator(); iur.hasNext();) {
edgeReactionCounter++;
Reaction r = (Reaction) iur.next();
String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure);
bw.write("\n" + str);
}
edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation)
// For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions
if (validityTester instanceof RateBasedPDepVT) {
//first consider NetReactions (formerly known as PDepNetReactionList)
for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) {
PDepNetwork pdn = (PDepNetwork) iter0.next();
for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
// boolean allCoreReac=true; //flag to check whether all the reactants are in the core;
boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species)
boolean edgeReaction=false;//flag to track whether this is an edge reaction
//first determine the direction that gives unreacted products; this will set the forward flag
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = false; //use the reverse reaction
edgeReaction = true;
}
}
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = true; //use the forward reaction
edgeReaction = true;
}
}
//check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere)
if (edgeReaction){
if(forwardFlag){
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
else{
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
}
//write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species))
if(edgeReaction){
edgeReactionCounter++;
if(forwardFlag){
String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction
bw.write("\n" + str);
}
else{
String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction
bw.write("\n" + str);
}
}
}
}
//6/19/09 gmagoon: original code below; with new P-dep implementation, it would only take into account forward reactions
//if (rxn.isEdgeReaction(model)) {
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
//}
//a potentially simpler approach based on the original approach (however, it seems like isEdgeReaction may return false even if there are some core products along with edge products):
// PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
// if (rxn.isEdgeReaction(model)) {
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
// }
// else if (rxnReverse.isEdgeReaction(model)){
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
// }
//second, consider kLeak of each reaction network so that the validity of each reaction network may be tested
//in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network
//with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants
edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context
for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) {
PDepNetwork pdn = (PDepNetwork)iter1.next();
//account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap
int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product
int[] tempProdArray = {0, 0, 0};
edgeSpeciesCounter++;
tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code
double k = 0.0;
// double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak
// if (!pdn.isActive() && pdn.getIsChemAct()) {
// k = pdn.getEntryReaction().calculateTotalRate(p_temperature);
// }
for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork
PDepReaction rxn = iter.next();
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
boolean allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
if(allCoreReac){//only consider cases where all reactants are in the core
edgeReactionCounter++;
//update the output string with info for kLeak for one PDepNetwork
bw.write("\n" + reacCount + " " + prodCount + " " + tempReacArray[0] + " " + tempReacArray[1] + " " + tempReacArray[2] + " " + tempProdArray[0] + " " + tempProdArray[1] + " " + tempProdArray[2] + " " + k);
}
}
}
}
}
catch(IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
}
| public void getAutoEdgeReactionInfo(CoreEdgeReactionModel model, Temperature p_temperature,
Pressure p_pressure) {
//updated 10/22/09 by gmagoon to use BufferedReader; this isn't exactly the most elegant solution (as I have effectively copied code and made this loop through twice in order to correctly count the number of edge species and reactions), but it should save on memory
//IMPORTANT: this code should pass the information needed to perform the same checks as done by the validity testing in the Java code
//much of code below is taken or based off of code from appendUnreactedSpeciesStatus in ReactionSystem.java
//StringBuilder edgeReacInfoString = new StringBuilder();
int edgeReactionCounter = 0;
int edgeSpeciesCounter = 0;
// First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME
edgeID = new HashMap();
LinkedHashSet ur = model.getUnreactedReactionSet();
for (Iterator iur = ur.iterator(); iur.hasNext();) {
edgeReactionCounter++;
Reaction r = (Reaction) iur.next();
String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure);//this line is needed even when not writing to file because it will update edgeID
// edgeReacInfoString.append("\n" + str);
}
edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation)
// For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions
if (validityTester instanceof RateBasedPDepVT) {
//first consider NetReactions (formerly known as PDepNetReactionList)
for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) {
PDepNetwork pdn = (PDepNetwork) iter0.next();
for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
// boolean allCoreReac=true; //flag to check whether all the reactants are in the core;
boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species)
boolean edgeReaction=false;//flag to track whether this is an edge reaction
//first determine the direction that gives unreacted products; this will set the forward flag
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = false; //use the reverse reaction
edgeReaction = true;
}
}
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = true; //use the forward reaction
edgeReaction = true;
}
}
//check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere)
if (edgeReaction){
if(forwardFlag){
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
else{
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
}
//write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species))
if(edgeReaction){
edgeReactionCounter++;
if(forwardFlag){
String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction
// edgeReacInfoString.append("\n" + str);
}
else{
String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction
// edgeReacInfoString.append("\n" + str);
}
}
}
}
//second, consider kLeak of each reaction network so that the validity of each reaction network may be tested
//in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network
//with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants
edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context
for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) {
PDepNetwork pdn = (PDepNetwork)iter1.next();
//account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap
int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product
int[] tempProdArray = {0, 0, 0};
edgeSpeciesCounter++;
tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code
double k = 0.0;
boolean allCoreReac=false;
// double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak
// if (!pdn.isActive() && pdn.getIsChemAct()) {
// k = pdn.getEntryReaction().calculateTotalRate(p_temperature);
// }
if(pdn.getPathReactions().size() == 1 && pdn.getNonincludedReactions().size() == 1 && pdn.getNetReactions().size() == 0){//// If there is only one path reaction (and thus only one nonincluded reaction), use the high-pressure limit rate as the flux rather than the k(T,P) value (cf. PDepNetwork.getLeakFlux())
PDepReaction rxn = pdn.getPathReactions().get(0);
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (!rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else{
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
if(allCoreReac){//only consider cases where all reactants are in the core
edgeReactionCounter++;
}
}
else{
for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork
PDepReaction rxn = iter.next();
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
if(allCoreReac){//only consider cases where all reactants are in the core
edgeReactionCounter++;
}
}
}
}
}
//write the counter (and tolerance) info and go through a second time, this time writing to the buffered writer
try{
//edgeSpeciesCounter = edgeID.size();
bw.write("\n" + termTol + " " + coreTol + "\n" + edgeSpeciesCounter + " " + edgeReactionCounter);
//bw.flush();
// bw.write(edgeReacInfoString);
edgeReactionCounter = 0;
edgeSpeciesCounter = 0;
// First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME
edgeID = new HashMap();
ur = model.getUnreactedReactionSet();
for (Iterator iur = ur.iterator(); iur.hasNext();) {
edgeReactionCounter++;
Reaction r = (Reaction) iur.next();
String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure);
bw.write("\n" + str);
}
edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation)
// For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions
if (validityTester instanceof RateBasedPDepVT) {
//first consider NetReactions (formerly known as PDepNetReactionList)
for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) {
PDepNetwork pdn = (PDepNetwork) iter0.next();
for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) {
PDepReaction rxn = (PDepReaction) iter.next();
// boolean allCoreReac=true; //flag to check whether all the reactants are in the core;
boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species)
boolean edgeReaction=false;//flag to track whether this is an edge reaction
//first determine the direction that gives unreacted products; this will set the forward flag
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = false; //use the reverse reaction
edgeReaction = true;
}
}
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if (model.containsAsUnreactedSpecies(species)){
forwardFlag = true; //use the forward reaction
edgeReaction = true;
}
}
//check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere)
if (edgeReaction){
if(forwardFlag){
for (int j = 0; j < rxn.getReactantNumber(); j++) {
Species species = (Species) rxn.getReactantList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
else{
for (int j = 0; j < rxn.getProductNumber(); j++) {
Species species = (Species) rxn.getProductList().get(j);
if(!model.containsAsReactedSpecies(species)) edgeReaction = false;
}
}
}
//write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species))
if(edgeReaction){
edgeReactionCounter++;
if(forwardFlag){
String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction
bw.write("\n" + str);
}
else{
String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction
bw.write("\n" + str);
}
}
}
}
//6/19/09 gmagoon: original code below; with new P-dep implementation, it would only take into account forward reactions
//if (rxn.isEdgeReaction(model)) {
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
//}
//a potentially simpler approach based on the original approach (however, it seems like isEdgeReaction may return false even if there are some core products along with edge products):
// PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
// if (rxn.isEdgeReaction(model)) {
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
// }
// else if (rxnReverse.isEdgeReaction(model)){
// edgeReactionCounter++;
// String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);
// edgeReacInfoString.append("\n" + str);
// }
//second, consider kLeak of each reaction network so that the validity of each reaction network may be tested
//in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network
//with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants
edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context
for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) {
PDepNetwork pdn = (PDepNetwork)iter1.next();
//account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap
int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product
int[] tempProdArray = {0, 0, 0};
edgeSpeciesCounter++;
tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code
double k = 0.0;
// double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak
// if (!pdn.isActive() && pdn.getIsChemAct()) {
// k = pdn.getEntryReaction().calculateTotalRate(p_temperature);
// }
for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork
PDepReaction rxn = iter.next();
int reacCount=0;
int[] tempReacArray = {0, 0, 0};
boolean allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core
if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){
k = rxn.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){
PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction();
k = rxnReverse.calculateRate(p_temperature, p_pressure);
allCoreReac=true;
//iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants
for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) {
reacCount++;
Species spe = (Species)rIter.next();
if(model.containsAsReactedSpecies(spe)){
tempReacArray[reacCount-1]=getRealID(spe);
}
else{
allCoreReac=false;
}
}
}
if(allCoreReac){//only consider cases where all reactants are in the core
edgeReactionCounter++;
//update the output string with info for kLeak for one PDepNetwork
bw.write("\n" + reacCount + " " + prodCount + " " + tempReacArray[0] + " " + tempReacArray[1] + " " + tempReacArray[2] + " " + tempProdArray[0] + " " + tempProdArray[1] + " " + tempProdArray[2] + " " + k);
}
}
}
}
}
catch(IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
}
|
diff --git a/midas-webapp/src/java/com/robonobo/midas/controller/RecentActivityController.java b/midas-webapp/src/java/com/robonobo/midas/controller/RecentActivityController.java
index 6f42dfc..2a2de5c 100644
--- a/midas-webapp/src/java/com/robonobo/midas/controller/RecentActivityController.java
+++ b/midas-webapp/src/java/com/robonobo/midas/controller/RecentActivityController.java
@@ -1,43 +1,44 @@
package com.robonobo.midas.controller;
import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.robonobo.midas.model.MidasPlaylist;
import com.robonobo.remote.service.MidasService;
@Controller
public class RecentActivityController extends BaseController {
@Autowired
MidasService midas;
/**
* Gives stream ids that have been on recently-updated playlists, one per line (text/plain response type)
*/
@RequestMapping("/recent-activity")
public void showStreamIdsOnRecentPlaylists(@RequestParam(value = "maxAgeMs", required = false) Long maxAgeMs,
HttpServletRequest req, HttpServletResponse resp) throws IOException {
long tenMinsInMs = (long) (10 * 60 * 1000);
if(maxAgeMs == null || maxAgeMs > tenMinsInMs)
maxAgeMs = tenMinsInMs;
List<MidasPlaylist> playlists = midas.getRecentPlaylists(maxAgeMs);
Set<String> streamIds = new HashSet<String>();
for (MidasPlaylist pl : playlists) {
streamIds.addAll(pl.getStreamIds());
}
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
PrintWriter out = new PrintWriter(resp.getOutputStream());
for (String sid : streamIds) {
out.println(sid);
}
+ out.close();
}
}
| true | true | public void showStreamIdsOnRecentPlaylists(@RequestParam(value = "maxAgeMs", required = false) Long maxAgeMs,
HttpServletRequest req, HttpServletResponse resp) throws IOException {
long tenMinsInMs = (long) (10 * 60 * 1000);
if(maxAgeMs == null || maxAgeMs > tenMinsInMs)
maxAgeMs = tenMinsInMs;
List<MidasPlaylist> playlists = midas.getRecentPlaylists(maxAgeMs);
Set<String> streamIds = new HashSet<String>();
for (MidasPlaylist pl : playlists) {
streamIds.addAll(pl.getStreamIds());
}
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
PrintWriter out = new PrintWriter(resp.getOutputStream());
for (String sid : streamIds) {
out.println(sid);
}
}
| public void showStreamIdsOnRecentPlaylists(@RequestParam(value = "maxAgeMs", required = false) Long maxAgeMs,
HttpServletRequest req, HttpServletResponse resp) throws IOException {
long tenMinsInMs = (long) (10 * 60 * 1000);
if(maxAgeMs == null || maxAgeMs > tenMinsInMs)
maxAgeMs = tenMinsInMs;
List<MidasPlaylist> playlists = midas.getRecentPlaylists(maxAgeMs);
Set<String> streamIds = new HashSet<String>();
for (MidasPlaylist pl : playlists) {
streamIds.addAll(pl.getStreamIds());
}
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
PrintWriter out = new PrintWriter(resp.getOutputStream());
for (String sid : streamIds) {
out.println(sid);
}
out.close();
}
|
diff --git a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/bookmark/internal/BookmarkUtility.java b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/bookmark/internal/BookmarkUtility.java
index c88c4efed8..e3f385d92e 100644
--- a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/bookmark/internal/BookmarkUtility.java
+++ b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/bookmark/internal/BookmarkUtility.java
@@ -1,670 +1,673 @@
/*******************************************************************************
* Copyright (c) 2010 BSI Business Systems Integration AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipse.scout.rt.client.services.common.bookmark.internal;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.TreeMap;
import java.util.zip.CRC32;
import org.eclipse.scout.commons.CompareUtility;
import org.eclipse.scout.commons.CompositeObject;
import org.eclipse.scout.commons.exception.ProcessingException;
import org.eclipse.scout.rt.client.ui.basic.table.ColumnSet;
import org.eclipse.scout.rt.client.ui.basic.table.ITable;
import org.eclipse.scout.rt.client.ui.basic.table.ITableRow;
import org.eclipse.scout.rt.client.ui.basic.table.columns.IColumn;
import org.eclipse.scout.rt.client.ui.basic.table.customizer.ITableCustomizer;
import org.eclipse.scout.rt.client.ui.desktop.IDesktop;
import org.eclipse.scout.rt.client.ui.desktop.outline.IOutline;
import org.eclipse.scout.rt.client.ui.desktop.outline.pages.IPage;
import org.eclipse.scout.rt.client.ui.desktop.outline.pages.IPageWithNodes;
import org.eclipse.scout.rt.client.ui.desktop.outline.pages.IPageWithTable;
import org.eclipse.scout.rt.client.ui.desktop.outline.pages.ISearchForm;
import org.eclipse.scout.rt.client.ui.form.IForm;
import org.eclipse.scout.rt.shared.services.common.bookmark.AbstractPageState;
import org.eclipse.scout.rt.shared.services.common.bookmark.Bookmark;
import org.eclipse.scout.rt.shared.services.common.bookmark.NodePageState;
import org.eclipse.scout.rt.shared.services.common.bookmark.TableColumnState;
import org.eclipse.scout.rt.shared.services.common.bookmark.TablePageState;
import org.eclipse.scout.rt.shared.services.common.jdbc.SearchFilter;
public final class BookmarkUtility {
private BookmarkUtility() {
}
public static IOutline resolveOutline(IOutline[] outlines, String className) {
if (className == null) {
return null;
}
// pass 1: fully qualified name
for (IOutline o : outlines) {
if (o.getClass().getName().equals(className)) {
return o;
}
}
// pass 2: simple name, not case sensitive
String simpleClassName = className.replaceAll("^.*\\.", "");
for (IOutline o : outlines) {
if (o.getClass().getSimpleName().equalsIgnoreCase(simpleClassName)) {
return o;
}
}
return null;
}
/**
* @param columns
* is the set of available columns to search in
* @param className
* is the columnId, simple class name or class name of the columns to find
*/
public static IColumn resolveColumn(IColumn[] columns, String identifier) {
if (identifier == null) {
return null;
}
// pass 1: fully qualified name
for (IColumn c : columns) {
if (identifier.equals(c.getClass().getName())) {
return c;
}
}
// pass 2: columnId
for (IColumn c : columns) {
if (identifier.equals(c.getColumnId())) {
return c;
}
}
// pass 3: simple name, not case sensitive
String simpleClassName = identifier.replaceAll("^.*\\.", "");
for (IColumn c : columns) {
if (simpleClassName.equalsIgnoreCase(c.getClass().getSimpleName())) {
return c;
}
}
return null;
}
public static IPage resolvePage(IPage[] pages, String className, String bookmarkIdentifier) {
if (className == null) {
return null;
}
TreeMap<CompositeObject, IPage> sortMap = new TreeMap<CompositeObject, IPage>();
String simpleClassName = className.replaceAll("^.*\\.", "");
int index = 0;
for (IPage p : pages) {
int i1 = 0;
int i2 = 0;
if (p.getClass().getName().equals(className)) {
i1 = -2;
}
else if (p.getClass().getSimpleName().equalsIgnoreCase(simpleClassName)) {
i1 = -1;
}
if (bookmarkIdentifier == null || bookmarkIdentifier.equalsIgnoreCase(p.getUserPreferenceContext())) {
i2 = -1;
}
sortMap.put(new CompositeObject(i1, i2, index), p);
index++;
}
if (sortMap.size() > 0) {
return sortMap.get(sortMap.firstKey());
}
else {
return null;
}
}
/**
* intercept objects that are not remoting-capable or not serializable and
* replace by strings
*/
public static Object[] makeSerializableKeys(Object[] a) {
return (Object[]) makeSerializableKey(a);
}
public static Object makeSerializableKey(Object o) {
if (o == null) {
return o;
}
else if (o instanceof Number) {
return o;
}
else if (o instanceof String) {
return o;
}
else if (o instanceof Boolean) {
return o;
}
else if (o instanceof Date) {
return o;
}
else if (o.getClass().isArray()) {
ArrayList<Integer> dimList = new ArrayList<Integer>();
Class xc = o.getClass();
Object xo = o;
while (xc.isArray()) {
int len = xo != null ? Array.getLength(xo) : 0;
dimList.add(len);
xc = xc.getComponentType();
if (xo != null && len > 0) {
xo = Array.get(xo, 0);
}
}
int[] dim = new int[dimList.size()];
for (int i = 0; i < dim.length; i++) {
dim[i] = dimList.get(i);
}
Object b = Array.newInstance(makeSerializableClass(xc), dim);
for (int i = 0; i < dim[0]; i++) {
Array.set(b, i, makeSerializableKey(Array.get(o, i)));
}
return b;
}
else {
return o.toString();
}
}
/**
* return String.class for classes that are not remoting-capable or not
* serializable
*/
public static Class makeSerializableClass(Class c) {
if (c == null) {
throw new IllegalArgumentException("class must not be null");
}
if (c.isArray()) {
throw new IllegalArgumentException("class must not be an array class");
}
if (c.isPrimitive()) {
return c;
}
else if (Number.class.isAssignableFrom(c)) {
return c;
}
else if (String.class.isAssignableFrom(c)) {
return c;
}
else if (Boolean.class.isAssignableFrom(c)) {
return c;
}
else if (Date.class.isAssignableFrom(c)) {
return c;
}
else if (Object.class == c) {
return c;
}
else {
return String.class;
}
}
public static void activateBookmark(IDesktop desktop, Bookmark bm, boolean forceReload) throws ProcessingException {
if (bm.getOutlineClassName() == null) {
return;
}
IOutline outline = BookmarkUtility.resolveOutline(desktop.getAvailableOutlines(), bm.getOutlineClassName());
if (outline == null) {
throw new ProcessingException("outline '" + bm.getOutlineClassName() + "' was not found");
}
if (!(outline.isVisible() && outline.isEnabled())) {
throw new ProcessingException("activate outline " + outline.getTitle() + " denied");
}
desktop.setOutline(outline);
try {
outline.setTreeChanging(true);
//
IPage parentPage = outline.getRootPage();
boolean pathFullyRestored = true;
List<AbstractPageState> path = bm.getPath();
AbstractPageState parentPageState = path.get(0);
for (int i = 1; i < path.size(); i++) {
// try to find correct child page (next parentPage)
IPage childPage = null;
AbstractPageState childState = path.get(i);
if (parentPageState instanceof TablePageState) {
TablePageState tablePageState = (TablePageState) parentPageState;
if (parentPage instanceof IPageWithTable) {
IPageWithTable tablePage = (IPageWithTable) parentPage;
childPage = bmLoadTablePage(tablePage, tablePageState, false);
}
}
else if (parentPageState instanceof NodePageState) {
NodePageState nodePageState = (NodePageState) parentPageState;
if (parentPage instanceof IPageWithNodes) {
IPageWithNodes nodePage = (IPageWithNodes) parentPage;
childPage = bmLoadNodePage(nodePage, nodePageState, childState);
}
}
// next
if (childPage != null) {
parentPage = childPage;
parentPageState = childState;
}
else if (i + 1 < path.size()) {
pathFullyRestored = false;
break;
}
}
if (pathFullyRestored) {
if (parentPageState instanceof TablePageState && parentPage instanceof IPageWithTable) {
bmLoadTablePage((IPageWithTable) parentPage, (TablePageState) parentPageState, true);
}
else if (parentPage instanceof IPageWithNodes) {
bmLoadNodePage((IPageWithNodes) parentPage, (NodePageState) parentPageState, null);
}
}
/*
* Expansions of the restored tree path
*/
IPage p = parentPage;
// last element
if (pathFullyRestored && parentPageState.isExpanded() != null) {
p.setExpanded(parentPageState.isExpanded());
}
else {
if (!(p instanceof IPageWithTable)) {
p.setExpanded(true);
}
}
// ancestor elements
p = p.getParentPage();
while (p != null) {
p.setExpanded(true);
p = p.getParentPage();
}
outline.selectNode(parentPage, false);
}
finally {
outline.setTreeChanging(false);
}
}
public static Bookmark createBookmark(IDesktop desktop) throws ProcessingException {
IOutline outline = desktop.getOutline();
if (outline != null) {
IPage activePage = outline.getActivePage();
if (activePage != null) {
Bookmark b = new Bookmark();
b.setIconId(activePage.getCell().getIconId());
// outline
b.setOutlineClassName(outline.getClass().getName());
ArrayList<IPage> path = new ArrayList<IPage>();
ArrayList<String> titleSegments = new ArrayList<String>();
IPage page = activePage;
while (page != null) {
path.add(0, page);
String s = page.getCell().getText();
if (s != null) {
titleSegments.add(0, s);
}
// next
page = (IPage) page.getParentNode();
}
if (outline.getTitle() != null) {
titleSegments.add(0, outline.getTitle());
}
// title
int len = 0;
if (titleSegments.size() > 0) {
len += titleSegments.get(0).length();
}
if (titleSegments.size() > 1) {
len += titleSegments.get(titleSegments.size() - 1).length();
}
for (int i = titleSegments.size() - 1; i > 0; i--) {
if (len > 200) {
titleSegments.remove(i);
}
else if (len + titleSegments.get(i).length() <= 200) {
len += titleSegments.get(i).length();
}
else {
titleSegments.set(i, "...");
len = 201;
}
}
StringBuilder buf = new StringBuilder();
for (String s : titleSegments) {
if (buf.length() > 0) {
buf.append(" - ");
}
buf.append(s);
}
b.setTitle(buf.toString());
// text
StringBuffer text = new StringBuffer();
// add constraints texts
String prefix = "";
for (int i = 0; i < path.size(); i++) {
page = path.get(i);
if (i > 0 || outline.isRootNodeVisible()) {
text.append(prefix + page.getCell().getText());
text.append("\n");
if (page instanceof IPageWithTable) {
IPageWithTable tablePage = (IPageWithTable) page;
SearchFilter search = tablePage.getSearchFilter();
if (search != null) {
for (String s : search.getDisplayTexts()) {
if (s != null) {
String indent = prefix + " ";
s = s.trim().replaceAll("[\\n]", "\n" + indent);
if (s.length() > 0) {
text.append(indent + s);
text.append("\n");
}
}
}
}
}
prefix += " ";
}
}
b.setText(text.toString().trim());
// path
for (int i = 0; i < path.size(); i++) {
page = path.get(i);
if (page instanceof IPageWithTable) {
IPageWithTable tablePage = (IPageWithTable) page;
IPage childPage = null;
if (i + 1 < path.size()) {
childPage = path.get(i + 1);
}
b.addPathElement(bmStoreTablePage(tablePage, childPage));
}
else if (page instanceof IPageWithNodes) {
IPageWithNodes nodePage = (IPageWithNodes) page;
b.addPathElement(bmStoreNodePage(nodePage));
}
}
return b;
}
}
return null;
}
@SuppressWarnings("deprecation")
private static IPage bmLoadTablePage(IPageWithTable tablePage, TablePageState tablePageState, boolean leafState) throws ProcessingException {
ITable table = tablePage.getTable();
if (tablePageState.getTableCustomizerData() != null && tablePage.getTable().getTableCustomizer() != null) {
byte[] newData = tablePageState.getTableCustomizerData();
ITableCustomizer tc = tablePage.getTable().getTableCustomizer();
byte[] curData = tc.getSerializedData();
if (!CompareUtility.equals(curData, newData)) {
tc.removeAllColumns();
tc.setSerializedData(tablePageState.getTableCustomizerData());
tablePage.getTable().resetColumnConfiguration();
tablePage.setChildrenLoaded(false);
}
}
// starts search form
tablePage.getSearchFilter();
ColumnSet cs = table.getColumnSet();
// setup table
try {
table.setTableChanging(true);
//legacy support
List<TableColumnState> allColumns = tablePageState.getVisibleColumns();
if (allColumns == null || allColumns.size() == 0) {
allColumns = tablePageState.getAvailableColumns();
}
if (allColumns != null && allColumns.size() > 0) {
// visible columns and width
ArrayList<IColumn> visibleColumns = new ArrayList<IColumn>();
for (TableColumnState colState : allColumns) {
//legacy support: null=true
if (colState.getVisible() == null || colState.getVisible()) {
IColumn col = resolveColumn(cs.getDisplayableColumns(), colState.getClassName());
if (col != null && col.isDisplayable()) {
if (colState.getWidth() > 0) {
col.setWidth(colState.getWidth());
}
visibleColumns.add(col);
}
}
}
List<IColumn> existingVisibleCols = Arrays.asList(cs.getVisibleColumns());
if (!existingVisibleCols.equals(visibleColumns)) {
cs.setVisibleColumns(visibleColumns.toArray(new IColumn[0]));
}
// filters
if (tablePage.getTable().getColumnFilterManager() != null) {
for (TableColumnState colState : allColumns) {
if (colState.getColumnFilterData() != null) {
IColumn col = BookmarkUtility.resolveColumn(cs.getColumns(), colState.getClassName());
if (col != null) {
tablePage.getTable().getColumnFilterManager().setSerializedFilter(colState.getColumnFilterData(), col);
}
}
}
}
//sort order (only respect visible and user-sort columns)
boolean userSortValid = true;
TreeMap<Integer, IColumn> sortColMap = new TreeMap<Integer, IColumn>();
HashMap<IColumn, Boolean> sortColAscMap = new HashMap<IColumn, Boolean>();
for (TableColumnState colState : allColumns) {
if (colState.getSortOrder() >= 0) {
IColumn col = BookmarkUtility.resolveColumn(cs.getColumns(), colState.getClassName());
if (col != null) {
sortColMap.put(colState.getSortOrder(), col);
sortColAscMap.put(col, colState.isSortAscending());
if (col.getSortIndex() != colState.getSortOrder()) {
userSortValid = false;
}
if (col.isSortAscending() != colState.isSortAscending()) {
userSortValid = false;
}
}
}
}
HashSet<IColumn<?>> existingExplicitUserSortCols = new HashSet<IColumn<?>>();
for (IColumn<?> c : cs.getUserSortColumns()) {
if (c.isSortExplicit()) {
existingExplicitUserSortCols.add(c);
}
}
if (!sortColMap.values().containsAll(existingExplicitUserSortCols)) {
userSortValid = false;
}
if (!userSortValid) {
cs.clearSortColumns();
for (IColumn col : sortColMap.values()) {
cs.addSortColumn(col, sortColAscMap.get(col));
}
table.sort();
}
}
}
finally {
table.setTableChanging(false);
}
// setup search
if (tablePageState.getSearchFormState() != null) {
ISearchForm searchForm = tablePage.getSearchFormInternal();
if (searchForm != null) {
boolean doSearch = true;
String newSearchFilterState = tablePageState.getSearchFilterState();
String oldSearchFilterState = "" + createSearchFilterCRC(searchForm.getSearchFilter());
if (CompareUtility.equals(oldSearchFilterState, newSearchFilterState)) {
String newSearchFormState = tablePageState.getSearchFormState();
String oldSearchFormState = searchForm.getXML("UTF-8");
if (CompareUtility.equals(oldSearchFormState, newSearchFormState)) {
doSearch = false;
}
}
// in case search form is in correct state, but no search has been executed, force search
if (tablePage.getTable().getRowCount() == 0) {
doSearch = true;
}
if (doSearch) {
searchForm.setXML(tablePageState.getSearchFormState());
if (tablePageState.isSearchFilterComplete()) {
searchForm.doSaveWithoutMarkerChange();
}
}
}
}
IPage childPage = null;
boolean loadChildren = !leafState;
if (tablePage.isChildrenDirty() || tablePage.isChildrenVolatile()) {
loadChildren = true;
tablePage.setChildrenLoaded(false);
}
if (loadChildren) {
tablePage.ensureChildrenLoaded();
tablePage.setChildrenDirty(false);
CompositeObject childPk = tablePageState.getExpandedChildPrimaryKey();
if (childPk != null) {
for (int r = 0; r < table.getRowCount(); r++) {
CompositeObject testPk = new CompositeObject(BookmarkUtility.makeSerializableKeys(table.getRowKeys(r)));
if (testPk.equals(childPk)) {
if (r < tablePage.getChildNodeCount()) {
childPage = tablePage.getChildPage(r);
}
break;
}
}
}
else {
if (tablePage.getChildNodeCount() > 0) {
childPage = tablePage.getChildPage(0);
}
}
}
// load selections
if (leafState) {
if (tablePageState.getSelectedChildrenPrimaryKeys().size() > 0) {
tablePage.ensureChildrenLoaded();
HashSet<CompositeObject> selectionSet = new HashSet<CompositeObject>(tablePageState.getSelectedChildrenPrimaryKeys());
ArrayList<ITableRow> rowList = new ArrayList<ITableRow>();
for (ITableRow row : table.getRows()) {
CompositeObject testPk = new CompositeObject(BookmarkUtility.makeSerializableKeys(row.getKeyValues()));
if (selectionSet.contains(testPk)) {
- rowList.add(row);
+ //row must not be filtered out
+ if (row.isFilterAccepted()) {
+ rowList.add(row);
+ }
}
}
if (rowList.size() > 0) {
table.selectRows(rowList.toArray(new ITableRow[0]));
}
}
}
return childPage;
}
private static IPage bmLoadNodePage(IPageWithNodes nodePage, NodePageState nodePageState, AbstractPageState childState) throws ProcessingException {
IPage childPage = null;
if (childState != null) {
nodePage.ensureChildrenLoaded();
IPage p = BookmarkUtility.resolvePage(nodePage.getChildPages(), childState.getPageClassName(), childState.getBookmarkIdentifier());
if (p != null) {
childPage = p;
}
}
return childPage;
}
private static TablePageState bmStoreTablePage(IPageWithTable page, IPage childPage) throws ProcessingException {
ITable table = page.getTable();
ColumnSet cs = table.getColumnSet();
TablePageState state = new TablePageState();
state.setPageClassName(page.getClass().getName());
state.setBookmarkIdentifier(page.getUserPreferenceContext());
state.setLabel(page.getCell().getText());
state.setExpanded(page.isExpanded());
IForm searchForm = page.getSearchFormInternal();
if (searchForm != null) {
state.setSearchFormState(searchForm.getXML("UTF-8"));
state.setSearchFilterState(searchForm.getSearchFilter().isCompleted(), "" + createSearchFilterCRC(searchForm.getSearchFilter()));
}
if (page.getTable().getTableCustomizer() != null) {
state.setTableCustomizerData(page.getTable().getTableCustomizer().getSerializedData());
}
ArrayList<TableColumnState> allColumns = new ArrayList<TableColumnState>();
//add all columns but in user order
for (IColumn<?> c : cs.getAllColumnsInUserOrder()) {
TableColumnState colState = new TableColumnState();
colState.setColumnClassName(c.getColumnId());
colState.setDisplayable(c.isDisplayable());
colState.setVisible(c.isDisplayable() && c.isVisible());
colState.setWidth(c.getWidth());
if (cs.isUserSortColumn(c) && c.isSortExplicit()) {
int sortOrder = cs.getSortColumnIndex(c);
if (sortOrder >= 0) {
colState.setSortOrder(sortOrder);
colState.setSortAscending(c.isSortAscending());
}
else {
colState.setSortOrder(-1);
}
}
if (page.getTable().getColumnFilterManager() != null && c.isColumnFilterActive()) {
colState.setColumnFilterData(page.getTable().getColumnFilterManager().getSerializedFilter(c));
}
allColumns.add(colState);
}
state.setAvailableColumns(allColumns);
//
ArrayList<CompositeObject> pkList = new ArrayList<CompositeObject>();
for (ITableRow row : table.getSelectedRows()) {
pkList.add(new CompositeObject(BookmarkUtility.makeSerializableKeys(row.getKeyValues())));
}
state.setSelectedChildrenPrimaryKeys(pkList);
//
if (childPage != null) {
for (int j = 0; j < table.getRowCount(); j++) {
if (page.getChildNode(j) == childPage) {
ITableRow childRow = table.getRow(j);
state.setExpandedChildPrimaryKey(new CompositeObject(BookmarkUtility.makeSerializableKeys(childRow.getKeyValues())));
break;
}
}
}
return state;
}
private static NodePageState bmStoreNodePage(IPageWithNodes page) throws ProcessingException {
NodePageState state = new NodePageState();
state.setPageClassName(page.getClass().getName());
state.setBookmarkIdentifier(page.getUserPreferenceContext());
state.setLabel(page.getCell().getText());
state.setExpanded(page.isExpanded());
return state;
}
private static long createSearchFilterCRC(SearchFilter filter) {
if (filter == null) {
return 0L;
}
try {
CRC32 crc = new CRC32();
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(filter);
oo.close();
crc.update(bo.toByteArray());
return crc.getValue();
}
catch (Throwable t) {
// nop
return -1L;
}
}
}
| true | true | private static IPage bmLoadTablePage(IPageWithTable tablePage, TablePageState tablePageState, boolean leafState) throws ProcessingException {
ITable table = tablePage.getTable();
if (tablePageState.getTableCustomizerData() != null && tablePage.getTable().getTableCustomizer() != null) {
byte[] newData = tablePageState.getTableCustomizerData();
ITableCustomizer tc = tablePage.getTable().getTableCustomizer();
byte[] curData = tc.getSerializedData();
if (!CompareUtility.equals(curData, newData)) {
tc.removeAllColumns();
tc.setSerializedData(tablePageState.getTableCustomizerData());
tablePage.getTable().resetColumnConfiguration();
tablePage.setChildrenLoaded(false);
}
}
// starts search form
tablePage.getSearchFilter();
ColumnSet cs = table.getColumnSet();
// setup table
try {
table.setTableChanging(true);
//legacy support
List<TableColumnState> allColumns = tablePageState.getVisibleColumns();
if (allColumns == null || allColumns.size() == 0) {
allColumns = tablePageState.getAvailableColumns();
}
if (allColumns != null && allColumns.size() > 0) {
// visible columns and width
ArrayList<IColumn> visibleColumns = new ArrayList<IColumn>();
for (TableColumnState colState : allColumns) {
//legacy support: null=true
if (colState.getVisible() == null || colState.getVisible()) {
IColumn col = resolveColumn(cs.getDisplayableColumns(), colState.getClassName());
if (col != null && col.isDisplayable()) {
if (colState.getWidth() > 0) {
col.setWidth(colState.getWidth());
}
visibleColumns.add(col);
}
}
}
List<IColumn> existingVisibleCols = Arrays.asList(cs.getVisibleColumns());
if (!existingVisibleCols.equals(visibleColumns)) {
cs.setVisibleColumns(visibleColumns.toArray(new IColumn[0]));
}
// filters
if (tablePage.getTable().getColumnFilterManager() != null) {
for (TableColumnState colState : allColumns) {
if (colState.getColumnFilterData() != null) {
IColumn col = BookmarkUtility.resolveColumn(cs.getColumns(), colState.getClassName());
if (col != null) {
tablePage.getTable().getColumnFilterManager().setSerializedFilter(colState.getColumnFilterData(), col);
}
}
}
}
//sort order (only respect visible and user-sort columns)
boolean userSortValid = true;
TreeMap<Integer, IColumn> sortColMap = new TreeMap<Integer, IColumn>();
HashMap<IColumn, Boolean> sortColAscMap = new HashMap<IColumn, Boolean>();
for (TableColumnState colState : allColumns) {
if (colState.getSortOrder() >= 0) {
IColumn col = BookmarkUtility.resolveColumn(cs.getColumns(), colState.getClassName());
if (col != null) {
sortColMap.put(colState.getSortOrder(), col);
sortColAscMap.put(col, colState.isSortAscending());
if (col.getSortIndex() != colState.getSortOrder()) {
userSortValid = false;
}
if (col.isSortAscending() != colState.isSortAscending()) {
userSortValid = false;
}
}
}
}
HashSet<IColumn<?>> existingExplicitUserSortCols = new HashSet<IColumn<?>>();
for (IColumn<?> c : cs.getUserSortColumns()) {
if (c.isSortExplicit()) {
existingExplicitUserSortCols.add(c);
}
}
if (!sortColMap.values().containsAll(existingExplicitUserSortCols)) {
userSortValid = false;
}
if (!userSortValid) {
cs.clearSortColumns();
for (IColumn col : sortColMap.values()) {
cs.addSortColumn(col, sortColAscMap.get(col));
}
table.sort();
}
}
}
finally {
table.setTableChanging(false);
}
// setup search
if (tablePageState.getSearchFormState() != null) {
ISearchForm searchForm = tablePage.getSearchFormInternal();
if (searchForm != null) {
boolean doSearch = true;
String newSearchFilterState = tablePageState.getSearchFilterState();
String oldSearchFilterState = "" + createSearchFilterCRC(searchForm.getSearchFilter());
if (CompareUtility.equals(oldSearchFilterState, newSearchFilterState)) {
String newSearchFormState = tablePageState.getSearchFormState();
String oldSearchFormState = searchForm.getXML("UTF-8");
if (CompareUtility.equals(oldSearchFormState, newSearchFormState)) {
doSearch = false;
}
}
// in case search form is in correct state, but no search has been executed, force search
if (tablePage.getTable().getRowCount() == 0) {
doSearch = true;
}
if (doSearch) {
searchForm.setXML(tablePageState.getSearchFormState());
if (tablePageState.isSearchFilterComplete()) {
searchForm.doSaveWithoutMarkerChange();
}
}
}
}
IPage childPage = null;
boolean loadChildren = !leafState;
if (tablePage.isChildrenDirty() || tablePage.isChildrenVolatile()) {
loadChildren = true;
tablePage.setChildrenLoaded(false);
}
if (loadChildren) {
tablePage.ensureChildrenLoaded();
tablePage.setChildrenDirty(false);
CompositeObject childPk = tablePageState.getExpandedChildPrimaryKey();
if (childPk != null) {
for (int r = 0; r < table.getRowCount(); r++) {
CompositeObject testPk = new CompositeObject(BookmarkUtility.makeSerializableKeys(table.getRowKeys(r)));
if (testPk.equals(childPk)) {
if (r < tablePage.getChildNodeCount()) {
childPage = tablePage.getChildPage(r);
}
break;
}
}
}
else {
if (tablePage.getChildNodeCount() > 0) {
childPage = tablePage.getChildPage(0);
}
}
}
// load selections
if (leafState) {
if (tablePageState.getSelectedChildrenPrimaryKeys().size() > 0) {
tablePage.ensureChildrenLoaded();
HashSet<CompositeObject> selectionSet = new HashSet<CompositeObject>(tablePageState.getSelectedChildrenPrimaryKeys());
ArrayList<ITableRow> rowList = new ArrayList<ITableRow>();
for (ITableRow row : table.getRows()) {
CompositeObject testPk = new CompositeObject(BookmarkUtility.makeSerializableKeys(row.getKeyValues()));
if (selectionSet.contains(testPk)) {
rowList.add(row);
}
}
if (rowList.size() > 0) {
table.selectRows(rowList.toArray(new ITableRow[0]));
}
}
}
return childPage;
}
| private static IPage bmLoadTablePage(IPageWithTable tablePage, TablePageState tablePageState, boolean leafState) throws ProcessingException {
ITable table = tablePage.getTable();
if (tablePageState.getTableCustomizerData() != null && tablePage.getTable().getTableCustomizer() != null) {
byte[] newData = tablePageState.getTableCustomizerData();
ITableCustomizer tc = tablePage.getTable().getTableCustomizer();
byte[] curData = tc.getSerializedData();
if (!CompareUtility.equals(curData, newData)) {
tc.removeAllColumns();
tc.setSerializedData(tablePageState.getTableCustomizerData());
tablePage.getTable().resetColumnConfiguration();
tablePage.setChildrenLoaded(false);
}
}
// starts search form
tablePage.getSearchFilter();
ColumnSet cs = table.getColumnSet();
// setup table
try {
table.setTableChanging(true);
//legacy support
List<TableColumnState> allColumns = tablePageState.getVisibleColumns();
if (allColumns == null || allColumns.size() == 0) {
allColumns = tablePageState.getAvailableColumns();
}
if (allColumns != null && allColumns.size() > 0) {
// visible columns and width
ArrayList<IColumn> visibleColumns = new ArrayList<IColumn>();
for (TableColumnState colState : allColumns) {
//legacy support: null=true
if (colState.getVisible() == null || colState.getVisible()) {
IColumn col = resolveColumn(cs.getDisplayableColumns(), colState.getClassName());
if (col != null && col.isDisplayable()) {
if (colState.getWidth() > 0) {
col.setWidth(colState.getWidth());
}
visibleColumns.add(col);
}
}
}
List<IColumn> existingVisibleCols = Arrays.asList(cs.getVisibleColumns());
if (!existingVisibleCols.equals(visibleColumns)) {
cs.setVisibleColumns(visibleColumns.toArray(new IColumn[0]));
}
// filters
if (tablePage.getTable().getColumnFilterManager() != null) {
for (TableColumnState colState : allColumns) {
if (colState.getColumnFilterData() != null) {
IColumn col = BookmarkUtility.resolveColumn(cs.getColumns(), colState.getClassName());
if (col != null) {
tablePage.getTable().getColumnFilterManager().setSerializedFilter(colState.getColumnFilterData(), col);
}
}
}
}
//sort order (only respect visible and user-sort columns)
boolean userSortValid = true;
TreeMap<Integer, IColumn> sortColMap = new TreeMap<Integer, IColumn>();
HashMap<IColumn, Boolean> sortColAscMap = new HashMap<IColumn, Boolean>();
for (TableColumnState colState : allColumns) {
if (colState.getSortOrder() >= 0) {
IColumn col = BookmarkUtility.resolveColumn(cs.getColumns(), colState.getClassName());
if (col != null) {
sortColMap.put(colState.getSortOrder(), col);
sortColAscMap.put(col, colState.isSortAscending());
if (col.getSortIndex() != colState.getSortOrder()) {
userSortValid = false;
}
if (col.isSortAscending() != colState.isSortAscending()) {
userSortValid = false;
}
}
}
}
HashSet<IColumn<?>> existingExplicitUserSortCols = new HashSet<IColumn<?>>();
for (IColumn<?> c : cs.getUserSortColumns()) {
if (c.isSortExplicit()) {
existingExplicitUserSortCols.add(c);
}
}
if (!sortColMap.values().containsAll(existingExplicitUserSortCols)) {
userSortValid = false;
}
if (!userSortValid) {
cs.clearSortColumns();
for (IColumn col : sortColMap.values()) {
cs.addSortColumn(col, sortColAscMap.get(col));
}
table.sort();
}
}
}
finally {
table.setTableChanging(false);
}
// setup search
if (tablePageState.getSearchFormState() != null) {
ISearchForm searchForm = tablePage.getSearchFormInternal();
if (searchForm != null) {
boolean doSearch = true;
String newSearchFilterState = tablePageState.getSearchFilterState();
String oldSearchFilterState = "" + createSearchFilterCRC(searchForm.getSearchFilter());
if (CompareUtility.equals(oldSearchFilterState, newSearchFilterState)) {
String newSearchFormState = tablePageState.getSearchFormState();
String oldSearchFormState = searchForm.getXML("UTF-8");
if (CompareUtility.equals(oldSearchFormState, newSearchFormState)) {
doSearch = false;
}
}
// in case search form is in correct state, but no search has been executed, force search
if (tablePage.getTable().getRowCount() == 0) {
doSearch = true;
}
if (doSearch) {
searchForm.setXML(tablePageState.getSearchFormState());
if (tablePageState.isSearchFilterComplete()) {
searchForm.doSaveWithoutMarkerChange();
}
}
}
}
IPage childPage = null;
boolean loadChildren = !leafState;
if (tablePage.isChildrenDirty() || tablePage.isChildrenVolatile()) {
loadChildren = true;
tablePage.setChildrenLoaded(false);
}
if (loadChildren) {
tablePage.ensureChildrenLoaded();
tablePage.setChildrenDirty(false);
CompositeObject childPk = tablePageState.getExpandedChildPrimaryKey();
if (childPk != null) {
for (int r = 0; r < table.getRowCount(); r++) {
CompositeObject testPk = new CompositeObject(BookmarkUtility.makeSerializableKeys(table.getRowKeys(r)));
if (testPk.equals(childPk)) {
if (r < tablePage.getChildNodeCount()) {
childPage = tablePage.getChildPage(r);
}
break;
}
}
}
else {
if (tablePage.getChildNodeCount() > 0) {
childPage = tablePage.getChildPage(0);
}
}
}
// load selections
if (leafState) {
if (tablePageState.getSelectedChildrenPrimaryKeys().size() > 0) {
tablePage.ensureChildrenLoaded();
HashSet<CompositeObject> selectionSet = new HashSet<CompositeObject>(tablePageState.getSelectedChildrenPrimaryKeys());
ArrayList<ITableRow> rowList = new ArrayList<ITableRow>();
for (ITableRow row : table.getRows()) {
CompositeObject testPk = new CompositeObject(BookmarkUtility.makeSerializableKeys(row.getKeyValues()));
if (selectionSet.contains(testPk)) {
//row must not be filtered out
if (row.isFilterAccepted()) {
rowList.add(row);
}
}
}
if (rowList.size() > 0) {
table.selectRows(rowList.toArray(new ITableRow[0]));
}
}
}
return childPage;
}
|
diff --git a/src/main/java/com/troiaTester/DataGenerator.java b/src/main/java/com/troiaTester/DataGenerator.java
index 9f6c479..3bff98e 100644
--- a/src/main/java/com/troiaTester/DataGenerator.java
+++ b/src/main/java/com/troiaTester/DataGenerator.java
@@ -1,325 +1,325 @@
package main.com.troiaTester;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import troiaClient.Category;
import troiaClient.CategoryFactory;
import troiaClient.GoldLabel;
import troiaClient.Label;
import troiaClient.MisclassificationCost;
import troiaClient.MisclassificationCostFactory;
/**
* This class is used to create test data for Troia client tests.
*
* @author [email protected]
*/
public class DataGenerator {
/**
* Generate collection of test objects.
*
* @see TroiaObjectCollection
* @param objectCount
* Numbers of objects to generate
* @param categories
* Map that associates class names with probability of object
* belonging to that class ( form 0 to 1 )
* @return TestObjectCollection object.
*/
public TroiaObjectCollection generateTestObjects(int objectCount,
Map<String, Double> categories) {
Collection<Double> percentages = categories.values();
double totalPercentage = 0;
for (Double percentage : percentages) {
totalPercentage += percentage.doubleValue();
}
- if (1 - totalPercentage > 0.0001) {
+ if (Math.abs(1 - totalPercentage) > 0.0001) {
throw new ArithmeticException("Percentage values sum up to "
+ totalPercentage + " instead of 1.");
} else {
int[] borders = new int[percentages.size()];
int index = 0;
for (Double percentage : percentages) {
borders[index] = (int) (percentage.doubleValue() * objectCount);
index++;
}
Map<String, String> objects = new HashMap<String, String>();
index = 0;
int categortySwitchCounter = 0;
int categoryIndex = 0;
Collection<String> categoryNames = categories.keySet();
Iterator<String> categoryNameIterator = categoryNames.iterator();
String categoryName = categoryNameIterator.next();
for (index = 0; index < objectCount; index++) {
if (categortySwitchCounter < borders[categoryIndex]) {
if (categoryIndex < categoryNames.size()) {
categortySwitchCounter++;
}
} else {
categortySwitchCounter = 0;
categoryIndex++;
categoryName = categoryNameIterator.next();
}
String objectName = "Object-" + index;
objects.put(objectName, categoryName);
}
return new TroiaObjectCollection(objects);
}
}
/**
* Generates test object collection with auto generated categories that have
* equal distribution among the objects.
*
* @see TroiaObjectCollection
* @param objectCount
* Numbers of objects to generate
* @param categoryCount
* Number of categories to generate
* @return TestObjectCollection object
*/
public TroiaObjectCollection generateTestObjects(int objectCount,
int categoryCount) {
Collection<String> categoryNames = this
.generateCategoryNames(categoryCount);
double p = 1.0 / (double) categoryNames.size();
Double percentage = new Double(p);
Map<String, Double> categories = new HashMap<String, Double>();
for (String category : categoryNames) {
categories.put(category, percentage);
}
return this.generateTestObjects(objectCount, categories);
}
public TroiaObjectCollection generateTestObjects(int objectCount,
Collection<String> categoryNames) {
double p = 1.0 / (double) categoryNames.size();
Double percentage = new Double(p);
Map<String, Double> categories = new HashMap<String, Double>();
for (String category : categoryNames) {
categories.put(category, percentage);
}
return this.generateTestObjects(objectCount, categories);
}
/**
* Generates category names
*
* @param categoryCount
* Number of categories to generate
* @return Collection of category names.
*/
public Collection<String> generateCategoryNames(int categoryCount) {
ArrayList<String> categories = new ArrayList<String>();
for (int i = 0; i < categoryCount; i++) {
categories.add("Category-" + i);
}
return categories;
}
/**
* Creates artificial worker that will be working in environment with
* categories given as a parameter
*
* @param name
* Worker name
* @param quality
* Quality of the worker (probability that he will label object
* correctly)
* @param categories
* Categories that exist in task executed by this worker
* @return Artificial worker
*/
public ArtificialWorker generateArtificialWorker(String name,
double quality, Collection<String> categories) {
ArtificialWorker worker = new ArtificialWorker();
Map<String, Map<String, Double>> confMatrix = new HashMap<String, Map<String, Double>>();
Map<String, Double> confVector;
double wrongProb = 1 - quality;
for (String correctClass : categories) {
double restProb = wrongProb;
double prob;
confVector = new HashMap<String, Double>();
for (String labeledClass : categories) {
if (labeledClass.equalsIgnoreCase(correctClass)) {
confVector.put(labeledClass, quality);
logger.debug("Set correct label probability to " + quality);
} else {
prob = Math.random() * restProb;
restProb -= prob;
confVector.put(labeledClass, prob);
}
}
confMatrix.put(correctClass, confVector);
}
worker.setName(name);
worker.setConfusionMatrix(new ConfusionMatrix(confMatrix));
logger.debug("Generated artifical worker with quality " + quality);
return worker;
}
/**
* Creates artificial worker, with random work quality, that will be working
* in environment with categories given as a parameter
*
* @param name
* Worker name
* @param categories
* Categories that exist in task executed by this worker
* @return Artificial worker
*/
public ArtificialWorker generateArtificialWorker(String name,
Collection<String> categories) {
return this.generateArtificialWorker(name, Math.random(), categories);
}
/**
* Creates collection of workers, with qualities form given range, that will
* operate in environment that contains categories given as a parameter.
*
* @param workerCount
* Number of workers that will be generated
* @param categories
* Collection of categories that workers will be assigning
* @param minQuality
* Minimal quality of generated worker (from 0 to 1)
* @param maxQuality
* Maximal quality of generated worker (from 0 to 1)
* @return Collection of artifical workers
*/
public Collection<ArtificialWorker> generateArtificialWorkers(
int workerCount, Collection<String> categories, double minQuality,
double maxQuality) {
Collection<ArtificialWorker> workers = new ArrayList<ArtificialWorker>();
if (minQuality > maxQuality)
minQuality = 0;
double qualityRange = maxQuality - minQuality;
for (int i = 0; i < workerCount; i++) {
double quality = Math.random() * qualityRange + minQuality;
ArtificialWorker worker = this.generateArtificialWorker("Worker-"
+ i, quality, categories);
workers.add(worker);
}
return workers;
}
/**
* Generates labels assigned by artificial workers.
*
* @param workers
* Collection of artificial workers
* @param objects
* Test objects collection
* @param workersPerObject
* How many workers will assign label to same object
* @return Collection of worker assigned labels
*/
public Collection<Label> generateLabels(
Collection<ArtificialWorker> workers, TroiaObjectCollection objects,
int workersPerObject) {
Collection<Label> labels = new ArrayList<Label>();
Map<ArtificialWorker, NoisedLabelGenerator> generators = NoisedLabelGeneratorFactory
.getInstance().getRouletteGeneratorsForWorkers(workers);
Iterator<ArtificialWorker> workersIterator = workers.iterator();
for (String object : objects) {
String correctCat = objects.getCategory(object);
ArtificialWorker worker;
for (int labelsForObject = 0; labelsForObject < workersPerObject; labelsForObject++) {
String assignedLabel;
if (!workersIterator.hasNext()) {
workersIterator = workers.iterator();
}
worker = workersIterator.next();
assignedLabel = generators.get(worker).getCategoryWithNoise(
correctCat);
labels.add(new Label(worker.getName(), object, assignedLabel));
}
}
return labels;
}
/**
* Generates gold labels from collection of test objects
*
* @param objects
* Test objects
* @param goldCoverage
* Fraction of objects that will have gold label
* @return Collection of gold labels.
*/
public Collection<GoldLabel> generateGoldLabels(
TroiaObjectCollection objects, double goldCoverage) {
int goldCount = (int) (objects.size() * goldCoverage);
Collection<GoldLabel> goldLabels = new ArrayList<GoldLabel>();
Iterator<String> objectsIterator = objects.iterator();
for (int i = 0; i < goldCount; i++) {
String objectName;
if (objectsIterator.hasNext()) {
objectName = objectsIterator.next();
goldLabels.add(new GoldLabel(objectName, objects
.getCategory(objectName)));
} else {
break;
}
}
return goldLabels;
}
public Data generateTestData(String requestId, int objectCount,
int categoryCount, int workerCount, double minQuality,
double maxQuality, double goldRatio, int workersPerObject) {
Data data = new Data();
Collection<String> categoryNames = this
.generateCategoryNames(categoryCount);
Collection<Category> categories = CategoryFactory.getInstance()
.createCategories(categoryNames);
TroiaObjectCollection objects = this.generateTestObjects(objectCount,
categoryNames);
Collection<MisclassificationCost> misclassificationCost = MisclassificationCostFactory
.getInstance().getMisclassificationCosts(categories);
Collection<GoldLabel> goldLabels = this.generateGoldLabels(objects,
goldRatio);
Collection<ArtificialWorker> workers = null;
Collection<Label> labels = null;
Collection<String> workerNames = null;
if(workerCount>0) {
workers = this.generateArtificialWorkers(workerCount, categoryNames, minQuality, maxQuality);
labels = this.generateLabels(workers, objects,workersPerObject);
workerNames = new ArrayList<String>();
for (ArtificialWorker worker : workers) {
workerNames.add(worker.getName());
}
}
data.setCategories(categories);
data.setGoldLabels(goldLabels);
data.setLabels(labels);
data.setMisclassificationCost(misclassificationCost);
data.setObjectCollection(objects);
data.setRequestId(requestId);
data.setWorkers(workerNames);
data.setArtificialWorkers(workers);
return data;
}
public static DataGenerator getInstance() {
return instance;
}
private static DataGenerator instance = new DataGenerator();
private DataGenerator() {
}
/**
* Logger for this class
*/
private static Logger logger = Logger.getLogger(DataGenerator.class);
}
| true | true | public TroiaObjectCollection generateTestObjects(int objectCount,
Map<String, Double> categories) {
Collection<Double> percentages = categories.values();
double totalPercentage = 0;
for (Double percentage : percentages) {
totalPercentage += percentage.doubleValue();
}
if (1 - totalPercentage > 0.0001) {
throw new ArithmeticException("Percentage values sum up to "
+ totalPercentage + " instead of 1.");
} else {
int[] borders = new int[percentages.size()];
int index = 0;
for (Double percentage : percentages) {
borders[index] = (int) (percentage.doubleValue() * objectCount);
index++;
}
Map<String, String> objects = new HashMap<String, String>();
index = 0;
int categortySwitchCounter = 0;
int categoryIndex = 0;
Collection<String> categoryNames = categories.keySet();
Iterator<String> categoryNameIterator = categoryNames.iterator();
String categoryName = categoryNameIterator.next();
for (index = 0; index < objectCount; index++) {
if (categortySwitchCounter < borders[categoryIndex]) {
if (categoryIndex < categoryNames.size()) {
categortySwitchCounter++;
}
} else {
categortySwitchCounter = 0;
categoryIndex++;
categoryName = categoryNameIterator.next();
}
String objectName = "Object-" + index;
objects.put(objectName, categoryName);
}
return new TroiaObjectCollection(objects);
}
}
| public TroiaObjectCollection generateTestObjects(int objectCount,
Map<String, Double> categories) {
Collection<Double> percentages = categories.values();
double totalPercentage = 0;
for (Double percentage : percentages) {
totalPercentage += percentage.doubleValue();
}
if (Math.abs(1 - totalPercentage) > 0.0001) {
throw new ArithmeticException("Percentage values sum up to "
+ totalPercentage + " instead of 1.");
} else {
int[] borders = new int[percentages.size()];
int index = 0;
for (Double percentage : percentages) {
borders[index] = (int) (percentage.doubleValue() * objectCount);
index++;
}
Map<String, String> objects = new HashMap<String, String>();
index = 0;
int categortySwitchCounter = 0;
int categoryIndex = 0;
Collection<String> categoryNames = categories.keySet();
Iterator<String> categoryNameIterator = categoryNames.iterator();
String categoryName = categoryNameIterator.next();
for (index = 0; index < objectCount; index++) {
if (categortySwitchCounter < borders[categoryIndex]) {
if (categoryIndex < categoryNames.size()) {
categortySwitchCounter++;
}
} else {
categortySwitchCounter = 0;
categoryIndex++;
categoryName = categoryNameIterator.next();
}
String objectName = "Object-" + index;
objects.put(objectName, categoryName);
}
return new TroiaObjectCollection(objects);
}
}
|
diff --git a/extension/eevolution/libero/src/main/java/org/eevolution/form/VHRActionNotice.java b/extension/eevolution/libero/src/main/java/org/eevolution/form/VHRActionNotice.java
index 7b45c9e..d989798 100644
--- a/extension/eevolution/libero/src/main/java/org/eevolution/form/VHRActionNotice.java
+++ b/extension/eevolution/libero/src/main/java/org/eevolution/form/VHRActionNotice.java
@@ -1,718 +1,719 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Contributor(s): Oscar Gomez & Victor Perez www.e-evolution.com *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.EventObject;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import org.compiere.apps.ADialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VComboBox;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VNumber;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MRefList;
import org.compiere.model.MRole;
import org.compiere.model.MTable;
import org.compiere.plaf.CompiereColor;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTextField;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.eevolution.model.MHRConcept;
import org.eevolution.model.MHREmployee;
import org.eevolution.model.MHRMovement;
import org.eevolution.model.MHRPeriod;
import org.eevolution.model.MHRProcess;
/**
* @author Oscar Gomez
* @author Cristina Ghita, www.arhipac.ro
* @version $Id: VHRActionNotice.java
*
* Contributor: Carlos Ruiz (globalqss)
* [ adempiere-Libero-2840048 ] Apply ABP to VHRActionNotice
* [ adempiere-Libero-2840056 ] Payroll Action Notice - concept list wrong
*/
public class VHRActionNotice extends CPanel implements FormPanel,VetoableChangeListener, ActionListener
{
/** @todo withholding */
/**
*
*/
private static final long serialVersionUID = 5905687280280831354L;
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info("");
m_WindowNo = WindowNo;
m_frame = frame;
jbInit();
dynInit();
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.setSize(1000, 400);
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private int HR_Process_ID = 0;
private int HR_Payroll_ID = 0;
private int sHR_Movement_ID = 0; // // initial not exist record in Movement to actual date
private Timestamp dateStart = null;
private Timestamp dateEnd = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VHRActionNotice.class);
//
private CPanel mainPanel = new CPanel();
private BorderLayout mainLayout = new BorderLayout();
private CPanel parameterPanel = new CPanel();
private CLabel labelProcess = new CLabel();
private VComboBox fieldProcess; // = new VComboBox();
private CLabel labelEmployee = new CLabel();
private VComboBox fieldEmployee = new VComboBox();
private CLabel labelColumnType = new CLabel();
private CTextField fieldColumnType = new CTextField(18);
private CLabel labelConcept = new CLabel();
private VComboBox fieldConcept = new VComboBox();
private JLabel labelValue = new JLabel();
private VNumber fieldQty = new VNumber();
private VNumber fieldAmount = new VNumber();
private VDate fieldDate = new VDate();
private CTextField fieldText = new CTextField(22);
private VNumber fieldRuleE = new VNumber();
private JLabel dataStatus = new JLabel();
private JScrollPane dataPane = new JScrollPane();
private MiniTable miniTable = new MiniTable();
private CPanel commandPanel = new CPanel();
private FlowLayout commandLayout = new FlowLayout();
private JButton bOk = ConfirmPanel.createOKButton(true);
private CLabel labelValidFrom = new CLabel();
private VDate fieldValidFrom = new VDate();
private CLabel labelDescription = new CLabel();
private CTextField fieldDescription = new CTextField(22);
private GridBagLayout parameterLayout = new GridBagLayout();
/**
* Static Init
* @throws Exception
*/
private void jbInit()
{
CompiereColor.setBackground(this);
mainPanel.setLayout(mainLayout);
///mainPanel.setSize(500, 500);
mainPanel.setPreferredSize(new Dimension(1000, 400));
parameterPanel.setLayout(parameterLayout);
// Process
labelProcess.setText(Msg.translate(Env.getCtx(), "HR_Process_ID"));
fieldProcess = new VComboBox(getProcess());
fieldProcess.setMandatory(true);
fieldProcess.addActionListener(this);
// Employee
labelEmployee.setText(Msg.translate(Env.getCtx(), "HR_Employee_ID"));
fieldEmployee.setReadWrite(false);
fieldEmployee.setMandatory(true);
fieldEmployee.addActionListener(this);
fieldEmployee.addVetoableChangeListener(this);
// Concept
labelConcept.setText(Msg.translate(Env.getCtx(), "HR_Concept_ID"));
getConceptValid();
fieldConcept.setReadWrite(false);
fieldConcept.setMandatory(true);
fieldConcept.addActionListener(this);
// ValidFrom
labelValidFrom.setText(Msg.translate(Env.getCtx(), "Date"));
fieldValidFrom.setReadWrite(false);
fieldValidFrom.setMandatory(true);
fieldValidFrom.addVetoableChangeListener(this);
// Description
labelDescription.setText(Msg.translate(Env.getCtx(), "Description"));
fieldDescription.setValue("");
fieldDescription.setReadWrite(false);
// ColumnType
labelColumnType.setText(Msg.translate(Env.getCtx(), "ColumnType"));
fieldColumnType.setReadWrite(false);
// Qty-Amount-Date-Text-RuleEngine
fieldQty.setReadWrite(false);
fieldQty.setDisplayType(DisplayType.Quantity);
fieldQty.setVisible(true);
fieldAmount.setDisplayType(DisplayType.Amount);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
//
bOk.addActionListener(this);
//
mainPanel.add(parameterPanel, BorderLayout.NORTH);
// Process
parameterPanel.add(labelProcess, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldProcess, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
// Employee
parameterPanel.add(labelEmployee, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldEmployee, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
// ValidFrom
parameterPanel.add(labelValidFrom, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldValidFrom, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
// Concepto
parameterPanel.add(labelConcept, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldConcept, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// ColumnType
parameterPanel.add(labelColumnType, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldColumnType, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Qty-Amount-Date-Text-RuleEngine
parameterPanel.add(labelValue, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldQty, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldAmount, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldDate, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldText, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Description
parameterPanel.add(labelDescription, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldDescription, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Refresh
parameterPanel.add(bOk, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Agree
mainPanel.add(dataStatus, BorderLayout.SOUTH);
mainPanel.add(dataPane, BorderLayout.CENTER);
dataPane.getViewport().add(miniTable, null);
//
commandPanel.setLayout(commandLayout);
commandLayout.setAlignment(FlowLayout.RIGHT);
commandLayout.setHgap(10);
} // jbInit
/**
* Dynamic Init.
* - Load Bank Info
* - Load BPartner
* - Init Table
*/
private void dynInit()
{
miniTable.addColumn("HR_Movement_ID"); // 0
miniTable.addColumn("AD_Org_ID"); // 1
miniTable.addColumn("HR_Concept_ID"); // 2
miniTable.addColumn("ValidFrom"); // 3
miniTable.addColumn("ColumnType"); // 4
miniTable.addColumn("Qty"); // 5
miniTable.addColumn("Amount"); // 6
miniTable.addColumn("ServiceDate"); // 7
miniTable.addColumn("Text"); // 8
miniTable.addColumn("AD_Rule_ID"); // 9
miniTable.addColumn("Description"); // 10
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "HR_Concept_ID"));
miniTable.setColumnClass(3, Timestamp.class, true, Msg.translate(Env.getCtx(), "ValidFrom"));
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "ColumnType"));
miniTable.setColumnClass(5, BigDecimal.class, true, Msg.translate(Env.getCtx(), "Qty"));
miniTable.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "Amount"));
miniTable.setColumnClass(7, Timestamp.class, true, Msg.translate(Env.getCtx(), "ServiceDate"));
miniTable.setColumnClass(8, String.class, true, Msg.translate(Env.getCtx(), "Text"));
miniTable.setColumnClass(9, String.class, true, Msg.translate(Env.getCtx(), "AD_Rule_ID"));
miniTable.setColumnClass(10, String.class, true, Msg.translate(Env.getCtx(), "Description"));
//
miniTable.autoSize();
} // dynInit
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**************************************************************************
* vetoableChange
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e) throws PropertyVetoException
{
fieldConcept.setReadWrite(true);
log.fine("Event"+ e);
log.fine("Event Source "+ e.getSource());
log.fine("Event Property "+ e.getPropertyName());
processChangeEvent(e);
Integer HR_Period_ID = new MHRProcess(Env.getCtx(),(Integer)fieldProcess.getValue(),null).getHR_Period_ID();
String date = DB.TO_DATE((Timestamp)fieldValidFrom.getValue());
int existRange = DB.getSQLValueEx(null,"SELECT * FROM HR_Period WHERE " +date+
" >= StartDate AND "+date+ " <= EndDate AND HR_Period_ID = "+HR_Period_ID);
// Exist of Range Payroll
if ( existRange < 0){
fieldConcept.setReadWrite(false);
return;
}
if (fieldConcept != null)
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
} // vetoableChange
/**************************************************************************
* Action Listener
* @param e event
*/
public void actionPerformed(ActionEvent e)
{
log.fine("Event "+ e);
log.fine("Event Source "+ e.getSource());
processChangeEvent(e);
} // actionPerformed
private void processChangeEvent(EventObject e) {
if ( e.getSource().equals(fieldProcess) ) { // Process
KeyNamePair pp = (KeyNamePair)fieldProcess.getSelectedItem();
if (pp != null){
HR_Process_ID = pp.getKey();
MHRProcess process = new MHRProcess(Env.getCtx(),HR_Process_ID, null);
MHRPeriod period = MHRPeriod.get(Env.getCtx(), process.getHR_Period_ID());
dateStart= period.getStartDate();
dateEnd = period.getEndDate();
HR_Payroll_ID = process.getHR_Payroll_ID();
getEmployeeValid(process);
fieldEmployee.setReadWrite(true);
}
}
else if ( e.getSource().equals(fieldEmployee) ){ // Employee
KeyNamePair pp = (KeyNamePair)fieldEmployee.getSelectedItem();
int C_BPartner_ID = 0;
if ( pp != null )
C_BPartner_ID = pp.getKey();
if ( C_BPartner_ID > 0){
fieldValidFrom.setValue(dateEnd);
fieldValidFrom.setReadWrite(true);
getConceptValid();
fieldConcept.setReadWrite(true);
executeQuery();
}
}
else if ( e.getSource().equals(fieldConcept) ) { // Concept
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = 0;
if (pp != null)
HR_Concept_ID = pp.getKey();
if (HR_Concept_ID > 0) {
MHRConcept concept = MHRConcept.get(Env.getCtx(),HR_Concept_ID);
// Name To Type Column
fieldColumnType.setValue(DB.getSQLValueStringEx(null, getSQL_ColumnType("?"), concept.getColumnType() ));
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
//
if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity)){ // Concept Type
fieldQty.setVisible(true);
fieldQty.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount)){
fieldQty.setVisible(false);
fieldAmount.setVisible(true);
fieldAmount.setReadWrite(true);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date)){
fieldQty.setVisible(false);
fieldAmount.setVisible(false);
fieldDate.setVisible(true);
fieldDate.setReadWrite(true);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text)){
fieldText.setVisible(true);
fieldText.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldRuleE.setVisible(false);
}
fieldDescription.setReadWrite(true);
}
} // Concept
else if (e instanceof ActionEvent && e.getSource().equals(bOk) ){ // Movement SAVE
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = pp.getKey();
if ( HR_Concept_ID <= 0
|| fieldProcess.getValue() == null
|| ((Integer)fieldProcess.getValue()).intValue() <= 0
|| fieldEmployee.getValue() == null
|| ((Integer)fieldEmployee.getValue()).intValue() <= 0) { // required fields
ADialog.error(m_WindowNo, this, Msg.translate(Env.getCtx(), "FillMandatory")
+ Msg.translate(Env.getCtx(), "HR_Process_ID") + ", "
+ Msg.translate(Env.getCtx(), "HR_Employee_ID") + ", "
+ Msg.translate(Env.getCtx(), "HR_Concept_ID"));
} else {
MHRConcept conceptOK = MHRConcept.get(Env.getCtx(),HR_Concept_ID);
int mov = sHR_Movement_ID > 0 ? sHR_Movement_ID : 0;
MHRMovement movementOK = new MHRMovement(Env.getCtx(),mov,null);
movementOK.setDescription(fieldDescription.getValue() != null ? (String)fieldDescription.getValue().toString() : "");
movementOK.setHR_Process_ID((Integer)fieldProcess.getValue());
movementOK.setC_BPartner_ID((Integer)fieldEmployee.getValue());
movementOK.setHR_Concept_ID((Integer)fieldConcept.getValue());
movementOK.setHR_Concept_Category_ID(conceptOK.getHR_Concept_Category_ID());
movementOK.setColumnType(conceptOK.getColumnType());
movementOK.setQty(fieldQty.getValue() != null ? (BigDecimal)fieldQty.getValue() : Env.ZERO);
movementOK.setAmount(fieldAmount.getValue() != null ? (BigDecimal)fieldAmount.getValue() : Env.ZERO );
movementOK.setTextMsg(fieldText.getValue() != null ? (String)fieldText.getValue().toString() : "");
movementOK.setServiceDate(fieldDate.getValue() != null ? (Timestamp)fieldDate.getValue() : null);
movementOK.setValidFrom((Timestamp)fieldValidFrom.getTimestamp());
movementOK.setValidTo((Timestamp)fieldValidFrom.getTimestamp());
MHREmployee employee = MHREmployee.getActiveEmployee(Env.getCtx(), movementOK.getC_BPartner_ID(), null);
if (employee != null) {
movementOK.setHR_Department_ID(employee.getHR_Department_ID());
movementOK.setHR_Job_ID(employee.getHR_Job_ID());
+ movementOK.setC_Activity_ID(employee.getC_Activity_ID());
}
movementOK.setIsRegistered(true);
movementOK.saveEx();
executeQuery();
fieldValidFrom.setValue(dateEnd);
fieldColumnType.setValue("");
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldQty.setReadWrite(false);
fieldAmount.setReadWrite(false);
fieldText.setReadWrite(false);
fieldDescription.setReadWrite(false);
sHR_Movement_ID = 0; // Initial not exist record in Movement to actual date
// clear fields
fieldDescription.setValue("");
fieldText.setValue("");
fieldDate.setValue(null);
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldConcept.setSelectedIndex(0);
}
}
} // processChangeEvent
/**
* Query Info
*/
private void executeQuery()
{
StringBuffer sqlQuery = new StringBuffer("SELECT DISTINCT o.Name,hp.Name," // AD_Org_ID, HR_Process_ID -- 1,2
+ " bp.Name,hc.Name,hm.ValidFrom," // HR_Employee_ID,HR_Concept_ID,ValidFrom,ColumnType -- 3,4,5
+ "("+getSQL_ColumnType("hc.ColumnType")+") AS ColumnType," // 6 ColumnType(Reference Name)
+ " hm.Qty,hm.Amount,hm.ServiceDate,hm.TextMsg,er.Name,hm.Description " // Qty,Amount,ServiceDate,Text,AD_Rule_ID,Description -- 7,8,9,10,11,12
+ " , HR_Movement_id, hm.AD_Org_ID,hp.HR_Process_ID,hm.HR_Concept_ID " // to make the distinct useful
+ " FROM HR_Movement hm "
+ " INNER JOIN AD_Org o ON (hm.AD_Org_ID=o.AD_Org_ID)"
+ " INNER JOIN HR_Process hp ON (hm.HR_Process_ID=hp.HR_Process_ID)"
+ " INNER JOIN C_BPartner bp ON (hm.C_BPartner_ID=bp.C_BPartner_ID)"
+ " INNER JOIN HR_Employee e ON (e.C_BPartner_ID=bp.C_BPartner_ID)"
+ " INNER JOIN HR_Concept hc ON (hm.HR_Concept_ID=hc.HR_Concept_ID)"
+ " LEFT OUTER JOIN AD_Rule er ON (hm.AD_Rule_ID=er.AD_Rule_ID)"
+ " WHERE hm.Processed='N' AND hp.HR_Process_ID = " +fieldProcess.getValue()
//+ " AND IsStatic = 'Y' " // Just apply incidences [add 30Dic2006 to see everything]
+ " AND hm.C_BPartner_ID = " + fieldEmployee.getValue()
// + " AND (Qty > 0 OR Amount > 0 OR hm.TextMsg IS NOT NULL OR ServiceDate IS NOT NULL) "
);
if (fieldValidFrom.getValue() == null) {
sqlQuery.append(" AND " +DB.TO_DATE(dateStart)+" >= hm.ValidFrom AND "+DB.TO_DATE(dateEnd)+" <= hm.ValidTo ");
}
sqlQuery.append(" ORDER BY hm.AD_Org_ID,hp.HR_Process_ID,bp.Name,hm.ValidFrom,hm.HR_Concept_ID");
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = DB.prepareStatement(sqlQuery.toString(), null);
rs = pstmt.executeQuery();
while (rs.next()) {
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setValueAt(rs.getString(1), row, 1); // AD_Org_ID
miniTable.setValueAt(rs.getString(4), row, 2); // HR_Concept_ID
miniTable.setValueAt(rs.getTimestamp(5), row, 3); // ValidFrom
miniTable.setValueAt(rs.getString(6), row, 4); // ColumnType
miniTable.setValueAt(rs.getObject(7) != null ? rs.getBigDecimal(7) : Env.ZERO, row, 5); // Qty
miniTable.setValueAt(rs.getObject(8) != null ? rs.getBigDecimal(8) : Env.ZERO, row, 6); // Amount
miniTable.setValueAt(rs.getTimestamp(9), row, 7); // ServiceDate
miniTable.setValueAt(rs.getString(10), row, 8); // TextMsg
miniTable.setValueAt(rs.getString(11), row, 9); // AD_Rule_ID
miniTable.setValueAt(rs.getString(12), row, 10); // Description
// prepare next
row++;
}
}
catch (SQLException e) {
log.log(Level.SEVERE, sqlQuery.toString(), e);
}
finally {
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
miniTable.autoSize();
} // executeQuery
/**
* get Process
* parameter: MHRProcess
*/
private KeyNamePair[] getProcess()
{
String sql = MRole.getDefault().addAccessSQL(
"SELECT hrp.HR_Process_ID,hrp.DocumentNo ||'-'|| hrp.Name,hrp.DocumentNo,hrp.Name FROM HR_Process hrp",
"hrp",MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO) + " AND hrp.IsActive = 'Y' ";
sql += " ORDER BY hrp.DocumentNo, hrp.Name";
return DB.getKeyNamePairs(sql, true);
} //getProcess
/**
* get Employee
* to Valid Payroll-Departmant-Employee of Process Actual
* parameter: MHRProcess
*/
private void getEmployeeValid(MHRProcess process)
{
if (process == null)
return;
fieldEmployee.removeAllItems(); // Clean before adding
KeyNamePair pp = new KeyNamePair(0, "");
fieldEmployee.addItem(pp);
String sql = MRole.getDefault().addAccessSQL(
"SELECT DISTINCT bp.C_BPartner_ID,bp.Name FROM HR_Employee hrpe INNER JOIN C_BPartner bp ON(bp.C_BPartner_ID=hrpe.C_BPartner_ID)",
"hrpe",MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO) + " AND hrpe.IsActive = 'Y' ";
if ( process.getHR_Payroll_ID() != 0){
sql += " AND (hrpe.HR_Payroll_ID =" +process.getHR_Payroll_ID()+ " OR hrpe.HR_Payroll_ID is NULL)" ;
/*if ( process.getHR_Department_ID() != 0 );
sql += " AND (hrpe.HR_Department_ID =" +process.getHR_Department_ID()+" OR hrpe.HR_Department_ID is NULL)" ;
if ( process.getHR_Employee_ID() != 0 );
sql += " AND (hrpe.HR_Employee_ID =" + process.getHR_Employee_ID()+" OR hrpe.HR_Employee_ID is NULL)" ;*/
}
sql += " ORDER BY bp.Name ";
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
pstmt = DB.prepareStatement(sql, null);
rs = pstmt.executeQuery();
while (rs.next())
{
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
fieldEmployee.addItem(pp);
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
fieldEmployee.setSelectedIndex(0);
} //getEmployeeValid
/**
* get Concept
* to Valide Dates of Process
* parameter: MHRProcess
*/
private void getConceptValid()
{
if( fieldProcess == null )
return;
fieldConcept.removeAllItems(); // Clean list before adding
KeyNamePair pp = new KeyNamePair(0, "");
fieldConcept.addItem(pp);
String sql = "SELECT DISTINCT hrpc.HR_Concept_ID,hrpc.Name,hrpc.Value "
+ " FROM HR_Concept hrpc "
+ " INNER JOIN HR_Attribute hrpa ON (hrpa.HR_Concept_ID=hrpc.HR_Concept_ID)"
+ " WHERE hrpc.AD_Client_ID = " +Env.getAD_Client_ID(Env.getCtx())
+ " AND hrpc.IsActive = 'Y' AND hrpc.IsRegistered = 'Y' AND hrpc.Type != 'E'"
+ " AND (hrpa.HR_Payroll_ID = " +HR_Payroll_ID+ " OR hrpa.HR_Payroll_ID IS NULL)";
if (fieldProcess != null)
{ // Process
; //sql += " AND " +DB.TO_DATE(dateStart)+ " >= hrpa.ValidFrom AND " +DB.TO_DATE(dateEnd)+ "<= hrpa.ValidTo";
/* if (process.getHR_Payroll_ID() != 0) // Process & Payroll
sql = sql + " AND (hrpa.HR_Payroll_ID = " +process.getHR_Payroll_ID()+ " OR hrpa.HR_Payroll_ID is NULL)" ;
if (process.getHR_Department_ID() != 0 ); // Process & Department
sql = sql + " AND (hrpa.HR_Department_ID = " +process.getHR_Department_ID()+" OR hrpa.HR_Department_ID is NULL)" ;
if (process.getHR_Department_ID() != 0 ); // Process & Employee
sql = sql + " AND (hrpa.HR_Employee_ID = " + process.getHR_Employee_ID()+" OR hrpa.HR_Employee_ID is NULL)" ;*/
}
sql = sql +" ORDER BY hrpc.Value";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = DB.prepareStatement(sql, null);
rs = pstmt.executeQuery();
while (rs.next()){
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
fieldConcept.addItem(pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
finally
{
DB.close(rs,pstmt);
rs=null; pstmt = null;
}
fieldConcept.setSelectedIndex(0);
} //getConceptValid
/**
* get record Found to Movement Payroll
* parameter:
*/
public int seekMovement()
{
if(fieldConcept.getValue() == null )
return 0;
int HR_Movement_ID = 0;
String date = DB.TO_DATE((Timestamp)fieldValidFrom.getValue());
int Process_ID = 0; KeyNamePair ppp = (KeyNamePair)fieldProcess.getSelectedItem();
int Employee_ID = 0; KeyNamePair ppe = (KeyNamePair)fieldEmployee.getSelectedItem();
int Concept_ID = 0; KeyNamePair ppc = (KeyNamePair)fieldConcept.getSelectedItem();
//
Process_ID = ppp != null ? ppp.getKey(): null;
Employee_ID = ppe != null ? ppe.getKey(): null;
Concept_ID = ppc != null ? ppc.getKey(): null;
MHRConcept concept = MHRConcept.get(Env.getCtx(),Concept_ID);
//
if ( (Process_ID+Employee_ID+Concept_ID) > 0 ){
HR_Movement_ID = DB.getSQLValue(null,"SELECT HR_Movement_ID "
+" FROM HR_Movement WHERE HR_Process_ID = "+Process_ID
+" AND C_BPartner_ID =" +Employee_ID+ " AND HR_Concept_ID = "+Concept_ID
+" AND TRUNC(ValidFrom) = TRUNC(" + date +")");
if (HR_Movement_ID > 0){ // exist record in Movement Payroll
sHR_Movement_ID = HR_Movement_ID;
MHRMovement movementFound = new MHRMovement(Env.getCtx(),sHR_Movement_ID,null);
//
fieldDescription.setValue(movementFound.getDescription());
// clear fields
fieldText.setValue("");
fieldDate.setValue(null);
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
// assign just corresponding field
if ( concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity) ) // Quantity
fieldQty.setValue(movementFound.getQty());
else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount) ) // Amount
fieldAmount.setValue(movementFound.getAmount());
else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text) ) // Text
fieldText.setValue(movementFound.getTextMsg());
else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date) ) // Date
fieldDate.setValue(movementFound.getServiceDate());
}
}
return HR_Movement_ID;
} //seekMovement
/**
* Get SQL Code of ColumnType for given sqlValue
* @param sqlValue
* @return sql select code
*/
private String getSQL_ColumnType(String sqlValue) {
int columnType_Ref_ID = MTable.get(Env.getCtx(), MHRConcept.Table_ID)
.getColumn(MHRConcept.COLUMNNAME_ColumnType)
.getAD_Reference_Value_ID();
String sql;
if (Env.isBaseLanguage(Env.getCtx(), MRefList.Table_Name)) {
sql = "SELECT zz.Name FROM AD_Ref_List zz WHERE zz.AD_Reference_ID="+columnType_Ref_ID;
}
else {
sql = "SELECT zz.Name FROM AD_Ref_List zz, AD_Ref_List_Trl zzt"
+" WHERE zz.AD_Reference_ID="+columnType_Ref_ID
+" AND zzt.AD_Ref_List_ID=zz.AD_Ref_List_ID"
+" AND zzt.AD_Language="+DB.TO_STRING(Env.getAD_Language(Env.getCtx()));
}
sql += " AND zz.Value = "+sqlValue;
return sql;
} // getSQL_ColumnType
} // VHRActionNotice
| true | true | private void processChangeEvent(EventObject e) {
if ( e.getSource().equals(fieldProcess) ) { // Process
KeyNamePair pp = (KeyNamePair)fieldProcess.getSelectedItem();
if (pp != null){
HR_Process_ID = pp.getKey();
MHRProcess process = new MHRProcess(Env.getCtx(),HR_Process_ID, null);
MHRPeriod period = MHRPeriod.get(Env.getCtx(), process.getHR_Period_ID());
dateStart= period.getStartDate();
dateEnd = period.getEndDate();
HR_Payroll_ID = process.getHR_Payroll_ID();
getEmployeeValid(process);
fieldEmployee.setReadWrite(true);
}
}
else if ( e.getSource().equals(fieldEmployee) ){ // Employee
KeyNamePair pp = (KeyNamePair)fieldEmployee.getSelectedItem();
int C_BPartner_ID = 0;
if ( pp != null )
C_BPartner_ID = pp.getKey();
if ( C_BPartner_ID > 0){
fieldValidFrom.setValue(dateEnd);
fieldValidFrom.setReadWrite(true);
getConceptValid();
fieldConcept.setReadWrite(true);
executeQuery();
}
}
else if ( e.getSource().equals(fieldConcept) ) { // Concept
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = 0;
if (pp != null)
HR_Concept_ID = pp.getKey();
if (HR_Concept_ID > 0) {
MHRConcept concept = MHRConcept.get(Env.getCtx(),HR_Concept_ID);
// Name To Type Column
fieldColumnType.setValue(DB.getSQLValueStringEx(null, getSQL_ColumnType("?"), concept.getColumnType() ));
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
//
if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity)){ // Concept Type
fieldQty.setVisible(true);
fieldQty.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount)){
fieldQty.setVisible(false);
fieldAmount.setVisible(true);
fieldAmount.setReadWrite(true);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date)){
fieldQty.setVisible(false);
fieldAmount.setVisible(false);
fieldDate.setVisible(true);
fieldDate.setReadWrite(true);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text)){
fieldText.setVisible(true);
fieldText.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldRuleE.setVisible(false);
}
fieldDescription.setReadWrite(true);
}
} // Concept
else if (e instanceof ActionEvent && e.getSource().equals(bOk) ){ // Movement SAVE
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = pp.getKey();
if ( HR_Concept_ID <= 0
|| fieldProcess.getValue() == null
|| ((Integer)fieldProcess.getValue()).intValue() <= 0
|| fieldEmployee.getValue() == null
|| ((Integer)fieldEmployee.getValue()).intValue() <= 0) { // required fields
ADialog.error(m_WindowNo, this, Msg.translate(Env.getCtx(), "FillMandatory")
+ Msg.translate(Env.getCtx(), "HR_Process_ID") + ", "
+ Msg.translate(Env.getCtx(), "HR_Employee_ID") + ", "
+ Msg.translate(Env.getCtx(), "HR_Concept_ID"));
} else {
MHRConcept conceptOK = MHRConcept.get(Env.getCtx(),HR_Concept_ID);
int mov = sHR_Movement_ID > 0 ? sHR_Movement_ID : 0;
MHRMovement movementOK = new MHRMovement(Env.getCtx(),mov,null);
movementOK.setDescription(fieldDescription.getValue() != null ? (String)fieldDescription.getValue().toString() : "");
movementOK.setHR_Process_ID((Integer)fieldProcess.getValue());
movementOK.setC_BPartner_ID((Integer)fieldEmployee.getValue());
movementOK.setHR_Concept_ID((Integer)fieldConcept.getValue());
movementOK.setHR_Concept_Category_ID(conceptOK.getHR_Concept_Category_ID());
movementOK.setColumnType(conceptOK.getColumnType());
movementOK.setQty(fieldQty.getValue() != null ? (BigDecimal)fieldQty.getValue() : Env.ZERO);
movementOK.setAmount(fieldAmount.getValue() != null ? (BigDecimal)fieldAmount.getValue() : Env.ZERO );
movementOK.setTextMsg(fieldText.getValue() != null ? (String)fieldText.getValue().toString() : "");
movementOK.setServiceDate(fieldDate.getValue() != null ? (Timestamp)fieldDate.getValue() : null);
movementOK.setValidFrom((Timestamp)fieldValidFrom.getTimestamp());
movementOK.setValidTo((Timestamp)fieldValidFrom.getTimestamp());
MHREmployee employee = MHREmployee.getActiveEmployee(Env.getCtx(), movementOK.getC_BPartner_ID(), null);
if (employee != null) {
movementOK.setHR_Department_ID(employee.getHR_Department_ID());
movementOK.setHR_Job_ID(employee.getHR_Job_ID());
}
movementOK.setIsRegistered(true);
movementOK.saveEx();
executeQuery();
fieldValidFrom.setValue(dateEnd);
fieldColumnType.setValue("");
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldQty.setReadWrite(false);
fieldAmount.setReadWrite(false);
fieldText.setReadWrite(false);
fieldDescription.setReadWrite(false);
sHR_Movement_ID = 0; // Initial not exist record in Movement to actual date
// clear fields
fieldDescription.setValue("");
fieldText.setValue("");
fieldDate.setValue(null);
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldConcept.setSelectedIndex(0);
}
}
} // processChangeEvent
| private void processChangeEvent(EventObject e) {
if ( e.getSource().equals(fieldProcess) ) { // Process
KeyNamePair pp = (KeyNamePair)fieldProcess.getSelectedItem();
if (pp != null){
HR_Process_ID = pp.getKey();
MHRProcess process = new MHRProcess(Env.getCtx(),HR_Process_ID, null);
MHRPeriod period = MHRPeriod.get(Env.getCtx(), process.getHR_Period_ID());
dateStart= period.getStartDate();
dateEnd = period.getEndDate();
HR_Payroll_ID = process.getHR_Payroll_ID();
getEmployeeValid(process);
fieldEmployee.setReadWrite(true);
}
}
else if ( e.getSource().equals(fieldEmployee) ){ // Employee
KeyNamePair pp = (KeyNamePair)fieldEmployee.getSelectedItem();
int C_BPartner_ID = 0;
if ( pp != null )
C_BPartner_ID = pp.getKey();
if ( C_BPartner_ID > 0){
fieldValidFrom.setValue(dateEnd);
fieldValidFrom.setReadWrite(true);
getConceptValid();
fieldConcept.setReadWrite(true);
executeQuery();
}
}
else if ( e.getSource().equals(fieldConcept) ) { // Concept
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = 0;
if (pp != null)
HR_Concept_ID = pp.getKey();
if (HR_Concept_ID > 0) {
MHRConcept concept = MHRConcept.get(Env.getCtx(),HR_Concept_ID);
// Name To Type Column
fieldColumnType.setValue(DB.getSQLValueStringEx(null, getSQL_ColumnType("?"), concept.getColumnType() ));
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
//
if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity)){ // Concept Type
fieldQty.setVisible(true);
fieldQty.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount)){
fieldQty.setVisible(false);
fieldAmount.setVisible(true);
fieldAmount.setReadWrite(true);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date)){
fieldQty.setVisible(false);
fieldAmount.setVisible(false);
fieldDate.setVisible(true);
fieldDate.setReadWrite(true);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text)){
fieldText.setVisible(true);
fieldText.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldRuleE.setVisible(false);
}
fieldDescription.setReadWrite(true);
}
} // Concept
else if (e instanceof ActionEvent && e.getSource().equals(bOk) ){ // Movement SAVE
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = pp.getKey();
if ( HR_Concept_ID <= 0
|| fieldProcess.getValue() == null
|| ((Integer)fieldProcess.getValue()).intValue() <= 0
|| fieldEmployee.getValue() == null
|| ((Integer)fieldEmployee.getValue()).intValue() <= 0) { // required fields
ADialog.error(m_WindowNo, this, Msg.translate(Env.getCtx(), "FillMandatory")
+ Msg.translate(Env.getCtx(), "HR_Process_ID") + ", "
+ Msg.translate(Env.getCtx(), "HR_Employee_ID") + ", "
+ Msg.translate(Env.getCtx(), "HR_Concept_ID"));
} else {
MHRConcept conceptOK = MHRConcept.get(Env.getCtx(),HR_Concept_ID);
int mov = sHR_Movement_ID > 0 ? sHR_Movement_ID : 0;
MHRMovement movementOK = new MHRMovement(Env.getCtx(),mov,null);
movementOK.setDescription(fieldDescription.getValue() != null ? (String)fieldDescription.getValue().toString() : "");
movementOK.setHR_Process_ID((Integer)fieldProcess.getValue());
movementOK.setC_BPartner_ID((Integer)fieldEmployee.getValue());
movementOK.setHR_Concept_ID((Integer)fieldConcept.getValue());
movementOK.setHR_Concept_Category_ID(conceptOK.getHR_Concept_Category_ID());
movementOK.setColumnType(conceptOK.getColumnType());
movementOK.setQty(fieldQty.getValue() != null ? (BigDecimal)fieldQty.getValue() : Env.ZERO);
movementOK.setAmount(fieldAmount.getValue() != null ? (BigDecimal)fieldAmount.getValue() : Env.ZERO );
movementOK.setTextMsg(fieldText.getValue() != null ? (String)fieldText.getValue().toString() : "");
movementOK.setServiceDate(fieldDate.getValue() != null ? (Timestamp)fieldDate.getValue() : null);
movementOK.setValidFrom((Timestamp)fieldValidFrom.getTimestamp());
movementOK.setValidTo((Timestamp)fieldValidFrom.getTimestamp());
MHREmployee employee = MHREmployee.getActiveEmployee(Env.getCtx(), movementOK.getC_BPartner_ID(), null);
if (employee != null) {
movementOK.setHR_Department_ID(employee.getHR_Department_ID());
movementOK.setHR_Job_ID(employee.getHR_Job_ID());
movementOK.setC_Activity_ID(employee.getC_Activity_ID());
}
movementOK.setIsRegistered(true);
movementOK.saveEx();
executeQuery();
fieldValidFrom.setValue(dateEnd);
fieldColumnType.setValue("");
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldQty.setReadWrite(false);
fieldAmount.setReadWrite(false);
fieldText.setReadWrite(false);
fieldDescription.setReadWrite(false);
sHR_Movement_ID = 0; // Initial not exist record in Movement to actual date
// clear fields
fieldDescription.setValue("");
fieldText.setValue("");
fieldDate.setValue(null);
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldConcept.setSelectedIndex(0);
}
}
} // processChangeEvent
|
diff --git a/SilentModeScheduler/src/giulio/frasca/silencesched/EditEventActivity.java b/SilentModeScheduler/src/giulio/frasca/silencesched/EditEventActivity.java
index 4a2d2ac..2ae090a 100644
--- a/SilentModeScheduler/src/giulio/frasca/silencesched/EditEventActivity.java
+++ b/SilentModeScheduler/src/giulio/frasca/silencesched/EditEventActivity.java
@@ -1,891 +1,892 @@
package giulio.frasca.silencesched;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.regex.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.os.Bundle;
//import android.view.*;
//import android.view.Gravity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.content.SharedPreferences;
import giulio.frasca.silencesched.exceptions.*;
import giulio.frasca.silencesched.weekview.WeekViewActivity;
import giulio.frasca.lib.*;
public class EditEventActivity extends Activity {
/** Called when the activity is first created. *//**
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editevent);
// TODO Auto-generated method stub
}*/
/**
* removed cancel
* removed add
* event name EditText is only partially functional, isn't saving the name
* confirm is labeled "Enable" button on xml file
* delete and disable buttons are the same currently
*/
//SpinnerMap
HashMap<Integer,Integer> nameDictionary ;
HashMap<Integer,Integer> nameDictionaryReverse;
//private LinkedList<RingerSettingBlock> ringerSchedule;
private Schedule schedule;
// filename
private final String PREF_FILE = "ncsusilencepreffile2";
private int currentBlockId;
//GUI components
Button confirmButton,deleteButton,disableButton;
Spinner startSpinner,endSpinner,ringSpinner;
EditText startHour,endHour,startMinute,endMinute,eventName;
ToggleButton sunToggle,monToggle,tueToggle,wedToggle,thuToggle,friToggle,satToggle;
//status vars
boolean sunOn,monOn,tueOn,wedOn,thuOn,friOn,satOn;
boolean updating;
boolean serviceRunning;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editevent);
updating=false;
serviceRunning=false;
SharedPreferences settings = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE);
clearPrefsForTesting(settings);
schedule = new Schedule(settings);
initComponents();
currentBlockId = 0;
RingerSettingBlock first =schedule.getBlock(currentBlockId);
createTestData();
updateInterface(first);
//ringerSchedule = new LinkedList<RingerSettingBlock>();
//initRingerSched();
//checkCurrentSetting();
}
public void printScheduleContents(){
LinkedList<RingerSettingBlock> list = schedule.getList();
Iterator<RingerSettingBlock> i = list.iterator();
while (i.hasNext()){
RingerSettingBlock block = i.next();
int id=block.getId();
logcatPrint(id+": id ="+id);
logcatPrint(id+": strt="+block.getStartTime());
logcatPrint(id+": end ="+block.getEndTime());
logcatPrint(id+": ring="+block.getRingVal());
logcatPrint(id+": days="+block.getDays());
logcatPrint(id+": ru ="+block.getRepeatUntil());
logcatPrint("-----");
}
}
private void createTestData() {
schedule.addBlock(0 , 1*60*60*1000 , AudioManager.RINGER_MODE_SILENT, 1000000, 253402300799000L, "CSC 326", false, true);
schedule.addBlock(1*60*60*1000 , 23*60*60*1000 , AudioManager.RINGER_MODE_SILENT, 1010000, 253402300799000L, "CSC 495", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_SILENT, 1000110, 253402300799000L, "Dinner", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_VIBRATE, 1110110, 253402300799000L, "Staff Meeting", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_VIBRATE, 1001000, 253402300799000L, "MA 305", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_VIBRATE, 1000110, 253402300799000L, "Homework", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_SILENT, 0000110, 253402300799000L, "Driving to Work", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_NORMAL, 1000110, 253402300799000L, "Driving Home", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_SILENT, 1000110, 253402300799000L, "Upcoming Mental Breakdown", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_SILENT, 110110, 253402300799000L, "Meditation", false, true);
schedule.addBlock(10*60*60*1000, 15*60*60*1000, AudioManager.RINGER_MODE_SILENT, 1000110, 253402300799000L, "Therapy", false, true);
lcPrintBlock(0);
}
private void lcPrintBlock(int id){
RingerSettingBlock block = schedule.getBlock(id);
long start = block.getStartTime();
long end = block.getEndTime();
long ru = block.getRepeatUntil();
int days = block.getDays();
int ring = block.getRingVal();
String name = block.getName();
boolean enabled = block.isEnabled();
boolean deleted = block.isDeleted();
logcatPrint("ID:"+id+";start:"+start+";end:"+end+";ring:"+ring+";days:"+days+";ru:"+ru+"name:"+name+";ena:"+enabled+";del:"+deleted);
}
/**
* Updates the name spinner on the user interface
*/
public void updateSpinner(){
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
LinkedList<RingerSettingBlock> list = schedule.getList();
Iterator<RingerSettingBlock> i = list.iterator();
nameDictionary.clear();
nameDictionaryReverse.clear();
boolean skippedFirst=true;
int mapID=0;
while (i.hasNext()){
RingerSettingBlock thisBlock = i.next();
if (skippedFirst && thisBlock.isEnabled() && thisBlock.getId()>=0){
nameDictionary.put(mapID, thisBlock.getId());
nameDictionaryReverse.put(thisBlock.getId(),mapID);
//adapter.add(Formatter.formatName(thisBlock));
adapter.add(thisBlock.getName());
mapID++;
}
skippedFirst=true;
}
adapter.notifyDataSetChanged();
//alarmSpinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void updateInterfaceWithoutSpinner(RingerSettingBlock block) {
startHour.setText(""+TimeFunctions.getHourOfTime(block.getStartTime()));
endHour.setText(""+TimeFunctions.getHourOfTime(block.getEndTime()));
startMinute.setText(Formatter.minFormat(TimeFunctions.getMinuteOfTime(block.getStartTime())));
endMinute.setText(Formatter.minFormat(TimeFunctions.getMinuteOfTime(block.getEndTime())));
eventName.setText(block.getName());
ringSpinner.setSelection(block.getRingVal());
//repeatDate
// int day = TimeFunctions.getDayFromTimestamp(block.getRepeatUntil());
// int month = TimeFunctions.getMonthFromTimestamp(block.getRepeatUntil());
// int year = TimeFunctions.getYearFromTimestamp(block.getRepeatUntil());
// dateText.setText(month+"/"+day+"/"+year);
setDaysChecking(block);
if (TimeFunctions.isAM(block.getStartTime())){
startSpinner.setSelection(0);
}
else{
startSpinner.setSelection(1);
}
if (TimeFunctions.isAM(block.getEndTime())){
endSpinner.setSelection(0);
}
else{
endSpinner.setSelection(1);
}
}
/**
* Updates the entire interface to display the settings for the current block
*
* @param block - the block to update the GUI to
*/
public void updateInterface(RingerSettingBlock block){
startHour.setText(""+TimeFunctions.getHourOfTime(block.getStartTime()));
endHour.setText(""+TimeFunctions.getHourOfTime(block.getEndTime()));
startMinute.setText(Formatter.minFormat(TimeFunctions.getMinuteOfTime(block.getStartTime())));
endMinute.setText(Formatter.minFormat(TimeFunctions.getMinuteOfTime(block.getEndTime())));
eventName.setText(block.getName());
ringSpinner.setSelection(block.getRingVal());
//repeatDate
// int day = TimeFunctions.getDayFromTimestamp(block.getRepeatUntil());
// int month = TimeFunctions.getMonthFromTimestamp(block.getRepeatUntil());
// int year = TimeFunctions.getYearFromTimestamp(block.getRepeatUntil());
// dateText.setText(month+"/"+day+"/"+year);
setDaysChecking(block);
updateSpinner();
if (TimeFunctions.isAM(block.getStartTime())){
startSpinner.setSelection(0);
}
else{
startSpinner.setSelection(1);
}
if (TimeFunctions.isAM(block.getEndTime())){
endSpinner.setSelection(0);
}
else{
endSpinner.setSelection(1);
}
}
/**
* Updates the toggle buttons on the user interface
*
* @param block - the block to update the toggle buttons to match
*/
private void setDaysChecking(RingerSettingBlock block) {
if (block.isEnabledSunday()){
sunToggle.setChecked(true);
}
else{
sunToggle.setChecked(false);
}
if (block.isEnabledMonday()){
monToggle.setChecked(true);
}
else{
monToggle.setChecked(false);
}
if (block.isEnabledTuesday()){
tueToggle.setChecked(true);
}
else{
tueToggle.setChecked(false);
}
if (block.isEnabledWednesday()){
wedToggle.setChecked(true);
}
else{
wedToggle.setChecked(false);
}
if (block.isEnabledThursday()){
thuToggle.setChecked(true);
}
else{
thuToggle.setChecked(false);
}
if (block.isEnabledFriday()){
friToggle.setChecked(true);
}
else{
friToggle.setChecked(false);
}
if (block.isEnabledSaturday()){
satToggle.setChecked(true);
}
else{
satToggle.setChecked(false);
}
}
/**
* Testing Method. Clears the prefs file
*
* @param settings - The SharedPreferences object that contains the user data
*/
private void clearPrefsForTesting(SharedPreferences settings) {
Editor e = settings.edit().clear();
for (int i=0; i<100; i++){
e.remove(i+".id");
e.remove(i+".start");
e.remove(i+".end");
e.remove(i+".ringer");
e.remove(i+".days");
}
e.remove("alarmCount");
e.commit();
logcatPrint("cleared");
}
/**
* Initializes all of the GUI components
*/
public void initComponents(){
nameDictionary= new HashMap<Integer,Integer>();
nameDictionaryReverse= new HashMap<Integer,Integer>();
//the repeat until date text box
// dateText = (EditText)findViewById(R.id.dateText);
//testing
// dateText.setText("11/11/1111");
//The toggle button for sunday
sunToggle = (ToggleButton)findViewById(R.id.sunToggle);
sunToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton sunButton, boolean isChecked) {
sunOn=isChecked;
}
});
//The toggle button for monday
monToggle = (ToggleButton)findViewById(R.id.monToggle);
monToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
monOn=isChecked;
}
});
//The toggle button for tuesday
tueToggle = (ToggleButton)findViewById(R.id.tueToggle);
tueToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
tueOn=isChecked;
}
});
//The toggle button for wednesday
wedToggle = (ToggleButton)findViewById(R.id.wedToggle);
wedToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
wedOn=isChecked;
}
});
//The toggle button for thursday
thuToggle = (ToggleButton)findViewById(R.id.thuToggle);
thuToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
thuOn=isChecked;
}
});
//The toggle button for friday
friToggle = (ToggleButton)findViewById(R.id.friToggle);
friToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
friOn=isChecked;
}
});
//The toggle button for saturday
satToggle = (ToggleButton)findViewById(R.id.satToggle);
satToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
satOn=isChecked;
}
});
//The settings button
/**
settingsButton = (Button)findViewById(R.id.settingsButton);
settingsButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Currently does not do anything
if (!serviceRunning){
serviceRunning=true;
startService(new Intent(BackroundService.class.getName()));
}
else{
serviceRunning=false;
stopService(new Intent(BackroundService.class.getName()));
}
//toastMessage("Sorry this currently doesn't do anything");
}
}); */
//The confirm edit button
confirmButton = (Button)findViewById(R.id.editEventButton);
confirmButton.setOnClickListener(new OnClickListener(){
/**
* If button is clicked, edit the current block permanently
*/
public void onClick(View v) {
if (inputValidates()){
try{
long startTime = getStartFromForm();
long endTime= getEndFromForm();
int ringer = getRinger();
long repeatUntil = getRepeatFromForm();
schedule.editBlockDays(currentBlockId, schedule.formatDays(sunOn, monOn, tueOn, wedOn, thuOn, friOn, satOn));
schedule.editBlockStart(currentBlockId, startTime);
schedule.editBlockEnd(currentBlockId, endTime);
schedule.editBlockRinger(currentBlockId, ringer);
+ schedule.editBlockName(currentBlockId, eventName.getText().toString());
schedule.editRepeatUntil(currentBlockId, repeatUntil);
updateInterface(schedule.getBlock(currentBlockId));
toastMessage("Current Block Editted");
}
catch (inputValidationError ive){
toastMessage("Incorrect input formatting");
}
}
}
});
//The add block button, adds new block if cleared
/**
addButton = (Button)findViewById(R.id.addNewEventButton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
int id= schedule.addBlock(getStartFromForm(), getEndFromForm(), ringSpinner.getSelectedItemPosition(), 1111111, getRepeatFromForm(),"Change this somehow", false, true);
currentBlockId = id;
updateInterface(schedule.getBlock(currentBlockId));
toastMessage("New Block Added. Now edit it and click 'confirm'");
} catch (inputValidationError e) {
toastMessage("Couldn't Add Block: Input Not Correctly Formatted");
}
}
}); */
//The cancel edit button, Discards any changes made to the UI and refreshes back to a stored state
/**
cancelButton = (Button)findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
RingerSettingBlock block =schedule.getBlock(currentBlockId);
updateInterface(block);
toastMessage("Current Changes Cancelled. Returning to Stored Block");
}
}); */
//The delete alarm button
deleteButton = (Button)findViewById(R.id.deleteEventButton);
deleteButton.setOnClickListener(new OnClickListener(){
/**
* Deletes the current block, unless it is the default block, which cant be deleted
*/
public void onClick(View v) {
if (currentBlockId == 0){
toastMessage("Cannot Delete: Default Ringer Setting Undeleteable.\n Please edit instead");
return;
}
schedule.disableBlock(currentBlockId);
int spinnerPos = nameDictionaryReverse.get(currentBlockId);
int newSpinnerBlockId = nameDictionary.get(spinnerPos -1 );
currentBlockId=newSpinnerBlockId;
updateInterface(schedule.getBlock(currentBlockId));
boolean deleted=true;
if (deleted){
toastMessage("Current Block deleted. Now showing previous block");
}
else{
toastMessage("Could not delete current block: Default setting is undeletable!");
}
}
});
//The disable alarm button, same as above
disableButton = (Button)findViewById(R.id.disableButton);
disableButton.setOnClickListener(new OnClickListener(){
/**
* Deletes the current block, unless it is the default block, which cant be deleted
*/
public void onClick(View v) {
if (currentBlockId == 0){
toastMessage("Cannot Delete: Default Ringer Setting Undeleteable.\n Please edit instead");
return;
}
schedule.disableBlock(currentBlockId);
int spinnerPos = nameDictionaryReverse.get(currentBlockId);
int newSpinnerBlockId = nameDictionary.get(spinnerPos -1 );
currentBlockId=newSpinnerBlockId;
updateInterface(schedule.getBlock(currentBlockId));
boolean deleted=true;
if (deleted){
toastMessage("Current Block deleted. Now showing previous block");
}
else{
toastMessage("Could not delete current block: Default setting is undeletable!");
}
}
});
//The hour of the start block text field
startHour = (EditText)findViewById(R.id.startHour);
//The minute of the start block text field
startMinute = (EditText)findViewById(R.id.startMinute);
//The hour of the end block text field
endHour = (EditText)findViewById(R.id.endHour);
//The minute of the end block text field
endMinute = (EditText)findViewById(R.id.endMinute);
//The name
eventName = (EditText)findViewById(R.id.eventName);
//The am/pm spinner for the start of the current block
startSpinner = (Spinner)findViewById(R.id.startSpinner);
//The am/pm spinner for the end of the current block
endSpinner = (Spinner)findViewById(R.id.endSpinner);
//The ringer level for the current block
ringSpinner = (Spinner)findViewById(R.id.ringSpinner);
//The name spinner for the current block
/**alarmSpinner = (Spinner)findViewById(R.id.alarmSpinner);
alarmSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
currentBlockId=nameDictionary.get(position);
updateInterfaceWithoutSpinner(schedule.getBlock(currentBlockId));
alarmSpinner.setSelection(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); */
}
/**
* Gets the start time from the UI
* DO NOT USE...USE getStartFromForm() instead
* as it has text validation
*
* @return The start time shown in the user interface
*/
public long getStartTime(){
int hour = Integer.parseInt(startHour.getText().toString());
int min = Integer.parseInt(startMinute.getText().toString());
boolean am = false;
if (startSpinner.getSelectedItemPosition() == 0) { am=true; }
return Formatter.formTimestamp(hour , min , am);
}
/**
* Gets the end time from the UI
* DO NOT USE...USE getEndFromForm() instead
* as it has text validation
*
* @return The end time shown in the user interface
*/
public long getEndTime(){
int hour = Integer.parseInt(endHour.getText().toString());
int min = Integer.parseInt(endMinute.getText().toString());
boolean am = false;
if (endSpinner.getSelectedItemPosition() == 0) { am=true; }
return Formatter.formTimestamp(hour , min , am);
}
/**
* Gets the ringer setting from the UI
*
* @return - The ringer level (0, 1, or 2) displayed on the UI
*/
public int getRinger(){
return ringSpinner.getSelectedItemPosition();
}
/**
* Ensure that the input validates correctly (only number or correctly formatted dates)
* also displays toast message if there is an error
*
* @return true if input is valid, false if not.
*/
public boolean inputValidates() {
String sHour = startHour.getText().toString();
String sMin = startMinute.getText().toString();
String eHour = endHour.getText().toString();
String eMin = endMinute.getText().toString();
String repeatUntil = "01/01/2200";
Pattern minPattern = Pattern.compile("^\\d{2}$");
Matcher ms = minPattern.matcher(sMin);
Matcher me = minPattern.matcher(eMin);
Pattern hourPattern = Pattern.compile("^\\d{1,2}$");
Matcher hs = hourPattern.matcher(sHour);
Matcher he = hourPattern.matcher(eHour);
Pattern datePattern = Pattern.compile("^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$");
Matcher d = datePattern.matcher(repeatUntil);
if (!d.matches()){
toastMessage("Date Not Formatted Correctly.\n Use mm/dd/yyyy");
return false;
}
String[] dateArray = repeatUntil.split("/");
String month = dateArray[0];
String day = dateArray[1];
String year = dateArray[2];
if (Integer.parseInt(month)>12 || Integer.parseInt(month)<1){
toastMessage("Nonexistant Month Used:\n Please use a number 1-12");
return false;
}
int dayInt = Integer.parseInt(day);
int monthInt = Integer.parseInt(month);
if (dayInt<0){
toastMessage("Nonexistant Day Used:\nPlease use a date that exists");
return false;
}
//30 day months
if ((monthInt == 4 || monthInt == 6 || monthInt == 9 || monthInt == 11) && dayInt>30){
toastMessage("Nonexistant Day Used:\nPlease use a date that exists");
return false;
}
//february (counts leap years)
if (monthInt == 2 && ((Integer.parseInt(year)%4 == 0 && dayInt>29) || (Integer.parseInt(year)%4 != 0 && dayInt>28))){
toastMessage("Nonexistant Day Used:\nPlease use a date that exists");
return false;
}
//all other months
if (dayInt>31){
toastMessage("Nonexistant Day Used:\nPlease use a date that exists");
return false;
}
if (!ms.matches() || Integer.parseInt(sMin)<0 || Integer.parseInt(sMin)>59){
toastMessage("Start Minutes Not Formatted Correctly.\n Must be a number 0-59");
return false;
}
if (!me.matches()|| Integer.parseInt(eMin)<0 || Integer.parseInt(eMin)>59){
toastMessage("End Minutes Not Formatted Correctly.\n Must be a number 0-59");
return false;
}
if (!hs.matches() || Integer.parseInt(sHour)<1 || Integer.parseInt(sHour)>12){
toastMessage("Start Hour Not Formatted Correctly.\n Must be a number 1-12");
return false;
}
if (!he.matches() || Integer.parseInt(eHour)<1 || Integer.parseInt(eHour)>12){
toastMessage("End Hour Not Formatted Correctly.\n Must be a number 1-12");
return false;
}
return true;
}
/**
* Gets the start time from the UI, given that it is correctly formatted
*
* @return the start time, in ms since midnight
* @throws inputValidationError if the input is not correctly formatted
*/
public long getStartFromForm() throws inputValidationError{
if (!inputValidates()){
throw new inputValidationError("Input is not in correct time format");
}
String sHour = startHour.getText().toString();
String sMin = startMinute.getText().toString();
long sHourInt = Long.parseLong(sHour);
long sMinInt = Long.parseLong(sMin);
return Formatter.formTimestamp(sHourInt, sMinInt, (startSpinner.getSelectedItemPosition()==0));
}
/**
* Gets the end time from the UI, given that it is correctly formatted
*
* @return the end time, in ms since midnight
* @throws inputValidationError if the input is not correctly formatted
*/
public long getEndFromForm() throws inputValidationError{
if (!inputValidates()){
throw new inputValidationError("Input is not in correct time format");
}
String eHour = endHour.getText().toString();
String eMin = endMinute.getText().toString();
long eHourInt = Long.parseLong(eHour);
long eMinInt = Long.parseLong(eMin);
return Formatter.formTimestamp(eHourInt, eMinInt, (endSpinner.getSelectedItemPosition()==0));
}
/**
* Gets the repeat until timestamp from the UI
*
* @return a long for ms after the epoch for when the given block no longer becomes valid
* @throws inputValidationError if the input is not correclty formatted as mm/dd/yyyy
*/
private long getRepeatFromForm() throws inputValidationError{
if (!inputValidates()){
throw new inputValidationError("Input is not in the correct date format");
}
String date = "01/01/2200";
String [] dateSplit = date.split("/");
int month = Integer.parseInt(dateSplit[0])-1;
int day = Integer.parseInt(dateSplit[1]);
int year = Integer.parseInt(dateSplit[2]);
return TimeFunctions.componentTimeToTimestamp(year,month,day,0,0);
}
/**
* Prints a temporary 'tooltip' style reminder on the GUI
*
* @param msg - a short message to print
*/
public void toastMessage(String msg){
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
/**
* Prints a logcat message with a customdebug tag
*
* @param message - the message to include with the logcat packet
*/
public void logcatPrint(String message){
Log.v("customdebug",message + " | sent from " +this.getClass().getSimpleName());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menuBar:
Intent i = new Intent(this, WeekViewActivity.class);
Bundle params = new Bundle();
i.putExtras(params);
this.startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// private void initRingerSched() {
// //SharedPreferences settings = getSharedPreferences(PREFS_FILE,0);
// if ( settings.getBoolean("initialized",false) ){
// //recreate ringer schedule
//
// long overflow = (7*24*60*60*1000)+1;
// long start=settings.getLong("0_0_start",overflow);
// long end=settings.getLong("0_0_end",overflow);
// int ringer=settings.getInt("0_0_ringer",AudioManager.RINGER_MODE_VIBRATE);
// for (int dayOfWeek=0; dayOfWeek<7; dayOfWeek++){
// int eventNumber=0;
// while (start <overflow){
// start=settings.getLong(dayOfWeek+"_"+eventNumber+"_start", overflow);
// end=settings.getLong(dayOfWeek+"_"+eventNumber+"_end", overflow);
// ringer=settings.getInt(dayOfWeek+"_"+eventNumber+"_ringer", AudioManager.RINGER_MODE_VIBRATE);
// ringerSchedule.add(new RingerSettingBlock(start,end,ringer));
// eventNumber++;
// }
// }
// }
// else{
// //create a default schedule event
// //id like to have a setup popup at some point...
// long day= 24*60*60*1000;
// int ringer=((AudioManager)getSystemService(Context.AUDIO_SERVICE)).getRingerMode();
// for (int i=0;i<7;i++){
//
// RingerSettingBlock defsched = new RingerSettingBlock(i*day,(i+1)*day,ringer);
// ringerSchedule.add(defsched);
// SharedPreferences.Editor e = settings.edit();
// e.putLong(i+"_0_start", i*day);
// e.putLong(i+"_0_end", (i+1)*day);
// e.putInt(i+"_0_ringer", ringer);
// e.putBoolean("initialized", true);
// e.commit();
// }
//
// }
// }
//
// private void checkCurrentSetting(){
// long offset = 4*24*60*60*1000; //time between Jan 1 1970 and midnight on a sunday
// long currentTime= System.currentTimeMillis()-offset; //this will set currentTime to time since midnight on sunday
// int modulater= 7*24*60*60*1000;
// int targetMode = getTargetMode(currentTime % modulater);
// AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// int ringerMode = am.getRingerMode();
// if (ringerMode != targetMode){
// am.setRingerMode(targetMode);
// }
// }
//
// private int getTargetMode(long currentTime){
// Iterator<RingerSettingBlock> i = ringerSchedule.iterator();
// while (i.hasNext()){
// RingerSettingBlock r = i.next();
// if (currentTime>=r.getStartTime() && currentTime<r.getEndTime()){
// return r.getRingVal();
// }
// }
// return ringerSchedule.getFirst().getRingVal();
//
// }
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.settings_menu, menu);
// return true;
// }
}
| true | true | public void initComponents(){
nameDictionary= new HashMap<Integer,Integer>();
nameDictionaryReverse= new HashMap<Integer,Integer>();
//the repeat until date text box
// dateText = (EditText)findViewById(R.id.dateText);
//testing
// dateText.setText("11/11/1111");
//The toggle button for sunday
sunToggle = (ToggleButton)findViewById(R.id.sunToggle);
sunToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton sunButton, boolean isChecked) {
sunOn=isChecked;
}
});
//The toggle button for monday
monToggle = (ToggleButton)findViewById(R.id.monToggle);
monToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
monOn=isChecked;
}
});
//The toggle button for tuesday
tueToggle = (ToggleButton)findViewById(R.id.tueToggle);
tueToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
tueOn=isChecked;
}
});
//The toggle button for wednesday
wedToggle = (ToggleButton)findViewById(R.id.wedToggle);
wedToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
wedOn=isChecked;
}
});
//The toggle button for thursday
thuToggle = (ToggleButton)findViewById(R.id.thuToggle);
thuToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
thuOn=isChecked;
}
});
//The toggle button for friday
friToggle = (ToggleButton)findViewById(R.id.friToggle);
friToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
friOn=isChecked;
}
});
//The toggle button for saturday
satToggle = (ToggleButton)findViewById(R.id.satToggle);
satToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
satOn=isChecked;
}
});
//The settings button
/**
settingsButton = (Button)findViewById(R.id.settingsButton);
settingsButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Currently does not do anything
if (!serviceRunning){
serviceRunning=true;
startService(new Intent(BackroundService.class.getName()));
}
else{
serviceRunning=false;
stopService(new Intent(BackroundService.class.getName()));
}
//toastMessage("Sorry this currently doesn't do anything");
}
}); */
//The confirm edit button
confirmButton = (Button)findViewById(R.id.editEventButton);
confirmButton.setOnClickListener(new OnClickListener(){
/**
* If button is clicked, edit the current block permanently
*/
public void onClick(View v) {
if (inputValidates()){
try{
long startTime = getStartFromForm();
long endTime= getEndFromForm();
int ringer = getRinger();
long repeatUntil = getRepeatFromForm();
schedule.editBlockDays(currentBlockId, schedule.formatDays(sunOn, monOn, tueOn, wedOn, thuOn, friOn, satOn));
schedule.editBlockStart(currentBlockId, startTime);
schedule.editBlockEnd(currentBlockId, endTime);
schedule.editBlockRinger(currentBlockId, ringer);
schedule.editRepeatUntil(currentBlockId, repeatUntil);
updateInterface(schedule.getBlock(currentBlockId));
toastMessage("Current Block Editted");
}
catch (inputValidationError ive){
toastMessage("Incorrect input formatting");
}
}
}
});
//The add block button, adds new block if cleared
/**
addButton = (Button)findViewById(R.id.addNewEventButton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
int id= schedule.addBlock(getStartFromForm(), getEndFromForm(), ringSpinner.getSelectedItemPosition(), 1111111, getRepeatFromForm(),"Change this somehow", false, true);
currentBlockId = id;
updateInterface(schedule.getBlock(currentBlockId));
toastMessage("New Block Added. Now edit it and click 'confirm'");
} catch (inputValidationError e) {
toastMessage("Couldn't Add Block: Input Not Correctly Formatted");
}
}
}); */
//The cancel edit button, Discards any changes made to the UI and refreshes back to a stored state
/**
cancelButton = (Button)findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
RingerSettingBlock block =schedule.getBlock(currentBlockId);
updateInterface(block);
toastMessage("Current Changes Cancelled. Returning to Stored Block");
}
}); */
//The delete alarm button
deleteButton = (Button)findViewById(R.id.deleteEventButton);
deleteButton.setOnClickListener(new OnClickListener(){
/**
* Deletes the current block, unless it is the default block, which cant be deleted
*/
public void onClick(View v) {
if (currentBlockId == 0){
toastMessage("Cannot Delete: Default Ringer Setting Undeleteable.\n Please edit instead");
return;
}
schedule.disableBlock(currentBlockId);
int spinnerPos = nameDictionaryReverse.get(currentBlockId);
int newSpinnerBlockId = nameDictionary.get(spinnerPos -1 );
currentBlockId=newSpinnerBlockId;
updateInterface(schedule.getBlock(currentBlockId));
boolean deleted=true;
if (deleted){
toastMessage("Current Block deleted. Now showing previous block");
}
else{
toastMessage("Could not delete current block: Default setting is undeletable!");
}
}
});
//The disable alarm button, same as above
disableButton = (Button)findViewById(R.id.disableButton);
disableButton.setOnClickListener(new OnClickListener(){
/**
* Deletes the current block, unless it is the default block, which cant be deleted
*/
public void onClick(View v) {
if (currentBlockId == 0){
toastMessage("Cannot Delete: Default Ringer Setting Undeleteable.\n Please edit instead");
return;
}
schedule.disableBlock(currentBlockId);
int spinnerPos = nameDictionaryReverse.get(currentBlockId);
int newSpinnerBlockId = nameDictionary.get(spinnerPos -1 );
currentBlockId=newSpinnerBlockId;
updateInterface(schedule.getBlock(currentBlockId));
boolean deleted=true;
if (deleted){
toastMessage("Current Block deleted. Now showing previous block");
}
else{
toastMessage("Could not delete current block: Default setting is undeletable!");
}
}
});
//The hour of the start block text field
startHour = (EditText)findViewById(R.id.startHour);
//The minute of the start block text field
startMinute = (EditText)findViewById(R.id.startMinute);
//The hour of the end block text field
endHour = (EditText)findViewById(R.id.endHour);
//The minute of the end block text field
endMinute = (EditText)findViewById(R.id.endMinute);
//The name
eventName = (EditText)findViewById(R.id.eventName);
//The am/pm spinner for the start of the current block
startSpinner = (Spinner)findViewById(R.id.startSpinner);
//The am/pm spinner for the end of the current block
endSpinner = (Spinner)findViewById(R.id.endSpinner);
//The ringer level for the current block
ringSpinner = (Spinner)findViewById(R.id.ringSpinner);
//The name spinner for the current block
/**alarmSpinner = (Spinner)findViewById(R.id.alarmSpinner);
alarmSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
currentBlockId=nameDictionary.get(position);
updateInterfaceWithoutSpinner(schedule.getBlock(currentBlockId));
alarmSpinner.setSelection(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); */
}
| public void initComponents(){
nameDictionary= new HashMap<Integer,Integer>();
nameDictionaryReverse= new HashMap<Integer,Integer>();
//the repeat until date text box
// dateText = (EditText)findViewById(R.id.dateText);
//testing
// dateText.setText("11/11/1111");
//The toggle button for sunday
sunToggle = (ToggleButton)findViewById(R.id.sunToggle);
sunToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton sunButton, boolean isChecked) {
sunOn=isChecked;
}
});
//The toggle button for monday
monToggle = (ToggleButton)findViewById(R.id.monToggle);
monToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
monOn=isChecked;
}
});
//The toggle button for tuesday
tueToggle = (ToggleButton)findViewById(R.id.tueToggle);
tueToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
tueOn=isChecked;
}
});
//The toggle button for wednesday
wedToggle = (ToggleButton)findViewById(R.id.wedToggle);
wedToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
wedOn=isChecked;
}
});
//The toggle button for thursday
thuToggle = (ToggleButton)findViewById(R.id.thuToggle);
thuToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
thuOn=isChecked;
}
});
//The toggle button for friday
friToggle = (ToggleButton)findViewById(R.id.friToggle);
friToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
friOn=isChecked;
}
});
//The toggle button for saturday
satToggle = (ToggleButton)findViewById(R.id.satToggle);
satToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
/**
* Changes the value representing this date in the edit memory
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
satOn=isChecked;
}
});
//The settings button
/**
settingsButton = (Button)findViewById(R.id.settingsButton);
settingsButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Currently does not do anything
if (!serviceRunning){
serviceRunning=true;
startService(new Intent(BackroundService.class.getName()));
}
else{
serviceRunning=false;
stopService(new Intent(BackroundService.class.getName()));
}
//toastMessage("Sorry this currently doesn't do anything");
}
}); */
//The confirm edit button
confirmButton = (Button)findViewById(R.id.editEventButton);
confirmButton.setOnClickListener(new OnClickListener(){
/**
* If button is clicked, edit the current block permanently
*/
public void onClick(View v) {
if (inputValidates()){
try{
long startTime = getStartFromForm();
long endTime= getEndFromForm();
int ringer = getRinger();
long repeatUntil = getRepeatFromForm();
schedule.editBlockDays(currentBlockId, schedule.formatDays(sunOn, monOn, tueOn, wedOn, thuOn, friOn, satOn));
schedule.editBlockStart(currentBlockId, startTime);
schedule.editBlockEnd(currentBlockId, endTime);
schedule.editBlockRinger(currentBlockId, ringer);
schedule.editBlockName(currentBlockId, eventName.getText().toString());
schedule.editRepeatUntil(currentBlockId, repeatUntil);
updateInterface(schedule.getBlock(currentBlockId));
toastMessage("Current Block Editted");
}
catch (inputValidationError ive){
toastMessage("Incorrect input formatting");
}
}
}
});
//The add block button, adds new block if cleared
/**
addButton = (Button)findViewById(R.id.addNewEventButton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
int id= schedule.addBlock(getStartFromForm(), getEndFromForm(), ringSpinner.getSelectedItemPosition(), 1111111, getRepeatFromForm(),"Change this somehow", false, true);
currentBlockId = id;
updateInterface(schedule.getBlock(currentBlockId));
toastMessage("New Block Added. Now edit it and click 'confirm'");
} catch (inputValidationError e) {
toastMessage("Couldn't Add Block: Input Not Correctly Formatted");
}
}
}); */
//The cancel edit button, Discards any changes made to the UI and refreshes back to a stored state
/**
cancelButton = (Button)findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
RingerSettingBlock block =schedule.getBlock(currentBlockId);
updateInterface(block);
toastMessage("Current Changes Cancelled. Returning to Stored Block");
}
}); */
//The delete alarm button
deleteButton = (Button)findViewById(R.id.deleteEventButton);
deleteButton.setOnClickListener(new OnClickListener(){
/**
* Deletes the current block, unless it is the default block, which cant be deleted
*/
public void onClick(View v) {
if (currentBlockId == 0){
toastMessage("Cannot Delete: Default Ringer Setting Undeleteable.\n Please edit instead");
return;
}
schedule.disableBlock(currentBlockId);
int spinnerPos = nameDictionaryReverse.get(currentBlockId);
int newSpinnerBlockId = nameDictionary.get(spinnerPos -1 );
currentBlockId=newSpinnerBlockId;
updateInterface(schedule.getBlock(currentBlockId));
boolean deleted=true;
if (deleted){
toastMessage("Current Block deleted. Now showing previous block");
}
else{
toastMessage("Could not delete current block: Default setting is undeletable!");
}
}
});
//The disable alarm button, same as above
disableButton = (Button)findViewById(R.id.disableButton);
disableButton.setOnClickListener(new OnClickListener(){
/**
* Deletes the current block, unless it is the default block, which cant be deleted
*/
public void onClick(View v) {
if (currentBlockId == 0){
toastMessage("Cannot Delete: Default Ringer Setting Undeleteable.\n Please edit instead");
return;
}
schedule.disableBlock(currentBlockId);
int spinnerPos = nameDictionaryReverse.get(currentBlockId);
int newSpinnerBlockId = nameDictionary.get(spinnerPos -1 );
currentBlockId=newSpinnerBlockId;
updateInterface(schedule.getBlock(currentBlockId));
boolean deleted=true;
if (deleted){
toastMessage("Current Block deleted. Now showing previous block");
}
else{
toastMessage("Could not delete current block: Default setting is undeletable!");
}
}
});
//The hour of the start block text field
startHour = (EditText)findViewById(R.id.startHour);
//The minute of the start block text field
startMinute = (EditText)findViewById(R.id.startMinute);
//The hour of the end block text field
endHour = (EditText)findViewById(R.id.endHour);
//The minute of the end block text field
endMinute = (EditText)findViewById(R.id.endMinute);
//The name
eventName = (EditText)findViewById(R.id.eventName);
//The am/pm spinner for the start of the current block
startSpinner = (Spinner)findViewById(R.id.startSpinner);
//The am/pm spinner for the end of the current block
endSpinner = (Spinner)findViewById(R.id.endSpinner);
//The ringer level for the current block
ringSpinner = (Spinner)findViewById(R.id.ringSpinner);
//The name spinner for the current block
/**alarmSpinner = (Spinner)findViewById(R.id.alarmSpinner);
alarmSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
currentBlockId=nameDictionary.get(position);
updateInterfaceWithoutSpinner(schedule.getBlock(currentBlockId));
alarmSpinner.setSelection(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); */
}
|
diff --git a/SNPrankData.java b/SNPrankData.java
index b20905d..e163a22 100644
--- a/SNPrankData.java
+++ b/SNPrankData.java
@@ -1,197 +1,197 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import org.jblas.DoubleMatrix;
import org.jblas.MatrixFunctions;
/*
* Matrix methods and implementation of the SNPrank algorithm.
* Authors: Brett McKinney and Nick Davis
* Email: [email protected], [email protected]
*/
public class SNPrankData {
private String [] header;
private DoubleMatrix data;
public SNPrankData(String file) {
header = null;
data = null;
readFile(file);
}
private void readFile(String filename) {
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
// strRow is used to read line from file
String delimiter = "";
String strRow = br.readLine();
if(strRow.indexOf(',')>=0) {
delimiter = "\\,";
}else {
delimiter = "\\s";
}
//set the header from first line of the input file
this.setHeader(strRow.split(delimiter));
data = new DoubleMatrix(this.getHeader().length, this.getHeader().length);
// set the data part from other lines of the input file
int index = 0;
while ((strRow = br.readLine()) != null) {
if(strRow.indexOf(',')>=0) {
delimiter = "\\,";
}else {
delimiter = "\\s";
}
String [] strArray = strRow.trim().split(delimiter);
for(int i = 0; i < data.rows; i++) {
data.put(index, i, Double.parseDouble(strArray[i].trim()));
}
index++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void snprank(String[] name, DoubleMatrix G, String gamma, String outFile) {
// G diagonal is information gain
DoubleMatrix Gdiag = G.diag();
double Gtrace = Gdiag.sum();
// vector of column sums of G
DoubleMatrix colsum = G.columnSums();
// find the indices of non-zero c array elements
int[] colsum_nzidx = colsum.findIndices();
// sparse matrix where the nonzero indices are filled with 1/colsum
DoubleMatrix D = DoubleMatrix.zeros(G.rows, G.columns);
DoubleMatrix fillD = DoubleMatrix.ones(1, colsum_nzidx.length)
.div(colsum.get(colsum_nzidx));
for (int i = 0; i < fillD.length; i++){
D.put(colsum_nzidx[i], colsum_nzidx[i], fillD.get(i));
}
// non-zero elements of colsum/d_j have (1 - gamma) in the numerator of
// the second term (Eq. 5 from SNPrank paper)
DoubleMatrix T_nz = DoubleMatrix.ones(1, G.columns);
T_nz.put(colsum_nzidx, 1 - Double.parseDouble(gamma));
// Compute T, Markov chain transition matrix
DoubleMatrix T = G.mmul(D).mul(Double.parseDouble(gamma))
.add(Gdiag.mmul(T_nz).mul(1.0 / Gtrace));
// initial arbitrary vector
DoubleMatrix r = new DoubleMatrix(G.rows, 1);
r.fill(1.0 / G.rows);
double threshold = 1.0E-4;
double lambda = 0.0;
boolean converged = false;
DoubleMatrix r_old = r;
// if the absolute value of the difference between old and current r
// vector is < threshold, we have converged
while(!converged) {
r_old = r;
r = T.mmul(r);
// sum of r elements
lambda = r.sum();
// normalize eigenvector r so sum(r) == 1
r = r.div(lambda);
// check convergence, ensure all elements of r - r_old < threshold
if (MatrixFunctions.abs(r.sub(r_old)).lt(threshold).min() == 1.0){
converged = true;
}
else converged = false;
}
// location of indices, used for sorting
Integer[] indices = new Integer[r.length];
for (int i = 0; i < indices.length; i++){
indices[i] = i;
}
final double[][] r_data = r.toArray2();
// sort r, preserving sorted order of original indices
Arrays.sort(indices, new Comparator<Integer>() {
public int compare(final Integer o1, final Integer o2) {
return Double.compare(r_data[o1][0], r_data[o2][0]);
}
});
// reverse sorted list of indices (sort descending)
for (int i = 0; i < indices.length / 2; i++){
int current = indices[i];
indices[i] = indices[indices.length - 1 - i];
indices[indices.length - 1 - i] = current;
}
// output to file, truncating values to 6 decimal places
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter writer = new BufferedWriter(fw);
writer.write("SNP\tSNPrank\tIG\n");
int index = 0;
for(int i=0; i<r.length; i++) {
index = indices[i];
writer.write(name[index] + "\t" +
String.format("%8.6f", r.get(index)) + "\t" +
- String.format("%8.6f", colsum.get(index)) + "\n");
+ String.format("%8.6f", G.get(index, index)) + "\n");
}
writer.close();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* @return the header
*/
public String[] getHeader() {
return header;
}
/**
* @param header the header to set
*/
public void setHeader(String[] header) {
this.header = header;
}
/**
* @return the data
*/
public DoubleMatrix getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(DoubleMatrix data) {
this.data = data;
}
}
| true | true | public void snprank(String[] name, DoubleMatrix G, String gamma, String outFile) {
// G diagonal is information gain
DoubleMatrix Gdiag = G.diag();
double Gtrace = Gdiag.sum();
// vector of column sums of G
DoubleMatrix colsum = G.columnSums();
// find the indices of non-zero c array elements
int[] colsum_nzidx = colsum.findIndices();
// sparse matrix where the nonzero indices are filled with 1/colsum
DoubleMatrix D = DoubleMatrix.zeros(G.rows, G.columns);
DoubleMatrix fillD = DoubleMatrix.ones(1, colsum_nzidx.length)
.div(colsum.get(colsum_nzidx));
for (int i = 0; i < fillD.length; i++){
D.put(colsum_nzidx[i], colsum_nzidx[i], fillD.get(i));
}
// non-zero elements of colsum/d_j have (1 - gamma) in the numerator of
// the second term (Eq. 5 from SNPrank paper)
DoubleMatrix T_nz = DoubleMatrix.ones(1, G.columns);
T_nz.put(colsum_nzidx, 1 - Double.parseDouble(gamma));
// Compute T, Markov chain transition matrix
DoubleMatrix T = G.mmul(D).mul(Double.parseDouble(gamma))
.add(Gdiag.mmul(T_nz).mul(1.0 / Gtrace));
// initial arbitrary vector
DoubleMatrix r = new DoubleMatrix(G.rows, 1);
r.fill(1.0 / G.rows);
double threshold = 1.0E-4;
double lambda = 0.0;
boolean converged = false;
DoubleMatrix r_old = r;
// if the absolute value of the difference between old and current r
// vector is < threshold, we have converged
while(!converged) {
r_old = r;
r = T.mmul(r);
// sum of r elements
lambda = r.sum();
// normalize eigenvector r so sum(r) == 1
r = r.div(lambda);
// check convergence, ensure all elements of r - r_old < threshold
if (MatrixFunctions.abs(r.sub(r_old)).lt(threshold).min() == 1.0){
converged = true;
}
else converged = false;
}
// location of indices, used for sorting
Integer[] indices = new Integer[r.length];
for (int i = 0; i < indices.length; i++){
indices[i] = i;
}
final double[][] r_data = r.toArray2();
// sort r, preserving sorted order of original indices
Arrays.sort(indices, new Comparator<Integer>() {
public int compare(final Integer o1, final Integer o2) {
return Double.compare(r_data[o1][0], r_data[o2][0]);
}
});
// reverse sorted list of indices (sort descending)
for (int i = 0; i < indices.length / 2; i++){
int current = indices[i];
indices[i] = indices[indices.length - 1 - i];
indices[indices.length - 1 - i] = current;
}
// output to file, truncating values to 6 decimal places
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter writer = new BufferedWriter(fw);
writer.write("SNP\tSNPrank\tIG\n");
int index = 0;
for(int i=0; i<r.length; i++) {
index = indices[i];
writer.write(name[index] + "\t" +
String.format("%8.6f", r.get(index)) + "\t" +
String.format("%8.6f", colsum.get(index)) + "\n");
}
writer.close();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
| public void snprank(String[] name, DoubleMatrix G, String gamma, String outFile) {
// G diagonal is information gain
DoubleMatrix Gdiag = G.diag();
double Gtrace = Gdiag.sum();
// vector of column sums of G
DoubleMatrix colsum = G.columnSums();
// find the indices of non-zero c array elements
int[] colsum_nzidx = colsum.findIndices();
// sparse matrix where the nonzero indices are filled with 1/colsum
DoubleMatrix D = DoubleMatrix.zeros(G.rows, G.columns);
DoubleMatrix fillD = DoubleMatrix.ones(1, colsum_nzidx.length)
.div(colsum.get(colsum_nzidx));
for (int i = 0; i < fillD.length; i++){
D.put(colsum_nzidx[i], colsum_nzidx[i], fillD.get(i));
}
// non-zero elements of colsum/d_j have (1 - gamma) in the numerator of
// the second term (Eq. 5 from SNPrank paper)
DoubleMatrix T_nz = DoubleMatrix.ones(1, G.columns);
T_nz.put(colsum_nzidx, 1 - Double.parseDouble(gamma));
// Compute T, Markov chain transition matrix
DoubleMatrix T = G.mmul(D).mul(Double.parseDouble(gamma))
.add(Gdiag.mmul(T_nz).mul(1.0 / Gtrace));
// initial arbitrary vector
DoubleMatrix r = new DoubleMatrix(G.rows, 1);
r.fill(1.0 / G.rows);
double threshold = 1.0E-4;
double lambda = 0.0;
boolean converged = false;
DoubleMatrix r_old = r;
// if the absolute value of the difference between old and current r
// vector is < threshold, we have converged
while(!converged) {
r_old = r;
r = T.mmul(r);
// sum of r elements
lambda = r.sum();
// normalize eigenvector r so sum(r) == 1
r = r.div(lambda);
// check convergence, ensure all elements of r - r_old < threshold
if (MatrixFunctions.abs(r.sub(r_old)).lt(threshold).min() == 1.0){
converged = true;
}
else converged = false;
}
// location of indices, used for sorting
Integer[] indices = new Integer[r.length];
for (int i = 0; i < indices.length; i++){
indices[i] = i;
}
final double[][] r_data = r.toArray2();
// sort r, preserving sorted order of original indices
Arrays.sort(indices, new Comparator<Integer>() {
public int compare(final Integer o1, final Integer o2) {
return Double.compare(r_data[o1][0], r_data[o2][0]);
}
});
// reverse sorted list of indices (sort descending)
for (int i = 0; i < indices.length / 2; i++){
int current = indices[i];
indices[i] = indices[indices.length - 1 - i];
indices[indices.length - 1 - i] = current;
}
// output to file, truncating values to 6 decimal places
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter writer = new BufferedWriter(fw);
writer.write("SNP\tSNPrank\tIG\n");
int index = 0;
for(int i=0; i<r.length; i++) {
index = indices[i];
writer.write(name[index] + "\t" +
String.format("%8.6f", r.get(index)) + "\t" +
String.format("%8.6f", G.get(index, index)) + "\n");
}
writer.close();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.